Skip to content
Merged
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
1 change: 1 addition & 0 deletions apps/presentation/dashboard/src/data/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1029,6 +1029,7 @@ const chatQueueSchema = z.object({
preview: z.string(), character_count: z.number().int().nonnegative(),
attachment_count: z.number().int().nonnegative(),
input_revision: z.number().int().nonnegative().default(0),
input_mutation_allowed: z.boolean().optional(),
mutation: z.object({action: z.enum(["edit", "cancel"]), operation_id: z.string().min(1),
expected_revision: z.number().int().nonnegative(), input_revision: z.number().int().positive(),
message: z.string().optional()}).nullable().optional().default(null),
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useEffect, useRef, useState } from "react";
import { useEffect, useId, useRef, useState } from "react";
import { CornerUpLeft, MoreHorizontal, Pencil, RefreshCw, X } from "lucide-react";
import { ChatApiError, chatQueueInputRequestSchema, fetchQueuedChatInput, mutateQueuedChatTurn, steerQueuedChatTurn,
type ChatQueueInputRequest, type ChatQueuedInput, type ChatQueuedTurn } from "../../data/chat";
Expand Down Expand Up @@ -40,16 +40,21 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
const [draft, setDraft] = useState<string | null>(recovery.editor?.message ?? null);
const [editRevision, setEditRevision] = useState<number | null>(recovery.editor?.revision ?? null);
const textarea = useRef<HTMLTextAreaElement>(null), menuButton = useRef<HTMLButtonElement>(null);
const summary = useRef<HTMLElement>(null);
const sourceDescriptionId = useId();
const composing = useRef(false);
const held = turn.steering?.status === "pending" ? turn.steering : null;
const steerLabel = held ? (zh ? "核对插入" : "Check insertion") : (zh ? "插入本轮" : "Steer");
const canSteer = !unresolved && !editing && !recovery.failed && Boolean(held || (targetTurnId && !turn.attachment_count));
const editable = !held && !unresolved && !recovery.failed && turn.origin === "web";
const sourceEditable = turn.origin === "web" && turn.input_mutation_allowed !== false;
const canSteer = !unresolved && !(sourceEditable && editing) && !recovery.failed
&& Boolean(held || (targetTurnId && !turn.attachment_count));
const editable = !held && !unresolved && !recovery.failed && sourceEditable;
useEffect(() => {setMessage(null);}, [turn.input_revision]);
useEffect(() => {if (editing && message && draft === null) {
setDraft(message.message); setEditRevision(message.input_revision);
}}, [editing, message, draft]);
useEffect(() => {if (editing && draft !== null) textarea.current?.focus();}, [editing, draft === null]);
useEffect(() => {if (editing && sourceEditable && draft !== null) textarea.current?.focus();},
[editing, sourceEditable, draft === null]);
async function mutate(request: ChatQueueInputRequest) {
if (lock.current) return;
lock.current = true; setBusy(true); setActionError(""); setMenu(false);
Expand Down Expand Up @@ -79,6 +84,7 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
} finally {lock.current = false; setBusy(false); onInputChanged();}
}
function save() {
if (!sourceEditable) return;
if (draft && [...draft].length > 12000) {
setActionError(zh ? "待处理消息最多 12000 个字符,请缩短后保存。" : "Queued messages support up to 12000 characters. Shorten the text before saving."); return;
}
Expand All @@ -87,7 +93,13 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
}
function discard() {
try {localStorage.removeItem(draftKey);} catch {setActionError(zh ? "草稿恢复信息无法清除,请保留文本。" : "Draft recovery could not be cleared. Retain the text."); return;}
setEditing(false); setDraft(null); setEditRevision(null); setMenu(false); menuButton.current?.focus();
setEditing(false); setDraft(null); setEditRevision(null); setMenu(false);
if (sourceEditable) menuButton.current?.focus();
else summary.current?.focus();
}
function closeRetainedDraft() {
setEditing(false);
summary.current?.focus();
}
async function steer() {
if (lock.current || !canSteer) return;
Expand Down Expand Up @@ -115,13 +127,14 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
}, [open, editing, message, sessionId, turn.turn_id, turn.input_revision, retry]);
return <li onKeyDown={event => {
if (composing.current || event.nativeEvent.isComposing || event.nativeEvent.keyCode === 229) return;
if (event.key === "Escape" && !busy && !unresolved) {
if (event.key === "Escape" && !busy && !unresolved && (menu || editing)) {
event.preventDefault(); event.stopPropagation();
if (menu) {setMenu(false); menuButton.current?.focus();}
else discard();
else if (sourceEditable) discard();
else closeRetainedDraft();
return;
}
if (editing) {
if (editing && (sourceEditable || event.target === textarea.current)) {
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
if (composerKeyAction({...event, isComposing: event.nativeEvent.isComposing, keyCode: event.nativeEvent.keyCode}, false) === "steer") {
event.preventDefault(); event.stopPropagation(); save();
}
Expand All @@ -130,8 +143,9 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
if (composerKeyAction({...event, isComposing: event.nativeEvent.isComposing, keyCode: event.nativeEvent.keyCode}, false) === "steer" && canSteer) {
event.preventDefault(); event.stopPropagation(); void steer();
}
}}><div className="personal-queue-row"><details onToggle={event => setOpen(event.currentTarget.open)}>
<summary aria-label={`${zh ? "待处理消息" : "Queued message"} ${index + 1}`}>
}}><div className="personal-queue-row"><div className="personal-queue-content"><details onToggle={event => setOpen(event.currentTarget.open)}>
<summary ref={summary} aria-label={`${zh ? "待处理消息" : "Queued message"} ${index + 1}`}
aria-describedby={sourceEditable ? undefined : sourceDescriptionId}>
<span>{turn.preview || (zh ? "附件消息" : "Attachments")}</span>
{turn.attachment_count ? <small>{zh ? `${turn.attachment_count} 个附件` : `${turn.attachment_count} attachments`}</small> : null}
</summary>
Expand All @@ -143,7 +157,15 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
? <DocumentAttachment key={attachment.id} dataUrl={attachment.data_url} name={attachment.name} size={attachment.size} zh={zh}/>
: <img key={attachment.id} src={attachment.data_url} alt={attachment.name}/>)}</>}
</div> : null}
</details><button type="button" className="personal-queue-steer" onClick={() => void steer()}
</details>
{!sourceEditable ? <p id={sourceDescriptionId} className="personal-queue-source">
{zh ? "请在原协作入口编辑或取消排队。" : "Edit or cancel this queued message in its original conversation."}
</p> : null}
{!sourceEditable && (editing || draft !== null) ? <button type="button" aria-expanded={editing}
onClick={() => { if (editing) closeRetainedDraft(); else setEditing(true); }}>
{editing ? (zh ? "关闭草稿" : "Close draft") : (zh ? "查看保留的草稿" : "View retained draft")}
</button> : null}
</div><button type="button" className="personal-queue-steer" onClick={() => void steer()}
disabled={busy || !canSteer}
aria-label={zh ? `${steerLabel}:待处理消息 ${index + 1}`
: held ? `${steerLabel} for queued message ${index + 1}` : `Steer with queued message ${index + 1}`}
Expand All @@ -153,23 +175,29 @@ function QueuedMessage({sessionId, turn, index, targetTurnId, onChange, onInputC
: (zh ? "插入本轮 · Command+Enter" : "Steer · Command+Enter")}>
{busy || held ? <RefreshCw size={14}/> : <CornerUpLeft size={14}/>}<span>{steerLabel}</span>
</button><div className="personal-queue-actions"><button ref={menuButton} type="button" disabled={busy || !editable}
aria-label={zh ? `更多操作:待处理消息 ${index + 1}` : `More actions for queued message ${index + 1}`}
aria-expanded={menu} onClick={() => setMenu(!menu)}><MoreHorizontal size={16}/></button>
{menu ? <div className="personal-queue-menu">
aria-label={!sourceEditable
? (zh ? `编辑或取消不可用:待处理消息 ${index + 1}` : `Editing or cancelling unavailable for queued message ${index + 1}`)
Comment thread
loopx-agent marked this conversation as resolved.
Resolved
: (zh ? `更多操作:待处理消息 ${index + 1}` : `More actions for queued message ${index + 1}`)}
aria-describedby={sourceEditable ? undefined : sourceDescriptionId}
aria-expanded={menu && editable} onClick={() => setMenu(!menu)}><MoreHorizontal size={16}/></button>
{menu && editable ? <div className="personal-queue-menu">
<button type="button" onClick={() => {setMenu(false); setEditing(true); setOpen(true);}}><Pencil size={14}/>{zh ? "编辑" : "Edit"}</button>
<button type="button" onClick={() => void mutate({action: "cancel", operation_id: crypto.randomUUID(),
expected_revision: turn.input_revision})}><X size={14}/>{zh ? "取消排队" : "Cancel queued message"}</button>
</div> : null}</div></div>
{editing ? <div className="personal-queue-editor">
{draft === null ? <p role="status">{failed ? (zh ? "完整消息读取失败" : "Full message unavailable") : (zh ? "正在读取…" : "Reading…")}</p>
: <textarea ref={textarea} aria-label={zh ? `编辑待处理消息 ${index + 1}` : `Edit queued message ${index + 1}`}
maxLength={24000} value={draft} onChange={event => {
: <textarea ref={textarea} aria-label={sourceEditable
? (zh ? `编辑待处理消息 ${index + 1}` : `Edit queued message ${index + 1}`)
: (zh ? "保留的编辑草稿" : "Retained edit draft")}
readOnly={!sourceEditable} maxLength={24000} value={draft} onChange={event => {
setDraft(event.target.value);
try {localStorage.setItem(draftKey, JSON.stringify({message: event.target.value, revision: editRevision}));}
catch {setActionError(zh ? "草稿无法保存,切换前请保留文本。" : "Draft could not be saved. Retain the text before switching.");}
}} onCompositionStart={() => {composing.current = true;}} onCompositionEnd={() => {composing.current = false;}}
disabled={busy || Boolean(unresolved)} rows={3}/>}
<div><button type="button" onClick={save} disabled={busy || !draft?.trim() || Boolean(unresolved)}>{zh ? "保存" : "Save"}</button>
<div>{sourceEditable ? <button type="button" onClick={save}
disabled={busy || !draft?.trim() || Boolean(unresolved)}>{zh ? "保存" : "Save"}</button> : null}
<button type="button" disabled={busy || Boolean(unresolved)} onClick={discard}>{zh ? "放弃修改" : "Discard edit"}</button></div>
</div> : null}
{unresolved ? <div className="personal-queue-feedback"><span>{zh ? "修改尚未确认" : "Change unconfirmed"}</span>
Expand Down
50 changes: 50 additions & 0 deletions examples/personal-workspace-browser/attached-host-follow-up.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -191,6 +191,56 @@ export const attachedHostFollowUpScenario = {
|| !await queueMenu.evaluate(element => element === document.activeElement)) {
throw new Error("Escape must close the queue action menu and restore its trigger focus");
}
// A saved edit and an unconfirmed insertion can both survive a reload.
page.__loopxRuntime.queuedTurns.set(attachedSessionId,
page.__loopxRuntime.queuedTurns.get(attachedSessionId).map(turn =>
turn.turn_id === "turn-queued-1" ? {
...turn, input_mutation_allowed: false,
steering: {
schema_version: "loopx_chat_queue_steering_v1",
client_ingress_id: "bound-queue-original-ingress",
operation_id: "bound-queue-original-insertion",
target_turn_id: racedTurnId,
status: "pending",
},
} : turn));
await page.reload();
const boundDraft = queuedFollowUp.getByRole("textbox", {name: "保留的编辑草稿", exact: true});
await boundDraft.waitFor();
if (await boundDraft.isEditable() || await boundDraft.inputValue() !== retainedDraft
|| await queuedFollowUp.getByRole("button", {name: "保存", exact: true}).count()) {
throw new Error("A bound queue reopened a retained draft as a writable change");
}
const checkInsertion = queuedFollowUp.getByRole("button", {name: "核对插入:待处理消息 1", exact: true});
if (!await checkInsertion.isEnabled()
|| await checkInsertion.getAttribute("title") !== "核对该消息在原回合的插入结果") {
throw new Error("The bound row must allow checking the existing insertion while its draft is read-only");
}

for (const [width, height] of [[1440, 900], [390, 844]]) {
await page.setViewportSize({width, height});
const description = queuedFollowUp.getByText("请在原协作入口编辑或取消排队。", {exact: true});
const summary = queuedFollowUp.locator(".personal-queue-row summary");
await page.screenshot({path: resolve(outputDir, `bound-queue-review-draft-${width}.png`), fullPage: false});
const canReadOrigin = await description.isVisible()
&& (await summary.getAttribute("aria-describedby")) === await description.getAttribute("id");
const reopen = queuedFollowUp.getByRole("button", {name: "查看保留的草稿", exact: true});
if (width === 1440) {
await boundDraft.press("Escape");
} else {
await queuedFollowUp.getByRole("button", {name: "关闭草稿", exact: true}).click();
}
await boundDraft.waitFor({state: "hidden"});
if (!canReadOrigin || !await reopen.isVisible()
|| !await summary.evaluate(element => element === document.activeElement)) {
throw new Error(`Bound queue source and preserved draft must remain reachable after closing (${width}px)`);
}
await reopen.click();
if (await boundDraft.inputValue() !== retainedDraft || posts.length !== 2) {
throw new Error("Closing a read-only draft deleted it or sent another message");
}
}
await page.setViewportSize({width: 1440, height: 900});
await composer.fill("主输入框的另一份草稿");
page.__loopxRuntime.queuedTurns.set(attachedSessionId,
page.__loopxRuntime.queuedTurns.get(attachedSessionId).filter(turn => turn.turn_id !== "turn-queued-1"));
Expand Down
3 changes: 3 additions & 0 deletions loopx/capabilities/native_chat/queue_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from ...chat_store import CHAT_STORE_SCHEMA_VERSION
from ...status_server import is_loopback_host
from .queued_admission import unbound_input_source_denial


class ChatQueueRequestMixin:
Expand Down Expand Up @@ -70,6 +71,7 @@ def _session_queue(self, session_id: str) -> None:
self.server.runtime_controller.project_contexts.session_context(session)
else:
self._session_context(session)
mutable_source = unbound_input_source_denial(session) is None
rows: list[dict[str, Any]] = []
for turn in store.queued_turns(session_id, strict=True, include_reserved=True):
# Reuse history's exact admission/source checks before truncating;
Expand All @@ -87,6 +89,7 @@ def _session_queue(self, session_id: str) -> None:
"attachment_count": len(turn.get("attachments") or []),
"steering": turn.get("_queue_steering"),
"input_revision": turn.get("input_revision", 0),
"input_mutation_allowed": mutable_source and turn.get("origin") == "web",
"mutation": turn.get("_queue_mutation"),
})
self._send_json({"ok": True, "schema_version": CHAT_STORE_SCHEMA_VERSION,
Expand Down
10 changes: 10 additions & 0 deletions loopx/capabilities/native_chat/queued_admission.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,16 @@
from ...chat_runtime import ChatRuntimeController


def unbound_input_source_denial(session: dict[str, Any]) -> str | None:
"""Identify Sessions whose input must pass through their original source."""
if session.get("steward_context") is not None:
return "bound steward Chat requires its external source admission"
context = session.get("project_context") or {}
if context.get("audience") in {"bound_owner", "bound_group"}:
return "bound project steering requires its external source admission"
return None


def enqueue_turn(controller: Any, *, session_id: str, client_turn_id: str, message: str,
attachments: list[dict[str, Any]] | None, work_dir: Path | None, objective: str,
origin: str, external_agent_target: dict[str, Any] | None) -> tuple[dict[str, Any], bool]:
Expand Down
9 changes: 5 additions & 4 deletions loopx/chat_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,11 +508,12 @@ def _start_accepted_turn_worker(
def _require_steering_session(self, session_id: str) -> dict[str, Any]:
session = self._load_open_session(session_id)
require_managed_agent_session(self, session, Path(session.get("managed_workspace_path") or "."))
if session.get("steward_context") is not None:
raise ValueError("bound steward Chat requires its external source admission")
from .capabilities.native_chat.queued_admission import unbound_input_source_denial

denial = unbound_input_source_denial(session)
if denial:
raise ValueError(denial)
if session.get("project_context") is not None:
if session["project_context"].get("audience") in {"bound_owner", "bound_group"}:
raise ValueError("bound project steering requires its external source admission")
self.project_contexts.session_context(session)
if session.get("session_mode") == CHAT_SESSION_MODE_ATTACHED:
session = require_current_attached_session(store=self.store, registry_path=self.registry_path, session_id=session_id)
Expand Down
4 changes: 4 additions & 0 deletions tests/presentation/test_chat_turn_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,10 @@ def test_edit_cancel_and_admission_retries_keep_exact_input_history_and_active_t
sid, active, queued, original = held_queue(ordinary)
path = f"/api/chat/sessions/{sid}/queue/{queued}/input"
before = capture.read_bytes()
code, queue = request(f"/api/chat/sessions/{sid}/queue")
assert code == 200
pending, = queue["turns"]
assert pending["turn_id"] == queued and pending["input_mutation_allowed"] is True
assert request(path)[0] == 404
assert store.load_turn(sid, queued)["message"] == original["message"] # GET never mutates.
body = queue_input_body()
Expand Down
Loading
Loading