2026-10-08 11:55:13 +08:00
|
|
|
import { uploadAttachments, uploadCapability, type AttachmentReference, type UploadCapability } from "../../../packages/client-events/attachments";
|
|
|
|
|
import { DeliveryReceipts } from "../../../packages/client-events/delivery";
|
2026-09-06 02:11:19 +08:00
|
|
|
import { decodeNotification } from "../../../packages/client-events/notifications";
|
2026-04-21 10:29:47 +00:00
|
|
|
import type {
|
|
|
|
|
ConnectionStatus,
|
|
|
|
|
InboundEvent,
|
|
|
|
|
Outbound,
|
2026-05-22 22:25:12 +08:00
|
|
|
OutboundCliAppMention,
|
2026-05-24 13:38:37 +08:00
|
|
|
OutboundMcpPresetMention,
|
2026-04-21 10:29:47 +00:00
|
|
|
OutboundMedia,
|
2026-08-02 22:04:59 +08:00
|
|
|
SessionMention,
|
2026-08-06 18:21:16 +08:00
|
|
|
SidebarStatePayload,
|
2026-05-16 01:14:11 +08:00
|
|
|
GoalStateWsPayload,
|
2026-05-29 03:42:53 +08:00
|
|
|
WorkspaceScopePayload,
|
2026-04-21 10:29:47 +00:00
|
|
|
} from "./types";
|
2026-05-31 17:00:42 +08:00
|
|
|
import { createHostWebSocket } from "./runtime";
|
2026-10-16 14:35:46 +08:00
|
|
|
import { ClientRunLedger } from "./client-run-ledger";
|
2026-10-24 00:43:34 +08:00
|
|
|
import type { CanonicalRunSnapshot, RunEffect, RunObservation, RunState } from "./client-run-ledger";
|
2026-10-16 14:35:46 +08:00
|
|
|
|
2026-10-24 00:43:34 +08:00
|
|
|
export type { CanonicalRunSnapshot, RunState } from "./client-run-ledger";
|
2026-04-18 18:51:53 +00:00
|
|
|
|
|
|
|
|
/** WebSocket readyState constants, referenced by value to stay portable
|
|
|
|
|
* across runtimes that don't expose a global ``WebSocket`` (tests, SSR). */
|
|
|
|
|
const WS_OPEN = 1;
|
|
|
|
|
const WS_CLOSING = 2;
|
2026-05-31 17:00:42 +08:00
|
|
|
const HOST_SOCKET_URL_PREFIX = "nanobot-host://";
|
|
|
|
|
|
|
|
|
|
function createDefaultSocket(url: string): WebSocket {
|
|
|
|
|
if (url.startsWith(HOST_SOCKET_URL_PREFIX)) {
|
|
|
|
|
return createHostWebSocket(url);
|
|
|
|
|
}
|
|
|
|
|
return new WebSocket(url);
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
|
2026-05-16 08:33:15 +00:00
|
|
|
/** Inbound WebSocket ``console.log`` / parse-failure ``console.warn``.
|
|
|
|
|
*
|
|
|
|
|
* - **Dev** (non-production bundle): **on by default** — messages appear at default log level.
|
|
|
|
|
* - **Production**: off unless ``localStorage.setItem('nanobot_debug_ws','1')`` (or ``true``).
|
|
|
|
|
* - **Silence anywhere**: ``localStorage.setItem('nanobot_debug_ws','0')`` (or ``false`` / ``off``).
|
|
|
|
|
* Values are read on every frame; no reload needed.
|
|
|
|
|
*/
|
|
|
|
|
function wsInboundDebugEnabled(): boolean {
|
|
|
|
|
if (typeof globalThis === "undefined") return false;
|
|
|
|
|
try {
|
|
|
|
|
if (import.meta.env.MODE === "test") return false;
|
|
|
|
|
const ls = (globalThis as unknown as { localStorage?: Storage }).localStorage;
|
|
|
|
|
const raw = ls?.getItem("nanobot_debug_ws")?.trim().toLowerCase() ?? "";
|
|
|
|
|
if (raw === "0" || raw === "false" || raw === "off" || raw === "no") {
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
if (raw === "1" || raw === "true" || raw === "on" || raw === "yes") {
|
|
|
|
|
return true;
|
|
|
|
|
}
|
|
|
|
|
return !import.meta.env.PROD;
|
|
|
|
|
} catch {
|
|
|
|
|
return !import.meta.env.PROD;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function summarizeInboundWsPayload(ev: InboundEvent): unknown {
|
|
|
|
|
const kind = (ev as { event?: string }).event;
|
2026-10-08 11:55:13 +08:00
|
|
|
if (kind === "ready") return { ...ev, upload: "[redacted]" };
|
2026-05-16 08:33:15 +00:00
|
|
|
if (kind !== "delta" && kind !== "reasoning_delta") return ev;
|
|
|
|
|
const row = { ...(ev as object) } as Record<string, unknown>;
|
|
|
|
|
const text = typeof row.text === "string" ? row.text : "";
|
|
|
|
|
const max = 240;
|
|
|
|
|
if (text.length > max) {
|
|
|
|
|
row.text = `${text.slice(0, max)}… (${text.length} chars)`;
|
|
|
|
|
}
|
|
|
|
|
return row;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
type Unsubscribe = () => void;
|
|
|
|
|
type EventHandler = (ev: InboundEvent) => void;
|
2026-10-11 18:00:37 +08:00
|
|
|
export interface TaskNotice {
|
|
|
|
|
event: Extract<InboundEvent, { event: "turn_end" | "recovery_state" }>;
|
|
|
|
|
temporary: boolean;
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
type StatusHandler = (status: ConnectionStatus) => void;
|
2026-10-16 11:38:05 +08:00
|
|
|
type RunCompletionHandler = (chatId: string) => void;
|
2026-05-12 09:05:24 +00:00
|
|
|
type RuntimeModelHandler = (modelName: string | null, modelPreset?: string | null) => void;
|
2026-05-17 23:52:50 +08:00
|
|
|
type SessionUpdateScope = "metadata" | "thread" | string;
|
2026-05-29 03:42:53 +08:00
|
|
|
type SessionUpdateHandler = (
|
|
|
|
|
chatId: string,
|
|
|
|
|
scope?: SessionUpdateScope,
|
|
|
|
|
workspaceScope?: WorkspaceScopePayload,
|
|
|
|
|
) => void;
|
2026-08-12 14:45:12 +08:00
|
|
|
type SidebarStateUpdateHandler = (state: SidebarStatePayload) => void;
|
2026-10-25 20:16:51 +08:00
|
|
|
type PairingChangeHandler = () => void;
|
2026-10-24 00:43:34 +08:00
|
|
|
type RunStatusHandler = (chatId: string, state: RunState) => void;
|
2026-04-18 18:51:53 +00:00
|
|
|
|
2026-05-29 03:42:53 +08:00
|
|
|
/** Structured errors surfaced to the UI.
|
2026-04-21 10:29:47 +00:00
|
|
|
*
|
2026-09-07 15:12:39 +08:00
|
|
|
* Most entries are transport-level or protocol-level faults. Runtime and
|
|
|
|
|
* workspace failures are promoted here when they must remain visible outside
|
|
|
|
|
* the message stream.
|
2026-04-21 10:29:47 +00:00
|
|
|
*/
|
|
|
|
|
export type StreamError =
|
|
|
|
|
/** Server rejected the inbound frame as too large (WS close code 1009).
|
2026-07-14 14:47:42 +08:00
|
|
|
* This is the transport fallback after text and attachment policies have
|
|
|
|
|
* already been checked independently. */
|
2026-07-28 11:40:01 +08:00
|
|
|
| { kind: "message_too_big"; chatId?: string; turnId?: string }
|
|
|
|
|
| {
|
|
|
|
|
kind: "workspace_scope_rejected";
|
|
|
|
|
reason?: string;
|
|
|
|
|
chatId?: string;
|
|
|
|
|
turnId?: string;
|
|
|
|
|
}
|
|
|
|
|
| {
|
|
|
|
|
kind: "turn_rejected";
|
|
|
|
|
detail?: string;
|
|
|
|
|
reason?: string;
|
|
|
|
|
chatId: string;
|
|
|
|
|
turnId: string;
|
2026-09-07 15:12:39 +08:00
|
|
|
}
|
|
|
|
|
| {
|
|
|
|
|
kind: "model_request_failed";
|
|
|
|
|
chatId: string;
|
|
|
|
|
turnId?: string;
|
|
|
|
|
errorKind?: string;
|
|
|
|
|
attempts?: number;
|
2026-07-28 11:40:01 +08:00
|
|
|
};
|
2026-04-21 10:29:47 +00:00
|
|
|
|
|
|
|
|
type ErrorHandler = (error: StreamError) => void;
|
|
|
|
|
|
2026-07-24 17:34:26 +08:00
|
|
|
interface PendingRequest<T> {
|
|
|
|
|
resolve: (value: T) => void;
|
2026-04-18 18:51:53 +00:00
|
|
|
reject: (err: Error) => void;
|
|
|
|
|
timer: ReturnType<typeof setTimeout>;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-16 02:49:00 +08:00
|
|
|
interface PendingWebUIRequest extends PendingRequest<unknown> {
|
2026-08-16 02:56:23 +08:00
|
|
|
serializedFrame: string;
|
2026-08-16 02:49:00 +08:00
|
|
|
}
|
|
|
|
|
|
2026-08-21 23:37:06 +08:00
|
|
|
class WebUIMutationError extends Error {
|
2026-08-10 15:43:54 +08:00
|
|
|
status: number;
|
|
|
|
|
|
|
|
|
|
constructor(status: number, message: string) {
|
|
|
|
|
super(message);
|
|
|
|
|
this.status = status;
|
|
|
|
|
this.name = "WebUIMutationError";
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:44:38 +08:00
|
|
|
type ChatRequestFrame = Extract<Outbound, { type: "new_chat" | "new_temporary_chat" | "fork_chat" }>;
|
|
|
|
|
|
2026-08-07 11:20:08 +08:00
|
|
|
interface PendingChatRequest extends PendingRequest<string> {
|
2026-11-12 14:44:38 +08:00
|
|
|
frame: ChatRequestFrame & { request_id: string };
|
|
|
|
|
phase: "queued" | "sent";
|
2026-08-07 11:20:08 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-24 17:34:26 +08:00
|
|
|
const SYSTEM_COMMAND_TURN_PREFIX = "webui-system:";
|
2026-07-28 11:40:01 +08:00
|
|
|
const TURN_REJECTION_DETAILS = new Set([
|
|
|
|
|
"access_denied",
|
|
|
|
|
"attachment_rejected",
|
|
|
|
|
"message_rejected",
|
|
|
|
|
"missing content",
|
|
|
|
|
"workspace_scope_rejected",
|
|
|
|
|
]);
|
2026-07-24 17:34:26 +08:00
|
|
|
|
|
|
|
|
export function isSystemCommandTurnId(value: string | null | undefined): value is string {
|
|
|
|
|
return typeof value === "string" && value.startsWith(SYSTEM_COMMAND_TURN_PREFIX);
|
2026-06-09 01:08:49 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
export interface NanobotClientOptions {
|
|
|
|
|
url: string;
|
|
|
|
|
reconnect?: boolean;
|
2026-07-28 11:40:01 +08:00
|
|
|
/** Maximum UTF-8 bytes accepted for one websocket message. */
|
|
|
|
|
maxFrameBytes?: number;
|
2026-11-12 14:44:38 +08:00
|
|
|
/** Refresh authentication; discard side effects when the connection's signal aborts. */
|
|
|
|
|
onReauth?: (signal: AbortSignal) => Promise<string | null>;
|
2026-04-18 18:51:53 +00:00
|
|
|
socketFactory?: (url: string) => WebSocket;
|
|
|
|
|
maxBackoffMs?: number;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
function runObservation(event: InboundEvent): RunObservation | null {
|
|
|
|
|
if (!("chat_id" in event) || !event.chat_id) return null;
|
|
|
|
|
const turnId = "turn_id" in event && typeof event.turn_id === "string" ? event.turn_id : null;
|
|
|
|
|
const base = { chatId: event.chat_id, turnId, systemCommand: isSystemCommandTurnId(turnId) };
|
|
|
|
|
switch (event.event) {
|
|
|
|
|
case "message_accepted":
|
|
|
|
|
case "user_message": {
|
|
|
|
|
const activeTurnId = event.active_turn_id ?? (event.starts_turn ? event.turn_id : undefined);
|
2026-10-24 00:43:34 +08:00
|
|
|
if (event.event === "user_message" && event.provenance?.session_message && !activeTurnId) {
|
|
|
|
|
return { ...base, kind: "activity" };
|
|
|
|
|
}
|
2026-10-16 14:35:46 +08:00
|
|
|
return {
|
|
|
|
|
...base,
|
|
|
|
|
kind: event.event === "message_accepted" ? "admission" : "input",
|
|
|
|
|
...(activeTurnId ? { owner: { turnId: activeTurnId, startedAt: event.started_at } } : {}),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
case "goal_status":
|
|
|
|
|
return { ...base, kind: "status", activity: event.status, startedAt: event.started_at };
|
|
|
|
|
case "turn_end":
|
|
|
|
|
return { ...base, kind: "completed" };
|
|
|
|
|
case "error":
|
|
|
|
|
return { ...base, kind: "rejection" };
|
2026-10-24 00:43:34 +08:00
|
|
|
case "delta":
|
|
|
|
|
case "reasoning_delta":
|
|
|
|
|
return { ...base, kind: event.text ? "activity" : "progress" };
|
|
|
|
|
case "stream_end":
|
|
|
|
|
return { ...base, kind: "activity" };
|
|
|
|
|
case "retry_status":
|
2026-11-11 17:32:47 +08:00
|
|
|
return { ...base, lifecycleSignal: true, kind: event.state === "recovered" || event.state === "cleared" ? "progress" : "activity" };
|
2026-10-24 00:43:34 +08:00
|
|
|
case "recovery_state":
|
|
|
|
|
// Supersession resolves the old recovery, not the new user turn that caused it.
|
|
|
|
|
return event.status === "recovered" && event.reason === "superseded"
|
|
|
|
|
? { ...base, kind: "progress" }
|
|
|
|
|
: { ...base, kind: "recovery", active: event.status === "resuming" };
|
|
|
|
|
case "attached":
|
|
|
|
|
return event.recovery_state && event.recovery_state.status !== "recovered"
|
|
|
|
|
? { ...base, kind: "recovery", active: event.recovery_state.status === "resuming" }
|
|
|
|
|
: { ...base, kind: "progress" };
|
2026-10-16 14:35:46 +08:00
|
|
|
case "message":
|
|
|
|
|
return { ...base, kind: "message" };
|
|
|
|
|
default:
|
|
|
|
|
return { ...base, kind: "progress" };
|
|
|
|
|
}
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
/**
|
|
|
|
|
* Singleton WebSocket client that multiplexes chat streams.
|
|
|
|
|
*
|
|
|
|
|
* One socket carries many chat_ids: the server tags every outbound event with
|
|
|
|
|
* ``chat_id``, and this class fans those events out to handlers registered
|
|
|
|
|
* per chat. Reconnects are transparent and re-attach every known chat_id.
|
|
|
|
|
*/
|
|
|
|
|
export class NanobotClient {
|
|
|
|
|
private socket: WebSocket | null = null;
|
2026-10-08 11:55:13 +08:00
|
|
|
private upload: UploadCapability | null = null;
|
|
|
|
|
private receipts = new DeliveryReceipts();
|
2026-04-18 18:51:53 +00:00
|
|
|
private statusHandlers = new Set<StatusHandler>();
|
2026-05-12 09:05:24 +00:00
|
|
|
private runtimeModelHandlers = new Set<RuntimeModelHandler>();
|
2026-05-13 13:10:21 +00:00
|
|
|
private sessionUpdateHandlers = new Set<SessionUpdateHandler>();
|
2026-08-12 14:45:12 +08:00
|
|
|
private sidebarStateUpdateHandlers = new Set<SidebarStateUpdateHandler>();
|
2026-05-19 22:42:38 +08:00
|
|
|
private runStatusHandlers = new Set<RunStatusHandler>();
|
2026-10-16 11:38:05 +08:00
|
|
|
private runCompletionHandlers = new Set<RunCompletionHandler>();
|
2026-04-21 10:29:47 +00:00
|
|
|
private errorHandlers = new Set<ErrorHandler>();
|
2026-10-11 18:00:37 +08:00
|
|
|
private taskNoticeHandlers = new Set<(notice: TaskNotice) => void>();
|
2026-10-25 20:16:51 +08:00
|
|
|
private pairingChangeHandlers = new Set<PairingChangeHandler>();
|
|
|
|
|
private readyHandlers = new Set<() => void>();
|
2026-04-18 18:51:53 +00:00
|
|
|
private chatHandlers = new Map<string, Set<EventHandler>>();
|
2026-10-19 17:13:12 +08:00
|
|
|
private transcriptHandlers = new Map<string, { handler: EventHandler }>();
|
|
|
|
|
/** Inbound frames received while the transcript owner is absent, regardless of observers. */
|
2026-05-16 01:14:11 +08:00
|
|
|
private pendingInboundByChat = new Map<string, InboundEvent[]>();
|
|
|
|
|
private static readonly PENDING_INBOUND_MAX = 2000;
|
2026-04-18 18:51:53 +00:00
|
|
|
private knownChats = new Set<string>();
|
2026-08-06 18:29:04 +08:00
|
|
|
/** Temporary chats are connection-owned and intentionally not reattached. */
|
|
|
|
|
private temporaryChatIds = new Set<string>();
|
2026-10-16 14:35:46 +08:00
|
|
|
private readonly runs = new ClientRunLedger();
|
|
|
|
|
/** Last tracked application frame written, for conservative transport-error attribution. */
|
|
|
|
|
private lastSocketMessageSend: { chatId: string; turnId: string } | null = null;
|
2026-05-16 01:14:11 +08:00
|
|
|
private goalStateByChatId = new Map<string, GoalStateWsPayload>();
|
2026-11-12 14:44:38 +08:00
|
|
|
private pendingChatRequest: PendingChatRequest | null = null;
|
2026-07-24 17:34:26 +08:00
|
|
|
private pendingTranscriptions = new Map<string, PendingRequest<string>>();
|
|
|
|
|
private pendingSystemCommands = new Map<string, PendingRequest<void>>();
|
2026-08-16 02:49:00 +08:00
|
|
|
private pendingWebUIRequests = new Map<string, PendingWebUIRequest>();
|
2026-04-18 18:51:53 +00:00
|
|
|
private sendQueue: Outbound[] = [];
|
|
|
|
|
private reconnectAttempts = 0;
|
2026-11-12 14:44:38 +08:00
|
|
|
private reconnectController: AbortController | null = null;
|
2026-04-18 18:51:53 +00:00
|
|
|
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
|
|
|
|
|
private readonly shouldReconnect: boolean;
|
|
|
|
|
private readonly maxBackoffMs: number;
|
2026-07-28 11:40:01 +08:00
|
|
|
private maxFrameBytes: number | undefined;
|
2026-05-31 17:00:42 +08:00
|
|
|
private socketFactory: (url: string) => WebSocket;
|
2026-04-18 18:51:53 +00:00
|
|
|
private currentUrl: string;
|
|
|
|
|
private status_: ConnectionStatus = "idle";
|
|
|
|
|
private readyChatId: string | null = null;
|
|
|
|
|
// Set by ``close()`` so the onclose handler knows the drop was intentional
|
|
|
|
|
// and must not schedule a reconnect or flip status back to "reconnecting".
|
|
|
|
|
private intentionallyClosed = false;
|
|
|
|
|
|
|
|
|
|
constructor(private options: NanobotClientOptions) {
|
|
|
|
|
this.shouldReconnect = options.reconnect ?? true;
|
|
|
|
|
this.maxBackoffMs = options.maxBackoffMs ?? 15_000;
|
2026-07-28 11:40:01 +08:00
|
|
|
this.maxFrameBytes = this.normalizeMaxFrameBytes(options.maxFrameBytes);
|
2026-05-31 17:00:42 +08:00
|
|
|
this.socketFactory = options.socketFactory ?? createDefaultSocket;
|
2026-04-18 18:51:53 +00:00
|
|
|
this.currentUrl = options.url;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get status(): ConnectionStatus {
|
|
|
|
|
return this.status_;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
get defaultChatId(): string | null {
|
|
|
|
|
return this.readyChatId;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Swap the URL (e.g. after fetching a fresh token) then reconnect. */
|
2026-05-31 17:00:42 +08:00
|
|
|
updateUrl(url: string, socketFactory?: (url: string) => WebSocket): void {
|
2026-04-18 18:51:53 +00:00
|
|
|
this.currentUrl = url;
|
2026-05-31 17:00:42 +08:00
|
|
|
if (socketFactory) {
|
|
|
|
|
this.socketFactory = socketFactory;
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
onStatus(handler: StatusHandler): Unsubscribe {
|
|
|
|
|
this.statusHandlers.add(handler);
|
|
|
|
|
handler(this.status_);
|
|
|
|
|
return () => {
|
|
|
|
|
this.statusHandlers.delete(handler);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 09:05:24 +00:00
|
|
|
onRuntimeModelUpdate(handler: RuntimeModelHandler): Unsubscribe {
|
|
|
|
|
this.runtimeModelHandlers.add(handler);
|
|
|
|
|
return () => {
|
|
|
|
|
this.runtimeModelHandlers.delete(handler);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-13 13:10:21 +00:00
|
|
|
onSessionUpdate(handler: SessionUpdateHandler): Unsubscribe {
|
|
|
|
|
this.sessionUpdateHandlers.add(handler);
|
|
|
|
|
return () => {
|
|
|
|
|
this.sessionUpdateHandlers.delete(handler);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-25 20:16:51 +08:00
|
|
|
onPairingChange(handler: PairingChangeHandler): Unsubscribe {
|
|
|
|
|
this.pairingChangeHandlers.add(handler);
|
|
|
|
|
return () => { this.pairingChangeHandlers.delete(handler); };
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
onReady(handler: () => void): Unsubscribe {
|
|
|
|
|
this.readyHandlers.add(handler);
|
|
|
|
|
return () => { this.readyHandlers.delete(handler); };
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-12 14:45:12 +08:00
|
|
|
onSidebarStateUpdate(handler: SidebarStateUpdateHandler): Unsubscribe {
|
|
|
|
|
this.sidebarStateUpdateHandlers.add(handler);
|
|
|
|
|
return () => {
|
|
|
|
|
this.sidebarStateUpdateHandlers.delete(handler);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-19 22:42:38 +08:00
|
|
|
onRunStatus(handler: RunStatusHandler): Unsubscribe {
|
|
|
|
|
this.runStatusHandlers.add(handler);
|
2026-10-24 00:43:34 +08:00
|
|
|
for (const { chatId, state } of this.runs.states()) {
|
|
|
|
|
handler(chatId, state);
|
2026-05-19 22:42:38 +08:00
|
|
|
}
|
|
|
|
|
return () => {
|
|
|
|
|
this.runStatusHandlers.delete(handler);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-11 18:00:37 +08:00
|
|
|
/** Live lifecycle events, independent of mounted chats. Never replays history. */
|
|
|
|
|
onTaskNotice(handler: (notice: TaskNotice) => void): Unsubscribe {
|
|
|
|
|
this.taskNoticeHandlers.add(handler);
|
|
|
|
|
return () => { this.taskNoticeHandlers.delete(handler); };
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-21 10:29:47 +00:00
|
|
|
onError(handler: ErrorHandler): Unsubscribe {
|
|
|
|
|
this.errorHandlers.add(handler);
|
|
|
|
|
return () => {
|
|
|
|
|
this.errorHandlers.delete(handler);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-24 00:43:34 +08:00
|
|
|
getRunState(chatId: string): RunState {
|
|
|
|
|
return this.runs.view(chatId);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Restore pending history only within its original lifecycle generation. */
|
|
|
|
|
restorePendingRun(chatId: string, generation: number, turnId: string | null): void {
|
|
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "restore-pending", chatId, generation, turnId }));
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
/** Canonical lifecycle turn currently owning the run, retained after completion. */
|
2026-08-15 14:58:35 +08:00
|
|
|
getRunTurnId(chatId: string): string | null {
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.view(chatId).latestTurnId;
|
2026-08-15 14:58:35 +08:00
|
|
|
}
|
|
|
|
|
|
2026-10-16 13:33:41 +08:00
|
|
|
isRunCompleted(chatId: string, turnId: string): boolean {
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.isCompleted({ chatId, turnId });
|
2026-10-16 13:33:41 +08:00
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
/** End the local optimistic run without confirming gateway cancellation. */
|
2026-08-06 18:29:04 +08:00
|
|
|
finishRunLocally(chatId: string): void {
|
2026-10-16 14:35:46 +08:00
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "local-stop", chatId }));
|
2026-08-06 18:29:04 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
updateMaxFrameBytes(maxFrameBytes?: number): void {
|
|
|
|
|
this.maxFrameBytes = this.normalizeMaxFrameBytes(maxFrameBytes);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getRunGeneration(chatId: string): number {
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.view(chatId).generation;
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
hasUnsettledRun(chatId: string): boolean {
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.view(chatId).unsettled;
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-10-16 11:38:05 +08:00
|
|
|
onRunCompletion(handler: RunCompletionHandler): Unsubscribe {
|
|
|
|
|
this.runCompletionHandlers.add(handler);
|
|
|
|
|
return () => this.runCompletionHandlers.delete(handler);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
getUnsettledRunChatIds(): string[] {
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.unresolvedChatIds().filter((chatId) => !this.temporaryChatIds.has(chatId));
|
2026-10-16 11:38:05 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
private normalizeMaxFrameBytes(value: number | undefined): number | undefined {
|
|
|
|
|
if (typeof value !== "number" || !Number.isFinite(value) || value <= 0) {
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
return Math.floor(value);
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
/** Pure preflight; it neither settles runs nor prunes queued frames. */
|
2026-07-28 11:40:01 +08:00
|
|
|
canReconcileCanonicalCompletion(
|
|
|
|
|
chatId: string,
|
|
|
|
|
expectedRunGeneration: number,
|
|
|
|
|
completedTurnIds: readonly string[],
|
|
|
|
|
snapshot?: CanonicalRunSnapshot,
|
|
|
|
|
): boolean {
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.canApplyCanonical({
|
|
|
|
|
chatId, generation: expectedRunGeneration, completedTurnIds, snapshot,
|
|
|
|
|
});
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
/** Preserve explicit completion fences even when a newer run prevents adoption. */
|
2026-07-28 11:40:01 +08:00
|
|
|
reconcileCanonicalCompletion(
|
|
|
|
|
chatId: string,
|
|
|
|
|
expectedRunGeneration: number,
|
|
|
|
|
completedTurnIds: readonly string[],
|
|
|
|
|
snapshot?: CanonicalRunSnapshot,
|
|
|
|
|
): boolean {
|
2026-10-16 14:35:46 +08:00
|
|
|
const result = this.runs.applyCanonical({
|
|
|
|
|
chatId, generation: expectedRunGeneration, completedTurnIds, snapshot,
|
|
|
|
|
});
|
|
|
|
|
this.applyRunEffects(result.effects);
|
|
|
|
|
return result.accepted;
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-09-30 17:40:11 +08:00
|
|
|
fenceCanonicalCompletedTurns(chatId: string, completedTurnIds: readonly string[]): void {
|
2026-10-16 14:35:46 +08:00
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "fence", chatId, completedTurnIds }));
|
2026-09-30 17:40:11 +08:00
|
|
|
}
|
|
|
|
|
|
2026-11-11 17:32:47 +08:00
|
|
|
/** Settle explicit fragment completions without claiming coverage of live content. */
|
|
|
|
|
settleFragmentRunLifecycle(chatId: string, completedTurnIds: readonly string[]): void {
|
|
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "settle-fragment-lifecycle", chatId, completedTurnIds }));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/** Whether a mounted transcript owns delivery for this chat. */
|
|
|
|
|
hasTranscript(chatId: string): boolean {
|
|
|
|
|
return this.transcriptHandlers.has(chatId);
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-16 01:14:11 +08:00
|
|
|
/** Last ``goal_state`` payload for *chatId*, if any frame has arrived this connection. */
|
|
|
|
|
getGoalState(chatId: string): GoalStateWsPayload | undefined {
|
|
|
|
|
return this.goalStateByChatId.get(chatId);
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
private legacyRejectionTarget(ev: Extract<InboundEvent, { event: "error" }>): {
|
|
|
|
|
chatId: string;
|
|
|
|
|
turnId: string;
|
|
|
|
|
} | null {
|
|
|
|
|
if (!ev.detail || !TURN_REJECTION_DETAILS.has(ev.detail)) return null;
|
|
|
|
|
if (
|
|
|
|
|
ev.detail === "workspace_scope_rejected"
|
|
|
|
|
&& ev.chat_id === undefined
|
2026-11-12 14:44:38 +08:00
|
|
|
&& this.pendingChatRequest
|
2026-07-28 11:40:01 +08:00
|
|
|
) return null;
|
2026-10-16 14:35:46 +08:00
|
|
|
return this.runs.soleSentTurn(this.lastSocketMessageSend, ev.chat_id);
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
private applyRunEffects(effects: readonly RunEffect[]): void {
|
|
|
|
|
for (const effect of effects) {
|
|
|
|
|
switch (effect.kind) {
|
|
|
|
|
case "run-status":
|
2026-10-24 00:43:34 +08:00
|
|
|
this.emitRunStatus(effect.chatId, effect.state);
|
2026-10-16 14:35:46 +08:00
|
|
|
break;
|
|
|
|
|
case "completion":
|
|
|
|
|
for (const handler of this.runCompletionHandlers) handler(effect.chatId);
|
|
|
|
|
break;
|
|
|
|
|
case "discard-send":
|
|
|
|
|
this.sendQueue = this.sendQueue.filter((frame) => !(
|
|
|
|
|
frame.type === "message"
|
|
|
|
|
&& frame.chat_id === effect.chatId
|
|
|
|
|
&& frame.turn_id === effect.turnId
|
|
|
|
|
));
|
|
|
|
|
break;
|
2026-11-11 17:32:47 +08:00
|
|
|
case "prune-inbound":
|
|
|
|
|
case "prune-lifecycle-inbound": {
|
2026-10-16 14:35:46 +08:00
|
|
|
const pending = this.pendingInboundByChat.get(effect.chatId);
|
|
|
|
|
if (!pending) break;
|
|
|
|
|
const turnIds = new Set(effect.turnIds);
|
|
|
|
|
const remaining = pending.filter((event) => (
|
|
|
|
|
!("turn_id" in event)
|
|
|
|
|
|| typeof event.turn_id !== "string"
|
|
|
|
|
|| !turnIds.has(event.turn_id)
|
2026-11-11 17:32:47 +08:00
|
|
|
|| (effect.kind === "prune-lifecycle-inbound"
|
|
|
|
|
&& event.event !== "goal_status" && event.event !== "recovery_state" && event.event !== "retry_status")
|
2026-10-16 14:35:46 +08:00
|
|
|
));
|
|
|
|
|
if (remaining.length > 0) this.pendingInboundByChat.set(effect.chatId, remaining);
|
|
|
|
|
else this.pendingInboundByChat.delete(effect.chatId);
|
|
|
|
|
break;
|
|
|
|
|
}
|
|
|
|
|
default: {
|
|
|
|
|
const exhaustive: never = effect;
|
|
|
|
|
return exhaustive;
|
|
|
|
|
}
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
2026-05-16 01:14:11 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private recordGoalStateSnapshot(chatId: string, ev: InboundEvent): void {
|
|
|
|
|
if (ev.event === "goal_state") {
|
|
|
|
|
this.goalStateByChatId.set(chatId, ev.goal_state);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
if (ev.event === "turn_end" && ev.goal_state != null && typeof ev.goal_state === "object") {
|
|
|
|
|
this.goalStateByChatId.set(chatId, ev.goal_state);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-19 17:13:12 +08:00
|
|
|
/** Observe live chat events without consuming transcript replay. Auto-attaches. */
|
2026-04-18 18:51:53 +00:00
|
|
|
onChat(chatId: string, handler: EventHandler): Unsubscribe {
|
|
|
|
|
let handlers = this.chatHandlers.get(chatId);
|
|
|
|
|
if (!handlers) {
|
|
|
|
|
handlers = new Set();
|
|
|
|
|
this.chatHandlers.set(chatId, handlers);
|
|
|
|
|
}
|
|
|
|
|
handlers.add(handler);
|
|
|
|
|
this.attach(chatId);
|
|
|
|
|
return () => {
|
|
|
|
|
const current = this.chatHandlers.get(chatId);
|
|
|
|
|
if (!current) return;
|
|
|
|
|
current.delete(handler);
|
|
|
|
|
if (current.size === 0) this.chatHandlers.delete(chatId);
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-19 17:13:12 +08:00
|
|
|
/** Own transcript delivery: consume the pending tail once, then receive live events. */
|
|
|
|
|
onTranscript(chatId: string, handler: EventHandler): Unsubscribe {
|
|
|
|
|
if (this.transcriptHandlers.has(chatId)) {
|
|
|
|
|
throw new Error(`Transcript already subscribed: ${chatId}`);
|
|
|
|
|
}
|
|
|
|
|
const subscription = { handler };
|
|
|
|
|
this.transcriptHandlers.set(chatId, subscription);
|
|
|
|
|
const pending = this.pendingInboundByChat.get(chatId);
|
|
|
|
|
this.pendingInboundByChat.delete(chatId);
|
|
|
|
|
for (const event of pending ?? []) handler(event);
|
|
|
|
|
this.attach(chatId);
|
|
|
|
|
return () => {
|
|
|
|
|
if (this.transcriptHandlers.get(chatId) === subscription) {
|
|
|
|
|
this.transcriptHandlers.delete(chatId);
|
|
|
|
|
}
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
connect(): void {
|
|
|
|
|
if (this.socket && this.socket.readyState < WS_CLOSING) return;
|
2026-11-12 14:44:38 +08:00
|
|
|
this.cancelReconnect();
|
2026-04-18 18:51:53 +00:00
|
|
|
this.intentionallyClosed = false;
|
|
|
|
|
this.setStatus("connecting");
|
|
|
|
|
const sock = this.socketFactory(this.currentUrl);
|
|
|
|
|
this.socket = sock;
|
2026-11-12 14:44:38 +08:00
|
|
|
sock.onopen = () => { if (this.socket === sock) this.handleOpen(); };
|
|
|
|
|
sock.onmessage = (ev) => { if (this.socket === sock) this.handleMessage(ev); };
|
|
|
|
|
sock.onerror = () => { if (this.socket === sock) this.setStatus("error"); };
|
|
|
|
|
sock.onclose = (ev) => { if (this.socket === sock) this.handleClose(ev); };
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
close(): void {
|
|
|
|
|
this.intentionallyClosed = true;
|
|
|
|
|
const sock = this.socket;
|
2026-11-12 14:44:38 +08:00
|
|
|
// Settle connection-owned work now, not in a possibly delayed close callback.
|
|
|
|
|
this.handleClose();
|
2026-04-18 18:51:53 +00:00
|
|
|
try {
|
|
|
|
|
sock?.close();
|
|
|
|
|
} catch {
|
2026-11-12 14:44:38 +08:00
|
|
|
// Local cleanup has already completed.
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-05 19:24:41 +08:00
|
|
|
discardTemporaryChat(chatId: string): void {
|
2026-08-07 11:20:08 +08:00
|
|
|
if (!this.temporaryChatIds.has(chatId)) return;
|
2026-08-05 19:24:41 +08:00
|
|
|
if (this.socket?.readyState === WS_OPEN) {
|
|
|
|
|
this.rawSend({ type: "discard_temporary_chat", chat_id: chatId });
|
|
|
|
|
}
|
|
|
|
|
this.forgetTemporaryChat(chatId);
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
/** Ask the server to provision a new chat_id; resolves with the assigned id. */
|
2026-05-29 03:42:53 +08:00
|
|
|
newChat(timeoutMs: number = 5_000, workspaceScope?: WorkspaceScopePayload | null): Promise<string> {
|
2026-11-12 14:44:38 +08:00
|
|
|
return this.requestChat({
|
|
|
|
|
type: "new_chat",
|
|
|
|
|
...(workspaceScope ? { workspace_scope: workspaceScope } : {}),
|
|
|
|
|
}, timeoutMs, "newChat");
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
2026-08-07 11:20:08 +08:00
|
|
|
/** Ask the WebUI gateway to create a connection-owned non-persistent chat. */
|
|
|
|
|
newTemporaryChat(timeoutMs: number = 5_000): Promise<string> {
|
2026-11-12 14:44:38 +08:00
|
|
|
return this.requestChat({ type: "new_temporary_chat" }, timeoutMs, "newTemporaryChat");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private requestChat(frame: ChatRequestFrame, timeoutMs: number, name: string): Promise<string> {
|
|
|
|
|
if (this.intentionallyClosed) return Promise.reject(new Error("socket closed"));
|
|
|
|
|
if (this.pendingChatRequest) return Promise.reject(new Error("newChat already in flight"));
|
2026-08-07 11:20:08 +08:00
|
|
|
return new Promise<string>((resolve, reject) => {
|
2026-11-12 14:44:38 +08:00
|
|
|
const pending: PendingChatRequest = {
|
|
|
|
|
frame: { ...frame, request_id: crypto.randomUUID() },
|
|
|
|
|
phase: "queued", resolve, reject,
|
|
|
|
|
timer: setTimeout(() => {
|
|
|
|
|
const sent = pending.phase === "sent";
|
|
|
|
|
this.pendingChatRequest = null;
|
|
|
|
|
reject(new Error(`${name} timed out${sent ? "; creation outcome is unknown" : " before sending"}`));
|
|
|
|
|
}, timeoutMs),
|
|
|
|
|
};
|
|
|
|
|
this.pendingChatRequest = pending;
|
|
|
|
|
this.sendPendingChat();
|
2026-08-07 11:20:08 +08:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:44:38 +08:00
|
|
|
private sendPendingChat(): void {
|
|
|
|
|
const pending = this.pendingChatRequest;
|
|
|
|
|
if (!pending || pending.phase !== "queued" || this.socket?.readyState !== WS_OPEN) return;
|
|
|
|
|
try {
|
|
|
|
|
this.socket.send(JSON.stringify(pending.frame));
|
|
|
|
|
pending.phase = "sent";
|
|
|
|
|
this.lastSocketMessageSend = null;
|
|
|
|
|
} catch {
|
|
|
|
|
this.rejectPendingChat("Could not send chat request");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private rejectPendingChat(detail: string): void {
|
|
|
|
|
const pending = this.pendingChatRequest;
|
|
|
|
|
if (!pending) return;
|
|
|
|
|
this.pendingChatRequest = null;
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
pending.reject(new Error(detail));
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 01:08:49 +08:00
|
|
|
transcribeAudio(
|
|
|
|
|
dataUrl: string,
|
|
|
|
|
options?: { durationMs?: number; timeoutMs?: number },
|
|
|
|
|
): Promise<string> {
|
|
|
|
|
const requestId = crypto.randomUUID();
|
|
|
|
|
const timeoutMs = options?.timeoutMs ?? 120_000;
|
|
|
|
|
return new Promise<string>((resolve, reject) => {
|
|
|
|
|
const timer = setTimeout(() => {
|
|
|
|
|
this.pendingTranscriptions.delete(requestId);
|
|
|
|
|
reject(new Error("transcription timed out"));
|
|
|
|
|
}, timeoutMs);
|
|
|
|
|
this.pendingTranscriptions.set(requestId, { resolve, reject, timer });
|
|
|
|
|
this.queueSend({
|
|
|
|
|
type: "transcribe_audio",
|
|
|
|
|
request_id: requestId,
|
|
|
|
|
data_url: dataUrl,
|
|
|
|
|
...(options?.durationMs !== undefined ? { duration_ms: options.durationMs } : {}),
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-10 15:43:54 +08:00
|
|
|
/**
|
2026-08-16 02:49:00 +08:00
|
|
|
* Send one WebUI mutation over the authenticated socket. Pending requests are
|
|
|
|
|
* replayed with the same request_id after reconnect so the gateway can join or
|
|
|
|
|
* replay the original operation. A client-side timeout still ends all retries.
|
2026-08-10 15:43:54 +08:00
|
|
|
*/
|
|
|
|
|
requestMutation<T>(
|
|
|
|
|
action: string,
|
|
|
|
|
payload: Record<string, unknown> = {},
|
|
|
|
|
timeoutMs: number = 20_000,
|
|
|
|
|
): Promise<T> {
|
|
|
|
|
const socket = this.socket;
|
|
|
|
|
if (!socket || socket.readyState !== WS_OPEN) {
|
|
|
|
|
return Promise.reject(
|
|
|
|
|
new WebUIMutationError(503, "WebUI connection is not open"),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
const requestId = crypto.randomUUID();
|
|
|
|
|
const frame: Outbound = {
|
|
|
|
|
type: "webui_request",
|
|
|
|
|
request_id: requestId,
|
|
|
|
|
action,
|
|
|
|
|
payload,
|
|
|
|
|
};
|
|
|
|
|
if (!this.frameFitsTransport(frame)) {
|
|
|
|
|
return Promise.reject(
|
|
|
|
|
new WebUIMutationError(413, "WebUI mutation payload is too large"),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return new Promise<T>((resolve, reject) => {
|
2026-08-16 02:56:23 +08:00
|
|
|
let serializedFrame: string;
|
|
|
|
|
try {
|
|
|
|
|
serializedFrame = JSON.stringify(frame);
|
|
|
|
|
} catch {
|
|
|
|
|
reject(new WebUIMutationError(503, "Could not encode WebUI request"));
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-08-10 15:43:54 +08:00
|
|
|
const timer = setTimeout(() => {
|
|
|
|
|
this.pendingWebUIRequests.delete(requestId);
|
|
|
|
|
reject(
|
|
|
|
|
new WebUIMutationError(
|
|
|
|
|
504,
|
|
|
|
|
`WebUI request timed out after ${timeoutMs}ms`,
|
|
|
|
|
),
|
|
|
|
|
);
|
|
|
|
|
}, timeoutMs);
|
|
|
|
|
this.pendingWebUIRequests.set(requestId, {
|
|
|
|
|
resolve: (value) => resolve(value as T),
|
|
|
|
|
reject,
|
|
|
|
|
timer,
|
2026-08-16 02:56:23 +08:00
|
|
|
serializedFrame,
|
2026-08-10 15:43:54 +08:00
|
|
|
});
|
|
|
|
|
try {
|
2026-08-16 02:56:23 +08:00
|
|
|
socket.send(serializedFrame);
|
2026-08-10 15:43:54 +08:00
|
|
|
} catch {
|
|
|
|
|
clearTimeout(timer);
|
|
|
|
|
this.pendingWebUIRequests.delete(requestId);
|
|
|
|
|
reject(new WebUIMutationError(503, "Could not send WebUI request"));
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-05 19:49:34 +08:00
|
|
|
/** Ask the server to create a non-destructive fork before a user-message index. */
|
|
|
|
|
forkChat(
|
|
|
|
|
sourceChatId: string,
|
|
|
|
|
beforeUserIndex: number,
|
2026-06-10 02:07:47 +08:00
|
|
|
title?: string,
|
2026-06-05 19:49:34 +08:00
|
|
|
timeoutMs: number = 5_000,
|
|
|
|
|
): Promise<string> {
|
2026-11-12 14:44:38 +08:00
|
|
|
return this.requestChat({
|
|
|
|
|
type: "fork_chat",
|
|
|
|
|
source_chat_id: sourceChatId,
|
|
|
|
|
before_user_index: beforeUserIndex,
|
|
|
|
|
...(title?.trim() ? { title: title.trim() } : {}),
|
|
|
|
|
}, timeoutMs, "forkChat");
|
2026-06-05 19:49:34 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
attach(chatId: string): void {
|
2026-08-07 11:20:08 +08:00
|
|
|
if (this.temporaryChatIds.has(chatId)) return;
|
2026-04-18 18:51:53 +00:00
|
|
|
this.knownChats.add(chatId);
|
|
|
|
|
if (this.socket?.readyState === WS_OPEN) {
|
|
|
|
|
this.queueSend({ type: "attach", chat_id: chatId });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-08 11:55:13 +08:00
|
|
|
async sendAttachments(
|
|
|
|
|
chatId: string, content: string, media: OutboundMedia[],
|
|
|
|
|
options?: Parameters<NanobotClient["sendMessage"]>[3],
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
const socket = this.socket;
|
|
|
|
|
const capability = this.upload;
|
|
|
|
|
const turnId = options?.turnId ?? crypto.randomUUID();
|
|
|
|
|
const stillConnected = () => this.socket === socket
|
|
|
|
|
&& socket?.readyState === WS_OPEN && this.upload === capability;
|
2026-10-24 00:43:34 +08:00
|
|
|
this.applyRunEffects(this.runs.transition({
|
|
|
|
|
kind: "submit", chatId, turnId,
|
|
|
|
|
role: options?.startsNewRun === false ? "supplement" : "candidate-owner",
|
|
|
|
|
}));
|
2026-10-08 11:55:13 +08:00
|
|
|
try {
|
|
|
|
|
const references = await uploadAttachments(media, capability,
|
|
|
|
|
typeof window !== "undefined" ? window.location.href : this.currentUrl,
|
|
|
|
|
stillConnected);
|
|
|
|
|
if (!stillConnected()) throw new Error("Connection changed during attachment send");
|
|
|
|
|
await this.receipts.wait(turnId, () => {
|
|
|
|
|
if (!this.sendMessage(chatId, content, references, { ...options, turnId })) {
|
|
|
|
|
throw new Error("Message exceeds the gateway's WebSocket frame limit; draft retained");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
2026-10-24 00:43:34 +08:00
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "reject", chatId, turnId }));
|
2026-10-08 11:55:13 +08:00
|
|
|
this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "attachment_rejected",
|
|
|
|
|
reason: error instanceof Error ? error.message : "Attachment send failed" });
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-26 23:35:26 +08:00
|
|
|
async sendUserShellCommand(
|
|
|
|
|
chatId: string, content: string, options?: Parameters<NanobotClient["sendMessage"]>[3],
|
|
|
|
|
): Promise<void> {
|
|
|
|
|
const turnId = options?.turnId ?? crypto.randomUUID();
|
|
|
|
|
try {
|
|
|
|
|
await this.receipts.wait(turnId, () => {
|
|
|
|
|
if (!this.sendMessage(chatId, content, undefined, { ...options, turnId, userShell: true, startsNewRun: false })) {
|
|
|
|
|
throw new Error("Shell command was not sent; draft retained");
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
} catch (error) {
|
|
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "reject", chatId, turnId }));
|
|
|
|
|
this.emitError({ kind: "turn_rejected", chatId, turnId, detail: "message_rejected",
|
|
|
|
|
reason: error instanceof Error ? error.message : "Shell command send failed" });
|
|
|
|
|
throw error;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-08 09:40:15 +00:00
|
|
|
sendMessage(
|
|
|
|
|
chatId: string,
|
|
|
|
|
content: string,
|
2026-10-08 11:55:13 +08:00
|
|
|
media?: AttachmentReference[],
|
2026-05-24 13:38:37 +08:00
|
|
|
options?: {
|
|
|
|
|
cliApps?: OutboundCliAppMention[];
|
|
|
|
|
mcpPresets?: OutboundMcpPresetMention[];
|
2026-08-02 22:04:59 +08:00
|
|
|
sessionMentions?: SessionMention[];
|
2026-07-22 22:35:39 +08:00
|
|
|
quotedContext?: string;
|
2026-09-13 05:20:26 +08:00
|
|
|
intent?: "create_automation";
|
2026-10-26 23:35:26 +08:00
|
|
|
userShell?: boolean;
|
2026-05-29 03:42:53 +08:00
|
|
|
workspaceScope?: WorkspaceScopePayload | null;
|
2026-06-06 19:49:33 +08:00
|
|
|
turnId?: string;
|
2026-07-28 11:40:01 +08:00
|
|
|
/** False for side-channel or injected messages that do not own a lifecycle. */
|
|
|
|
|
startsNewRun?: boolean;
|
2026-05-24 13:38:37 +08:00
|
|
|
},
|
2026-10-08 11:55:13 +08:00
|
|
|
): boolean {
|
2026-10-26 23:35:26 +08:00
|
|
|
if (options?.userShell && this.socket?.readyState !== WS_OPEN) return false;
|
2026-08-07 11:20:08 +08:00
|
|
|
const temporary = this.temporaryChatIds.has(chatId);
|
2026-08-05 19:24:41 +08:00
|
|
|
if (!temporary) this.knownChats.add(chatId);
|
2026-05-08 09:40:15 +00:00
|
|
|
const frame: Outbound = {
|
|
|
|
|
type: "message",
|
|
|
|
|
chat_id: chatId,
|
|
|
|
|
content,
|
|
|
|
|
...(media && media.length > 0 ? { media } : {}),
|
2026-05-22 22:25:12 +08:00
|
|
|
...(options?.cliApps?.length ? { cli_apps: options.cliApps } : {}),
|
2026-05-24 13:38:37 +08:00
|
|
|
...(options?.mcpPresets?.length ? { mcp_presets: options.mcpPresets } : {}),
|
2026-08-02 22:04:59 +08:00
|
|
|
...(options?.sessionMentions?.length
|
|
|
|
|
? { session_mentions: options.sessionMentions }
|
|
|
|
|
: {}),
|
2026-07-22 22:35:39 +08:00
|
|
|
...(options?.quotedContext?.trim() ? { quoted_context: options.quotedContext.trim() } : {}),
|
2026-09-13 05:20:26 +08:00
|
|
|
...(options?.intent === "create_automation" ? { intent: options.intent } : {}),
|
2026-10-26 23:35:26 +08:00
|
|
|
...(options?.userShell ? { user_shell: true } : {}),
|
2026-05-29 03:42:53 +08:00
|
|
|
...(options?.workspaceScope ? { workspace_scope: options.workspaceScope } : {}),
|
2026-06-06 19:49:33 +08:00
|
|
|
...(options?.turnId ? { turn_id: options.turnId } : {}),
|
2026-05-08 09:40:15 +00:00
|
|
|
webui: true,
|
|
|
|
|
};
|
2026-07-28 11:40:01 +08:00
|
|
|
if (!this.frameFitsTransport(frame)) {
|
|
|
|
|
if (options?.turnId && isSystemCommandTurnId(options.turnId)) {
|
|
|
|
|
this.rejectSystemCommand(options.turnId, "message_too_big");
|
|
|
|
|
}
|
|
|
|
|
this.emitError({
|
|
|
|
|
kind: "message_too_big",
|
|
|
|
|
chatId,
|
|
|
|
|
...(options?.turnId ? { turnId: options.turnId } : {}),
|
|
|
|
|
});
|
2026-10-08 11:55:13 +08:00
|
|
|
return false;
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
if (options?.turnId && !isSystemCommandTurnId(options.turnId)) {
|
2026-10-16 14:35:46 +08:00
|
|
|
this.applyRunEffects(this.runs.transition({
|
|
|
|
|
kind: "submit",
|
|
|
|
|
chatId,
|
|
|
|
|
turnId: options.turnId,
|
|
|
|
|
role: options.startsNewRun === false ? "supplement" : "candidate-owner",
|
|
|
|
|
}));
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
2026-10-26 23:35:26 +08:00
|
|
|
if (options?.userShell) return this.rawSend(frame);
|
2026-04-21 10:29:47 +00:00
|
|
|
this.queueSend(frame);
|
2026-10-08 11:55:13 +08:00
|
|
|
return true;
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
2026-07-24 17:34:26 +08:00
|
|
|
sendSystemCommand(chatId: string, command: string, timeoutMs = 5_000): Promise<void> {
|
|
|
|
|
const normalized = command.trim();
|
|
|
|
|
const turnId = `${SYSTEM_COMMAND_TURN_PREFIX}${crypto.randomUUID()}`;
|
|
|
|
|
return new Promise<void>((resolve, reject) => {
|
|
|
|
|
const timer = setTimeout(() => {
|
|
|
|
|
this.pendingSystemCommands.delete(turnId);
|
|
|
|
|
reject(new Error("system command timed out"));
|
|
|
|
|
}, timeoutMs);
|
|
|
|
|
this.pendingSystemCommands.set(turnId, { resolve, reject, timer });
|
|
|
|
|
this.sendMessage(chatId, normalized, undefined, { turnId });
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 03:42:53 +08:00
|
|
|
setWorkspaceScope(chatId: string, workspaceScope: WorkspaceScopePayload): void {
|
2026-08-07 11:20:08 +08:00
|
|
|
if (this.temporaryChatIds.has(chatId)) return;
|
2026-05-29 03:42:53 +08:00
|
|
|
this.knownChats.add(chatId);
|
|
|
|
|
this.queueSend({
|
|
|
|
|
type: "set_workspace_scope",
|
|
|
|
|
chat_id: chatId,
|
|
|
|
|
workspace_scope: workspaceScope,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-10 15:43:54 +08:00
|
|
|
setSidebarState(state: SidebarStatePayload): Promise<SidebarStatePayload> {
|
|
|
|
|
return this.requestMutation<SidebarStatePayload>("sidebar.update", { state });
|
2026-08-06 18:21:16 +08:00
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
|
|
|
|
|
private setStatus(status: ConnectionStatus): void {
|
|
|
|
|
if (this.status_ === status) return;
|
|
|
|
|
this.status_ = status;
|
|
|
|
|
for (const handler of this.statusHandlers) handler(status);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private handleOpen(): void {
|
|
|
|
|
this.setStatus("open");
|
|
|
|
|
this.reconnectAttempts = 0;
|
|
|
|
|
for (const chatId of this.knownChats) {
|
|
|
|
|
this.rawSend({ type: "attach", chat_id: chatId });
|
|
|
|
|
}
|
2026-08-16 02:49:00 +08:00
|
|
|
for (const pending of this.pendingWebUIRequests.values()) {
|
2026-08-16 02:56:23 +08:00
|
|
|
this.rawSendSerialized(pending.serializedFrame);
|
2026-08-16 02:49:00 +08:00
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
const queued = this.sendQueue.splice(0);
|
|
|
|
|
for (const frame of queued) this.rawSend(frame);
|
2026-11-12 14:44:38 +08:00
|
|
|
this.sendPendingChat();
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private handleMessage(ev: MessageEvent): void {
|
|
|
|
|
let parsed: InboundEvent;
|
|
|
|
|
try {
|
|
|
|
|
parsed = JSON.parse(typeof ev.data === "string" ? ev.data : "") as InboundEvent;
|
2026-09-06 02:11:19 +08:00
|
|
|
if (decodeNotification(parsed) === null) return;
|
2026-04-18 18:51:53 +00:00
|
|
|
} catch {
|
2026-05-16 08:33:15 +00:00
|
|
|
if (wsInboundDebugEnabled()) {
|
|
|
|
|
const raw = typeof ev.data === "string" ? ev.data : String(ev.data);
|
|
|
|
|
console.warn(
|
|
|
|
|
"[nanobot ws inbound] invalid JSON",
|
|
|
|
|
raw.length > 400 ? `${raw.slice(0, 400)}… (${raw.length} chars)` : raw,
|
|
|
|
|
);
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-16 08:33:15 +00:00
|
|
|
if (wsInboundDebugEnabled()) {
|
|
|
|
|
console.log("[nanobot ws inbound]", summarizeInboundWsPayload(parsed));
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-10 15:43:54 +08:00
|
|
|
if (parsed.event === "webui_response") {
|
|
|
|
|
const pending = this.pendingWebUIRequests.get(parsed.request_id);
|
|
|
|
|
if (!pending) return;
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
this.pendingWebUIRequests.delete(parsed.request_id);
|
|
|
|
|
if (parsed.ok) {
|
|
|
|
|
pending.resolve(parsed.result);
|
|
|
|
|
} else {
|
|
|
|
|
const status = Number.isFinite(parsed.error?.status)
|
|
|
|
|
? parsed.error.status
|
|
|
|
|
: 500;
|
|
|
|
|
const message = parsed.error?.message || "WebUI mutation failed";
|
|
|
|
|
pending.reject(new WebUIMutationError(status, message));
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:44:38 +08:00
|
|
|
if (parsed.event === "error" && parsed.request_id !== undefined) {
|
|
|
|
|
const pending = this.pendingChatRequest;
|
|
|
|
|
if (pending && pending.phase !== "queued" && pending.frame.request_id === parsed.request_id) {
|
|
|
|
|
this.rejectPendingChat([parsed.detail, parsed.reason].filter(Boolean).join(":") || "server error");
|
|
|
|
|
if (parsed.detail === "workspace_scope_rejected") {
|
|
|
|
|
this.emitError({ kind: "workspace_scope_rejected", reason: parsed.reason });
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
if (parsed.event === "error" && !parsed.turn_id) {
|
|
|
|
|
const fallback = this.legacyRejectionTarget(parsed);
|
|
|
|
|
if (fallback) {
|
|
|
|
|
parsed = {
|
|
|
|
|
...parsed,
|
|
|
|
|
chat_id: parsed.chat_id ?? fallback.chatId,
|
|
|
|
|
turn_id: fallback.turnId,
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (
|
|
|
|
|
(parsed.event === "goal_status" || parsed.event === "turn_end")
|
|
|
|
|
&& !parsed.turn_id
|
|
|
|
|
) {
|
2026-10-16 14:35:46 +08:00
|
|
|
const fallbackTurnId = this.runs.soleUnsettledTurn(parsed.chat_id);
|
2026-07-28 11:40:01 +08:00
|
|
|
if (fallbackTurnId) parsed = { ...parsed, turn_id: fallbackTurnId };
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-08 11:55:13 +08:00
|
|
|
this.receipts.event(parsed);
|
2026-07-24 17:34:26 +08:00
|
|
|
const turnId = "turn_id" in parsed && typeof parsed.turn_id === "string"
|
|
|
|
|
? parsed.turn_id
|
|
|
|
|
: null;
|
2026-10-16 14:35:46 +08:00
|
|
|
const correlatedChatId = "chat_id" in parsed ? parsed.chat_id : undefined;
|
|
|
|
|
const observation = runObservation(parsed);
|
|
|
|
|
if (observation) {
|
|
|
|
|
const result = this.runs.observe(observation);
|
|
|
|
|
this.applyRunEffects(result.effects);
|
|
|
|
|
if (result.forward === "drop") return;
|
|
|
|
|
if (
|
|
|
|
|
result.forward === "without-owner"
|
|
|
|
|
&& (parsed.event === "message_accepted" || parsed.event === "user_message")
|
|
|
|
|
) {
|
|
|
|
|
parsed = { ...parsed, active_turn_id: undefined, started_at: undefined, starts_turn: false };
|
|
|
|
|
}
|
2026-08-16 19:36:34 +08:00
|
|
|
}
|
2026-07-28 11:40:01 +08:00
|
|
|
if (parsed.event === "message_accepted") {
|
2026-07-29 23:15:45 +08:00
|
|
|
if (!isSystemCommandTurnId(turnId)) {
|
|
|
|
|
this.dispatch(parsed.chat_id, parsed);
|
|
|
|
|
}
|
2026-07-28 11:40:01 +08:00
|
|
|
return;
|
|
|
|
|
}
|
2026-07-24 17:34:26 +08:00
|
|
|
if (isSystemCommandTurnId(turnId)) {
|
2026-07-28 11:40:01 +08:00
|
|
|
if (parsed.event === "error") {
|
|
|
|
|
this.rejectSystemCommand(
|
|
|
|
|
turnId,
|
|
|
|
|
[parsed.detail, parsed.reason].filter(Boolean).join(":") || "server error",
|
|
|
|
|
);
|
|
|
|
|
} else if (parsed.event === "message" || parsed.event === "turn_end") {
|
2026-07-24 17:34:26 +08:00
|
|
|
this.resolveSystemCommand(turnId);
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
if (parsed.event === "error" && correlatedChatId && turnId) {
|
|
|
|
|
if (parsed.detail !== "workspace_scope_rejected") {
|
|
|
|
|
this.emitError({
|
|
|
|
|
kind: "turn_rejected",
|
|
|
|
|
detail: parsed.detail,
|
|
|
|
|
reason: parsed.reason,
|
|
|
|
|
chatId: correlatedChatId,
|
|
|
|
|
turnId,
|
|
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
if (parsed.event === "ready") {
|
2026-10-08 11:55:13 +08:00
|
|
|
this.upload = uploadCapability(parsed.upload);
|
2026-04-18 18:51:53 +00:00
|
|
|
this.readyChatId = parsed.chat_id;
|
|
|
|
|
this.knownChats.add(parsed.chat_id);
|
2026-10-25 20:16:51 +08:00
|
|
|
for (const handler of this.readyHandlers) {
|
|
|
|
|
try { handler(); } catch { /* One listener must not block another ready consumer. */ }
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (parsed.event === "attached") {
|
2026-11-12 14:44:38 +08:00
|
|
|
const pending = this.pendingChatRequest;
|
|
|
|
|
const known = this.knownChats.has(parsed.chat_id) || this.temporaryChatIds.has(parsed.chat_id);
|
|
|
|
|
const matches = pending?.phase === "sent" && parsed.request_id === pending.frame.request_id;
|
|
|
|
|
if (matches) {
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
this.pendingChatRequest = null;
|
|
|
|
|
pending.resolve(parsed.chat_id);
|
|
|
|
|
}
|
|
|
|
|
if (!matches && parsed.request_id !== undefined && !known) {
|
|
|
|
|
// A late success is not a new user selection; temporary resources need disposal.
|
|
|
|
|
if (parsed.temporary) this.rawSend({ type: "discard_temporary_chat", chat_id: parsed.chat_id });
|
|
|
|
|
return;
|
|
|
|
|
}
|
2026-08-07 11:20:08 +08:00
|
|
|
if (parsed.temporary === true) {
|
|
|
|
|
this.temporaryChatIds.add(parsed.chat_id);
|
|
|
|
|
} else {
|
|
|
|
|
this.knownChats.add(parsed.chat_id);
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
this.dispatch(parsed.chat_id, parsed);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-25 20:16:51 +08:00
|
|
|
if (parsed.event === "pairing_changed") {
|
|
|
|
|
for (const handler of this.pairingChangeHandlers) {
|
|
|
|
|
try { handler(); } catch { /* One listener must not block another pairing refresh. */ }
|
|
|
|
|
}
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-12 09:05:24 +00:00
|
|
|
if (parsed.event === "runtime_model_updated") {
|
|
|
|
|
this.emitRuntimeModelUpdate(parsed.model_name || null, parsed.model_preset ?? null);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 01:08:49 +08:00
|
|
|
if (parsed.event === "transcription_result") {
|
|
|
|
|
this.resolveTranscription(parsed.request_id, parsed.text);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (parsed.event === "transcription_error") {
|
|
|
|
|
this.rejectTranscription(parsed.request_id, parsed.detail || "error");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-13 13:10:21 +00:00
|
|
|
if (parsed.event === "session_updated") {
|
2026-05-29 03:42:53 +08:00
|
|
|
this.emitSessionUpdate(parsed.chat_id, parsed.scope, parsed.workspace_scope);
|
2026-05-13 13:10:21 +00:00
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-12 14:45:12 +08:00
|
|
|
if (parsed.event === "sidebar_state_updated") {
|
|
|
|
|
this.emitSidebarStateUpdate(parsed.state);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 03:42:53 +08:00
|
|
|
if (parsed.event === "error" && parsed.detail === "workspace_scope_rejected") {
|
|
|
|
|
this.emitError({
|
|
|
|
|
kind: "workspace_scope_rejected",
|
|
|
|
|
reason: parsed.reason,
|
|
|
|
|
chatId: parsed.chat_id,
|
2026-07-28 11:40:01 +08:00
|
|
|
turnId: parsed.turn_id,
|
2026-05-29 03:42:53 +08:00
|
|
|
});
|
2026-06-05 19:49:34 +08:00
|
|
|
}
|
|
|
|
|
|
2026-10-16 14:35:46 +08:00
|
|
|
if (correlatedChatId) {
|
|
|
|
|
this.recordGoalStateSnapshot(correlatedChatId, parsed);
|
2026-10-20 13:08:13 +08:00
|
|
|
if ((parsed.event === "turn_end" || parsed.event === "recovery_state")
|
|
|
|
|
&& (this.knownChats.has(correlatedChatId) || this.temporaryChatIds.has(correlatedChatId))) {
|
2026-10-11 18:00:37 +08:00
|
|
|
for (const handler of this.taskNoticeHandlers) {
|
2026-10-20 13:08:13 +08:00
|
|
|
// Optional browser features must not interrupt delivery or cleanup.
|
2026-10-11 18:00:37 +08:00
|
|
|
try { handler({ event: parsed, temporary: this.temporaryChatIds.has(correlatedChatId) }); }
|
|
|
|
|
catch { /* The notification owner reports its own delivery failure. */ }
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-10-16 14:35:46 +08:00
|
|
|
this.dispatch(correlatedChatId, parsed);
|
2026-05-16 01:14:11 +08:00
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
2026-05-12 09:05:24 +00:00
|
|
|
private emitRuntimeModelUpdate(modelName: string | null, modelPreset?: string | null): void {
|
|
|
|
|
for (const handler of this.runtimeModelHandlers) {
|
|
|
|
|
handler(modelName, modelPreset);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-05-29 03:42:53 +08:00
|
|
|
private emitSessionUpdate(
|
|
|
|
|
chatId: string,
|
|
|
|
|
scope?: SessionUpdateScope,
|
|
|
|
|
workspaceScope?: WorkspaceScopePayload,
|
|
|
|
|
): void {
|
2026-05-13 13:10:21 +00:00
|
|
|
for (const handler of this.sessionUpdateHandlers) {
|
2026-05-29 03:42:53 +08:00
|
|
|
handler(chatId, scope, workspaceScope);
|
2026-05-13 13:10:21 +00:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-12 14:45:12 +08:00
|
|
|
private emitSidebarStateUpdate(state: SidebarStatePayload): void {
|
|
|
|
|
for (const handler of this.sidebarStateUpdateHandlers) {
|
|
|
|
|
handler(state);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-24 00:43:34 +08:00
|
|
|
private emitRunStatus(chatId: string, state: RunState): void {
|
2026-05-19 22:42:38 +08:00
|
|
|
for (const handler of this.runStatusHandlers) {
|
2026-10-24 00:43:34 +08:00
|
|
|
handler(chatId, state);
|
2026-05-19 22:42:38 +08:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
private dispatch(chatId: string, ev: InboundEvent): void {
|
2026-10-19 17:13:12 +08:00
|
|
|
const transcript = this.transcriptHandlers.get(chatId);
|
|
|
|
|
if (transcript) {
|
|
|
|
|
transcript.handler(ev);
|
|
|
|
|
} else {
|
|
|
|
|
let pending = this.pendingInboundByChat.get(chatId);
|
|
|
|
|
if (!pending) {
|
|
|
|
|
pending = [];
|
|
|
|
|
this.pendingInboundByChat.set(chatId, pending);
|
|
|
|
|
}
|
|
|
|
|
pending.push(ev);
|
|
|
|
|
// Temporary chats have no canonical history to recover evicted events from.
|
|
|
|
|
if (!this.temporaryChatIds.has(chatId)) {
|
|
|
|
|
const over = pending.length - NanobotClient.PENDING_INBOUND_MAX;
|
|
|
|
|
if (over > 0) pending.splice(0, over);
|
2026-05-16 01:14:11 +08:00
|
|
|
}
|
|
|
|
|
}
|
2026-10-19 17:13:12 +08:00
|
|
|
for (const handler of this.chatHandlers.get(chatId) ?? []) handler(ev);
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
|
2026-04-21 10:29:47 +00:00
|
|
|
private handleClose(event?: { code?: number }): void {
|
2026-11-12 14:44:38 +08:00
|
|
|
this.cancelReconnect();
|
2026-10-08 11:55:13 +08:00
|
|
|
this.upload = null;
|
|
|
|
|
this.receipts.close();
|
2026-04-18 18:51:53 +00:00
|
|
|
this.socket = null;
|
2026-08-05 19:24:41 +08:00
|
|
|
this.clearTemporaryChats();
|
2026-08-16 02:49:00 +08:00
|
|
|
const willReconnect = !this.intentionallyClosed && this.shouldReconnect;
|
2026-11-12 14:44:38 +08:00
|
|
|
this.rejectPendingChat("socket closed");
|
2026-06-09 01:08:49 +08:00
|
|
|
this.rejectAllTranscriptions("socket closed");
|
2026-08-16 02:49:00 +08:00
|
|
|
if (!willReconnect) {
|
|
|
|
|
for (const pending of this.pendingWebUIRequests.values()) {
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
pending.reject(
|
|
|
|
|
new WebUIMutationError(503, "Socket closed before WebUI response"),
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
this.pendingWebUIRequests.clear();
|
2026-08-10 15:43:54 +08:00
|
|
|
}
|
2026-07-24 17:34:26 +08:00
|
|
|
for (const pending of this.pendingSystemCommands.values()) {
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
pending.reject(new Error("socket closed"));
|
|
|
|
|
}
|
|
|
|
|
this.pendingSystemCommands.clear();
|
2026-04-21 10:29:47 +00:00
|
|
|
// Surface structured reasons *before* reconnect logic so the UI can
|
|
|
|
|
// display the error even while the client transparently reconnects.
|
|
|
|
|
// Browsers populate ``CloseEvent.code`` with the wire-level close code;
|
|
|
|
|
// 1009 = Message Too Big (server's max frame guard).
|
|
|
|
|
if (event?.code === 1009) {
|
2026-10-16 14:35:46 +08:00
|
|
|
const rejected = this.runs.soleSentTurn(this.lastSocketMessageSend);
|
|
|
|
|
if (rejected) {
|
|
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "reject", ...rejected }));
|
|
|
|
|
this.emitError({ kind: "message_too_big", ...rejected });
|
2026-07-28 11:40:01 +08:00
|
|
|
this.dispatch(rejected.chatId, {
|
|
|
|
|
event: "error",
|
|
|
|
|
detail: "message_too_big",
|
|
|
|
|
chat_id: rejected.chatId,
|
|
|
|
|
turn_id: rejected.turnId,
|
|
|
|
|
});
|
|
|
|
|
} else {
|
2026-10-16 14:35:46 +08:00
|
|
|
// A close frame cannot identify one message among multiplexed sends.
|
2026-07-28 11:40:01 +08:00
|
|
|
this.emitError({ kind: "message_too_big" });
|
|
|
|
|
}
|
2026-04-21 10:29:47 +00:00
|
|
|
}
|
2026-10-16 14:35:46 +08:00
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "transport-lost" }));
|
|
|
|
|
this.lastSocketMessageSend = null;
|
2026-08-16 02:49:00 +08:00
|
|
|
if (!willReconnect) {
|
2026-04-18 18:51:53 +00:00
|
|
|
this.setStatus("closed");
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
this.scheduleReconnect();
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-21 10:29:47 +00:00
|
|
|
private emitError(error: StreamError): void {
|
|
|
|
|
// Isolate subscribers so a throwing handler cannot abort the surrounding
|
|
|
|
|
// ``handleClose`` flow (which still owes us a reconnect decision + status
|
|
|
|
|
// update). We deliberately swallow here: error reporting is best-effort
|
|
|
|
|
// and must never be allowed to compound the failure it's reporting.
|
|
|
|
|
for (const handler of this.errorHandlers) {
|
|
|
|
|
try {
|
|
|
|
|
handler(error);
|
|
|
|
|
} catch {
|
|
|
|
|
// best-effort: subscriber fault must not stall transport bookkeeping
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-06-09 01:08:49 +08:00
|
|
|
private resolveTranscription(requestId: string, text: string): void {
|
|
|
|
|
const pending = this.pendingTranscriptions.get(requestId);
|
|
|
|
|
if (!pending) return;
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
this.pendingTranscriptions.delete(requestId);
|
|
|
|
|
pending.resolve(text);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private rejectTranscription(requestId: string | undefined, detail: string): void {
|
|
|
|
|
if (!requestId) {
|
|
|
|
|
this.rejectAllTranscriptions(detail);
|
|
|
|
|
return;
|
|
|
|
|
}
|
|
|
|
|
const pending = this.pendingTranscriptions.get(requestId);
|
|
|
|
|
if (!pending) return;
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
this.pendingTranscriptions.delete(requestId);
|
|
|
|
|
pending.reject(new Error(detail));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private rejectAllTranscriptions(detail: string): void {
|
|
|
|
|
for (const [requestId, pending] of this.pendingTranscriptions) {
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
pending.reject(new Error(detail));
|
|
|
|
|
this.pendingTranscriptions.delete(requestId);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-24 17:34:26 +08:00
|
|
|
private resolveSystemCommand(turnId: string): void {
|
|
|
|
|
const pending = this.pendingSystemCommands.get(turnId);
|
|
|
|
|
if (!pending) return;
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
this.pendingSystemCommands.delete(turnId);
|
|
|
|
|
pending.resolve();
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
private rejectSystemCommand(turnId: string, detail: string): void {
|
|
|
|
|
const pending = this.pendingSystemCommands.get(turnId);
|
|
|
|
|
if (!pending) return;
|
|
|
|
|
clearTimeout(pending.timer);
|
|
|
|
|
this.pendingSystemCommands.delete(turnId);
|
|
|
|
|
pending.reject(new Error(detail));
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-12 14:44:38 +08:00
|
|
|
private cancelReconnect(): void {
|
|
|
|
|
this.reconnectController?.abort();
|
|
|
|
|
this.reconnectController = null;
|
|
|
|
|
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
|
|
|
this.reconnectTimer = null;
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-18 18:51:53 +00:00
|
|
|
private scheduleReconnect(): void {
|
2026-11-12 14:44:38 +08:00
|
|
|
const controller = new AbortController();
|
|
|
|
|
this.reconnectController = controller;
|
2026-04-18 18:51:53 +00:00
|
|
|
this.setStatus("reconnecting");
|
|
|
|
|
const attempt = this.reconnectAttempts++;
|
|
|
|
|
const delay = Math.min(500 * 2 ** attempt, this.maxBackoffMs);
|
|
|
|
|
this.reconnectTimer = setTimeout(async () => {
|
|
|
|
|
this.reconnectTimer = null;
|
2026-11-12 14:44:38 +08:00
|
|
|
if (controller.signal.aborted) return;
|
|
|
|
|
let refreshed: string | null = null;
|
2026-04-18 18:51:53 +00:00
|
|
|
if (this.options.onReauth) {
|
|
|
|
|
try {
|
2026-11-12 14:44:38 +08:00
|
|
|
refreshed = await this.options.onReauth(controller.signal);
|
2026-04-18 18:51:53 +00:00
|
|
|
} catch {
|
|
|
|
|
// fall through to retry with current URL
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-11-12 14:44:38 +08:00
|
|
|
if (controller.signal.aborted) return;
|
|
|
|
|
if (refreshed) this.currentUrl = refreshed;
|
2026-04-18 18:51:53 +00:00
|
|
|
this.connect();
|
|
|
|
|
}, delay);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private queueSend(frame: Outbound): void {
|
|
|
|
|
if (this.socket?.readyState === WS_OPEN) {
|
|
|
|
|
this.rawSend(frame);
|
|
|
|
|
} else {
|
|
|
|
|
this.sendQueue.push(frame);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-08-05 19:24:41 +08:00
|
|
|
private clearTemporaryChats(): void {
|
2026-08-06 18:29:04 +08:00
|
|
|
for (const chatId of [...this.temporaryChatIds]) {
|
|
|
|
|
this.forgetTemporaryChat(chatId);
|
|
|
|
|
}
|
2026-08-05 19:24:41 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private forgetTemporaryChat(chatId: string): void {
|
2026-08-06 18:29:04 +08:00
|
|
|
this.temporaryChatIds.delete(chatId);
|
2026-08-05 19:24:41 +08:00
|
|
|
this.knownChats.delete(chatId);
|
|
|
|
|
this.chatHandlers.delete(chatId);
|
2026-10-19 17:13:12 +08:00
|
|
|
this.transcriptHandlers.delete(chatId);
|
2026-08-05 19:24:41 +08:00
|
|
|
this.pendingInboundByChat.delete(chatId);
|
2026-10-16 14:35:46 +08:00
|
|
|
const effects = this.runs.transition({ kind: "forget", chatId });
|
2026-08-05 19:24:41 +08:00
|
|
|
this.goalStateByChatId.delete(chatId);
|
|
|
|
|
this.sendQueue = this.sendQueue.filter((frame) => (
|
|
|
|
|
!("chat_id" in frame) || frame.chat_id !== chatId
|
|
|
|
|
));
|
2026-10-16 14:35:46 +08:00
|
|
|
if (this.lastSocketMessageSend?.chatId === chatId) this.lastSocketMessageSend = null;
|
|
|
|
|
this.applyRunEffects(effects);
|
2026-08-05 19:24:41 +08:00
|
|
|
}
|
|
|
|
|
|
2026-07-28 11:40:01 +08:00
|
|
|
private frameFitsTransport(frame: Outbound): boolean {
|
|
|
|
|
if (this.maxFrameBytes === undefined) return true;
|
|
|
|
|
return new TextEncoder().encode(JSON.stringify(frame)).byteLength <= this.maxFrameBytes;
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-26 23:35:26 +08:00
|
|
|
private rawSend(frame: Outbound): boolean {
|
|
|
|
|
if (!this.socket) return false;
|
2026-04-18 18:51:53 +00:00
|
|
|
try {
|
|
|
|
|
this.socket.send(JSON.stringify(frame));
|
2026-10-16 14:35:46 +08:00
|
|
|
this.lastSocketMessageSend = null;
|
2026-07-28 11:40:01 +08:00
|
|
|
if (frame.type === "message" && frame.turn_id) {
|
2026-10-16 14:35:46 +08:00
|
|
|
const ref = { chatId: frame.chat_id, turnId: frame.turn_id };
|
|
|
|
|
if (this.runs.hasPendingSend(ref)) {
|
|
|
|
|
this.applyRunEffects(this.runs.transition({ kind: "written", ...ref }));
|
|
|
|
|
this.lastSocketMessageSend = ref;
|
2026-07-28 11:40:01 +08:00
|
|
|
}
|
|
|
|
|
}
|
2026-10-26 23:35:26 +08:00
|
|
|
return true;
|
2026-04-18 18:51:53 +00:00
|
|
|
} catch {
|
2026-10-26 23:35:26 +08:00
|
|
|
// Shell commands require a new explicit submission, never reconnect replay.
|
|
|
|
|
if (frame.type !== "message" || !frame.user_shell) this.sendQueue.push(frame);
|
|
|
|
|
return false;
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|
|
|
|
|
}
|
2026-08-16 02:56:23 +08:00
|
|
|
|
|
|
|
|
private rawSendSerialized(serializedFrame: string): void {
|
|
|
|
|
if (!this.socket) return;
|
|
|
|
|
try {
|
|
|
|
|
this.socket.send(serializedFrame);
|
|
|
|
|
} catch {
|
|
|
|
|
// The pending request remains available for the next successful reconnect.
|
|
|
|
|
}
|
|
|
|
|
}
|
2026-04-18 18:51:53 +00:00
|
|
|
}
|