Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -224,3 +224,13 @@ assert.deepEqual(conversationPendingReturnSessions(revised), []);

revised[0].collaborations[0].returns.unshift({phase: "conclusion", status: "superseded", request_revision: 2});
assert.deepEqual(conversationPendingReturnSessions(revised), [], "A superseded result cannot hide the delivered current conclusion");

const documentSource = {role: "agent", session_id: "local", turn_id: "first", message_id: "managed.first.completed",
text: "Your checklist", attachments: [{id: "artifact", name: "checklist.md", mime_type: "text/markdown",
size: 3, data_url: "data:text/markdown;base64,YWJj"}]};
const liveReply = {role: "assistant", pending: false, sourceSessionId: "local", sourceTurnId: "first", text: "Your checklist"};
const attach = source => reconcileConversationReturns([liveReply], "local", [source], createReply)[0].attachments;
assert.equal(attach(documentSource)[0].dataUrl, documentSource.attachments[0].data_url);
assert.equal(attach({...documentSource, session_id: "other"}), undefined);
assert.equal(attach({...documentSource, message_id: "commentary"}), undefined);
assert.equal(attach({...documentSource, attachments: [{...documentSource.attachments[0], data_url: "https://example.com/file"}]}), undefined);
23 changes: 22 additions & 1 deletion apps/presentation/dashboard/src/data/conversation-returns.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,25 @@ type ConversationMessage = {
text?: string;
};

export function workspaceImageAttachments(attachments?: ChatVisibleMessage["attachments"]): WorkspaceImageAttachment[] | undefined {
return attachments?.map((attachment) => ({
dataUrl: attachment.data_url,
id: attachment.id,
mimeType: attachment.mime_type,
name: attachment.name,
size: attachment.size,
}));
}

/** Fetch completed files from the stored assistant message, including on live readback. */
export function managedReplyDocuments(source: ChatVisibleMessage) {
if (source.role !== "agent" || !source.turn_id || source.message_id !== `managed.${source.turn_id}.completed`
|| !source.attachments?.length || !source.attachments.every(file =>
(file.mime_type === "text/plain" || file.mime_type === "text/markdown")
&& file.data_url.startsWith(`data:${file.mime_type};base64,`))) return undefined;
return workspaceImageAttachments(source.attachments);
}

function refreshHistoryImageLinks(row: ConversationMessage, source: ChatVisibleMessage, sessionId: string) {
if (row.pending || row.queued || row.queueInputCancelled || !row.sourceMessageId || row.sourceMessageId !== source.message_id
|| source.session_id !== sessionId || row.role !== (source.role === "user" ? "user" : "assistant")
Expand Down Expand Up @@ -97,7 +116,9 @@ export function reconcileConversationReturns<T extends ConversationMessage>(
const collaborations = source.collaborations ?? row.collaborations;
const sourceCreatedAt = source.created_at ?? row.sourceCreatedAt;
const replyContext = source.reply_context ?? row.replyContext;
const attachments = refreshLinkedImages ? refreshHistoryImageLinks(row, source, sessionId) : row.attachments;
const replyDocuments = row.role === "assistant" && !row.pending && !row.attachments?.length
&& source.session_id === sessionId ? managedReplyDocuments(source) : undefined;
const attachments = replyDocuments ?? (refreshLinkedImages ? refreshHistoryImageLinks(row, source, sessionId) : row.attachments);
// Only the exact canonical user body can switch to its source-backed view.
// A background read never replaces a live answer or a different draft.
const inputChanged = row.role === "user" && source.role === "user"
Expand Down
18 changes: 5 additions & 13 deletions apps/presentation/dashboard/src/views/dashboard-page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {useManagedConversation} from "../data/use-managed-conversation";
import { normalizeGoalDraft, type GoalDraft } from "../../../../../loopx/control_plane/collaboration/goal_draft.js";
import { withTurnActivity, type TurnStep } from "../data/turn-steps";
import { conversationReturnSessions, conversationPendingReturnSessions, reconcileConversationHistory } from "../data/conversation-returns";
import { conversationReturnSessions, conversationPendingReturnSessions, reconcileConversationHistory, workspaceImageAttachments, managedReplyDocuments } from "../data/conversation-returns";
import { readConversationReturns, readTaskSessions } from "../data/conversation-return-observation";
import { currentChannelSession, useConversationHistory } from "../data/use-conversation-history";
import { useChatProjects } from "../data/use-chat-projects";
Expand Down Expand Up @@ -82,7 +82,6 @@ import {
isTodoProposal,
type ChatSessionSnapshot,
type ChatSessionSummary,
type ChatImageAttachment,
type ChatVisibleMessage,
mergeChatSessionMessages,
type ManagerChannelBinding,
Expand Down Expand Up @@ -566,15 +565,6 @@ type PersonalManagerMessage = {
text: string;
};

function workspaceImageAttachments(attachments?: ChatImageAttachment[]): WorkspaceImageAttachment[] | undefined {
return attachments?.map((attachment) => ({
dataUrl: attachment.data_url,
id: attachment.id,
mimeType: attachment.mime_type,
name: attachment.name,
size: attachment.size,
}));
}

type PersonalAgentOption = {
adapterKind?: string;
Expand Down Expand Up @@ -2611,10 +2601,12 @@ function PersonalGoalHome({
if (sessionIds.current.get(key) === sessionId && !newSessionRequired.current.has(key)) {
recordSessionAdmission(targetContextId, stored.session);
}
const answer = stored.messages.find((item) =>
item.turn_id === streamed.turnId && ["agent", "assistant"].includes(item.role));
const answer = stored.messages.find(item => item.message_id === `managed.${streamed.turnId}.completed`)
?? stored.messages.find(item => item.turn_id === streamed.turnId && ["agent", "assistant"].includes(item.role));
const documents = answer && managedReplyDocuments(answer);
if (answer) updateConversationMessage(targetContextId, completedMessageId, {
sourceMessageId: answer.message_id, sourceSessionId: sessionId,
...(documents ? {attachments: documents} : {}),
sourceCreatedAt: answer.created_at,
collaboration: answer.collaboration, collaborations: answer.collaborations, returnDelivery: answer.return_delivery,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1763,6 +1763,14 @@ input before admission; this is not a file-sync or arbitrary-path grant. Images
retain their existing routes. Source delivery does not prove comprehension,
automatic material adoption, full GQ06 qualification or lower model cost.

A local managed Codex Goal can also return a requested Markdown or plain-text
file in its web reply. Open the original conversation and choose **Download
source**. Reopening the message retrieves the captured bytes even after the
workspace file changes. The Agent supplies the filename, MIME type, byte count
and inline base64 data in the reply envelope. The same count, size and UTF-8
checks apply. A file containing a protected local path is withheld and the
answer reports the delivery failure. LoopX never opens a path from the reply.

### Default Lark private images reuse native Turn attachments

Ordinary project and steward private conversations accept images and image/text
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,12 @@ Attached 宿主、其他 executor 以及关联/Lark 会话在准入前拒绝这
授予文件同步或任意路径访问。图片保留现有路径。来源送达不证明理解、自动材料采用、
完整 GQ06 验收或模型成本降低。

本地托管 Codex 的 Goal 网页对话也可以返回用户要求的 Markdown 或纯文本文件。
在原对话中点击“下载原文”即可保存。即使工作区文件后来改变,重新打开消息仍可取回当时
的字节。Agent 在答复中提供文件名、MIME 类型、字节数和内联 Base64 数据,沿用已有的
数量、大小及 UTF-8 校验。文件含受保护的本机路径时,答复会说明附件交付失败。
LoopX 只使用答复携带的数据。

### 飞书私聊默认复用原生 Turn 图片附件

普通项目与管家私聊默认接收图片和图文消息。provider 在接收 App 下核验 canonical
Expand Down
25 changes: 17 additions & 8 deletions loopx/capabilities/native_chat/codex_adapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -1230,10 +1230,19 @@ def capabilities(self) -> dict[str, Any]:
"steering": True,
}

def start_turn(self, message: str, event_sink: Callable[[str, dict[str, Any]], None], *,
reply_image_turn_id: str | None = None) -> dict[str, Any]:
return self.session.send(message, on_event=event_sink, **self._ordinary_turn_arguments(),
**({"reply_image_turn_id": reply_image_turn_id} if reply_image_turn_id is not None else {}))
def start_turn(
self, message: str, event_sink: Callable[[str, dict[str, Any]], None], *,
reply_image_turn_id: str | None = None, attachments: list[dict[str, Any]] | None = None,
reply_documents: bool = False,
) -> dict[str, Any]:
arguments = self._ordinary_turn_arguments()
if reply_image_turn_id is not None:
arguments["reply_image_turn_id"] = reply_image_turn_id
if attachments:
arguments["attachments"] = attachments
if reply_documents:
arguments["reply_documents"] = True
return self.session.send(message, on_event=event_sink, **arguments)

def _ordinary_turn_arguments(self):
check = self._managed_read_turn_guard
Expand Down Expand Up @@ -1282,8 +1291,7 @@ def start_turn_with_attachments(
event_sink: Callable[[str, dict[str, Any]], None],
attachments: list[dict[str, Any]],
) -> dict[str, Any]:
return self.session.send(message, attachments=attachments, on_event=event_sink,
**self._ordinary_turn_arguments())
return self.start_turn(message, event_sink, attachments=attachments)

def interrupt_turn(self, turn_id: str | None = None) -> None:
driver = self.goal_driver
Expand Down Expand Up @@ -1338,7 +1346,7 @@ def start_bound_project_turn(external: ChatExternalConversations, adapter: Any,


def native_turn_response(session: CodexChatAgentSession, raw: str, *, output_schema: dict | None,
reply_image_turn_id: str | None) -> dict[str, Any]:
reply_image_turn_id: str | None, reply_documents: bool = False) -> dict[str, Any]:
if output_schema is not None:
try:
result = json.loads(raw)
Expand All @@ -1353,7 +1361,8 @@ def native_turn_response(session: CodexChatAgentSession, raw: str, *, output_sch

image_targets: list[str] | None = [] if reply_image_turn_id is not None else None
response = parse_agent_response(raw, protected_paths=[session.work_dir],
team_plan_context=getattr(session, "team_plan_context", None), image_targets=image_targets)
team_plan_context=getattr(session, "team_plan_context", None), image_targets=image_targets,
reply_documents=reply_documents)
if image_targets and reply_image_turn_id is not None:
plan = capture_reply_image_plan(session.work_dir.resolve(), reply_image_turn_id, image_targets)
if plan:
Expand Down
17 changes: 17 additions & 0 deletions loopx/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -864,6 +864,7 @@ def normalize_agent_response(
protected_paths: Iterable[Path | str] = (),
team_plan_context: Mapping[str, Any] | None = None,
image_targets: list[str] | None = None,
reply_documents: bool = False,
) -> dict[str, Any]:
"""Normalize one structured provider response to the public Chat contract."""

Expand Down Expand Up @@ -905,6 +906,13 @@ def normalize_agent_response(
protected_paths=protected,
image_targets=image_targets,
).strip()
documents = []
if reply_documents and payload.get("attachments"):
from .chat.attachments import normalize_reply_documents
try:
documents = normalize_reply_documents(payload["attachments"], message=message, protected_paths=protected)
except ValueError:
message = (message + "\n\nThe requested file could not be attached.").strip()
goal_draft = _normalize_goal_draft(payload, protected_paths=protected)
# A worker's bounded progress report, never a grant or a retry decision.
# Legacy prose and incomplete/ambiguous objects cannot request continuation.
Expand All @@ -923,6 +931,7 @@ def normalize_agent_response(
return {
"schema_version": CHAT_AGENT_RESPONSE_SCHEMA_VERSION,
"message": message,
**({"attachments": documents} if documents else {}),
**({"memory_preferences": memory_prefs} if memory_prefs else {}),
**({"unfinished_work": unfinished} if unfinished else {}),
**({"goal_draft": goal_draft} if goal_draft else {}),
Expand All @@ -946,6 +955,7 @@ def parse_agent_response(
protected_paths: Iterable[Path | str] = (),
team_plan_context: Mapping[str, Any] | None = None,
image_targets: list[str] | None = None,
reply_documents: bool = False,
) -> dict[str, Any]:
protected = tuple(protected_paths)
openings, _, uncertain = _review_openings(raw_text)
Expand All @@ -972,6 +982,7 @@ def parse_agent_response(
protected_paths=protected,
team_plan_context=team_plan_context,
image_targets=image_targets,
reply_documents=reply_documents,
)
except ValueError:
# A bad action envelope must not discard an already generated
Expand Down Expand Up @@ -1403,6 +1414,7 @@ def _turn_prompt(
project_work: bool = False,
public_source_read_context: str = "",
reply_image_directory: Path | None = None,
reply_documents: bool = False,
) -> str:
direct_work = runtime_profile == "trusted_owner" and not execution_mode and not project_work
try:
Expand Down Expand Up @@ -1461,6 +1473,11 @@ def _turn_prompt(
role
+ "The operator message below is the current task. Answer it directly and do not replace it "
+ "with an autonomous project task. "
+ ("For a requested downloadable .md or .txt file, include its actual UTF-8 bytes in the final "
"review JSON attachments array. Each entry has name (basename), mime_type (text/markdown or "
"text/plain), size (byte count), and data_url (matching base64 data URL). Keep the combined "
"envelope under 64 KB. Preserve original bytes. If unavailable, explain in the answer. "
if reply_documents else "")
+ planning_limits
+ trusted_manager_limits
+ public_source_read_context
Expand Down
26 changes: 26 additions & 0 deletions loopx/chat/attachments.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
import json
import re
import uuid
from collections.abc import Iterable
from pathlib import Path
from typing import Any


Expand Down Expand Up @@ -170,6 +172,30 @@ def normalize_chat_attachments(value: Any) -> list[dict[str, Any]]:
return normalized


def local_goal_reply_route(session: dict[str, Any], turn: dict[str, Any], *, scope_kind: str) -> bool:
return (scope_kind == "owner_goal" and session.get("agent_id") == "codex"
and session.get("session_mode") == "managed_runtime" and turn.get("origin") == "web"
and session.get("project_context") is None and session.get("steward_context") is None)


def normalize_reply_documents(value: Any, *, message: str, protected_paths: Iterable[Path | str]) -> list[dict[str, Any]]:
"""Admit only self-contained text. The service never resolves an Agent file path."""
from ..chat import redact_response_markdown

if not isinstance(value, list) or not all(
isinstance(row, dict) and isinstance(row.get("mime_type"), str)
and row["mime_type"] in CHAT_TEXT_TYPES for row in value
):
raise ValueError("reply attachments must be text documents")
documents = normalize_chat_attachments([{k: v for k, v in row.items() if k != "id"} for row in value])
validate_chat_turn_envelope({"message": message, "attachments": documents})
for document in documents:
content = text_document_content(document)
if redact_response_markdown(content, protected_paths=protected_paths) != content:
raise ValueError("document contains private paths")
return documents


def normalize_local_chat_attachments(session: dict[str, Any], value: Any) -> list[dict[str, Any]]:
attachments = normalize_chat_attachments(value)
require_text_document_route(session, attachments)
Expand Down
4 changes: 3 additions & 1 deletion loopx/chat_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -1518,6 +1518,7 @@ def send(
turn_start_guard: Callable[[], AbstractContextManager[None]] | None = None,
check_running: Callable[[], None] | None = None,
reply_image_turn_id: str | None = None,
reply_documents: bool = False,
_native_task: bool = False,
sandbox_policy: dict[str, object] | None = None,
) -> dict[str, Any]:
Expand All @@ -1544,6 +1545,7 @@ def send(
project_work=self.project_context is not None and self.sandbox == "workspace-write",
public_source_read_context=self._public_source_read_context,
reply_image_directory=image_dir,
reply_documents=reply_documents,
)
turn_input: list[dict[str, Any]] = [{"type": "text", "text": text}]
from .chat.attachments import native_attachment_inputs
Expand Down Expand Up @@ -1745,7 +1747,7 @@ def raise_turn_failure(error_payload: Any, fallback: str) -> None:
emit_visible(display_filter.finish())
raw_response = completed_agent_response if completed_agent_response is not None else "".join(parts)
response = native_turn_response(self, raw_response, output_schema=output_schema,
reply_image_turn_id=reply_image_turn_id)
reply_image_turn_id=reply_image_turn_id, reply_documents=reply_documents)
if output_schema is None and on_event:
if (
CHAT_REVIEW_OPEN_TAG not in raw_response
Expand Down
6 changes: 5 additions & 1 deletion loopx/chat_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -1073,7 +1073,11 @@ def record_owner_resume() -> None:
# and waiting boundaries. Do not invent Goal timing for them.
observed_goal = str(session.get("goal_id") or "") if scope["kind"] == "owner_goal" else ""
with observe_goal_execution(self.store.root.parent, observed_goal, host=str(session.get("agent_id") or "unknown")):
if attachments:
from .chat.attachments import local_goal_reply_route
if isinstance(adapter, CodexAppServerAdapter) and local_goal_reply_route(
session, current_turn, scope_kind=scope["kind"]):
response = adapter.start_turn(message, event_sink, attachments=attachments, reply_documents=True)
elif attachments:
response = start_attachment_turn(adapter, session, current_turn, message, event_sink, attachments)
else:
from .capabilities.native_chat.external_conversations import ChatExternalConversations
Expand Down
12 changes: 10 additions & 2 deletions loopx/chat_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -1436,9 +1436,17 @@ def finalize_managed_turn_completion(
if not isinstance(response, dict):
raise ValueError("completing chat turn requires a response")
completed_at = str(turn.get("completed_at") or utc_now())
if response.get("message"):
attachments = response.get("attachments")
if attachments:
from .chat.attachments import local_goal_reply_route
from .control_plane.collaboration import conversation_scope
session = self.load_session(session_id) or {}
if not local_goal_reply_route(session, turn, scope_kind=conversation_scope(session)["kind"]):
attachments = None
if response.get("message") or attachments:
self.append_message(
session_id, role="agent", text=str(response["message"]), turn_id=turn_id,
session_id, role="agent", text=str(response.get("message") or ""), turn_id=turn_id,
attachments=attachments,
message_id=f"managed.{turn_id}.completed", goal_draft=response.get("goal_draft"),
)
self.append_completed_response_events(session_id, turn_id, response=response, idempotent=True)
Expand Down
Loading
Loading