diff --git a/apps/presentation/dashboard/src/data/conversation-returns.test.mjs b/apps/presentation/dashboard/src/data/conversation-returns.test.mjs index 787e9dc6c3..1198d2e356 100644 --- a/apps/presentation/dashboard/src/data/conversation-returns.test.mjs +++ b/apps/presentation/dashboard/src/data/conversation-returns.test.mjs @@ -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); diff --git a/apps/presentation/dashboard/src/data/conversation-returns.ts b/apps/presentation/dashboard/src/data/conversation-returns.ts index c5e6ec0378..72c3358af1 100644 --- a/apps/presentation/dashboard/src/data/conversation-returns.ts +++ b/apps/presentation/dashboard/src/data/conversation-returns.ts @@ -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") @@ -97,7 +116,9 @@ export function reconcileConversationReturns( 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" diff --git a/apps/presentation/dashboard/src/views/dashboard-page.tsx b/apps/presentation/dashboard/src/views/dashboard-page.tsx index d3047a170c..e95cd03497 100644 --- a/apps/presentation/dashboard/src/views/dashboard-page.tsx +++ b/apps/presentation/dashboard/src/views/dashboard-page.tsx @@ -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"; @@ -82,7 +82,6 @@ import { isTodoProposal, type ChatSessionSnapshot, type ChatSessionSummary, - type ChatImageAttachment, type ChatVisibleMessage, mergeChatSessionMessages, type ManagerChannelBinding, @@ -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; @@ -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, }); diff --git a/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.md b/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.md index ac01613378..3a8e2cff2f 100644 --- a/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.md +++ b/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.md @@ -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 diff --git a/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.zh-CN.md b/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.zh-CN.md index 6482108035..14bdc1f57d 100644 --- a/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.zh-CN.md +++ b/docs/architecture/rfcs/app-conversation-and-async-inbox-v0.zh-CN.md @@ -1111,6 +1111,12 @@ Attached 宿主、其他 executor 以及关联/Lark 会话在准入前拒绝这 授予文件同步或任意路径访问。图片保留现有路径。来源送达不证明理解、自动材料采用、 完整 GQ06 验收或模型成本降低。 +本地托管 Codex 的 Goal 网页对话也可以返回用户要求的 Markdown 或纯文本文件。 +在原对话中点击“下载原文”即可保存。即使工作区文件后来改变,重新打开消息仍可取回当时 +的字节。Agent 在答复中提供文件名、MIME 类型、字节数和内联 Base64 数据,沿用已有的 +数量、大小及 UTF-8 校验。文件含受保护的本机路径时,答复会说明附件交付失败。 +LoopX 只使用答复携带的数据。 + ### 飞书私聊默认复用原生 Turn 图片附件 普通项目与管家私聊默认接收图片和图文消息。provider 在接收 App 下核验 canonical diff --git a/loopx/capabilities/native_chat/codex_adapter.py b/loopx/capabilities/native_chat/codex_adapter.py index 819bb590ff..1f45cd0c3a 100644 --- a/loopx/capabilities/native_chat/codex_adapter.py +++ b/loopx/capabilities/native_chat/codex_adapter.py @@ -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 @@ -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 @@ -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) @@ -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: diff --git a/loopx/chat.py b/loopx/chat.py index f90c357d80..82598c2b82 100644 --- a/loopx/chat.py +++ b/loopx/chat.py @@ -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.""" @@ -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. @@ -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 {}), @@ -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) @@ -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 @@ -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: @@ -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 diff --git a/loopx/chat/attachments.py b/loopx/chat/attachments.py index 98ddbf078e..a5c3268621 100644 --- a/loopx/chat/attachments.py +++ b/loopx/chat/attachments.py @@ -7,6 +7,8 @@ import json import re import uuid +from collections.abc import Iterable +from pathlib import Path from typing import Any @@ -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) diff --git a/loopx/chat_agent.py b/loopx/chat_agent.py index ad9b2a4690..a55b33db6f 100644 --- a/loopx/chat_agent.py +++ b/loopx/chat_agent.py @@ -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]: @@ -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 @@ -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 diff --git a/loopx/chat_runtime.py b/loopx/chat_runtime.py index ba118db695..5f01f45def 100644 --- a/loopx/chat_runtime.py +++ b/loopx/chat_runtime.py @@ -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 diff --git a/loopx/chat_store.py b/loopx/chat_store.py index 2dc43e81d3..14c3cc72c5 100644 --- a/loopx/chat_store.py +++ b/loopx/chat_store.py @@ -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) diff --git a/tests/test_chat_image_http.py b/tests/test_chat_image_http.py index 03acaaa707..eddec9ba5b 100644 --- a/tests/test_chat_image_http.py +++ b/tests/test_chat_image_http.py @@ -63,6 +63,12 @@ def image_conversation(tmp_path): ' json.dump([hashlib.sha256(i["url"].encode()).hexdigest() for i in request["params"]["input"] if i["type"] == "image"], output)\n' " turn_count += 1", ) + source = source.replace( + '"message": "Runtime response.",', + '"message": "Runtime response.",\n' + f' **({{"attachments": [{document_attachment()!r}]}} if "Deliver the fixture file" in ' + 'json.dumps(request["params"].get("input")) else {}),', + ) executable = tmp_path / "codex" executable.write_text(source, encoding="utf-8") executable.chmod(executable.stat().st_mode | stat.S_IXUSR) @@ -296,3 +302,69 @@ def test_document_waits_for_busy_session_without_second_executor(image_conversat result = runtime.wait_for_turn(session_id=session, turn_id=queued["turn_id"], timeout_sec=10) assert result["status"] == "completed", result assert json.loads(capture.with_suffix(".inputs.json").read_text())[-1]["text"] == DOCUMENT_BYTES.decode() + + +def test_local_goal_reply_preserves_file_on_session_reopen(image_conversation): + store, runtime, session, post, capture = image_conversation + request = {"message": "Deliver the fixture file", "client_turn_id": "download-first-reply"} + status, receipt = post(request) + assert status == 202, receipt + turn = runtime.wait_for_turn(session_id=session, turn_id=receipt["turn_id"], timeout_sec=10) + assert turn["status"] == "completed", turn + assert "review JSON attachments" in json.loads(capture.with_suffix(".inputs.json").read_text())[0]["text"] + assert post(request)[1]["created"] is False + reopened = ChatSessionStore(store.root.parent) + replies = [row for row in reopened.messages(session) if row["role"] == "agent"] + assert len(replies) == 1 + assert replies[0]["turn_id"] == receipt["turn_id"] + document, = replies[0]["attachments"] + assert document["name"] == "requirements.md" + assert document["id"] != "requirements" + assert base64.b64decode(document["data_url"].split(",", 1)[1], validate=True) == DOCUMENT_BYTES + + +@pytest.mark.parametrize("change", [ + {"name": "../notes.md"}, {"mime_type": "application/octet-stream"}, + {"size": 1}, {"data_url": "https://example.com/notes.md"}, +]) +def test_invalid_reply_file_keeps_the_answer(change): + from loopx.chat import normalize_agent_response + + payload = {"message": "Here is the result.", "attachments": [{**document_attachment(), **change}]} + result = normalize_agent_response(payload, reply_documents=True) + assert result["message"].startswith("Here is the result.") + assert "could not be attached" in result["message"] + assert "attachments" not in result + + +def test_reply_document_limits_and_path_privacy(tmp_path): + from loopx.chat import normalize_agent_response + + for data, message in [ + (str(tmp_path / "private" / "keys.txt").encode(), "Read the result."), + (b"x" * 24000, "m" * 34000), + (b"\xff", "Read the result."), + ]: + payload = {"message": message, "attachments": [document_attachment(data)]} + result = normalize_agent_response(payload, protected_paths=[tmp_path], reply_documents=True) + assert "attachments" not in result + assert "could not be attached" in result["message"] + payload = {"message": "Ordinary answer.", "attachments": [document_attachment()]} + ordinary = normalize_agent_response(payload) + assert ordinary["message"] == "Ordinary answer." + assert "attachments" not in ordinary + + +@pytest.mark.parametrize(("changes", "origin", "scope_kind"), [ + ({"agent_id": "other"}, "web", "owner_goal"), + ({"session_mode": "attached_host"}, "web", "owner_goal"), + ({"project_context": {"audience": "bound_owner"}}, "web", "owner_goal"), + ({"steward_context": {"audience": "bound_group"}}, "web", "owner_goal"), + ({}, "peer", "owner_goal"), + ({}, "web", "owner_portfolio"), +]) +def test_reply_documents_stay_on_the_local_goal(changes, origin, scope_kind): + from loopx.chat.attachments import local_goal_reply_route + + session = {"agent_id": "codex", "session_mode": "managed_runtime", **changes} + assert not local_goal_reply_route(session, {"origin": origin}, scope_kind=scope_kind)