Compare commits

...
5 changed files with 569 additions and 39 deletions
+1 -1
View File
@@ -477,7 +477,7 @@ impl App {
.state .state
.lock() .lock()
.expect("structured state mutex") .expect("structured state mutex")
.approval_failed(error.to_string()); .approval_failed(&nonce, error.to_string());
} }
} }
} }
+79 -1
View File
@@ -289,7 +289,10 @@ impl StructuredState {
Some((nonce, decision)) Some((nonce, decision))
} }
pub fn approval_failed(&mut self, error: String) { pub fn approval_failed(&mut self, nonce: &str, error: String) {
if self.pending_nonce() != Some(nonce) {
return;
}
self.approval_submitting = false; self.approval_submitting = false;
self.error = Some(error); self.error = Some(error);
} }
@@ -554,6 +557,81 @@ mod tests {
); );
} }
#[test]
fn resolved_approval_ignores_its_late_failure() {
let mut state = StructuredState::default();
state.rows.push(row(
"approval:1",
TranscriptRowKind::Approval,
json!({"options":[{"kind":"allow_once"}]}),
));
state.selected = Some("approval:1".into());
state.reduced.pending_approval = Some(json!({"nonce":"old"}));
assert!(state.approval_decision('a').is_some());
state.apply(StructuredEvent::ProjectionUpdate {
transcript: None,
state: ReducedState::default(),
});
state.approval_failed("old", "response lost".into());
assert_eq!(state.error, None);
assert!(!state.approval_submitting);
}
#[test]
fn superseded_approval_ignores_its_late_failure() {
let mut state = StructuredState::default();
state.rows.push(row(
"approval:1",
TranscriptRowKind::Approval,
json!({"options":[{"kind":"allow_once"}]}),
));
state.selected = Some("approval:1".into());
state.reduced.pending_approval = Some(json!({"nonce":"old"}));
assert!(state.approval_decision('a').is_some());
state.rows.push(row(
"approval:2",
TranscriptRowKind::Approval,
json!({"options":[{"kind":"allow_once"}]}),
));
state.apply(StructuredEvent::ProjectionUpdate {
transcript: None,
state: ReducedState {
pending_approval: Some(json!({"nonce":"new"})),
..ReducedState::default()
},
});
assert_eq!(
state.approval_decision('a'),
Some(("new".into(), StructuredApprovalDecision::AllowOnce))
);
state.approval_failed("old", "response lost".into());
assert_eq!(state.error, None);
assert!(state.approval_submitting);
}
#[test]
fn matching_approval_surfaces_its_failure() {
let mut state = StructuredState::default();
state.rows.push(row(
"approval:1",
TranscriptRowKind::Approval,
json!({"options":[{"kind":"allow_once"}]}),
));
state.selected = Some("approval:1".into());
state.reduced.pending_approval = Some(json!({"nonce":"current"}));
assert!(state.approval_decision('a').is_some());
state.approval_failed("current", "request failed".into());
assert_eq!(state.error.as_deref(), Some("request failed"));
assert!(!state.approval_submitting);
}
#[test] #[test]
fn composer_is_gated_by_the_projected_turn_lifecycle() { fn composer_is_gated_by_the_projected_turn_lifecycle() {
let mut state = StructuredState::default(); let mut state = StructuredState::default();
+356
View File
@@ -115,6 +115,113 @@ describe("structured connection: data flow", () => {
expect(conn.el.textContent).not.toContain("partial\n"); // the un-patched text is gone, not appended beside it expect(conn.el.textContent).not.toContain("partial\n"); // the un-patched text is gone, not appended beside it
conn.dispose(); conn.dispose();
}); });
it("keeps an expanded running tool open without emitting a click when patched", () => {
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({
type: "transcript_snapshot",
snapshot: {
cursor: 1,
rows: [
row("tool:1", "tool_call", {
title: "Bash(pnpm test)",
status: "in_progress",
content: [{ type: "content", content: { type: "text", text: "starting" } }],
}),
],
},
});
ws.emit({ type: "reduced_state", state: idleState });
const originalHead = conn.el.querySelector<HTMLButtonElement>(".st-tool-head")!;
originalHead.click();
expect(originalHead.getAttribute("aria-expanded")).toBe("true");
const clickListener = vi.fn();
window.addEventListener("click", clickListener, { capture: true, once: true });
ws.emit({
type: "projection_update",
transcript: {
type: "patch",
row: row("tool:1", "tool_call", {
title: "Bash(pnpm test)",
status: "in_progress",
content: [{ type: "content", content: { type: "text", text: "still running" } }],
}),
},
state: idleState,
});
expect(clickListener).not.toHaveBeenCalled();
window.removeEventListener("click", clickListener, true);
const patchedHead = conn.el.querySelector<HTMLButtonElement>(".st-tool-head")!;
expect(patchedHead).not.toBe(originalHead);
expect(patchedHead.getAttribute("aria-expanded")).toBe("true");
expect(conn.el.querySelector<HTMLElement>(".st-tool-out")!.hidden).toBe(false);
expect(conn.el.textContent).toContain("still running");
conn.dispose();
});
it("restores focus to a patched tool header with the same stable row id", () => {
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({
type: "transcript_snapshot",
snapshot: {
cursor: 1,
rows: [row("tool:1", "tool_call", { title: "Read(file.ts)", status: "in_progress" })],
},
});
ws.emit({ type: "reduced_state", state: idleState });
const originalHead = conn.el.querySelector<HTMLButtonElement>(".st-tool-head")!;
originalHead.focus();
expect(document.activeElement).toBe(originalHead);
ws.emit({
type: "projection_update",
transcript: {
type: "patch",
row: row("tool:1", "tool_call", { title: "Read(file.ts)", status: "completed" }),
},
state: idleState,
});
const patchedHead = conn.el.querySelector<HTMLButtonElement>(".st-tool-head")!;
expect(patchedHead).not.toBe(originalHead);
expect(document.activeElement).toBe(patchedHead);
conn.dispose();
});
it("does not move unrelated focus when a tool row is patched", () => {
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({
type: "transcript_snapshot",
snapshot: {
cursor: 1,
rows: [row("tool:1", "tool_call", { title: "Read(file.ts)", status: "in_progress" })],
},
});
ws.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector<HTMLTextAreaElement>(".structured-input")!;
input.focus();
ws.emit({
type: "projection_update",
transcript: {
type: "patch",
row: row("tool:1", "tool_call", { title: "Read(file.ts)", status: "completed" }),
},
state: idleState,
});
expect(document.activeElement).toBe(input);
conn.dispose();
});
}); });
describe("structured connection: turn/composer gating", () => { describe("structured connection: turn/composer gating", () => {
@@ -147,6 +254,8 @@ describe("structured connection: turn/composer gating", () => {
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true })); input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
expect(sendStructuredPrompt).toHaveBeenCalledWith("s1", "do the thing"); expect(sendStructuredPrompt).toHaveBeenCalledWith("s1", "do the thing");
expect(input.value).toBe(""); expect(input.value).toBe("");
ws.emit({ type: "reduced_state", state: { turn: { responding: true, thinking: false, active_tool_calls: [] } } });
ws.emit({ type: "reduced_state", state: idleState });
vi.mocked(sendStructuredPrompt).mockRejectedValueOnce(new Error("boom")); vi.mocked(sendStructuredPrompt).mockRejectedValueOnce(new Error("boom"));
input.value = "retry me"; input.value = "retry me";
@@ -158,6 +267,103 @@ describe("structured connection: turn/composer gating", () => {
conn.dispose(); conn.dispose();
}); });
it("disables immediately and dispatches only once before begin-turn is projected", () => {
vi.mocked(sendStructuredPrompt).mockImplementationOnce(() => new Promise(() => {}));
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
ws.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
const send = conn.el.querySelector(".structured-send") as HTMLButtonElement;
const form = conn.el.querySelector(".structured-composer") as HTMLFormElement;
input.value = "only once";
form.dispatchEvent(new SubmitEvent("submit", { bubbles: true, cancelable: true }));
form.dispatchEvent(new SubmitEvent("submit", { bubbles: true, cancelable: true }));
expect(input.disabled).toBe(true);
expect(send.disabled).toBe(true);
expect(sendStructuredPrompt).toHaveBeenCalledTimes(1);
expect(sendStructuredPrompt).toHaveBeenCalledWith("s1", "only once");
conn.dispose();
});
it("does not overwrite a newer operator draft when the matching request fails", async () => {
let reject!: (error: unknown) => void;
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
() => new Promise((_, rejectPromise) => { reject = rejectPromise; }),
);
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
ws.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "first prompt";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
ws.emit({ type: "reduced_state", state: { turn: { responding: true, thinking: false, active_tool_calls: [] } } });
ws.emit({ type: "reduced_state", state: idleState });
input.value = "newer draft";
reject(new Error("late failure"));
await Promise.resolve().then(() => Promise.resolve());
expect(input.value).toBe("newer draft");
expect(conn.el.textContent).toContain("late failure");
conn.dispose();
});
it("ignores an older failure after a newer submission generation starts", async () => {
let rejectFirst!: (error: unknown) => void;
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
() => new Promise((_, rejectPromise) => { rejectFirst = rejectPromise; }),
);
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
ws.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "first prompt";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
ws.emit({ type: "reduced_state", state: { turn: { responding: true, thinking: false, active_tool_calls: [] } } });
ws.emit({ type: "reduced_state", state: idleState });
input.value = "second prompt";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
rejectFirst(new Error("stale failure"));
await Promise.resolve().then(() => Promise.resolve());
expect(sendStructuredPrompt).toHaveBeenCalledTimes(2);
expect(input.value).toBe("");
expect(input.disabled).toBe(true);
expect(conn.el.textContent).not.toContain("stale failure");
conn.dispose();
});
it("ignores a submission failure after disposal", async () => {
let reject!: (error: unknown) => void;
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
() => new Promise((_, rejectPromise) => { reject = rejectPromise; }),
);
const ws = new FakeSocket();
const conn = mount({ sockets: [ws] });
ws.open();
ws.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "do not restore";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
conn.dispose();
input.value = "detached draft";
reject(new Error("late failure"));
await Promise.resolve().then(() => Promise.resolve());
expect(input.value).toBe("detached draft");
expect(conn.el.querySelector(".structured-error")).toBeNull();
});
it("cancels the active turn via the cancel button", () => { it("cancels the active turn via the cancel button", () => {
const ws = new FakeSocket(); const ws = new FakeSocket();
const conn = mount({ sockets: [ws] }); const conn = mount({ sockets: [ws] });
@@ -301,6 +507,8 @@ describe("structured connection: reconnection/error/loading", () => {
vi.useFakeTimers(); vi.useFakeTimers();
}); });
afterEach(() => vi.useRealTimers());
it("shows connecting, then connected, then reconnecting with backoff, and rebuilds from the fresh snapshot", () => { it("shows connecting, then connected, then reconnecting with backoff, and rebuilds from the fresh snapshot", () => {
const first = new FakeSocket(); const first = new FakeSocket();
const second = new FakeSocket(); const second = new FakeSocket();
@@ -327,6 +535,154 @@ describe("structured connection: reconnection/error/loading", () => {
conn.dispose(); conn.dispose();
}); });
it("keeps a local submission gated across a reconnect until begin-turn arrives", () => {
vi.mocked(sendStructuredPrompt).mockImplementationOnce(() => new Promise(() => {}));
const first = new FakeSocket();
const second = new FakeSocket();
const conn = mount({ sockets: [first, second], shouldReconnect: () => true });
first.open();
first.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
first.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "survive reconnect";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
first.drop();
vi.advanceTimersByTime(1000);
second.open();
second.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
second.emit({ type: "reduced_state", state: idleState });
expect(input.disabled).toBe(true);
second.emit({ type: "reduced_state", state: { turn: { responding: true, thinking: false, active_tool_calls: [] } } });
second.emit({ type: "reduced_state", state: idleState });
expect(input.disabled).toBe(false);
conn.dispose();
});
it("releases an accepted submission from a post-acceptance idle snapshot", async () => {
vi.mocked(sendStructuredPrompt).mockResolvedValueOnce(undefined);
const first = new FakeSocket();
const second = new FakeSocket();
const conn = mount({ sockets: [first, second], shouldReconnect: () => true });
first.open();
first.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
first.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "finishes while disconnected";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
await Promise.resolve().then(() => Promise.resolve());
first.drop();
vi.advanceTimersByTime(1000);
second.open();
second.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
second.emit({ type: "reduced_state", state: idleState });
expect(input.disabled).toBe(false);
conn.dispose();
});
it("does not release from reconnect idle cached before submission acceptance", async () => {
let accept!: () => void;
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
() => new Promise((resolve) => { accept = resolve; }),
);
const first = new FakeSocket();
const second = new FakeSocket();
const third = new FakeSocket();
const conn = mount({ sockets: [first, second, third], shouldReconnect: () => true });
first.open();
first.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
first.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "accepted after reconnect";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
first.drop();
vi.advanceTimersByTime(1000);
second.open();
second.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
second.emit({ type: "reduced_state", state: idleState });
expect(input.disabled).toBe(true);
accept();
await Promise.resolve().then(() => Promise.resolve());
expect(input.disabled).toBe(true);
expect(second.closed).toBe(true);
third.open();
third.emit({ type: "transcript_snapshot", snapshot: { cursor: 0, rows: [] } });
third.emit({ type: "reduced_state", state: idleState });
expect(input.disabled).toBe(false);
conn.dispose();
});
it("cancels pending backoff when acceptance forces reconciliation", async () => {
let accept!: () => void;
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
() => new Promise((resolve) => { accept = resolve; }),
);
const first = new FakeSocket();
const second = new FakeSocket();
const reconciliation = new FakeSocket();
const duplicate = new FakeSocket();
const conn = mount({
sockets: [first, second, reconciliation, duplicate],
shouldReconnect: () => true,
});
first.open();
first.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "accepted during backoff";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
first.drop();
vi.advanceTimersByTime(1000);
second.drop();
accept();
await Promise.resolve().then(() => Promise.resolve());
expect(reconciliation.onopen).not.toBeNull();
vi.advanceTimersByTime(60_000);
expect(duplicate.onopen).toBeNull();
reconciliation.open();
reconciliation.emit({ type: "reduced_state", state: idleState });
expect(input.disabled).toBe(false);
conn.dispose();
expect(reconciliation.closed).toBe(true);
});
it("does not reconcile when submission acceptance arrives after disposal", async () => {
let accept!: () => void;
vi.mocked(sendStructuredPrompt).mockImplementationOnce(
() => new Promise((resolve) => { accept = resolve; }),
);
const first = new FakeSocket();
const second = new FakeSocket();
const late = new FakeSocket();
const conn = mount({ sockets: [first, second, late], shouldReconnect: () => true });
first.open();
first.emit({ type: "reduced_state", state: idleState });
const input = conn.el.querySelector(".structured-input") as HTMLTextAreaElement;
input.value = "accepted after disposal";
input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true, cancelable: true }));
first.drop();
vi.advanceTimersByTime(1000);
second.open();
second.emit({ type: "reduced_state", state: idleState });
conn.dispose();
accept();
await Promise.resolve().then(() => Promise.resolve());
vi.advanceTimersByTime(60_000);
expect(second.closed).toBe(true);
expect(late.onopen).toBeNull();
});
it("reports a daemon rejection reason and does not schedule a retry", () => { it("reports a daemon rejection reason and does not schedule a retry", () => {
const only = new FakeSocket(); const only = new FakeSocket();
const conn = mount({ sockets: [only], shouldReconnect: () => true }); const conn = mount({ sockets: [only], shouldReconnect: () => true });
+118 -29
View File
@@ -109,6 +109,12 @@ export function createStructuredConnection(
let state: ReducedState = { turn: idleTurn() }; let state: ReducedState = { turn: idleTurn() };
let pendingApprovalRowId: string | null = null; let pendingApprovalRowId: string | null = null;
let latestSession: Session | undefined = store?.snapshot().sessions.get(sessionId); let latestSession: Session | undefined = store?.snapshot().sessions.get(sessionId);
let submissionGeneration = 0;
let awaitingBeginGeneration: number | null = null;
let acceptedSubmission: { generation: number; socketGeneration: number } | null = null;
let socketGeneration = 0;
let stateSocketGeneration = 0;
let disposed = false;
function lastRowIdOfKind(kind: TranscriptRowKind): string | null { function lastRowIdOfKind(kind: TranscriptRowKind): string | null {
for (let i = rows.length - 1; i >= 0; i--) if (rows[i].kind === kind) return rows[i].id; for (let i = rows.length - 1; i >= 0; i--) if (rows[i].kind === kind) return rows[i].id;
@@ -138,7 +144,7 @@ export function createStructuredConnection(
// request was in flight (superseded, cancelled, answered elsewhere), // request was in flight (superseded, cancelled, answered elsewhere),
// the state-driven re-render already replaced the row; reviving // the state-driven re-render already replaced the row; reviving
// buttons on it would be reviving a decision that no longer applies. // buttons on it would be reviving a decision that no longer applies.
if (rowId === pendingApprovalRowId) { if (!disposed && rowId === pendingApprovalRowId) {
showError(String(e)); showError(String(e));
throw e; throw e;
} }
@@ -153,10 +159,15 @@ export function createStructuredConnection(
function remountRow(row: TranscriptRow): void { function remountRow(row: TranscriptRow): void {
const old = rowEls.get(row.id); const old = rowEls.get(row.id);
const el = buildTranscriptRow(row, approvalStateFor(row)); const oldToolHead = old?.querySelector<HTMLButtonElement>(".st-tool-head") ?? null;
const wasExpanded = oldToolHead?.getAttribute("aria-expanded") === "true";
const restoreFocus = document.activeElement === oldToolHead;
const el = buildTranscriptRow(row, approvalStateFor(row), wasExpanded);
rowEls.set(row.id, el); rowEls.set(row.id, el);
if (old) old.replaceWith(el); if (old) old.replaceWith(el);
else rowsEl.appendChild(el); else rowsEl.appendChild(el);
const newToolHead = el.querySelector<HTMLButtonElement>(".st-tool-head");
if (restoreFocus) newToolHead?.focus();
} }
function applySnapshot(snapshot: { rows: TranscriptRow[] }): void { function applySnapshot(snapshot: { rows: TranscriptRow[] }): void {
@@ -217,14 +228,28 @@ export function createStructuredConnection(
} }
function renderComposerState(): void { function renderComposerState(): void {
const active = state.turn.responding || state.turn.thinking; const active = state.turn.responding || state.turn.thinking || awaitingBeginGeneration !== null;
input.disabled = active; input.disabled = active;
sendBtn.disabled = active; sendBtn.disabled = active;
cancelBtn.hidden = !active; cancelBtn.hidden = !state.turn.responding && !state.turn.thinking;
} }
function applyState(next: ReducedState): void { function reconcileAwaitingBegin(): void {
if (state.turn.responding || state.turn.thinking) {
awaitingBeginGeneration = null;
} else if (
awaitingBeginGeneration !== null
&& acceptedSubmission?.generation === awaitingBeginGeneration
&& stateSocketGeneration > acceptedSubmission.socketGeneration
) {
awaitingBeginGeneration = null;
}
}
function applyState(next: ReducedState, connectionGeneration: number): void {
state = next; state = next;
stateSocketGeneration = connectionGeneration;
reconcileAwaitingBegin();
const newPendingId = state.pending_approval ? lastRowIdOfKind("approval") : null; const newPendingId = state.pending_approval ? lastRowIdOfKind("approval") : null;
if (newPendingId !== pendingApprovalRowId) { if (newPendingId !== pendingApprovalRowId) {
const prev = pendingApprovalRowId; const prev = pendingApprovalRowId;
@@ -268,18 +293,44 @@ export function createStructuredConnection(
e.preventDefault(); e.preventDefault();
const text = input.value; const text = input.value;
if (!text.trim() || input.disabled) return; if (!text.trim() || input.disabled) return;
const generation = ++submissionGeneration;
const submissionSocketGeneration = socketGeneration;
awaitingBeginGeneration = generation;
acceptedSubmission = null;
input.value = ""; input.value = "";
autoResize(); autoResize();
clearError(); clearError();
sendStructuredPrompt(sessionId, text).catch((e: unknown) => { renderComposerState();
input.value = text; sendStructuredPrompt(sessionId, text).then(
autoResize(); () => {
showError(String(e)); if (
}); disposed
|| generation !== submissionGeneration
|| awaitingBeginGeneration !== generation
) return;
const acceptanceSocketGeneration = socketGeneration;
acceptedSubmission = { generation, socketGeneration: acceptanceSocketGeneration };
// A replacement socket may have captured idle before the POST claimed
// the prompt. Reconnect again so its snapshot cannot predate the 204.
if (acceptanceSocketGeneration > submissionSocketGeneration) reconnectForReconciliation();
},
(e: unknown) => {
if (disposed || generation !== submissionGeneration) return;
if (awaitingBeginGeneration === generation) awaitingBeginGeneration = null;
if (input.value === "") {
input.value = text;
autoResize();
}
showError(String(e));
renderComposerState();
},
);
}); });
cancelBtn.addEventListener("click", () => { cancelBtn.addEventListener("click", () => {
clearError(); clearError();
cancelStructuredTurn(sessionId).catch((e: unknown) => showError(String(e))); cancelStructuredTurn(sessionId).catch((e: unknown) => {
if (!disposed) showError(String(e));
});
}); });
// ---- narrow-pane rail collapse (a split pane, not just the viewport) ---- // ---- narrow-pane rail collapse (a split pane, not just the viewport) ----
@@ -292,23 +343,59 @@ export function createStructuredConnection(
// ---- live worktree/git-status rail data ---- // ---- live worktree/git-status rail data ----
const unsubscribeStore = store?.subscribe((catalog: CatalogState) => { const unsubscribeStore = store?.subscribe((catalog: CatalogState) => {
if (disposed) return;
latestSession = catalog.sessions.get(sessionId); latestSession = catalog.sessions.get(sessionId);
renderRailNow(); renderRailNow();
}); });
// ---- socket lifecycle ---- // ---- socket lifecycle ----
let ws: WebSocket; let ws: WebSocket | null = null;
let reconnectMs = INITIAL_RECONNECT_MS; let reconnectMs = INITIAL_RECONNECT_MS;
let reconnectTimer: number | null = null; let reconnectTimer: number | null = null;
let disposed = false;
function cancelReconnect(): void {
if (reconnectTimer === null) return;
window.clearTimeout(reconnectTimer);
reconnectTimer = null;
}
function closeCurrentSocket(): void {
const socket = ws;
ws = null;
if (!socket) return;
socket.onopen = null;
socket.onmessage = null;
socket.onerror = null;
socket.onclose = null;
try {
socket.close();
} catch {
// ignore
}
}
function reconnectForReconciliation(): void {
if (disposed) return;
cancelReconnect();
closeCurrentSocket();
setConnState("reconnecting…", "connecting");
connect();
}
function connect(): void { function connect(): void {
ws = socketFactory(sessionId); if (disposed) return;
ws.onopen = () => { cancelReconnect();
closeCurrentSocket();
const connectionGeneration = ++socketGeneration;
const socket = socketFactory(sessionId);
ws = socket;
socket.onopen = () => {
if (disposed || ws !== socket) return;
reconnectMs = INITIAL_RECONNECT_MS; reconnectMs = INITIAL_RECONNECT_MS;
setConnState("connected", "open"); setConnState("connected", "open");
}; };
ws.onmessage = (ev) => { socket.onmessage = (ev) => {
if (disposed || ws !== socket) return;
if (typeof ev.data !== "string") return; if (typeof ev.data !== "string") return;
let msg: StructuredEvent; let msg: StructuredEvent;
try { try {
@@ -321,28 +408,33 @@ export function createStructuredConnection(
applySnapshot(msg.snapshot); applySnapshot(msg.snapshot);
break; break;
case "reduced_state": case "reduced_state":
applyState(msg.state); applyState(msg.state, connectionGeneration);
break; break;
case "projection_update": case "projection_update":
applyDelta(msg.transcript); applyDelta(msg.transcript);
applyState(msg.state); applyState(msg.state, connectionGeneration);
break; break;
} }
}; };
ws.onerror = () => setConnState("error", "error"); socket.onerror = () => {
ws.onclose = (ev) => { if (disposed || ws !== socket) return;
setConnState("error", "error");
};
socket.onclose = (ev) => {
if (disposed || ws !== socket) return;
ws = null;
const reason = ev.reason?.trim(); const reason = ev.reason?.trim();
if (ev.code >= 4000 && reason && !disposed) { if (ev.code >= 4000 && reason) {
setConnState(reason, "error"); setConnState(reason, "error");
showError(`cannot attach: ${reason}`); showError(`cannot attach: ${reason}`);
return; return;
} }
if (disposed) return;
if (opts.shouldReconnect?.(sessionId, ev.code)) { if (opts.shouldReconnect?.(sessionId, ev.code)) {
const delay = Math.min(reconnectMs, MAX_RECONNECT_MS); const delay = Math.min(reconnectMs, MAX_RECONNECT_MS);
setConnState("reconnecting…", "connecting"); setConnState("reconnecting…", "connecting");
reconnectTimer = window.setTimeout(() => { reconnectTimer = window.setTimeout(() => {
reconnectTimer = null; reconnectTimer = null;
if (disposed) return;
reconnectMs = Math.min(reconnectMs * 2, MAX_RECONNECT_MS); reconnectMs = Math.min(reconnectMs * 2, MAX_RECONNECT_MS);
connect(); connect();
}, delay); }, delay);
@@ -368,7 +460,7 @@ export function createStructuredConnection(
const focusOnMount = mountOpts?.focus !== false; const focusOnMount = mountOpts?.focus !== false;
const token = ++mountToken; const token = ++mountToken;
requestAnimationFrame(() => { requestAnimationFrame(() => {
if (token !== mountToken) return; // parked/remounted since this was scheduled if (disposed || token !== mountToken) return; // parked/remounted since this was scheduled
if (focusOnMount && !input.disabled) input.focus(); if (focusOnMount && !input.disabled) input.focus();
}); });
}, },
@@ -385,14 +477,11 @@ export function createStructuredConnection(
dispose() { dispose() {
if (disposed) return; if (disposed) return;
disposed = true; disposed = true;
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer); mountToken++;
cancelReconnect();
resizeObserver.disconnect(); resizeObserver.disconnect();
unsubscribeStore?.(); unsubscribeStore?.();
try { closeCurrentSocket();
ws.close();
} catch {
// ignore
}
el.remove(); el.remove();
}, },
}; };
+15 -8
View File
@@ -187,7 +187,7 @@ function statusMeta(status: string | undefined, hasDiff: boolean): { text: strin
return null; return null;
} }
function buildToolRow(row: TranscriptRow): HTMLElement { function buildToolRow(row: TranscriptRow, expanded: boolean): HTMLElement {
const tool = (row.data ?? {}) as AcpToolCallLike; const tool = (row.data ?? {}) as AcpToolCallLike;
const content = tool.content ?? []; const content = tool.content ?? [];
const hasDiff = content.some((c) => c.type === "diff"); const hasDiff = content.some((c) => c.type === "diff");
@@ -251,13 +251,16 @@ function buildToolRow(row: TranscriptRow): HTMLElement {
}; };
card.appendChild(out); card.appendChild(out);
const setExpanded = (nextExpanded: boolean) => {
if (nextExpanded) buildOut();
if (out.children.length === 0) nextExpanded = false;
head.setAttribute("aria-expanded", String(nextExpanded));
out.hidden = !nextExpanded;
};
head.addEventListener("click", () => { head.addEventListener("click", () => {
const expanded = head.getAttribute("aria-expanded") === "true"; setExpanded(head.getAttribute("aria-expanded") !== "true");
if (!expanded) buildOut();
if (out.children.length === 0) return; // nothing to show — stay collapsed
head.setAttribute("aria-expanded", String(!expanded));
out.hidden = expanded;
}); });
setExpanded(expanded);
return wrap; return wrap;
} }
@@ -361,7 +364,11 @@ function buildApprovalRow(row: TranscriptRow, approval: ApprovalRowState): HTMLE
/** Build the DOM for one transcript row. `approval` is consulted only for an /** Build the DOM for one transcript row. `approval` is consulted only for an
* `approval` row; pass it whenever the row might be that kind. */ * `approval` row; pass it whenever the row might be that kind. */
export function buildTranscriptRow(row: TranscriptRow, approval?: ApprovalRowState): HTMLElement { export function buildTranscriptRow(
row: TranscriptRow,
approval?: ApprovalRowState,
toolExpanded = false,
): HTMLElement {
let built: HTMLElement; let built: HTMLElement;
switch (row.kind) { switch (row.kind) {
case "user": case "user":
@@ -375,7 +382,7 @@ export function buildTranscriptRow(row: TranscriptRow, approval?: ApprovalRowSta
break; break;
case "tool_call": case "tool_call":
case "tool_diff": case "tool_diff":
built = buildToolRow(row); built = buildToolRow(row, toolExpanded);
break; break;
case "approval": case "approval":
built = buildApprovalRow(row, approval ?? { pending: false, onDecide: () => Promise.resolve() }); built = buildApprovalRow(row, approval ?? { pending: false, onDecide: () => Promise.resolve() });