From 2c5eedc8690b4d1d113b65cf8ff4959c99ade64a Mon Sep 17 00:00:00 2001 From: Callum Alpass Date: Mon, 2 Nov 2026 23:13:06 +1100 Subject: [PATCH] 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. --- src/bin.ts | 22 ++++++++----- src/client/session.ts | 27 ++++++++++++---- src/ui/App.tsx | 67 ++++++++++++++++++++++++++++++--------- src/ui/useAttachments.ts | 6 ++++ src/ui/useComposerMenu.ts | 9 +++++- src/ui/useDraft.ts | 9 ++++-- src/ui/usePullRequests.ts | 16 ++++++++-- test/app/app.test.tsx | 35 ++++++++++++++++++++ test/app/harness.tsx | 20 +++++++++--- 9 files changed, 169 insertions(+), 42 deletions(-) diff --git a/src/bin.ts b/src/bin.ts index 2bf8426..be9ef15 100755 --- a/src/bin.ts +++ b/src/bin.ts @@ -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((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}".`); diff --git a/src/client/session.ts b/src/client/session.ts index 116301e..e68d4ac 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -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 { const scope = this.scope; this.scope = null; diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 087bebf..bb52e45 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -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) => { + 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 tui3 - {` ${status}`} + session.retryNow()}>{` ${status}`} {usageInfo.note ? {` ${usageInfo.note}`} : null}