refactor(webui): centralize client run lifecycle state
This commit is contained in:
1 parent
6f04038d21
commit
0d1beac3aa
4 files changed
+624
-532
No files matched your search
@@ -45,6 +45,8 @@ Channel fixture fields, defaults, and requirements come from the Python channel
|
|||||||
|
|
||||||
Supporting hooks and display-model helpers stay near the feature that owns them. Common theme tokens and reusable CSS treatments live in `src/globals.css`, `tailwind.config.js`, and the relevant `ui/` modules. The component inventory lists `.tsx` modules; pure `.ts` helpers remain discoverable through their callers and source imports.
|
Supporting hooks and display-model helpers stay near the feature that owns them. Common theme tokens and reusable CSS treatments live in `src/globals.css`, `tailwind.config.js`, and the relevant `ui/` modules. The component inventory lists `.tsx` modules; pure `.ts` helpers remain discoverable through their callers and source imports.
|
||||||
|
|
||||||
|
`NanobotClient` adapts WebSocket frames into observations for its `ClientRunLedger`. The ledger owns each chat's message delivery, run identities, clocks, and completion records, and returns effects for the client to apply to its queues and subscribers. A dropped connection makes unconfirmed delivery unknown while durable runs remain unresolved. Wire completion still permits late final messages; canonical completion records suppress matching top-level turn events. `useNanobotStream` owns message projection and render batching, while `ThreadShell` adopts canonical history and confirms completion after the messages commit.
|
||||||
|
|
||||||
## Choose an existing component
|
## Choose an existing component
|
||||||
|
|
||||||
- Check the gallery and current callers before creating a control. Different labels, colors, or sizes usually call for an existing component's options. `Button` already has appearance and size variants; `Input` and `SearchInput` share the input implementation.
|
- Check the gallery and current callers before creating a control. Different labels, colors, or sizes usually call for an existing component's options. `Button` already has appearance and size variants; `Input` and `SearchInput` share the input implementation.
|
||||||
|
|||||||
@@ -0,0 +1,444 @@
|
|||||||
|
type TurnRef = Readonly<{ chatId: string; turnId: string }>;
|
||||||
|
type DeliveryRole = "candidate-owner" | "supplement";
|
||||||
|
type Delivery =
|
||||||
|
| { phase: "queued" | "sent" | "unknown"; role: DeliveryRole }
|
||||||
|
| { phase: "accepted"; role: "candidate-owner" };
|
||||||
|
|
||||||
|
interface TurnRecord {
|
||||||
|
delivery: Delivery | null;
|
||||||
|
// Only openOrder marks unsettled ownership; a timestamp alone does not.
|
||||||
|
openOrder: number | null;
|
||||||
|
startedAt: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface ChatRecord {
|
||||||
|
generation: number;
|
||||||
|
latestTurnId: string | null;
|
||||||
|
effectiveStartedAt: number | null;
|
||||||
|
turns: Map<string, TurnRecord>;
|
||||||
|
/** Closed turns permit late inputs, messages, completions and idle. */
|
||||||
|
closed: Set<string>;
|
||||||
|
/** Canonical fences discard every frame with a matching top-level turn id. */
|
||||||
|
fenced: Set<string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CanonicalRunSnapshot {
|
||||||
|
/** User turn ids present in the canonical transcript page. */
|
||||||
|
observedTurnIds: readonly string[];
|
||||||
|
/** Whether the server still considers the transcript tail active. */
|
||||||
|
hasPendingToolCalls: boolean;
|
||||||
|
/** Exact active turn when supplied by a current gateway. */
|
||||||
|
activeTurnId?: string | null;
|
||||||
|
/** Supplied completion identities are authoritative for lifecycle turns. */
|
||||||
|
completionIdsProvided?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface CanonicalRequest {
|
||||||
|
chatId: string;
|
||||||
|
generation: number;
|
||||||
|
completedTurnIds: readonly string[];
|
||||||
|
snapshot?: CanonicalRunSnapshot;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type RunObservation = Readonly<{
|
||||||
|
chatId: string;
|
||||||
|
turnId: string | null;
|
||||||
|
systemCommand?: boolean;
|
||||||
|
}> & (
|
||||||
|
| { kind: "admission" | "input"; owner?: { turnId: string; startedAt?: number } }
|
||||||
|
| { kind: "status"; activity: "running" | "idle"; startedAt?: number }
|
||||||
|
| { kind: "completed" | "message" | "progress" | "rejection" }
|
||||||
|
);
|
||||||
|
|
||||||
|
type Command =
|
||||||
|
| ({ kind: "submit"; role: DeliveryRole } & TurnRef)
|
||||||
|
| ({ kind: "written" | "reject" } & TurnRef)
|
||||||
|
| { kind: "transport-lost" }
|
||||||
|
| { kind: "local-stop" | "forget"; chatId: string }
|
||||||
|
| { kind: "fence"; chatId: string; completedTurnIds: readonly string[] };
|
||||||
|
|
||||||
|
export type RunEffect =
|
||||||
|
| { kind: "run-status"; chatId: string; startedAt: number | null }
|
||||||
|
| { kind: "completion"; chatId: string }
|
||||||
|
| ({ kind: "discard-send" } & TurnRef)
|
||||||
|
| { kind: "prune-inbound"; chatId: string; turnIds: readonly string[] };
|
||||||
|
|
||||||
|
interface ObservationResult {
|
||||||
|
forward: "normal" | "without-owner" | "drop";
|
||||||
|
effects: readonly RunEffect[];
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RunView {
|
||||||
|
generation: number;
|
||||||
|
latestTurnId: string | null;
|
||||||
|
startedAt: number | null;
|
||||||
|
unsettled: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const COMPLETED_TURN_FENCE_MAX = 256;
|
||||||
|
|
||||||
|
/** Owns transport-observed delivery and run facts for one client. */
|
||||||
|
export class ClientRunLedger {
|
||||||
|
private chats = new Map<string, ChatRecord>();
|
||||||
|
|
||||||
|
view(chatId: string): RunView {
|
||||||
|
const chat = this.chats.get(chatId);
|
||||||
|
return {
|
||||||
|
generation: chat?.generation ?? 0,
|
||||||
|
latestTurnId: chat?.latestTurnId ?? null,
|
||||||
|
startedAt: chat?.effectiveStartedAt ?? null,
|
||||||
|
unsettled: this.hasOpenTurn(chat),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
isCompleted({ chatId, turnId }: TurnRef): boolean {
|
||||||
|
const chat = this.chats.get(chatId);
|
||||||
|
return chat?.closed.has(turnId) === true || chat?.fenced.has(turnId) === true;
|
||||||
|
}
|
||||||
|
|
||||||
|
hasPendingSend({ chatId, turnId }: TurnRef): boolean {
|
||||||
|
return this.chats.get(chatId)?.turns.get(turnId)?.delivery != null;
|
||||||
|
}
|
||||||
|
|
||||||
|
activeClocks(): readonly Readonly<{ chatId: string; startedAt: number }>[] {
|
||||||
|
return Array.from(this.chats).flatMap(([chatId, chat]) => (
|
||||||
|
chat.effectiveStartedAt === null ? [] : [{ chatId, startedAt: chat.effectiveStartedAt }]
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
unresolvedChatIds(): string[] {
|
||||||
|
return Array.from(this.chats).flatMap(([chatId, chat]) => (
|
||||||
|
chat.effectiveStartedAt !== null || this.hasOpenTurn(chat) ? [chatId] : []
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
soleSentTurn(lastApplicationMessage: TurnRef | null, chatId?: string): TurnRef | null {
|
||||||
|
if (lastApplicationMessage === null) return null;
|
||||||
|
let candidate: TurnRef | null = null;
|
||||||
|
for (const [id, chat] of this.chats) {
|
||||||
|
if (chatId !== undefined && id !== chatId) continue;
|
||||||
|
for (const [turnId, turn] of chat.turns) {
|
||||||
|
if (turn.delivery?.phase !== "sent") continue;
|
||||||
|
if (candidate !== null) return null;
|
||||||
|
candidate = { chatId: id, turnId };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return candidate?.chatId === lastApplicationMessage.chatId
|
||||||
|
&& candidate.turnId === lastApplicationMessage.turnId ? candidate : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
soleUnsettledTurn(chatId: string): string | null {
|
||||||
|
const chat = this.chats.get(chatId);
|
||||||
|
if (!chat) return null;
|
||||||
|
let candidate: string | null = null;
|
||||||
|
for (const [turnId, turn] of chat.turns) {
|
||||||
|
if (turn.openOrder === null) continue;
|
||||||
|
if (candidate !== null) return null;
|
||||||
|
candidate = turnId;
|
||||||
|
}
|
||||||
|
return candidate;
|
||||||
|
}
|
||||||
|
|
||||||
|
transition(command: Command): readonly RunEffect[] {
|
||||||
|
const effects: RunEffect[] = [];
|
||||||
|
switch (command.kind) {
|
||||||
|
case "submit": {
|
||||||
|
const chat = this.ensureChat(command.chatId);
|
||||||
|
if (command.role === "candidate-owner") this.advance(chat, command.turnId);
|
||||||
|
this.ensureTurn(chat, command.turnId).delivery = { phase: "queued", role: command.role };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "written": {
|
||||||
|
const turn = this.chats.get(command.chatId)?.turns.get(command.turnId);
|
||||||
|
if (turn?.delivery) turn.delivery = { phase: "sent", role: turn.delivery.role };
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "reject":
|
||||||
|
this.reject(command.chatId, command.turnId, effects);
|
||||||
|
break;
|
||||||
|
case "transport-lost":
|
||||||
|
for (const chat of this.chats.values()) {
|
||||||
|
for (const turn of chat.turns.values()) {
|
||||||
|
if (turn.delivery?.phase === "sent") {
|
||||||
|
turn.delivery = { phase: "unknown", role: turn.delivery.role };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case "local-stop": {
|
||||||
|
const chat = this.chats.get(command.chatId);
|
||||||
|
if (!chat) break;
|
||||||
|
const openTurnIds = this.openTurnIds(chat);
|
||||||
|
if (chat.latestTurnId) this.rememberClosed(chat, chat.latestTurnId);
|
||||||
|
for (const turnId of openTurnIds) this.rememberClosed(chat, turnId);
|
||||||
|
for (const turnId of openTurnIds) this.settle(command.chatId, turnId, effects);
|
||||||
|
chat.latestTurnId = null;
|
||||||
|
this.updateClock(command.chatId, chat, null, effects);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "forget": {
|
||||||
|
const chat = this.chats.get(command.chatId);
|
||||||
|
this.chats.delete(command.chatId);
|
||||||
|
if (chat?.effectiveStartedAt != null) {
|
||||||
|
effects.push({ kind: "run-status", chatId: command.chatId, startedAt: null });
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
case "fence":
|
||||||
|
this.fence(command.chatId, command.completedTurnIds, effects);
|
||||||
|
break;
|
||||||
|
default: {
|
||||||
|
const unhandled: never = command;
|
||||||
|
throw new Error(`Unexpected run command: ${unhandled}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return effects;
|
||||||
|
}
|
||||||
|
|
||||||
|
observe(observation: RunObservation): ObservationResult {
|
||||||
|
const { chatId, turnId } = observation;
|
||||||
|
let chat = this.chats.get(chatId);
|
||||||
|
const effects: RunEffect[] = [];
|
||||||
|
if (turnId !== null && chat?.fenced.has(turnId)) return { forward: "drop", effects };
|
||||||
|
if (
|
||||||
|
turnId && chat?.closed.has(turnId)
|
||||||
|
&& observation.kind !== "admission" && observation.kind !== "input"
|
||||||
|
&& observation.kind !== "message" && observation.kind !== "completed"
|
||||||
|
&& !(observation.kind === "status" && observation.activity === "idle")
|
||||||
|
) return { forward: "drop", effects };
|
||||||
|
|
||||||
|
let forward: ObservationResult["forward"] = "normal";
|
||||||
|
if ((observation.kind === "admission" || observation.kind === "input") && observation.owner?.turnId) {
|
||||||
|
const owner = observation.owner;
|
||||||
|
chat = this.ensureChat(chatId);
|
||||||
|
if (chat.closed.has(owner.turnId) || chat.fenced.has(owner.turnId)) {
|
||||||
|
if (turnId && turnId !== owner.turnId && chat.turns.get(turnId)?.delivery?.role === "candidate-owner") {
|
||||||
|
this.reject(chatId, turnId, effects);
|
||||||
|
if (!this.hasOpenTurn(chat)) effects.push({ kind: "run-status", chatId, startedAt: null });
|
||||||
|
}
|
||||||
|
forward = "without-owner";
|
||||||
|
} else {
|
||||||
|
if (turnId && turnId !== owner.turnId && chat.turns.get(turnId)?.delivery?.role === "candidate-owner") {
|
||||||
|
this.settle(chatId, turnId, effects);
|
||||||
|
}
|
||||||
|
if (chat.latestTurnId !== owner.turnId) this.advance(chat, owner.turnId);
|
||||||
|
if (typeof owner.startedAt === "number") {
|
||||||
|
this.ensureTurn(chat, owner.turnId).startedAt = owner.startedAt;
|
||||||
|
this.updateClock(chatId, chat, owner.startedAt, effects);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (observation.kind === "admission") {
|
||||||
|
if (turnId) this.accept(chat, turnId);
|
||||||
|
return { forward, effects };
|
||||||
|
}
|
||||||
|
if (observation.systemCommand) return { forward, effects };
|
||||||
|
if (observation.kind === "rejection") {
|
||||||
|
if (turnId) this.reject(chatId, turnId, effects);
|
||||||
|
return { forward, effects };
|
||||||
|
}
|
||||||
|
if (turnId) this.accept(chat, turnId);
|
||||||
|
|
||||||
|
const completion = observation.kind === "completed"
|
||||||
|
|| (observation.kind === "status" && observation.activity === "idle");
|
||||||
|
const superseded = completion && chat?.latestTurnId != null && turnId !== chat.latestTurnId;
|
||||||
|
if (observation.kind === "status" && observation.activity === "running" && typeof observation.startedAt === "number") {
|
||||||
|
chat = this.ensureChat(chatId);
|
||||||
|
this.advance(chat, turnId);
|
||||||
|
if (turnId) this.ensureTurn(chat, turnId).startedAt = observation.startedAt;
|
||||||
|
this.updateClock(chatId, chat, observation.startedAt, effects);
|
||||||
|
} else if (observation.kind === "status" || observation.kind === "completed") {
|
||||||
|
// A running status without a numeric start time also settles the turn.
|
||||||
|
chat = this.ensureChat(chatId);
|
||||||
|
if (turnId) this.rememberClosed(chat, turnId);
|
||||||
|
if (turnId) this.settle(chatId, turnId, effects);
|
||||||
|
if (chat.latestTurnId === null || turnId === chat.latestTurnId) {
|
||||||
|
this.updateClock(chatId, chat, null, effects);
|
||||||
|
}
|
||||||
|
effects.push({ kind: "completion", chatId });
|
||||||
|
}
|
||||||
|
return { forward: superseded ? "drop" : forward, effects };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Check snapshot eligibility without recording fences or producing effects. */
|
||||||
|
canApplyCanonical(request: CanonicalRequest): boolean {
|
||||||
|
const chat = this.chats.get(request.chatId);
|
||||||
|
const completed = new Set(chat?.fenced);
|
||||||
|
for (const turnId of request.completedTurnIds) {
|
||||||
|
if (turnId) completed.add(turnId);
|
||||||
|
}
|
||||||
|
const observed = new Set(request.snapshot?.observedTurnIds.filter((turnId) => turnId.length > 0) ?? []);
|
||||||
|
const willSettle = (turnId: string) => this.canonicalTurnWillSettle(chat, turnId, completed, observed, request.snapshot);
|
||||||
|
const latestTurnId = chat?.latestTurnId ?? null;
|
||||||
|
const latestIsRepresented = latestTurnId !== null && (
|
||||||
|
completed.has(latestTurnId) || (observed.has(latestTurnId) && willSettle(latestTurnId))
|
||||||
|
);
|
||||||
|
if (chat) {
|
||||||
|
for (const [turnId, turn] of chat.turns) {
|
||||||
|
if (turn.openOrder !== null && !willSettle(turnId)) return false;
|
||||||
|
}
|
||||||
|
if (chat.effectiveStartedAt !== null && latestTurnId === null && (!request.snapshot || request.snapshot.hasPendingToolCalls)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (chat?.generation ?? 0) === request.generation || latestIsRepresented;
|
||||||
|
}
|
||||||
|
|
||||||
|
applyCanonical(request: CanonicalRequest): { accepted: boolean; effects: readonly RunEffect[] } {
|
||||||
|
const { chatId, snapshot } = request;
|
||||||
|
const effects: RunEffect[] = [];
|
||||||
|
this.fence(chatId, request.completedTurnIds, effects);
|
||||||
|
if (!this.canApplyCanonical({ ...request, completedTurnIds: [] })) return { accepted: false, effects };
|
||||||
|
|
||||||
|
const chat = this.chats.get(chatId);
|
||||||
|
if (!chat) return { accepted: true, effects };
|
||||||
|
const completed = chat.fenced;
|
||||||
|
const observed = new Set(snapshot?.observedTurnIds.filter((turnId) => turnId.length > 0) ?? []);
|
||||||
|
for (const turnId of this.openTurnIds(chat)) {
|
||||||
|
if (!this.canonicalTurnWillSettle(chat, turnId, completed, observed, snapshot)) continue;
|
||||||
|
this.rememberClosed(chat, turnId);
|
||||||
|
this.settle(chatId, turnId, effects);
|
||||||
|
}
|
||||||
|
for (const [turnId, turn] of chat.turns) {
|
||||||
|
if (turn.delivery?.role !== "supplement") continue;
|
||||||
|
if (!this.canonicalTurnWillSettle(chat, turnId, completed, observed, snapshot)) continue;
|
||||||
|
turn.delivery = null;
|
||||||
|
this.removeEmptyTurn(chat, turnId, turn);
|
||||||
|
effects.push({ kind: "discard-send", chatId, turnId });
|
||||||
|
}
|
||||||
|
this.updateClock(chatId, chat, null, effects);
|
||||||
|
return { accepted: true, effects };
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureChat(chatId: string): ChatRecord {
|
||||||
|
let chat = this.chats.get(chatId);
|
||||||
|
if (!chat) {
|
||||||
|
chat = {
|
||||||
|
generation: 0,
|
||||||
|
latestTurnId: null,
|
||||||
|
effectiveStartedAt: null,
|
||||||
|
turns: new Map(),
|
||||||
|
closed: new Set(),
|
||||||
|
fenced: new Set(),
|
||||||
|
};
|
||||||
|
this.chats.set(chatId, chat);
|
||||||
|
}
|
||||||
|
return chat;
|
||||||
|
}
|
||||||
|
|
||||||
|
private ensureTurn(chat: ChatRecord, turnId: string): TurnRecord {
|
||||||
|
let turn = chat.turns.get(turnId);
|
||||||
|
if (!turn) {
|
||||||
|
turn = { delivery: null, openOrder: null, startedAt: null };
|
||||||
|
chat.turns.set(turnId, turn);
|
||||||
|
}
|
||||||
|
return turn;
|
||||||
|
}
|
||||||
|
|
||||||
|
private advance(chat: ChatRecord, turnId: string | null): void {
|
||||||
|
chat.generation += 1;
|
||||||
|
chat.latestTurnId = turnId || null;
|
||||||
|
if (turnId) {
|
||||||
|
const turn = this.ensureTurn(chat, turnId);
|
||||||
|
if (turn.openOrder === null) turn.openOrder = chat.generation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private hasOpenTurn(chat: ChatRecord | undefined): boolean {
|
||||||
|
if (!chat) return false;
|
||||||
|
for (const turn of chat.turns.values()) {
|
||||||
|
if (turn.openOrder !== null) return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
private openTurnIds(chat: ChatRecord): string[] {
|
||||||
|
const turns: { turnId: string; order: number }[] = [];
|
||||||
|
for (const [turnId, turn] of chat.turns) {
|
||||||
|
if (turn.openOrder !== null) turns.push({ turnId, order: turn.openOrder });
|
||||||
|
}
|
||||||
|
return turns.sort((left, right) => left.order - right.order).map(({ turnId }) => turnId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private accept(chat: ChatRecord | undefined, turnId: string): void {
|
||||||
|
const turn = chat?.turns.get(turnId);
|
||||||
|
if (!chat || !turn?.delivery) return;
|
||||||
|
if (turn.delivery.role === "supplement") {
|
||||||
|
turn.delivery = null;
|
||||||
|
this.removeEmptyTurn(chat, turnId, turn);
|
||||||
|
} else if (turn.delivery.phase !== "accepted") {
|
||||||
|
turn.delivery = { phase: "accepted", role: "candidate-owner" };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private removeEmptyTurn(chat: ChatRecord, turnId: string, turn: TurnRecord): void {
|
||||||
|
if (turn.delivery === null && turn.openOrder === null && turn.startedAt === null) chat.turns.delete(turnId);
|
||||||
|
}
|
||||||
|
|
||||||
|
private settle(chatId: string, turnId: string, effects: RunEffect[]): void {
|
||||||
|
this.chats.get(chatId)?.turns.delete(turnId);
|
||||||
|
effects.push({ kind: "discard-send", chatId, turnId });
|
||||||
|
}
|
||||||
|
|
||||||
|
private reject(chatId: string, turnId: string, effects: RunEffect[]): void {
|
||||||
|
if (!turnId) return;
|
||||||
|
const chat = this.chats.get(chatId);
|
||||||
|
const rejectedLatest = chat?.latestTurnId === turnId;
|
||||||
|
this.settle(chatId, turnId, effects);
|
||||||
|
effects.push({ kind: "prune-inbound", chatId, turnIds: [turnId] });
|
||||||
|
if (!chat || !rejectedLatest) return;
|
||||||
|
let previous: { turnId: string; order: number; startedAt: number | null } | null = null;
|
||||||
|
for (const [id, turn] of chat.turns) {
|
||||||
|
if (turn.openOrder !== null && (previous === null || turn.openOrder > previous.order)) {
|
||||||
|
previous = { turnId: id, order: turn.openOrder, startedAt: turn.startedAt };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
chat.latestTurnId = previous?.turnId ?? null;
|
||||||
|
this.updateClock(chatId, chat, previous?.startedAt ?? null, effects);
|
||||||
|
}
|
||||||
|
|
||||||
|
private updateClock(chatId: string, chat: ChatRecord, startedAt: number | null, effects: RunEffect[]): void {
|
||||||
|
// An optimistic latest identity can coexist with an older effective clock.
|
||||||
|
const previous = chat.effectiveStartedAt;
|
||||||
|
chat.effectiveStartedAt = startedAt;
|
||||||
|
if (previous !== startedAt) effects.push({ kind: "run-status", chatId, startedAt });
|
||||||
|
}
|
||||||
|
|
||||||
|
private rememberClosed(chat: ChatRecord, turnId: string): void {
|
||||||
|
chat.closed.add(turnId);
|
||||||
|
this.trimTerminalSet(chat.closed);
|
||||||
|
}
|
||||||
|
|
||||||
|
private fence(chatId: string, turnIds: readonly string[], effects: RunEffect[]): void {
|
||||||
|
let chat = this.chats.get(chatId);
|
||||||
|
for (const turnId of turnIds) {
|
||||||
|
if (!turnId) continue;
|
||||||
|
chat ??= this.ensureChat(chatId);
|
||||||
|
chat.fenced.add(turnId);
|
||||||
|
}
|
||||||
|
if (chat) this.trimTerminalSet(chat.fenced);
|
||||||
|
effects.push({ kind: "prune-inbound", chatId, turnIds: Array.from(chat?.fenced ?? []) });
|
||||||
|
}
|
||||||
|
|
||||||
|
private trimTerminalSet(turnIds: Set<string>): void {
|
||||||
|
for (const oldest of turnIds) {
|
||||||
|
if (turnIds.size <= COMPLETED_TURN_FENCE_MAX) break;
|
||||||
|
turnIds.delete(oldest);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private canonicalTurnWillSettle(
|
||||||
|
chat: ChatRecord | undefined,
|
||||||
|
turnId: string,
|
||||||
|
completed: ReadonlySet<string>,
|
||||||
|
observed: ReadonlySet<string>,
|
||||||
|
snapshot?: CanonicalRunSnapshot,
|
||||||
|
): boolean {
|
||||||
|
if (completed.has(turnId)) return true;
|
||||||
|
const delivery = chat?.turns.get(turnId)?.delivery;
|
||||||
|
if (snapshot?.completionIdsProvided && delivery?.role !== "supplement") return false;
|
||||||
|
if (!snapshot || snapshot.activeTurnId === turnId || snapshot.hasPendingToolCalls) return false;
|
||||||
|
return observed.has(turnId) || delivery?.phase === "unknown" || delivery?.phase === "accepted";
|
||||||
|
}
|
||||||
|
}
|
||||||
+124
-532
@@ -14,6 +14,10 @@ import type {
|
|||||||
WorkspaceScopePayload,
|
WorkspaceScopePayload,
|
||||||
} from "./types";
|
} from "./types";
|
||||||
import { createHostWebSocket } from "./runtime";
|
import { createHostWebSocket } from "./runtime";
|
||||||
|
import { ClientRunLedger } from "./client-run-ledger";
|
||||||
|
import type { CanonicalRunSnapshot, RunEffect, RunObservation } from "./client-run-ledger";
|
||||||
|
|
||||||
|
export type { CanonicalRunSnapshot } from "./client-run-ledger";
|
||||||
|
|
||||||
/** WebSocket readyState constants, referenced by value to stay portable
|
/** WebSocket readyState constants, referenced by value to stay portable
|
||||||
* across runtimes that don't expose a global ``WebSocket`` (tests, SSR). */
|
* across runtimes that don't expose a global ``WebSocket`` (tests, SSR). */
|
||||||
@@ -165,24 +169,31 @@ export interface NanobotClientOptions {
|
|||||||
maxBackoffMs?: number;
|
maxBackoffMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CanonicalRunSnapshot {
|
function runObservation(event: InboundEvent): RunObservation | null {
|
||||||
/** User turn ids present in the canonical transcript page. */
|
if (!("chat_id" in event) || !event.chat_id) return null;
|
||||||
observedTurnIds: readonly string[];
|
const turnId = "turn_id" in event && typeof event.turn_id === "string" ? event.turn_id : null;
|
||||||
/** Whether the server still considers the transcript tail active. */
|
const base = { chatId: event.chat_id, turnId, systemCommand: isSystemCommandTurnId(turnId) };
|
||||||
hasPendingToolCalls: boolean;
|
switch (event.event) {
|
||||||
/** Exact active turn when supplied by a current gateway. */
|
case "message_accepted":
|
||||||
activeTurnId?: string | null;
|
case "user_message": {
|
||||||
/** Supplied completion identities are authoritative for lifecycle turns. */
|
const activeTurnId = event.active_turn_id ?? (event.starts_turn ? event.turn_id : undefined);
|
||||||
completionIdsProvided?: boolean;
|
return {
|
||||||
}
|
...base,
|
||||||
|
kind: event.event === "message_accepted" ? "admission" : "input",
|
||||||
type PendingMessageState = "queued" | "sent" | "unknown" | "accepted";
|
...(activeTurnId ? { owner: { turnId: activeTurnId, startedAt: event.started_at } } : {}),
|
||||||
|
};
|
||||||
interface PendingMessageSend {
|
}
|
||||||
chatId: string;
|
case "goal_status":
|
||||||
turnId: string;
|
return { ...base, kind: "status", activity: event.status, startedAt: event.started_at };
|
||||||
startsNewRun: boolean;
|
case "turn_end":
|
||||||
state: PendingMessageState;
|
return { ...base, kind: "completed" };
|
||||||
|
case "error":
|
||||||
|
return { ...base, kind: "rejection" };
|
||||||
|
case "message":
|
||||||
|
return { ...base, kind: "message" };
|
||||||
|
default:
|
||||||
|
return { ...base, kind: "progress" };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -212,27 +223,9 @@ export class NanobotClient {
|
|||||||
private knownChats = new Set<string>();
|
private knownChats = new Set<string>();
|
||||||
/** Temporary chats are connection-owned and intentionally not reattached. */
|
/** Temporary chats are connection-owned and intentionally not reattached. */
|
||||||
private temporaryChatIds = new Set<string>();
|
private temporaryChatIds = new Set<string>();
|
||||||
/** Wall-clock run strip: updated from ``goal_status`` even with no ``onChat`` subscriber. */
|
private readonly runs = new ClientRunLedger();
|
||||||
private runStartedAtByChatId = new Map<string, number>();
|
/** Last tracked application frame written, for conservative transport-error attribution. */
|
||||||
/** Per-turn clocks let a rejected newer turn fall back without borrowing its timer. */
|
private lastSocketMessageSend: { chatId: string; turnId: string } | null = null;
|
||||||
private runStartedAtByTurnKey = new Map<string, number>();
|
|
||||||
/** Monotonic per-chat generation for local sends and observed backend runs. */
|
|
||||||
private runGenerationByChatId = new Map<string, number>();
|
|
||||||
/** Turn associated with the latest generation, retained after idle for reconciliation. */
|
|
||||||
private latestRunTurnIdByChatId = new Map<string, string>();
|
|
||||||
/** Submitted or running turns not yet closed by lifecycle or canonical state. */
|
|
||||||
private unsettledRunTurnIdsByChatId = new Map<string, Set<string>>();
|
|
||||||
/** Correlated WebUI sends retained until protocol/canonical disposition. */
|
|
||||||
private pendingMessageSends = new Map<string, PendingMessageSend>();
|
|
||||||
/** Message sends written to the current socket but not yet acknowledged. */
|
|
||||||
private socketPendingMessageSendKeys = new Set<string>();
|
|
||||||
/** Last application frame written, used only for conservative 1009 attribution. */
|
|
||||||
private lastSocketMessageSendKey: string | null = null;
|
|
||||||
/** Canonically completed turns whose delayed websocket frames must be ignored. */
|
|
||||||
private canonicalCompletedTurnIdsByChatId = new Map<string, Set<string>>();
|
|
||||||
/** Closed run identities; output/ACKs can still arrive after idle or local stop. */
|
|
||||||
private closedRunTurnIdsByChatId = new Map<string, Set<string>>();
|
|
||||||
private static readonly COMPLETED_TURN_FENCE_MAX = 256;
|
|
||||||
/** Latest ``goal_state`` snapshot per ``chat_id`` (multi-session isolation). */
|
/** Latest ``goal_state`` snapshot per ``chat_id`` (multi-session isolation). */
|
||||||
private goalStateByChatId = new Map<string, GoalStateWsPayload>();
|
private goalStateByChatId = new Map<string, GoalStateWsPayload>();
|
||||||
private pendingNewChat: PendingChatRequest | null = null;
|
private pendingNewChat: PendingChatRequest | null = null;
|
||||||
@@ -309,7 +302,7 @@ export class NanobotClient {
|
|||||||
|
|
||||||
onRunStatus(handler: RunStatusHandler): Unsubscribe {
|
onRunStatus(handler: RunStatusHandler): Unsubscribe {
|
||||||
this.runStatusHandlers.add(handler);
|
this.runStatusHandlers.add(handler);
|
||||||
for (const [chatId, startedAt] of this.runStartedAtByChatId) {
|
for (const { chatId, startedAt } of this.runs.activeClocks()) {
|
||||||
handler(chatId, startedAt);
|
handler(chatId, startedAt);
|
||||||
}
|
}
|
||||||
return () => {
|
return () => {
|
||||||
@@ -327,61 +320,42 @@ export class NanobotClient {
|
|||||||
|
|
||||||
/** Last ``goal_status`` ``started_at`` (unix sec) for *chatId*, if the turn is running. */
|
/** Last ``goal_status`` ``started_at`` (unix sec) for *chatId*, if the turn is running. */
|
||||||
getRunStartedAt(chatId: string): number | null {
|
getRunStartedAt(chatId: string): number | null {
|
||||||
const v = this.runStartedAtByChatId.get(chatId);
|
return this.runs.view(chatId).startedAt;
|
||||||
return v === undefined ? null : v;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Canonical lifecycle turn currently owning the run for *chatId*, if known. */
|
/** Canonical lifecycle turn currently owning the run, retained after completion. */
|
||||||
getRunTurnId(chatId: string): string | null {
|
getRunTurnId(chatId: string): string | null {
|
||||||
return this.latestRunTurnIdByChatId.get(chatId) ?? null;
|
return this.runs.view(chatId).latestTurnId;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Whether a turn has a terminal wire, canonical, or local stop disposition. */
|
|
||||||
isRunCompleted(chatId: string, turnId: string): boolean {
|
isRunCompleted(chatId: string, turnId: string): boolean {
|
||||||
return this.closedRunTurnIdsByChatId.get(chatId)?.has(turnId) === true
|
return this.runs.isCompleted({ chatId, turnId });
|
||||||
|| this.canonicalCompletedTurnIdsByChatId.get(chatId)?.has(turnId) === true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clear the optimistic run state immediately after the user stops a turn. */
|
/** End the local optimistic run without confirming gateway cancellation. */
|
||||||
finishRunLocally(chatId: string): void {
|
finishRunLocally(chatId: string): void {
|
||||||
const unsettled = [...(this.unsettledRunTurnIdsByChatId.get(chatId) ?? [])];
|
this.applyRunEffects(this.runs.transition({ kind: "local-stop", chatId }));
|
||||||
const latestTurnId = this.latestRunTurnIdByChatId.get(chatId);
|
|
||||||
if (latestTurnId) this.rememberRunCompletion(chatId, latestTurnId);
|
|
||||||
for (const turnId of unsettled) this.rememberRunCompletion(chatId, turnId);
|
|
||||||
for (const turnId of unsettled) this.settleRunTurn(chatId, turnId);
|
|
||||||
this.latestRunTurnIdByChatId.delete(chatId);
|
|
||||||
if (this.runStartedAtByChatId.delete(chatId)) {
|
|
||||||
this.emitRunStatus(chatId, null);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Refresh transport policy after bootstrap token renewal. */
|
|
||||||
updateMaxFrameBytes(maxFrameBytes?: number): void {
|
updateMaxFrameBytes(maxFrameBytes?: number): void {
|
||||||
this.maxFrameBytes = this.normalizeMaxFrameBytes(maxFrameBytes);
|
this.maxFrameBytes = this.normalizeMaxFrameBytes(maxFrameBytes);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Generation captured when an HTTP thread reconciliation starts. */
|
|
||||||
getRunGeneration(chatId: string): number {
|
getRunGeneration(chatId: string): number {
|
||||||
return this.runGenerationByChatId.get(chatId) ?? 0;
|
return this.runs.view(chatId).generation;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Whether a locally submitted lifecycle turn still lacks a terminal disposition. */
|
|
||||||
hasUnsettledRun(chatId: string): boolean {
|
hasUnsettledRun(chatId: string): boolean {
|
||||||
return (this.unsettledRunTurnIdsByChatId.get(chatId)?.size ?? 0) > 0;
|
return this.runs.view(chatId).unsettled;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Observe terminal wire facts without subscribing to or attaching a chat. */
|
|
||||||
onRunCompletion(handler: RunCompletionHandler): Unsubscribe {
|
onRunCompletion(handler: RunCompletionHandler): Unsubscribe {
|
||||||
this.runCompletionHandlers.add(handler);
|
this.runCompletionHandlers.add(handler);
|
||||||
return () => this.runCompletionHandlers.delete(handler);
|
return () => this.runCompletionHandlers.delete(handler);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Durable runs that need a canonical disposition after transport recovery. */
|
|
||||||
getUnsettledRunChatIds(): string[] {
|
getUnsettledRunChatIds(): string[] {
|
||||||
return Array.from(new Set([
|
return this.runs.unresolvedChatIds().filter((chatId) => !this.temporaryChatIds.has(chatId));
|
||||||
...this.unsettledRunTurnIdsByChatId.keys(),
|
|
||||||
...this.runStartedAtByChatId.keys(),
|
|
||||||
])).filter((chatId) => !this.temporaryChatIds.has(chatId));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private normalizeMaxFrameBytes(value: number | undefined): number | undefined {
|
private normalizeMaxFrameBytes(value: number | undefined): number | undefined {
|
||||||
@@ -391,183 +365,34 @@ export class NanobotClient {
|
|||||||
return Math.floor(value);
|
return Math.floor(value);
|
||||||
}
|
}
|
||||||
|
|
||||||
private canonicalTurnWillSettle(
|
/** Pure preflight; it neither settles runs nor prunes queued frames. */
|
||||||
chatId: string,
|
|
||||||
turnId: string,
|
|
||||||
completed: ReadonlySet<string>,
|
|
||||||
observed: ReadonlySet<string>,
|
|
||||||
snapshot?: CanonicalRunSnapshot,
|
|
||||||
): boolean {
|
|
||||||
if (completed.has(turnId)) return true;
|
|
||||||
const pending = this.pendingMessageSends.get(this.runSendKey(chatId, turnId));
|
|
||||||
if (snapshot?.completionIdsProvided && pending?.startsNewRun !== false) return false;
|
|
||||||
if (!snapshot || snapshot.activeTurnId === turnId) return false;
|
|
||||||
if (snapshot.hasPendingToolCalls) return false;
|
|
||||||
if (observed.has(turnId)) return true;
|
|
||||||
return pending?.state === "unknown" || pending?.state === "accepted";
|
|
||||||
}
|
|
||||||
|
|
||||||
private settleNonLifecycleCanonicalSends(
|
|
||||||
chatId: string,
|
|
||||||
completed: ReadonlySet<string>,
|
|
||||||
observed: ReadonlySet<string>,
|
|
||||||
snapshot?: CanonicalRunSnapshot,
|
|
||||||
): void {
|
|
||||||
for (const pending of [...this.pendingMessageSends.values()]) {
|
|
||||||
if (pending.chatId !== chatId || pending.startsNewRun) continue;
|
|
||||||
if (!this.canonicalTurnWillSettle(
|
|
||||||
chatId,
|
|
||||||
pending.turnId,
|
|
||||||
completed,
|
|
||||||
observed,
|
|
||||||
snapshot,
|
|
||||||
)) continue;
|
|
||||||
this.clearPendingMessageSend(chatId, pending.turnId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private prunePendingInboundTurn(chatId: string, turnId: string): void {
|
|
||||||
const pending = this.pendingInboundByChat.get(chatId);
|
|
||||||
if (!pending) return;
|
|
||||||
const remaining = pending.filter((event) => (
|
|
||||||
!("turn_id" in event)
|
|
||||||
|| event.turn_id !== turnId
|
|
||||||
));
|
|
||||||
if (remaining.length > 0) this.pendingInboundByChat.set(chatId, remaining);
|
|
||||||
else this.pendingInboundByChat.delete(chatId);
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Pure preflight for canonical reconciliation.
|
|
||||||
*
|
|
||||||
* Unlike ``reconcileCanonicalCompletion``, this does not add completion
|
|
||||||
* fences, prune queued frames, settle turns, or emit run-status updates.
|
|
||||||
*/
|
|
||||||
canReconcileCanonicalCompletion(
|
canReconcileCanonicalCompletion(
|
||||||
chatId: string,
|
chatId: string,
|
||||||
expectedRunGeneration: number,
|
expectedRunGeneration: number,
|
||||||
completedTurnIds: readonly string[],
|
completedTurnIds: readonly string[],
|
||||||
snapshot?: CanonicalRunSnapshot,
|
snapshot?: CanonicalRunSnapshot,
|
||||||
): boolean {
|
): boolean {
|
||||||
const completed = new Set(this.canonicalCompletedTurnIdsByChatId.get(chatId));
|
return this.runs.canApplyCanonical({
|
||||||
for (const turnId of completedTurnIds) {
|
chatId, generation: expectedRunGeneration, completedTurnIds, snapshot,
|
||||||
if (turnId) completed.add(turnId);
|
});
|
||||||
}
|
|
||||||
const observed = new Set(
|
|
||||||
snapshot?.observedTurnIds.filter((turnId) => turnId.length > 0) ?? [],
|
|
||||||
);
|
|
||||||
const willSettle = (turnId: string): boolean => this.canonicalTurnWillSettle(
|
|
||||||
chatId,
|
|
||||||
turnId,
|
|
||||||
completed,
|
|
||||||
observed,
|
|
||||||
snapshot,
|
|
||||||
);
|
|
||||||
const latestRunTurnId = this.latestRunTurnIdByChatId.get(chatId);
|
|
||||||
const latestRunIsRepresented = (
|
|
||||||
typeof latestRunTurnId === "string"
|
|
||||||
&& (
|
|
||||||
completed.has(latestRunTurnId)
|
|
||||||
|| (
|
|
||||||
observed.has(latestRunTurnId)
|
|
||||||
&& willSettle(latestRunTurnId)
|
|
||||||
)
|
|
||||||
)
|
|
||||||
);
|
|
||||||
const unsettledTurnIds = this.unsettledRunTurnIdsByChatId.get(chatId);
|
|
||||||
const hasUnrepresentedTurn = (
|
|
||||||
unsettledTurnIds !== undefined
|
|
||||||
&& Array.from(unsettledTurnIds).some((turnId) => !willSettle(turnId))
|
|
||||||
);
|
|
||||||
const hasUnidentifiedActiveRun = (
|
|
||||||
this.runStartedAtByChatId.has(chatId)
|
|
||||||
&& latestRunTurnId === undefined
|
|
||||||
&& (snapshot === undefined || snapshot.hasPendingToolCalls)
|
|
||||||
);
|
|
||||||
if (hasUnrepresentedTurn || hasUnidentifiedActiveRun) return false;
|
|
||||||
return (
|
|
||||||
this.getRunGeneration(chatId) === expectedRunGeneration
|
|
||||||
|| latestRunIsRepresented
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/** Preserve explicit completion fences even when a newer run prevents adoption. */
|
||||||
* Atomically accept an HTTP snapshot as completed if no unrepresented run
|
|
||||||
* started while the request was in flight.
|
|
||||||
*
|
|
||||||
* Completed turn ids are fenced even when the snapshot loses the generation
|
|
||||||
* race: delayed websocket frames for older turns must never mutate newer UI.
|
|
||||||
*/
|
|
||||||
reconcileCanonicalCompletion(
|
reconcileCanonicalCompletion(
|
||||||
chatId: string,
|
chatId: string,
|
||||||
expectedRunGeneration: number,
|
expectedRunGeneration: number,
|
||||||
completedTurnIds: readonly string[],
|
completedTurnIds: readonly string[],
|
||||||
snapshot?: CanonicalRunSnapshot,
|
snapshot?: CanonicalRunSnapshot,
|
||||||
): boolean {
|
): boolean {
|
||||||
this.fenceCanonicalCompletedTurns(chatId, completedTurnIds);
|
const result = this.runs.applyCanonical({
|
||||||
const fences = this.canonicalCompletedTurnIdsByChatId.get(chatId) ?? new Set<string>();
|
chatId, generation: expectedRunGeneration, completedTurnIds, snapshot,
|
||||||
|
});
|
||||||
if (!this.canReconcileCanonicalCompletion(
|
this.applyRunEffects(result.effects);
|
||||||
chatId,
|
return result.accepted;
|
||||||
expectedRunGeneration,
|
|
||||||
[],
|
|
||||||
snapshot,
|
|
||||||
)) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const completed = new Set(fences);
|
|
||||||
const observed = new Set(
|
|
||||||
snapshot?.observedTurnIds.filter((turnId) => turnId.length > 0) ?? [],
|
|
||||||
);
|
|
||||||
const unsettledTurnIds = this.unsettledRunTurnIdsByChatId.get(chatId);
|
|
||||||
if (unsettledTurnIds) {
|
|
||||||
for (const turnId of [...unsettledTurnIds]) {
|
|
||||||
if (!this.canonicalTurnWillSettle(
|
|
||||||
chatId,
|
|
||||||
turnId,
|
|
||||||
completed,
|
|
||||||
observed,
|
|
||||||
snapshot,
|
|
||||||
)) continue;
|
|
||||||
this.rememberRunCompletion(chatId, turnId);
|
|
||||||
unsettledTurnIds.delete(turnId);
|
|
||||||
this.clearPendingMessageSend(chatId, turnId);
|
|
||||||
this.runStartedAtByTurnKey.delete(this.runSendKey(chatId, turnId));
|
|
||||||
}
|
|
||||||
if (unsettledTurnIds.size === 0) this.unsettledRunTurnIdsByChatId.delete(chatId);
|
|
||||||
}
|
|
||||||
this.settleNonLifecycleCanonicalSends(chatId, completed, observed, snapshot);
|
|
||||||
if (this.runStartedAtByChatId.delete(chatId)) {
|
|
||||||
this.emitRunStatus(chatId, null);
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Remember explicit terminal facts even when a history snapshot cannot replace live UI. */
|
|
||||||
fenceCanonicalCompletedTurns(chatId: string, completedTurnIds: readonly string[]): void {
|
fenceCanonicalCompletedTurns(chatId: string, completedTurnIds: readonly string[]): void {
|
||||||
const fences = this.canonicalCompletedTurnIdsByChatId.get(chatId) ?? new Set<string>();
|
this.applyRunEffects(this.runs.transition({ kind: "fence", chatId, completedTurnIds }));
|
||||||
for (const turnId of completedTurnIds) {
|
|
||||||
if (!turnId) continue;
|
|
||||||
fences.add(turnId);
|
|
||||||
}
|
|
||||||
while (fences.size > NanobotClient.COMPLETED_TURN_FENCE_MAX) {
|
|
||||||
const oldest = fences.values().next().value;
|
|
||||||
if (typeof oldest !== "string") break;
|
|
||||||
fences.delete(oldest);
|
|
||||||
}
|
|
||||||
if (fences.size > 0) this.canonicalCompletedTurnIdsByChatId.set(chatId, fences);
|
|
||||||
const pendingInbound = this.pendingInboundByChat.get(chatId);
|
|
||||||
if (pendingInbound) {
|
|
||||||
const remaining = pendingInbound.filter((event) => {
|
|
||||||
const turnId = "turn_id" in event && typeof event.turn_id === "string"
|
|
||||||
? event.turn_id
|
|
||||||
: null;
|
|
||||||
return turnId === null || !fences.has(turnId);
|
|
||||||
});
|
|
||||||
if (remaining.length > 0) this.pendingInboundByChat.set(chatId, remaining);
|
|
||||||
else this.pendingInboundByChat.delete(chatId);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Last ``goal_state`` payload for *chatId*, if any frame has arrived this connection. */
|
/** Last ``goal_state`` payload for *chatId*, if any frame has arrived this connection. */
|
||||||
@@ -575,145 +400,6 @@ export class NanobotClient {
|
|||||||
return this.goalStateByChatId.get(chatId);
|
return this.goalStateByChatId.get(chatId);
|
||||||
}
|
}
|
||||||
|
|
||||||
private advanceRunGeneration(chatId: string, turnId?: string): void {
|
|
||||||
this.runGenerationByChatId.set(chatId, this.getRunGeneration(chatId) + 1);
|
|
||||||
if (turnId) {
|
|
||||||
this.latestRunTurnIdByChatId.set(chatId, turnId);
|
|
||||||
const unsettled = this.unsettledRunTurnIdsByChatId.get(chatId) ?? new Set<string>();
|
|
||||||
unsettled.add(turnId);
|
|
||||||
this.unsettledRunTurnIdsByChatId.set(chatId, unsettled);
|
|
||||||
} else {
|
|
||||||
this.latestRunTurnIdByChatId.delete(chatId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private settleRunTurn(chatId: string, turnId?: string): void {
|
|
||||||
if (!turnId) return;
|
|
||||||
this.clearPendingMessageSend(chatId, turnId);
|
|
||||||
this.runStartedAtByTurnKey.delete(this.runSendKey(chatId, turnId));
|
|
||||||
const unsettled = this.unsettledRunTurnIdsByChatId.get(chatId);
|
|
||||||
if (!unsettled) return;
|
|
||||||
unsettled.delete(turnId);
|
|
||||||
if (unsettled.size === 0) this.unsettledRunTurnIdsByChatId.delete(chatId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private runSendKey(chatId: string, turnId: string): string {
|
|
||||||
return `${chatId}\u0000${turnId}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
private trackPendingMessageSend(
|
|
||||||
chatId: string,
|
|
||||||
turnId: string,
|
|
||||||
startsNewRun: boolean,
|
|
||||||
): void {
|
|
||||||
const key = this.runSendKey(chatId, turnId);
|
|
||||||
this.pendingMessageSends.set(key, {
|
|
||||||
chatId,
|
|
||||||
turnId,
|
|
||||||
startsNewRun,
|
|
||||||
state: "queued",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
private clearPendingMessageSend(chatId: string, turnId: string): void {
|
|
||||||
const key = this.runSendKey(chatId, turnId);
|
|
||||||
this.pendingMessageSends.delete(key);
|
|
||||||
this.socketPendingMessageSendKeys.delete(key);
|
|
||||||
this.sendQueue = this.sendQueue.filter((frame) => !(
|
|
||||||
frame.type === "message"
|
|
||||||
&& frame.chat_id === chatId
|
|
||||||
&& frame.turn_id === turnId
|
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
private recordRunAcceptance(chatId: string, turnId?: string): void {
|
|
||||||
if (!turnId) return;
|
|
||||||
const key = this.runSendKey(chatId, turnId);
|
|
||||||
const pending = this.pendingMessageSends.get(key);
|
|
||||||
if (!pending) return;
|
|
||||||
this.socketPendingMessageSendKeys.delete(key);
|
|
||||||
if (!pending.startsNewRun) {
|
|
||||||
this.pendingMessageSends.delete(key);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
pending.state = "accepted";
|
|
||||||
}
|
|
||||||
|
|
||||||
private recordCanonicalTurnOwnership(
|
|
||||||
ev: Extract<InboundEvent, { event: "message_accepted" | "user_message" }>,
|
|
||||||
): Extract<InboundEvent, { event: "message_accepted" | "user_message" }> {
|
|
||||||
const activeTurnId = ev.active_turn_id ?? (ev.starts_turn ? ev.turn_id : undefined);
|
|
||||||
if (!activeTurnId) return ev;
|
|
||||||
|
|
||||||
if (this.isRunCompleted(ev.chat_id, activeTurnId)) {
|
|
||||||
// The input is still valid, but its admission-time owner is already closed.
|
|
||||||
// Undo a local new-run guess when this input was actually steering that owner.
|
|
||||||
const pending = ev.turn_id
|
|
||||||
? this.pendingMessageSends.get(this.runSendKey(ev.chat_id, ev.turn_id))
|
|
||||||
: undefined;
|
|
||||||
if (pending?.startsNewRun && ev.turn_id !== activeTurnId) {
|
|
||||||
this.recordRunRejection(ev.chat_id, ev.turn_id);
|
|
||||||
if (!this.hasUnsettledRun(ev.chat_id)) this.emitRunStatus(ev.chat_id, null);
|
|
||||||
}
|
|
||||||
return { ...ev, active_turn_id: undefined, started_at: undefined, starts_turn: false };
|
|
||||||
}
|
|
||||||
|
|
||||||
// Two clients can optimistically submit while the chat still looks idle.
|
|
||||||
// The gateway admits exactly one owner and classifies the other message as
|
|
||||||
// steering. Replace the local guess before its ACK can preserve the wrong
|
|
||||||
// run identity.
|
|
||||||
if (ev.turn_id && ev.turn_id !== activeTurnId) {
|
|
||||||
const pending = this.pendingMessageSends.get(this.runSendKey(ev.chat_id, ev.turn_id));
|
|
||||||
if (pending?.startsNewRun) this.settleRunTurn(ev.chat_id, ev.turn_id);
|
|
||||||
}
|
|
||||||
if (this.latestRunTurnIdByChatId.get(ev.chat_id) !== activeTurnId) {
|
|
||||||
this.advanceRunGeneration(ev.chat_id, activeTurnId);
|
|
||||||
}
|
|
||||||
if (typeof ev.started_at === "number") {
|
|
||||||
this.runStartedAtByTurnKey.set(
|
|
||||||
this.runSendKey(ev.chat_id, activeTurnId),
|
|
||||||
ev.started_at,
|
|
||||||
);
|
|
||||||
const previous = this.runStartedAtByChatId.get(ev.chat_id);
|
|
||||||
this.runStartedAtByChatId.set(ev.chat_id, ev.started_at);
|
|
||||||
if (previous !== ev.started_at) this.emitRunStatus(ev.chat_id, ev.started_at);
|
|
||||||
}
|
|
||||||
return ev;
|
|
||||||
}
|
|
||||||
|
|
||||||
private recordRunRejection(chatId: string, turnId?: string): void {
|
|
||||||
if (!turnId) return;
|
|
||||||
const rejectedLatest = this.latestRunTurnIdByChatId.get(chatId) === turnId;
|
|
||||||
this.settleRunTurn(chatId, turnId);
|
|
||||||
this.prunePendingInboundTurn(chatId, turnId);
|
|
||||||
if (!rejectedLatest) return;
|
|
||||||
|
|
||||||
const unsettled = this.unsettledRunTurnIdsByChatId.get(chatId);
|
|
||||||
const previousTurnId = unsettled ? Array.from(unsettled).at(-1) : undefined;
|
|
||||||
if (previousTurnId) {
|
|
||||||
this.latestRunTurnIdByChatId.set(chatId, previousTurnId);
|
|
||||||
const previousStartedAt = this.runStartedAtByTurnKey.get(
|
|
||||||
this.runSendKey(chatId, previousTurnId),
|
|
||||||
);
|
|
||||||
const currentStartedAt = this.runStartedAtByChatId.get(chatId);
|
|
||||||
if (previousStartedAt === undefined) {
|
|
||||||
if (this.runStartedAtByChatId.delete(chatId)) {
|
|
||||||
this.emitRunStatus(chatId, null);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
this.runStartedAtByChatId.set(chatId, previousStartedAt);
|
|
||||||
if (currentStartedAt !== previousStartedAt) {
|
|
||||||
this.emitRunStatus(chatId, previousStartedAt);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
this.latestRunTurnIdByChatId.delete(chatId);
|
|
||||||
if (this.runStartedAtByChatId.delete(chatId)) {
|
|
||||||
this.emitRunStatus(chatId, null);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private legacyRejectionTarget(ev: Extract<InboundEvent, { event: "error" }>): {
|
private legacyRejectionTarget(ev: Extract<InboundEvent, { event: "error" }>): {
|
||||||
chatId: string;
|
chatId: string;
|
||||||
turnId: string;
|
turnId: string;
|
||||||
@@ -724,94 +410,43 @@ export class NanobotClient {
|
|||||||
&& ev.chat_id === undefined
|
&& ev.chat_id === undefined
|
||||||
&& this.pendingNewChat
|
&& this.pendingNewChat
|
||||||
) return null;
|
) return null;
|
||||||
const candidates = [...this.pendingMessageSends.values()].filter((pending) => (
|
return this.runs.soleSentTurn(this.lastSocketMessageSend, ev.chat_id);
|
||||||
// A legacy error can only reject a frame currently awaiting its first
|
|
||||||
// server disposition. Accepted or prior-connection unknown sends are
|
|
||||||
// not safe candidates for an uncorrelated frame.
|
|
||||||
pending.state === "sent"
|
|
||||||
&& (ev.chat_id === undefined || pending.chatId === ev.chat_id)
|
|
||||||
));
|
|
||||||
if (candidates.length !== 1) return null;
|
|
||||||
const [candidate] = candidates;
|
|
||||||
if (
|
|
||||||
this.lastSocketMessageSendKey
|
|
||||||
!== this.runSendKey(candidate.chatId, candidate.turnId)
|
|
||||||
) return null;
|
|
||||||
return { chatId: candidate.chatId, turnId: candidate.turnId };
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private uniqueUnsettledTurnId(chatId: string): string | null {
|
private applyRunEffects(effects: readonly RunEffect[]): void {
|
||||||
const unsettled = this.unsettledRunTurnIdsByChatId.get(chatId);
|
for (const effect of effects) {
|
||||||
if (!unsettled || unsettled.size !== 1) return null;
|
switch (effect.kind) {
|
||||||
return unsettled.values().next().value ?? null;
|
case "run-status":
|
||||||
}
|
this.emitRunStatus(effect.chatId, effect.startedAt);
|
||||||
|
break;
|
||||||
private isCanonicalCompletedTurnEvent(chatId: string, ev: InboundEvent): boolean {
|
case "completion":
|
||||||
const turnId = "turn_id" in ev && typeof ev.turn_id === "string" ? ev.turn_id : null;
|
for (const handler of this.runCompletionHandlers) handler(effect.chatId);
|
||||||
return (
|
break;
|
||||||
turnId !== null
|
case "discard-send":
|
||||||
&& this.canonicalCompletedTurnIdsByChatId.get(chatId)?.has(turnId) === true
|
this.sendQueue = this.sendQueue.filter((frame) => !(
|
||||||
);
|
frame.type === "message"
|
||||||
}
|
&& frame.chat_id === effect.chatId
|
||||||
|
&& frame.turn_id === effect.turnId
|
||||||
private rememberRunCompletion(chatId: string, turnId: string): void {
|
));
|
||||||
const closed = this.closedRunTurnIdsByChatId.get(chatId) ?? new Set<string>();
|
break;
|
||||||
closed.add(turnId);
|
case "prune-inbound": {
|
||||||
while (closed.size > NanobotClient.COMPLETED_TURN_FENCE_MAX) {
|
const pending = this.pendingInboundByChat.get(effect.chatId);
|
||||||
const oldest = closed.values().next().value;
|
if (!pending) break;
|
||||||
if (typeof oldest !== "string") break;
|
const turnIds = new Set(effect.turnIds);
|
||||||
closed.delete(oldest);
|
const remaining = pending.filter((event) => (
|
||||||
}
|
!("turn_id" in event)
|
||||||
this.closedRunTurnIdsByChatId.set(chatId, closed);
|
|| typeof event.turn_id !== "string"
|
||||||
}
|
|| !turnIds.has(event.turn_id)
|
||||||
|
));
|
||||||
private isSupersededRunCompletion(chatId: string, ev: InboundEvent): boolean {
|
if (remaining.length > 0) this.pendingInboundByChat.set(effect.chatId, remaining);
|
||||||
if (
|
else this.pendingInboundByChat.delete(effect.chatId);
|
||||||
ev.event !== "turn_end"
|
break;
|
||||||
&& !(ev.event === "goal_status" && ev.status === "idle")
|
}
|
||||||
) {
|
default: {
|
||||||
return false;
|
const exhaustive: never = effect;
|
||||||
}
|
return exhaustive;
|
||||||
const turnId = "turn_id" in ev && typeof ev.turn_id === "string" ? ev.turn_id : undefined;
|
}
|
||||||
const latestRunTurnId = this.latestRunTurnIdByChatId.get(chatId);
|
|
||||||
if (turnId === undefined && latestRunTurnId !== undefined) return true;
|
|
||||||
return (
|
|
||||||
turnId !== undefined
|
|
||||||
&& latestRunTurnId !== undefined
|
|
||||||
&& turnId !== latestRunTurnId
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
private recordRunCompletion(chatId: string, turnId?: string): void {
|
|
||||||
if (turnId) this.rememberRunCompletion(chatId, turnId);
|
|
||||||
this.settleRunTurn(chatId, turnId);
|
|
||||||
const latestRunTurnId = this.latestRunTurnIdByChatId.get(chatId);
|
|
||||||
const closesCurrentRun = latestRunTurnId === undefined || turnId === latestRunTurnId;
|
|
||||||
if (closesCurrentRun && this.runStartedAtByChatId.delete(chatId)) {
|
|
||||||
this.emitRunStatus(chatId, null);
|
|
||||||
}
|
|
||||||
for (const handler of this.runCompletionHandlers) handler(chatId);
|
|
||||||
}
|
|
||||||
|
|
||||||
private recordGoalStatusForRunStrip(chatId: string, ev: InboundEvent): void {
|
|
||||||
if (ev.event === "turn_end") {
|
|
||||||
this.recordRunCompletion(chatId, ev.turn_id);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
if (ev.event !== "goal_status") return;
|
|
||||||
if (ev.status === "running" && typeof ev.started_at === "number") {
|
|
||||||
this.advanceRunGeneration(chatId, ev.turn_id);
|
|
||||||
if (ev.turn_id) {
|
|
||||||
this.runStartedAtByTurnKey.set(
|
|
||||||
this.runSendKey(chatId, ev.turn_id),
|
|
||||||
ev.started_at,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
const previous = this.runStartedAtByChatId.get(chatId);
|
|
||||||
this.runStartedAtByChatId.set(chatId, ev.started_at);
|
|
||||||
if (previous !== ev.started_at) this.emitRunStatus(chatId, ev.started_at);
|
|
||||||
} else {
|
|
||||||
this.recordRunCompletion(chatId, ev.turn_id);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1110,9 +745,12 @@ export class NanobotClient {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
if (options?.turnId && !isSystemCommandTurnId(options.turnId)) {
|
if (options?.turnId && !isSystemCommandTurnId(options.turnId)) {
|
||||||
const startsNewRun = options.startsNewRun !== false;
|
this.applyRunEffects(this.runs.transition({
|
||||||
if (startsNewRun) this.advanceRunGeneration(chatId, options.turnId);
|
kind: "submit",
|
||||||
this.trackPendingMessageSend(chatId, options.turnId, startsNewRun);
|
chatId,
|
||||||
|
turnId: options.turnId,
|
||||||
|
role: options.startsNewRun === false ? "supplement" : "candidate-owner",
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
this.queueSend(frame);
|
this.queueSend(frame);
|
||||||
return true;
|
return true;
|
||||||
@@ -1219,7 +857,7 @@ export class NanobotClient {
|
|||||||
(parsed.event === "goal_status" || parsed.event === "turn_end")
|
(parsed.event === "goal_status" || parsed.event === "turn_end")
|
||||||
&& !parsed.turn_id
|
&& !parsed.turn_id
|
||||||
) {
|
) {
|
||||||
const fallbackTurnId = this.uniqueUnsettledTurnId(parsed.chat_id);
|
const fallbackTurnId = this.runs.soleUnsettledTurn(parsed.chat_id);
|
||||||
if (fallbackTurnId) parsed = { ...parsed, turn_id: fallbackTurnId };
|
if (fallbackTurnId) parsed = { ...parsed, turn_id: fallbackTurnId };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1227,20 +865,20 @@ export class NanobotClient {
|
|||||||
const turnId = "turn_id" in parsed && typeof parsed.turn_id === "string"
|
const turnId = "turn_id" in parsed && typeof parsed.turn_id === "string"
|
||||||
? parsed.turn_id
|
? parsed.turn_id
|
||||||
: null;
|
: null;
|
||||||
const correlatedChatId = (parsed as { chat_id?: string }).chat_id;
|
const correlatedChatId = "chat_id" in parsed ? parsed.chat_id : undefined;
|
||||||
// Fence before ownership, clocks, acceptance, or subscribers can mutate state.
|
const observation = runObservation(parsed);
|
||||||
if (correlatedChatId && this.isCanonicalCompletedTurnEvent(correlatedChatId, parsed)) return;
|
if (observation) {
|
||||||
if (
|
const result = this.runs.observe(observation);
|
||||||
correlatedChatId && turnId && this.isRunCompleted(correlatedChatId, turnId)
|
this.applyRunEffects(result.effects);
|
||||||
&& parsed.event !== "message_accepted" && parsed.event !== "user_message"
|
if (result.forward === "drop") return;
|
||||||
&& parsed.event !== "message" && parsed.event !== "turn_end"
|
if (
|
||||||
&& !(parsed.event === "goal_status" && parsed.status === "idle")
|
result.forward === "without-owner"
|
||||||
) return;
|
&& (parsed.event === "message_accepted" || parsed.event === "user_message")
|
||||||
if (parsed.event === "message_accepted" || parsed.event === "user_message") {
|
) {
|
||||||
parsed = this.recordCanonicalTurnOwnership(parsed);
|
parsed = { ...parsed, active_turn_id: undefined, started_at: undefined, starts_turn: false };
|
||||||
|
}
|
||||||
}
|
}
|
||||||
if (parsed.event === "message_accepted") {
|
if (parsed.event === "message_accepted") {
|
||||||
this.recordRunAcceptance(parsed.chat_id, parsed.turn_id);
|
|
||||||
if (!isSystemCommandTurnId(turnId)) {
|
if (!isSystemCommandTurnId(turnId)) {
|
||||||
this.dispatch(parsed.chat_id, parsed);
|
this.dispatch(parsed.chat_id, parsed);
|
||||||
}
|
}
|
||||||
@@ -1259,7 +897,6 @@ export class NanobotClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (parsed.event === "error" && correlatedChatId && turnId) {
|
if (parsed.event === "error" && correlatedChatId && turnId) {
|
||||||
this.recordRunRejection(correlatedChatId, turnId);
|
|
||||||
if (parsed.detail !== "workspace_scope_rejected") {
|
if (parsed.detail !== "workspace_scope_rejected") {
|
||||||
this.emitError({
|
this.emitError({
|
||||||
kind: "turn_rejected",
|
kind: "turn_rejected",
|
||||||
@@ -1269,10 +906,6 @@ export class NanobotClient {
|
|||||||
turnId,
|
turnId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
} else if (parsed.event !== "error" && correlatedChatId && turnId) {
|
|
||||||
// Lifecycle traffic is also an implicit acceptance signal for clients
|
|
||||||
// connected to an older gateway that doesn't emit message_accepted.
|
|
||||||
this.recordRunAcceptance(correlatedChatId, turnId);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (parsed.event === "ready") {
|
if (parsed.event === "ready") {
|
||||||
@@ -1347,13 +980,9 @@ export class NanobotClient {
|
|||||||
this.pendingNewChat = null;
|
this.pendingNewChat = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const chatId = (parsed as { chat_id?: string }).chat_id;
|
if (correlatedChatId) {
|
||||||
if (chatId) {
|
this.recordGoalStateSnapshot(correlatedChatId, parsed);
|
||||||
const supersededRunCompletion = this.isSupersededRunCompletion(chatId, parsed);
|
this.dispatch(correlatedChatId, parsed);
|
||||||
this.recordGoalStatusForRunStrip(chatId, parsed);
|
|
||||||
if (supersededRunCompletion) return;
|
|
||||||
this.recordGoalStateSnapshot(chatId, parsed);
|
|
||||||
this.dispatch(chatId, parsed);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1439,24 +1068,11 @@ export class NanobotClient {
|
|||||||
// display the error even while the client transparently reconnects.
|
// display the error even while the client transparently reconnects.
|
||||||
// Browsers populate ``CloseEvent.code`` with the wire-level close code;
|
// Browsers populate ``CloseEvent.code`` with the wire-level close code;
|
||||||
// 1009 = Message Too Big (server's max frame guard).
|
// 1009 = Message Too Big (server's max frame guard).
|
||||||
const unacknowledged = Array.from(this.socketPendingMessageSendKeys)
|
|
||||||
.map((key) => this.pendingMessageSends.get(key))
|
|
||||||
.filter((pending): pending is PendingMessageSend => pending !== undefined);
|
|
||||||
if (event?.code === 1009) {
|
if (event?.code === 1009) {
|
||||||
const soleKey = unacknowledged.length === 1
|
const rejected = this.runs.soleSentTurn(this.lastSocketMessageSend);
|
||||||
? this.runSendKey(unacknowledged[0].chatId, unacknowledged[0].turnId)
|
if (rejected) {
|
||||||
: null;
|
this.applyRunEffects(this.runs.transition({ kind: "reject", ...rejected }));
|
||||||
if (
|
this.emitError({ kind: "message_too_big", ...rejected });
|
||||||
unacknowledged.length === 1
|
|
||||||
&& this.lastSocketMessageSendKey === soleKey
|
|
||||||
) {
|
|
||||||
const [rejected] = unacknowledged;
|
|
||||||
this.recordRunRejection(rejected.chatId, rejected.turnId);
|
|
||||||
this.emitError({
|
|
||||||
kind: "message_too_big",
|
|
||||||
chatId: rejected.chatId,
|
|
||||||
turnId: rejected.turnId,
|
|
||||||
});
|
|
||||||
this.dispatch(rejected.chatId, {
|
this.dispatch(rejected.chatId, {
|
||||||
event: "error",
|
event: "error",
|
||||||
detail: "message_too_big",
|
detail: "message_too_big",
|
||||||
@@ -1464,19 +1080,12 @@ export class NanobotClient {
|
|||||||
turn_id: rejected.turnId,
|
turn_id: rejected.turnId,
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
// A close frame identifies no offending application message. Never
|
// A close frame cannot identify one message among multiplexed sends.
|
||||||
// roll back multiple chats merely because they shared one socket.
|
|
||||||
this.emitError({ kind: "message_too_big" });
|
this.emitError({ kind: "message_too_big" });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
for (const pending of unacknowledged) {
|
this.applyRunEffects(this.runs.transition({ kind: "transport-lost" }));
|
||||||
const current = this.pendingMessageSends.get(
|
this.lastSocketMessageSend = null;
|
||||||
this.runSendKey(pending.chatId, pending.turnId),
|
|
||||||
);
|
|
||||||
if (current?.state === "sent") current.state = "unknown";
|
|
||||||
}
|
|
||||||
this.socketPendingMessageSendKeys.clear();
|
|
||||||
this.lastSocketMessageSendKey = null;
|
|
||||||
if (!willReconnect) {
|
if (!willReconnect) {
|
||||||
this.setStatus("closed");
|
this.setStatus("closed");
|
||||||
return;
|
return;
|
||||||
@@ -1580,28 +1189,13 @@ export class NanobotClient {
|
|||||||
this.knownChats.delete(chatId);
|
this.knownChats.delete(chatId);
|
||||||
this.chatHandlers.delete(chatId);
|
this.chatHandlers.delete(chatId);
|
||||||
this.pendingInboundByChat.delete(chatId);
|
this.pendingInboundByChat.delete(chatId);
|
||||||
const wasRunning = this.runStartedAtByChatId.delete(chatId);
|
const effects = this.runs.transition({ kind: "forget", chatId });
|
||||||
this.runGenerationByChatId.delete(chatId);
|
|
||||||
this.latestRunTurnIdByChatId.delete(chatId);
|
|
||||||
this.unsettledRunTurnIdsByChatId.delete(chatId);
|
|
||||||
this.canonicalCompletedTurnIdsByChatId.delete(chatId);
|
|
||||||
this.closedRunTurnIdsByChatId.delete(chatId);
|
|
||||||
this.goalStateByChatId.delete(chatId);
|
this.goalStateByChatId.delete(chatId);
|
||||||
for (const key of [...this.runStartedAtByTurnKey.keys()]) {
|
|
||||||
if (key.startsWith(`${chatId}\u0000`)) this.runStartedAtByTurnKey.delete(key);
|
|
||||||
}
|
|
||||||
for (const [key, pending] of [...this.pendingMessageSends]) {
|
|
||||||
if (pending.chatId !== chatId) continue;
|
|
||||||
this.pendingMessageSends.delete(key);
|
|
||||||
this.socketPendingMessageSendKeys.delete(key);
|
|
||||||
}
|
|
||||||
this.sendQueue = this.sendQueue.filter((frame) => (
|
this.sendQueue = this.sendQueue.filter((frame) => (
|
||||||
!("chat_id" in frame) || frame.chat_id !== chatId
|
!("chat_id" in frame) || frame.chat_id !== chatId
|
||||||
));
|
));
|
||||||
if (this.lastSocketMessageSendKey?.startsWith(`${chatId}\u0000`)) {
|
if (this.lastSocketMessageSend?.chatId === chatId) this.lastSocketMessageSend = null;
|
||||||
this.lastSocketMessageSendKey = null;
|
this.applyRunEffects(effects);
|
||||||
}
|
|
||||||
if (wasRunning) this.emitRunStatus(chatId, null);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private frameFitsTransport(frame: Outbound): boolean {
|
private frameFitsTransport(frame: Outbound): boolean {
|
||||||
@@ -1613,14 +1207,12 @@ export class NanobotClient {
|
|||||||
if (!this.socket) return;
|
if (!this.socket) return;
|
||||||
try {
|
try {
|
||||||
this.socket.send(JSON.stringify(frame));
|
this.socket.send(JSON.stringify(frame));
|
||||||
this.lastSocketMessageSendKey = null;
|
this.lastSocketMessageSend = null;
|
||||||
if (frame.type === "message" && frame.turn_id) {
|
if (frame.type === "message" && frame.turn_id) {
|
||||||
const key = this.runSendKey(frame.chat_id, frame.turn_id);
|
const ref = { chatId: frame.chat_id, turnId: frame.turn_id };
|
||||||
const pending = this.pendingMessageSends.get(key);
|
if (this.runs.hasPendingSend(ref)) {
|
||||||
if (pending) {
|
this.applyRunEffects(this.runs.transition({ kind: "written", ...ref }));
|
||||||
pending.state = "sent";
|
this.lastSocketMessageSend = ref;
|
||||||
this.socketPendingMessageSendKeys.add(key);
|
|
||||||
this.lastSocketMessageSendKey = key;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -1511,6 +1511,60 @@ describe("NanobotClient", () => {
|
|||||||
await expect(pending).rejects.toThrow("message_rejected:invalid_command");
|
await expect(pending).rejects.toThrow("message_rejected:invalid_command");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it.each(["progress", "tool_hint", "reasoning"] as const)(
|
||||||
|
"delivers a delayed %s message after completion without reopening the turn",
|
||||||
|
(kind) => {
|
||||||
|
const client = new NanobotClient({
|
||||||
|
url: "ws://test", reconnect: false,
|
||||||
|
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||||
|
});
|
||||||
|
const handler = vi.fn();
|
||||||
|
client.onChat("chat-late", handler);
|
||||||
|
client.connect();
|
||||||
|
const socket = lastSocket();
|
||||||
|
socket.fakeOpen();
|
||||||
|
socket.fakeMessage({
|
||||||
|
event: "goal_status", chat_id: "chat-late", turn_id: "turn-late",
|
||||||
|
status: "running", started_at: 123,
|
||||||
|
});
|
||||||
|
expect(client.getRunStartedAt("chat-late")).toBe(123);
|
||||||
|
socket.fakeMessage({ event: "turn_end", chat_id: "chat-late", turn_id: "turn-late" });
|
||||||
|
const message = {
|
||||||
|
event: "message", chat_id: "chat-late", turn_id: "turn-late", kind, text: "Late detail",
|
||||||
|
};
|
||||||
|
socket.fakeMessage(message);
|
||||||
|
|
||||||
|
expect(handler).toHaveBeenLastCalledWith(message);
|
||||||
|
expect(client.isRunCompleted("chat-late", "turn-late")).toBe(true);
|
||||||
|
expect(client.getRunStartedAt("chat-late")).toBeNull();
|
||||||
|
expect(client.hasUnsettledRun("chat-late")).toBe(false);
|
||||||
|
client.close();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
it("settles running status without a start timestamp", () => {
|
||||||
|
const client = new NanobotClient({
|
||||||
|
url: "ws://test", reconnect: false,
|
||||||
|
socketFactory: (url) => new FakeSocket(url) as unknown as WebSocket,
|
||||||
|
});
|
||||||
|
client.connect();
|
||||||
|
const socket = lastSocket();
|
||||||
|
socket.fakeOpen();
|
||||||
|
client.sendMessage("chat-legacy", "task", undefined, { turnId: "turn-legacy" });
|
||||||
|
expect(client.hasUnsettledRun("chat-legacy")).toBe(true);
|
||||||
|
const completed = vi.fn();
|
||||||
|
client.onRunCompletion(completed);
|
||||||
|
socket.fakeMessage({
|
||||||
|
event: "goal_status", chat_id: "chat-legacy", turn_id: "turn-legacy", status: "running",
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(completed).toHaveBeenCalledWith("chat-legacy");
|
||||||
|
expect(client.isRunCompleted("chat-legacy", "turn-legacy")).toBe(true);
|
||||||
|
expect(client.hasUnsettledRun("chat-legacy")).toBe(false);
|
||||||
|
expect(client.getRunTurnId("chat-legacy")).toBe("turn-legacy");
|
||||||
|
client.close();
|
||||||
|
});
|
||||||
|
|
||||||
it("ignores a delayed idle event from an older turn after a new run starts", () => {
|
it("ignores a delayed idle event from an older turn after a new run starts", () => {
|
||||||
const client = new NanobotClient({
|
const client = new NanobotClient({
|
||||||
url: "ws://test",
|
url: "ws://test",
|
||||||
|
|||||||
Reference in new issue
Block a user