From 16c261e05e375c4f59896aa21da8cc3852fdfce4 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 11:35:11 -0400 Subject: [PATCH 01/10] Agent pane: failing tests for picker refresh, history paging, socket readiness, lag recovery and select reset Seven client tests drive AcpmuxDirectClient over a scripted socket. All fail on this commit: an unselected purge leaves the picker stale, history reattaches instead of paging _acpmux/events, a request on a closed socket resolves silently, _acpmux/lagged is ignored, and select keeps the old session's queue, summary and permission. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../src/agent-session/acpmux/direct.test.ts | 168 +++++++++++++++++- 1 file changed, 165 insertions(+), 3 deletions(-) diff --git a/webviews/src/agent-session/acpmux/direct.test.ts b/webviews/src/agent-session/acpmux/direct.test.ts index ea9c2e752c82..1f7b2af0f99e 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,164 @@ 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")], hasMore: 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"); + }); + + 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 () => { + await connect(); + ScriptedSocket.respond = ({ method, params }) => method === "_acpmux/events" && params.afterSeq === 6 ? { events: [userEvent("a", 7, "a seven")] } : {}; + ScriptedSocket.current.notify("_acpmux/lagged", { sessionId: "a" }); + expect(texts()).toEqual(["a five", "a six"]); + await settle(); + expect(texts()).toEqual(["a five", "a six", "a seven"]); + expect(latest().queue).toEqual([{ id: "q1", prompt: "queued" }]); + }); + + 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", { sessionId: "a" }); + 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", { sessionId: "a" }); + 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"]); + }); +}); From 5311a4365f151deca5cccbe43b4bd06c2c797f6b Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 11:35:22 -0400 Subject: [PATCH 02/10] Agent pane: refresh the session picker on every session-list change sessionChanged emitted only when the selected session changed, so a session created, updated or purged elsewhere left the picker stale until some other event. It now emits after every list mutation, including the unselected purge branch. Ported from #16203 (0b8b161b4fd). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- webviews/src/agent-session/acpmux/direct.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/webviews/src/agent-session/acpmux/direct.ts b/webviews/src/agent-session/acpmux/direct.ts index 52a2b9079614..a94ebf48e772 100644 --- a/webviews/src/agent-session/acpmux/direct.ts +++ b/webviews/src/agent-session/acpmux/direct.ts @@ -261,6 +261,8 @@ export class AcpmuxDirectClient { this.pendingPermission = undefined; this.emit("session purged"); if (this.selectedSessionId) void this.attach(this.selectedSessionId, undefined, generation).catch(() => undefined); + } else { + this.emit("session purged"); } return; } @@ -269,8 +271,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 { From 8dab5fb10c1b834355f5c05a0a90d29b8f4ed5ae Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 11:35:42 -0400 Subject: [PATCH 03/10] Agent pane: select resets all of the previous session's client state select cleared only rows, sequence, turn, streaming and permission, so the old session's queue, summary, optimistic prompt rows, superseded IDs, message mapping and assistant message ID lingered until the new attach replaced some of them. One resetSessionState helper now does the full reset for select, the open missing-session path and the selected purge path. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- webviews/src/agent-session/acpmux/direct.ts | 60 ++++++++------------- 1 file changed, 22 insertions(+), 38 deletions(-) diff --git a/webviews/src/agent-session/acpmux/direct.ts b/webviews/src/agent-session/acpmux/direct.ts index a94ebf48e772..7ffae545d082 100644 --- a/webviews/src/agent-session/acpmux/direct.ts +++ b/webviews/src/agent-session/acpmux/direct.ts @@ -151,21 +151,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 +166,25 @@ export class AcpmuxDirectClient { } } + /** Drops everything that belongs to the previously selected session, before another one attaches. */ + private resetSessionState(): void { + 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; + } + private scheduleReconnect(): void { if (this.reconnectTimer !== undefined || this.closed) return; const delay = this.reconnectDelay; @@ -244,21 +249,7 @@ 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, undefined, generation).catch(() => undefined); } else { @@ -378,14 +369,7 @@ 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); return generation === this.selectionGeneration && this.selectedSessionId === sessionId ? sessionId : undefined; From f7ea055beed1fb293a28f6dbcc696bfcf75334bc Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 11:36:33 -0400 Subject: [PATCH 04/10] Agent pane: reject requests on a closed socket and recover from lag request sent through socket?.send and waited forever when the socket was absent or not open. It now rejects at once. The client also handles _acpmux/lagged: it fetches _acpmux/events after the last seen sequence, drops the reply if the session or selection generation changed, and merges the missed events into the transcript instead of clearing it. rebuild keeps optimistic rows for prompts still in flight, so a lag replay no longer blanks a prompt the user just sent; the lag test now covers that. Ported from #16203 (a974f73b448, 8fc1387f896). The reconnect test's fake socket gains readyState so the guard sees an open socket. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../acpmux/direct-reconnect.test.ts | 8 ++++--- .../src/agent-session/acpmux/direct.test.ts | 9 ++++--- webviews/src/agent-session/acpmux/direct.ts | 24 +++++++++++++++++-- 3 files changed, 33 insertions(+), 8 deletions(-) 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 1f7b2af0f99e..1615c601cb66 100644 --- a/webviews/src/agent-session/acpmux/direct.test.ts +++ b/webviews/src/agent-session/acpmux/direct.test.ts @@ -175,12 +175,15 @@ describe("direct client session state", () => { }); test("lag recovery merges missed events without clearing the transcript", async () => { - await connect(); + 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", { sessionId: "a" }); - expect(texts()).toEqual(["a five", "a six"]); + expect(texts()).toEqual(["a five", "a six", "still sending"]); await settle(); - expect(texts()).toEqual(["a five", "a six", "a seven"]); + expect(texts()).toEqual(["a five", "a six", "a seven", "still sending"]); expect(latest().queue).toEqual([{ id: "q1", prompt: "queued" }]); }); diff --git a/webviews/src/agent-session/acpmux/direct.ts b/webviews/src/agent-session/acpmux/direct.ts index 7ffae545d082..f9976e714aa3 100644 --- a/webviews/src/agent-session/acpmux/direct.ts +++ b/webviews/src/agent-session/acpmux/direct.ts @@ -218,13 +218,31 @@ 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. + private resyncAfterLag(params: any): void { + const sessionId = String(params?.sessionId ?? ""); + if (!sessionId || sessionId !== this.selectedSessionId) return; + const generation = this.selectionGeneration; + const afterSeq = this.lastSeq; + this.emit("resyncing"); + void this.request("_acpmux/events", { sessionId, afterSeq, limit: 5_000 }).then((result) => { + if (generation !== this.selectionGeneration || this.selectedSessionId !== sessionId) return; + this.events = mergeEventRecords(this.events, result?.events ?? []); + this.rebuild(); + this.emit("resynced"); + }).catch(() => undefined); } 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 })); }); } @@ -284,7 +302,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); } } From 86491e23121253e026912d5016fa2e9cb4b0fbd5 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 11:37:24 -0400 Subject: [PATCH 05/10] Agent pane: page history through _acpmux/events instead of reattaching loadOlder reattached with beforeSeq, which replaced the live summary and queue with the attach reply and rebuilt away the pending permission. It now asks _acpmux/events for the page before the first loaded sequence, captures the session and selection generation first and drops the reply if either changed, merges the older events, and restores the live summary, queue and permission after the rebuild. History stops when the daemon reports no more, returns an empty page, or reaches sequence 1. attach loses its now-unused beforeSeq parameter. Ported from #16203 (8fc1387f896, guard from 4d91ad2cd05). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- webviews/src/agent-session/acpmux/direct.ts | 36 ++++++++++++++++----- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/webviews/src/agent-session/acpmux/direct.ts b/webviews/src/agent-session/acpmux/direct.ts index f9976e714aa3..8c6a3dfb482e 100644 --- a/webviews/src/agent-session/acpmux/direct.ts +++ b/webviews/src/agent-session/acpmux/direct.ts @@ -107,6 +107,7 @@ export class AcpmuxDirectClient { private hasConnected = false; private closed = false; private selectionGeneration = 0; + private historyExhausted = false; private constructor(host: AcpmuxHostConfig, listener: Listener, onLost?: () => void) { this.host = host; @@ -169,6 +170,7 @@ 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; @@ -246,11 +248,9 @@ export class AcpmuxDirectClient { }); } - 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; @@ -269,7 +269,7 @@ export class AcpmuxDirectClient { const generation = ++this.selectionGeneration; this.resetSessionState(); this.emit("session purged"); - if (this.selectedSessionId) void this.attach(this.selectedSessionId, undefined, generation).catch(() => undefined); + if (this.selectedSessionId) void this.attach(this.selectedSessionId, generation).catch(() => undefined); } else { this.emit("session purged"); } @@ -359,7 +359,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(); } @@ -391,14 +391,34 @@ export class AcpmuxDirectClient { this.selectedSessionId = sessionId; 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?.hasMore === 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; } } From 7eed115b1d75abfbfbcac92cd07d06513b0af183 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 13:42:47 -0400 Subject: [PATCH 06/10] Agent pane: rebuild the bundled page after the session-state follow-ups Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../Resources/agent-pane/index.html | 38 +++++++++---------- 1 file changed, 19 insertions(+), 19 deletions(-) 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 bdce70c066fa..e9471f83430f 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html @@ -2001,19 +2001,19 @@
From 154cdbb307ce85cc8e17bd1ef290190159cad7c4 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 13:48:02 -0400 Subject: [PATCH 07/10] Agent pane: failing tests for the daemon's real lagged and history shapes The acpmux daemon sends _acpmux/lagged as {sessionIds, watch, dropped} (agent-gui) or {dropped} (older daemons), never {sessionId}, and ends _acpmux/events pages with `more`, not `hasMore`. With the real shapes the client ignores every lag notice, stops lag recovery after one page, leaves the picker stale after a watch lag, and keeps offering older history after `more: false`. Six tests fail here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../src/agent-session/acpmux/direct.test.ts | 55 +++++++++++++++++-- 1 file changed, 51 insertions(+), 4 deletions(-) diff --git a/webviews/src/agent-session/acpmux/direct.test.ts b/webviews/src/agent-session/acpmux/direct.test.ts index 1615c601cb66..cec555d0b0e0 100644 --- a/webviews/src/agent-session/acpmux/direct.test.ts +++ b/webviews/src/agent-session/acpmux/direct.test.ts @@ -138,7 +138,7 @@ describe("direct client session state", () => { 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")], hasMore: true } : {}; + 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); @@ -147,6 +147,15 @@ describe("direct client session state", () => { 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 () => { @@ -180,23 +189,61 @@ describe("direct client session state", () => { 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", { sessionId: "a" }); + 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("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", { sessionId: "a" }); + 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", { sessionId: "a" }); + ScriptedSocket.current.notify("_acpmux/lagged", { sessionIds: ["a"], watch: false, dropped: 1 }); expect(ScriptedSocket.current.waiting.length).toBe(0); }); From 4d6b7f577502af412703791ac8f7bb666a0400be Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 13:48:35 -0400 Subject: [PATCH 08/10] Agent pane: follow the daemon's real lagged and history shapes Lag recovery read a sessionId the daemon never sends, so it never ran. It now resyncs the selected session when the notice lists it, or when the notice has no sessionIds (older daemons send only dropped), pages _acpmux/events until `more` is false, and rereads the session list when the watch stream lagged. History paging reads `more` instead of `hasMore`. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../Resources/agent-pane/index.html | 2 +- webviews/src/agent-session/acpmux/direct.ts | 34 ++++++++++++++----- 2 files changed, 26 insertions(+), 10 deletions(-) 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 e9471f83430f..85d81b426598 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html @@ -2070,7 +2070,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let l="

An error occurred:

"+Fe(n.message+"",!0)+"
";return e?Promise.resolve(l):l}if(e)return Promise.reject(n);throw n}}},In=new xS;function I(t,e){return In.parse(t,e)}I.options=I.setOptions=function(t){return In.setOptions(t),I.defaults=In.defaults,g1(I.defaults),I};I.getDefaults=jr;I.defaults=Pn;I.use=function(...t){return In.use(...t),I.defaults=In.defaults,g1(I.defaults),I};I.walkTokens=function(t,e){return In.walkTokens(t,e)};I.parseInline=In.parseInline;I.Parser=ge;I.parser=ge.parse;I.Renderer=Vu;I.TextRenderer=$r;I.Lexer=pe;I.lexer=pe.lex;I.Tokenizer=Zu;I.Hooks=sa;I.parse=I;var bv=I.options,Ev=I.setOptions,Nv=I.use,Mv=I.walkTokens,Cv=I.parseInline;var Fv=ge.parse,F1=pe.lex;var mS={isDark:null,pageBackground:"--agent-page-bg",surfaceBackground:"--agent-surface",surfaceElevatedBackground:"--agent-surface-elevated",inputBackground:"--agent-input-bg",border:"--agent-border",borderStrong:"--agent-border-strong",text:"--agent-text",mutedText:"--agent-muted",softText:"--agent-soft",accent:"--agent-accent",accentSoft:"--agent-accent-soft",danger:"--agent-danger",shadow:"--agent-shadow"};function D1(t){if(typeof document>"u")return;let e=document.documentElement;e.dataset.theme=t.isDark?"dark":"light",pS(),e.classList.toggle("dark",t.isDark),e.classList.toggle("electron-dark",t.isDark),e.classList.toggle("light",!t.isDark),e.style.colorScheme=t.isDark?"dark":"light";for(let[n,l]of Object.entries(mS))l&&e.style.setProperty(l,String(t[n]))}function pS(){if(typeof document>"u")return;let t=document.documentElement;t.dataset.codexWindowType="electron",t.dataset.windowType="electron",t.dataset.codexOs=gS(),document.body&&(document.body.dataset.codexWindowType="electron")}function gS(){if(typeof navigator>"u")return"unknown";let t=navigator,e=(t.userAgentData?.platform??t.platform??t.userAgent).toLowerCase();return e.includes("win")?"win32":e.includes("mac")||e.includes("darwin")?"darwin":e.includes("linux")?"linux":"unknown"}var B1=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],Ir=[[697,698,"ON"],[706,719,"ON"],[722,735,"ON"],[741,749,"ON"],[751,767,"ON"],[768,879,"NSM"],[884,885,"ON"],[894,894,"ON"],[900,901,"ON"],[903,903,"ON"],[1014,1014,"ON"],[1155,1161,"NSM"],[1418,1418,"ON"],[1421,1422,"ON"],[1423,1423,"ET"],[1424,1424,"R"],[1425,1469,"NSM"],[1470,1470,"R"],[1471,1471,"NSM"],[1472,1472,"R"],[1473,1474,"NSM"],[1475,1475,"R"],[1476,1477,"NSM"],[1478,1478,"R"],[1479,1479,"NSM"],[1480,1535,"R"],[1536,1541,"AN"],[1542,1543,"ON"],[1544,1544,"AL"],[1545,1546,"ET"],[1547,1547,"AL"],[1548,1548,"CS"],[1549,1549,"AL"],[1550,1551,"ON"],[1552,1562,"NSM"],[1563,1610,"AL"],[1611,1631,"NSM"],[1632,1641,"AN"],[1642,1642,"ET"],[1643,1644,"AN"],[1645,1647,"AL"],[1648,1648,"NSM"],[1649,1749,"AL"],[1750,1756,"NSM"],[1757,1757,"AN"],[1758,1758,"ON"],[1759,1764,"NSM"],[1765,1766,"AL"],[1767,1768,"NSM"],[1769,1769,"ON"],[1770,1773,"NSM"],[1774,1775,"AL"],[1776,1785,"EN"],[1786,1808,"AL"],[1809,1809,"NSM"],[1810,1839,"AL"],[1840,1866,"NSM"],[1867,1957,"AL"],[1958,1968,"NSM"],[1969,1983,"AL"],[1984,2026,"R"],[2027,2035,"NSM"],[2036,2037,"R"],[2038,2041,"ON"],[2042,2044,"R"],[2045,2045,"NSM"],[2046,2069,"R"],[2070,2073,"NSM"],[2074,2074,"R"],[2075,2083,"NSM"],[2084,2084,"R"],[2085,2087,"NSM"],[2088,2088,"R"],[2089,2093,"NSM"],[2094,2136,"R"],[2137,2139,"NSM"],[2140,2143,"R"],[2144,2191,"AL"],[2192,2193,"AN"],[2194,2198,"AL"],[2199,2207,"NSM"],[2208,2249,"AL"],[2250,2273,"NSM"],[2274,2274,"AN"],[2275,2306,"NSM"],[2362,2362,"NSM"],[2364,2364,"NSM"],[2369,2376,"NSM"],[2381,2381,"NSM"],[2385,2391,"NSM"],[2402,2403,"NSM"],[2433,2433,"NSM"],[2492,2492,"NSM"],[2497,2500,"NSM"],[2509,2509,"NSM"],[2530,2531,"NSM"],[2546,2547,"ET"],[2555,2555,"ET"],[2558,2558,"NSM"],[2561,2562,"NSM"],[2620,2620,"NSM"],[2625,2626,"NSM"],[2631,2632,"NSM"],[2635,2637,"NSM"],[2641,2641,"NSM"],[2672,2673,"NSM"],[2677,2677,"NSM"],[2689,2690,"NSM"],[2748,2748,"NSM"],[2753,2757,"NSM"],[2759,2760,"NSM"],[2765,2765,"NSM"],[2786,2787,"NSM"],[2801,2801,"ET"],[2810,2815,"NSM"],[2817,2817,"NSM"],[2876,2876,"NSM"],[2879,2879,"NSM"],[2881,2884,"NSM"],[2893,2893,"NSM"],[2901,2902,"NSM"],[2914,2915,"NSM"],[2946,2946,"NSM"],[3008,3008,"NSM"],[3021,3021,"NSM"],[3059,3064,"ON"],[3065,3065,"ET"],[3066,3066,"ON"],[3072,3072,"NSM"],[3076,3076,"NSM"],[3132,3132,"NSM"],[3134,3136,"NSM"],[3142,3144,"NSM"],[3146,3149,"NSM"],[3157,3158,"NSM"],[3170,3171,"NSM"],[3192,3198,"ON"],[3201,3201,"NSM"],[3260,3260,"NSM"],[3276,3277,"NSM"],[3298,3299,"NSM"],[3328,3329,"NSM"],[3387,3388,"NSM"],[3393,3396,"NSM"],[3405,3405,"NSM"],[3426,3427,"NSM"],[3457,3457,"NSM"],[3530,3530,"NSM"],[3538,3540,"NSM"],[3542,3542,"NSM"],[3633,3633,"NSM"],[3636,3642,"NSM"],[3647,3647,"ET"],[3655,3662,"NSM"],[3761,3761,"NSM"],[3764,3772,"NSM"],[3784,3790,"NSM"],[3864,3865,"NSM"],[3893,3893,"NSM"],[3895,3895,"NSM"],[3897,3897,"NSM"],[3898,3901,"ON"],[3953,3966,"NSM"],[3968,3972,"NSM"],[3974,3975,"NSM"],[3981,3991,"NSM"],[3993,4028,"NSM"],[4038,4038,"NSM"],[4141,4144,"NSM"],[4146,4151,"NSM"],[4153,4154,"NSM"],[4157,4158,"NSM"],[4184,4185,"NSM"],[4190,4192,"NSM"],[4209,4212,"NSM"],[4226,4226,"NSM"],[4229,4230,"NSM"],[4237,4237,"NSM"],[4253,4253,"NSM"],[4957,4959,"NSM"],[5008,5017,"ON"],[5120,5120,"ON"],[5760,5760,"WS"],[5787,5788,"ON"],[5906,5908,"NSM"],[5938,5939,"NSM"],[5970,5971,"NSM"],[6002,6003,"NSM"],[6068,6069,"NSM"],[6071,6077,"NSM"],[6086,6086,"NSM"],[6089,6099,"NSM"],[6107,6107,"ET"],[6109,6109,"NSM"],[6128,6137,"ON"],[6144,6154,"ON"],[6155,6157,"NSM"],[6158,6158,"BN"],[6159,6159,"NSM"],[6277,6278,"NSM"],[6313,6313,"NSM"],[6432,6434,"NSM"],[6439,6440,"NSM"],[6450,6450,"NSM"],[6457,6459,"NSM"],[6464,6464,"ON"],[6468,6469,"ON"],[6622,6655,"ON"],[6679,6680,"NSM"],[6683,6683,"NSM"],[6742,6742,"NSM"],[6744,6750,"NSM"],[6752,6752,"NSM"],[6754,6754,"NSM"],[6757,6764,"NSM"],[6771,6780,"NSM"],[6783,6783,"NSM"],[6832,6877,"NSM"],[6880,6891,"NSM"],[6912,6915,"NSM"],[6964,6964,"NSM"],[6966,6970,"NSM"],[6972,6972,"NSM"],[6978,6978,"NSM"],[7019,7027,"NSM"],[7040,7041,"NSM"],[7074,7077,"NSM"],[7080,7081,"NSM"],[7083,7085,"NSM"],[7142,7142,"NSM"],[7144,7145,"NSM"],[7149,7149,"NSM"],[7151,7153,"NSM"],[7212,7219,"NSM"],[7222,7223,"NSM"],[7376,7378,"NSM"],[7380,7392,"NSM"],[7394,7400,"NSM"],[7405,7405,"NSM"],[7412,7412,"NSM"],[7416,7417,"NSM"],[7616,7679,"NSM"],[8125,8125,"ON"],[8127,8129,"ON"],[8141,8143,"ON"],[8157,8159,"ON"],[8173,8175,"ON"],[8189,8190,"ON"],[8192,8202,"WS"],[8203,8205,"BN"],[8207,8207,"R"],[8208,8231,"ON"],[8232,8232,"WS"],[8233,8233,"B"],[8234,8238,"BN"],[8239,8239,"CS"],[8240,8244,"ET"],[8245,8259,"ON"],[8260,8260,"CS"],[8261,8286,"ON"],[8287,8287,"WS"],[8288,8303,"BN"],[8304,8304,"EN"],[8308,8313,"EN"],[8314,8315,"ES"],[8316,8318,"ON"],[8320,8329,"EN"],[8330,8331,"ES"],[8332,8334,"ON"],[8352,8399,"ET"],[8400,8432,"NSM"],[8448,8449,"ON"],[8451,8454,"ON"],[8456,8457,"ON"],[8468,8468,"ON"],[8470,8472,"ON"],[8478,8483,"ON"],[8485,8485,"ON"],[8487,8487,"ON"],[8489,8489,"ON"],[8494,8494,"ET"],[8506,8507,"ON"],[8512,8516,"ON"],[8522,8525,"ON"],[8528,8543,"ON"],[8585,8587,"ON"],[8592,8721,"ON"],[8722,8722,"ES"],[8723,8723,"ET"],[8724,9013,"ON"],[9083,9108,"ON"],[9110,9257,"ON"],[9280,9290,"ON"],[9312,9351,"ON"],[9352,9371,"EN"],[9450,9899,"ON"],[9901,10239,"ON"],[10496,11123,"ON"],[11126,11263,"ON"],[11493,11498,"ON"],[11503,11505,"NSM"],[11513,11519,"ON"],[11647,11647,"NSM"],[11744,11775,"NSM"],[11776,11869,"ON"],[11904,11929,"ON"],[11931,12019,"ON"],[12032,12245,"ON"],[12272,12287,"ON"],[12288,12288,"WS"],[12289,12292,"ON"],[12296,12320,"ON"],[12330,12333,"NSM"],[12336,12336,"ON"],[12342,12343,"ON"],[12349,12351,"ON"],[12441,12442,"NSM"],[12443,12444,"ON"],[12448,12448,"ON"],[12539,12539,"ON"],[12736,12773,"ON"],[12783,12783,"ON"],[12829,12830,"ON"],[12880,12895,"ON"],[12924,12926,"ON"],[12977,12991,"ON"],[13004,13007,"ON"],[13175,13178,"ON"],[13278,13279,"ON"],[13311,13311,"ON"],[19904,19967,"ON"],[42128,42182,"ON"],[42509,42511,"ON"],[42607,42610,"NSM"],[42611,42611,"ON"],[42612,42621,"NSM"],[42622,42623,"ON"],[42654,42655,"NSM"],[42736,42737,"NSM"],[42752,42785,"ON"],[42888,42888,"ON"],[43010,43010,"NSM"],[43014,43014,"NSM"],[43019,43019,"NSM"],[43045,43046,"NSM"],[43048,43051,"ON"],[43052,43052,"NSM"],[43064,43065,"ET"],[43124,43127,"ON"],[43204,43205,"NSM"],[43232,43249,"NSM"],[43263,43263,"NSM"],[43302,43309,"NSM"],[43335,43345,"NSM"],[43392,43394,"NSM"],[43443,43443,"NSM"],[43446,43449,"NSM"],[43452,43453,"NSM"],[43493,43493,"NSM"],[43561,43566,"NSM"],[43569,43570,"NSM"],[43573,43574,"NSM"],[43587,43587,"NSM"],[43596,43596,"NSM"],[43644,43644,"NSM"],[43696,43696,"NSM"],[43698,43700,"NSM"],[43703,43704,"NSM"],[43710,43711,"NSM"],[43713,43713,"NSM"],[43756,43757,"NSM"],[43766,43766,"NSM"],[43882,43883,"ON"],[44005,44005,"NSM"],[44008,44008,"NSM"],[44013,44013,"NSM"],[64285,64285,"R"],[64286,64286,"NSM"],[64287,64296,"R"],[64297,64297,"ES"],[64298,64335,"R"],[64336,64450,"AL"],[64451,64466,"ON"],[64467,64829,"AL"],[64830,64847,"ON"],[64848,64911,"AL"],[64912,64913,"ON"],[64914,64967,"AL"],[64968,64975,"ON"],[64976,65007,"BN"],[65008,65020,"AL"],[65021,65023,"ON"],[65024,65039,"NSM"],[65040,65049,"ON"],[65056,65071,"NSM"],[65072,65103,"ON"],[65104,65104,"CS"],[65105,65105,"ON"],[65106,65106,"CS"],[65108,65108,"ON"],[65109,65109,"CS"],[65110,65118,"ON"],[65119,65119,"ET"],[65120,65121,"ON"],[65122,65123,"ES"],[65124,65126,"ON"],[65128,65128,"ON"],[65129,65130,"ET"],[65131,65131,"ON"],[65136,65278,"AL"],[65279,65279,"BN"],[65281,65282,"ON"],[65283,65285,"ET"],[65286,65290,"ON"],[65291,65291,"ES"],[65292,65292,"CS"],[65293,65293,"ES"],[65294,65295,"CS"],[65296,65305,"EN"],[65306,65306,"CS"],[65307,65312,"ON"],[65339,65344,"ON"],[65371,65381,"ON"],[65504,65505,"ET"],[65506,65508,"ON"],[65509,65510,"ET"],[65512,65518,"ON"],[65520,65528,"BN"],[65529,65533,"ON"],[65534,65535,"BN"],[65793,65793,"ON"],[65856,65932,"ON"],[65936,65948,"ON"],[65952,65952,"ON"],[66045,66045,"NSM"],[66272,66272,"NSM"],[66273,66299,"EN"],[66422,66426,"NSM"],[67584,67870,"R"],[67871,67871,"ON"],[67872,68096,"R"],[68097,68099,"NSM"],[68100,68100,"R"],[68101,68102,"NSM"],[68103,68107,"R"],[68108,68111,"NSM"],[68112,68151,"R"],[68152,68154,"NSM"],[68155,68158,"R"],[68159,68159,"NSM"],[68160,68324,"R"],[68325,68326,"NSM"],[68327,68408,"R"],[68409,68415,"ON"],[68416,68863,"R"],[68864,68899,"AL"],[68900,68903,"NSM"],[68904,68911,"AL"],[68912,68921,"AN"],[68922,68927,"AL"],[68928,68937,"AN"],[68938,68968,"R"],[68969,68973,"NSM"],[68974,68974,"ON"],[68975,69215,"R"],[69216,69246,"AN"],[69247,69290,"R"],[69291,69292,"NSM"],[69293,69311,"R"],[69312,69327,"AL"],[69328,69336,"ON"],[69337,69369,"AL"],[69370,69375,"NSM"],[69376,69423,"R"],[69424,69445,"AL"],[69446,69456,"NSM"],[69457,69487,"AL"],[69488,69505,"R"],[69506,69509,"NSM"],[69510,69631,"R"],[69633,69633,"NSM"],[69688,69702,"NSM"],[69714,69733,"ON"],[69744,69744,"NSM"],[69747,69748,"NSM"],[69759,69761,"NSM"],[69811,69814,"NSM"],[69817,69818,"NSM"],[69826,69826,"NSM"],[69888,69890,"NSM"],[69927,69931,"NSM"],[69933,69940,"NSM"],[70003,70003,"NSM"],[70016,70017,"NSM"],[70070,70078,"NSM"],[70089,70092,"NSM"],[70095,70095,"NSM"],[70191,70193,"NSM"],[70196,70196,"NSM"],[70198,70199,"NSM"],[70206,70206,"NSM"],[70209,70209,"NSM"],[70367,70367,"NSM"],[70371,70378,"NSM"],[70400,70401,"NSM"],[70459,70460,"NSM"],[70464,70464,"NSM"],[70502,70508,"NSM"],[70512,70516,"NSM"],[70587,70592,"NSM"],[70606,70606,"NSM"],[70608,70608,"NSM"],[70610,70610,"NSM"],[70625,70626,"NSM"],[70712,70719,"NSM"],[70722,70724,"NSM"],[70726,70726,"NSM"],[70750,70750,"NSM"],[70835,70840,"NSM"],[70842,70842,"NSM"],[70847,70848,"NSM"],[70850,70851,"NSM"],[71090,71093,"NSM"],[71100,71101,"NSM"],[71103,71104,"NSM"],[71132,71133,"NSM"],[71219,71226,"NSM"],[71229,71229,"NSM"],[71231,71232,"NSM"],[71264,71276,"ON"],[71339,71339,"NSM"],[71341,71341,"NSM"],[71344,71349,"NSM"],[71351,71351,"NSM"],[71453,71453,"NSM"],[71455,71455,"NSM"],[71458,71461,"NSM"],[71463,71467,"NSM"],[71727,71735,"NSM"],[71737,71738,"NSM"],[71995,71996,"NSM"],[71998,71998,"NSM"],[72003,72003,"NSM"],[72148,72151,"NSM"],[72154,72155,"NSM"],[72160,72160,"NSM"],[72193,72198,"NSM"],[72201,72202,"NSM"],[72243,72248,"NSM"],[72251,72254,"NSM"],[72263,72263,"NSM"],[72273,72278,"NSM"],[72281,72283,"NSM"],[72330,72342,"NSM"],[72344,72345,"NSM"],[72544,72544,"NSM"],[72546,72548,"NSM"],[72550,72550,"NSM"],[72752,72758,"NSM"],[72760,72765,"NSM"],[72850,72871,"NSM"],[72874,72880,"NSM"],[72882,72883,"NSM"],[72885,72886,"NSM"],[73009,73014,"NSM"],[73018,73018,"NSM"],[73020,73021,"NSM"],[73023,73029,"NSM"],[73031,73031,"NSM"],[73104,73105,"NSM"],[73109,73109,"NSM"],[73111,73111,"NSM"],[73459,73460,"NSM"],[73472,73473,"NSM"],[73526,73530,"NSM"],[73536,73536,"NSM"],[73538,73538,"NSM"],[73562,73562,"NSM"],[73685,73692,"ON"],[73693,73696,"ET"],[73697,73713,"ON"],[78912,78912,"NSM"],[78919,78933,"NSM"],[90398,90409,"NSM"],[90413,90415,"NSM"],[92912,92916,"NSM"],[92976,92982,"NSM"],[94031,94031,"NSM"],[94095,94098,"NSM"],[94178,94178,"ON"],[94180,94180,"NSM"],[113821,113822,"NSM"],[113824,113827,"BN"],[117760,117973,"ON"],[118e3,118009,"EN"],[118010,118012,"ON"],[118016,118451,"ON"],[118458,118480,"ON"],[118496,118512,"ON"],[118528,118573,"NSM"],[118576,118598,"NSM"],[119143,119145,"NSM"],[119155,119162,"BN"],[119163,119170,"NSM"],[119173,119179,"NSM"],[119210,119213,"NSM"],[119273,119274,"ON"],[119296,119361,"ON"],[119362,119364,"NSM"],[119365,119365,"ON"],[119552,119638,"ON"],[120513,120513,"ON"],[120539,120539,"ON"],[120571,120571,"ON"],[120597,120597,"ON"],[120629,120629,"ON"],[120655,120655,"ON"],[120687,120687,"ON"],[120713,120713,"ON"],[120745,120745,"ON"],[120771,120771,"ON"],[120782,120831,"EN"],[121344,121398,"NSM"],[121403,121452,"NSM"],[121461,121461,"NSM"],[121476,121476,"NSM"],[121499,121503,"NSM"],[121505,121519,"NSM"],[122880,122886,"NSM"],[122888,122904,"NSM"],[122907,122913,"NSM"],[122915,122916,"NSM"],[122918,122922,"NSM"],[123023,123023,"NSM"],[123184,123190,"NSM"],[123566,123566,"NSM"],[123628,123631,"NSM"],[123647,123647,"ET"],[124140,124143,"NSM"],[124398,124399,"NSM"],[124643,124643,"NSM"],[124646,124646,"NSM"],[124654,124655,"NSM"],[124661,124661,"NSM"],[124928,125135,"R"],[125136,125142,"NSM"],[125143,125251,"R"],[125252,125258,"NSM"],[125259,126063,"R"],[126064,126143,"AL"],[126144,126207,"R"],[126208,126287,"AL"],[126288,126463,"R"],[126464,126703,"AL"],[126704,126705,"ON"],[126706,126719,"AL"],[126720,126975,"R"],[126976,127019,"ON"],[127024,127123,"ON"],[127136,127150,"ON"],[127153,127167,"ON"],[127169,127183,"ON"],[127185,127221,"ON"],[127232,127242,"EN"],[127243,127247,"ON"],[127279,127279,"ON"],[127338,127343,"ON"],[127405,127405,"ON"],[127584,127589,"ON"],[127744,128728,"ON"],[128732,128748,"ON"],[128752,128764,"ON"],[128768,128985,"ON"],[128992,129003,"ON"],[129008,129008,"ON"],[129024,129035,"ON"],[129040,129095,"ON"],[129104,129113,"ON"],[129120,129159,"ON"],[129168,129197,"ON"],[129200,129211,"ON"],[129216,129217,"ON"],[129232,129240,"ON"],[129280,129623,"ON"],[129632,129645,"ON"],[129648,129660,"ON"],[129664,129674,"ON"],[129678,129734,"ON"],[129736,129736,"ON"],[129741,129756,"ON"],[129759,129770,"ON"],[129775,129784,"ON"],[129792,129938,"ON"],[129940,130031,"ON"],[130032,130041,"EN"],[130042,130042,"ON"],[131070,131071,"BN"],[196606,196607,"BN"],[262142,262143,"BN"],[327678,327679,"BN"],[393214,393215,"BN"],[458750,458751,"BN"],[524286,524287,"BN"],[589822,589823,"BN"],[655358,655359,"BN"],[720894,720895,"BN"],[786430,786431,"BN"],[851966,851967,"BN"],[917502,917759,"BN"],[917760,917999,"NSM"],[918e3,921599,"BN"],[983038,983039,"BN"],[1048574,1048575,"BN"],[1114110,1114111,"BN"]];function SS(t){if(t<=255)return B1[t];let e=0,n=Ir.length-1;for(;e<=n;){let l=e+n>>1,i=Ir[l];if(ti[1]){e=l+1;continue}return i[2]}return"L"}function yS(t){let e=t.length;if(e===0)return null;let n=new Array(e),l=!1,i=0,a=null;for(let u=0;u=55296&&s<=56319&&u+1=56320&&m<=57343&&(c=(s-55296<<10)+(m-56320)+65536,r=2)}let f=SS(c);(f==="R"||f==="AL"||f==="AN")&&(l=!0);for(let m=0;m=n&&t[r]==="ET";r--)t[r]="EN";for(r=c+1;rn?t[c-1]:u,m=r0&&e.charCodeAt(e.length-1)===32&&(e=e.slice(0,-1)),e}function ES(t){return/[\r\f]/.test(t)?t.replace(/\r\n/g,` `).replace(/[\r\f]/g,` `):t}var Pr=null;function Dn(){return Pr===null&&(Pr=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Pr}var to=null,NS;function MS(){return to===null&&(to=new Intl.Segmenter(NS,{granularity:"word"})),to}var CS=/\p{Script=Arabic}/u,We=/\p{M}/u,oa=/\p{Nd}/u;function O1(t){return CS.test(t)}var FS=/[\u3000-\u30FF\u3130-\u318F\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF\u{20000}-\u{2A6DF}\u{2A700}-\u{2EE5D}\u{2F800}-\u{2FA1F}\u{30000}-\u{33479}]/u;function jt(t){return FS.test(t)}function DS(t){let e=fa(t);return e!==null&&(io.has(e)||tl.has(e))}var BS=new Set(["\xA0","\u202F","\u2060","\uFEFF"]),kS=new Set(["-","\u2010","\u2013","\u2014"]);function TS(t){let e=fa(t);return e!==null&&BS.has(e)}function OS(t){let e=fa(t);return e!==null&&kS.has(e)}function q1(t,e){return TS(t)?!1:e?!(DS(t)||OS(t)):!0}var io=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011","\u3017","\u3019","\u301B","\u30FC","\u3005","\u303B","\u309D","\u309E","\u30FD","\u30FE"]),$u=new Set(['"',"(","[","{","\xA1","\xBF","\u201C","\u2018","\u201A","\u201E","\xAB","\u2039","\u2E18","\uFF08","\u3014","\u3008","\u300A","\u300C","\u300E","\u3010","\u3016","\u3018","\u301A"]),ao=new Set(["'","\u2019"]),tl=new Set([".",",","!","?",":",";","\u060C","\u061B","\u061F","\u0964","\u0965","\u104A","\u104B","\u104C","\u104D","\u104F",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]),RS=new Set([":",".","\u060C","\u061B"]),zS=new Set(["\u104F"]),wS=new Set(["\u201D","\u2019","\xBB","\u203A","\u300D","\u300F","\u3011","\u300B","\u3009","\u3015","\uFF09"]);function _S(t){if(uo(t))return!0;let e=!1;for(let n of t){if(tl.has(n)||el(n)){e=!0;continue}if(!(e&&We.test(n)))return!1}return e}function LS(t){for(let e of t)if(!io.has(e)&&!tl.has(e))return!1;return t.length>0}function qS(t){if(uo(t))return!0;for(let e of t)if(!$u.has(e)&&!ao.has(e)&&!We.test(e)&&!el(e))return!1;return t.length>0}function uo(t){let e=!1;for(let n of t)if(!(n==="\\"||We.test(n))){if($u.has(n)||tl.has(n)||ao.has(n)){e=!0;continue}return!1}return e}function Wl(t,e){let n=e-1;if(n<=0)return Math.max(n,0);let l=t.charCodeAt(n);if(l<56320||l>57343)return n;let i=n-1;if(i<0)return n;let a=t.charCodeAt(i);return a>=55296&&a<=56319?i:n}function fa(t){if(t.length===0)return null;let e=Wl(t,t.length);return t.slice(e)}function US(t){for(let e of t)if(!We.test(e))return e;return null}function so(t,e=t.length){for(;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(!We.test(l))return l;e=n}return null}var HS=[36,37,43,43,92,92,162,165,176,177,1423,1423,1545,1547,1642,1642,2046,2047,2546,2547,2553,2555,2801,2801,3065,3065,3449,3449,3647,3647,6107,6107,8240,8247,8279,8279,8352,8399,8451,8451,8457,8457,8470,8470,8722,8723,43064,43064,65020,65020,65129,65130,65284,65285,65504,65505,65509,65510,73693,73696,123647,123647,126124,126124,126128,126128];function GS(t,e){for(let n=0;n=e[n]&&t<=e[n+1])return!0;return!1}function el(t){let e=t.codePointAt(0);return e!==void 0&&GS(e,HS)}function YS(t){let e=so(t);return e!==null&&el(e)}function jS(t){let e=US(t);return e!==null&&oa.test(e)}function QS(t){let e=t.length;for(;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(We.test(l)||$u.has(l)||ao.has(l)){e=n;continue}break}return e<=0||e===t.length?null:{head:t.slice(0,e),tail:t.slice(e)}}function XS(t,e,n){return n==="text"&&!e&&t.length===1&&t!=="-"&&t!=="\u2014"?t:null}function R1(t,e){return t&&e!==null&&RS.has(e)}function ZS(t){let e=fa(t);return e!==null&&zS.has(e)}function VS(t){if(t.length<2||t[0]!==" ")return null;let e=t.slice(1);return/^\p{M}+$/u.test(e)?{space:" ",marks:e}:null}function no(t){let e=t.length;for(;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(wS.has(l))return!0;if(!tl.has(l))return!1;e=n}return!1}function KS(t,e){if(e==="pre-wrap"){if(t===" ")return"preserved-space";if(t===" ")return"tab";if(t===` -`)return"hard-break"}return t===" "?"space":t==="\xA0"||t==="\u202F"||t==="\u2060"||t==="\uFEFF"?"glue":t==="\u200B"?"zero-width-break":t==="\xAD"?"soft-hyphen":"text"}var JS=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function Fn(t){return t.length===1?t[0]:t.join("")}function z1(t,e){let n=[];for(let l=t.length-1;l>=0;l--)n.push(t[l]);return n.push(e),Fn(n)}function WS(t,e,n,l){if(!JS.test(t))return[{text:t,isWordLike:e,kind:"text",start:n}];let i=[],a=null,u=0,s=!1,c=0;for(let r of t){let f=KS(r,l),m=f==="text"&&e;if(a!==null&&f===a&&m===s){c+=r.length;continue}a!==null&&i.push({text:t.slice(u,c),isWordLike:s,kind:a,start:n+u}),a=f,u=c,s=m,c+=r.length}return a!==null&&i.push({text:t.slice(u),isWordLike:s,kind:a,start:n+u}),i}function eo(t){return t==="space"||t==="preserved-space"||t==="zero-width-break"||t==="hard-break"}var $S=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function w1(t,e){let n=t.texts[e];return n.startsWith("www.")?!0:$S.test(n)&&e+1=t.len||eo(t.kinds[x]))continue;let g=[],y=o<0?t.starts[x]:o,N=x;for(;N0&&(l.push(Fn(g)),i.push(!0),a.push("text"),u.push(y),s=N-1)}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}var ty=new Set([":","-","/","\xD7",",",".","+","\u2013","\u2014"]),ey=/[\p{P}\p{S}\p{Co}]/u,U1=/\p{Emoji_Presentation}/u,ny=new Set(["?","\u058A","-","\u2010","\u2012","\u2013","\u2014","\u2026","\u203C","\u203D","\u2049"]);function ly(t){return t>=33&&t<=47&&t!==45||t>=58&&t<=64&&t!==63||t>=91&&t<=96||t>=123&&t<=126}function H1(t){let e=t.charCodeAt(0);return e<128?ly(e):!ny.has(t)&&!U1.test(t)&&ey.test(t)}function _1(t){let e=!1;for(let n of t)if(!We.test(n)){if(!H1(n))return!1;e=!0}return e}function iy(t){for(let e=t.length;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(We.test(l)){e=n;continue}return H1(l)||el(l)}return!1}var lo=/[A-Za-z#&*<=>@^_`~]/;function G1(t,e){return t.charCodeAt(0)<128&&e.charCodeAt(0)<128}function Je(t,e,n){if(!n.geckoAsciiLineBreaks||e<=0||e>=t.length)return null;let l=so(t,e),i=String.fromCodePoint(t.codePointAt(e));if(l===null||!G1(l,i))return null;let a=el(l),u=el(i);return!a&&!u?null:!!(i===")"||i==="]"||i==="}"||"!,.:;?/".includes(i)||"([{".includes(l)||l==='"'||l==="'"||i==='"'||i==="'"||i==="|"||i==="-"||a&&lo.test(i)||lo.test(l)&&u||u&&(")]}".includes(l)||/[0-9]/.test(l))||a&&("([{".includes(i)||/[0-9]/.test(i)))}function Wu(t,e,n,l=t.length){let i=e[0];if(i===void 0||!"([{".includes(i))return null;let a=so(t,l);return a===null?null:n.geckoAsciiLineBreaks&&G1(a,i)?lo.test(a)||oa.test(a)||`"'([{`.includes(a)||el(a):a.charCodeAt(0)>=128?!jt(a)&&/[\p{L}\p{N}]/u.test(a)?!0:null:/[A-Za-z0-9]/.test(a)||"$'(/<@[^_`{".includes(a)}function ay(t,e,n,l,i){if(n[0]==="-"&&jt(t))return!0;if(jt(t)||jt(n))return!1;let a=Wu(t,n,i);if(a!==null)return a;let u=!e&&_1(t),s=!l&&_1(n),c=YS(t),r=(e||c)&&iy(t);return!u&&!s&&!r?!1:(e||u||c)&&(l||s)}function L1(t){for(let e of t)if(oa.test(e))return!0;return!1}function ra(t){if(t.length===0)return!1;for(let e of t)if(!(oa.test(e)||ty.has(e)))return!1;return!0}function uy(t,e,n){let l=[],i=[],a=[],u=[];function s(c,r){if(c.includes("-")){let f=c.split("-"),m=f.length>1;for(let o=0;os+1){l.push(Fn(m)),i.push(x),a.push("text"),u.push(t.starts[s]),s=o;continue}}l.push(c),i.push(f),a.push(r),u.push(t.starts[s]),s++}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function cy(t){let e=[],n=[],l=[],i=[],a=0;for(;a=0;v--){let A=a[v];if(A.length===0)continue;let B=M?.at(-1)??(S>=0?a[S]:null);if(s[v]==="text"&&!u[v]&&B!==null&&s[S]==="text"&&((Je(t,c[v]+A.length,e)??(qS(A)&&Wu(A,B,e)!==!1))||A==="-"&&jS(B))){M===null&&(M=[]),M.push(A),c[S]=c[v],a[v]="";continue}M!==null&&(a[S]=z1(M,a[S]),M=null),S=v}M!==null&&(a[S]=z1(M,a[S]));let F=0;for(let v=0;v=0&&(!q1(e.texts[o-1],n.breakKeepAllAfterPunctuation)||Je(t,e.starts[o],n)===!1)&&m(o),s<0&&(s=o),c=c||jt(x);continue}m(o),l.push(x),i.push(e.isWordLike[o]),a.push(g),u.push(e.starts[o])}return m(e.len),{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function Y1(t,e){let n=t.charCodeAt(e+1);if(n<128){if(n<48||n>57)return!1}else{let l=t.codePointAt(e+1);if(l===void 0||!oa.test(String.fromCodePoint(l)))return!1}for(let l=e;l>0;){let i=Wl(t,l),a=t.slice(i,l);if(!We.test(a))return jt(a)||!/[\p{L}\p{N}]/u.test(a);l=i}return!0}function dy(t,e){let n=[],l=0,i=0,a=!1,u=!1,s=!1,c=!1,r=!1;function f(){i!==l&&(n.push({text:t.slice(l,i),start:l,overflow:a?c?"grapheme":"none":"word-like"}),l=i,a=!1,u=!1,s=!1,c=!1,r=!1)}function m(x,g,y){l=g,i=g+x.length,a=y,c=x==="-",u=no(x),s=$u.has(x)}function o(x,g){i+=x.length,a=a||g,c=c||x==="-";let y=no(x);x.length===1&&tl.has(x)?u=u||y:u=y,s=!1}for(let x of Dn().segment(t)){let g=x.segment,y=jt(g);if(i===l){m(g,x.index,y);continue}let N=g==="-"&&a;if(N&&Y1(t,x.index)&&(r=!0),s||io.has(g)||tl.has(g)||N||r&&!y||e.carryCJKAfterClosingQuote&&y&&u){o(g,y);continue}if(!a&&!y){o(g,y);continue}f(),m(g,x.index,y)}return f(),n}function hy(t,e,n){if(e.length<=1)return e;let l=[],i=-1,a=!1;function u(c,r){let f=e[c].start,m=r=0&&(!q1(e[c-1].text,n.breakKeepAllAfterPunctuation)||Je(t,r.start,n)===!1)&&s(c),i<0&&(i=c),a=a||jt(r.text)}return s(e.length),l}function j1(t,e,n){let l=dy(t,e);return n==="keep-all"?hy(t,l,e):l}function xy(t){return t==="-"||t==="\u058A"||t==="\u2010"||t==="\u2012"||t==="\u2013"||t==="\u2014"}function Q1(t){if(t.length===0||/\p{Cf}/u.test(t))return!1;for(let{segment:e}of Dn().segment(t)){let n=String.fromCodePoint(e.codePointAt(0));if(!/[\p{P}\p{S}]/u.test(n)||U1.test(n)||e.includes("\uFE0F")||/\p{Emoji_Modifier}/u.test(n))return!1}return!0}function X1(t){if(!/[-\u058A\u2010\u2012\u2013\u2014]/u.test(t))return null;let e=[],n=0;for(let l of Dn().segment(t)){n++;let i=l.segment==="-"&&Y1(t,l.index);xy(l.segment)&&!i&&e.push(n)}return e.length===0?null:e}function Z1(t,e,n="normal",l="normal"){let i=n==="pre-wrap"?ES(t):bS(t);if(i.length===0)return{normalized:i,len:0,texts:[],isWordLike:[],kinds:[],starts:[]};let a=oy(i,e,n),u=l==="keep-all"?fy(i,a,e):a;return{normalized:i,...u}}var $l=null,V1=new Map,Il=null,my=96,py=/\p{Emoji_Presentation}/u,gy=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u,K1=new Map;function co(){if($l!==null)return $l;if(typeof OffscreenCanvas<"u")return $l=new OffscreenCanvas(1,1).getContext("2d"),$l;if(typeof document<"u")return $l=document.createElement("canvas").getContext("2d"),$l;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function Sy(t){let e=V1.get(t);return e||(e=new Map,V1.set(t,e)),e}function $e(t,e){let n=e.get(t);return n===void 0&&(n={width:co().measureText(t).width},e.set(t,n)),n}function Pl(){if(Il!==null)return Il;if(typeof navigator>"u")return Il={geckoAsciiLineBreaks:!1,lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,breakKeepAllAfterPunctuation:!0,preferPrefixWidthsForBreakableRuns:!1},Il;let t=navigator.userAgent,n=navigator.vendor==="Apple Computer, Inc."&&t.includes("Safari/")&&!t.includes("Chrome/")&&!t.includes("Chromium/")&&!t.includes("CriOS/")&&!t.includes("FxiOS/")&&!t.includes("EdgiOS/"),l=t.includes("Chrome/")||t.includes("Chromium/")||t.includes("CriOS/")||t.includes("Edg/");return Il={geckoAsciiLineBreaks:t.includes("Firefox/")&&!t.includes("FxiOS/"),lineFitEpsilon:n?1/64:.005,carryCJKAfterClosingQuote:l,breakKeepAllAfterPunctuation:!n,preferPrefixWidthsForBreakableRuns:n},Il}function yy(t){let e=t.match(/(?:^|\D)(\d+(?:\.\d+)?)\s*px/);return e?parseFloat(e[1]):16}function vy(t){return py.test(t)||t.includes("\uFE0F")}function J1(t){return gy.test(t)}function Ay(t){let e=K1.get(t);if(e!==void 0)return e;let n=yy(t),l=co();l.font=t;let i=l.measureText("\u{1F600}").width;if(e=0,i>n+.5&&typeof document<"u"&&document.body!==null){let a=document.createElement("span");a.style.font=t,a.style.display="inline-block",a.style.visibility="hidden",a.style.position="absolute",a.textContent="\u{1F600}",document.body.appendChild(a);let u=a.getBoundingClientRect().width;document.body.removeChild(a),i-u>.5&&(e=i-u)}return K1.set(t,e),e}function by(t){let e=0,n=Dn();for(let l of n.segment(t))vy(l.segment)&&e++;return e}function Ey(t,e){return e.emojiCount===void 0&&(e.emojiCount=by(t)),e.emojiCount}function Bn(t,e,n){return n===0?e.width:e.width-Ey(t,e)*n}function W1(t,e,n,l,i){if(e.breakableFitAdvances!==void 0&&e.breakableFitMode===i)return e.breakableFitAdvances;e.breakableFitMode=i;let a=Dn(),u=[];for(let f of a.segment(t))u.push(f.segment);if(u.length<=1)return e.breakableFitAdvances=null,e.breakableFitAdvances;if(i==="sum-graphemes"){let f=[];for(let m of u){let o=$e(m,n);f.push(Bn(m,o,l))}return e.breakableFitAdvances=f,e.breakableFitAdvances}if(i==="pair-context"||u.length>my){let f=[],m=null,o=0;for(let x of u){let g=$e(x,n),y=Bn(x,g,l);if(m===null)f.push(y);else{let N=m+x,h=$e(N,n);f.push(Bn(N,h,l)-o)}m=x,o=y}return e.breakableFitAdvances=f,e.breakableFitAdvances}let s=[],c="",r=0;for(let f of u){c+=f;let m=$e(c,n),o=Bn(c,m,l);s.push(o-r),r=o}return e.breakableFitAdvances=s,e.breakableFitAdvances}function $1(t,e){let n=co();n.font=t;let l=Sy(t),i=e?Ay(t):0;return{cache:l,emojiCorrection:i}}function Ny(t,e,n){return n===0&&e>0&&e0?t.letterSpacing:0}function oo(t,e){return e===0?0:t+e}function Dy(t,e){return t.letterSpacing!==0&&t.spacingGraphemeCounts[e]>0?t.letterSpacing:0}function By(t,e,n,l,i){let a=e==="tab"?i+Dy(t,n):t.lineEndFitAdvances[n];return oo(l,a)}function I1(t,e,n,l){let i=e==="tab"?0:t.lineEndFitAdvances[n];return oo(l,i)}function P1(t,e,n,l,i){let a=e==="tab"?i:t.lineEndPaintAdvances[n];return oo(l,a)}function ky(t,e,n){return t.letterSpacing!==0&&e?n+t.letterSpacing:n}function Ty(t,e){return t.letterSpacing===0?e:e+t.letterSpacing}function ro(t,e,n){let l=e;if(l>=t.length||t[l]>=n)return l;let i=t.length;for(l++;l0)return t.spacingGraphemeCounts[l]>0?t.letterSpacing:0;if(Ny(t.kinds,l,i))return 0;for(let a=l-1;a>=e;a--){let u=t.kinds[a];if(!(u==="space"||u==="zero-width-break"||u==="hard-break"||u==="soft-hyphen"))return a===e&&n>0||t.spacingGraphemeCounts[a]>0?t.letterSpacing:0}return 0}function Ry(t,e,n,l,i,a){return e+Oy(t,n,l,i,a)}function zy(t,e){let n=0,l=t.chunks.length;for(;n0)return e;for(let i=e;i=t.widths.length)return-1;l=a.consumedEndSegmentIndex,n.segmentIndex=l,n.graphemeIndex=0}return-1}function lx(t,e){if(e.segmentIndex>=t.widths.length)return-1;let n=zy(t,e.segmentIndex);return n<0?-1:nx(t,n,e)}function wy(t,e,n){if(n.segmentIndex>=t.widths.length)return-1;let l=e;for(;l=t.chunks[l].consumedEndSegmentIndex;)l++;return l>=t.chunks.length?-1:nx(t,l,n)}function ix(t,e){return ax(t,e)}function _y(t,e,n){let{widths:l,kinds:i,breakableFitAdvances:a,breakablePreferredBreaks:u}=t;if(l.length===0)return 0;let c=Pl().lineFitEpsilon,r=e+c,f=0,m=0,o=!1,x=0,g=0,y=0,N=0,h=-1,d=0;function p(){h=-1,d=0}function S(A=y,B=N,L=m){f++,n?.(L,x,g,A,B),m=0,o=!1,p()}function M(A,B){o=!0,x=A,g=0,y=A+1,N=0,m=B}function F(A,B,L){o=!0,x=A,g=B,y=A,N=B+1,m=L}function C(A,B){if(!o){M(A,B);return}m+=B,y=A+1,N=0}function E(A,B){let L=a[A],_=u[A]??null,et=_===null?-1:ro(_,0,B+1),Z=-1,rt=0,k=B;for(;kr){if(_!==null&&Z>B){S(A,Z,rt),k=Z,et=ro(_,et,k+1),Z=-1,rt=0;continue}S(),F(A,k,R)}else m+=R,y=A,N=k+1;let O=k+1;_!==null&&_[et]===O&&(Z=O,rt=m,et++),k++}o&&y===A&&N===L.length&&(y=A+1,N=0)}let v=0;for(;v=l.length));){let A=l[v],B=i[v],L=tx(B);if(!o){A>r&&a[v]!==null?E(v,0):M(v,A),L&&(h=v+1,d=m-A),v++;continue}if(m+A>r){if(L){C(v,A),S(v+1,0,m-A),v++;continue}if(h>=0){if(y>h||y===h&&N>0){S();continue}S(h,0,d);continue}if(A>r&&a[v]!==null){S(),E(v,0),v++;continue}S();continue}C(v,A),L&&(h=v+1,d=m-A),v++}return o&&S(),f}function ax(t,e,n){if(t.simpleLineWalkFastPath)return _y(t,e,n);let l={segmentIndex:0,graphemeIndex:0},i=lx(t,l);return Ly(t,l,i,e,n).lineCount}function Ly(t,e,n,l,i,a=Number.POSITIVE_INFINITY){let{widths:u,kinds:s,breakableFitAdvances:c,breakablePreferredBreaks:r,discretionaryHyphenWidth:f}=t,o=Pl().lineFitEpsilon,x=l+o,g,y,N,h,d,p,S,M,F,C;function E(){return C==="soft-hyphen"&&S===d&&p===0?F:N}function v(k=d,R=p,O=E()){return h?(e.segmentIndex=k,e.graphemeIndex=R,Ry(t,O,g,y,k,R)):null}function A(k,R){h=!0,d=k+1,p=0,N=R}function B(k,R,O){h=!0,d=k,p=R+1,N=O}function L(k,R){if(!h){A(k,R);return}N+=R,d=k+1,p=0}function _(k,R,O,J,zt,Xt){if(!R)return;let wt=I1(t,k,O,zt),Bt=P1(t,k,O,zt,J);S=O+1,M=N-Xt+wt,F=N-Xt+Bt,C=k}function et(k,R){let O=c[k],J=r[k]??null,zt=J===null?-1:ro(J,0,R+1),Xt=-1,wt=0;for(let Bt=R;Btx)return J!==null&&Xt>R?v(k,Xt,wt):v();N=Se,d=k,p=Bt+1}let li=Bt+1;J!==null&&J[zt]===li&&(Xt=li,wt=N,zt++)}return h&&d===k&&p===O.length&&(d=k+1,p=0),null}let Z=0,rt=null;for(;n>=0&&Z0){let Se=et(O,Xt);if(Se!==null){R=Se;break t}}else if(li>x&&c[O]!==null){let Se=et(O,0);if(Se!==null){R=Se;break t}}else A(O,Bt);_(J,zt,O,Bt,wt,kn);continue}if(N+li>x){let Se=N+I1(t,J,O,wt),kx=N+P1(t,J,O,wt,Bt);if(zt&&Se<=x){L(O,kn),R=v(O+1,0,kx);break t}if(S>=0&&M<=x){if(d>S||d===S&&p>0){R=v();break t}R=v(S,0,F);break t}R=v();break t}L(O,kn),_(J,zt,O,Bt,wt,kn)}R===null&&(R=S===k.consumedEndSegmentIndex&&p===0?v(k.consumedEndSegmentIndex,0,F):v(k.consumedEndSegmentIndex,0,N))}if(R===null)break;rt=R,Z++,i?.(R,g,y,e.segmentIndex,e.graphemeIndex),Z1?t+(e-1)*n:t}function Hy(t,e,n,l,i){let a=Pl(),{cache:u,emojiCorrection:s}=$1(e,J1(t.normalized)),c=Bn("-",$e("-",u),s)+(i===0?0:i*2),f=Bn(" ",$e(" ",u),s)*8,m=i!==0;if(t.len===0)return qy(n);let o=[],x=[],g=[],y=[],N=!m,h=n?[]:null,d=[],p=[],S=[],M=n?[]:null,F=[],C=0;function E(B,L,_,et,Z,rt,k,R,O){Z!=="text"&&Z!=="space"&&Z!=="zero-width-break"&&(N=!1),o.push(L),x.push(_),g.push(et),y.push(Z),h?.push(rt),d.push(k),p.push(R),m&&S.push(O),M!==null&&M.push(B)}function v(B,L,_,et,Z){let rt=m?ux(B,_):0,k=Uy(Bn(B,L,s),rt,i),R=_==="space"||_==="preserved-space"||_==="zero-width-break"?0:k,O=R===0?0:R+(rt>0?i:0),J=_==="space"||_==="zero-width-break"?0:k;if(Z&&B.length>1){let zt="sum-graphemes";i!==0?zt="segment-prefixes":ra(B)?zt="pair-context":a.preferPrefixWidthsForBreakableRuns&&(zt="segment-prefixes");let Xt=W1(B,L,u,s,zt),wt=Xt===null||l==="keep-all"?null:X1(B);E(B,k,O,J,_,et,Xt,wt,rt);return}E(B,k,O,J,_,et,null,null,rt)}for(let B=0;B[u.id,u])),l=[],i=[];for(let u of e){let s=t.get(u.id);s?s.version!==u.version&&i.push(u):l.push(u)}let a=[...t.keys()].filter(u=>!n.has(u));return{added:l,updated:i,removed:a}}function ho(t,e){let n=Math.max(1,Math.ceil((t.text?.length??0)/Math.max(24,Math.floor(e/8))));return t.kind==="activity"?Math.max(46,24+(t.items?.length??0)*20):t.kind==="turnSummary"||t.kind==="notice"||t.kind==="typing"?32:24+n*ox}function Yy(t,e,n){if(!t.text)return ho(t,e);let i=n.get(t.id)??{version:t.version,text:t.text,prepared:null,blocks:new Map};if(i.version=t.version,i.text=t.text,!i.blocks.size)try{i.prepared=fo(t.text,cx,{whiteSpace:"pre-wrap"})}catch{i.prepared=null}n.set(t.id,i);let a=Math.max(80,e-(t.kind==="user"?120:0)),u=t.text.split(/\n{2,}/).filter(Boolean);if(u.length===0)return ho(t,e);let s=0;for(let c of u){let r=i.blocks.get(c);if(!r)try{r=fo(c,cx,{whiteSpace:"pre-wrap"}),i.blocks.set(c,r)}catch{return ho(t,e)}s+=sx(r,a,ox).height}return Math.max(34,16+s+Math.max(0,u.length-1)*8)}function dx(t,e,n=new Map,l){let i=new Float64Array(t.length),a=new Float64Array(t.length),u=0;for(let s=0;s0?c:Yy(t[s],e,n);a[s]=r,u+=r}return{tops:i,heights:a,totalHeight:u}}function rx(t,e){let n=0,l=t.length;for(;n>>1;t[i]<=e?n=i+1:l=i}return n}function hx(t,e,n,l=4){if(t.tops.length===0)return{first:0,last:0};let i=Math.max(0,rx(t.tops,Math.max(0,e))-1-l),a=Math.min(t.tops.length,rx(t.tops,e+n)+l);return{first:i,last:a}}function jy(t,e){let n=t??{},l=n?.request??n,i=n?.sessionId??l?.sessionId,a=n?.permissionId??l?.permissionId;if(!(!a||i!==e))return{permissionId:String(a),title:l.toolCall?.title,kind:l.toolCall?.kind,pending:!0,options:(l.options??[]).map(u=>({id:String(u.optionId??u.id),name:String(u.name??u.optionId),allow:String(u.kind??"").startsWith("allow")}))}}function Qy(t,e,n){let l=typeof n?.promptId=="string"?n.promptId:void 0;if(!l)return;let i=e.get(l);i&&t.delete(i),e.delete(l)}function xo(...t){let e=new Map;for(let n of t.flat())e.set(n.seq,n);return[...e.values()].sort((n,l)=>n.seq-l.seq)}function Xy(t,e,n,l){n.add(l);let i=e.get(l);i&&t.delete(i),e.delete(l)}function Zy(t,e,n){return t||(n?void 0:e[0]?.sessionId)}function xx(t){return typeof t=="string"?t:t?.type==="text"?String(t.text??""):Array.isArray(t)?t.map(xx).join(""):""}function Vy(t){return t.dir==="in"&&t.msg.method==="session/update"?t.msg.params?.update:void 0}var Iu=class t{socket;nextRequest=1;pending=new Map;events=[];rows=new Map;sessions=[];selectedSessionId;summary;catalog=[];queue=[];pendingPermission;optimisticPromptRows=new Map;optimisticPromptTexts=new Map;firstSeq;lastSeq=0;turnOpen=!1;streamingAssistant;streamingAssistantMessageId;streamingActivity;supersededMessageIds=new Set;messageRows=new Map;listener;host;reconnectTimer;reconnectDelay=250;onLost;opening=!1;hasConnected=!1;closed=!1;selectionGeneration=0;historyExhausted=!1;constructor(e,n,l){this.host=e,this.listener=n,this.onLost=l,this.selectedSessionId=e.sessionId}static async connect(e,n,l){let i=new t(e,n,l);return await i.open(),i}async open(){if(this.opening||this.closed)return;this.opening=!0;let e=new URL(this.host.endpoint);e.searchParams.set("token",this.host.token),await new Promise((n,l)=>{let i=new WebSocket(e);this.socket=i;let a=!1;i.onopen=()=>{a=!0,n()},i.onerror=()=>{this.opening=!1,l(new Error("Unable to connect to acpmux WebSocket"))},i.onclose=()=>{if(this.socket===i){if(!a){this.opening=!1,l(new Error("acpmux WebSocket closed before connect"));return}for(let u of this.pending.values())u.reject(new Error("acpmux WebSocket closed"));if(this.pending.clear(),this.emit("disconnected"),!(!this.hasConnected||this.closed))if(this.onLost){let u=this.onLost;this.close(),u()}else this.scheduleReconnect()}},i.onmessage=u=>this.receive(String(u.data))});try{await this.request("initialize",{protocolVersion:1,clientInfo:{name:"cmux-react-agent-pane",version:"1"},clientCapabilities:{}});let n=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(n?.sessions??[]).filter(i=>i.sessionId);let l=await this.request("_acpmux/harnesses",{});this.catalog=Ky(l),this.selectedSessionId&&!this.sessions.some(i=>i.sessionId===this.selectedSessionId)&&(this.selectedSessionId=this.sessions[0]?.sessionId,this.resetSessionState()),this.selectedSessionId=Zy(this.selectedSessionId,this.sessions,this.host.newSession),this.selectedSessionId&&await this.attach(this.selectedSessionId),this.hasConnected=!0,this.reconnectDelay=250,this.emit("connected")}catch(n){throw this.socket?.close(),n}finally{this.opening=!1}}resetSessionState(){this.events=[],this.historyExhausted=!1,this.rows.clear(),this.firstSeq=void 0,this.lastSeq=0,this.summary=void 0,this.queue=[],this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.optimisticPromptRows.clear(),this.optimisticPromptTexts.clear(),this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0}scheduleReconnect(){if(this.reconnectTimer!==void 0||this.closed)return;let e=this.reconnectDelay;this.reconnectDelay=Math.min(e*2,3e4),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=void 0,this.open().catch(()=>this.scheduleReconnect())},e)}receive(e){let n;try{n=JSON.parse(e)}catch{return}if("id"in n&&typeof n.id=="number"){let i=this.pending.get(n.id);if(!i)return;this.pending.delete(n.id),n.error?i.reject(new Error(n.error.message??"acpmux request failed")):i.resolve(n.result);return}let l=n;l.method==="_acpmux/event"?this.apply(l.params):l.method==="session/update"?this.apply({sessionId:l.params?.sessionId,seq:Number(l.params?._meta?.acpmux?.seq??0),at:Number(l.params?._meta?.acpmux?.at??Date.now()),dir:"in",kind:String(l.params?.update?.sessionUpdate??""),msg:{method:"session/update",params:{update:l.params?.update}}}):l.method==="_acpmux/session_changed"?this.sessionChanged(l.params):l.method==="_acpmux/permission_pending"?this.applyPermission(l.params):l.method==="_acpmux/lagged"&&this.resyncAfterLag(l.params)}resyncAfterLag(e){let n=String(e?.sessionId??"");if(!n||n!==this.selectedSessionId)return;let l=this.selectionGeneration,i=this.lastSeq;this.emit("resyncing"),this.request("_acpmux/events",{sessionId:n,afterSeq:i,limit:5e3}).then(a=>{l!==this.selectionGeneration||this.selectedSessionId!==n||(this.events=xo(this.events,a?.events??[]),this.rebuild(),this.emit("resynced"))}).catch(()=>{})}request(e,n){if(this.socket?.readyState!==WebSocket.OPEN)return Promise.reject(new Error("acpmux WebSocket is not open"));let l=this.nextRequest++;return new Promise((i,a)=>{this.pending.set(l,{resolve:i,reject:a}),this.socket.send(JSON.stringify({jsonrpc:"2.0",id:l,method:e,params:n}))})}async attach(e,n=this.selectionGeneration){if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let l=await this.request("_acpmux/attach",{sessionId:e,limit:400,kinds:["transcript"],eventStream:!0});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=l?.session??{};this.summary=i,this.queue=(i.queue??[]).map(a=>({id:String(a.promptId),prompt:String(a.prompt??"")})),this.events=xo(l?.events??[],this.events),this.rebuild(),this.emit("attached")}sessionChanged(e){let n=e?.session;if(e?.kind==="purged"&&n?.sessionId){if(this.sessions=this.sessions.filter(l=>l.sessionId!==n.sessionId),n.sessionId===this.selectedSessionId){this.selectedSessionId=this.sessions[0]?.sessionId;let l=++this.selectionGeneration;this.resetSessionState(),this.emit("session purged"),this.selectedSessionId&&this.attach(this.selectedSessionId,l).catch(()=>{})}else this.emit("session purged");return}n?.sessionId&&(this.sessions=[...this.sessions.filter(l=>l.sessionId!==n.sessionId),n],n.sessionId===this.selectedSessionId&&(this.summary={...this.summary,...n},this.queue=(n.queue??this.queue).map(l=>({id:String(l.promptId),prompt:String(l.prompt??l.preview??"")}))),this.emit("session changed"))}applyPermission(e){let n=jy(e,this.selectedSessionId??"");n&&(this.pendingPermission=n,this.emit("permission"))}apply(e){!e?.seq||e.sessionId!==this.selectedSessionId||e.seq<=this.lastSeq||(this.events.push(e),this.lastSeq=e.seq,this.firstSeq=this.firstSeq===void 0?e.seq:Math.min(this.firstSeq,e.seq),this.reduce(e),this.emit(e.kind))}rebuild(){let e=[...this.optimisticPromptRows.values()].flatMap(l=>this.rows.get(l)??[]);this.rows.clear();for(let l of e)this.rows.set(l.id,l);this.firstSeq=void 0,this.lastSeq=0,this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0;let n=[...this.events].sort((l,i)=>l.seq-i.seq);for(let l of n)this.lastSeq=Math.max(this.lastSeq,l.seq),this.firstSeq=this.firstSeq===void 0?l.seq:Math.min(this.firstSeq,l.seq),this.reduce(l)}reduce(e){let n=e.msg??{},l=Vy(e);if(e.dir==="mux"){if(e.kind==="user_message"){let a=typeof n.promptId=="string"?n.promptId:void 0,u=typeof n.text=="string"?n.text:void 0,s=a??(u?[...this.optimisticPromptTexts.entries()].find(([,c])=>c===u)?.[0]:void 0);Qy(this.rows,this.optimisticPromptRows,{...n,promptId:s}),s&&this.optimisticPromptTexts.delete(s),this.rows.set(`user-${e.seq}`,{id:`user-${e.seq}`,version:1,at:e.at,kind:"user",text:String(n.text??"")}),this.turnOpen=!0}else if(e.kind==="turn_started")this.turnOpen=!0,this.rows.set("typing",{id:"typing",version:1,at:e.at,kind:"typing"});else if(e.kind==="message_superseded"){let a=typeof n.oldMessageId=="string"?n.oldMessageId:void 0;a&&(Xy(this.rows,this.messageRows,this.supersededMessageIds,a),this.streamingAssistantMessageId===a&&(this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0))}else if(e.kind==="turn_end"||e.kind==="turn_result"){if(this.turnOpen=!1,this.streamingAssistant){let a=this.rows.get(this.streamingAssistant);a&&(a.streaming=!1,a.version+=1)}this.rows.delete("typing"),e.kind==="turn_result"&&this.rows.set(`summary-${e.seq}`,{id:`summary-${e.seq}`,version:1,at:e.at,kind:"turnSummary",durationMs:void 0,toolCount:[...this.rows.values()].filter(a=>a.kind==="activity").length,status:String(n.status??"completed"),error:n.errorText}),this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0}else if(e.kind==="queued"||e.kind==="queue_updated"){let a=String(n.promptId??"");a&&(this.queue=[...this.queue.filter(u=>u.id!==a),{id:a,prompt:String(n.text??"")}])}else e.kind==="queue_removed"||e.kind==="dequeued"?this.queue=this.queue.filter(a=>a.id!==String(n.promptId??"")):e.kind==="permission_request"?this.applyPermission({...n,sessionId:e.sessionId}):e.kind==="permission_decision"?this.pendingPermission=void 0:e.kind==="status"&&(this.summary={...this.summary,status:n.status});return}if(!l)return;let i=xx(l.content);if(e.kind==="agent_message_chunk"&&i){let a=typeof l.messageId=="string"?l.messageId:void 0;if(a&&this.supersededMessageIds.has(a))return;let s=!!(this.streamingAssistant&&(!a||!this.streamingAssistantMessageId||this.streamingAssistantMessageId===a))?this.streamingAssistant:`assistant-${e.seq}`,c=this.rows.get(s);this.rows.set(s,{id:s,version:(c?.version??0)+1,at:e.at,kind:"assistant",text:`${c?.text??""}${i}`,streaming:!0}),this.streamingAssistant=s,this.streamingAssistantMessageId=a,a&&this.messageRows.set(a,s),this.rows.delete("typing")}else if(e.kind==="agent_thought_chunk"&&i){let a=this.streamingActivity??`activity-${e.seq}`,u=this.rows.get(a);this.rows.set(a,{id:a,version:(u?.version??0)+1,at:e.at,kind:"activity",toolCount:u?.toolCount??0,items:[...u?.items??[],{kind:"thought",text:i}]}),this.streamingActivity=a}else if(e.kind==="tool_call"||e.kind==="tool_call_update"){let a=String(l.toolCallId??`tool-${e.seq}`),u=this.streamingActivity??`activity-${e.seq}`,s=this.rows.get(u),c=[...s?.items??[]],r=c.findIndex(m=>m.tool?.id===a),f={kind:"tool",text:String(l.title??l.name??a),tool:{id:a,title:String(l.title??a),kind:l.kind,status:String(l.status??"in_progress"),inputSummary:l.rawInput?JSON.stringify(l.rawInput):void 0,output:i||void 0}};r>=0?c[r]=f:c.push(f),this.rows.set(u,{id:u,version:(s?.version??0)+1,at:e.at,kind:"activity",toolCount:c.filter(m=>m.kind==="tool").length,items:c}),this.streamingActivity=u}else e.kind==="plan"&&this.rows.set(`plan-${e.seq}`,{id:`plan-${e.seq}`,version:1,at:e.at,kind:"plan",text:i||JSON.stringify(l.entries??l.content??"")})}emit(e="connected"){let n=this.summary,l=(n?.configOptions??[]).find(i=>i.category==="thought_level"||i.id==="reasoning_effort");this.listener({type:"snapshot",protocolVersion:1,rows:[...this.rows.values()].sort((i,a)=>i.at-a.at),sessions:this.sessions.map(i=>({sessionId:i.sessionId,displayTitle:i.title??i.name,title:i.title,name:i.name,status:i.status,model:i.model})),summary:n?{sessionId:n.sessionId,title:n.title,name:n.name,harness:n.harness,model:n.model,effort:l?.currentValue,status:n.status,modes:n.modes,configOptions:n.configOptions}:void 0,connection:e,sessionId:this.selectedSessionId,isWorking:this.turnOpen||n?.status==="running",queue:this.queue,permission:this.pendingPermission,catalog:this.catalog,canLoadOlder:!this.historyExhausted&&(this.firstSeq??1)>1})}snapshot(){this.emit()}async ensureSession(){return this.selectedSessionId||await this.create(),this.selectedSessionId}async send(e){let n=await this.ensureSession();if(!n)return;let l=crypto.randomUUID(),i=`local-${l}`,a=Date.now();this.optimisticPromptRows.set(l,i),this.optimisticPromptTexts.set(l,e),this.rows.set(i,{id:i,version:1,at:a,kind:"user",text:e,pending:!0}),this.emit();try{await this.request("session/prompt",{sessionId:n,prompt:[{type:"text",text:e}],_meta:{acpmux:{promptId:l}}})}catch(u){let s=this.rows.get(i);throw s&&(s.pending=!1,s.failed=!0,s.version+=1),this.optimisticPromptRows.delete(l),this.optimisticPromptTexts.delete(l),this.emit("failed"),u}return n}async cancel(){this.selectedSessionId&&this.socket?.send(JSON.stringify({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:this.selectedSessionId}}))}async permission(e,n){this.selectedSessionId&&await this.request("_acpmux/permission_respond",{sessionId:this.selectedSessionId,permissionId:e,optionId:n})}async select(e){let n=this.selectedSessionId,l=++this.selectionGeneration;return this.selectedSessionId=e,this.resetSessionState(),n&&await this.request("_acpmux/detach",{sessionId:n}),await this.attach(e,l),l===this.selectionGeneration&&this.selectedSessionId===e?e:void 0}async create(e){let n=await this.request("session/new",{mcpServers:[],_meta:{acpmux:{harness:e}}});if(n?.sessionId)return this.select(String(n.sessionId))}async setModel(e){this.selectedSessionId&&await this.request("session/set_model",{sessionId:this.selectedSessionId,modelId:e})}async setMode(e){this.selectedSessionId&&await this.request("session/set_mode",{sessionId:this.selectedSessionId,modeId:e})}async setConfig(e,n){this.selectedSessionId&&await this.request("session/set_config_option",{sessionId:this.selectedSessionId,configId:e,value:n})}async loadOlder(){if(!this.selectedSessionId||!this.firstSeq||this.firstSeq<=1||this.historyExhausted)return;let e=this.selectedSessionId,n=this.selectionGeneration,l=await this.request("_acpmux/events",{sessionId:e,beforeSeq:this.firstSeq,limit:400,kinds:["transcript"]});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=this.summary,a=this.queue,u=this.pendingPermission,s=l?.events??[];this.events=xo(s,this.events),this.rebuild(),this.summary=i,this.queue=a,this.pendingPermission=u,this.historyExhausted=l?.hasMore===!1||s.length===0||(this.firstSeq??1)<=1,this.emit("history")}close(){this.closed=!0,this.reconnectTimer!==void 0&&window.clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close(),this.socket=void 0}};function Ky(t){let e=t?.harnesses??t?.items??t??[];return(Array.isArray(e)?e:Object.entries(e).map(([n,l])=>({id:n,...l}))).map(n=>({id:String(n.id??n.name),name:String(n.name??n.id),models:(n.models??[]).map(l=>({id:String(l.id??l.modelId),name:l.name}))}))}var mo="mock-session",Jy=[{id:"claude",name:"Claude",models:[{id:"claude-sonnet",name:"Claude Sonnet"}]},{id:"codex",name:"Codex",models:[{id:"gpt-6-astra",name:"GPT-6-Astra"}]}];function Wy(t,e=!1){return{type:"snapshot",protocolVersion:1,rows:t,sessions:[{sessionId:mo,title:"Mock session"}],summary:{sessionId:mo,title:"Mock session",harness:"claude",model:"claude-sonnet"},connection:"mock",sessionId:mo,isWorking:e,queue:[],catalog:Jy,canLoadOlder:!1}}function $y(t){return`Mock reply to **${t.replace(/[*_`]/g,"")}**. No acpmux daemon is attached; this pane is running in mock mode.`}function mx(t,e=n=>{window.setTimeout(n,400)}){let n=[{id:"mock-welcome",version:1,at:Date.now(),kind:"assistant",text:"Mock agent session. Type a prompt to see the pane render a turn."}],l=0,i=(u=!1)=>t(Wy(n,u)),a=u=>{n=[...n,{id:`mock-${l++}`,version:1,at:Date.now(),...u}]};return i(),{"chat.send":async({text:u})=>{let s=String(u??"");a({kind:"user",text:s}),i(!0),e(()=>{a({kind:"assistant",text:$y(s)}),i()})},"chat.cancel":async()=>i(),"chat.permission":async()=>i(),"chat.model":async()=>{},"chat.mode":async()=>{},"chat.effort":async()=>{},"chat.select":async()=>{},"chat.new":async()=>{n=[],i()},"chat.history":async()=>{}}}function Qt(t){return Math.round(t*100)/100}function ei(t,e){return t.length===0?0:t[Math.min(t.length-1,Math.max(0,Math.round((t.length-1)*e)))]}function px(t){return ei([...t].sort((e,n)=>e-n),.5)}function Iy(t){let e=[];for(let n=1;n0))return 0;let n=0;for(let l of t)n+=Math.max(0,Math.round(l/e)-1);return n}function gx(t,e){let n=Iy(t).sort((l,i)=>l-i);return{frames:t.length,nominal_ms:Qt(e),p50_ms:Qt(ei(n,.5)),p95_ms:Qt(ei(n,.95)),p99_ms:Qt(ei(n,.99)),max_ms:Qt(n.at(-1)??0),dropped_frames:Py(n,e)}}function ti(t){let e=[...t].sort((n,l)=>n-l);return{p50_ms:Qt(ei(e,.5)),p95_ms:Qt(ei(e,.95)),max_ms:Qt(e.at(-1)??0)}}function Sx(t,e,n,l,i){let a=Math.max(0,n),u=Math.min(i,n+l);return u<=a?!1:t>a+.5||ee.frame)),to_paint:ti(t.map(e=>e.paint))}}var go=class{enabled=!1;ring=new po;layoutSinceMark=0;reactSinceMark=0;lastMark;mountedTop=0;mountedBottom=0;commitWaiters=[];typing=[];keyListener;enable(e=typeof document>"u"?void 0:document){this.enabled=!0,!(this.keyListener||!e)&&(this.keyListener=n=>{if(!n.target?.closest?.(".acpmux-composer"))return;let i=n.timeStamp;requestAnimationFrame(()=>{let a=performance.now(),u=new MessageChannel;u.port1.onmessage=()=>{this.typing.push({frame:a-i,paint:performance.now()-i}),this.typing.length>4096&&this.typing.shift(),u.port1.close()},u.port2.postMessage(0)})},e.addEventListener("keydown",this.keyListener,!0))}addLayout(e){this.layoutSinceMark+=e}commit(e,n,l,i,a){this.reactSinceMark+=Math.max(0,e-n),this.mountedTop=l,this.mountedBottom=i;let u=this.commitWaiters;this.commitWaiters=[];for(let s of u)s(a)}nextCommit(e=1e4){return new Promise(n=>{let l=setTimeout(()=>{this.commitWaiters=this.commitWaiters.filter(a=>a!==i),n(void 0)},e),i=a=>{clearTimeout(l),n(a)};this.commitWaiters.push(i)})}resetFrames(){this.ring.clear(),this.lastMark=void 0,this.layoutSinceMark=0,this.reactSinceMark=0}markFrame(e,n){this.lastMark!==void 0&&this.ring.push(e-this.lastMark,this.layoutSinceMark,this.reactSinceMark,n),this.lastMark=e,this.layoutSinceMark=0,this.reactSinceMark=0}stats(e=!1){let n=this.ring.samples(),l={frames:n.length,blank_frames:n.filter(i=>i.blank).length,interval:ti(n.map(i=>i.interval)),layout:ti(n.map(i=>i.layout)),react:ti(n.map(i=>i.react)),other:ti(n.map(i=>i.other))};return e&&(l.samples=n.map(i=>({interval_ms:Qt(i.interval),layout_ms:Qt(i.layout),react_ms:Qt(i.react),other_ms:Qt(i.other),blank:i.blank}))),l}},tt=new go;function vx(t){let e=[],n=0,l=a=>{n+=1,e.push({...a,version:1,at:n*1e3})},i=Math.max(1,Math.floor(t/3));for(let a=0;a=0;l--)n.push(t[l]);return n.push(e),Fn(n)}function WS(t,e,n,l){if(!JS.test(t))return[{text:t,isWordLike:e,kind:"text",start:n}];let i=[],a=null,u=0,s=!1,c=0;for(let r of t){let f=KS(r,l),m=f==="text"&&e;if(a!==null&&f===a&&m===s){c+=r.length;continue}a!==null&&i.push({text:t.slice(u,c),isWordLike:s,kind:a,start:n+u}),a=f,u=c,s=m,c+=r.length}return a!==null&&i.push({text:t.slice(u),isWordLike:s,kind:a,start:n+u}),i}function eo(t){return t==="space"||t==="preserved-space"||t==="zero-width-break"||t==="hard-break"}var $S=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function w1(t,e){let n=t.texts[e];return n.startsWith("www.")?!0:$S.test(n)&&e+1=t.len||eo(t.kinds[x]))continue;let g=[],y=o<0?t.starts[x]:o,N=x;for(;N0&&(l.push(Fn(g)),i.push(!0),a.push("text"),u.push(y),s=N-1)}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}var ty=new Set([":","-","/","\xD7",",",".","+","\u2013","\u2014"]),ey=/[\p{P}\p{S}\p{Co}]/u,U1=/\p{Emoji_Presentation}/u,ny=new Set(["?","\u058A","-","\u2010","\u2012","\u2013","\u2014","\u2026","\u203C","\u203D","\u2049"]);function ly(t){return t>=33&&t<=47&&t!==45||t>=58&&t<=64&&t!==63||t>=91&&t<=96||t>=123&&t<=126}function H1(t){let e=t.charCodeAt(0);return e<128?ly(e):!ny.has(t)&&!U1.test(t)&&ey.test(t)}function _1(t){let e=!1;for(let n of t)if(!We.test(n)){if(!H1(n))return!1;e=!0}return e}function iy(t){for(let e=t.length;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(We.test(l)){e=n;continue}return H1(l)||el(l)}return!1}var lo=/[A-Za-z#&*<=>@^_`~]/;function G1(t,e){return t.charCodeAt(0)<128&&e.charCodeAt(0)<128}function Je(t,e,n){if(!n.geckoAsciiLineBreaks||e<=0||e>=t.length)return null;let l=so(t,e),i=String.fromCodePoint(t.codePointAt(e));if(l===null||!G1(l,i))return null;let a=el(l),u=el(i);return!a&&!u?null:!!(i===")"||i==="]"||i==="}"||"!,.:;?/".includes(i)||"([{".includes(l)||l==='"'||l==="'"||i==='"'||i==="'"||i==="|"||i==="-"||a&&lo.test(i)||lo.test(l)&&u||u&&(")]}".includes(l)||/[0-9]/.test(l))||a&&("([{".includes(i)||/[0-9]/.test(i)))}function Wu(t,e,n,l=t.length){let i=e[0];if(i===void 0||!"([{".includes(i))return null;let a=so(t,l);return a===null?null:n.geckoAsciiLineBreaks&&G1(a,i)?lo.test(a)||oa.test(a)||`"'([{`.includes(a)||el(a):a.charCodeAt(0)>=128?!jt(a)&&/[\p{L}\p{N}]/u.test(a)?!0:null:/[A-Za-z0-9]/.test(a)||"$'(/<@[^_`{".includes(a)}function ay(t,e,n,l,i){if(n[0]==="-"&&jt(t))return!0;if(jt(t)||jt(n))return!1;let a=Wu(t,n,i);if(a!==null)return a;let u=!e&&_1(t),s=!l&&_1(n),c=YS(t),r=(e||c)&&iy(t);return!u&&!s&&!r?!1:(e||u||c)&&(l||s)}function L1(t){for(let e of t)if(oa.test(e))return!0;return!1}function ra(t){if(t.length===0)return!1;for(let e of t)if(!(oa.test(e)||ty.has(e)))return!1;return!0}function uy(t,e,n){let l=[],i=[],a=[],u=[];function s(c,r){if(c.includes("-")){let f=c.split("-"),m=f.length>1;for(let o=0;os+1){l.push(Fn(m)),i.push(x),a.push("text"),u.push(t.starts[s]),s=o;continue}}l.push(c),i.push(f),a.push(r),u.push(t.starts[s]),s++}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function cy(t){let e=[],n=[],l=[],i=[],a=0;for(;a=0;v--){let A=a[v];if(A.length===0)continue;let B=M?.at(-1)??(S>=0?a[S]:null);if(s[v]==="text"&&!u[v]&&B!==null&&s[S]==="text"&&((Je(t,c[v]+A.length,e)??(qS(A)&&Wu(A,B,e)!==!1))||A==="-"&&jS(B))){M===null&&(M=[]),M.push(A),c[S]=c[v],a[v]="";continue}M!==null&&(a[S]=z1(M,a[S]),M=null),S=v}M!==null&&(a[S]=z1(M,a[S]));let F=0;for(let v=0;v=0&&(!q1(e.texts[o-1],n.breakKeepAllAfterPunctuation)||Je(t,e.starts[o],n)===!1)&&m(o),s<0&&(s=o),c=c||jt(x);continue}m(o),l.push(x),i.push(e.isWordLike[o]),a.push(g),u.push(e.starts[o])}return m(e.len),{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function Y1(t,e){let n=t.charCodeAt(e+1);if(n<128){if(n<48||n>57)return!1}else{let l=t.codePointAt(e+1);if(l===void 0||!oa.test(String.fromCodePoint(l)))return!1}for(let l=e;l>0;){let i=Wl(t,l),a=t.slice(i,l);if(!We.test(a))return jt(a)||!/[\p{L}\p{N}]/u.test(a);l=i}return!0}function dy(t,e){let n=[],l=0,i=0,a=!1,u=!1,s=!1,c=!1,r=!1;function f(){i!==l&&(n.push({text:t.slice(l,i),start:l,overflow:a?c?"grapheme":"none":"word-like"}),l=i,a=!1,u=!1,s=!1,c=!1,r=!1)}function m(x,g,y){l=g,i=g+x.length,a=y,c=x==="-",u=no(x),s=$u.has(x)}function o(x,g){i+=x.length,a=a||g,c=c||x==="-";let y=no(x);x.length===1&&tl.has(x)?u=u||y:u=y,s=!1}for(let x of Dn().segment(t)){let g=x.segment,y=jt(g);if(i===l){m(g,x.index,y);continue}let N=g==="-"&&a;if(N&&Y1(t,x.index)&&(r=!0),s||io.has(g)||tl.has(g)||N||r&&!y||e.carryCJKAfterClosingQuote&&y&&u){o(g,y);continue}if(!a&&!y){o(g,y);continue}f(),m(g,x.index,y)}return f(),n}function hy(t,e,n){if(e.length<=1)return e;let l=[],i=-1,a=!1;function u(c,r){let f=e[c].start,m=r=0&&(!q1(e[c-1].text,n.breakKeepAllAfterPunctuation)||Je(t,r.start,n)===!1)&&s(c),i<0&&(i=c),a=a||jt(r.text)}return s(e.length),l}function j1(t,e,n){let l=dy(t,e);return n==="keep-all"?hy(t,l,e):l}function xy(t){return t==="-"||t==="\u058A"||t==="\u2010"||t==="\u2012"||t==="\u2013"||t==="\u2014"}function Q1(t){if(t.length===0||/\p{Cf}/u.test(t))return!1;for(let{segment:e}of Dn().segment(t)){let n=String.fromCodePoint(e.codePointAt(0));if(!/[\p{P}\p{S}]/u.test(n)||U1.test(n)||e.includes("\uFE0F")||/\p{Emoji_Modifier}/u.test(n))return!1}return!0}function X1(t){if(!/[-\u058A\u2010\u2012\u2013\u2014]/u.test(t))return null;let e=[],n=0;for(let l of Dn().segment(t)){n++;let i=l.segment==="-"&&Y1(t,l.index);xy(l.segment)&&!i&&e.push(n)}return e.length===0?null:e}function Z1(t,e,n="normal",l="normal"){let i=n==="pre-wrap"?ES(t):bS(t);if(i.length===0)return{normalized:i,len:0,texts:[],isWordLike:[],kinds:[],starts:[]};let a=oy(i,e,n),u=l==="keep-all"?fy(i,a,e):a;return{normalized:i,...u}}var $l=null,V1=new Map,Il=null,my=96,py=/\p{Emoji_Presentation}/u,gy=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u,K1=new Map;function co(){if($l!==null)return $l;if(typeof OffscreenCanvas<"u")return $l=new OffscreenCanvas(1,1).getContext("2d"),$l;if(typeof document<"u")return $l=document.createElement("canvas").getContext("2d"),$l;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function Sy(t){let e=V1.get(t);return e||(e=new Map,V1.set(t,e)),e}function $e(t,e){let n=e.get(t);return n===void 0&&(n={width:co().measureText(t).width},e.set(t,n)),n}function Pl(){if(Il!==null)return Il;if(typeof navigator>"u")return Il={geckoAsciiLineBreaks:!1,lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,breakKeepAllAfterPunctuation:!0,preferPrefixWidthsForBreakableRuns:!1},Il;let t=navigator.userAgent,n=navigator.vendor==="Apple Computer, Inc."&&t.includes("Safari/")&&!t.includes("Chrome/")&&!t.includes("Chromium/")&&!t.includes("CriOS/")&&!t.includes("FxiOS/")&&!t.includes("EdgiOS/"),l=t.includes("Chrome/")||t.includes("Chromium/")||t.includes("CriOS/")||t.includes("Edg/");return Il={geckoAsciiLineBreaks:t.includes("Firefox/")&&!t.includes("FxiOS/"),lineFitEpsilon:n?1/64:.005,carryCJKAfterClosingQuote:l,breakKeepAllAfterPunctuation:!n,preferPrefixWidthsForBreakableRuns:n},Il}function yy(t){let e=t.match(/(?:^|\D)(\d+(?:\.\d+)?)\s*px/);return e?parseFloat(e[1]):16}function vy(t){return py.test(t)||t.includes("\uFE0F")}function J1(t){return gy.test(t)}function Ay(t){let e=K1.get(t);if(e!==void 0)return e;let n=yy(t),l=co();l.font=t;let i=l.measureText("\u{1F600}").width;if(e=0,i>n+.5&&typeof document<"u"&&document.body!==null){let a=document.createElement("span");a.style.font=t,a.style.display="inline-block",a.style.visibility="hidden",a.style.position="absolute",a.textContent="\u{1F600}",document.body.appendChild(a);let u=a.getBoundingClientRect().width;document.body.removeChild(a),i-u>.5&&(e=i-u)}return K1.set(t,e),e}function by(t){let e=0,n=Dn();for(let l of n.segment(t))vy(l.segment)&&e++;return e}function Ey(t,e){return e.emojiCount===void 0&&(e.emojiCount=by(t)),e.emojiCount}function Bn(t,e,n){return n===0?e.width:e.width-Ey(t,e)*n}function W1(t,e,n,l,i){if(e.breakableFitAdvances!==void 0&&e.breakableFitMode===i)return e.breakableFitAdvances;e.breakableFitMode=i;let a=Dn(),u=[];for(let f of a.segment(t))u.push(f.segment);if(u.length<=1)return e.breakableFitAdvances=null,e.breakableFitAdvances;if(i==="sum-graphemes"){let f=[];for(let m of u){let o=$e(m,n);f.push(Bn(m,o,l))}return e.breakableFitAdvances=f,e.breakableFitAdvances}if(i==="pair-context"||u.length>my){let f=[],m=null,o=0;for(let x of u){let g=$e(x,n),y=Bn(x,g,l);if(m===null)f.push(y);else{let N=m+x,h=$e(N,n);f.push(Bn(N,h,l)-o)}m=x,o=y}return e.breakableFitAdvances=f,e.breakableFitAdvances}let s=[],c="",r=0;for(let f of u){c+=f;let m=$e(c,n),o=Bn(c,m,l);s.push(o-r),r=o}return e.breakableFitAdvances=s,e.breakableFitAdvances}function $1(t,e){let n=co();n.font=t;let l=Sy(t),i=e?Ay(t):0;return{cache:l,emojiCorrection:i}}function Ny(t,e,n){return n===0&&e>0&&e0?t.letterSpacing:0}function oo(t,e){return e===0?0:t+e}function Dy(t,e){return t.letterSpacing!==0&&t.spacingGraphemeCounts[e]>0?t.letterSpacing:0}function By(t,e,n,l,i){let a=e==="tab"?i+Dy(t,n):t.lineEndFitAdvances[n];return oo(l,a)}function I1(t,e,n,l){let i=e==="tab"?0:t.lineEndFitAdvances[n];return oo(l,i)}function P1(t,e,n,l,i){let a=e==="tab"?i:t.lineEndPaintAdvances[n];return oo(l,a)}function ky(t,e,n){return t.letterSpacing!==0&&e?n+t.letterSpacing:n}function Ty(t,e){return t.letterSpacing===0?e:e+t.letterSpacing}function ro(t,e,n){let l=e;if(l>=t.length||t[l]>=n)return l;let i=t.length;for(l++;l0)return t.spacingGraphemeCounts[l]>0?t.letterSpacing:0;if(Ny(t.kinds,l,i))return 0;for(let a=l-1;a>=e;a--){let u=t.kinds[a];if(!(u==="space"||u==="zero-width-break"||u==="hard-break"||u==="soft-hyphen"))return a===e&&n>0||t.spacingGraphemeCounts[a]>0?t.letterSpacing:0}return 0}function Ry(t,e,n,l,i,a){return e+Oy(t,n,l,i,a)}function zy(t,e){let n=0,l=t.chunks.length;for(;n0)return e;for(let i=e;i=t.widths.length)return-1;l=a.consumedEndSegmentIndex,n.segmentIndex=l,n.graphemeIndex=0}return-1}function lx(t,e){if(e.segmentIndex>=t.widths.length)return-1;let n=zy(t,e.segmentIndex);return n<0?-1:nx(t,n,e)}function wy(t,e,n){if(n.segmentIndex>=t.widths.length)return-1;let l=e;for(;l=t.chunks[l].consumedEndSegmentIndex;)l++;return l>=t.chunks.length?-1:nx(t,l,n)}function ix(t,e){return ax(t,e)}function _y(t,e,n){let{widths:l,kinds:i,breakableFitAdvances:a,breakablePreferredBreaks:u}=t;if(l.length===0)return 0;let c=Pl().lineFitEpsilon,r=e+c,f=0,m=0,o=!1,x=0,g=0,y=0,N=0,h=-1,d=0;function p(){h=-1,d=0}function S(A=y,B=N,L=m){f++,n?.(L,x,g,A,B),m=0,o=!1,p()}function M(A,B){o=!0,x=A,g=0,y=A+1,N=0,m=B}function F(A,B,L){o=!0,x=A,g=B,y=A,N=B+1,m=L}function C(A,B){if(!o){M(A,B);return}m+=B,y=A+1,N=0}function E(A,B){let L=a[A],_=u[A]??null,et=_===null?-1:ro(_,0,B+1),Z=-1,rt=0,k=B;for(;kr){if(_!==null&&Z>B){S(A,Z,rt),k=Z,et=ro(_,et,k+1),Z=-1,rt=0;continue}S(),F(A,k,R)}else m+=R,y=A,N=k+1;let O=k+1;_!==null&&_[et]===O&&(Z=O,rt=m,et++),k++}o&&y===A&&N===L.length&&(y=A+1,N=0)}let v=0;for(;v=l.length));){let A=l[v],B=i[v],L=tx(B);if(!o){A>r&&a[v]!==null?E(v,0):M(v,A),L&&(h=v+1,d=m-A),v++;continue}if(m+A>r){if(L){C(v,A),S(v+1,0,m-A),v++;continue}if(h>=0){if(y>h||y===h&&N>0){S();continue}S(h,0,d);continue}if(A>r&&a[v]!==null){S(),E(v,0),v++;continue}S();continue}C(v,A),L&&(h=v+1,d=m-A),v++}return o&&S(),f}function ax(t,e,n){if(t.simpleLineWalkFastPath)return _y(t,e,n);let l={segmentIndex:0,graphemeIndex:0},i=lx(t,l);return Ly(t,l,i,e,n).lineCount}function Ly(t,e,n,l,i,a=Number.POSITIVE_INFINITY){let{widths:u,kinds:s,breakableFitAdvances:c,breakablePreferredBreaks:r,discretionaryHyphenWidth:f}=t,o=Pl().lineFitEpsilon,x=l+o,g,y,N,h,d,p,S,M,F,C;function E(){return C==="soft-hyphen"&&S===d&&p===0?F:N}function v(k=d,R=p,O=E()){return h?(e.segmentIndex=k,e.graphemeIndex=R,Ry(t,O,g,y,k,R)):null}function A(k,R){h=!0,d=k+1,p=0,N=R}function B(k,R,O){h=!0,d=k,p=R+1,N=O}function L(k,R){if(!h){A(k,R);return}N+=R,d=k+1,p=0}function _(k,R,O,J,zt,Xt){if(!R)return;let wt=I1(t,k,O,zt),Bt=P1(t,k,O,zt,J);S=O+1,M=N-Xt+wt,F=N-Xt+Bt,C=k}function et(k,R){let O=c[k],J=r[k]??null,zt=J===null?-1:ro(J,0,R+1),Xt=-1,wt=0;for(let Bt=R;Btx)return J!==null&&Xt>R?v(k,Xt,wt):v();N=Se,d=k,p=Bt+1}let li=Bt+1;J!==null&&J[zt]===li&&(Xt=li,wt=N,zt++)}return h&&d===k&&p===O.length&&(d=k+1,p=0),null}let Z=0,rt=null;for(;n>=0&&Z0){let Se=et(O,Xt);if(Se!==null){R=Se;break t}}else if(li>x&&c[O]!==null){let Se=et(O,0);if(Se!==null){R=Se;break t}}else A(O,Bt);_(J,zt,O,Bt,wt,kn);continue}if(N+li>x){let Se=N+I1(t,J,O,wt),kx=N+P1(t,J,O,wt,Bt);if(zt&&Se<=x){L(O,kn),R=v(O+1,0,kx);break t}if(S>=0&&M<=x){if(d>S||d===S&&p>0){R=v();break t}R=v(S,0,F);break t}R=v();break t}L(O,kn),_(J,zt,O,Bt,wt,kn)}R===null&&(R=S===k.consumedEndSegmentIndex&&p===0?v(k.consumedEndSegmentIndex,0,F):v(k.consumedEndSegmentIndex,0,N))}if(R===null)break;rt=R,Z++,i?.(R,g,y,e.segmentIndex,e.graphemeIndex),Z1?t+(e-1)*n:t}function Hy(t,e,n,l,i){let a=Pl(),{cache:u,emojiCorrection:s}=$1(e,J1(t.normalized)),c=Bn("-",$e("-",u),s)+(i===0?0:i*2),f=Bn(" ",$e(" ",u),s)*8,m=i!==0;if(t.len===0)return qy(n);let o=[],x=[],g=[],y=[],N=!m,h=n?[]:null,d=[],p=[],S=[],M=n?[]:null,F=[],C=0;function E(B,L,_,et,Z,rt,k,R,O){Z!=="text"&&Z!=="space"&&Z!=="zero-width-break"&&(N=!1),o.push(L),x.push(_),g.push(et),y.push(Z),h?.push(rt),d.push(k),p.push(R),m&&S.push(O),M!==null&&M.push(B)}function v(B,L,_,et,Z){let rt=m?ux(B,_):0,k=Uy(Bn(B,L,s),rt,i),R=_==="space"||_==="preserved-space"||_==="zero-width-break"?0:k,O=R===0?0:R+(rt>0?i:0),J=_==="space"||_==="zero-width-break"?0:k;if(Z&&B.length>1){let zt="sum-graphemes";i!==0?zt="segment-prefixes":ra(B)?zt="pair-context":a.preferPrefixWidthsForBreakableRuns&&(zt="segment-prefixes");let Xt=W1(B,L,u,s,zt),wt=Xt===null||l==="keep-all"?null:X1(B);E(B,k,O,J,_,et,Xt,wt,rt);return}E(B,k,O,J,_,et,null,null,rt)}for(let B=0;B[u.id,u])),l=[],i=[];for(let u of e){let s=t.get(u.id);s?s.version!==u.version&&i.push(u):l.push(u)}let a=[...t.keys()].filter(u=>!n.has(u));return{added:l,updated:i,removed:a}}function ho(t,e){let n=Math.max(1,Math.ceil((t.text?.length??0)/Math.max(24,Math.floor(e/8))));return t.kind==="activity"?Math.max(46,24+(t.items?.length??0)*20):t.kind==="turnSummary"||t.kind==="notice"||t.kind==="typing"?32:24+n*ox}function Yy(t,e,n){if(!t.text)return ho(t,e);let i=n.get(t.id)??{version:t.version,text:t.text,prepared:null,blocks:new Map};if(i.version=t.version,i.text=t.text,!i.blocks.size)try{i.prepared=fo(t.text,cx,{whiteSpace:"pre-wrap"})}catch{i.prepared=null}n.set(t.id,i);let a=Math.max(80,e-(t.kind==="user"?120:0)),u=t.text.split(/\n{2,}/).filter(Boolean);if(u.length===0)return ho(t,e);let s=0;for(let c of u){let r=i.blocks.get(c);if(!r)try{r=fo(c,cx,{whiteSpace:"pre-wrap"}),i.blocks.set(c,r)}catch{return ho(t,e)}s+=sx(r,a,ox).height}return Math.max(34,16+s+Math.max(0,u.length-1)*8)}function dx(t,e,n=new Map,l){let i=new Float64Array(t.length),a=new Float64Array(t.length),u=0;for(let s=0;s0?c:Yy(t[s],e,n);a[s]=r,u+=r}return{tops:i,heights:a,totalHeight:u}}function rx(t,e){let n=0,l=t.length;for(;n>>1;t[i]<=e?n=i+1:l=i}return n}function hx(t,e,n,l=4){if(t.tops.length===0)return{first:0,last:0};let i=Math.max(0,rx(t.tops,Math.max(0,e))-1-l),a=Math.min(t.tops.length,rx(t.tops,e+n)+l);return{first:i,last:a}}function jy(t,e){let n=t??{},l=n?.request??n,i=n?.sessionId??l?.sessionId,a=n?.permissionId??l?.permissionId;if(!(!a||i!==e))return{permissionId:String(a),title:l.toolCall?.title,kind:l.toolCall?.kind,pending:!0,options:(l.options??[]).map(u=>({id:String(u.optionId??u.id),name:String(u.name??u.optionId),allow:String(u.kind??"").startsWith("allow")}))}}function Qy(t,e,n){let l=typeof n?.promptId=="string"?n.promptId:void 0;if(!l)return;let i=e.get(l);i&&t.delete(i),e.delete(l)}function xo(...t){let e=new Map;for(let n of t.flat())e.set(n.seq,n);return[...e.values()].sort((n,l)=>n.seq-l.seq)}function Xy(t,e,n,l){n.add(l);let i=e.get(l);i&&t.delete(i),e.delete(l)}function Zy(t,e,n){return t||(n?void 0:e[0]?.sessionId)}function xx(t){return typeof t=="string"?t:t?.type==="text"?String(t.text??""):Array.isArray(t)?t.map(xx).join(""):""}function Vy(t){return t.dir==="in"&&t.msg.method==="session/update"?t.msg.params?.update:void 0}var Iu=class t{socket;nextRequest=1;pending=new Map;events=[];rows=new Map;sessions=[];selectedSessionId;summary;catalog=[];queue=[];pendingPermission;optimisticPromptRows=new Map;optimisticPromptTexts=new Map;firstSeq;lastSeq=0;turnOpen=!1;streamingAssistant;streamingAssistantMessageId;streamingActivity;supersededMessageIds=new Set;messageRows=new Map;listener;host;reconnectTimer;reconnectDelay=250;onLost;opening=!1;hasConnected=!1;closed=!1;selectionGeneration=0;historyExhausted=!1;constructor(e,n,l){this.host=e,this.listener=n,this.onLost=l,this.selectedSessionId=e.sessionId}static async connect(e,n,l){let i=new t(e,n,l);return await i.open(),i}async open(){if(this.opening||this.closed)return;this.opening=!0;let e=new URL(this.host.endpoint);e.searchParams.set("token",this.host.token),await new Promise((n,l)=>{let i=new WebSocket(e);this.socket=i;let a=!1;i.onopen=()=>{a=!0,n()},i.onerror=()=>{this.opening=!1,l(new Error("Unable to connect to acpmux WebSocket"))},i.onclose=()=>{if(this.socket===i){if(!a){this.opening=!1,l(new Error("acpmux WebSocket closed before connect"));return}for(let u of this.pending.values())u.reject(new Error("acpmux WebSocket closed"));if(this.pending.clear(),this.emit("disconnected"),!(!this.hasConnected||this.closed))if(this.onLost){let u=this.onLost;this.close(),u()}else this.scheduleReconnect()}},i.onmessage=u=>this.receive(String(u.data))});try{await this.request("initialize",{protocolVersion:1,clientInfo:{name:"cmux-react-agent-pane",version:"1"},clientCapabilities:{}});let n=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(n?.sessions??[]).filter(i=>i.sessionId);let l=await this.request("_acpmux/harnesses",{});this.catalog=Ky(l),this.selectedSessionId&&!this.sessions.some(i=>i.sessionId===this.selectedSessionId)&&(this.selectedSessionId=this.sessions[0]?.sessionId,this.resetSessionState()),this.selectedSessionId=Zy(this.selectedSessionId,this.sessions,this.host.newSession),this.selectedSessionId&&await this.attach(this.selectedSessionId),this.hasConnected=!0,this.reconnectDelay=250,this.emit("connected")}catch(n){throw this.socket?.close(),n}finally{this.opening=!1}}resetSessionState(){this.events=[],this.historyExhausted=!1,this.rows.clear(),this.firstSeq=void 0,this.lastSeq=0,this.summary=void 0,this.queue=[],this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.optimisticPromptRows.clear(),this.optimisticPromptTexts.clear(),this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0}scheduleReconnect(){if(this.reconnectTimer!==void 0||this.closed)return;let e=this.reconnectDelay;this.reconnectDelay=Math.min(e*2,3e4),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=void 0,this.open().catch(()=>this.scheduleReconnect())},e)}receive(e){let n;try{n=JSON.parse(e)}catch{return}if("id"in n&&typeof n.id=="number"){let i=this.pending.get(n.id);if(!i)return;this.pending.delete(n.id),n.error?i.reject(new Error(n.error.message??"acpmux request failed")):i.resolve(n.result);return}let l=n;l.method==="_acpmux/event"?this.apply(l.params):l.method==="session/update"?this.apply({sessionId:l.params?.sessionId,seq:Number(l.params?._meta?.acpmux?.seq??0),at:Number(l.params?._meta?.acpmux?.at??Date.now()),dir:"in",kind:String(l.params?.update?.sessionUpdate??""),msg:{method:"session/update",params:{update:l.params?.update}}}):l.method==="_acpmux/session_changed"?this.sessionChanged(l.params):l.method==="_acpmux/permission_pending"?this.applyPermission(l.params):l.method==="_acpmux/lagged"&&this.resyncAfterLag(l.params)}resyncAfterLag(e){e?.watch===!0&&this.refreshSessions().catch(()=>{});let n=this.selectedSessionId;n&&(Array.isArray(e?.sessionIds)&&!e.sessionIds.map(String).includes(n)||(this.emit("resyncing"),this.fetchMissedEvents(n,this.selectionGeneration).catch(()=>{})))}async fetchMissedEvents(e,n){for(;;){let l=await this.request("_acpmux/events",{sessionId:e,afterSeq:this.lastSeq,limit:5e3});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=l?.events??[];if(this.events=xo(this.events,i),this.rebuild(),l?.more!==!0||i.length===0)break}this.emit("resynced")}async refreshSessions(){let e=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(e?.sessions??[]).filter(n=>n.sessionId),this.emit("session changed")}request(e,n){if(this.socket?.readyState!==WebSocket.OPEN)return Promise.reject(new Error("acpmux WebSocket is not open"));let l=this.nextRequest++;return new Promise((i,a)=>{this.pending.set(l,{resolve:i,reject:a}),this.socket.send(JSON.stringify({jsonrpc:"2.0",id:l,method:e,params:n}))})}async attach(e,n=this.selectionGeneration){if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let l=await this.request("_acpmux/attach",{sessionId:e,limit:400,kinds:["transcript"],eventStream:!0});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=l?.session??{};this.summary=i,this.queue=(i.queue??[]).map(a=>({id:String(a.promptId),prompt:String(a.prompt??"")})),this.events=xo(l?.events??[],this.events),this.rebuild(),this.emit("attached")}sessionChanged(e){let n=e?.session;if(e?.kind==="purged"&&n?.sessionId){if(this.sessions=this.sessions.filter(l=>l.sessionId!==n.sessionId),n.sessionId===this.selectedSessionId){this.selectedSessionId=this.sessions[0]?.sessionId;let l=++this.selectionGeneration;this.resetSessionState(),this.emit("session purged"),this.selectedSessionId&&this.attach(this.selectedSessionId,l).catch(()=>{})}else this.emit("session purged");return}n?.sessionId&&(this.sessions=[...this.sessions.filter(l=>l.sessionId!==n.sessionId),n],n.sessionId===this.selectedSessionId&&(this.summary={...this.summary,...n},this.queue=(n.queue??this.queue).map(l=>({id:String(l.promptId),prompt:String(l.prompt??l.preview??"")}))),this.emit("session changed"))}applyPermission(e){let n=jy(e,this.selectedSessionId??"");n&&(this.pendingPermission=n,this.emit("permission"))}apply(e){!e?.seq||e.sessionId!==this.selectedSessionId||e.seq<=this.lastSeq||(this.events.push(e),this.lastSeq=e.seq,this.firstSeq=this.firstSeq===void 0?e.seq:Math.min(this.firstSeq,e.seq),this.reduce(e),this.emit(e.kind))}rebuild(){let e=[...this.optimisticPromptRows.values()].flatMap(l=>this.rows.get(l)??[]);this.rows.clear();for(let l of e)this.rows.set(l.id,l);this.firstSeq=void 0,this.lastSeq=0,this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0;let n=[...this.events].sort((l,i)=>l.seq-i.seq);for(let l of n)this.lastSeq=Math.max(this.lastSeq,l.seq),this.firstSeq=this.firstSeq===void 0?l.seq:Math.min(this.firstSeq,l.seq),this.reduce(l)}reduce(e){let n=e.msg??{},l=Vy(e);if(e.dir==="mux"){if(e.kind==="user_message"){let a=typeof n.promptId=="string"?n.promptId:void 0,u=typeof n.text=="string"?n.text:void 0,s=a??(u?[...this.optimisticPromptTexts.entries()].find(([,c])=>c===u)?.[0]:void 0);Qy(this.rows,this.optimisticPromptRows,{...n,promptId:s}),s&&this.optimisticPromptTexts.delete(s),this.rows.set(`user-${e.seq}`,{id:`user-${e.seq}`,version:1,at:e.at,kind:"user",text:String(n.text??"")}),this.turnOpen=!0}else if(e.kind==="turn_started")this.turnOpen=!0,this.rows.set("typing",{id:"typing",version:1,at:e.at,kind:"typing"});else if(e.kind==="message_superseded"){let a=typeof n.oldMessageId=="string"?n.oldMessageId:void 0;a&&(Xy(this.rows,this.messageRows,this.supersededMessageIds,a),this.streamingAssistantMessageId===a&&(this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0))}else if(e.kind==="turn_end"||e.kind==="turn_result"){if(this.turnOpen=!1,this.streamingAssistant){let a=this.rows.get(this.streamingAssistant);a&&(a.streaming=!1,a.version+=1)}this.rows.delete("typing"),e.kind==="turn_result"&&this.rows.set(`summary-${e.seq}`,{id:`summary-${e.seq}`,version:1,at:e.at,kind:"turnSummary",durationMs:void 0,toolCount:[...this.rows.values()].filter(a=>a.kind==="activity").length,status:String(n.status??"completed"),error:n.errorText}),this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0}else if(e.kind==="queued"||e.kind==="queue_updated"){let a=String(n.promptId??"");a&&(this.queue=[...this.queue.filter(u=>u.id!==a),{id:a,prompt:String(n.text??"")}])}else e.kind==="queue_removed"||e.kind==="dequeued"?this.queue=this.queue.filter(a=>a.id!==String(n.promptId??"")):e.kind==="permission_request"?this.applyPermission({...n,sessionId:e.sessionId}):e.kind==="permission_decision"?this.pendingPermission=void 0:e.kind==="status"&&(this.summary={...this.summary,status:n.status});return}if(!l)return;let i=xx(l.content);if(e.kind==="agent_message_chunk"&&i){let a=typeof l.messageId=="string"?l.messageId:void 0;if(a&&this.supersededMessageIds.has(a))return;let s=!!(this.streamingAssistant&&(!a||!this.streamingAssistantMessageId||this.streamingAssistantMessageId===a))?this.streamingAssistant:`assistant-${e.seq}`,c=this.rows.get(s);this.rows.set(s,{id:s,version:(c?.version??0)+1,at:e.at,kind:"assistant",text:`${c?.text??""}${i}`,streaming:!0}),this.streamingAssistant=s,this.streamingAssistantMessageId=a,a&&this.messageRows.set(a,s),this.rows.delete("typing")}else if(e.kind==="agent_thought_chunk"&&i){let a=this.streamingActivity??`activity-${e.seq}`,u=this.rows.get(a);this.rows.set(a,{id:a,version:(u?.version??0)+1,at:e.at,kind:"activity",toolCount:u?.toolCount??0,items:[...u?.items??[],{kind:"thought",text:i}]}),this.streamingActivity=a}else if(e.kind==="tool_call"||e.kind==="tool_call_update"){let a=String(l.toolCallId??`tool-${e.seq}`),u=this.streamingActivity??`activity-${e.seq}`,s=this.rows.get(u),c=[...s?.items??[]],r=c.findIndex(m=>m.tool?.id===a),f={kind:"tool",text:String(l.title??l.name??a),tool:{id:a,title:String(l.title??a),kind:l.kind,status:String(l.status??"in_progress"),inputSummary:l.rawInput?JSON.stringify(l.rawInput):void 0,output:i||void 0}};r>=0?c[r]=f:c.push(f),this.rows.set(u,{id:u,version:(s?.version??0)+1,at:e.at,kind:"activity",toolCount:c.filter(m=>m.kind==="tool").length,items:c}),this.streamingActivity=u}else e.kind==="plan"&&this.rows.set(`plan-${e.seq}`,{id:`plan-${e.seq}`,version:1,at:e.at,kind:"plan",text:i||JSON.stringify(l.entries??l.content??"")})}emit(e="connected"){let n=this.summary,l=(n?.configOptions??[]).find(i=>i.category==="thought_level"||i.id==="reasoning_effort");this.listener({type:"snapshot",protocolVersion:1,rows:[...this.rows.values()].sort((i,a)=>i.at-a.at),sessions:this.sessions.map(i=>({sessionId:i.sessionId,displayTitle:i.title??i.name,title:i.title,name:i.name,status:i.status,model:i.model})),summary:n?{sessionId:n.sessionId,title:n.title,name:n.name,harness:n.harness,model:n.model,effort:l?.currentValue,status:n.status,modes:n.modes,configOptions:n.configOptions}:void 0,connection:e,sessionId:this.selectedSessionId,isWorking:this.turnOpen||n?.status==="running",queue:this.queue,permission:this.pendingPermission,catalog:this.catalog,canLoadOlder:!this.historyExhausted&&(this.firstSeq??1)>1})}snapshot(){this.emit()}async ensureSession(){return this.selectedSessionId||await this.create(),this.selectedSessionId}async send(e){let n=await this.ensureSession();if(!n)return;let l=crypto.randomUUID(),i=`local-${l}`,a=Date.now();this.optimisticPromptRows.set(l,i),this.optimisticPromptTexts.set(l,e),this.rows.set(i,{id:i,version:1,at:a,kind:"user",text:e,pending:!0}),this.emit();try{await this.request("session/prompt",{sessionId:n,prompt:[{type:"text",text:e}],_meta:{acpmux:{promptId:l}}})}catch(u){let s=this.rows.get(i);throw s&&(s.pending=!1,s.failed=!0,s.version+=1),this.optimisticPromptRows.delete(l),this.optimisticPromptTexts.delete(l),this.emit("failed"),u}return n}async cancel(){this.selectedSessionId&&this.socket?.send(JSON.stringify({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:this.selectedSessionId}}))}async permission(e,n){this.selectedSessionId&&await this.request("_acpmux/permission_respond",{sessionId:this.selectedSessionId,permissionId:e,optionId:n})}async select(e){let n=this.selectedSessionId,l=++this.selectionGeneration;return this.selectedSessionId=e,this.resetSessionState(),n&&await this.request("_acpmux/detach",{sessionId:n}),await this.attach(e,l),l===this.selectionGeneration&&this.selectedSessionId===e?e:void 0}async create(e){let n=await this.request("session/new",{mcpServers:[],_meta:{acpmux:{harness:e}}});if(n?.sessionId)return this.select(String(n.sessionId))}async setModel(e){this.selectedSessionId&&await this.request("session/set_model",{sessionId:this.selectedSessionId,modelId:e})}async setMode(e){this.selectedSessionId&&await this.request("session/set_mode",{sessionId:this.selectedSessionId,modeId:e})}async setConfig(e,n){this.selectedSessionId&&await this.request("session/set_config_option",{sessionId:this.selectedSessionId,configId:e,value:n})}async loadOlder(){if(!this.selectedSessionId||!this.firstSeq||this.firstSeq<=1||this.historyExhausted)return;let e=this.selectedSessionId,n=this.selectionGeneration,l=await this.request("_acpmux/events",{sessionId:e,beforeSeq:this.firstSeq,limit:400,kinds:["transcript"]});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=this.summary,a=this.queue,u=this.pendingPermission,s=l?.events??[];this.events=xo(s,this.events),this.rebuild(),this.summary=i,this.queue=a,this.pendingPermission=u,this.historyExhausted=l?.more===!1||s.length===0||(this.firstSeq??1)<=1,this.emit("history")}close(){this.closed=!0,this.reconnectTimer!==void 0&&window.clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close(),this.socket=void 0}};function Ky(t){let e=t?.harnesses??t?.items??t??[];return(Array.isArray(e)?e:Object.entries(e).map(([n,l])=>({id:n,...l}))).map(n=>({id:String(n.id??n.name),name:String(n.name??n.id),models:(n.models??[]).map(l=>({id:String(l.id??l.modelId),name:l.name}))}))}var mo="mock-session",Jy=[{id:"claude",name:"Claude",models:[{id:"claude-sonnet",name:"Claude Sonnet"}]},{id:"codex",name:"Codex",models:[{id:"gpt-6-astra",name:"GPT-6-Astra"}]}];function Wy(t,e=!1){return{type:"snapshot",protocolVersion:1,rows:t,sessions:[{sessionId:mo,title:"Mock session"}],summary:{sessionId:mo,title:"Mock session",harness:"claude",model:"claude-sonnet"},connection:"mock",sessionId:mo,isWorking:e,queue:[],catalog:Jy,canLoadOlder:!1}}function $y(t){return`Mock reply to **${t.replace(/[*_`]/g,"")}**. No acpmux daemon is attached; this pane is running in mock mode.`}function mx(t,e=n=>{window.setTimeout(n,400)}){let n=[{id:"mock-welcome",version:1,at:Date.now(),kind:"assistant",text:"Mock agent session. Type a prompt to see the pane render a turn."}],l=0,i=(u=!1)=>t(Wy(n,u)),a=u=>{n=[...n,{id:`mock-${l++}`,version:1,at:Date.now(),...u}]};return i(),{"chat.send":async({text:u})=>{let s=String(u??"");a({kind:"user",text:s}),i(!0),e(()=>{a({kind:"assistant",text:$y(s)}),i()})},"chat.cancel":async()=>i(),"chat.permission":async()=>i(),"chat.model":async()=>{},"chat.mode":async()=>{},"chat.effort":async()=>{},"chat.select":async()=>{},"chat.new":async()=>{n=[],i()},"chat.history":async()=>{}}}function Qt(t){return Math.round(t*100)/100}function ei(t,e){return t.length===0?0:t[Math.min(t.length-1,Math.max(0,Math.round((t.length-1)*e)))]}function px(t){return ei([...t].sort((e,n)=>e-n),.5)}function Iy(t){let e=[];for(let n=1;n0))return 0;let n=0;for(let l of t)n+=Math.max(0,Math.round(l/e)-1);return n}function gx(t,e){let n=Iy(t).sort((l,i)=>l-i);return{frames:t.length,nominal_ms:Qt(e),p50_ms:Qt(ei(n,.5)),p95_ms:Qt(ei(n,.95)),p99_ms:Qt(ei(n,.99)),max_ms:Qt(n.at(-1)??0),dropped_frames:Py(n,e)}}function ti(t){let e=[...t].sort((n,l)=>n-l);return{p50_ms:Qt(ei(e,.5)),p95_ms:Qt(ei(e,.95)),max_ms:Qt(e.at(-1)??0)}}function Sx(t,e,n,l,i){let a=Math.max(0,n),u=Math.min(i,n+l);return u<=a?!1:t>a+.5||ee.frame)),to_paint:ti(t.map(e=>e.paint))}}var go=class{enabled=!1;ring=new po;layoutSinceMark=0;reactSinceMark=0;lastMark;mountedTop=0;mountedBottom=0;commitWaiters=[];typing=[];keyListener;enable(e=typeof document>"u"?void 0:document){this.enabled=!0,!(this.keyListener||!e)&&(this.keyListener=n=>{if(!n.target?.closest?.(".acpmux-composer"))return;let i=n.timeStamp;requestAnimationFrame(()=>{let a=performance.now(),u=new MessageChannel;u.port1.onmessage=()=>{this.typing.push({frame:a-i,paint:performance.now()-i}),this.typing.length>4096&&this.typing.shift(),u.port1.close()},u.port2.postMessage(0)})},e.addEventListener("keydown",this.keyListener,!0))}addLayout(e){this.layoutSinceMark+=e}commit(e,n,l,i,a){this.reactSinceMark+=Math.max(0,e-n),this.mountedTop=l,this.mountedBottom=i;let u=this.commitWaiters;this.commitWaiters=[];for(let s of u)s(a)}nextCommit(e=1e4){return new Promise(n=>{let l=setTimeout(()=>{this.commitWaiters=this.commitWaiters.filter(a=>a!==i),n(void 0)},e),i=a=>{clearTimeout(l),n(a)};this.commitWaiters.push(i)})}resetFrames(){this.ring.clear(),this.lastMark=void 0,this.layoutSinceMark=0,this.reactSinceMark=0}markFrame(e,n){this.lastMark!==void 0&&this.ring.push(e-this.lastMark,this.layoutSinceMark,this.reactSinceMark,n),this.lastMark=e,this.layoutSinceMark=0,this.reactSinceMark=0}stats(e=!1){let n=this.ring.samples(),l={frames:n.length,blank_frames:n.filter(i=>i.blank).length,interval:ti(n.map(i=>i.interval)),layout:ti(n.map(i=>i.layout)),react:ti(n.map(i=>i.react)),other:ti(n.map(i=>i.other))};return e&&(l.samples=n.map(i=>({interval_ms:Qt(i.interval),layout_ms:Qt(i.layout),react_ms:Qt(i.react),other_ms:Qt(i.other),blank:i.blank}))),l}},tt=new go;function vx(t){let e=[],n=0,l=a=>{n+=1,e.push({...a,version:1,at:n*1e3})},i=Math.max(1,Math.floor(t/3));for(let a=0;a undefined); + const sessionId = this.selectedSessionId; + if (!sessionId) return; + if (Array.isArray(params?.sessionIds) && !params.sessionIds.map(String).includes(sessionId)) return; this.emit("resyncing"); - void this.request("_acpmux/events", { sessionId, afterSeq, limit: 5_000 }).then((result) => { + void this.fetchMissedEvents(sessionId, this.selectionGeneration).catch(() => undefined); + } + + private async fetchMissedEvents(sessionId: string, generation: number): Promise { + for (;;) { + const result = await this.request("_acpmux/events", { sessionId, afterSeq: this.lastSeq, limit: 5_000 }); if (generation !== this.selectionGeneration || this.selectedSessionId !== sessionId) return; - this.events = mergeEventRecords(this.events, result?.events ?? []); + const missed: EventRecord[] = result?.events ?? []; + this.events = mergeEventRecords(this.events, missed); this.rebuild(); - this.emit("resynced"); - }).catch(() => undefined); + if (result?.more !== true || missed.length === 0) break; + } + 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 { @@ -416,7 +432,7 @@ export class AcpmuxDirectClient { this.summary = summary; this.queue = queue; this.pendingPermission = permission; - this.historyExhausted = result?.hasMore === false || older.length === 0 || (this.firstSeq ?? 1) <= 1; + 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; } From 2c57221efb800cf31f65bcad8b52224f47f6ff2c Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 13:54:48 -0400 Subject: [PATCH 09/10] Agent pane: failing tests for lag paging past live events and lag before attach Lag recovery pages from this.lastSeq, which live events advance between pages, so a live event that lands mid-resync makes the next page skip the rest of the gap. A lag notice that arrives while a newly selected session's attach is in flight resyncs from seq 0. Both tests fail here. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../src/agent-session/acpmux/direct.test.ts | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/webviews/src/agent-session/acpmux/direct.test.ts b/webviews/src/agent-session/acpmux/direct.test.ts index cec555d0b0e0..88ff23edad95 100644 --- a/webviews/src/agent-session/acpmux/direct.test.ts +++ b/webviews/src/agent-session/acpmux/direct.test.ts @@ -226,6 +226,32 @@ describe("direct client session state", () => { 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: [] }; From 276e7e8cf7340a2d24d543eaccbc99e8d145cdd1 Mon Sep 17 00:00:00 2001 From: Leo Li Date: Thu, 1 Oct 2026 13:55:18 -0400 Subject: [PATCH 10/10] Agent pane: page lag recovery from its own cursor and wait for attach The resync loop now advances a local cursor to the newest seq of each page instead of reading lastSeq, which live events move ahead mid-resync. A lag notice is ignored until the selected session's attach reply has landed, since that reply already carries the latest events and there is no cursor before it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01RYQHfug1ZVQDp4eWgwVUtD --- .../Resources/agent-pane/index.html | 2 +- webviews/src/agent-session/acpmux/direct.ts | 16 +++++++++++----- 2 files changed, 12 insertions(+), 6 deletions(-) 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 85d81b426598..ccba46bdddce 100644 --- a/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html +++ b/Packages/macOS/CmuxNext/Sources/CmuxNextAgentPane/Resources/agent-pane/index.html @@ -2070,7 +2070,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let l="

An error occurred:

"+Fe(n.message+"",!0)+"
";return e?Promise.resolve(l):l}if(e)return Promise.reject(n);throw n}}},In=new xS;function I(t,e){return In.parse(t,e)}I.options=I.setOptions=function(t){return In.setOptions(t),I.defaults=In.defaults,g1(I.defaults),I};I.getDefaults=jr;I.defaults=Pn;I.use=function(...t){return In.use(...t),I.defaults=In.defaults,g1(I.defaults),I};I.walkTokens=function(t,e){return In.walkTokens(t,e)};I.parseInline=In.parseInline;I.Parser=ge;I.parser=ge.parse;I.Renderer=Vu;I.TextRenderer=$r;I.Lexer=pe;I.lexer=pe.lex;I.Tokenizer=Zu;I.Hooks=sa;I.parse=I;var bv=I.options,Ev=I.setOptions,Nv=I.use,Mv=I.walkTokens,Cv=I.parseInline;var Fv=ge.parse,F1=pe.lex;var mS={isDark:null,pageBackground:"--agent-page-bg",surfaceBackground:"--agent-surface",surfaceElevatedBackground:"--agent-surface-elevated",inputBackground:"--agent-input-bg",border:"--agent-border",borderStrong:"--agent-border-strong",text:"--agent-text",mutedText:"--agent-muted",softText:"--agent-soft",accent:"--agent-accent",accentSoft:"--agent-accent-soft",danger:"--agent-danger",shadow:"--agent-shadow"};function D1(t){if(typeof document>"u")return;let e=document.documentElement;e.dataset.theme=t.isDark?"dark":"light",pS(),e.classList.toggle("dark",t.isDark),e.classList.toggle("electron-dark",t.isDark),e.classList.toggle("light",!t.isDark),e.style.colorScheme=t.isDark?"dark":"light";for(let[n,l]of Object.entries(mS))l&&e.style.setProperty(l,String(t[n]))}function pS(){if(typeof document>"u")return;let t=document.documentElement;t.dataset.codexWindowType="electron",t.dataset.windowType="electron",t.dataset.codexOs=gS(),document.body&&(document.body.dataset.codexWindowType="electron")}function gS(){if(typeof navigator>"u")return"unknown";let t=navigator,e=(t.userAgentData?.platform??t.platform??t.userAgent).toLowerCase();return e.includes("win")?"win32":e.includes("mac")||e.includes("darwin")?"darwin":e.includes("linux")?"linux":"unknown"}var B1=["BN","BN","BN","BN","BN","BN","BN","BN","BN","S","B","S","WS","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","B","B","B","S","WS","ON","ON","ET","ET","ET","ON","ON","ON","ON","ON","ES","CS","ES","CS","CS","EN","EN","EN","EN","EN","EN","EN","EN","EN","EN","CS","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","ON","ON","ON","BN","BN","BN","BN","BN","BN","B","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","BN","CS","ON","ET","ET","ET","ET","ON","ON","ON","ON","L","ON","ON","BN","ON","ON","ET","ET","EN","EN","ON","L","ON","ON","ON","EN","L","ON","ON","ON","ON","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","L","ON","L","L","L","L","L","L","L","L"],Ir=[[697,698,"ON"],[706,719,"ON"],[722,735,"ON"],[741,749,"ON"],[751,767,"ON"],[768,879,"NSM"],[884,885,"ON"],[894,894,"ON"],[900,901,"ON"],[903,903,"ON"],[1014,1014,"ON"],[1155,1161,"NSM"],[1418,1418,"ON"],[1421,1422,"ON"],[1423,1423,"ET"],[1424,1424,"R"],[1425,1469,"NSM"],[1470,1470,"R"],[1471,1471,"NSM"],[1472,1472,"R"],[1473,1474,"NSM"],[1475,1475,"R"],[1476,1477,"NSM"],[1478,1478,"R"],[1479,1479,"NSM"],[1480,1535,"R"],[1536,1541,"AN"],[1542,1543,"ON"],[1544,1544,"AL"],[1545,1546,"ET"],[1547,1547,"AL"],[1548,1548,"CS"],[1549,1549,"AL"],[1550,1551,"ON"],[1552,1562,"NSM"],[1563,1610,"AL"],[1611,1631,"NSM"],[1632,1641,"AN"],[1642,1642,"ET"],[1643,1644,"AN"],[1645,1647,"AL"],[1648,1648,"NSM"],[1649,1749,"AL"],[1750,1756,"NSM"],[1757,1757,"AN"],[1758,1758,"ON"],[1759,1764,"NSM"],[1765,1766,"AL"],[1767,1768,"NSM"],[1769,1769,"ON"],[1770,1773,"NSM"],[1774,1775,"AL"],[1776,1785,"EN"],[1786,1808,"AL"],[1809,1809,"NSM"],[1810,1839,"AL"],[1840,1866,"NSM"],[1867,1957,"AL"],[1958,1968,"NSM"],[1969,1983,"AL"],[1984,2026,"R"],[2027,2035,"NSM"],[2036,2037,"R"],[2038,2041,"ON"],[2042,2044,"R"],[2045,2045,"NSM"],[2046,2069,"R"],[2070,2073,"NSM"],[2074,2074,"R"],[2075,2083,"NSM"],[2084,2084,"R"],[2085,2087,"NSM"],[2088,2088,"R"],[2089,2093,"NSM"],[2094,2136,"R"],[2137,2139,"NSM"],[2140,2143,"R"],[2144,2191,"AL"],[2192,2193,"AN"],[2194,2198,"AL"],[2199,2207,"NSM"],[2208,2249,"AL"],[2250,2273,"NSM"],[2274,2274,"AN"],[2275,2306,"NSM"],[2362,2362,"NSM"],[2364,2364,"NSM"],[2369,2376,"NSM"],[2381,2381,"NSM"],[2385,2391,"NSM"],[2402,2403,"NSM"],[2433,2433,"NSM"],[2492,2492,"NSM"],[2497,2500,"NSM"],[2509,2509,"NSM"],[2530,2531,"NSM"],[2546,2547,"ET"],[2555,2555,"ET"],[2558,2558,"NSM"],[2561,2562,"NSM"],[2620,2620,"NSM"],[2625,2626,"NSM"],[2631,2632,"NSM"],[2635,2637,"NSM"],[2641,2641,"NSM"],[2672,2673,"NSM"],[2677,2677,"NSM"],[2689,2690,"NSM"],[2748,2748,"NSM"],[2753,2757,"NSM"],[2759,2760,"NSM"],[2765,2765,"NSM"],[2786,2787,"NSM"],[2801,2801,"ET"],[2810,2815,"NSM"],[2817,2817,"NSM"],[2876,2876,"NSM"],[2879,2879,"NSM"],[2881,2884,"NSM"],[2893,2893,"NSM"],[2901,2902,"NSM"],[2914,2915,"NSM"],[2946,2946,"NSM"],[3008,3008,"NSM"],[3021,3021,"NSM"],[3059,3064,"ON"],[3065,3065,"ET"],[3066,3066,"ON"],[3072,3072,"NSM"],[3076,3076,"NSM"],[3132,3132,"NSM"],[3134,3136,"NSM"],[3142,3144,"NSM"],[3146,3149,"NSM"],[3157,3158,"NSM"],[3170,3171,"NSM"],[3192,3198,"ON"],[3201,3201,"NSM"],[3260,3260,"NSM"],[3276,3277,"NSM"],[3298,3299,"NSM"],[3328,3329,"NSM"],[3387,3388,"NSM"],[3393,3396,"NSM"],[3405,3405,"NSM"],[3426,3427,"NSM"],[3457,3457,"NSM"],[3530,3530,"NSM"],[3538,3540,"NSM"],[3542,3542,"NSM"],[3633,3633,"NSM"],[3636,3642,"NSM"],[3647,3647,"ET"],[3655,3662,"NSM"],[3761,3761,"NSM"],[3764,3772,"NSM"],[3784,3790,"NSM"],[3864,3865,"NSM"],[3893,3893,"NSM"],[3895,3895,"NSM"],[3897,3897,"NSM"],[3898,3901,"ON"],[3953,3966,"NSM"],[3968,3972,"NSM"],[3974,3975,"NSM"],[3981,3991,"NSM"],[3993,4028,"NSM"],[4038,4038,"NSM"],[4141,4144,"NSM"],[4146,4151,"NSM"],[4153,4154,"NSM"],[4157,4158,"NSM"],[4184,4185,"NSM"],[4190,4192,"NSM"],[4209,4212,"NSM"],[4226,4226,"NSM"],[4229,4230,"NSM"],[4237,4237,"NSM"],[4253,4253,"NSM"],[4957,4959,"NSM"],[5008,5017,"ON"],[5120,5120,"ON"],[5760,5760,"WS"],[5787,5788,"ON"],[5906,5908,"NSM"],[5938,5939,"NSM"],[5970,5971,"NSM"],[6002,6003,"NSM"],[6068,6069,"NSM"],[6071,6077,"NSM"],[6086,6086,"NSM"],[6089,6099,"NSM"],[6107,6107,"ET"],[6109,6109,"NSM"],[6128,6137,"ON"],[6144,6154,"ON"],[6155,6157,"NSM"],[6158,6158,"BN"],[6159,6159,"NSM"],[6277,6278,"NSM"],[6313,6313,"NSM"],[6432,6434,"NSM"],[6439,6440,"NSM"],[6450,6450,"NSM"],[6457,6459,"NSM"],[6464,6464,"ON"],[6468,6469,"ON"],[6622,6655,"ON"],[6679,6680,"NSM"],[6683,6683,"NSM"],[6742,6742,"NSM"],[6744,6750,"NSM"],[6752,6752,"NSM"],[6754,6754,"NSM"],[6757,6764,"NSM"],[6771,6780,"NSM"],[6783,6783,"NSM"],[6832,6877,"NSM"],[6880,6891,"NSM"],[6912,6915,"NSM"],[6964,6964,"NSM"],[6966,6970,"NSM"],[6972,6972,"NSM"],[6978,6978,"NSM"],[7019,7027,"NSM"],[7040,7041,"NSM"],[7074,7077,"NSM"],[7080,7081,"NSM"],[7083,7085,"NSM"],[7142,7142,"NSM"],[7144,7145,"NSM"],[7149,7149,"NSM"],[7151,7153,"NSM"],[7212,7219,"NSM"],[7222,7223,"NSM"],[7376,7378,"NSM"],[7380,7392,"NSM"],[7394,7400,"NSM"],[7405,7405,"NSM"],[7412,7412,"NSM"],[7416,7417,"NSM"],[7616,7679,"NSM"],[8125,8125,"ON"],[8127,8129,"ON"],[8141,8143,"ON"],[8157,8159,"ON"],[8173,8175,"ON"],[8189,8190,"ON"],[8192,8202,"WS"],[8203,8205,"BN"],[8207,8207,"R"],[8208,8231,"ON"],[8232,8232,"WS"],[8233,8233,"B"],[8234,8238,"BN"],[8239,8239,"CS"],[8240,8244,"ET"],[8245,8259,"ON"],[8260,8260,"CS"],[8261,8286,"ON"],[8287,8287,"WS"],[8288,8303,"BN"],[8304,8304,"EN"],[8308,8313,"EN"],[8314,8315,"ES"],[8316,8318,"ON"],[8320,8329,"EN"],[8330,8331,"ES"],[8332,8334,"ON"],[8352,8399,"ET"],[8400,8432,"NSM"],[8448,8449,"ON"],[8451,8454,"ON"],[8456,8457,"ON"],[8468,8468,"ON"],[8470,8472,"ON"],[8478,8483,"ON"],[8485,8485,"ON"],[8487,8487,"ON"],[8489,8489,"ON"],[8494,8494,"ET"],[8506,8507,"ON"],[8512,8516,"ON"],[8522,8525,"ON"],[8528,8543,"ON"],[8585,8587,"ON"],[8592,8721,"ON"],[8722,8722,"ES"],[8723,8723,"ET"],[8724,9013,"ON"],[9083,9108,"ON"],[9110,9257,"ON"],[9280,9290,"ON"],[9312,9351,"ON"],[9352,9371,"EN"],[9450,9899,"ON"],[9901,10239,"ON"],[10496,11123,"ON"],[11126,11263,"ON"],[11493,11498,"ON"],[11503,11505,"NSM"],[11513,11519,"ON"],[11647,11647,"NSM"],[11744,11775,"NSM"],[11776,11869,"ON"],[11904,11929,"ON"],[11931,12019,"ON"],[12032,12245,"ON"],[12272,12287,"ON"],[12288,12288,"WS"],[12289,12292,"ON"],[12296,12320,"ON"],[12330,12333,"NSM"],[12336,12336,"ON"],[12342,12343,"ON"],[12349,12351,"ON"],[12441,12442,"NSM"],[12443,12444,"ON"],[12448,12448,"ON"],[12539,12539,"ON"],[12736,12773,"ON"],[12783,12783,"ON"],[12829,12830,"ON"],[12880,12895,"ON"],[12924,12926,"ON"],[12977,12991,"ON"],[13004,13007,"ON"],[13175,13178,"ON"],[13278,13279,"ON"],[13311,13311,"ON"],[19904,19967,"ON"],[42128,42182,"ON"],[42509,42511,"ON"],[42607,42610,"NSM"],[42611,42611,"ON"],[42612,42621,"NSM"],[42622,42623,"ON"],[42654,42655,"NSM"],[42736,42737,"NSM"],[42752,42785,"ON"],[42888,42888,"ON"],[43010,43010,"NSM"],[43014,43014,"NSM"],[43019,43019,"NSM"],[43045,43046,"NSM"],[43048,43051,"ON"],[43052,43052,"NSM"],[43064,43065,"ET"],[43124,43127,"ON"],[43204,43205,"NSM"],[43232,43249,"NSM"],[43263,43263,"NSM"],[43302,43309,"NSM"],[43335,43345,"NSM"],[43392,43394,"NSM"],[43443,43443,"NSM"],[43446,43449,"NSM"],[43452,43453,"NSM"],[43493,43493,"NSM"],[43561,43566,"NSM"],[43569,43570,"NSM"],[43573,43574,"NSM"],[43587,43587,"NSM"],[43596,43596,"NSM"],[43644,43644,"NSM"],[43696,43696,"NSM"],[43698,43700,"NSM"],[43703,43704,"NSM"],[43710,43711,"NSM"],[43713,43713,"NSM"],[43756,43757,"NSM"],[43766,43766,"NSM"],[43882,43883,"ON"],[44005,44005,"NSM"],[44008,44008,"NSM"],[44013,44013,"NSM"],[64285,64285,"R"],[64286,64286,"NSM"],[64287,64296,"R"],[64297,64297,"ES"],[64298,64335,"R"],[64336,64450,"AL"],[64451,64466,"ON"],[64467,64829,"AL"],[64830,64847,"ON"],[64848,64911,"AL"],[64912,64913,"ON"],[64914,64967,"AL"],[64968,64975,"ON"],[64976,65007,"BN"],[65008,65020,"AL"],[65021,65023,"ON"],[65024,65039,"NSM"],[65040,65049,"ON"],[65056,65071,"NSM"],[65072,65103,"ON"],[65104,65104,"CS"],[65105,65105,"ON"],[65106,65106,"CS"],[65108,65108,"ON"],[65109,65109,"CS"],[65110,65118,"ON"],[65119,65119,"ET"],[65120,65121,"ON"],[65122,65123,"ES"],[65124,65126,"ON"],[65128,65128,"ON"],[65129,65130,"ET"],[65131,65131,"ON"],[65136,65278,"AL"],[65279,65279,"BN"],[65281,65282,"ON"],[65283,65285,"ET"],[65286,65290,"ON"],[65291,65291,"ES"],[65292,65292,"CS"],[65293,65293,"ES"],[65294,65295,"CS"],[65296,65305,"EN"],[65306,65306,"CS"],[65307,65312,"ON"],[65339,65344,"ON"],[65371,65381,"ON"],[65504,65505,"ET"],[65506,65508,"ON"],[65509,65510,"ET"],[65512,65518,"ON"],[65520,65528,"BN"],[65529,65533,"ON"],[65534,65535,"BN"],[65793,65793,"ON"],[65856,65932,"ON"],[65936,65948,"ON"],[65952,65952,"ON"],[66045,66045,"NSM"],[66272,66272,"NSM"],[66273,66299,"EN"],[66422,66426,"NSM"],[67584,67870,"R"],[67871,67871,"ON"],[67872,68096,"R"],[68097,68099,"NSM"],[68100,68100,"R"],[68101,68102,"NSM"],[68103,68107,"R"],[68108,68111,"NSM"],[68112,68151,"R"],[68152,68154,"NSM"],[68155,68158,"R"],[68159,68159,"NSM"],[68160,68324,"R"],[68325,68326,"NSM"],[68327,68408,"R"],[68409,68415,"ON"],[68416,68863,"R"],[68864,68899,"AL"],[68900,68903,"NSM"],[68904,68911,"AL"],[68912,68921,"AN"],[68922,68927,"AL"],[68928,68937,"AN"],[68938,68968,"R"],[68969,68973,"NSM"],[68974,68974,"ON"],[68975,69215,"R"],[69216,69246,"AN"],[69247,69290,"R"],[69291,69292,"NSM"],[69293,69311,"R"],[69312,69327,"AL"],[69328,69336,"ON"],[69337,69369,"AL"],[69370,69375,"NSM"],[69376,69423,"R"],[69424,69445,"AL"],[69446,69456,"NSM"],[69457,69487,"AL"],[69488,69505,"R"],[69506,69509,"NSM"],[69510,69631,"R"],[69633,69633,"NSM"],[69688,69702,"NSM"],[69714,69733,"ON"],[69744,69744,"NSM"],[69747,69748,"NSM"],[69759,69761,"NSM"],[69811,69814,"NSM"],[69817,69818,"NSM"],[69826,69826,"NSM"],[69888,69890,"NSM"],[69927,69931,"NSM"],[69933,69940,"NSM"],[70003,70003,"NSM"],[70016,70017,"NSM"],[70070,70078,"NSM"],[70089,70092,"NSM"],[70095,70095,"NSM"],[70191,70193,"NSM"],[70196,70196,"NSM"],[70198,70199,"NSM"],[70206,70206,"NSM"],[70209,70209,"NSM"],[70367,70367,"NSM"],[70371,70378,"NSM"],[70400,70401,"NSM"],[70459,70460,"NSM"],[70464,70464,"NSM"],[70502,70508,"NSM"],[70512,70516,"NSM"],[70587,70592,"NSM"],[70606,70606,"NSM"],[70608,70608,"NSM"],[70610,70610,"NSM"],[70625,70626,"NSM"],[70712,70719,"NSM"],[70722,70724,"NSM"],[70726,70726,"NSM"],[70750,70750,"NSM"],[70835,70840,"NSM"],[70842,70842,"NSM"],[70847,70848,"NSM"],[70850,70851,"NSM"],[71090,71093,"NSM"],[71100,71101,"NSM"],[71103,71104,"NSM"],[71132,71133,"NSM"],[71219,71226,"NSM"],[71229,71229,"NSM"],[71231,71232,"NSM"],[71264,71276,"ON"],[71339,71339,"NSM"],[71341,71341,"NSM"],[71344,71349,"NSM"],[71351,71351,"NSM"],[71453,71453,"NSM"],[71455,71455,"NSM"],[71458,71461,"NSM"],[71463,71467,"NSM"],[71727,71735,"NSM"],[71737,71738,"NSM"],[71995,71996,"NSM"],[71998,71998,"NSM"],[72003,72003,"NSM"],[72148,72151,"NSM"],[72154,72155,"NSM"],[72160,72160,"NSM"],[72193,72198,"NSM"],[72201,72202,"NSM"],[72243,72248,"NSM"],[72251,72254,"NSM"],[72263,72263,"NSM"],[72273,72278,"NSM"],[72281,72283,"NSM"],[72330,72342,"NSM"],[72344,72345,"NSM"],[72544,72544,"NSM"],[72546,72548,"NSM"],[72550,72550,"NSM"],[72752,72758,"NSM"],[72760,72765,"NSM"],[72850,72871,"NSM"],[72874,72880,"NSM"],[72882,72883,"NSM"],[72885,72886,"NSM"],[73009,73014,"NSM"],[73018,73018,"NSM"],[73020,73021,"NSM"],[73023,73029,"NSM"],[73031,73031,"NSM"],[73104,73105,"NSM"],[73109,73109,"NSM"],[73111,73111,"NSM"],[73459,73460,"NSM"],[73472,73473,"NSM"],[73526,73530,"NSM"],[73536,73536,"NSM"],[73538,73538,"NSM"],[73562,73562,"NSM"],[73685,73692,"ON"],[73693,73696,"ET"],[73697,73713,"ON"],[78912,78912,"NSM"],[78919,78933,"NSM"],[90398,90409,"NSM"],[90413,90415,"NSM"],[92912,92916,"NSM"],[92976,92982,"NSM"],[94031,94031,"NSM"],[94095,94098,"NSM"],[94178,94178,"ON"],[94180,94180,"NSM"],[113821,113822,"NSM"],[113824,113827,"BN"],[117760,117973,"ON"],[118e3,118009,"EN"],[118010,118012,"ON"],[118016,118451,"ON"],[118458,118480,"ON"],[118496,118512,"ON"],[118528,118573,"NSM"],[118576,118598,"NSM"],[119143,119145,"NSM"],[119155,119162,"BN"],[119163,119170,"NSM"],[119173,119179,"NSM"],[119210,119213,"NSM"],[119273,119274,"ON"],[119296,119361,"ON"],[119362,119364,"NSM"],[119365,119365,"ON"],[119552,119638,"ON"],[120513,120513,"ON"],[120539,120539,"ON"],[120571,120571,"ON"],[120597,120597,"ON"],[120629,120629,"ON"],[120655,120655,"ON"],[120687,120687,"ON"],[120713,120713,"ON"],[120745,120745,"ON"],[120771,120771,"ON"],[120782,120831,"EN"],[121344,121398,"NSM"],[121403,121452,"NSM"],[121461,121461,"NSM"],[121476,121476,"NSM"],[121499,121503,"NSM"],[121505,121519,"NSM"],[122880,122886,"NSM"],[122888,122904,"NSM"],[122907,122913,"NSM"],[122915,122916,"NSM"],[122918,122922,"NSM"],[123023,123023,"NSM"],[123184,123190,"NSM"],[123566,123566,"NSM"],[123628,123631,"NSM"],[123647,123647,"ET"],[124140,124143,"NSM"],[124398,124399,"NSM"],[124643,124643,"NSM"],[124646,124646,"NSM"],[124654,124655,"NSM"],[124661,124661,"NSM"],[124928,125135,"R"],[125136,125142,"NSM"],[125143,125251,"R"],[125252,125258,"NSM"],[125259,126063,"R"],[126064,126143,"AL"],[126144,126207,"R"],[126208,126287,"AL"],[126288,126463,"R"],[126464,126703,"AL"],[126704,126705,"ON"],[126706,126719,"AL"],[126720,126975,"R"],[126976,127019,"ON"],[127024,127123,"ON"],[127136,127150,"ON"],[127153,127167,"ON"],[127169,127183,"ON"],[127185,127221,"ON"],[127232,127242,"EN"],[127243,127247,"ON"],[127279,127279,"ON"],[127338,127343,"ON"],[127405,127405,"ON"],[127584,127589,"ON"],[127744,128728,"ON"],[128732,128748,"ON"],[128752,128764,"ON"],[128768,128985,"ON"],[128992,129003,"ON"],[129008,129008,"ON"],[129024,129035,"ON"],[129040,129095,"ON"],[129104,129113,"ON"],[129120,129159,"ON"],[129168,129197,"ON"],[129200,129211,"ON"],[129216,129217,"ON"],[129232,129240,"ON"],[129280,129623,"ON"],[129632,129645,"ON"],[129648,129660,"ON"],[129664,129674,"ON"],[129678,129734,"ON"],[129736,129736,"ON"],[129741,129756,"ON"],[129759,129770,"ON"],[129775,129784,"ON"],[129792,129938,"ON"],[129940,130031,"ON"],[130032,130041,"EN"],[130042,130042,"ON"],[131070,131071,"BN"],[196606,196607,"BN"],[262142,262143,"BN"],[327678,327679,"BN"],[393214,393215,"BN"],[458750,458751,"BN"],[524286,524287,"BN"],[589822,589823,"BN"],[655358,655359,"BN"],[720894,720895,"BN"],[786430,786431,"BN"],[851966,851967,"BN"],[917502,917759,"BN"],[917760,917999,"NSM"],[918e3,921599,"BN"],[983038,983039,"BN"],[1048574,1048575,"BN"],[1114110,1114111,"BN"]];function SS(t){if(t<=255)return B1[t];let e=0,n=Ir.length-1;for(;e<=n;){let l=e+n>>1,i=Ir[l];if(ti[1]){e=l+1;continue}return i[2]}return"L"}function yS(t){let e=t.length;if(e===0)return null;let n=new Array(e),l=!1,i=0,a=null;for(let u=0;u=55296&&s<=56319&&u+1=56320&&m<=57343&&(c=(s-55296<<10)+(m-56320)+65536,r=2)}let f=SS(c);(f==="R"||f==="AL"||f==="AN")&&(l=!0);for(let m=0;m=n&&t[r]==="ET";r--)t[r]="EN";for(r=c+1;rn?t[c-1]:u,m=r0&&e.charCodeAt(e.length-1)===32&&(e=e.slice(0,-1)),e}function ES(t){return/[\r\f]/.test(t)?t.replace(/\r\n/g,` `).replace(/[\r\f]/g,` `):t}var Pr=null;function Dn(){return Pr===null&&(Pr=new Intl.Segmenter(void 0,{granularity:"grapheme"})),Pr}var to=null,NS;function MS(){return to===null&&(to=new Intl.Segmenter(NS,{granularity:"word"})),to}var CS=/\p{Script=Arabic}/u,We=/\p{M}/u,oa=/\p{Nd}/u;function O1(t){return CS.test(t)}var FS=/[\u3000-\u30FF\u3130-\u318F\u3400-\u4DBF\u4E00-\u9FFF\uAC00-\uD7AF\uF900-\uFAFF\uFF00-\uFFEF\u{20000}-\u{2A6DF}\u{2A700}-\u{2EE5D}\u{2F800}-\u{2FA1F}\u{30000}-\u{33479}]/u;function jt(t){return FS.test(t)}function DS(t){let e=fa(t);return e!==null&&(io.has(e)||tl.has(e))}var BS=new Set(["\xA0","\u202F","\u2060","\uFEFF"]),kS=new Set(["-","\u2010","\u2013","\u2014"]);function TS(t){let e=fa(t);return e!==null&&BS.has(e)}function OS(t){let e=fa(t);return e!==null&&kS.has(e)}function q1(t,e){return TS(t)?!1:e?!(DS(t)||OS(t)):!0}var io=new Set(["\uFF0C","\uFF0E","\uFF01","\uFF1A","\uFF1B","\uFF1F","\u3001","\u3002","\u30FB","\uFF09","\u3015","\u3009","\u300B","\u300D","\u300F","\u3011","\u3017","\u3019","\u301B","\u30FC","\u3005","\u303B","\u309D","\u309E","\u30FD","\u30FE"]),$u=new Set(['"',"(","[","{","\xA1","\xBF","\u201C","\u2018","\u201A","\u201E","\xAB","\u2039","\u2E18","\uFF08","\u3014","\u3008","\u300A","\u300C","\u300E","\u3010","\u3016","\u3018","\u301A"]),ao=new Set(["'","\u2019"]),tl=new Set([".",",","!","?",":",";","\u060C","\u061B","\u061F","\u0964","\u0965","\u104A","\u104B","\u104C","\u104D","\u104F",")","]","}","%",'"',"\u201D","\u2019","\xBB","\u203A","\u2026"]),RS=new Set([":",".","\u060C","\u061B"]),zS=new Set(["\u104F"]),wS=new Set(["\u201D","\u2019","\xBB","\u203A","\u300D","\u300F","\u3011","\u300B","\u3009","\u3015","\uFF09"]);function _S(t){if(uo(t))return!0;let e=!1;for(let n of t){if(tl.has(n)||el(n)){e=!0;continue}if(!(e&&We.test(n)))return!1}return e}function LS(t){for(let e of t)if(!io.has(e)&&!tl.has(e))return!1;return t.length>0}function qS(t){if(uo(t))return!0;for(let e of t)if(!$u.has(e)&&!ao.has(e)&&!We.test(e)&&!el(e))return!1;return t.length>0}function uo(t){let e=!1;for(let n of t)if(!(n==="\\"||We.test(n))){if($u.has(n)||tl.has(n)||ao.has(n)){e=!0;continue}return!1}return e}function Wl(t,e){let n=e-1;if(n<=0)return Math.max(n,0);let l=t.charCodeAt(n);if(l<56320||l>57343)return n;let i=n-1;if(i<0)return n;let a=t.charCodeAt(i);return a>=55296&&a<=56319?i:n}function fa(t){if(t.length===0)return null;let e=Wl(t,t.length);return t.slice(e)}function US(t){for(let e of t)if(!We.test(e))return e;return null}function so(t,e=t.length){for(;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(!We.test(l))return l;e=n}return null}var HS=[36,37,43,43,92,92,162,165,176,177,1423,1423,1545,1547,1642,1642,2046,2047,2546,2547,2553,2555,2801,2801,3065,3065,3449,3449,3647,3647,6107,6107,8240,8247,8279,8279,8352,8399,8451,8451,8457,8457,8470,8470,8722,8723,43064,43064,65020,65020,65129,65130,65284,65285,65504,65505,65509,65510,73693,73696,123647,123647,126124,126124,126128,126128];function GS(t,e){for(let n=0;n=e[n]&&t<=e[n+1])return!0;return!1}function el(t){let e=t.codePointAt(0);return e!==void 0&&GS(e,HS)}function YS(t){let e=so(t);return e!==null&&el(e)}function jS(t){let e=US(t);return e!==null&&oa.test(e)}function QS(t){let e=t.length;for(;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(We.test(l)||$u.has(l)||ao.has(l)){e=n;continue}break}return e<=0||e===t.length?null:{head:t.slice(0,e),tail:t.slice(e)}}function XS(t,e,n){return n==="text"&&!e&&t.length===1&&t!=="-"&&t!=="\u2014"?t:null}function R1(t,e){return t&&e!==null&&RS.has(e)}function ZS(t){let e=fa(t);return e!==null&&zS.has(e)}function VS(t){if(t.length<2||t[0]!==" ")return null;let e=t.slice(1);return/^\p{M}+$/u.test(e)?{space:" ",marks:e}:null}function no(t){let e=t.length;for(;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(wS.has(l))return!0;if(!tl.has(l))return!1;e=n}return!1}function KS(t,e){if(e==="pre-wrap"){if(t===" ")return"preserved-space";if(t===" ")return"tab";if(t===` -`)return"hard-break"}return t===" "?"space":t==="\xA0"||t==="\u202F"||t==="\u2060"||t==="\uFEFF"?"glue":t==="\u200B"?"zero-width-break":t==="\xAD"?"soft-hyphen":"text"}var JS=/[\x20\t\n\xA0\xAD\u200B\u202F\u2060\uFEFF]/;function Fn(t){return t.length===1?t[0]:t.join("")}function z1(t,e){let n=[];for(let l=t.length-1;l>=0;l--)n.push(t[l]);return n.push(e),Fn(n)}function WS(t,e,n,l){if(!JS.test(t))return[{text:t,isWordLike:e,kind:"text",start:n}];let i=[],a=null,u=0,s=!1,c=0;for(let r of t){let f=KS(r,l),m=f==="text"&&e;if(a!==null&&f===a&&m===s){c+=r.length;continue}a!==null&&i.push({text:t.slice(u,c),isWordLike:s,kind:a,start:n+u}),a=f,u=c,s=m,c+=r.length}return a!==null&&i.push({text:t.slice(u),isWordLike:s,kind:a,start:n+u}),i}function eo(t){return t==="space"||t==="preserved-space"||t==="zero-width-break"||t==="hard-break"}var $S=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function w1(t,e){let n=t.texts[e];return n.startsWith("www.")?!0:$S.test(n)&&e+1=t.len||eo(t.kinds[x]))continue;let g=[],y=o<0?t.starts[x]:o,N=x;for(;N0&&(l.push(Fn(g)),i.push(!0),a.push("text"),u.push(y),s=N-1)}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}var ty=new Set([":","-","/","\xD7",",",".","+","\u2013","\u2014"]),ey=/[\p{P}\p{S}\p{Co}]/u,U1=/\p{Emoji_Presentation}/u,ny=new Set(["?","\u058A","-","\u2010","\u2012","\u2013","\u2014","\u2026","\u203C","\u203D","\u2049"]);function ly(t){return t>=33&&t<=47&&t!==45||t>=58&&t<=64&&t!==63||t>=91&&t<=96||t>=123&&t<=126}function H1(t){let e=t.charCodeAt(0);return e<128?ly(e):!ny.has(t)&&!U1.test(t)&&ey.test(t)}function _1(t){let e=!1;for(let n of t)if(!We.test(n)){if(!H1(n))return!1;e=!0}return e}function iy(t){for(let e=t.length;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(We.test(l)){e=n;continue}return H1(l)||el(l)}return!1}var lo=/[A-Za-z#&*<=>@^_`~]/;function G1(t,e){return t.charCodeAt(0)<128&&e.charCodeAt(0)<128}function Je(t,e,n){if(!n.geckoAsciiLineBreaks||e<=0||e>=t.length)return null;let l=so(t,e),i=String.fromCodePoint(t.codePointAt(e));if(l===null||!G1(l,i))return null;let a=el(l),u=el(i);return!a&&!u?null:!!(i===")"||i==="]"||i==="}"||"!,.:;?/".includes(i)||"([{".includes(l)||l==='"'||l==="'"||i==='"'||i==="'"||i==="|"||i==="-"||a&&lo.test(i)||lo.test(l)&&u||u&&(")]}".includes(l)||/[0-9]/.test(l))||a&&("([{".includes(i)||/[0-9]/.test(i)))}function Wu(t,e,n,l=t.length){let i=e[0];if(i===void 0||!"([{".includes(i))return null;let a=so(t,l);return a===null?null:n.geckoAsciiLineBreaks&&G1(a,i)?lo.test(a)||oa.test(a)||`"'([{`.includes(a)||el(a):a.charCodeAt(0)>=128?!jt(a)&&/[\p{L}\p{N}]/u.test(a)?!0:null:/[A-Za-z0-9]/.test(a)||"$'(/<@[^_`{".includes(a)}function ay(t,e,n,l,i){if(n[0]==="-"&&jt(t))return!0;if(jt(t)||jt(n))return!1;let a=Wu(t,n,i);if(a!==null)return a;let u=!e&&_1(t),s=!l&&_1(n),c=YS(t),r=(e||c)&&iy(t);return!u&&!s&&!r?!1:(e||u||c)&&(l||s)}function L1(t){for(let e of t)if(oa.test(e))return!0;return!1}function ra(t){if(t.length===0)return!1;for(let e of t)if(!(oa.test(e)||ty.has(e)))return!1;return!0}function uy(t,e,n){let l=[],i=[],a=[],u=[];function s(c,r){if(c.includes("-")){let f=c.split("-"),m=f.length>1;for(let o=0;os+1){l.push(Fn(m)),i.push(x),a.push("text"),u.push(t.starts[s]),s=o;continue}}l.push(c),i.push(f),a.push(r),u.push(t.starts[s]),s++}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function cy(t){let e=[],n=[],l=[],i=[],a=0;for(;a=0;v--){let A=a[v];if(A.length===0)continue;let B=M?.at(-1)??(S>=0?a[S]:null);if(s[v]==="text"&&!u[v]&&B!==null&&s[S]==="text"&&((Je(t,c[v]+A.length,e)??(qS(A)&&Wu(A,B,e)!==!1))||A==="-"&&jS(B))){M===null&&(M=[]),M.push(A),c[S]=c[v],a[v]="";continue}M!==null&&(a[S]=z1(M,a[S]),M=null),S=v}M!==null&&(a[S]=z1(M,a[S]));let F=0;for(let v=0;v=0&&(!q1(e.texts[o-1],n.breakKeepAllAfterPunctuation)||Je(t,e.starts[o],n)===!1)&&m(o),s<0&&(s=o),c=c||jt(x);continue}m(o),l.push(x),i.push(e.isWordLike[o]),a.push(g),u.push(e.starts[o])}return m(e.len),{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function Y1(t,e){let n=t.charCodeAt(e+1);if(n<128){if(n<48||n>57)return!1}else{let l=t.codePointAt(e+1);if(l===void 0||!oa.test(String.fromCodePoint(l)))return!1}for(let l=e;l>0;){let i=Wl(t,l),a=t.slice(i,l);if(!We.test(a))return jt(a)||!/[\p{L}\p{N}]/u.test(a);l=i}return!0}function dy(t,e){let n=[],l=0,i=0,a=!1,u=!1,s=!1,c=!1,r=!1;function f(){i!==l&&(n.push({text:t.slice(l,i),start:l,overflow:a?c?"grapheme":"none":"word-like"}),l=i,a=!1,u=!1,s=!1,c=!1,r=!1)}function m(x,g,y){l=g,i=g+x.length,a=y,c=x==="-",u=no(x),s=$u.has(x)}function o(x,g){i+=x.length,a=a||g,c=c||x==="-";let y=no(x);x.length===1&&tl.has(x)?u=u||y:u=y,s=!1}for(let x of Dn().segment(t)){let g=x.segment,y=jt(g);if(i===l){m(g,x.index,y);continue}let N=g==="-"&&a;if(N&&Y1(t,x.index)&&(r=!0),s||io.has(g)||tl.has(g)||N||r&&!y||e.carryCJKAfterClosingQuote&&y&&u){o(g,y);continue}if(!a&&!y){o(g,y);continue}f(),m(g,x.index,y)}return f(),n}function hy(t,e,n){if(e.length<=1)return e;let l=[],i=-1,a=!1;function u(c,r){let f=e[c].start,m=r=0&&(!q1(e[c-1].text,n.breakKeepAllAfterPunctuation)||Je(t,r.start,n)===!1)&&s(c),i<0&&(i=c),a=a||jt(r.text)}return s(e.length),l}function j1(t,e,n){let l=dy(t,e);return n==="keep-all"?hy(t,l,e):l}function xy(t){return t==="-"||t==="\u058A"||t==="\u2010"||t==="\u2012"||t==="\u2013"||t==="\u2014"}function Q1(t){if(t.length===0||/\p{Cf}/u.test(t))return!1;for(let{segment:e}of Dn().segment(t)){let n=String.fromCodePoint(e.codePointAt(0));if(!/[\p{P}\p{S}]/u.test(n)||U1.test(n)||e.includes("\uFE0F")||/\p{Emoji_Modifier}/u.test(n))return!1}return!0}function X1(t){if(!/[-\u058A\u2010\u2012\u2013\u2014]/u.test(t))return null;let e=[],n=0;for(let l of Dn().segment(t)){n++;let i=l.segment==="-"&&Y1(t,l.index);xy(l.segment)&&!i&&e.push(n)}return e.length===0?null:e}function Z1(t,e,n="normal",l="normal"){let i=n==="pre-wrap"?ES(t):bS(t);if(i.length===0)return{normalized:i,len:0,texts:[],isWordLike:[],kinds:[],starts:[]};let a=oy(i,e,n),u=l==="keep-all"?fy(i,a,e):a;return{normalized:i,...u}}var $l=null,V1=new Map,Il=null,my=96,py=/\p{Emoji_Presentation}/u,gy=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u,K1=new Map;function co(){if($l!==null)return $l;if(typeof OffscreenCanvas<"u")return $l=new OffscreenCanvas(1,1).getContext("2d"),$l;if(typeof document<"u")return $l=document.createElement("canvas").getContext("2d"),$l;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function Sy(t){let e=V1.get(t);return e||(e=new Map,V1.set(t,e)),e}function $e(t,e){let n=e.get(t);return n===void 0&&(n={width:co().measureText(t).width},e.set(t,n)),n}function Pl(){if(Il!==null)return Il;if(typeof navigator>"u")return Il={geckoAsciiLineBreaks:!1,lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,breakKeepAllAfterPunctuation:!0,preferPrefixWidthsForBreakableRuns:!1},Il;let t=navigator.userAgent,n=navigator.vendor==="Apple Computer, Inc."&&t.includes("Safari/")&&!t.includes("Chrome/")&&!t.includes("Chromium/")&&!t.includes("CriOS/")&&!t.includes("FxiOS/")&&!t.includes("EdgiOS/"),l=t.includes("Chrome/")||t.includes("Chromium/")||t.includes("CriOS/")||t.includes("Edg/");return Il={geckoAsciiLineBreaks:t.includes("Firefox/")&&!t.includes("FxiOS/"),lineFitEpsilon:n?1/64:.005,carryCJKAfterClosingQuote:l,breakKeepAllAfterPunctuation:!n,preferPrefixWidthsForBreakableRuns:n},Il}function yy(t){let e=t.match(/(?:^|\D)(\d+(?:\.\d+)?)\s*px/);return e?parseFloat(e[1]):16}function vy(t){return py.test(t)||t.includes("\uFE0F")}function J1(t){return gy.test(t)}function Ay(t){let e=K1.get(t);if(e!==void 0)return e;let n=yy(t),l=co();l.font=t;let i=l.measureText("\u{1F600}").width;if(e=0,i>n+.5&&typeof document<"u"&&document.body!==null){let a=document.createElement("span");a.style.font=t,a.style.display="inline-block",a.style.visibility="hidden",a.style.position="absolute",a.textContent="\u{1F600}",document.body.appendChild(a);let u=a.getBoundingClientRect().width;document.body.removeChild(a),i-u>.5&&(e=i-u)}return K1.set(t,e),e}function by(t){let e=0,n=Dn();for(let l of n.segment(t))vy(l.segment)&&e++;return e}function Ey(t,e){return e.emojiCount===void 0&&(e.emojiCount=by(t)),e.emojiCount}function Bn(t,e,n){return n===0?e.width:e.width-Ey(t,e)*n}function W1(t,e,n,l,i){if(e.breakableFitAdvances!==void 0&&e.breakableFitMode===i)return e.breakableFitAdvances;e.breakableFitMode=i;let a=Dn(),u=[];for(let f of a.segment(t))u.push(f.segment);if(u.length<=1)return e.breakableFitAdvances=null,e.breakableFitAdvances;if(i==="sum-graphemes"){let f=[];for(let m of u){let o=$e(m,n);f.push(Bn(m,o,l))}return e.breakableFitAdvances=f,e.breakableFitAdvances}if(i==="pair-context"||u.length>my){let f=[],m=null,o=0;for(let x of u){let g=$e(x,n),y=Bn(x,g,l);if(m===null)f.push(y);else{let N=m+x,h=$e(N,n);f.push(Bn(N,h,l)-o)}m=x,o=y}return e.breakableFitAdvances=f,e.breakableFitAdvances}let s=[],c="",r=0;for(let f of u){c+=f;let m=$e(c,n),o=Bn(c,m,l);s.push(o-r),r=o}return e.breakableFitAdvances=s,e.breakableFitAdvances}function $1(t,e){let n=co();n.font=t;let l=Sy(t),i=e?Ay(t):0;return{cache:l,emojiCorrection:i}}function Ny(t,e,n){return n===0&&e>0&&e0?t.letterSpacing:0}function oo(t,e){return e===0?0:t+e}function Dy(t,e){return t.letterSpacing!==0&&t.spacingGraphemeCounts[e]>0?t.letterSpacing:0}function By(t,e,n,l,i){let a=e==="tab"?i+Dy(t,n):t.lineEndFitAdvances[n];return oo(l,a)}function I1(t,e,n,l){let i=e==="tab"?0:t.lineEndFitAdvances[n];return oo(l,i)}function P1(t,e,n,l,i){let a=e==="tab"?i:t.lineEndPaintAdvances[n];return oo(l,a)}function ky(t,e,n){return t.letterSpacing!==0&&e?n+t.letterSpacing:n}function Ty(t,e){return t.letterSpacing===0?e:e+t.letterSpacing}function ro(t,e,n){let l=e;if(l>=t.length||t[l]>=n)return l;let i=t.length;for(l++;l0)return t.spacingGraphemeCounts[l]>0?t.letterSpacing:0;if(Ny(t.kinds,l,i))return 0;for(let a=l-1;a>=e;a--){let u=t.kinds[a];if(!(u==="space"||u==="zero-width-break"||u==="hard-break"||u==="soft-hyphen"))return a===e&&n>0||t.spacingGraphemeCounts[a]>0?t.letterSpacing:0}return 0}function Ry(t,e,n,l,i,a){return e+Oy(t,n,l,i,a)}function zy(t,e){let n=0,l=t.chunks.length;for(;n0)return e;for(let i=e;i=t.widths.length)return-1;l=a.consumedEndSegmentIndex,n.segmentIndex=l,n.graphemeIndex=0}return-1}function lx(t,e){if(e.segmentIndex>=t.widths.length)return-1;let n=zy(t,e.segmentIndex);return n<0?-1:nx(t,n,e)}function wy(t,e,n){if(n.segmentIndex>=t.widths.length)return-1;let l=e;for(;l=t.chunks[l].consumedEndSegmentIndex;)l++;return l>=t.chunks.length?-1:nx(t,l,n)}function ix(t,e){return ax(t,e)}function _y(t,e,n){let{widths:l,kinds:i,breakableFitAdvances:a,breakablePreferredBreaks:u}=t;if(l.length===0)return 0;let c=Pl().lineFitEpsilon,r=e+c,f=0,m=0,o=!1,x=0,g=0,y=0,N=0,h=-1,d=0;function p(){h=-1,d=0}function S(A=y,B=N,L=m){f++,n?.(L,x,g,A,B),m=0,o=!1,p()}function M(A,B){o=!0,x=A,g=0,y=A+1,N=0,m=B}function F(A,B,L){o=!0,x=A,g=B,y=A,N=B+1,m=L}function C(A,B){if(!o){M(A,B);return}m+=B,y=A+1,N=0}function E(A,B){let L=a[A],_=u[A]??null,et=_===null?-1:ro(_,0,B+1),Z=-1,rt=0,k=B;for(;kr){if(_!==null&&Z>B){S(A,Z,rt),k=Z,et=ro(_,et,k+1),Z=-1,rt=0;continue}S(),F(A,k,R)}else m+=R,y=A,N=k+1;let O=k+1;_!==null&&_[et]===O&&(Z=O,rt=m,et++),k++}o&&y===A&&N===L.length&&(y=A+1,N=0)}let v=0;for(;v=l.length));){let A=l[v],B=i[v],L=tx(B);if(!o){A>r&&a[v]!==null?E(v,0):M(v,A),L&&(h=v+1,d=m-A),v++;continue}if(m+A>r){if(L){C(v,A),S(v+1,0,m-A),v++;continue}if(h>=0){if(y>h||y===h&&N>0){S();continue}S(h,0,d);continue}if(A>r&&a[v]!==null){S(),E(v,0),v++;continue}S();continue}C(v,A),L&&(h=v+1,d=m-A),v++}return o&&S(),f}function ax(t,e,n){if(t.simpleLineWalkFastPath)return _y(t,e,n);let l={segmentIndex:0,graphemeIndex:0},i=lx(t,l);return Ly(t,l,i,e,n).lineCount}function Ly(t,e,n,l,i,a=Number.POSITIVE_INFINITY){let{widths:u,kinds:s,breakableFitAdvances:c,breakablePreferredBreaks:r,discretionaryHyphenWidth:f}=t,o=Pl().lineFitEpsilon,x=l+o,g,y,N,h,d,p,S,M,F,C;function E(){return C==="soft-hyphen"&&S===d&&p===0?F:N}function v(k=d,R=p,O=E()){return h?(e.segmentIndex=k,e.graphemeIndex=R,Ry(t,O,g,y,k,R)):null}function A(k,R){h=!0,d=k+1,p=0,N=R}function B(k,R,O){h=!0,d=k,p=R+1,N=O}function L(k,R){if(!h){A(k,R);return}N+=R,d=k+1,p=0}function _(k,R,O,J,zt,Xt){if(!R)return;let wt=I1(t,k,O,zt),Bt=P1(t,k,O,zt,J);S=O+1,M=N-Xt+wt,F=N-Xt+Bt,C=k}function et(k,R){let O=c[k],J=r[k]??null,zt=J===null?-1:ro(J,0,R+1),Xt=-1,wt=0;for(let Bt=R;Btx)return J!==null&&Xt>R?v(k,Xt,wt):v();N=Se,d=k,p=Bt+1}let li=Bt+1;J!==null&&J[zt]===li&&(Xt=li,wt=N,zt++)}return h&&d===k&&p===O.length&&(d=k+1,p=0),null}let Z=0,rt=null;for(;n>=0&&Z0){let Se=et(O,Xt);if(Se!==null){R=Se;break t}}else if(li>x&&c[O]!==null){let Se=et(O,0);if(Se!==null){R=Se;break t}}else A(O,Bt);_(J,zt,O,Bt,wt,kn);continue}if(N+li>x){let Se=N+I1(t,J,O,wt),kx=N+P1(t,J,O,wt,Bt);if(zt&&Se<=x){L(O,kn),R=v(O+1,0,kx);break t}if(S>=0&&M<=x){if(d>S||d===S&&p>0){R=v();break t}R=v(S,0,F);break t}R=v();break t}L(O,kn),_(J,zt,O,Bt,wt,kn)}R===null&&(R=S===k.consumedEndSegmentIndex&&p===0?v(k.consumedEndSegmentIndex,0,F):v(k.consumedEndSegmentIndex,0,N))}if(R===null)break;rt=R,Z++,i?.(R,g,y,e.segmentIndex,e.graphemeIndex),Z1?t+(e-1)*n:t}function Hy(t,e,n,l,i){let a=Pl(),{cache:u,emojiCorrection:s}=$1(e,J1(t.normalized)),c=Bn("-",$e("-",u),s)+(i===0?0:i*2),f=Bn(" ",$e(" ",u),s)*8,m=i!==0;if(t.len===0)return qy(n);let o=[],x=[],g=[],y=[],N=!m,h=n?[]:null,d=[],p=[],S=[],M=n?[]:null,F=[],C=0;function E(B,L,_,et,Z,rt,k,R,O){Z!=="text"&&Z!=="space"&&Z!=="zero-width-break"&&(N=!1),o.push(L),x.push(_),g.push(et),y.push(Z),h?.push(rt),d.push(k),p.push(R),m&&S.push(O),M!==null&&M.push(B)}function v(B,L,_,et,Z){let rt=m?ux(B,_):0,k=Uy(Bn(B,L,s),rt,i),R=_==="space"||_==="preserved-space"||_==="zero-width-break"?0:k,O=R===0?0:R+(rt>0?i:0),J=_==="space"||_==="zero-width-break"?0:k;if(Z&&B.length>1){let zt="sum-graphemes";i!==0?zt="segment-prefixes":ra(B)?zt="pair-context":a.preferPrefixWidthsForBreakableRuns&&(zt="segment-prefixes");let Xt=W1(B,L,u,s,zt),wt=Xt===null||l==="keep-all"?null:X1(B);E(B,k,O,J,_,et,Xt,wt,rt);return}E(B,k,O,J,_,et,null,null,rt)}for(let B=0;B[u.id,u])),l=[],i=[];for(let u of e){let s=t.get(u.id);s?s.version!==u.version&&i.push(u):l.push(u)}let a=[...t.keys()].filter(u=>!n.has(u));return{added:l,updated:i,removed:a}}function ho(t,e){let n=Math.max(1,Math.ceil((t.text?.length??0)/Math.max(24,Math.floor(e/8))));return t.kind==="activity"?Math.max(46,24+(t.items?.length??0)*20):t.kind==="turnSummary"||t.kind==="notice"||t.kind==="typing"?32:24+n*ox}function Yy(t,e,n){if(!t.text)return ho(t,e);let i=n.get(t.id)??{version:t.version,text:t.text,prepared:null,blocks:new Map};if(i.version=t.version,i.text=t.text,!i.blocks.size)try{i.prepared=fo(t.text,cx,{whiteSpace:"pre-wrap"})}catch{i.prepared=null}n.set(t.id,i);let a=Math.max(80,e-(t.kind==="user"?120:0)),u=t.text.split(/\n{2,}/).filter(Boolean);if(u.length===0)return ho(t,e);let s=0;for(let c of u){let r=i.blocks.get(c);if(!r)try{r=fo(c,cx,{whiteSpace:"pre-wrap"}),i.blocks.set(c,r)}catch{return ho(t,e)}s+=sx(r,a,ox).height}return Math.max(34,16+s+Math.max(0,u.length-1)*8)}function dx(t,e,n=new Map,l){let i=new Float64Array(t.length),a=new Float64Array(t.length),u=0;for(let s=0;s0?c:Yy(t[s],e,n);a[s]=r,u+=r}return{tops:i,heights:a,totalHeight:u}}function rx(t,e){let n=0,l=t.length;for(;n>>1;t[i]<=e?n=i+1:l=i}return n}function hx(t,e,n,l=4){if(t.tops.length===0)return{first:0,last:0};let i=Math.max(0,rx(t.tops,Math.max(0,e))-1-l),a=Math.min(t.tops.length,rx(t.tops,e+n)+l);return{first:i,last:a}}function jy(t,e){let n=t??{},l=n?.request??n,i=n?.sessionId??l?.sessionId,a=n?.permissionId??l?.permissionId;if(!(!a||i!==e))return{permissionId:String(a),title:l.toolCall?.title,kind:l.toolCall?.kind,pending:!0,options:(l.options??[]).map(u=>({id:String(u.optionId??u.id),name:String(u.name??u.optionId),allow:String(u.kind??"").startsWith("allow")}))}}function Qy(t,e,n){let l=typeof n?.promptId=="string"?n.promptId:void 0;if(!l)return;let i=e.get(l);i&&t.delete(i),e.delete(l)}function xo(...t){let e=new Map;for(let n of t.flat())e.set(n.seq,n);return[...e.values()].sort((n,l)=>n.seq-l.seq)}function Xy(t,e,n,l){n.add(l);let i=e.get(l);i&&t.delete(i),e.delete(l)}function Zy(t,e,n){return t||(n?void 0:e[0]?.sessionId)}function xx(t){return typeof t=="string"?t:t?.type==="text"?String(t.text??""):Array.isArray(t)?t.map(xx).join(""):""}function Vy(t){return t.dir==="in"&&t.msg.method==="session/update"?t.msg.params?.update:void 0}var Iu=class t{socket;nextRequest=1;pending=new Map;events=[];rows=new Map;sessions=[];selectedSessionId;summary;catalog=[];queue=[];pendingPermission;optimisticPromptRows=new Map;optimisticPromptTexts=new Map;firstSeq;lastSeq=0;turnOpen=!1;streamingAssistant;streamingAssistantMessageId;streamingActivity;supersededMessageIds=new Set;messageRows=new Map;listener;host;reconnectTimer;reconnectDelay=250;onLost;opening=!1;hasConnected=!1;closed=!1;selectionGeneration=0;historyExhausted=!1;constructor(e,n,l){this.host=e,this.listener=n,this.onLost=l,this.selectedSessionId=e.sessionId}static async connect(e,n,l){let i=new t(e,n,l);return await i.open(),i}async open(){if(this.opening||this.closed)return;this.opening=!0;let e=new URL(this.host.endpoint);e.searchParams.set("token",this.host.token),await new Promise((n,l)=>{let i=new WebSocket(e);this.socket=i;let a=!1;i.onopen=()=>{a=!0,n()},i.onerror=()=>{this.opening=!1,l(new Error("Unable to connect to acpmux WebSocket"))},i.onclose=()=>{if(this.socket===i){if(!a){this.opening=!1,l(new Error("acpmux WebSocket closed before connect"));return}for(let u of this.pending.values())u.reject(new Error("acpmux WebSocket closed"));if(this.pending.clear(),this.emit("disconnected"),!(!this.hasConnected||this.closed))if(this.onLost){let u=this.onLost;this.close(),u()}else this.scheduleReconnect()}},i.onmessage=u=>this.receive(String(u.data))});try{await this.request("initialize",{protocolVersion:1,clientInfo:{name:"cmux-react-agent-pane",version:"1"},clientCapabilities:{}});let n=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(n?.sessions??[]).filter(i=>i.sessionId);let l=await this.request("_acpmux/harnesses",{});this.catalog=Ky(l),this.selectedSessionId&&!this.sessions.some(i=>i.sessionId===this.selectedSessionId)&&(this.selectedSessionId=this.sessions[0]?.sessionId,this.resetSessionState()),this.selectedSessionId=Zy(this.selectedSessionId,this.sessions,this.host.newSession),this.selectedSessionId&&await this.attach(this.selectedSessionId),this.hasConnected=!0,this.reconnectDelay=250,this.emit("connected")}catch(n){throw this.socket?.close(),n}finally{this.opening=!1}}resetSessionState(){this.events=[],this.historyExhausted=!1,this.rows.clear(),this.firstSeq=void 0,this.lastSeq=0,this.summary=void 0,this.queue=[],this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.optimisticPromptRows.clear(),this.optimisticPromptTexts.clear(),this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0}scheduleReconnect(){if(this.reconnectTimer!==void 0||this.closed)return;let e=this.reconnectDelay;this.reconnectDelay=Math.min(e*2,3e4),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=void 0,this.open().catch(()=>this.scheduleReconnect())},e)}receive(e){let n;try{n=JSON.parse(e)}catch{return}if("id"in n&&typeof n.id=="number"){let i=this.pending.get(n.id);if(!i)return;this.pending.delete(n.id),n.error?i.reject(new Error(n.error.message??"acpmux request failed")):i.resolve(n.result);return}let l=n;l.method==="_acpmux/event"?this.apply(l.params):l.method==="session/update"?this.apply({sessionId:l.params?.sessionId,seq:Number(l.params?._meta?.acpmux?.seq??0),at:Number(l.params?._meta?.acpmux?.at??Date.now()),dir:"in",kind:String(l.params?.update?.sessionUpdate??""),msg:{method:"session/update",params:{update:l.params?.update}}}):l.method==="_acpmux/session_changed"?this.sessionChanged(l.params):l.method==="_acpmux/permission_pending"?this.applyPermission(l.params):l.method==="_acpmux/lagged"&&this.resyncAfterLag(l.params)}resyncAfterLag(e){e?.watch===!0&&this.refreshSessions().catch(()=>{});let n=this.selectedSessionId;n&&(Array.isArray(e?.sessionIds)&&!e.sessionIds.map(String).includes(n)||(this.emit("resyncing"),this.fetchMissedEvents(n,this.selectionGeneration).catch(()=>{})))}async fetchMissedEvents(e,n){for(;;){let l=await this.request("_acpmux/events",{sessionId:e,afterSeq:this.lastSeq,limit:5e3});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=l?.events??[];if(this.events=xo(this.events,i),this.rebuild(),l?.more!==!0||i.length===0)break}this.emit("resynced")}async refreshSessions(){let e=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(e?.sessions??[]).filter(n=>n.sessionId),this.emit("session changed")}request(e,n){if(this.socket?.readyState!==WebSocket.OPEN)return Promise.reject(new Error("acpmux WebSocket is not open"));let l=this.nextRequest++;return new Promise((i,a)=>{this.pending.set(l,{resolve:i,reject:a}),this.socket.send(JSON.stringify({jsonrpc:"2.0",id:l,method:e,params:n}))})}async attach(e,n=this.selectionGeneration){if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let l=await this.request("_acpmux/attach",{sessionId:e,limit:400,kinds:["transcript"],eventStream:!0});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=l?.session??{};this.summary=i,this.queue=(i.queue??[]).map(a=>({id:String(a.promptId),prompt:String(a.prompt??"")})),this.events=xo(l?.events??[],this.events),this.rebuild(),this.emit("attached")}sessionChanged(e){let n=e?.session;if(e?.kind==="purged"&&n?.sessionId){if(this.sessions=this.sessions.filter(l=>l.sessionId!==n.sessionId),n.sessionId===this.selectedSessionId){this.selectedSessionId=this.sessions[0]?.sessionId;let l=++this.selectionGeneration;this.resetSessionState(),this.emit("session purged"),this.selectedSessionId&&this.attach(this.selectedSessionId,l).catch(()=>{})}else this.emit("session purged");return}n?.sessionId&&(this.sessions=[...this.sessions.filter(l=>l.sessionId!==n.sessionId),n],n.sessionId===this.selectedSessionId&&(this.summary={...this.summary,...n},this.queue=(n.queue??this.queue).map(l=>({id:String(l.promptId),prompt:String(l.prompt??l.preview??"")}))),this.emit("session changed"))}applyPermission(e){let n=jy(e,this.selectedSessionId??"");n&&(this.pendingPermission=n,this.emit("permission"))}apply(e){!e?.seq||e.sessionId!==this.selectedSessionId||e.seq<=this.lastSeq||(this.events.push(e),this.lastSeq=e.seq,this.firstSeq=this.firstSeq===void 0?e.seq:Math.min(this.firstSeq,e.seq),this.reduce(e),this.emit(e.kind))}rebuild(){let e=[...this.optimisticPromptRows.values()].flatMap(l=>this.rows.get(l)??[]);this.rows.clear();for(let l of e)this.rows.set(l.id,l);this.firstSeq=void 0,this.lastSeq=0,this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0;let n=[...this.events].sort((l,i)=>l.seq-i.seq);for(let l of n)this.lastSeq=Math.max(this.lastSeq,l.seq),this.firstSeq=this.firstSeq===void 0?l.seq:Math.min(this.firstSeq,l.seq),this.reduce(l)}reduce(e){let n=e.msg??{},l=Vy(e);if(e.dir==="mux"){if(e.kind==="user_message"){let a=typeof n.promptId=="string"?n.promptId:void 0,u=typeof n.text=="string"?n.text:void 0,s=a??(u?[...this.optimisticPromptTexts.entries()].find(([,c])=>c===u)?.[0]:void 0);Qy(this.rows,this.optimisticPromptRows,{...n,promptId:s}),s&&this.optimisticPromptTexts.delete(s),this.rows.set(`user-${e.seq}`,{id:`user-${e.seq}`,version:1,at:e.at,kind:"user",text:String(n.text??"")}),this.turnOpen=!0}else if(e.kind==="turn_started")this.turnOpen=!0,this.rows.set("typing",{id:"typing",version:1,at:e.at,kind:"typing"});else if(e.kind==="message_superseded"){let a=typeof n.oldMessageId=="string"?n.oldMessageId:void 0;a&&(Xy(this.rows,this.messageRows,this.supersededMessageIds,a),this.streamingAssistantMessageId===a&&(this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0))}else if(e.kind==="turn_end"||e.kind==="turn_result"){if(this.turnOpen=!1,this.streamingAssistant){let a=this.rows.get(this.streamingAssistant);a&&(a.streaming=!1,a.version+=1)}this.rows.delete("typing"),e.kind==="turn_result"&&this.rows.set(`summary-${e.seq}`,{id:`summary-${e.seq}`,version:1,at:e.at,kind:"turnSummary",durationMs:void 0,toolCount:[...this.rows.values()].filter(a=>a.kind==="activity").length,status:String(n.status??"completed"),error:n.errorText}),this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0}else if(e.kind==="queued"||e.kind==="queue_updated"){let a=String(n.promptId??"");a&&(this.queue=[...this.queue.filter(u=>u.id!==a),{id:a,prompt:String(n.text??"")}])}else e.kind==="queue_removed"||e.kind==="dequeued"?this.queue=this.queue.filter(a=>a.id!==String(n.promptId??"")):e.kind==="permission_request"?this.applyPermission({...n,sessionId:e.sessionId}):e.kind==="permission_decision"?this.pendingPermission=void 0:e.kind==="status"&&(this.summary={...this.summary,status:n.status});return}if(!l)return;let i=xx(l.content);if(e.kind==="agent_message_chunk"&&i){let a=typeof l.messageId=="string"?l.messageId:void 0;if(a&&this.supersededMessageIds.has(a))return;let s=!!(this.streamingAssistant&&(!a||!this.streamingAssistantMessageId||this.streamingAssistantMessageId===a))?this.streamingAssistant:`assistant-${e.seq}`,c=this.rows.get(s);this.rows.set(s,{id:s,version:(c?.version??0)+1,at:e.at,kind:"assistant",text:`${c?.text??""}${i}`,streaming:!0}),this.streamingAssistant=s,this.streamingAssistantMessageId=a,a&&this.messageRows.set(a,s),this.rows.delete("typing")}else if(e.kind==="agent_thought_chunk"&&i){let a=this.streamingActivity??`activity-${e.seq}`,u=this.rows.get(a);this.rows.set(a,{id:a,version:(u?.version??0)+1,at:e.at,kind:"activity",toolCount:u?.toolCount??0,items:[...u?.items??[],{kind:"thought",text:i}]}),this.streamingActivity=a}else if(e.kind==="tool_call"||e.kind==="tool_call_update"){let a=String(l.toolCallId??`tool-${e.seq}`),u=this.streamingActivity??`activity-${e.seq}`,s=this.rows.get(u),c=[...s?.items??[]],r=c.findIndex(m=>m.tool?.id===a),f={kind:"tool",text:String(l.title??l.name??a),tool:{id:a,title:String(l.title??a),kind:l.kind,status:String(l.status??"in_progress"),inputSummary:l.rawInput?JSON.stringify(l.rawInput):void 0,output:i||void 0}};r>=0?c[r]=f:c.push(f),this.rows.set(u,{id:u,version:(s?.version??0)+1,at:e.at,kind:"activity",toolCount:c.filter(m=>m.kind==="tool").length,items:c}),this.streamingActivity=u}else e.kind==="plan"&&this.rows.set(`plan-${e.seq}`,{id:`plan-${e.seq}`,version:1,at:e.at,kind:"plan",text:i||JSON.stringify(l.entries??l.content??"")})}emit(e="connected"){let n=this.summary,l=(n?.configOptions??[]).find(i=>i.category==="thought_level"||i.id==="reasoning_effort");this.listener({type:"snapshot",protocolVersion:1,rows:[...this.rows.values()].sort((i,a)=>i.at-a.at),sessions:this.sessions.map(i=>({sessionId:i.sessionId,displayTitle:i.title??i.name,title:i.title,name:i.name,status:i.status,model:i.model})),summary:n?{sessionId:n.sessionId,title:n.title,name:n.name,harness:n.harness,model:n.model,effort:l?.currentValue,status:n.status,modes:n.modes,configOptions:n.configOptions}:void 0,connection:e,sessionId:this.selectedSessionId,isWorking:this.turnOpen||n?.status==="running",queue:this.queue,permission:this.pendingPermission,catalog:this.catalog,canLoadOlder:!this.historyExhausted&&(this.firstSeq??1)>1})}snapshot(){this.emit()}async ensureSession(){return this.selectedSessionId||await this.create(),this.selectedSessionId}async send(e){let n=await this.ensureSession();if(!n)return;let l=crypto.randomUUID(),i=`local-${l}`,a=Date.now();this.optimisticPromptRows.set(l,i),this.optimisticPromptTexts.set(l,e),this.rows.set(i,{id:i,version:1,at:a,kind:"user",text:e,pending:!0}),this.emit();try{await this.request("session/prompt",{sessionId:n,prompt:[{type:"text",text:e}],_meta:{acpmux:{promptId:l}}})}catch(u){let s=this.rows.get(i);throw s&&(s.pending=!1,s.failed=!0,s.version+=1),this.optimisticPromptRows.delete(l),this.optimisticPromptTexts.delete(l),this.emit("failed"),u}return n}async cancel(){this.selectedSessionId&&this.socket?.send(JSON.stringify({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:this.selectedSessionId}}))}async permission(e,n){this.selectedSessionId&&await this.request("_acpmux/permission_respond",{sessionId:this.selectedSessionId,permissionId:e,optionId:n})}async select(e){let n=this.selectedSessionId,l=++this.selectionGeneration;return this.selectedSessionId=e,this.resetSessionState(),n&&await this.request("_acpmux/detach",{sessionId:n}),await this.attach(e,l),l===this.selectionGeneration&&this.selectedSessionId===e?e:void 0}async create(e){let n=await this.request("session/new",{mcpServers:[],_meta:{acpmux:{harness:e}}});if(n?.sessionId)return this.select(String(n.sessionId))}async setModel(e){this.selectedSessionId&&await this.request("session/set_model",{sessionId:this.selectedSessionId,modelId:e})}async setMode(e){this.selectedSessionId&&await this.request("session/set_mode",{sessionId:this.selectedSessionId,modeId:e})}async setConfig(e,n){this.selectedSessionId&&await this.request("session/set_config_option",{sessionId:this.selectedSessionId,configId:e,value:n})}async loadOlder(){if(!this.selectedSessionId||!this.firstSeq||this.firstSeq<=1||this.historyExhausted)return;let e=this.selectedSessionId,n=this.selectionGeneration,l=await this.request("_acpmux/events",{sessionId:e,beforeSeq:this.firstSeq,limit:400,kinds:["transcript"]});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=this.summary,a=this.queue,u=this.pendingPermission,s=l?.events??[];this.events=xo(s,this.events),this.rebuild(),this.summary=i,this.queue=a,this.pendingPermission=u,this.historyExhausted=l?.more===!1||s.length===0||(this.firstSeq??1)<=1,this.emit("history")}close(){this.closed=!0,this.reconnectTimer!==void 0&&window.clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close(),this.socket=void 0}};function Ky(t){let e=t?.harnesses??t?.items??t??[];return(Array.isArray(e)?e:Object.entries(e).map(([n,l])=>({id:n,...l}))).map(n=>({id:String(n.id??n.name),name:String(n.name??n.id),models:(n.models??[]).map(l=>({id:String(l.id??l.modelId),name:l.name}))}))}var mo="mock-session",Jy=[{id:"claude",name:"Claude",models:[{id:"claude-sonnet",name:"Claude Sonnet"}]},{id:"codex",name:"Codex",models:[{id:"gpt-6-astra",name:"GPT-6-Astra"}]}];function Wy(t,e=!1){return{type:"snapshot",protocolVersion:1,rows:t,sessions:[{sessionId:mo,title:"Mock session"}],summary:{sessionId:mo,title:"Mock session",harness:"claude",model:"claude-sonnet"},connection:"mock",sessionId:mo,isWorking:e,queue:[],catalog:Jy,canLoadOlder:!1}}function $y(t){return`Mock reply to **${t.replace(/[*_`]/g,"")}**. No acpmux daemon is attached; this pane is running in mock mode.`}function mx(t,e=n=>{window.setTimeout(n,400)}){let n=[{id:"mock-welcome",version:1,at:Date.now(),kind:"assistant",text:"Mock agent session. Type a prompt to see the pane render a turn."}],l=0,i=(u=!1)=>t(Wy(n,u)),a=u=>{n=[...n,{id:`mock-${l++}`,version:1,at:Date.now(),...u}]};return i(),{"chat.send":async({text:u})=>{let s=String(u??"");a({kind:"user",text:s}),i(!0),e(()=>{a({kind:"assistant",text:$y(s)}),i()})},"chat.cancel":async()=>i(),"chat.permission":async()=>i(),"chat.model":async()=>{},"chat.mode":async()=>{},"chat.effort":async()=>{},"chat.select":async()=>{},"chat.new":async()=>{n=[],i()},"chat.history":async()=>{}}}function Qt(t){return Math.round(t*100)/100}function ei(t,e){return t.length===0?0:t[Math.min(t.length-1,Math.max(0,Math.round((t.length-1)*e)))]}function px(t){return ei([...t].sort((e,n)=>e-n),.5)}function Iy(t){let e=[];for(let n=1;n0))return 0;let n=0;for(let l of t)n+=Math.max(0,Math.round(l/e)-1);return n}function gx(t,e){let n=Iy(t).sort((l,i)=>l-i);return{frames:t.length,nominal_ms:Qt(e),p50_ms:Qt(ei(n,.5)),p95_ms:Qt(ei(n,.95)),p99_ms:Qt(ei(n,.99)),max_ms:Qt(n.at(-1)??0),dropped_frames:Py(n,e)}}function ti(t){let e=[...t].sort((n,l)=>n-l);return{p50_ms:Qt(ei(e,.5)),p95_ms:Qt(ei(e,.95)),max_ms:Qt(e.at(-1)??0)}}function Sx(t,e,n,l,i){let a=Math.max(0,n),u=Math.min(i,n+l);return u<=a?!1:t>a+.5||ee.frame)),to_paint:ti(t.map(e=>e.paint))}}var go=class{enabled=!1;ring=new po;layoutSinceMark=0;reactSinceMark=0;lastMark;mountedTop=0;mountedBottom=0;commitWaiters=[];typing=[];keyListener;enable(e=typeof document>"u"?void 0:document){this.enabled=!0,!(this.keyListener||!e)&&(this.keyListener=n=>{if(!n.target?.closest?.(".acpmux-composer"))return;let i=n.timeStamp;requestAnimationFrame(()=>{let a=performance.now(),u=new MessageChannel;u.port1.onmessage=()=>{this.typing.push({frame:a-i,paint:performance.now()-i}),this.typing.length>4096&&this.typing.shift(),u.port1.close()},u.port2.postMessage(0)})},e.addEventListener("keydown",this.keyListener,!0))}addLayout(e){this.layoutSinceMark+=e}commit(e,n,l,i,a){this.reactSinceMark+=Math.max(0,e-n),this.mountedTop=l,this.mountedBottom=i;let u=this.commitWaiters;this.commitWaiters=[];for(let s of u)s(a)}nextCommit(e=1e4){return new Promise(n=>{let l=setTimeout(()=>{this.commitWaiters=this.commitWaiters.filter(a=>a!==i),n(void 0)},e),i=a=>{clearTimeout(l),n(a)};this.commitWaiters.push(i)})}resetFrames(){this.ring.clear(),this.lastMark=void 0,this.layoutSinceMark=0,this.reactSinceMark=0}markFrame(e,n){this.lastMark!==void 0&&this.ring.push(e-this.lastMark,this.layoutSinceMark,this.reactSinceMark,n),this.lastMark=e,this.layoutSinceMark=0,this.reactSinceMark=0}stats(e=!1){let n=this.ring.samples(),l={frames:n.length,blank_frames:n.filter(i=>i.blank).length,interval:ti(n.map(i=>i.interval)),layout:ti(n.map(i=>i.layout)),react:ti(n.map(i=>i.react)),other:ti(n.map(i=>i.other))};return e&&(l.samples=n.map(i=>({interval_ms:Qt(i.interval),layout_ms:Qt(i.layout),react_ms:Qt(i.react),other_ms:Qt(i.other),blank:i.blank}))),l}},tt=new go;function vx(t){let e=[],n=0,l=a=>{n+=1,e.push({...a,version:1,at:n*1e3})},i=Math.max(1,Math.floor(t/3));for(let a=0;a=0;l--)n.push(t[l]);return n.push(e),Fn(n)}function WS(t,e,n,l){if(!JS.test(t))return[{text:t,isWordLike:e,kind:"text",start:n}];let i=[],a=null,u=0,s=!1,c=0;for(let r of t){let f=KS(r,l),m=f==="text"&&e;if(a!==null&&f===a&&m===s){c+=r.length;continue}a!==null&&i.push({text:t.slice(u,c),isWordLike:s,kind:a,start:n+u}),a=f,u=c,s=m,c+=r.length}return a!==null&&i.push({text:t.slice(u),isWordLike:s,kind:a,start:n+u}),i}function eo(t){return t==="space"||t==="preserved-space"||t==="zero-width-break"||t==="hard-break"}var $S=/^[A-Za-z][A-Za-z0-9+.-]*:$/;function w1(t,e){let n=t.texts[e];return n.startsWith("www.")?!0:$S.test(n)&&e+1=t.len||eo(t.kinds[x]))continue;let g=[],y=o<0?t.starts[x]:o,N=x;for(;N0&&(l.push(Fn(g)),i.push(!0),a.push("text"),u.push(y),s=N-1)}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}var ty=new Set([":","-","/","\xD7",",",".","+","\u2013","\u2014"]),ey=/[\p{P}\p{S}\p{Co}]/u,U1=/\p{Emoji_Presentation}/u,ny=new Set(["?","\u058A","-","\u2010","\u2012","\u2013","\u2014","\u2026","\u203C","\u203D","\u2049"]);function ly(t){return t>=33&&t<=47&&t!==45||t>=58&&t<=64&&t!==63||t>=91&&t<=96||t>=123&&t<=126}function H1(t){let e=t.charCodeAt(0);return e<128?ly(e):!ny.has(t)&&!U1.test(t)&&ey.test(t)}function _1(t){let e=!1;for(let n of t)if(!We.test(n)){if(!H1(n))return!1;e=!0}return e}function iy(t){for(let e=t.length;e>0;){let n=Wl(t,e),l=t.slice(n,e);if(We.test(l)){e=n;continue}return H1(l)||el(l)}return!1}var lo=/[A-Za-z#&*<=>@^_`~]/;function G1(t,e){return t.charCodeAt(0)<128&&e.charCodeAt(0)<128}function Je(t,e,n){if(!n.geckoAsciiLineBreaks||e<=0||e>=t.length)return null;let l=so(t,e),i=String.fromCodePoint(t.codePointAt(e));if(l===null||!G1(l,i))return null;let a=el(l),u=el(i);return!a&&!u?null:!!(i===")"||i==="]"||i==="}"||"!,.:;?/".includes(i)||"([{".includes(l)||l==='"'||l==="'"||i==='"'||i==="'"||i==="|"||i==="-"||a&&lo.test(i)||lo.test(l)&&u||u&&(")]}".includes(l)||/[0-9]/.test(l))||a&&("([{".includes(i)||/[0-9]/.test(i)))}function Wu(t,e,n,l=t.length){let i=e[0];if(i===void 0||!"([{".includes(i))return null;let a=so(t,l);return a===null?null:n.geckoAsciiLineBreaks&&G1(a,i)?lo.test(a)||oa.test(a)||`"'([{`.includes(a)||el(a):a.charCodeAt(0)>=128?!jt(a)&&/[\p{L}\p{N}]/u.test(a)?!0:null:/[A-Za-z0-9]/.test(a)||"$'(/<@[^_`{".includes(a)}function ay(t,e,n,l,i){if(n[0]==="-"&&jt(t))return!0;if(jt(t)||jt(n))return!1;let a=Wu(t,n,i);if(a!==null)return a;let u=!e&&_1(t),s=!l&&_1(n),c=YS(t),r=(e||c)&&iy(t);return!u&&!s&&!r?!1:(e||u||c)&&(l||s)}function L1(t){for(let e of t)if(oa.test(e))return!0;return!1}function ra(t){if(t.length===0)return!1;for(let e of t)if(!(oa.test(e)||ty.has(e)))return!1;return!0}function uy(t,e,n){let l=[],i=[],a=[],u=[];function s(c,r){if(c.includes("-")){let f=c.split("-"),m=f.length>1;for(let o=0;os+1){l.push(Fn(m)),i.push(x),a.push("text"),u.push(t.starts[s]),s=o;continue}}l.push(c),i.push(f),a.push(r),u.push(t.starts[s]),s++}return{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function cy(t){let e=[],n=[],l=[],i=[],a=0;for(;a=0;v--){let A=a[v];if(A.length===0)continue;let B=M?.at(-1)??(S>=0?a[S]:null);if(s[v]==="text"&&!u[v]&&B!==null&&s[S]==="text"&&((Je(t,c[v]+A.length,e)??(qS(A)&&Wu(A,B,e)!==!1))||A==="-"&&jS(B))){M===null&&(M=[]),M.push(A),c[S]=c[v],a[v]="";continue}M!==null&&(a[S]=z1(M,a[S]),M=null),S=v}M!==null&&(a[S]=z1(M,a[S]));let F=0;for(let v=0;v=0&&(!q1(e.texts[o-1],n.breakKeepAllAfterPunctuation)||Je(t,e.starts[o],n)===!1)&&m(o),s<0&&(s=o),c=c||jt(x);continue}m(o),l.push(x),i.push(e.isWordLike[o]),a.push(g),u.push(e.starts[o])}return m(e.len),{len:l.length,texts:l,isWordLike:i,kinds:a,starts:u}}function Y1(t,e){let n=t.charCodeAt(e+1);if(n<128){if(n<48||n>57)return!1}else{let l=t.codePointAt(e+1);if(l===void 0||!oa.test(String.fromCodePoint(l)))return!1}for(let l=e;l>0;){let i=Wl(t,l),a=t.slice(i,l);if(!We.test(a))return jt(a)||!/[\p{L}\p{N}]/u.test(a);l=i}return!0}function dy(t,e){let n=[],l=0,i=0,a=!1,u=!1,s=!1,c=!1,r=!1;function f(){i!==l&&(n.push({text:t.slice(l,i),start:l,overflow:a?c?"grapheme":"none":"word-like"}),l=i,a=!1,u=!1,s=!1,c=!1,r=!1)}function m(x,g,y){l=g,i=g+x.length,a=y,c=x==="-",u=no(x),s=$u.has(x)}function o(x,g){i+=x.length,a=a||g,c=c||x==="-";let y=no(x);x.length===1&&tl.has(x)?u=u||y:u=y,s=!1}for(let x of Dn().segment(t)){let g=x.segment,y=jt(g);if(i===l){m(g,x.index,y);continue}let N=g==="-"&&a;if(N&&Y1(t,x.index)&&(r=!0),s||io.has(g)||tl.has(g)||N||r&&!y||e.carryCJKAfterClosingQuote&&y&&u){o(g,y);continue}if(!a&&!y){o(g,y);continue}f(),m(g,x.index,y)}return f(),n}function hy(t,e,n){if(e.length<=1)return e;let l=[],i=-1,a=!1;function u(c,r){let f=e[c].start,m=r=0&&(!q1(e[c-1].text,n.breakKeepAllAfterPunctuation)||Je(t,r.start,n)===!1)&&s(c),i<0&&(i=c),a=a||jt(r.text)}return s(e.length),l}function j1(t,e,n){let l=dy(t,e);return n==="keep-all"?hy(t,l,e):l}function xy(t){return t==="-"||t==="\u058A"||t==="\u2010"||t==="\u2012"||t==="\u2013"||t==="\u2014"}function Q1(t){if(t.length===0||/\p{Cf}/u.test(t))return!1;for(let{segment:e}of Dn().segment(t)){let n=String.fromCodePoint(e.codePointAt(0));if(!/[\p{P}\p{S}]/u.test(n)||U1.test(n)||e.includes("\uFE0F")||/\p{Emoji_Modifier}/u.test(n))return!1}return!0}function X1(t){if(!/[-\u058A\u2010\u2012\u2013\u2014]/u.test(t))return null;let e=[],n=0;for(let l of Dn().segment(t)){n++;let i=l.segment==="-"&&Y1(t,l.index);xy(l.segment)&&!i&&e.push(n)}return e.length===0?null:e}function Z1(t,e,n="normal",l="normal"){let i=n==="pre-wrap"?ES(t):bS(t);if(i.length===0)return{normalized:i,len:0,texts:[],isWordLike:[],kinds:[],starts:[]};let a=oy(i,e,n),u=l==="keep-all"?fy(i,a,e):a;return{normalized:i,...u}}var $l=null,V1=new Map,Il=null,my=96,py=/\p{Emoji_Presentation}/u,gy=/[\p{Emoji_Presentation}\p{Extended_Pictographic}\p{Regional_Indicator}\uFE0F\u20E3]/u,K1=new Map;function co(){if($l!==null)return $l;if(typeof OffscreenCanvas<"u")return $l=new OffscreenCanvas(1,1).getContext("2d"),$l;if(typeof document<"u")return $l=document.createElement("canvas").getContext("2d"),$l;throw new Error("Text measurement requires OffscreenCanvas or a DOM canvas context.")}function Sy(t){let e=V1.get(t);return e||(e=new Map,V1.set(t,e)),e}function $e(t,e){let n=e.get(t);return n===void 0&&(n={width:co().measureText(t).width},e.set(t,n)),n}function Pl(){if(Il!==null)return Il;if(typeof navigator>"u")return Il={geckoAsciiLineBreaks:!1,lineFitEpsilon:.005,carryCJKAfterClosingQuote:!1,breakKeepAllAfterPunctuation:!0,preferPrefixWidthsForBreakableRuns:!1},Il;let t=navigator.userAgent,n=navigator.vendor==="Apple Computer, Inc."&&t.includes("Safari/")&&!t.includes("Chrome/")&&!t.includes("Chromium/")&&!t.includes("CriOS/")&&!t.includes("FxiOS/")&&!t.includes("EdgiOS/"),l=t.includes("Chrome/")||t.includes("Chromium/")||t.includes("CriOS/")||t.includes("Edg/");return Il={geckoAsciiLineBreaks:t.includes("Firefox/")&&!t.includes("FxiOS/"),lineFitEpsilon:n?1/64:.005,carryCJKAfterClosingQuote:l,breakKeepAllAfterPunctuation:!n,preferPrefixWidthsForBreakableRuns:n},Il}function yy(t){let e=t.match(/(?:^|\D)(\d+(?:\.\d+)?)\s*px/);return e?parseFloat(e[1]):16}function vy(t){return py.test(t)||t.includes("\uFE0F")}function J1(t){return gy.test(t)}function Ay(t){let e=K1.get(t);if(e!==void 0)return e;let n=yy(t),l=co();l.font=t;let i=l.measureText("\u{1F600}").width;if(e=0,i>n+.5&&typeof document<"u"&&document.body!==null){let a=document.createElement("span");a.style.font=t,a.style.display="inline-block",a.style.visibility="hidden",a.style.position="absolute",a.textContent="\u{1F600}",document.body.appendChild(a);let u=a.getBoundingClientRect().width;document.body.removeChild(a),i-u>.5&&(e=i-u)}return K1.set(t,e),e}function by(t){let e=0,n=Dn();for(let l of n.segment(t))vy(l.segment)&&e++;return e}function Ey(t,e){return e.emojiCount===void 0&&(e.emojiCount=by(t)),e.emojiCount}function Bn(t,e,n){return n===0?e.width:e.width-Ey(t,e)*n}function W1(t,e,n,l,i){if(e.breakableFitAdvances!==void 0&&e.breakableFitMode===i)return e.breakableFitAdvances;e.breakableFitMode=i;let a=Dn(),u=[];for(let f of a.segment(t))u.push(f.segment);if(u.length<=1)return e.breakableFitAdvances=null,e.breakableFitAdvances;if(i==="sum-graphemes"){let f=[];for(let m of u){let o=$e(m,n);f.push(Bn(m,o,l))}return e.breakableFitAdvances=f,e.breakableFitAdvances}if(i==="pair-context"||u.length>my){let f=[],m=null,o=0;for(let x of u){let g=$e(x,n),y=Bn(x,g,l);if(m===null)f.push(y);else{let N=m+x,h=$e(N,n);f.push(Bn(N,h,l)-o)}m=x,o=y}return e.breakableFitAdvances=f,e.breakableFitAdvances}let s=[],c="",r=0;for(let f of u){c+=f;let m=$e(c,n),o=Bn(c,m,l);s.push(o-r),r=o}return e.breakableFitAdvances=s,e.breakableFitAdvances}function $1(t,e){let n=co();n.font=t;let l=Sy(t),i=e?Ay(t):0;return{cache:l,emojiCorrection:i}}function Ny(t,e,n){return n===0&&e>0&&e0?t.letterSpacing:0}function oo(t,e){return e===0?0:t+e}function Dy(t,e){return t.letterSpacing!==0&&t.spacingGraphemeCounts[e]>0?t.letterSpacing:0}function By(t,e,n,l,i){let a=e==="tab"?i+Dy(t,n):t.lineEndFitAdvances[n];return oo(l,a)}function I1(t,e,n,l){let i=e==="tab"?0:t.lineEndFitAdvances[n];return oo(l,i)}function P1(t,e,n,l,i){let a=e==="tab"?i:t.lineEndPaintAdvances[n];return oo(l,a)}function ky(t,e,n){return t.letterSpacing!==0&&e?n+t.letterSpacing:n}function Ty(t,e){return t.letterSpacing===0?e:e+t.letterSpacing}function ro(t,e,n){let l=e;if(l>=t.length||t[l]>=n)return l;let i=t.length;for(l++;l0)return t.spacingGraphemeCounts[l]>0?t.letterSpacing:0;if(Ny(t.kinds,l,i))return 0;for(let a=l-1;a>=e;a--){let u=t.kinds[a];if(!(u==="space"||u==="zero-width-break"||u==="hard-break"||u==="soft-hyphen"))return a===e&&n>0||t.spacingGraphemeCounts[a]>0?t.letterSpacing:0}return 0}function Ry(t,e,n,l,i,a){return e+Oy(t,n,l,i,a)}function zy(t,e){let n=0,l=t.chunks.length;for(;n0)return e;for(let i=e;i=t.widths.length)return-1;l=a.consumedEndSegmentIndex,n.segmentIndex=l,n.graphemeIndex=0}return-1}function lx(t,e){if(e.segmentIndex>=t.widths.length)return-1;let n=zy(t,e.segmentIndex);return n<0?-1:nx(t,n,e)}function wy(t,e,n){if(n.segmentIndex>=t.widths.length)return-1;let l=e;for(;l=t.chunks[l].consumedEndSegmentIndex;)l++;return l>=t.chunks.length?-1:nx(t,l,n)}function ix(t,e){return ax(t,e)}function _y(t,e,n){let{widths:l,kinds:i,breakableFitAdvances:a,breakablePreferredBreaks:u}=t;if(l.length===0)return 0;let c=Pl().lineFitEpsilon,r=e+c,f=0,m=0,o=!1,x=0,g=0,y=0,N=0,h=-1,d=0;function p(){h=-1,d=0}function S(A=y,B=N,L=m){f++,n?.(L,x,g,A,B),m=0,o=!1,p()}function M(A,B){o=!0,x=A,g=0,y=A+1,N=0,m=B}function F(A,B,L){o=!0,x=A,g=B,y=A,N=B+1,m=L}function C(A,B){if(!o){M(A,B);return}m+=B,y=A+1,N=0}function E(A,B){let L=a[A],_=u[A]??null,et=_===null?-1:ro(_,0,B+1),Z=-1,rt=0,k=B;for(;kr){if(_!==null&&Z>B){S(A,Z,rt),k=Z,et=ro(_,et,k+1),Z=-1,rt=0;continue}S(),F(A,k,R)}else m+=R,y=A,N=k+1;let O=k+1;_!==null&&_[et]===O&&(Z=O,rt=m,et++),k++}o&&y===A&&N===L.length&&(y=A+1,N=0)}let v=0;for(;v=l.length));){let A=l[v],B=i[v],L=tx(B);if(!o){A>r&&a[v]!==null?E(v,0):M(v,A),L&&(h=v+1,d=m-A),v++;continue}if(m+A>r){if(L){C(v,A),S(v+1,0,m-A),v++;continue}if(h>=0){if(y>h||y===h&&N>0){S();continue}S(h,0,d);continue}if(A>r&&a[v]!==null){S(),E(v,0),v++;continue}S();continue}C(v,A),L&&(h=v+1,d=m-A),v++}return o&&S(),f}function ax(t,e,n){if(t.simpleLineWalkFastPath)return _y(t,e,n);let l={segmentIndex:0,graphemeIndex:0},i=lx(t,l);return Ly(t,l,i,e,n).lineCount}function Ly(t,e,n,l,i,a=Number.POSITIVE_INFINITY){let{widths:u,kinds:s,breakableFitAdvances:c,breakablePreferredBreaks:r,discretionaryHyphenWidth:f}=t,o=Pl().lineFitEpsilon,x=l+o,g,y,N,h,d,p,S,M,F,C;function E(){return C==="soft-hyphen"&&S===d&&p===0?F:N}function v(k=d,R=p,O=E()){return h?(e.segmentIndex=k,e.graphemeIndex=R,Ry(t,O,g,y,k,R)):null}function A(k,R){h=!0,d=k+1,p=0,N=R}function B(k,R,O){h=!0,d=k,p=R+1,N=O}function L(k,R){if(!h){A(k,R);return}N+=R,d=k+1,p=0}function _(k,R,O,J,zt,Xt){if(!R)return;let wt=I1(t,k,O,zt),Bt=P1(t,k,O,zt,J);S=O+1,M=N-Xt+wt,F=N-Xt+Bt,C=k}function et(k,R){let O=c[k],J=r[k]??null,zt=J===null?-1:ro(J,0,R+1),Xt=-1,wt=0;for(let Bt=R;Btx)return J!==null&&Xt>R?v(k,Xt,wt):v();N=Se,d=k,p=Bt+1}let li=Bt+1;J!==null&&J[zt]===li&&(Xt=li,wt=N,zt++)}return h&&d===k&&p===O.length&&(d=k+1,p=0),null}let Z=0,rt=null;for(;n>=0&&Z0){let Se=et(O,Xt);if(Se!==null){R=Se;break t}}else if(li>x&&c[O]!==null){let Se=et(O,0);if(Se!==null){R=Se;break t}}else A(O,Bt);_(J,zt,O,Bt,wt,kn);continue}if(N+li>x){let Se=N+I1(t,J,O,wt),kx=N+P1(t,J,O,wt,Bt);if(zt&&Se<=x){L(O,kn),R=v(O+1,0,kx);break t}if(S>=0&&M<=x){if(d>S||d===S&&p>0){R=v();break t}R=v(S,0,F);break t}R=v();break t}L(O,kn),_(J,zt,O,Bt,wt,kn)}R===null&&(R=S===k.consumedEndSegmentIndex&&p===0?v(k.consumedEndSegmentIndex,0,F):v(k.consumedEndSegmentIndex,0,N))}if(R===null)break;rt=R,Z++,i?.(R,g,y,e.segmentIndex,e.graphemeIndex),Z1?t+(e-1)*n:t}function Hy(t,e,n,l,i){let a=Pl(),{cache:u,emojiCorrection:s}=$1(e,J1(t.normalized)),c=Bn("-",$e("-",u),s)+(i===0?0:i*2),f=Bn(" ",$e(" ",u),s)*8,m=i!==0;if(t.len===0)return qy(n);let o=[],x=[],g=[],y=[],N=!m,h=n?[]:null,d=[],p=[],S=[],M=n?[]:null,F=[],C=0;function E(B,L,_,et,Z,rt,k,R,O){Z!=="text"&&Z!=="space"&&Z!=="zero-width-break"&&(N=!1),o.push(L),x.push(_),g.push(et),y.push(Z),h?.push(rt),d.push(k),p.push(R),m&&S.push(O),M!==null&&M.push(B)}function v(B,L,_,et,Z){let rt=m?ux(B,_):0,k=Uy(Bn(B,L,s),rt,i),R=_==="space"||_==="preserved-space"||_==="zero-width-break"?0:k,O=R===0?0:R+(rt>0?i:0),J=_==="space"||_==="zero-width-break"?0:k;if(Z&&B.length>1){let zt="sum-graphemes";i!==0?zt="segment-prefixes":ra(B)?zt="pair-context":a.preferPrefixWidthsForBreakableRuns&&(zt="segment-prefixes");let Xt=W1(B,L,u,s,zt),wt=Xt===null||l==="keep-all"?null:X1(B);E(B,k,O,J,_,et,Xt,wt,rt);return}E(B,k,O,J,_,et,null,null,rt)}for(let B=0;B[u.id,u])),l=[],i=[];for(let u of e){let s=t.get(u.id);s?s.version!==u.version&&i.push(u):l.push(u)}let a=[...t.keys()].filter(u=>!n.has(u));return{added:l,updated:i,removed:a}}function ho(t,e){let n=Math.max(1,Math.ceil((t.text?.length??0)/Math.max(24,Math.floor(e/8))));return t.kind==="activity"?Math.max(46,24+(t.items?.length??0)*20):t.kind==="turnSummary"||t.kind==="notice"||t.kind==="typing"?32:24+n*ox}function Yy(t,e,n){if(!t.text)return ho(t,e);let i=n.get(t.id)??{version:t.version,text:t.text,prepared:null,blocks:new Map};if(i.version=t.version,i.text=t.text,!i.blocks.size)try{i.prepared=fo(t.text,cx,{whiteSpace:"pre-wrap"})}catch{i.prepared=null}n.set(t.id,i);let a=Math.max(80,e-(t.kind==="user"?120:0)),u=t.text.split(/\n{2,}/).filter(Boolean);if(u.length===0)return ho(t,e);let s=0;for(let c of u){let r=i.blocks.get(c);if(!r)try{r=fo(c,cx,{whiteSpace:"pre-wrap"}),i.blocks.set(c,r)}catch{return ho(t,e)}s+=sx(r,a,ox).height}return Math.max(34,16+s+Math.max(0,u.length-1)*8)}function dx(t,e,n=new Map,l){let i=new Float64Array(t.length),a=new Float64Array(t.length),u=0;for(let s=0;s0?c:Yy(t[s],e,n);a[s]=r,u+=r}return{tops:i,heights:a,totalHeight:u}}function rx(t,e){let n=0,l=t.length;for(;n>>1;t[i]<=e?n=i+1:l=i}return n}function hx(t,e,n,l=4){if(t.tops.length===0)return{first:0,last:0};let i=Math.max(0,rx(t.tops,Math.max(0,e))-1-l),a=Math.min(t.tops.length,rx(t.tops,e+n)+l);return{first:i,last:a}}function jy(t,e){let n=t??{},l=n?.request??n,i=n?.sessionId??l?.sessionId,a=n?.permissionId??l?.permissionId;if(!(!a||i!==e))return{permissionId:String(a),title:l.toolCall?.title,kind:l.toolCall?.kind,pending:!0,options:(l.options??[]).map(u=>({id:String(u.optionId??u.id),name:String(u.name??u.optionId),allow:String(u.kind??"").startsWith("allow")}))}}function Qy(t,e,n){let l=typeof n?.promptId=="string"?n.promptId:void 0;if(!l)return;let i=e.get(l);i&&t.delete(i),e.delete(l)}function xo(...t){let e=new Map;for(let n of t.flat())e.set(n.seq,n);return[...e.values()].sort((n,l)=>n.seq-l.seq)}function Xy(t,e,n,l){n.add(l);let i=e.get(l);i&&t.delete(i),e.delete(l)}function Zy(t,e,n){return t||(n?void 0:e[0]?.sessionId)}function xx(t){return typeof t=="string"?t:t?.type==="text"?String(t.text??""):Array.isArray(t)?t.map(xx).join(""):""}function Vy(t){return t.dir==="in"&&t.msg.method==="session/update"?t.msg.params?.update:void 0}var Iu=class t{socket;nextRequest=1;pending=new Map;events=[];rows=new Map;sessions=[];selectedSessionId;summary;catalog=[];queue=[];pendingPermission;optimisticPromptRows=new Map;optimisticPromptTexts=new Map;firstSeq;lastSeq=0;turnOpen=!1;streamingAssistant;streamingAssistantMessageId;streamingActivity;supersededMessageIds=new Set;messageRows=new Map;listener;host;reconnectTimer;reconnectDelay=250;onLost;opening=!1;hasConnected=!1;closed=!1;selectionGeneration=0;attachedGeneration=-1;historyExhausted=!1;constructor(e,n,l){this.host=e,this.listener=n,this.onLost=l,this.selectedSessionId=e.sessionId}static async connect(e,n,l){let i=new t(e,n,l);return await i.open(),i}async open(){if(this.opening||this.closed)return;this.opening=!0;let e=new URL(this.host.endpoint);e.searchParams.set("token",this.host.token),await new Promise((n,l)=>{let i=new WebSocket(e);this.socket=i;let a=!1;i.onopen=()=>{a=!0,n()},i.onerror=()=>{this.opening=!1,l(new Error("Unable to connect to acpmux WebSocket"))},i.onclose=()=>{if(this.socket===i){if(!a){this.opening=!1,l(new Error("acpmux WebSocket closed before connect"));return}for(let u of this.pending.values())u.reject(new Error("acpmux WebSocket closed"));if(this.pending.clear(),this.emit("disconnected"),!(!this.hasConnected||this.closed))if(this.onLost){let u=this.onLost;this.close(),u()}else this.scheduleReconnect()}},i.onmessage=u=>this.receive(String(u.data))});try{await this.request("initialize",{protocolVersion:1,clientInfo:{name:"cmux-react-agent-pane",version:"1"},clientCapabilities:{}});let n=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(n?.sessions??[]).filter(i=>i.sessionId);let l=await this.request("_acpmux/harnesses",{});this.catalog=Ky(l),this.selectedSessionId&&!this.sessions.some(i=>i.sessionId===this.selectedSessionId)&&(this.selectedSessionId=this.sessions[0]?.sessionId,this.resetSessionState()),this.selectedSessionId=Zy(this.selectedSessionId,this.sessions,this.host.newSession),this.selectedSessionId&&await this.attach(this.selectedSessionId),this.hasConnected=!0,this.reconnectDelay=250,this.emit("connected")}catch(n){throw this.socket?.close(),n}finally{this.opening=!1}}resetSessionState(){this.events=[],this.historyExhausted=!1,this.rows.clear(),this.firstSeq=void 0,this.lastSeq=0,this.summary=void 0,this.queue=[],this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.optimisticPromptRows.clear(),this.optimisticPromptTexts.clear(),this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0}scheduleReconnect(){if(this.reconnectTimer!==void 0||this.closed)return;let e=this.reconnectDelay;this.reconnectDelay=Math.min(e*2,3e4),this.reconnectTimer=window.setTimeout(()=>{this.reconnectTimer=void 0,this.open().catch(()=>this.scheduleReconnect())},e)}receive(e){let n;try{n=JSON.parse(e)}catch{return}if("id"in n&&typeof n.id=="number"){let i=this.pending.get(n.id);if(!i)return;this.pending.delete(n.id),n.error?i.reject(new Error(n.error.message??"acpmux request failed")):i.resolve(n.result);return}let l=n;l.method==="_acpmux/event"?this.apply(l.params):l.method==="session/update"?this.apply({sessionId:l.params?.sessionId,seq:Number(l.params?._meta?.acpmux?.seq??0),at:Number(l.params?._meta?.acpmux?.at??Date.now()),dir:"in",kind:String(l.params?.update?.sessionUpdate??""),msg:{method:"session/update",params:{update:l.params?.update}}}):l.method==="_acpmux/session_changed"?this.sessionChanged(l.params):l.method==="_acpmux/permission_pending"?this.applyPermission(l.params):l.method==="_acpmux/lagged"&&this.resyncAfterLag(l.params)}resyncAfterLag(e){e?.watch===!0&&this.refreshSessions().catch(()=>{});let n=this.selectedSessionId;!n||this.attachedGeneration!==this.selectionGeneration||Array.isArray(e?.sessionIds)&&!e.sessionIds.map(String).includes(n)||(this.emit("resyncing"),this.fetchMissedEvents(n,this.selectionGeneration,this.lastSeq).catch(()=>{}))}async fetchMissedEvents(e,n,l){for(let i=l;;){let a=await this.request("_acpmux/events",{sessionId:e,afterSeq:i,limit:5e3});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let u=a?.events??[];if(this.events=xo(this.events,u),this.rebuild(),a?.more!==!0||u.length===0)break;i=Math.max(i,...u.map(s=>s.seq))}this.emit("resynced")}async refreshSessions(){let e=await this.request("_acpmux/watch",{enabled:!0});this.sessions=(e?.sessions??[]).filter(n=>n.sessionId),this.emit("session changed")}request(e,n){if(this.socket?.readyState!==WebSocket.OPEN)return Promise.reject(new Error("acpmux WebSocket is not open"));let l=this.nextRequest++;return new Promise((i,a)=>{this.pending.set(l,{resolve:i,reject:a}),this.socket.send(JSON.stringify({jsonrpc:"2.0",id:l,method:e,params:n}))})}async attach(e,n=this.selectionGeneration){if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let l=await this.request("_acpmux/attach",{sessionId:e,limit:400,kinds:["transcript"],eventStream:!0});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=l?.session??{};this.summary=i,this.queue=(i.queue??[]).map(a=>({id:String(a.promptId),prompt:String(a.prompt??"")})),this.events=xo(l?.events??[],this.events),this.rebuild(),this.attachedGeneration=n,this.emit("attached")}sessionChanged(e){let n=e?.session;if(e?.kind==="purged"&&n?.sessionId){if(this.sessions=this.sessions.filter(l=>l.sessionId!==n.sessionId),n.sessionId===this.selectedSessionId){this.selectedSessionId=this.sessions[0]?.sessionId;let l=++this.selectionGeneration;this.resetSessionState(),this.emit("session purged"),this.selectedSessionId&&this.attach(this.selectedSessionId,l).catch(()=>{})}else this.emit("session purged");return}n?.sessionId&&(this.sessions=[...this.sessions.filter(l=>l.sessionId!==n.sessionId),n],n.sessionId===this.selectedSessionId&&(this.summary={...this.summary,...n},this.queue=(n.queue??this.queue).map(l=>({id:String(l.promptId),prompt:String(l.prompt??l.preview??"")}))),this.emit("session changed"))}applyPermission(e){let n=jy(e,this.selectedSessionId??"");n&&(this.pendingPermission=n,this.emit("permission"))}apply(e){!e?.seq||e.sessionId!==this.selectedSessionId||e.seq<=this.lastSeq||(this.events.push(e),this.lastSeq=e.seq,this.firstSeq=this.firstSeq===void 0?e.seq:Math.min(this.firstSeq,e.seq),this.reduce(e),this.emit(e.kind))}rebuild(){let e=[...this.optimisticPromptRows.values()].flatMap(l=>this.rows.get(l)??[]);this.rows.clear();for(let l of e)this.rows.set(l.id,l);this.firstSeq=void 0,this.lastSeq=0,this.turnOpen=!1,this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0,this.supersededMessageIds.clear(),this.messageRows.clear(),this.pendingPermission=void 0;let n=[...this.events].sort((l,i)=>l.seq-i.seq);for(let l of n)this.lastSeq=Math.max(this.lastSeq,l.seq),this.firstSeq=this.firstSeq===void 0?l.seq:Math.min(this.firstSeq,l.seq),this.reduce(l)}reduce(e){let n=e.msg??{},l=Vy(e);if(e.dir==="mux"){if(e.kind==="user_message"){let a=typeof n.promptId=="string"?n.promptId:void 0,u=typeof n.text=="string"?n.text:void 0,s=a??(u?[...this.optimisticPromptTexts.entries()].find(([,c])=>c===u)?.[0]:void 0);Qy(this.rows,this.optimisticPromptRows,{...n,promptId:s}),s&&this.optimisticPromptTexts.delete(s),this.rows.set(`user-${e.seq}`,{id:`user-${e.seq}`,version:1,at:e.at,kind:"user",text:String(n.text??"")}),this.turnOpen=!0}else if(e.kind==="turn_started")this.turnOpen=!0,this.rows.set("typing",{id:"typing",version:1,at:e.at,kind:"typing"});else if(e.kind==="message_superseded"){let a=typeof n.oldMessageId=="string"?n.oldMessageId:void 0;a&&(Xy(this.rows,this.messageRows,this.supersededMessageIds,a),this.streamingAssistantMessageId===a&&(this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0))}else if(e.kind==="turn_end"||e.kind==="turn_result"){if(this.turnOpen=!1,this.streamingAssistant){let a=this.rows.get(this.streamingAssistant);a&&(a.streaming=!1,a.version+=1)}this.rows.delete("typing"),e.kind==="turn_result"&&this.rows.set(`summary-${e.seq}`,{id:`summary-${e.seq}`,version:1,at:e.at,kind:"turnSummary",durationMs:void 0,toolCount:[...this.rows.values()].filter(a=>a.kind==="activity").length,status:String(n.status??"completed"),error:n.errorText}),this.streamingAssistant=void 0,this.streamingAssistantMessageId=void 0,this.streamingActivity=void 0}else if(e.kind==="queued"||e.kind==="queue_updated"){let a=String(n.promptId??"");a&&(this.queue=[...this.queue.filter(u=>u.id!==a),{id:a,prompt:String(n.text??"")}])}else e.kind==="queue_removed"||e.kind==="dequeued"?this.queue=this.queue.filter(a=>a.id!==String(n.promptId??"")):e.kind==="permission_request"?this.applyPermission({...n,sessionId:e.sessionId}):e.kind==="permission_decision"?this.pendingPermission=void 0:e.kind==="status"&&(this.summary={...this.summary,status:n.status});return}if(!l)return;let i=xx(l.content);if(e.kind==="agent_message_chunk"&&i){let a=typeof l.messageId=="string"?l.messageId:void 0;if(a&&this.supersededMessageIds.has(a))return;let s=!!(this.streamingAssistant&&(!a||!this.streamingAssistantMessageId||this.streamingAssistantMessageId===a))?this.streamingAssistant:`assistant-${e.seq}`,c=this.rows.get(s);this.rows.set(s,{id:s,version:(c?.version??0)+1,at:e.at,kind:"assistant",text:`${c?.text??""}${i}`,streaming:!0}),this.streamingAssistant=s,this.streamingAssistantMessageId=a,a&&this.messageRows.set(a,s),this.rows.delete("typing")}else if(e.kind==="agent_thought_chunk"&&i){let a=this.streamingActivity??`activity-${e.seq}`,u=this.rows.get(a);this.rows.set(a,{id:a,version:(u?.version??0)+1,at:e.at,kind:"activity",toolCount:u?.toolCount??0,items:[...u?.items??[],{kind:"thought",text:i}]}),this.streamingActivity=a}else if(e.kind==="tool_call"||e.kind==="tool_call_update"){let a=String(l.toolCallId??`tool-${e.seq}`),u=this.streamingActivity??`activity-${e.seq}`,s=this.rows.get(u),c=[...s?.items??[]],r=c.findIndex(m=>m.tool?.id===a),f={kind:"tool",text:String(l.title??l.name??a),tool:{id:a,title:String(l.title??a),kind:l.kind,status:String(l.status??"in_progress"),inputSummary:l.rawInput?JSON.stringify(l.rawInput):void 0,output:i||void 0}};r>=0?c[r]=f:c.push(f),this.rows.set(u,{id:u,version:(s?.version??0)+1,at:e.at,kind:"activity",toolCount:c.filter(m=>m.kind==="tool").length,items:c}),this.streamingActivity=u}else e.kind==="plan"&&this.rows.set(`plan-${e.seq}`,{id:`plan-${e.seq}`,version:1,at:e.at,kind:"plan",text:i||JSON.stringify(l.entries??l.content??"")})}emit(e="connected"){let n=this.summary,l=(n?.configOptions??[]).find(i=>i.category==="thought_level"||i.id==="reasoning_effort");this.listener({type:"snapshot",protocolVersion:1,rows:[...this.rows.values()].sort((i,a)=>i.at-a.at),sessions:this.sessions.map(i=>({sessionId:i.sessionId,displayTitle:i.title??i.name,title:i.title,name:i.name,status:i.status,model:i.model})),summary:n?{sessionId:n.sessionId,title:n.title,name:n.name,harness:n.harness,model:n.model,effort:l?.currentValue,status:n.status,modes:n.modes,configOptions:n.configOptions}:void 0,connection:e,sessionId:this.selectedSessionId,isWorking:this.turnOpen||n?.status==="running",queue:this.queue,permission:this.pendingPermission,catalog:this.catalog,canLoadOlder:!this.historyExhausted&&(this.firstSeq??1)>1})}snapshot(){this.emit()}async ensureSession(){return this.selectedSessionId||await this.create(),this.selectedSessionId}async send(e){let n=await this.ensureSession();if(!n)return;let l=crypto.randomUUID(),i=`local-${l}`,a=Date.now();this.optimisticPromptRows.set(l,i),this.optimisticPromptTexts.set(l,e),this.rows.set(i,{id:i,version:1,at:a,kind:"user",text:e,pending:!0}),this.emit();try{await this.request("session/prompt",{sessionId:n,prompt:[{type:"text",text:e}],_meta:{acpmux:{promptId:l}}})}catch(u){let s=this.rows.get(i);throw s&&(s.pending=!1,s.failed=!0,s.version+=1),this.optimisticPromptRows.delete(l),this.optimisticPromptTexts.delete(l),this.emit("failed"),u}return n}async cancel(){this.selectedSessionId&&this.socket?.send(JSON.stringify({jsonrpc:"2.0",method:"session/cancel",params:{sessionId:this.selectedSessionId}}))}async permission(e,n){this.selectedSessionId&&await this.request("_acpmux/permission_respond",{sessionId:this.selectedSessionId,permissionId:e,optionId:n})}async select(e){let n=this.selectedSessionId,l=++this.selectionGeneration;return this.selectedSessionId=e,this.resetSessionState(),n&&await this.request("_acpmux/detach",{sessionId:n}),await this.attach(e,l),l===this.selectionGeneration&&this.selectedSessionId===e?e:void 0}async create(e){let n=await this.request("session/new",{mcpServers:[],_meta:{acpmux:{harness:e}}});if(n?.sessionId)return this.select(String(n.sessionId))}async setModel(e){this.selectedSessionId&&await this.request("session/set_model",{sessionId:this.selectedSessionId,modelId:e})}async setMode(e){this.selectedSessionId&&await this.request("session/set_mode",{sessionId:this.selectedSessionId,modeId:e})}async setConfig(e,n){this.selectedSessionId&&await this.request("session/set_config_option",{sessionId:this.selectedSessionId,configId:e,value:n})}async loadOlder(){if(!this.selectedSessionId||!this.firstSeq||this.firstSeq<=1||this.historyExhausted)return;let e=this.selectedSessionId,n=this.selectionGeneration,l=await this.request("_acpmux/events",{sessionId:e,beforeSeq:this.firstSeq,limit:400,kinds:["transcript"]});if(n!==this.selectionGeneration||this.selectedSessionId!==e)return;let i=this.summary,a=this.queue,u=this.pendingPermission,s=l?.events??[];this.events=xo(s,this.events),this.rebuild(),this.summary=i,this.queue=a,this.pendingPermission=u,this.historyExhausted=l?.more===!1||s.length===0||(this.firstSeq??1)<=1,this.emit("history")}close(){this.closed=!0,this.reconnectTimer!==void 0&&window.clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0,this.socket?.close(),this.socket=void 0}};function Ky(t){let e=t?.harnesses??t?.items??t??[];return(Array.isArray(e)?e:Object.entries(e).map(([n,l])=>({id:n,...l}))).map(n=>({id:String(n.id??n.name),name:String(n.name??n.id),models:(n.models??[]).map(l=>({id:String(l.id??l.modelId),name:l.name}))}))}var mo="mock-session",Jy=[{id:"claude",name:"Claude",models:[{id:"claude-sonnet",name:"Claude Sonnet"}]},{id:"codex",name:"Codex",models:[{id:"gpt-6-astra",name:"GPT-6-Astra"}]}];function Wy(t,e=!1){return{type:"snapshot",protocolVersion:1,rows:t,sessions:[{sessionId:mo,title:"Mock session"}],summary:{sessionId:mo,title:"Mock session",harness:"claude",model:"claude-sonnet"},connection:"mock",sessionId:mo,isWorking:e,queue:[],catalog:Jy,canLoadOlder:!1}}function $y(t){return`Mock reply to **${t.replace(/[*_`]/g,"")}**. No acpmux daemon is attached; this pane is running in mock mode.`}function mx(t,e=n=>{window.setTimeout(n,400)}){let n=[{id:"mock-welcome",version:1,at:Date.now(),kind:"assistant",text:"Mock agent session. Type a prompt to see the pane render a turn."}],l=0,i=(u=!1)=>t(Wy(n,u)),a=u=>{n=[...n,{id:`mock-${l++}`,version:1,at:Date.now(),...u}]};return i(),{"chat.send":async({text:u})=>{let s=String(u??"");a({kind:"user",text:s}),i(!0),e(()=>{a({kind:"assistant",text:$y(s)}),i()})},"chat.cancel":async()=>i(),"chat.permission":async()=>i(),"chat.model":async()=>{},"chat.mode":async()=>{},"chat.effort":async()=>{},"chat.select":async()=>{},"chat.new":async()=>{n=[],i()},"chat.history":async()=>{}}}function Qt(t){return Math.round(t*100)/100}function ei(t,e){return t.length===0?0:t[Math.min(t.length-1,Math.max(0,Math.round((t.length-1)*e)))]}function px(t){return ei([...t].sort((e,n)=>e-n),.5)}function Iy(t){let e=[];for(let n=1;n0))return 0;let n=0;for(let l of t)n+=Math.max(0,Math.round(l/e)-1);return n}function gx(t,e){let n=Iy(t).sort((l,i)=>l-i);return{frames:t.length,nominal_ms:Qt(e),p50_ms:Qt(ei(n,.5)),p95_ms:Qt(ei(n,.95)),p99_ms:Qt(ei(n,.99)),max_ms:Qt(n.at(-1)??0),dropped_frames:Py(n,e)}}function ti(t){let e=[...t].sort((n,l)=>n-l);return{p50_ms:Qt(ei(e,.5)),p95_ms:Qt(ei(e,.95)),max_ms:Qt(e.at(-1)??0)}}function Sx(t,e,n,l,i){let a=Math.max(0,n),u=Math.min(i,n+l);return u<=a?!1:t>a+.5||ee.frame)),to_paint:ti(t.map(e=>e.paint))}}var go=class{enabled=!1;ring=new po;layoutSinceMark=0;reactSinceMark=0;lastMark;mountedTop=0;mountedBottom=0;commitWaiters=[];typing=[];keyListener;enable(e=typeof document>"u"?void 0:document){this.enabled=!0,!(this.keyListener||!e)&&(this.keyListener=n=>{if(!n.target?.closest?.(".acpmux-composer"))return;let i=n.timeStamp;requestAnimationFrame(()=>{let a=performance.now(),u=new MessageChannel;u.port1.onmessage=()=>{this.typing.push({frame:a-i,paint:performance.now()-i}),this.typing.length>4096&&this.typing.shift(),u.port1.close()},u.port2.postMessage(0)})},e.addEventListener("keydown",this.keyListener,!0))}addLayout(e){this.layoutSinceMark+=e}commit(e,n,l,i,a){this.reactSinceMark+=Math.max(0,e-n),this.mountedTop=l,this.mountedBottom=i;let u=this.commitWaiters;this.commitWaiters=[];for(let s of u)s(a)}nextCommit(e=1e4){return new Promise(n=>{let l=setTimeout(()=>{this.commitWaiters=this.commitWaiters.filter(a=>a!==i),n(void 0)},e),i=a=>{clearTimeout(l),n(a)};this.commitWaiters.push(i)})}resetFrames(){this.ring.clear(),this.lastMark=void 0,this.layoutSinceMark=0,this.reactSinceMark=0}markFrame(e,n){this.lastMark!==void 0&&this.ring.push(e-this.lastMark,this.layoutSinceMark,this.reactSinceMark,n),this.lastMark=e,this.layoutSinceMark=0,this.reactSinceMark=0}stats(e=!1){let n=this.ring.samples(),l={frames:n.length,blank_frames:n.filter(i=>i.blank).length,interval:ti(n.map(i=>i.interval)),layout:ti(n.map(i=>i.layout)),react:ti(n.map(i=>i.react)),other:ti(n.map(i=>i.other))};return e&&(l.samples=n.map(i=>({interval_ms:Qt(i.interval),layout_ms:Qt(i.layout),react_ms:Qt(i.react),other_ms:Qt(i.other),blank:i.blank}))),l}},tt=new go;function vx(t){let e=[],n=0,l=a=>{n+=1,e.push({...a,version:1,at:n*1e3})},i=Math.max(1,Math.floor(t/3));for(let a=0;a void) { @@ -230,20 +232,23 @@ export class AcpmuxDirectClient { private resyncAfterLag(params: any): void { if (params?.watch === true) void this.refreshSessions().catch(() => undefined); const sessionId = this.selectedSessionId; - if (!sessionId) return; + // 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).catch(() => undefined); + void this.fetchMissedEvents(sessionId, this.selectionGeneration, this.lastSeq).catch(() => undefined); } - private async fetchMissedEvents(sessionId: string, generation: number): Promise { - for (;;) { - const result = await this.request("_acpmux/events", { sessionId, afterSeq: this.lastSeq, limit: 5_000 }); + /// 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"); } @@ -273,6 +278,7 @@ export class AcpmuxDirectClient { 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"); }