Keep retrying the connection and say why; never lose a message that didn't send

As the web's connection supervisor and composer:
- The first connection retries too, so tui3 opens without a server and
  connects when it's up. One-off commands still fail fast.
- The header says why it couldn't connect and when it retries; r, a
  click on it, or the palette retries now.
- Enter while disconnected keeps the message and says so.
- A failed send, or a new thread that doesn't start, puts the message,
  its attachments and its mentions back in the composer.
- Opening a PR in the browser says why it failed and copies the link.
- Error notices stay 8s instead of 4s.
This commit is contained in:
Callum Alpass committed 2026-11-02 23:13:06 +11:00
1 parent 275a2bcde1
commit 2c5eedc869
9 files changed
+169 -42

No files matched your search

+14 -8
View File
@@ -43,13 +43,15 @@ async function main(argv: string[]) {
} }
} }
/** For one-off commands: fails on the first failed attempt rather than retrying, as the UI does. */
async function connectedSession(): Promise<{ session: T3Session; snapshot: OrchestrationV2ShellSnapshot }> { async function connectedSession(): Promise<{ session: T3Session; snapshot: OrchestrationV2ShellSnapshot }> {
const session = new T3Session(); const session = new T3Session();
await session.start(); await session.start();
const snapshot = await new Promise<OrchestrationV2ShellSnapshot>((resolve, reject) => { const snapshot = await new Promise<OrchestrationV2ShellSnapshot>((resolve, reject) => {
const off = session.onShell((shell) => { const off = session.onShell((shell) => {
if (shell.status.type === "error") { if (shell.status.type === "reconnecting") {
queueMicrotask(() => off()); queueMicrotask(() => off());
void session.stop();
reject(new Error(shell.status.message)); reject(new Error(shell.status.message));
} else if (shell.status.type === "live" && shell.snapshot) { } else if (shell.status.type === "live" && shell.snapshot) {
queueMicrotask(() => off()); queueMicrotask(() => off());
@@ -109,18 +111,22 @@ async function tmuxCommand(args: string[]) {
} }
} }
}; };
session.onShell((shell) => { // A dropped connection retries by itself; sync runs again once the shell is back.
if (shell.status.type === "error") fail(shell.status.message); session.onShell(() => void sync());
void sync();
});
await new Promise(() => {}); await new Promise(() => {});
} }
async function runUi(attachNeedle?: string) { async function runUi(attachNeedle?: string) {
const { session, snapshot } = await connectedSession(); let session: T3Session;
let attachThreadId: ThreadId | undefined; let attachThreadId: ThreadId | undefined;
if (attachNeedle) { if (!attachNeedle) {
const thread = findThread(snapshot, attachNeedle); // The UI opens at once and shows the connection, retrying until the server is there.
session = new T3Session();
void session.start();
} else {
const connected = await connectedSession();
session = connected.session;
const thread = findThread(connected.snapshot, attachNeedle);
if (!thread) { if (!thread) {
await session.stop(); await session.stop();
return fail(`No thread matches "${attachNeedle}".`); return fail(`No thread matches "${attachNeedle}".`);
+20 -7
View File
@@ -89,11 +89,12 @@ import { applyShellStreamEvent, mergeShellSnapshotProjects } from "../../vendor/
import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT, type CommandOutputView } from "@t3tools/client-runtime/state/command-output"; import { applyCommandOutputFrame, EMPTY_COMMAND_OUTPUT, type CommandOutputView } from "@t3tools/client-runtime/state/command-output";
import { connect, type Connection } from "./rpc.ts"; import { connect, type Connection } from "./rpc.ts";
/** As the web's supervisor: it keeps retrying, first connection included, with the last failure as the reason. */
export type ConnectionStatus = export type ConnectionStatus =
| { readonly type: "connecting" } | { readonly type: "connecting" }
| { readonly type: "live" } | { readonly type: "live" }
| { readonly type: "reconnecting"; readonly message: string } /** `retryAt`: when the next attempt starts (epoch ms); null while one is under way. */
| { readonly type: "error"; readonly message: string }; | { readonly type: "reconnecting"; readonly message: string; readonly retryAt: number | null };
export interface ShellState { export interface ShellState {
readonly status: ConnectionStatus; readonly status: ConnectionStatus;
@@ -207,9 +208,7 @@ export class T3Session {
} catch (error) { } catch (error) {
this.scope = null; this.scope = null;
await Effect.runPromise(Scope.close(scope, Exit.void)); await Effect.runPromise(Scope.close(scope, Exit.void));
if (this.reconnectAttempt > 0) return this.scheduleReconnect(messageOf(error)); return this.scheduleReconnect(messageOf(error));
this.setShell({ status: { type: "error", message: messageOf(error) } });
return;
} }
this.recovering = false; this.recovering = false;
this.setShell({ serverUrl: this.connection.target.httpBaseUrl }); this.setShell({ serverUrl: this.connection.target.httpBaseUrl });
@@ -224,6 +223,14 @@ export class T3Session {
await this.closeScope(); await this.closeScope();
} }
/** Skips the wait before the next reconnect attempt. */
retryNow(): void {
if (this.stopped || !this.reconnectTimer) return;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
this.attempt();
}
getShell(): ShellState { getShell(): ShellState {
return this.shell; return this.shell;
} }
@@ -1109,13 +1116,19 @@ export class T3Session {
if (this.stopped || this.reconnectTimer) return; if (this.stopped || this.reconnectTimer) return;
const delay = RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]!; const delay = RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]!;
this.reconnectAttempt++; this.reconnectAttempt++;
this.setShell({ status: { type: "reconnecting", message } }); this.setShell({ status: { type: "reconnecting", message, retryAt: Date.now() + delay } });
this.reconnectTimer = setTimeout(() => { this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null; this.reconnectTimer = null;
void this.start(); this.attempt();
}, delay); }, delay);
} }
private attempt(): void {
const status = this.shell.status;
if (status.type === "reconnecting") this.setShell({ status: { ...status, retryAt: null } });
void this.start();
}
private async closeScope(): Promise<void> { private async closeScope(): Promise<void> {
const scope = this.scope; const scope = this.scope;
this.scope = null; this.scope = null;
+52 -15
View File
@@ -6,7 +6,7 @@ import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId } f
import { homedir } from "node:os"; import { homedir } from "node:os";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { OrchestrationV2Subagent } from "@t3tools/contracts"; import type { ChatAttachment, OrchestrationMessageContext, OrchestrationV2Subagent } from "@t3tools/contracts";
import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts"; import type { ServerConfigState, ShellState, T3Session, ThreadState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts"; import { createAlerts, type Alert } from "../model/alerts.ts";
import { modelSummary } from "../model/models.ts"; import { modelSummary } from "../model/models.ts";
@@ -304,7 +304,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}, [shell.snapshot, familyShells]); }, [shell.snapshot, familyShells]);
const say = (text: string, bad = false) => { const say = (text: string, bad = false) => {
setFlash({ text, bad }); setFlash({ text, bad });
setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), 4000); // Errors stay longer: they're longer, and they matter more.
setTimeout(() => setFlash((value) => (value?.text === text ? null : value)), bad ? 8000 : 4000);
}; };
// Taking the mouse costs the terminal's own drag-to-select, so a drag selects here and copies on release. // Taking the mouse costs the terminal's own drag-to-select, so a drag selects here and copies on release.
const copySelection = useEvent((selection: Selection) => { const copySelection = useEvent((selection: Selection) => {
@@ -511,6 +512,37 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setMode("nav"); setMode("nav");
}; };
/**
* A message that didn't go comes back to its composer, as the web's does: its text, its
* attachments and its mentions, unless something new was typed there meanwhile.
*/
const restoreMessage = (key: string, text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[]) => {
const composer = composerRef.current;
if (key === activeComposerKey.current && composer) {
if (composer.plainText.trim()) return;
composer.setText(text);
composer.gotoBufferEnd();
setComposerLines(composerLineCount(composer));
setComposerEmpty(text === "");
} else {
if (drafts.current.get(key)?.trim()) return;
drafts.current.set(key, text);
}
composerMenu.remember(key, context);
attach.restore(key, attachments);
};
/** Sends; on failure says why and puts the message back. */
const send = (label: string, text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[], action: () => Promise<unknown>) => {
const key = composerKey;
action().then(
() => say(label),
(error) => {
say(`Not sent: ${messageOf(error)}`, true);
restoreMessage(key, text, context, attachments);
},
);
};
const clearComposer = () => { const clearComposer = () => {
composerRef.current?.setText(""); composerRef.current?.setText("");
if (threadId) drafts.current.delete(threadId); if (threadId) drafts.current.delete(threadId);
@@ -531,13 +563,15 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return; return;
} }
const text = raw.trim(); const text = raw.trim();
// As the web's: refused up front while disconnected, and the message stays put.
if (!live && (text || attach.pending.length > 0)) return say("Not connected: message not sent. Reconnecting; try again once it's connected.", true);
const attachedFiles = attach.pending; const attachedFiles = attach.pending;
const context = composerMenu.context(text); const context = composerMenu.context(text);
if (draft) { if (draft) {
if (!text && attachedFiles.length === 0) return; if (!text && attachedFiles.length === 0) return;
const taken = attach.take(); const taken = attach.take();
clearComposer(); clearComposer();
return newThread.launch(text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, context, taken); return newThread.launch(text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, context, taken, () => restoreMessage(DRAFT_KEY, text, context, taken));
} }
if (!threadId) return; if (!threadId) return;
if (questions.request) { if (questions.request) {
@@ -554,12 +588,12 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const sendText = text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT; const sendText = text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
if (pendingApproval) { if (pendingApproval) {
// As in the web composer: the message declines the request and redirects the agent. // As in the web composer: the message declines the request and redirects the agent.
if (pendingApproval.supportsFeedback) return run("Declined with feedback", () => session.respond(threadId, pendingApproval.requestId, "decline", text)); if (pendingApproval.supportsFeedback) return send("Declined with feedback", text, context, taken, () => session.respond(threadId, pendingApproval.requestId, "decline", text));
return run("Declined and redirected", () => session.sendMessage(threadId, sendText, "steer", undefined, context, taken)); return send("Declined and redirected", text, context, taken, () => session.sendMessage(threadId, sendText, "steer", undefined, context, taken));
} }
const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior }); const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior });
const pendingModel = models.take(threadId); const pendingModel = models.take(threadId);
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, sendText, dispatchMode, pendingModel, context, taken)); send(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", text, context, taken, () => session.sendMessage(threadId, sendText, dispatchMode, pendingModel, context, taken));
}; };
const loadEarlier = () => { const loadEarlier = () => {
@@ -683,6 +717,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const detailsKey = panel.keys.focus; const detailsKey = panel.keys.focus;
const cancelDraftKey = newThread.keys?.cancel; const cancelDraftKey = newThread.keys?.cancel;
const navKeys = keys( const navKeys = keys(
shell.status.type === "reconnecting" && { keys: ["r"], run: () => session.retryNow(), hint: "reconnect now", command: { id: "reconnect", title: "Reconnect now", keywords: ["retry", "connection", "server"] } },
diff && [scrollDiffDown, { keys: ["k", "↑"], run: () => scrollBy(-1) }, closeDiff], diff && [scrollDiffDown, { keys: ["k", "↑"], run: () => scrollBy(-1) }, closeDiff],
turns.bindings, turns.bindings,
pendingApproval && [ pendingApproval && [
@@ -911,14 +946,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
panel.leave(); panel.leave();
}; };
const status = const status = connectionLabel(shell, now);
shell.status.type === "error"
? `error: ${shell.status.message}`
: shell.status.type === "connecting"
? "connecting…"
: shell.status.type === "reconnecting"
? "reconnecting…"
: (shell.serverUrl ?? "");
const listWidth = attached ? 0 : clampListWidth(listWidthPref ?? Math.min(46, Math.max(28, Math.floor(width * 0.3))), width); const listWidth = attached ? 0 : clampListWidth(listWidthPref ?? Math.min(46, Math.max(28, Math.floor(width * 0.3))), width);
const detailsColumn = panel.show && width - listWidth - DETAILS_WIDTH >= MIN_CONVERSATION_WIDTH; const detailsColumn = panel.show && width - listWidth - DETAILS_WIDTH >= MIN_CONVERSATION_WIDTH;
const detailsInPlace = panel.show && !detailsColumn; const detailsInPlace = panel.show && !detailsColumn;
@@ -983,7 +1011,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<text fg={colors.accent}> <text fg={colors.accent}>
<strong>tui3</strong> <strong>tui3</strong>
</text> </text>
<text fg={shell.status.type === "live" ? colors.faint : colors.warn}>{` ${status}`}</text> <text fg={shell.status.type === "live" ? colors.faint : colors.warn} wrapMode="none" onMouseDown={() => session.retryNow()}>{` ${status}`}</text>
{usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null} {usageInfo.note ? <text fg={colors.warn} wrapMode="none">{` ${usageInfo.note}`}</text> : null}
<box flexGrow={1} /> <box flexGrow={1} />
<Button label="commands" shortcut="ctrl+k" onPress={openPalette} /> <Button label="commands" shortcut="ctrl+k" onPress={openPalette} />
@@ -1208,3 +1236,12 @@ function composerLineCount(composer: TextareaRenderable): number {
function clampListWidth(columns: number, width: number): number { function clampListWidth(columns: number, width: number): number {
return Math.max(20, Math.min(columns, width - MIN_CONVERSATION_WIDTH)); return Math.max(20, Math.min(columns, width - MIN_CONVERSATION_WIDTH));
} }
/** The header's connection note, as the web words it: what failed, and when it tries again. */
function connectionLabel(shell: ShellState, now: number): string {
const status = shell.status;
if (status.type === "live") return shell.serverUrl ?? "";
if (status.type === "connecting") return "connecting…";
const wait = status.retryAt === null ? 0 : Math.max(0, Math.ceil((status.retryAt - now) / 1000));
return `couldn't connect, ${wait > 0 ? `retrying in ${wait}s` : "retrying…"} · ${truncate(firstLine(status.message), 60)}`;
}
+6
View File
@@ -19,6 +19,8 @@ export interface Attachments {
readonly remove: (attachment: ChatAttachment) => void; readonly remove: (attachment: ChatAttachment) => void;
/** Hands the pending attachments to a send and clears them. */ /** Hands the pending attachments to a send and clears them. */
readonly take: () => readonly ChatAttachment[]; readonly take: () => readonly ChatAttachment[];
/** A send failed: its attachments go back to their composer, unless it has new ones. */
readonly restore: (composerKey: string, attachments: readonly ChatAttachment[]) => void;
} }
/** /**
@@ -139,6 +141,10 @@ export function useAttachments(deps: {
if (taken.length > 0) setPending([]); if (taken.length > 0) setPending([]);
return taken; return taken;
}, },
restore: (key, attachments) => {
if (attachments.length === 0) return;
setByComposer((previous) => ((previous.get(key) ?? []).length > 0 ? previous : new Map(previous).set(key, attachments)));
},
}; };
} }
+8 -1
View File
@@ -113,6 +113,13 @@ export function useComposerMenu(deps: {
const context = (text: string): OrchestrationMessageContext | undefined => messageContext(text, mentions.current.get(composerKey) ?? new Map()); const context = (text: string): OrchestrationMessageContext | undefined => messageContext(text, mentions.current.get(composerKey) ?? new Map());
/** The message went: its mentions go with it. */ /** The message went: its mentions go with it. */
const forget = () => mentions.current.delete(composerKey); const forget = () => mentions.current.delete(composerKey);
/** A message that didn't send came back to its composer: so do its mentions. */
const remember = (key: string, restored: OrchestrationMessageContext | undefined) => {
if (!restored) return;
const records = mentions.current.get(key) ?? new Map<string, ComposerContextRecord>();
for (const record of restored.records) records.set(record.contextId, record);
mentions.current.set(key, records);
};
const bindings: Binding[] = menu const bindings: Binding[] = menu
? keys( ? keys(
@@ -128,5 +135,5 @@ export function useComposerMenu(deps: {
) )
: []; : [];
return { menu, selected, sync, pick: (at: number) => menu && choose(menu.items[at]), context, forget, bindings }; return { menu, selected, sync, pick: (at: number) => menu && choose(menu.items[at]), context, forget, remember, bindings };
} }
+6 -3
View File
@@ -79,8 +79,8 @@ export function useDraft(deps: {
setDraft({ ...rest, envMode: draft.existingWorktree ? "local" : draft.envMode === "local" ? "worktree" : "local" }); setDraft({ ...rest, envMode: draft.existingWorktree ? "local" : draft.envMode === "local" ? "worktree" : "local" });
}; };
/** Sends the first message, which creates the thread. */ /** Sends the first message, which creates the thread; `onFailed` gets the message back. */
const launch = (text: string, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []) => { const launch = (text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[], onFailed: () => void) => {
if (!draft || !project) return; if (!draft || !project) return;
const launching = draft; const launching = draft;
const root = project.workspaceRoot; const root = project.workspaceRoot;
@@ -113,7 +113,10 @@ export function useDraft(deps: {
deps.onLaunched(id); deps.onLaunched(id);
say("Thread started"); say("Thread started");
}, },
(error) => say(`Could not start the thread: ${error instanceof Error ? error.message : String(error)}`, true), (error) => {
say(`Could not start the thread: ${error instanceof Error ? error.message : String(error)}`, true);
onFailed();
},
); );
}; };
+13 -3
View File
@@ -39,6 +39,7 @@ import {
} from "../model/pullRequests.ts"; } from "../model/pullRequests.ts";
import type { Confirmation } from "./ConfirmBar.tsx"; import type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts"; import { editInEditor } from "./editor.ts";
import { copyText } from "./terminalOut.ts";
import { firstLine } from "./text.ts"; import { firstLine } from "./text.ts";
import type { PullRequestViewState } from "./PullRequestView.tsx"; import type { PullRequestViewState } from "./PullRequestView.tsx";
@@ -159,10 +160,19 @@ export function usePullRequests(deps: PullRequestDeps) {
const openInBrowser = () => { const openInBrowser = () => {
const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url; const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url;
if (!url) return; if (!url) return;
// Over SSH or without a desktop there may be no browser to open: copy the link instead.
const fallBack = (reason: string) => {
copyText(deps.renderer, url);
deps.say(`Could not open the browser (${reason}); link copied: ${url}`, true);
};
try { try {
Bun.spawn([process.platform === "darwin" ? "open" : "xdg-open", url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" }); const opener = process.platform === "darwin" ? "open" : "xdg-open";
} catch { const child = Bun.spawn([opener, url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
deps.say(`Could not open ${url}`, true); void child.exited.then((code) => {
if (code !== 0) fallBack(`${opener} exited with ${code}`);
});
} catch (error) {
fallBack(messageOf(error));
} }
}; };
+35
View File
@@ -207,6 +207,41 @@ describe("composer", () => {
}); });
}); });
describe("connection", () => {
const reconnecting = () => ({ type: "reconnecting", message: "connect ECONNREFUSED 127.0.0.1:3773", retryAt: Date.now() + 5_000 }) as const;
test("a dropped connection says why and when it retries; r and a click on it retry now", async () => {
const app = await open({ session: fakeSession({ status: reconnecting() }) });
expect(app.frame()).toMatch(/couldn't connect, retrying in \ds · connect ECONNREFUSED/);
expect(app.hints()).toStartWith("r reconnect now · ");
await app.press("r");
expect(app.calls("retryNow")).toHaveLength(1);
const at = app.find("couldn't connect");
await app.click(at.x, at.y);
expect(app.calls("retryNow")).toHaveLength(2);
});
test("while disconnected, enter keeps the message rather than sending it", async () => {
const app = await open({ session: fakeSession({ status: reconnecting() }) });
await app.press("i");
await app.type("hello there");
await app.press("return");
expect(app.calls("sendMessage")).toHaveLength(0);
expect(app.hints()).toStartWith("Not connected: message not sent.");
expect(app.frame()).toContain("hello there");
});
test("a send that fails puts the message back in the composer", async () => {
const app = await open({ session: fakeSession({ failures: { sendMessage: "socket closed" } }) });
await app.press("i");
await app.type("hello there");
await app.press("return");
expect(app.calls("sendMessage")).toHaveLength(1);
expect(app.hints()).toBe("Not sent: socket closed");
expect(app.frame()).toContain("hello there");
});
});
describe("mouse", () => { describe("mouse", () => {
test("the header button opens the palette", async () => { test("the header button opens the palette", async () => {
const app = await open(); const app = await open();
+15 -5
View File
@@ -2,7 +2,7 @@ import { testRender } from "@opentui/react/test-utils";
import { createMockKeys, type KeyInput } from "@opentui/core/testing"; import { createMockKeys, type KeyInput } from "@opentui/core/testing";
import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts"; import type { OrchestrationV2ShellSnapshot, OrchestrationV2ThreadProjection, ThreadId } from "@t3tools/contracts";
import type { T3Session } from "../../src/client/session.ts"; import type { ConnectionStatus, T3Session } from "../../src/client/session.ts";
import { DEFAULT_CONFIG, type Tui3Config } from "../../src/config.ts"; import { DEFAULT_CONFIG, type Tui3Config } from "../../src/config.ts";
import { App } from "../../src/ui/App.tsx"; import { App } from "../../src/ui/App.tsx";
import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts"; import { v2Projection, v2ShellSnapshot, v2ThreadId } from "../../vendor/t3code/packages/client-runtime/src/state/orchestrationV2TestFixtures.ts";
@@ -23,9 +23,18 @@ export interface Call {
/** /**
* A session that serves fixed state and records every other call. Watchers get one live * A session that serves fixed state and records every other call. Watchers get one live
* value straight away; anything not listed resolves to undefined. * value straight away; anything not listed resolves to undefined, or rejects with its
* `failures` message.
*/ */
export function fakeSession(state: { readonly snapshot?: OrchestrationV2ShellSnapshot; readonly projection?: OrchestrationV2ThreadProjection; readonly results?: Record<string, unknown> } = {}) { export function fakeSession(
state: {
readonly snapshot?: OrchestrationV2ShellSnapshot;
readonly projection?: OrchestrationV2ThreadProjection;
readonly status?: ConnectionStatus;
readonly results?: Record<string, unknown>;
readonly failures?: Record<string, string>;
} = {},
) {
const calls: Call[] = []; const calls: Call[] = [];
const snapshot = state.snapshot ?? v2ShellSnapshot; const snapshot = state.snapshot ?? v2ShellSnapshot;
const projection = state.projection ?? v2Projection; const projection = state.projection ?? v2Projection;
@@ -34,7 +43,7 @@ export function fakeSession(state: { readonly snapshot?: OrchestrationV2ShellSna
return () => {}; return () => {};
}; };
const known: Record<string, unknown> = { const known: Record<string, unknown> = {
getShell: () => ({ status: { type: "live" }, snapshot, serverUrl: "ws://test" }), getShell: () => ({ status: state.status ?? { type: "live" }, snapshot, serverUrl: "ws://test" }),
onShell: () => () => {}, onShell: () => () => {},
watchThread: (_id: ThreadId, listener: (value: unknown) => void) => live({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } })(listener), watchThread: (_id: ThreadId, listener: (value: unknown) => void) => live({ status: "live", projection, history: { cursor: null, hasMore: false, loading: false } })(listener),
watchServerConfig: live({ status: "loading", config: null }), watchServerConfig: live({ status: "loading", config: null }),
@@ -51,7 +60,8 @@ export function fakeSession(state: { readonly snapshot?: OrchestrationV2ShellSna
return (...args: unknown[]) => { return (...args: unknown[]) => {
calls.push({ method: name, args }); calls.push({ method: name, args });
if (name.startsWith("watch") || name.startsWith("on")) return () => {}; if (name.startsWith("watch") || name.startsWith("on")) return () => {};
return Promise.resolve(state.results?.[name]); const failure = state.failures?.[name];
return failure ? Promise.reject(new Error(failure)) : Promise.resolve(state.results?.[name]);
}; };
}, },
}) as unknown as T3Session; }) as unknown as T3Session;