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 }> {
const session = new T3Session();
await session.start();
const snapshot = await new Promise<OrchestrationV2ShellSnapshot>((resolve, reject) => {
const off = session.onShell((shell) => {
if (shell.status.type === "error") {
if (shell.status.type === "reconnecting") {
queueMicrotask(() => off());
void session.stop();
reject(new Error(shell.status.message));
} else if (shell.status.type === "live" && shell.snapshot) {
queueMicrotask(() => off());
@@ -109,18 +111,22 @@ async function tmuxCommand(args: string[]) {
}
}
};
session.onShell((shell) => {
if (shell.status.type === "error") fail(shell.status.message);
void sync();
});
// A dropped connection retries by itself; sync runs again once the shell is back.
session.onShell(() => void sync());
await new Promise(() => {});
}
async function runUi(attachNeedle?: string) {
const { session, snapshot } = await connectedSession();
let session: T3Session;
let attachThreadId: ThreadId | undefined;
if (attachNeedle) {
const thread = findThread(snapshot, attachNeedle);
if (!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) {
await session.stop();
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 { 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 =
| { readonly type: "connecting" }
| { readonly type: "live" }
| { readonly type: "reconnecting"; readonly message: string }
| { readonly type: "error"; readonly message: string };
/** `retryAt`: when the next attempt starts (epoch ms); null while one is under way. */
| { readonly type: "reconnecting"; readonly message: string; readonly retryAt: number | null };
export interface ShellState {
readonly status: ConnectionStatus;
@@ -207,9 +208,7 @@ export class T3Session {
} catch (error) {
this.scope = null;
await Effect.runPromise(Scope.close(scope, Exit.void));
if (this.reconnectAttempt > 0) return this.scheduleReconnect(messageOf(error));
this.setShell({ status: { type: "error", message: messageOf(error) } });
return;
return this.scheduleReconnect(messageOf(error));
}
this.recovering = false;
this.setShell({ serverUrl: this.connection.target.httpBaseUrl });
@@ -224,6 +223,14 @@ export class T3Session {
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 {
return this.shell;
}
@@ -1109,13 +1116,19 @@ export class T3Session {
if (this.stopped || this.reconnectTimer) return;
const delay = RECONNECT_DELAYS_MS[Math.min(this.reconnectAttempt, RECONNECT_DELAYS_MS.length - 1)]!;
this.reconnectAttempt++;
this.setShell({ status: { type: "reconnecting", message } });
this.setShell({ status: { type: "reconnecting", message, retryAt: Date.now() + delay } });
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.start();
this.attempt();
}, 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> {
const scope = this.scope;
this.scope = null;
+52 -15
View File
@@ -6,7 +6,7 @@ import type { OrchestrationV2ThreadShell, ProviderApprovalDecision, ThreadId } f
import { homedir } from "node:os";
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 { createAlerts, type Alert } from "../model/alerts.ts";
import { modelSummary } from "../model/models.ts";
@@ -304,7 +304,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}, [shell.snapshot, familyShells]);
const say = (text: string, bad = false) => {
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.
const copySelection = useEvent((selection: Selection) => {
@@ -511,6 +512,37 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
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 = () => {
composerRef.current?.setText("");
if (threadId) drafts.current.delete(threadId);
@@ -531,13 +563,15 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return;
}
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 context = composerMenu.context(text);
if (draft) {
if (!text && attachedFiles.length === 0) return;
const taken = attach.take();
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 (questions.request) {
@@ -554,12 +588,12 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const sendText = text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT;
if (pendingApproval) {
// 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));
return run("Declined and redirected", () => session.sendMessage(threadId, sendText, "steer", undefined, context, taken));
if (pendingApproval.supportsFeedback) return send("Declined with feedback", text, context, taken, () => session.respond(threadId, pendingApproval.requestId, "decline", text));
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 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 = () => {
@@ -683,6 +717,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const detailsKey = panel.keys.focus;
const cancelDraftKey = newThread.keys?.cancel;
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],
turns.bindings,
pendingApproval && [
@@ -911,14 +946,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
panel.leave();
};
const status =
shell.status.type === "error"
? `error: ${shell.status.message}`
: shell.status.type === "connecting"
? "connecting…"
: shell.status.type === "reconnecting"
? "reconnecting…"
: (shell.serverUrl ?? "");
const status = connectionLabel(shell, now);
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 detailsInPlace = panel.show && !detailsColumn;
@@ -983,7 +1011,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
<text fg={colors.accent}>
<strong>tui3</strong>
</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}
<box flexGrow={1} />
<Button label="commands" shortcut="ctrl+k" onPress={openPalette} />
@@ -1208,3 +1236,12 @@ function composerLineCount(composer: TextareaRenderable): number {
function clampListWidth(columns: number, width: number): number {
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;
/** Hands the pending attachments to a send and clears them. */
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([]);
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());
/** The message went: its mentions go with it. */
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
? 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" });
};
/** Sends the first message, which creates the thread. */
const launch = (text: string, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []) => {
/** Sends the first message, which creates the thread; `onFailed` gets the message back. */
const launch = (text: string, context: OrchestrationMessageContext | undefined, attachments: readonly ChatAttachment[], onFailed: () => void) => {
if (!draft || !project) return;
const launching = draft;
const root = project.workspaceRoot;
@@ -113,7 +113,10 @@ export function useDraft(deps: {
deps.onLaunched(id);
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";
import type { Confirmation } from "./ConfirmBar.tsx";
import { editInEditor } from "./editor.ts";
import { copyText } from "./terminalOut.ts";
import { firstLine } from "./text.ts";
import type { PullRequestViewState } from "./PullRequestView.tsx";
@@ -159,10 +160,19 @@ export function usePullRequests(deps: PullRequestDeps) {
const openInBrowser = () => {
const url = loadedRef.current?.detail?.url ?? loadedRef.current?.link.url;
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 {
Bun.spawn([process.platform === "darwin" ? "open" : "xdg-open", url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
} catch {
deps.say(`Could not open ${url}`, true);
const opener = process.platform === "darwin" ? "open" : "xdg-open";
const child = Bun.spawn([opener, url], { stdin: "ignore", stdout: "ignore", stderr: "ignore" });
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", () => {
test("the header button opens the palette", async () => {
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 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 { App } from "../../src/ui/App.tsx";
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
* 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 snapshot = state.snapshot ?? v2ShellSnapshot;
const projection = state.projection ?? v2Projection;
@@ -34,7 +43,7 @@ export function fakeSession(state: { readonly snapshot?: OrchestrationV2ShellSna
return () => {};
};
const known: Record<string, unknown> = {
getShell: () => ({ status: { type: "live" }, snapshot, serverUrl: "ws://test" }),
getShell: () => ({ status: state.status ?? { type: "live" }, snapshot, serverUrl: "ws://test" }),
onShell: () => () => {},
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 }),
@@ -51,7 +60,8 @@ export function fakeSession(state: { readonly snapshot?: OrchestrationV2ShellSna
return (...args: unknown[]) => {
calls.push({ method: name, args });
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;