diff --git a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html
index 24e96d75cc29..2cb1f58fb274 100644
--- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html
+++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html
@@ -2001,85 +2001,85 @@
diff --git a/webviews/src/agent-session/acpmux/direct-reconnect.test.ts b/webviews/src/agent-session/acpmux/direct-reconnect.test.ts
index 461a71e59af9..452c14d67047 100644
--- a/webviews/src/agent-session/acpmux/direct-reconnect.test.ts
+++ b/webviews/src/agent-session/acpmux/direct-reconnect.test.ts
@@ -3,22 +3,24 @@ import { AcpmuxDirectClient } from "./direct";
/// A loopback acpmux that answers the open handshake and can drop the socket.
class FakeSocket {
+ static OPEN = 1;
static made: FakeSocket[] = [];
+ readyState = 0;
onopen?: () => void;
onerror?: () => void;
onclose?: () => void;
onmessage?: (message: { data: string }) => void;
constructor(readonly url: URL) {
FakeSocket.made.push(this);
- queueMicrotask(() => this.onopen?.());
+ queueMicrotask(() => { this.readyState = 1; this.onopen?.(); });
}
send(raw: string) {
const { id, method } = JSON.parse(raw) as { id: number; method: string };
const result = method === "_acpmux/watch" ? { sessions: [] } : {};
queueMicrotask(() => this.onmessage?.({ data: JSON.stringify({ id, result }) }));
}
- close() {}
- drop() { this.onclose?.(); }
+ close() { this.readyState = 3; }
+ drop() { this.readyState = 3; this.onclose?.(); }
}
const realSocket = globalThis.WebSocket;
diff --git a/webviews/src/agent-session/acpmux/direct.test.ts b/webviews/src/agent-session/acpmux/direct.test.ts
index ea9c2e752c82..88ff23edad95 100644
--- a/webviews/src/agent-session/acpmux/direct.test.ts
+++ b/webviews/src/agent-session/acpmux/direct.test.ts
@@ -1,6 +1,7 @@
-import { describe, expect, test } from "bun:test";
-import { applySupersededMessage, initialSession, mergeEventRecords, permissionFromMessage, settleOptimisticPrompt } from "./direct";
-import type { AcpmuxRow } from "./model";
+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
+import { AcpmuxDirectClient, applySupersededMessage, initialSession, mergeEventRecords, permissionFromMessage, settleOptimisticPrompt } from "./direct";
+import type { EventRecord } from "./direct";
+import type { AcpmuxRow, AcpmuxSnapshot } from "./model";
describe("direct acpmux event helpers", () => {
test("uses the permission notification envelope session id", () => {
@@ -55,3 +56,240 @@ describe("initial session", () => {
test("falls back to the most recent session", () => expect(initialSession(undefined, sessions)).toBe("recent"));
test("a new chat attaches nothing until its first prompt", () => expect(initialSession(undefined, sessions, true)).toBeUndefined());
});
+
+type Request = { id?: number; method: string; params: Record };
+
+/// A loopback acpmux whose replies a test scripts, holding back any method it names.
+class ScriptedSocket {
+ static OPEN = 1;
+ static current: ScriptedSocket;
+ static respond: (request: Request) => unknown = () => ({});
+ static held = new Set();
+ readyState = 0;
+ sent: Request[] = [];
+ waiting: Request[] = [];
+ onopen?: () => void;
+ onerror?: () => void;
+ onclose?: () => void;
+ onmessage?: (message: { data: string }) => void;
+ constructor(readonly url: URL) {
+ ScriptedSocket.current = this;
+ queueMicrotask(() => { this.readyState = 1; this.onopen?.(); });
+ }
+ send(raw: string) {
+ const request = JSON.parse(raw) as Request;
+ this.sent.push(request);
+ if (request.id === undefined) return;
+ if (ScriptedSocket.held.has(request.method)) { this.waiting.push(request); return; }
+ const result = ScriptedSocket.respond(request);
+ queueMicrotask(() => this.reply(request, result));
+ }
+ reply(request: Request, result: unknown) { this.onmessage?.({ data: JSON.stringify({ id: request.id, result }) }); }
+ release(method: string, result: unknown) {
+ const index = this.waiting.findIndex((request) => request.method === method);
+ if (index < 0) throw new Error(`no ${method} request is waiting`);
+ const [request] = this.waiting.splice(index, 1);
+ this.reply(request!, result);
+ }
+ notify(method: string, params: unknown) { this.onmessage?.({ data: JSON.stringify({ jsonrpc: "2.0", method, params }) }); }
+ close() { this.readyState = 3; }
+}
+
+const userEvent = (sessionId: string, seq: number, text: string): EventRecord => ({ sessionId, seq, at: seq, dir: "mux", kind: "user_message", msg: { text } });
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+
+describe("direct client session state", () => {
+ const realSocket = globalThis.WebSocket;
+ const host = { protocolVersion: 1, transport: "acpmux-websocket", endpoint: "ws://127.0.0.1:4100/acp", token: "t", sessionId: "a" } as const;
+ let snapshots: AcpmuxSnapshot[];
+ const latest = () => snapshots[snapshots.length - 1]!;
+ const texts = () => latest().rows.map((row) => row.text);
+ /// Session "a" starts at seq 5 with a queued prompt; "b" holds one message.
+ const attachReply = (sessionId: string) => sessionId === "a"
+ ? { session: { sessionId: "a", status: "idle", queue: [{ promptId: "q1", prompt: "queued" }] }, events: [userEvent("a", 5, "a five"), userEvent("a", 6, "a six")] }
+ : { session: { sessionId: "b", status: "idle" }, events: [userEvent("b", 1, "b one")] };
+
+ beforeEach(() => {
+ snapshots = [];
+ ScriptedSocket.held = new Set();
+ ScriptedSocket.respond = ({ method, params }) => {
+ if (method === "_acpmux/watch") return { sessions: [{ sessionId: "a" }, { sessionId: "b" }] };
+ if (method === "_acpmux/attach") return attachReply(params.sessionId);
+ return {};
+ };
+ (globalThis as any).WebSocket = ScriptedSocket;
+ (globalThis as any).window ??= globalThis;
+ });
+ afterEach(() => { (globalThis as any).WebSocket = realSocket; });
+
+ const connect = () => AcpmuxDirectClient.connect(host, (snapshot) => snapshots.push(snapshot));
+
+ test("purging an unselected session refreshes the picker", async () => {
+ await connect();
+ const before = snapshots.length;
+ ScriptedSocket.current.notify("_acpmux/session_changed", { kind: "purged", session: { sessionId: "b" } });
+ expect(snapshots.length).toBe(before + 1);
+ expect(latest().sessions.map((session) => session.sessionId)).toEqual(["a"]);
+ ScriptedSocket.current.notify("_acpmux/session_changed", { kind: "created", session: { sessionId: "c", title: "Elsewhere" } });
+ expect(latest().sessions.map((session) => session.sessionId)).toEqual(["a", "c"]);
+ expect(latest().sessionId).toBe("a");
+ });
+
+ test("history pages through events and keeps the live summary, queue and permission", async () => {
+ const client = await connect();
+ ScriptedSocket.current.notify("_acpmux/permission_pending", { sessionId: "a", permissionId: "p1", request: { toolCall: { title: "Run" }, options: [] } });
+ ScriptedSocket.respond = ({ method }) => method === "_acpmux/events" ? { events: [userEvent("a", 3, "a three"), userEvent("a", 4, "a four")], more: true } : {};
+ await client.loadOlder();
+ const methods = ScriptedSocket.current.sent.map((request) => request.method);
+ expect(methods.filter((method) => method === "_acpmux/attach").length).toBe(1);
+ expect(ScriptedSocket.current.sent.find((request) => request.method === "_acpmux/events")?.params.beforeSeq).toBe(5);
+ expect(texts()).toEqual(["a three", "a four", "a five", "a six"]);
+ expect(latest().queue).toEqual([{ id: "q1", prompt: "queued" }]);
+ expect(latest().summary?.status).toBe("idle");
+ expect(latest().permission?.permissionId).toBe("p1");
+ expect(latest().canLoadOlder).toBe(true);
+ });
+
+ test("history stops when the daemon reports no more", async () => {
+ const client = await connect();
+ ScriptedSocket.respond = ({ method }) => method === "_acpmux/events" ? { events: [userEvent("a", 3, "a three")], more: false } : {};
+ await client.loadOlder();
+ expect(texts()).toEqual(["a three", "a five", "a six"]);
+ expect(latest().canLoadOlder).toBe(false);
+ });
+
+ test("a history page that lands after the selection changed is dropped", async () => {
+ const client = await connect();
+ ScriptedSocket.held.add("_acpmux/events");
+ const older = client.loadOlder();
+ await settle();
+ await client.select("b");
+ ScriptedSocket.current.release("_acpmux/events", { events: [userEvent("a", 3, "stale a three")] });
+ await older;
+ client.snapshot();
+ expect(latest().sessionId).toBe("b");
+ expect(texts()).toEqual(["b one"]);
+ });
+
+ test("a request on a socket that is not open rejects instead of hanging", async () => {
+ const client = await connect();
+ ScriptedSocket.current.readyState = 3;
+ const sent = ScriptedSocket.current.sent.length;
+ const outcome = await Promise.race([
+ client.setModel("m").then(() => "resolved", () => "rejected"),
+ new Promise((resolve) => setTimeout(() => resolve("pending"), 100)),
+ ]);
+ expect(outcome).toBe("rejected");
+ expect(ScriptedSocket.current.sent.length).toBe(sent);
+ });
+
+ test("lag recovery merges missed events without clearing the transcript", async () => {
+ const client = await connect();
+ ScriptedSocket.held.add("session/prompt");
+ void client.send("still sending").catch(() => undefined);
+ await settle();
+ ScriptedSocket.respond = ({ method, params }) => method === "_acpmux/events" && params.afterSeq === 6 ? { events: [userEvent("a", 7, "a seven")] } : {};
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["a"], watch: false, dropped: 3 });
+ expect(texts()).toEqual(["a five", "a six", "still sending"]);
+ await settle();
+ expect(texts()).toEqual(["a five", "a six", "a seven", "still sending"]);
+ expect(latest().queue).toEqual([{ id: "q1", prompt: "queued" }]);
+ });
+
+ test("a lag notice without session IDs resyncs the selected session", async () => {
+ await connect();
+ ScriptedSocket.respond = ({ method, params }) => method === "_acpmux/events" && params.sessionId === "a" && params.afterSeq === 6 ? { events: [userEvent("a", 7, "a seven")] } : {};
+ ScriptedSocket.current.notify("_acpmux/lagged", { dropped: 2 });
+ await settle();
+ expect(texts()).toEqual(["a five", "a six", "a seven"]);
+ });
+
+ test("a lag notice for other sessions leaves the selected one alone", async () => {
+ await connect();
+ const sent = ScriptedSocket.current.sent.length;
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["b"], watch: false, dropped: 1 });
+ await settle();
+ expect(ScriptedSocket.current.sent.length).toBe(sent);
+ });
+
+ test("lag recovery pages until the daemon reports no more", async () => {
+ await connect();
+ ScriptedSocket.respond = ({ method, params }) => {
+ if (method !== "_acpmux/events") return {};
+ if (params.afterSeq === 6) return { events: [userEvent("a", 7, "a seven")], more: true };
+ if (params.afterSeq === 7) return { events: [userEvent("a", 8, "a eight")], more: false };
+ return {};
+ };
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["a"], watch: false, dropped: 2 });
+ await settle();
+ await settle();
+ expect(texts()).toEqual(["a five", "a six", "a seven", "a eight"]);
+ });
+
+ test("lag paging continues from the page it fetched, not from live events that landed meanwhile", async () => {
+ await connect();
+ ScriptedSocket.held.add("_acpmux/events");
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["a"], watch: false, dropped: 9 });
+ ScriptedSocket.current.notify("_acpmux/event", userEvent("a", 12, "a twelve"));
+ ScriptedSocket.current.release("_acpmux/events", { events: [userEvent("a", 7, "a seven"), userEvent("a", 8, "a eight")], more: true });
+ await settle();
+ expect(ScriptedSocket.current.waiting.find((request) => request.method === "_acpmux/events")?.params.afterSeq).toBe(8);
+ ScriptedSocket.current.release("_acpmux/events", { events: [9, 10, 11].map((seq) => userEvent("a", seq, `a ${seq}`)), more: false });
+ await settle();
+ expect(texts()).toEqual(["a five", "a six", "a seven", "a eight", "a 9", "a 10", "a 11", "a twelve"]);
+ });
+
+ test("a lag notice before the selected session's attach returns waits for the attach", async () => {
+ const client = await connect();
+ ScriptedSocket.held.add("_acpmux/attach");
+ const selecting = client.select("b");
+ await settle();
+ ScriptedSocket.current.notify("_acpmux/lagged", { dropped: 1 });
+ await settle();
+ expect(ScriptedSocket.current.sent.some((request) => request.method === "_acpmux/events")).toBe(false);
+ ScriptedSocket.current.release("_acpmux/attach", { session: { sessionId: "b", status: "idle" }, events: [userEvent("b", 1, "b one")] });
+ await selecting;
+ expect(texts()).toEqual(["b one"]);
+ });
+
+ test("a watch lag refreshes the session picker", async () => {
+ await connect();
+ ScriptedSocket.respond = ({ method }) => method === "_acpmux/watch" ? { sessions: [{ sessionId: "a" }, { sessionId: "b" }, { sessionId: "c" }] } : { events: [] };
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: [], watch: true, dropped: 4 });
+ await settle();
+ expect(latest().sessions.map((session) => session.sessionId)).toEqual(["a", "b", "c"]);
+ });
+
+ test("lag recovery for a session that is no longer selected is ignored", async () => {
+ const client = await connect();
+ ScriptedSocket.held.add("_acpmux/events");
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["a"], watch: false, dropped: 1 });
+ await client.select("b");
+ ScriptedSocket.current.release("_acpmux/events", { events: [userEvent("a", 7, "stale a seven")] });
+ await settle();
+ client.snapshot();
+ expect(texts()).toEqual(["b one"]);
+ ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["a"], watch: false, dropped: 1 });
+ expect(ScriptedSocket.current.waiting.length).toBe(0);
+ });
+
+ test("selecting a session drops the previous session's queue, summary, permission and pending prompt", async () => {
+ const client = await connect();
+ ScriptedSocket.current.notify("_acpmux/permission_pending", { sessionId: "a", permissionId: "p1", request: { toolCall: { title: "Run" }, options: [] } });
+ ScriptedSocket.held.add("session/prompt");
+ void client.send("still sending").catch(() => undefined);
+ await settle();
+ expect(texts()).toContain("still sending");
+ ScriptedSocket.held.add("_acpmux/attach");
+ const selected = client.select("b");
+ await settle();
+ client.snapshot();
+ expect(latest().rows).toEqual([]);
+ expect(latest().queue).toEqual([]);
+ expect(latest().summary).toBeUndefined();
+ expect(latest().permission).toBeUndefined();
+ ScriptedSocket.current.release("_acpmux/attach", attachReply("b"));
+ expect(await selected).toBe("b");
+ expect(texts()).toEqual(["b one"]);
+ });
+});
diff --git a/webviews/src/agent-session/acpmux/direct.ts b/webviews/src/agent-session/acpmux/direct.ts
index 52a2b9079614..1450fb208458 100644
--- a/webviews/src/agent-session/acpmux/direct.ts
+++ b/webviews/src/agent-session/acpmux/direct.ts
@@ -107,6 +107,9 @@ export class AcpmuxDirectClient {
private hasConnected = false;
private closed = false;
private selectionGeneration = 0;
+ /// The selection generation whose attach reply has landed; lag resync waits for it.
+ private attachedGeneration = -1;
+ private historyExhausted = false;
private constructor(host: AcpmuxHostConfig, listener: Listener, onLost?: () => void) {
this.host = host;
@@ -151,21 +154,7 @@ export class AcpmuxDirectClient {
this.catalog = normalizeCatalog(harnesses);
if (this.selectedSessionId && !this.sessions.some((session) => session.sessionId === this.selectedSessionId)) {
this.selectedSessionId = this.sessions[0]?.sessionId;
- this.events = [];
- this.rows.clear();
- this.firstSeq = undefined;
- this.lastSeq = 0;
- this.summary = undefined;
- this.queue = [];
- this.turnOpen = false;
- this.streamingAssistant = undefined;
- this.streamingAssistantMessageId = undefined;
- this.streamingActivity = undefined;
- this.optimisticPromptRows.clear();
- this.optimisticPromptTexts.clear();
- this.supersededMessageIds.clear();
- this.messageRows.clear();
- this.pendingPermission = undefined;
+ this.resetSessionState();
}
this.selectedSessionId = initialSession(this.selectedSessionId, this.sessions, this.host.newSession);
if (this.selectedSessionId) await this.attach(this.selectedSessionId);
@@ -180,6 +169,26 @@ export class AcpmuxDirectClient {
}
}
+ /** Drops everything that belongs to the previously selected session, before another one attaches. */
+ private resetSessionState(): void {
+ this.events = [];
+ this.historyExhausted = false;
+ this.rows.clear();
+ this.firstSeq = undefined;
+ this.lastSeq = 0;
+ this.summary = undefined;
+ this.queue = [];
+ this.turnOpen = false;
+ this.streamingAssistant = undefined;
+ this.streamingAssistantMessageId = undefined;
+ this.streamingActivity = undefined;
+ this.optimisticPromptRows.clear();
+ this.optimisticPromptTexts.clear();
+ this.supersededMessageIds.clear();
+ this.messageRows.clear();
+ this.pendingPermission = undefined;
+ }
+
private scheduleReconnect(): void {
if (this.reconnectTimer !== undefined || this.closed) return;
const delay = this.reconnectDelay;
@@ -213,27 +222,63 @@ export class AcpmuxDirectClient {
});
else if (notification.method === "_acpmux/session_changed") this.sessionChanged(notification.params);
else if (notification.method === "_acpmux/permission_pending") this.applyPermission(notification.params);
+ else if (notification.method === "_acpmux/lagged") this.resyncAfterLag(notification.params);
+ }
+
+ /// The daemon dropped events for this client. Fetch what came after the last
+ /// one seen and merge it in, keeping the transcript on screen meanwhile.
+ /// agent-gui daemons send {sessionIds, watch, dropped}; older ones send only
+ /// {dropped}, so a notice without sessionIds resyncs the selected session.
+ private resyncAfterLag(params: any): void {
+ if (params?.watch === true) void this.refreshSessions().catch(() => undefined);
+ const sessionId = this.selectedSessionId;
+ // Before the attach reply lands there is no cursor; the reply carries the latest events.
+ if (!sessionId || this.attachedGeneration !== this.selectionGeneration) return;
+ if (Array.isArray(params?.sessionIds) && !params.sessionIds.map(String).includes(sessionId)) return;
+ this.emit("resyncing");
+ void this.fetchMissedEvents(sessionId, this.selectionGeneration, this.lastSeq).catch(() => undefined);
+ }
+
+ /// Pages from its own cursor: live events keep advancing lastSeq meanwhile.
+ private async fetchMissedEvents(sessionId: string, generation: number, afterSeq: number): Promise {
+ for (let cursor = afterSeq; ;) {
+ const result = await this.request("_acpmux/events", { sessionId, afterSeq: cursor, limit: 5_000 });
+ if (generation !== this.selectionGeneration || this.selectedSessionId !== sessionId) return;
+ const missed: EventRecord[] = result?.events ?? [];
+ this.events = mergeEventRecords(this.events, missed);
+ this.rebuild();
+ if (result?.more !== true || missed.length === 0) break;
+ cursor = Math.max(cursor, ...missed.map((event) => event.seq));
+ }
+ this.emit("resynced");
+ }
+
+ /// session_changed notices dropped by a watch lag: reread the whole list.
+ private async refreshSessions(): Promise {
+ const watched = await this.request("_acpmux/watch", { enabled: true });
+ this.sessions = (watched?.sessions ?? []).filter((session: Session) => session.sessionId);
+ this.emit("session changed");
}
private request(method: string, params: Record): Promise {
+ if (this.socket?.readyState !== WebSocket.OPEN) return Promise.reject(new Error("acpmux WebSocket is not open"));
const id = this.nextRequest++;
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject });
- this.socket?.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
+ this.socket!.send(JSON.stringify({ jsonrpc: "2.0", id, method, params }));
});
}
- private async attach(sessionId: string, beforeSeq?: number, generation = this.selectionGeneration): Promise {
+ private async attach(sessionId: string, generation = this.selectionGeneration): Promise {
if (generation !== this.selectionGeneration || this.selectedSessionId !== sessionId) return;
- const params: Record = { sessionId, limit: 400, kinds: ["transcript"], eventStream: true };
- if (beforeSeq !== undefined) params.beforeSeq = beforeSeq;
- const result = await this.request("_acpmux/attach", params);
+ const result = await this.request("_acpmux/attach", { sessionId, limit: 400, kinds: ["transcript"], eventStream: true });
if (generation !== this.selectionGeneration || this.selectedSessionId !== sessionId) return;
const detail = result?.session ?? {};
this.summary = detail;
this.queue = (detail.queue ?? []).map((entry: any) => ({ id: String(entry.promptId), prompt: String(entry.prompt ?? "") }));
this.events = mergeEventRecords(result?.events ?? [], this.events);
this.rebuild();
+ this.attachedGeneration = generation;
this.emit("attached");
}
@@ -244,23 +289,11 @@ export class AcpmuxDirectClient {
if (session.sessionId === this.selectedSessionId) {
this.selectedSessionId = this.sessions[0]?.sessionId;
const generation = ++this.selectionGeneration;
- this.events = [];
- this.rows.clear();
- this.firstSeq = undefined;
- this.lastSeq = 0;
- this.summary = undefined;
- this.queue = [];
- this.turnOpen = false;
- this.streamingAssistant = undefined;
- this.streamingAssistantMessageId = undefined;
- this.streamingActivity = undefined;
- this.optimisticPromptRows.clear();
- this.optimisticPromptTexts.clear();
- this.supersededMessageIds.clear();
- this.messageRows.clear();
- this.pendingPermission = undefined;
+ this.resetSessionState();
+ this.emit("session purged");
+ if (this.selectedSessionId) void this.attach(this.selectedSessionId, generation).catch(() => undefined);
+ } else {
this.emit("session purged");
- if (this.selectedSessionId) void this.attach(this.selectedSessionId, undefined, generation).catch(() => undefined);
}
return;
}
@@ -269,8 +302,9 @@ export class AcpmuxDirectClient {
if (session.sessionId === this.selectedSessionId) {
this.summary = { ...this.summary, ...session };
this.queue = (session.queue ?? this.queue).map((entry: any) => ({ id: String(entry.promptId), prompt: String(entry.prompt ?? entry.preview ?? "") }));
- this.emit("session changed");
}
+ // The picker lists every session, so a change elsewhere still needs a snapshot.
+ this.emit("session changed");
}
private applyPermission(message: any): void {
@@ -290,7 +324,9 @@ export class AcpmuxDirectClient {
}
private rebuild(): void {
- this.rows.clear(); this.optimisticPromptRows.clear(); this.optimisticPromptTexts.clear(); this.firstSeq = undefined; this.lastSeq = 0; this.turnOpen = false; this.streamingAssistant = undefined; this.streamingAssistantMessageId = undefined; this.streamingActivity = undefined; this.supersededMessageIds.clear(); this.messageRows.clear(); this.pendingPermission = undefined;
+ // A prompt still in flight keeps its optimistic row until an event settles it.
+ const inFlight = [...this.optimisticPromptRows.values()].flatMap((rowId) => this.rows.get(rowId) ?? []);
+ this.rows.clear(); for (const row of inFlight) this.rows.set(row.id, row); this.firstSeq = undefined; this.lastSeq = 0; this.turnOpen = false; this.streamingAssistant = undefined; this.streamingAssistantMessageId = undefined; this.streamingActivity = undefined; this.supersededMessageIds.clear(); this.messageRows.clear(); this.pendingPermission = undefined;
const events = [...this.events].sort((a, b) => a.seq - b.seq);
for (const event of events) { this.lastSeq = Math.max(this.lastSeq, event.seq); this.firstSeq = this.firstSeq === undefined ? event.seq : Math.min(this.firstSeq, event.seq); this.reduce(event); }
}
@@ -345,7 +381,7 @@ export class AcpmuxDirectClient {
private emit(connection = "connected"): void {
const summary = this.summary;
const effort = (summary?.configOptions ?? []).find((option: any) => option.category === "thought_level" || option.id === "reasoning_effort");
- this.listener({ type: "snapshot", protocolVersion: 1, rows: [...this.rows.values()].sort((a, b) => a.at - b.at), sessions: this.sessions.map((session) => ({ sessionId: session.sessionId, displayTitle: session.title ?? session.name, title: session.title, name: session.name, status: session.status, model: session.model })), summary: summary ? { sessionId: summary.sessionId, title: summary.title, name: summary.name, harness: summary.harness, model: summary.model, effort: effort?.currentValue, status: summary.status, modes: summary.modes, configOptions: summary.configOptions } : undefined, connection, sessionId: this.selectedSessionId, isWorking: this.turnOpen || summary?.status === "running", queue: this.queue, permission: this.pendingPermission, catalog: this.catalog, canLoadOlder: (this.firstSeq ?? 1) > 1 });
+ this.listener({ type: "snapshot", protocolVersion: 1, rows: [...this.rows.values()].sort((a, b) => a.at - b.at), sessions: this.sessions.map((session) => ({ sessionId: session.sessionId, displayTitle: session.title ?? session.name, title: session.title, name: session.name, status: session.status, model: session.model })), summary: summary ? { sessionId: summary.sessionId, title: summary.title, name: summary.name, harness: summary.harness, model: summary.model, effort: effort?.currentValue, status: summary.status, modes: summary.modes, configOptions: summary.configOptions } : undefined, connection, sessionId: this.selectedSessionId, isWorking: this.turnOpen || summary?.status === "running", queue: this.queue, permission: this.pendingPermission, catalog: this.catalog, canLoadOlder: !this.historyExhausted && (this.firstSeq ?? 1) > 1 });
}
snapshot(): void { this.emit(); }
@@ -375,23 +411,36 @@ export class AcpmuxDirectClient {
const previousSessionId = this.selectedSessionId;
const generation = ++this.selectionGeneration;
this.selectedSessionId = sessionId;
- this.events = [];
- this.rows.clear();
- this.firstSeq = undefined;
- this.lastSeq = 0;
- this.turnOpen = false;
- this.streamingAssistant = undefined;
- this.streamingActivity = undefined;
- this.pendingPermission = undefined;
+ this.resetSessionState();
if (previousSessionId) await this.request("_acpmux/detach", { sessionId: previousSessionId });
- await this.attach(sessionId, undefined, generation);
+ await this.attach(sessionId, generation);
return generation === this.selectionGeneration && this.selectedSessionId === sessionId ? sessionId : undefined;
}
async create(harness?: string): Promise { const result = await this.request("session/new", { mcpServers: [], _meta: { acpmux: { harness } } }); if (result?.sessionId) return this.select(String(result.sessionId)); return undefined; }
async setModel(modelId: string): Promise { if (this.selectedSessionId) await this.request("session/set_model", { sessionId: this.selectedSessionId, modelId }); }
async setMode(modeId: string): Promise { if (this.selectedSessionId) await this.request("session/set_mode", { sessionId: this.selectedSessionId, modeId }); }
async setConfig(configId: string, value: string): Promise { if (this.selectedSessionId) await this.request("session/set_config_option", { sessionId: this.selectedSessionId, configId, value }); }
- async loadOlder(): Promise { if (this.selectedSessionId && this.firstSeq && this.firstSeq > 1) await this.attach(this.selectedSessionId, this.firstSeq); }
+ /// Pages older transcript events in without reattaching, so the live summary,
+ /// queue and permission stay as they are. A page that lands after the
+ /// selection changed belongs to another session and is dropped.
+ async loadOlder(): Promise {
+ if (!this.selectedSessionId || !this.firstSeq || this.firstSeq <= 1 || this.historyExhausted) return;
+ const sessionId = this.selectedSessionId;
+ const generation = this.selectionGeneration;
+ const result = await this.request("_acpmux/events", { sessionId, beforeSeq: this.firstSeq, limit: 400, kinds: ["transcript"] });
+ if (generation !== this.selectionGeneration || this.selectedSessionId !== sessionId) return;
+ const summary = this.summary;
+ const queue = this.queue;
+ const permission = this.pendingPermission;
+ const older: EventRecord[] = result?.events ?? [];
+ this.events = mergeEventRecords(older, this.events);
+ this.rebuild();
+ this.summary = summary;
+ this.queue = queue;
+ this.pendingPermission = permission;
+ this.historyExhausted = result?.more === false || older.length === 0 || (this.firstSeq ?? 1) <= 1;
+ this.emit("history");
+ }
close(): void { this.closed = true; if (this.reconnectTimer !== undefined) window.clearTimeout(this.reconnectTimer); this.reconnectTimer = undefined; this.socket?.close(); this.socket = undefined; }
}