New threads, model and mode picker, alerts, $EDITOR and terminal attach

- c starts a draft thread (project, model, mode, worktree) launched with orchestration.launchThread
- m picks model, provider options and access mode from the server's providers, following the web's provider lock; model changes ride on the next message
- Alerts port T3's notification gate: bell, OSC 9/99 desktop notifications when unfocused, in-app flash
- ctrl+g edits the message in $EDITOR; ctrl+j attaches to the thread's T3 terminal
- Credential gains terminal:read
This commit is contained in:
Callum Alpass committed 2026-11-02 18:55:47 +11:00
1 parent 121bbd9137
commit 626d37a4e9
18 files changed
+1074 -49

No files matched your search

+2 -2
View File
@@ -4,9 +4,9 @@ import { dirname, join } from "node:path";
/**
* Scopes tui3 asks for: read and operate threads, read diffs, run git actions
* (commit, push, open a PR), and stop a thread's local servers.
* (commit, push, open a PR), stop a thread's local servers, and use its terminals.
*/
export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:operate"] as const;
export const TUI3_SCOPES = ["orchestration:read", "orchestration:operate", "filesystem:read", "source-control:write", "terminal:read", "terminal:operate"] as const;
export interface ServerTarget {
/** e.g. http://127.0.0.1:3773 */
+84 -1
View File
@@ -20,6 +20,12 @@ import {
type ScheduledTask,
type ScheduledTaskId,
type ServerConfig,
type ModelSelection,
type RuntimeMode,
type TerminalAttachStreamEvent,
type TerminalSummary,
type VcsRef,
type OrchestrationV2ThreadLaunchInput,
type OrchestrationV2ThreadShell,
type VcsStatusLocalResult,
type VcsStatusRemoteResult,
@@ -366,7 +372,8 @@ export class T3Session {
* Sends a message the way the web composer does: "auto" when idle, otherwise
* "steer" (into the active run) or "queue" (after it). See resolveComposerDispatchMode.
*/
sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto"): Promise<void> {
/** `modelSelection` switches the thread's model (and options) with this message, as the web composer does. */
sendMessage(threadId: ThreadId, text: string, mode: ComposerDispatchMode = "auto", modelSelection?: ModelSelection): Promise<void> {
const commandId = newCommandId();
return this.dispatch({
type: "message.dispatch",
@@ -375,6 +382,7 @@ export class T3Session {
messageId: MessageId.make(commandId),
text,
attachments: [],
...(modelSelection ? { modelSelection } : {}),
...(mode === "queue" ? { dispatchMode: { type: "queue_after_active" } } : { dispatchMode: { type: "start_immediately" }, deliveryIntent: mode }),
createdBy: "user",
creationSource: "web",
@@ -405,6 +413,81 @@ export class T3Session {
return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId });
}
setRuntimeMode(threadId: ThreadId, runtimeMode: RuntimeMode): Promise<void> {
return this.dispatch({ type: "thread.runtime-mode.set", commandId: newCommandId(), threadId, runtimeMode });
}
/**
* Creates a thread and sends its first message in one call, as the web app does when a
* draft is first sent. Resolves with the new thread's id.
*/
async launchThread(input: Omit<OrchestrationV2ThreadLaunchInput, "commandId" | "initialMessage"> & { readonly text: string }): Promise<ThreadId> {
const { text, ...rest } = input;
const commandId = newCommandId();
const result = await Effect.runPromise(
this.requireConnection().rpc[ORCHESTRATION_V2_WS_METHODS.launchThread]({ ...rest, commandId, initialMessage: { messageId: MessageId.make(commandId), text, attachments: [] } }),
);
return result.threadId;
}
/** Whether `cwd` is a repository, and its default branch (else the current one), for a new worktree's base. */
async defaultRef(cwd: string): Promise<{ readonly isRepo: boolean; readonly ref: VcsRef | null }> {
const result = await Effect.runPromise(this.requireConnection().rpc[WS_METHODS.vcsListRefs]({ cwd, refKind: "local" }));
return { isRepo: result.isRepo, ref: result.refs.find((ref) => ref.isDefault) ?? result.refs.find((ref) => ref.current) ?? null };
}
/** Every open terminal on the server; filter by thread. */
watchTerminals(listener: Listener<FeedState<TerminalSummary>>): () => void {
return this.watchFeed<FeedState<TerminalSummary>>("terminals", { status: "loading", items: [] }, listener, (update) =>
this.requireConnection()
.rpc[WS_METHODS.subscribeTerminalMetadata]({})
.pipe(
Stream.runForEach((event) =>
Effect.sync(() => {
const items = (this.feeds.get("terminals")?.state as FeedState<TerminalSummary> | undefined)?.items ?? [];
const same = (a: { threadId: string; terminalId: string }, b: { threadId: string; terminalId: string }) => a.threadId === b.threadId && a.terminalId === b.terminalId;
switch (event.type) {
case "snapshot":
return update({ status: "live", items: event.terminals });
case "upsert":
return update({ status: "live", items: [...items.filter((item) => !same(item, event.terminal)), event.terminal] });
case "remove":
return update({ items: items.filter((item) => !same(item, event)) });
}
}),
),
),
);
}
/**
* Attaches to a terminal (opening it in `cwd` if it isn't running) and streams its events.
* Returns a function that detaches; the terminal keeps running.
*/
attachTerminal(
input: { readonly threadId: ThreadId; readonly terminalId: string; readonly cwd: string; readonly worktreePath: string | null; readonly cols: number; readonly rows: number },
onEvent: Listener<TerminalAttachStreamEvent>,
onEnd: (error?: string) => void,
): () => void {
const fiber = Effect.runFork(
this.requireConnection()
.rpc[WS_METHODS.terminalAttach]({ ...input, restartIfNotRunning: true })
.pipe(
Stream.runForEach((event) => Effect.sync(() => onEvent(event))),
Effect.match({ onFailure: (error) => onEnd(messageOf(error)), onSuccess: () => onEnd() }),
),
);
return () => void Effect.runFork(Fiber.interrupt(fiber));
}
writeTerminal(threadId: ThreadId, terminalId: string, data: string): Promise<void> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.terminalWrite]({ threadId, terminalId, data }));
}
resizeTerminal(threadId: ThreadId, terminalId: string, cols: number, rows: number): Promise<void> {
return Effect.runPromise(this.requireConnection().rpc[WS_METHODS.terminalResize]({ threadId, terminalId, cols, rows }));
}
private async dispatch(command: OrchestrationV2Command): Promise<void> {
const rpc = this.requireConnection().rpc;
await Effect.runPromise(rpc[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](command));
+7 -1
View File
@@ -14,9 +14,13 @@ export interface Tui3Config {
readonly sendShortcut: "enter" | "ctrl-enter";
readonly timestampFormat: "locale" | "12-hour" | "24-hour";
readonly diffIgnoreWhitespace: boolean;
/** As the web's notificationMode: sound is the terminal bell, notifications go through the terminal. */
readonly notificationMode: "off" | "notifications" | "sound" | "notifications-and-sound";
/** As the web's in-app toasts: a line at the bottom for threads you aren't looking at. */
readonly inAppNotificationsEnabled: boolean;
}
export const DEFAULT_CONFIG: Tui3Config = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true };
export const DEFAULT_CONFIG: Tui3Config = { followUpBehavior: "steer", sendShortcut: "enter", timestampFormat: "locale", diffIgnoreWhitespace: true, notificationMode: "sound", inAppNotificationsEnabled: true };
/** Every setting with its choices in cycling order, for the settings view. */
export const CONFIG_CHOICES: { readonly [K in keyof Tui3Config]: readonly Tui3Config[K][] } = {
@@ -24,6 +28,8 @@ export const CONFIG_CHOICES: { readonly [K in keyof Tui3Config]: readonly Tui3Co
sendShortcut: ["enter", "ctrl-enter"],
timestampFormat: ["locale", "12-hour", "24-hour"],
diffIgnoreWhitespace: [true, false],
notificationMode: ["off", "sound", "notifications", "notifications-and-sound"],
inAppNotificationsEnabled: [true, false],
};
export const configPath = () => join(configDir(), "config.json");
+86
View File
@@ -0,0 +1,86 @@
import { presentThreadShell } from "@t3tools/client-runtime/state/models";
import type { EnvironmentId, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ThreadId } from "@t3tools/contracts";
import { createThreadNotificationGate, type ThreadNotificationKind, type ThreadNotificationObservation } from "../../vendor/t3code/apps/web/src/components/ThreadNotificationCoordinator.logic.ts";
import { resolveStatus, type ThreadStatus } from "./threads.ts";
export type { ThreadNotificationKind };
export interface Alert {
readonly thread: OrchestrationV2ThreadShell;
readonly kind: ThreadNotificationKind;
readonly status: ThreadStatus;
/** As the web's notification titles. */
readonly title: string;
}
interface Observed extends ThreadNotificationObservation {
readonly raw: OrchestrationV2ThreadShell;
readonly status: ThreadStatus;
}
const LOCAL_ENVIRONMENT = "local" as EnvironmentId;
/**
* The web's ThreadNotificationCoordinator over the shell snapshot: attention (approval,
* question, guest request, failure, usage limit) alerts once per run and status;
* completion alerts after the Working shelf's grace, unless the run was stopped. Nothing
* alerts for state that was already there when tui3 connected.
*/
export function createAlerts(onAlert: (alert: Alert) => void) {
let previous = new Map<ThreadId, Observed>();
const gate = createThreadNotificationGate<ThreadId>((threadId, kind) => {
const state = previous.get(threadId);
if (state) onAlert({ thread: state.raw, kind, status: state.status, title: alertTitle(kind, state.status) });
});
return {
observe(snapshot: OrchestrationV2ShellSnapshot): void {
const next = new Map<ThreadId, Observed>();
const changed: [Observed | undefined, Observed][] = [];
for (const raw of snapshot.threads) {
// Subagents show under their parent, whose status covers them.
if (raw.lineage.relationshipToParent === "subagent") continue;
const prior = previous.get(raw.id);
if (prior?.raw === raw) {
next.set(raw.id, prior);
continue;
}
const shell = presentThreadShell(LOCAL_ENVIRONMENT, raw);
let status = resolveStatus(shell);
if (status === "ready" && shell.latestRun?.status === "failed") status = "failed";
const attention = status === "input" || status === "request" || status === "approval" || status === "failed" || status === "limited" ? `${shell.latestRun?.runId ?? ""}:${status}` : null;
const completedAt = Date.parse(shell.latestRun?.completedAt ?? "");
const settled = status === "ready" && shell.latestRun?.status === "completed";
const state: Observed = { raw, status, attention, settled, completedAt: settled && Number.isFinite(completedAt) ? completedAt : null };
next.set(raw.id, state);
changed.push([prior, state]);
}
previous = next;
gate.retain(new Set(next.keys()));
for (const [prior, state] of changed) {
gate.observe(state.raw.id, prior, state, { archived: state.raw.archivedAt !== null, quiet: state.raw.latestRunStopRequested === true });
}
},
/** The shell went away: the next snapshot counts as a first sighting again. */
clear(): void {
gate.clear();
previous = new Map();
},
};
}
export function alertTitle(kind: ThreadNotificationKind, status: ThreadStatus): string {
if (kind === "completion") return "Thread completed";
switch (status) {
case "approval":
return "Approval needed";
case "limited":
return "Usage limit reached";
case "failed":
return "Thread failed";
case "request":
return "Guest request";
default:
return "Input needed";
}
}
+129
View File
@@ -0,0 +1,129 @@
import { deriveThreadStructureRuntime } from "@t3tools/client-runtime/state/thread-execution";
import { threadSupportsProviderHandoff } from "@t3tools/client-runtime/state/thread-workflows";
import { resolveProviderInstanceDisplayName } from "@t3tools/client-runtime/state/provider-instance-display";
import {
isProviderAvailable,
type ModelSelection,
type OrchestrationProjectShell,
type OrchestrationV2ThreadProjection,
type ProviderInstanceId,
type ProviderOptionDescriptor,
type ProviderOptionSelectionValue,
type RuntimeMode,
type ServerConfig,
type ServerProvider,
type ServerProviderModel,
type ThreadEnvMode,
} from "@t3tools/contracts";
import { resolveNewThreadEnvMode, resolveProjectSettings } from "@t3tools/shared/projectSettings";
/** Providers you can pick, as the web's picker: enabled and not unavailable. */
export function selectableProviders(config: ServerConfig | null): ServerProvider[] {
return (config?.providers ?? []).filter((provider) => provider.enabled && isProviderAvailable(provider));
}
export function providerName(provider: Pick<ServerProvider, "instanceId" | "driver" | "displayName">): string {
return resolveProviderInstanceDisplayName(provider);
}
/** As the web's default model for an instance: its default, else the first built-in model. */
export function defaultModel(provider: ServerProvider): ServerProviderModel | undefined {
return provider.models.find((model) => model.isDefault && !model.isCustom) ?? provider.models.find((model) => !model.isCustom) ?? provider.models[0];
}
export function findModel(config: ServerConfig | null, selection: ModelSelection): { provider: ServerProvider; model: ServerProviderModel | undefined } | null {
const provider = config?.providers.find((candidate) => candidate.instanceId === selection.instanceId);
if (!provider) return null;
return { provider, model: provider.models.find((model) => model.slug === selection.model || model.aliases?.includes(selection.model)) };
}
/** The model's adjustable options (thinking level, speed, …), as the server describes them. */
export function optionDescriptors(config: ServerConfig | null, selection: ModelSelection): readonly ProviderOptionDescriptor[] {
return findModel(config, selection)?.model?.capabilities?.optionDescriptors ?? [];
}
/** The option's value in this selection, else the descriptor's current or default value. */
export function optionValue(selection: ModelSelection, descriptor: ProviderOptionDescriptor): ProviderOptionSelectionValue | undefined {
const chosen = selection.options?.find((option) => option.id === descriptor.id)?.value;
if (chosen !== undefined) return chosen;
if (descriptor.type === "boolean") return descriptor.currentValue;
return descriptor.currentValue ?? descriptor.options.find((choice) => choice.isDefault)?.id;
}
export function optionValueLabel(descriptor: ProviderOptionDescriptor, value: ProviderOptionSelectionValue | undefined): string {
if (descriptor.type === "boolean") return value === true ? "on" : "off";
return descriptor.options.find((choice) => choice.id === value)?.label ?? String(value ?? "default");
}
export function withOption(selection: ModelSelection, id: string, value: ProviderOptionSelectionValue): ModelSelection {
return { ...selection, options: [...(selection.options ?? []).filter((option) => option.id !== id), { id, value }] };
}
/** A switch to another model keeps the options the new model also has. */
export function withModel(config: ServerConfig | null, current: ModelSelection, instanceId: ProviderInstanceId, model: string): ModelSelection {
const next: ModelSelection = { instanceId, model };
const descriptors = optionDescriptors(config, next);
const kept = (current.options ?? []).filter((option) => descriptors.some((descriptor) => descriptor.id === option.id));
return kept.length > 0 ? { ...next, options: kept } : next;
}
/** "Opus 4.7 · High · Fast": the model, then each option that differs from off. */
export function modelSummary(config: ServerConfig | null, selection: ModelSelection): string {
const found = findModel(config, selection);
const name = found?.model?.shortName ?? found?.model?.name ?? selection.model;
const options = optionDescriptors(config, selection).flatMap((descriptor) => {
const value = optionValue(selection, descriptor);
if (descriptor.type === "boolean") return value === true ? [descriptor.label] : [];
return value === undefined ? [] : [optionValueLabel(descriptor, value)];
});
return [name, ...options].join(" · ");
}
/**
* Which providers a started thread may move to, as the web's
* getStartedThreadModelChangeBlockReason: any, before a session starts or when the
* provider supports handoff; otherwise only the one it runs on.
*/
export function lockedProviderInstance(projection: OrchestrationV2ThreadProjection | null | undefined): ProviderInstanceId | null {
if (!projection) return null;
const runtime = deriveThreadStructureRuntime(projection);
if (runtime === null || threadSupportsProviderHandoff(projection)) return null;
return runtime.providerInstanceId;
}
export const RUNTIME_MODES: readonly RuntimeMode[] = ["approval-required", "auto-accept-edits", "auto", "full-access"];
export interface DraftThread {
readonly projectId: OrchestrationProjectShell["id"];
readonly modelSelection: ModelSelection;
readonly runtimeMode: RuntimeMode;
readonly envMode: ThreadEnvMode;
}
/**
* A new thread's defaults, as the web's new-thread handler: the project's or machine's
* default model, else the current thread's, else the first selectable provider's default;
* the default mode; and local or worktree from the project settings.
*/
export function draftDefaults(input: {
readonly config: ServerConfig | null;
readonly project: OrchestrationProjectShell;
readonly currentModel: ModelSelection | null;
readonly projectHasThreads: boolean;
}): DraftThread {
const settings = input.config ? resolveProjectSettings(input.config.settings, input.project.id, input.project, null) : null;
const firstProvider = selectableProviders(input.config)[0];
const firstModel = firstProvider ? defaultModel(firstProvider) : undefined;
const modelSelection: ModelSelection = settings?.settings.defaultModelSelection ??
input.currentModel ?? { instanceId: (firstProvider?.instanceId ?? "codex") as ProviderInstanceId, model: firstModel?.slug ?? "default" };
const envMode = settings
? resolveNewThreadEnvMode({ projectSettings: settings, workspaceRoot: input.project.workspaceRoot, newProjectsRoot: null, projectHasThreads: input.projectHasThreads })
: "local";
return { projectId: input.project.id, modelSelection, runtimeMode: settings?.settings.defaultRuntimeMode ?? "full-access", envMode };
}
/** Same model with the same effective options, counting defaults as chosen. */
export function sameSelection(config: ServerConfig | null, a: ModelSelection, b: ModelSelection): boolean {
if (a.instanceId !== b.instanceId || a.model !== b.model) return false;
return optionDescriptors(config, a).every((descriptor) => optionValue(a, descriptor) === optionValue(b, descriptor));
}
+31
View File
@@ -88,3 +88,34 @@ export function paletteGroups(input: {
export function paletteEntries(groups: readonly PaletteGroup[]): PaletteEntry[] {
return groups.flatMap((group) => group.entries);
}
/** A choice in a picker (model, option, project, terminal…). */
export interface PickerItem {
readonly id: string;
readonly title: string;
/** Shown on the right: "current", a provider, a status. */
readonly hint?: string;
readonly run: () => void;
}
export interface Picker {
readonly placeholder: string;
readonly groups: readonly { readonly label: string; readonly items: readonly PickerItem[] }[];
}
/** A picker's groups filtered and ranked by the query, in the palette's shape. */
export function pickerGroups(picker: Picker, query: string): PaletteGroup[] {
const folded = foldSearchQuery(query);
return picker.groups
.map((group) => {
const items = folded
? group.items
.map((item) => ({ item, match: scoreSearchTerms(folded, [item.title, group.label, item.hint ?? ""], { typos: true }) }))
.filter((candidate) => candidate.match !== null)
.sort((a, b) => b.match!.score - a.match!.score)
.map(({ item }) => item)
: group.items;
return { label: group.label, entries: items.map((item): PaletteEntry => ({ kind: "command", command: { id: item.id, title: item.title, ...(item.hint ? { shortcut: item.hint } : {}) } })) };
})
.filter((group) => group.entries.length > 0);
}
+6
View File
@@ -15,6 +15,12 @@ const LABELS: { readonly [K in keyof Tui3Config]: { readonly label: string; read
sendShortcut: { label: "Send with", help: "ctrl+enter needs kitty keyboard support; alt+enter also sends", values: { enter: "enter", "ctrl-enter": "ctrl+enter (enter adds a line)" } },
timestampFormat: { label: "Times", help: "automation schedules", values: { locale: "system locale", "12-hour": "12-hour", "24-hour": "24-hour" } },
diffIgnoreWhitespace: { label: "Diffs", help: "whitespace-only changes", values: { true: "ignore whitespace", false: "show whitespace" } },
notificationMode: {
label: "Alerts",
help: "when a thread needs you or finishes; notifications only while the terminal is unfocused",
values: { off: "off", sound: "bell", notifications: "desktop notifications", "notifications-and-sound": "bell and desktop notifications" },
},
inAppNotificationsEnabled: { label: "In-app alerts", help: "a line at the bottom for other threads", values: { true: "on", false: "off" } },
};
/** tui3's own settings, in display order, each cycled with enter. */
+382 -37
View File
@@ -8,23 +8,30 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "@t3tools/client-runtime/state/pending-user-input";
import type { DiscoveredLocalServer, OrchestrationV2ThreadShell, ProviderApprovalDecision, ScheduledTask, ThreadId } from "@t3tools/contracts";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { DEFAULT_TERMINAL_ID, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type TerminalSummary, type ThreadId } from "@t3tools/contracts";
import { homedir } from "node:os";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { FeedState, ServerConfigState, ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts";
import { draftDefaults, lockedProviderInstance, modelSummary, optionDescriptors, optionValue, optionValueLabel, providerName, RUNTIME_MODES, sameSelection, selectableProviders, withModel, withOption, type DraftThread } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts";
import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts";
import { paletteEntries, paletteGroups, type PaletteCommand } from "../model/palette.ts";
import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type Picker, type PickerItem } from "../model/palette.ts";
import { serverSettingLines, settingRows } from "../model/settings.ts";
import { buildTimeline, type Timeline } from "../model/timeline.ts";
import { threadRows, type Section } from "../model/threads.ts";
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
import { DetailsPanel } from "./DetailsPanel.tsx";
import { DiffView, type DiffState } from "./DiffView.tsx";
import { DraftView, type DraftLine } from "./DraftView.tsx";
import { editInEditor } from "./editor.ts";
import { Palette } from "./Palette.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx";
import { SettingsView } from "./SettingsView.tsx";
import { attachTerminal } from "./terminalAttach.ts";
import { desktopNotify, ring } from "./terminalOut.ts";
import { colors } from "./theme.ts";
import { ThreadList } from "./ThreadList.tsx";
import { ThreadView } from "./ThreadView.tsx";
@@ -34,7 +41,7 @@ import { ThreadView } from "./ThreadView.tsx";
* "details": j/k move through the details panel. "settings": j/k move through settings.
* The rest are overlays with their own input.
*/
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "confirm" | "settings";
type Mode = "input" | "nav" | "filter" | "details" | "palette" | "picker" | "confirm" | "settings";
/** Holding j/k skims past threads; only subscribe to one you stop on. */
const SUBSCRIBE_DELAY_MS = 120;
@@ -53,15 +60,15 @@ const COMPOSER_KEYS = {
enter: [
{ name: "return", action: "submit" },
{ name: "return", shift: true, action: "newline" },
{ name: "j", ctrl: true, action: "newline" },
],
"ctrl-enter": [
{ name: "return", action: "newline" },
{ name: "return", ctrl: true, action: "submit" },
{ name: "return", shift: true, action: "newline" },
{ name: "j", ctrl: true, action: "newline" },
],
} as const;
/** The composer's key while a new thread is being drafted. */
const DRAFT_KEY = "draft";
interface QuestionDraft {
readonly index: number;
@@ -87,6 +94,14 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const [config, setConfig] = useState(props.config);
const [settingsIndex, setSettingsIndex] = useState<number | null>(null);
const [serverConfig, setServerConfig] = useState<ServerConfigState | null>(null);
/** A new thread before its first message; the composer sends it. */
const [draft, setDraft] = useState<DraftThread | null>(null);
const [picker, setPicker] = useState<Picker | null>(null);
const [pickerQuery, setPickerQuery] = useState("");
const [pickerIndex, setPickerIndex] = useState(0);
/** Model changes waiting for each thread's next message, as the web composer holds them. */
const [pendingModels, setPendingModels] = useState<ReadonlyMap<ThreadId, ModelSelection>>(new Map());
const [terminals, setTerminals] = useState<FeedState<TerminalSummary> | null>(null);
/** Idle subagents the shell leaves out, fetched when you open one. */
const [familyShells, setFamilyShells] = useState<ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>>(new Map());
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
@@ -105,6 +120,25 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const returnMode = useRef<Mode>("nav");
useEffect(() => session.onShell(setShell), [session]);
// Alerts, from the shell as the web's notification coordinator computes them.
const onAlert = useRef<(alert: Alert) => void>(() => {});
const alerts = useMemo(() => createAlerts((alert) => onAlert.current(alert)), []);
useEffect(() => {
if (shell.status.type === "live" && shell.snapshot) alerts.observe(shell.snapshot);
else alerts.clear();
}, [alerts, shell.status.type, shell.snapshot]);
// Desktop notifications only while the terminal is in the background, as the web's need an unfocused window.
const terminalFocused = useRef(true);
useEffect(() => {
const onFocus = () => (terminalFocused.current = true);
const onBlur = () => (terminalFocused.current = false);
renderer.on("focus", onFocus);
renderer.on("blur", onBlur);
return () => {
renderer.off("focus", onFocus);
renderer.off("blur", onBlur);
};
}, [renderer]);
// Drives "Working for 12s" and the sidebar's durations.
useEffect(() => {
const timer = setInterval(() => setNow(Date.now()), 1_000);
@@ -132,6 +166,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setSelectedId(id);
setDiff(null);
setSettingsIndex(null);
setDraft(null);
setDetailsSelected(null);
setMode((current) => (current === "details" || current === "settings" ? "nav" : current));
}, []);
@@ -201,6 +236,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const vcsCwd = threadShell ? detailsCwd(threadShell, project) : null;
const live = shell.status.type === "live";
useEffect(() => (live ? session.watchServerConfig(setServerConfig) : undefined), [session, live]);
useEffect(() => (live ? session.watchTerminals(setTerminals) : undefined), [session, live]);
// An idle subagent isn't in the shell; its family (root, forks, all subagents) is, on servers that serve it.
const supportsFamilies = serverConfig?.config?.shellThreadFamilies === true;
const unlisted = threadId !== undefined && !threadShell;
@@ -275,6 +311,17 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
(error) => say(`${label} failed: ${messageOf(error)}`, true),
);
};
onAlert.current = (alert) => {
const mode = config.notificationMode;
if (mode === "sound" || mode === "notifications-and-sound") ring();
const viewing = alert.thread.id === threadId;
if (terminalFocused.current) {
if (config.inAppNotificationsEnabled && !viewing) say(`${alert.title}: ${alert.thread.title}`, alert.status === "failed" || alert.status === "limited");
} else if (mode === "notifications" || mode === "notifications-and-sound") {
desktopNotify(alert.title, alert.thread.title);
}
};
const respond = (decision: ProviderApprovalDecision) => {
if (!threadId || !pendingApproval) return say("Nothing is waiting for approval.", true);
run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingApproval.requestId, decision));
@@ -374,6 +421,225 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setMode("details");
};
// Pickers: the palette's overlay over a fixed list.
const openPicker = (next: Picker) => {
if (mode !== "picker" && mode !== "palette" && mode !== "confirm") returnMode.current = mode === "filter" || mode === "details" ? "nav" : mode;
setPicker(next);
setPickerQuery("");
setPickerIndex(0);
setMode("picker");
};
const pickerView = useMemo(() => (picker ? pickerGroups(picker, pickerQuery) : []), [picker, pickerQuery]);
const pickerItems = useMemo(() => (picker ? picker.groups.flatMap((group) => group.items) : []), [picker]);
const pickerEntries = paletteEntries(pickerView);
const pickItem = (index: number) => {
const entry = pickerEntries[index];
if (entry?.kind !== "command") return;
const item = pickerItems.find((candidate) => candidate.id === entry.command.id);
setPicker(null);
setMode(returnMode.current);
item?.run();
};
// Model, options and mode: for the draft, or for the open thread (sent with its next message).
const providerConfig = serverConfig?.config ?? null;
const currentModel: ModelSelection | null = draft ? draft.modelSelection : threadShell ? (pendingModels.get(threadShell.id) ?? threadShell.modelSelection) : null;
const setModel = (selection: ModelSelection) => {
if (draft) return setDraft({ ...draft, modelSelection: selection });
if (!threadShell) return;
const id = threadShell.id;
const same = sameSelection(providerConfig, selection, threadShell.modelSelection);
setPendingModels((previous) => {
const next = new Map(previous);
if (same) next.delete(id);
else next.set(id, selection);
return next;
});
};
const runtimeMode = draft ? draft.runtimeMode : threadShell?.runtimeMode;
const setRuntime = (next: (typeof RUNTIME_MODES)[number]) => {
if (draft) return setDraft({ ...draft, runtimeMode: next });
if (threadShell) run(`Mode: ${RUNTIME_MODE_LABELS[next] ?? next}`, () => session.setRuntimeMode(threadShell.id, next));
};
const openModelPicker = () => {
const selection = currentModel;
if (!selection) return;
if (!providerConfig) return say("Still loading the server's providers.", true);
// A started thread stays on its provider unless the provider supports handing over.
const locked = draft ? null : lockedProviderInstance(projection);
const groups: { label: string; items: PickerItem[] }[] = [];
for (const provider of selectableProviders(providerConfig)) {
if (locked && provider.instanceId !== locked) continue;
groups.push({
label: providerName(provider),
items: provider.models
.filter((model) => !model.isLegacy || model.slug === selection.model)
.map((model) => ({
id: `model:${provider.instanceId}:${model.slug}`,
title: model.name,
...(provider.instanceId === selection.instanceId && model.slug === selection.model ? { hint: "current" } : {}),
run: () => setModel(withModel(providerConfig, selection, provider.instanceId, model.slug)),
})),
});
}
const options: PickerItem[] = optionDescriptors(providerConfig, selection).map((descriptor) => ({
id: `option:${descriptor.id}`,
title: `${descriptor.label}: ${optionValueLabel(descriptor, optionValue(selection, descriptor))}`,
run: () => {
if (descriptor.type === "boolean") return setModel(withOption(selection, descriptor.id, optionValue(selection, descriptor) !== true));
openPicker({
placeholder: descriptor.label,
groups: [
{
label: descriptor.label,
items: descriptor.options.map((choice) => ({
id: `choice:${choice.id}`,
title: choice.label,
...(choice.id === optionValue(selection, descriptor) ? { hint: "current" } : choice.description ? { hint: choice.description } : {}),
run: () => setModel(withOption(selection, descriptor.id, choice.id)),
})),
},
],
});
},
}));
if (options.length > 0) groups.unshift({ label: "Options", items: options });
if (runtimeMode) {
groups.unshift({
label: "Mode",
items: RUNTIME_MODES.map((candidate) => ({
id: `mode:${candidate}`,
title: RUNTIME_MODE_LABELS[candidate] ?? candidate,
...(candidate === runtimeMode ? { hint: "current" } : {}),
run: () => setRuntime(candidate),
})),
});
}
openPicker({ placeholder: locked ? "Model, options and mode (this thread stays on its provider)" : "Model, options and mode", groups });
};
// New threads, as the web's: a local draft that becomes a thread when its first message is sent.
const startDraft = () => {
const projects = shell.snapshot?.projects ?? [];
const project = projects.find((candidate) => candidate.id === threadShell?.projectId) ?? projects[0];
if (!project) return say("No projects on this server yet; add one in T3 Code.", true);
setDraft(
draftDefaults({
config: providerConfig,
project,
currentModel: threadShell?.modelSelection ?? null,
projectHasThreads: shell.snapshot?.threads.some((candidate) => candidate.projectId === project.id) ?? false,
}),
);
setDiff(null);
setSettingsIndex(null);
setMode("input");
};
const draftProject = draft ? shell.snapshot?.projects.find((candidate) => candidate.id === draft.projectId) : undefined;
const openProjectPicker = () => {
if (!draft) return;
openPicker({
placeholder: "Project",
groups: [
{
label: "Projects",
items: (shell.snapshot?.projects ?? []).map((candidate) => ({
id: `project:${candidate.id}`,
title: candidate.title,
hint: candidate.id === draft.projectId ? "current" : candidate.workspaceRoot.replace(homedir(), "~"),
run: () =>
setDraft(
draftDefaults({
config: providerConfig,
project: candidate,
currentModel: draft.modelSelection,
projectHasThreads: shell.snapshot?.threads.some((member) => member.projectId === candidate.id) ?? false,
}),
),
})),
},
],
});
};
const toggleWorkspace = () => draft && setDraft({ ...draft, envMode: draft.envMode === "local" ? "worktree" : "local" });
const launchDraft = (text: string) => {
if (!draft || !draftProject) return;
const launching = draft;
const project = draftProject;
say("Starting thread…");
void (async () => {
let workspaceStrategy: { type: "root" } | { type: "worktree"; baseRef: string; startFromOrigin?: boolean } = { type: "root" };
if (launching.envMode === "worktree") {
// A worktree starts from the default branch; outside a git repository it runs in place, as the web's.
const refs = await session.defaultRef(project.workspaceRoot);
if (refs.isRepo && refs.ref) workspaceStrategy = { type: "worktree", baseRef: refs.ref.name, startFromOrigin: providerConfig?.settings.newWorktreesStartFromOrigin ?? true };
}
return session.launchThread({
projectId: launching.projectId,
title: deriveThreadTitleSeed({ text, attachments: [] }),
generateTitle: true,
modelSelection: launching.modelSelection,
runtimeMode: launching.runtimeMode,
interactionMode: "default",
workspaceStrategy,
text,
});
})().then(
(id) => {
drafts.current.delete(DRAFT_KEY);
openThread(id);
say("Thread started");
},
(error) => say(`Could not start the thread: ${messageOf(error)}`, true),
);
};
// The thread's terminals, as the web's terminal drawer: attach to one, or open the first.
const threadTerminals = threadShell ? (terminals?.items ?? []).filter((terminal) => terminal.threadId === threadShell.id) : [];
const enterTerminal = (terminal: { terminalId: string; cwd: string; worktreePath: string | null; label?: string }) => {
if (!threadShell) return;
attachTerminal(renderer, session, { threadId: threadShell.id, terminalId: terminal.terminalId, cwd: terminal.cwd, worktreePath: terminal.worktreePath, label: terminal.label || terminal.terminalId }, (message) => {
if (message) say(message, true);
});
};
const openTerminal = () => {
if (!threadShell) return say("Open a thread first.", true);
const cwd = threadShell.worktreePath ?? project?.workspaceRoot;
if (!cwd) return say("This thread has no folder to open a terminal in.", true);
const fresh = (id: string) => ({ terminalId: id, cwd, worktreePath: threadShell.worktreePath });
if (threadTerminals.length === 0) return enterTerminal(fresh(DEFAULT_TERMINAL_ID));
if (threadTerminals.length === 1 && threadTerminals[0]) return enterTerminal(threadTerminals[0]);
const taken = new Set(threadTerminals.map((terminal) => terminal.terminalId));
let next = 1;
while (taken.has(`term-${next}`)) next += 1;
openPicker({
placeholder: "Terminal",
groups: [
{
label: "Terminals",
items: threadTerminals.map((terminal) => ({
id: `terminal:${terminal.terminalId}`,
title: terminal.label || terminal.terminalId,
hint: terminal.status === "running" ? (terminal.hasRunningSubprocess ? "busy" : "running") : terminal.status,
run: () => enterTerminal(terminal),
})),
},
{ label: "New", items: [{ id: "terminal:new", title: "New terminal", run: () => enterTerminal(fresh(`term-${next}`)) }] },
],
});
};
/** The composer's text in $EDITOR. */
const openEditor = () => {
const composer = composerRef.current;
if (!composer) return;
const edited = editInEditor(renderer, composer.plainText);
if (edited === null) return say("The editor exited with an error; the message is unchanged.", true);
composer.setText(edited);
composer.gotoBufferEnd();
setMode("input");
};
const settingsRows = settingRows(config);
const cycleSetting = (index: number) => {
const row = settingsRows[index];
@@ -441,6 +707,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return;
}
const text = raw.trim();
if (draft) {
if (!text) return;
clearComposer();
return launchDraft(text);
}
if (!threadId) return;
if (pendingInput && questionDraft) {
const question = pendingInput.questions[questionDraft.index];
@@ -457,7 +728,15 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer"));
}
const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior });
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode));
const pendingModel = pendingModels.get(threadId);
if (pendingModel) {
setPendingModels((previous) => {
const next = new Map(previous);
next.delete(threadId);
return next;
});
}
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, text, dispatchMode, pendingModel));
};
const loadEarlier = () => {
@@ -503,7 +782,16 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
command("filter", "Filter threads", () => setMode("filter"), { shortcut: "/", keywords: ["search"] });
command("settled", showFolded ? "Hide settled threads" : "Show settled threads", () => setShowFolded(!showFolded), { shortcut: "z", keywords: ["snoozed", "archive"] });
}
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options"] });
command("new-thread", "New thread", startDraft, { shortcut: "c", keywords: ["create", "start", "chat"] });
if (draft) {
command("draft-project", "New thread: choose project", openProjectPicker, { shortcut: "p" });
command("draft-workspace", draft.envMode === "local" ? "New thread: use a new worktree" : "New thread: run in the project folder", toggleWorkspace, { shortcut: "w", keywords: ["worktree", "local", "branch"] });
command("draft-cancel", "Cancel new thread", () => setDraft(null), { keywords: ["discard"] });
}
if (currentModel) command("model", "Change model, options or mode", openModelPicker, { shortcut: "m", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] });
if (threadShell && !draft) command("terminal", "Open terminal", openTerminal, { shortcut: "ctrl+j", keywords: ["shell", "console"] });
if (threadId || draft) command("editor", "Write the message in $EDITOR", openEditor, { shortcut: "ctrl+g", keywords: ["vim", "editor", "compose"] });
command("settings", "Settings", openSettings, { keywords: ["preferences", "config", "options", "notifications", "alerts"] });
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}`).join("|");
@@ -528,6 +816,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const globalKey = (key: KeyEvent): boolean => {
if (key.ctrl && key.name === "c") return quit(), true;
if (key.ctrl && key.name === "k") return openPalette(), true;
if ((key.ctrl && key.name === "j") || key.name === "linefeed") return openTerminal(), true;
if (key.ctrl && key.name === "g" && (threadId || draft)) return openEditor(), true;
// One-line inputs keep ctrl+u and ctrl+d for editing.
const lineInput = mode === "filter" || mode === "palette" || mode === "confirm";
if (key.name === "pagedown" || (!lineInput && key.ctrl && key.name === "d")) return scrollPage(1), true;
@@ -539,6 +829,16 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
};
useKeyboard((key) => {
if (mode === "picker") {
if (key.ctrl && key.name === "c") return quit();
if (key.name === "escape") {
setPicker(null);
setMode(returnMode.current);
} else if (key.name === "down" || (key.ctrl && key.name === "n")) setPickerIndex((index) => Math.min(pickerEntries.length - 1, index + 1));
else if (key.name === "up" || (key.ctrl && key.name === "p")) setPickerIndex((index) => Math.max(0, index - 1));
else return;
return key.preventDefault();
}
if (mode === "palette") {
if (key.ctrl && key.name === "c") return quit();
if (key.name === "escape" || (key.ctrl && key.name === "k")) setMode(returnMode.current);
@@ -632,6 +932,17 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return quit();
case "escape":
if (diff) setDiff(null);
else if (draft) setDraft(null);
return;
case "c":
return startDraft();
case "m":
return openModelPicker();
case "p":
if (draft) openProjectPicker();
return;
case "w":
if (draft) toggleWorkspace();
return;
case "j":
case "down":
@@ -674,7 +985,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
case "i":
case "return":
case "tab":
if (threadId) setMode("input");
if (threadId || draft) setMode("input");
return key.preventDefault();
}
});
@@ -694,26 +1005,39 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const placeholder =
mode !== "input"
? "Press i to type"
: pendingApproval
? pendingApproval.supportsFeedback
? "Send feedback to decline this request"
: "Send a message to decline and redirect the agent"
: pendingInput
? "Type your own answer, or leave this blank to use the selected option"
: working
? config.followUpBehavior === "queue"
? "Queue a message for after this run (alt+enter to steer instead)"
: "Steer the agent (alt+enter to queue instead)"
: "Ask anything";
const footer = threadShell
: draft
? "What should the new thread do?"
: pendingApproval
? pendingApproval.supportsFeedback
? "Send feedback to decline this request"
: "Send a message to decline and redirect the agent"
: pendingInput
? "Type your own answer, or leave this blank to use the selected option"
: working
? config.followUpBehavior === "queue"
? "Queue a message for after this run (alt+enter to steer instead)"
: "Steer the agent (alt+enter to queue instead)"
: "Ask anything";
// The model with its options, then the mode when it isn't full access; click or m to change.
const composerKey: string = draft ? DRAFT_KEY : (threadId ?? "");
const pendingModel = !draft && threadShell ? pendingModels.get(threadShell.id) : undefined;
const footer =
currentModel && runtimeMode
? [
providerConfig ? modelSummary(providerConfig, currentModel) : currentModel.model === "default" ? "" : currentModel.model,
runtimeMode === "full-access" ? "" : (RUNTIME_MODE_LABELS[runtimeMode] ?? runtimeMode),
]
.filter(Boolean)
.join(" · ")
: "";
const draftLines: DraftLine[] = draft
? [
threadShell.modelSelection.model === "default" ? "" : threadShell.modelSelection.model,
threadShell.interactionMode === "plan" ? "Plan" : "Build",
threadShell.runtimeMode === "full-access" ? "" : (RUNTIME_MODE_LABELS[threadShell.runtimeMode] ?? threadShell.runtimeMode),
{ key: "project", label: "Project", value: draftProject?.title ?? "—", shortcut: "p", onPick: openProjectPicker },
{ key: "model", label: "Model", value: modelSummary(providerConfig, draft.modelSelection), shortcut: "m", onPick: openModelPicker },
{ key: "mode", label: "Mode", value: RUNTIME_MODE_LABELS[draft.runtimeMode] ?? draft.runtimeMode, shortcut: "m", onPick: openModelPicker },
{ key: "workspace", label: "Runs in", value: draft.envMode === "worktree" ? "a new worktree from the default branch" : "the project folder", shortcut: "w", onPick: toggleWorkspace },
]
.filter(Boolean)
.join(" · ")
: "";
: [];
const detailsPanel = (inPlace: boolean) => (
<DetailsPanel
details={details}
@@ -773,6 +1097,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
/>
) : diff ? (
<DiffView diff={diff} scrollRef={scrollRef} />
) : draft ? (
<DraftView lines={draftLines} />
) : threadId && detailsInPlace ? (
<box flexGrow={1} minHeight={0} flexDirection="column">
{detailsPanel(true)}
@@ -810,7 +1136,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}}
/>
) : null}
{threadId ? (
{threadId || draft ? (
<box
border
borderStyle="rounded"
@@ -824,10 +1150,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
onMouseDown={() => setMode("input")}
>
<textarea
key={threadId}
key={composerKey}
ref={composerRef}
focused={mode === "input"}
initialValue={drafts.current.get(threadId) ?? ""}
initialValue={drafts.current.get(composerKey) ?? ""}
placeholder={placeholder}
placeholderColor={colors.faint}
textColor={colors.text}
@@ -837,8 +1163,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
onContentChange={() => {
const composer = composerRef.current;
const text = composer?.plainText ?? "";
if (text) drafts.current.set(threadId, text);
else drafts.current.delete(threadId);
if (text) drafts.current.set(composerKey, text);
else drafts.current.delete(composerKey);
// Wrapped lines count too, so a long paragraph grows the box.
// The wrapped count can lag a programmatic newline, so hard lines are a floor.
setComposerLines(Math.max(text.split("\n").length, composer?.virtualLineCount ?? 1));
@@ -847,9 +1173,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
/>
</box>
) : null}
{threadId ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
{threadId || draft ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2} onMouseDown={openModelPicker}>
<text fg={colors.faint}>{footer}</text>
{pendingModel ? <text fg={colors.accent}>{" · next message"}</text> : null}
</box>
) : null}
</box>
@@ -859,7 +1186,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
{flash ? (
<text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text>
) : (
<text fg={colors.faint}>{hints(mode, { config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined })}</text>
<text fg={colors.faint}>{hints(mode, { draft: draft !== null, config, approval: Boolean(pendingApproval), question: Boolean(pendingInput), working, attached, diff: diff !== null, parent: parent !== undefined })}</text>
)}
</box>
{mode === "palette" ? (
@@ -877,16 +1204,33 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
onPick={pick}
/>
) : null}
{mode === "picker" && picker ? (
<Palette
query={pickerQuery}
placeholder={picker.placeholder}
groups={pickerView}
selected={Math.min(pickerIndex, Math.max(0, pickerEntries.length - 1))}
width={width}
height={height}
onQuery={(value) => {
setPickerQuery(value);
setPickerIndex(0);
}}
onSubmit={() => pickItem(Math.min(pickerIndex, pickerEntries.length - 1))}
onPick={pickItem}
/>
) : null}
</box>
);
}
function hints(
mode: Mode,
state: { readonly config: Tui3Config; readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean; readonly diff: boolean; readonly parent: boolean },
state: { readonly draft: boolean; readonly config: Tui3Config; readonly approval: boolean; readonly question: boolean; readonly working: boolean; readonly attached: boolean; readonly diff: boolean; readonly parent: boolean },
): string {
if (mode === "filter") return "enter done · esc close";
if (mode === "palette") return "↑/↓ move · enter run · esc close";
if (mode === "picker") return "↑/↓ move · enter choose · esc close";
if (mode === "confirm") return "enter confirm · esc cancel";
if (mode === "details") return "j/k move · enter open · t toggle automation · esc back";
if (mode === "settings") return "j/k move · enter change · esc close";
@@ -894,15 +1238,16 @@ function hints(
const send = state.config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
const other = state.config.followUpBehavior === "steer" ? "queue" : "steer";
const newline = state.config.sendShortcut === "enter" ? "shift+enter or \\ newline" : "enter newline";
const parts = [state.working ? `${send} ${state.config.followUpBehavior} · alt+enter ${other}` : `${send} send`, newline, "esc navigate"];
const parts = [state.working ? `${send} ${state.config.followUpBehavior} · alt+enter ${other}` : `${send} send`, newline, "ctrl+g editor", "esc navigate"];
if (state.question) parts.unshift("1-9 pick");
if (state.approval) parts.unshift("approval waiting: esc, then y/n");
if (!state.attached) parts.push("ctrl+n/p thread");
return parts.join(" · ");
}
if (state.diff) return "j/k scroll · esc close diff · l details";
if (state.draft) return "i write the first message · p project · m model & mode · w worktree · esc cancel";
const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter"];
parts.push("i type", "l details", "e expand", "o earlier");
parts.push("i type", "c new", "m model", "ctrl+j terminal", "l details", "e expand");
if (state.parent) parts.push("u parent");
parts.push("ctrl+k commands", "q quit");
if (state.question) parts.unshift("1-9 pick · x dismiss");
+36
View File
@@ -0,0 +1,36 @@
import { colors } from "./theme.ts";
export interface DraftLine {
readonly key: string;
readonly label: string;
readonly value: string;
/** The key that changes it. */
readonly shortcut: string;
readonly onPick: () => void;
}
/** A new thread before its first message: where it runs and with what. The composer below sends it. */
export function DraftView(props: { readonly lines: readonly DraftLine[] }) {
const labelWidth = Math.max(...props.lines.map((line) => line.label.length)) + 2;
return (
<box flexGrow={1} minHeight={0} flexDirection="column" paddingLeft={2} paddingRight={1}>
<box flexDirection="row" flexShrink={0} height={1}>
<text fg={colors.text}>
<strong>New thread</strong>
</text>
<box flexGrow={1} />
<text fg={colors.faint}>esc cancel</text>
</box>
<box flexDirection="column" marginTop={1}>
{props.lines.map((line) => (
<box key={line.key} flexDirection="row" height={1} onMouseDown={line.onPick}>
<text fg={colors.muted} flexShrink={0}>{line.label.padEnd(labelWidth)}</text>
<text fg={colors.text} flexShrink={0}>{line.value}</text>
<text fg={colors.faint} wrapMode="none">{` ${line.shortcut}`}</text>
</box>
))}
</box>
<text fg={colors.faint} marginTop={1}>Write the first message below; sending it starts the thread.</text>
</box>
);
}
+2 -1
View File
@@ -7,6 +7,7 @@ import { colors } from "./theme.ts";
*/
export function Palette(props: {
readonly query: string;
readonly placeholder?: string;
readonly groups: readonly PaletteGroup[];
readonly selected: number;
readonly width: number;
@@ -31,7 +32,7 @@ export function Palette(props: {
<box position="absolute" top={2} left={Math.floor((props.width - width) / 2)} width={width} zIndex={10} flexDirection="column" border borderStyle="rounded" borderColor={colors.borderFocused} backgroundColor={colors.panel}>
<box paddingLeft={1} paddingRight={1} height={1} flexDirection="row">
<text fg={colors.accent}>{"› "}</text>
<input focused flexGrow={1} placeholder="Search commands and threads (> for commands only)" value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
<input focused flexGrow={1} placeholder={props.placeholder ?? "Search commands and threads (> for commands only)"} value={props.query} onInput={props.onQuery} onSubmit={props.onSubmit} backgroundColor={colors.panel} focusedBackgroundColor={colors.panel} />
</box>
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}>
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
+27
View File
@@ -0,0 +1,27 @@
import type { CliRenderer } from "@opentui/core";
import { spawnSync } from "node:child_process";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
/**
* Hands the terminal to $VISUAL or $EDITOR on a copy of `text` and returns what was saved,
* or null if the editor failed. The renderer is suspended meanwhile.
*/
export function editInEditor(renderer: CliRenderer, text: string): string | null {
const editor = process.env.VISUAL || process.env.EDITOR || "vi";
const dir = mkdtempSync(join(tmpdir(), "tui3-"));
const file = join(dir, "prompt.md");
writeFileSync(file, text);
renderer.suspend();
try {
// Through the shell, so EDITOR="code --wait" works.
const result = spawnSync(process.env.SHELL || "sh", ["-c", `${editor} "$1"`, "sh", file], { stdio: "inherit" });
if (result.status !== 0) return null;
return readFileSync(file, "utf8").replace(/\n$/, "");
} finally {
rmSync(dir, { recursive: true, force: true });
renderer.resume();
renderer.requestRender();
}
}
+90
View File
@@ -0,0 +1,90 @@
import type { CliRenderer } from "@opentui/core";
import type { ThreadId } from "@t3tools/contracts";
import type { T3Session } from "../client/session.ts";
/** Ctrl+J (LF), Ctrl+] and Ctrl+J under the kitty keyboard protocol leave the terminal. */
const DETACH_KEYS = new Set(["\n", "\x1d", "\x1b[106;5u"]);
/** Modes a full-screen program may leave on; switched off before tui3 draws again. */
const RESET = "\x1b[0m\x1b[?25h\x1b[?1l\x1b[?2004l\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?1049l";
export interface TerminalTarget {
readonly threadId: ThreadId;
readonly terminalId: string;
readonly cwd: string;
readonly worktreePath: string | null;
readonly label: string;
}
/**
* Gives the whole screen to one of T3's terminals: its scrollback, then live output, with
* keystrokes sent to it. Ctrl+J comes back. The terminal keeps running on the server.
* Note that a terminal's size is shared by everyone attached, so attaching resizes it.
*/
export function attachTerminal(renderer: CliRenderer, session: T3Session, target: TerminalTarget, onDone: (message?: string) => void): void {
const stdin = process.stdin;
const stdout = process.stdout;
const size = () => ({ cols: stdout.columns || 80, rows: stdout.rows || 24 });
let finished = false;
renderer.suspend();
stdout.write("\x1b[?1049h\x1b[H\x1b[2J");
stdout.write(`\x1b]2;tui3 · ${target.label} · ctrl+j to return\x07`);
stdin.setRawMode?.(true);
stdin.resume();
const onInput = (data: Buffer) => {
const text = data.toString("utf8");
if (DETACH_KEYS.has(text)) return finish();
session.writeTerminal(target.threadId, target.terminalId, text).catch(() => {});
};
const onResize = () => {
const { cols, rows } = size();
session.resizeTerminal(target.threadId, target.terminalId, cols, rows).catch(() => {});
};
const detach = session.attachTerminal(
{ threadId: target.threadId, terminalId: target.terminalId, cwd: target.cwd, worktreePath: target.worktreePath, ...size() },
(event) => {
switch (event.type) {
case "snapshot":
case "restarted":
stdout.write("\x1b[H\x1b[2J");
stdout.write(event.snapshot.history);
return;
case "output":
stdout.write(event.data);
return;
case "cleared":
stdout.write("\x1b[H\x1b[2J");
return;
case "exited":
stdout.write(`\r\n\x1b[2m[exited${event.exitCode === null ? "" : ` with code ${event.exitCode}`} · ctrl+j to return]\x1b[0m\r\n`);
return;
case "error":
stdout.write(`\r\n\x1b[31m[${event.message}]\x1b[0m\r\n`);
return;
case "closed":
return finish("Terminal closed");
}
},
(error) => {
if (error) finish(`Terminal: ${error}`);
},
);
stdin.on("data", onInput);
stdout.on("resize", onResize);
function finish(message?: string) {
if (finished) return;
finished = true;
detach();
stdin.off("data", onInput);
stdout.off("resize", onResize);
stdout.write(RESET);
stdout.write("\x1b]2;tui3\x07");
renderer.resume();
renderer.requestRender();
onDone(message);
}
}
+25
View File
@@ -0,0 +1,25 @@
/** Escape sequences tui3 writes past the renderer: the bell and desktop notifications. */
/** Inside tmux, escape sequences other than the bell need passthrough to reach the outer terminal. */
function passthrough(sequence: string): string {
if (!process.env.TMUX) return sequence;
return `\x1bPtmux;${sequence.replaceAll("\x1b", "\x1b\x1b")}\x1b\\`;
}
/** The terminal bell: a sound, a flash, or a flag on the tmux window, as the terminal is set up. */
export function ring(): void {
process.stdout.write("\x07");
}
/**
* A desktop notification through the terminal (so it works over SSH): OSC 99 for kitty,
* OSC 9 for the rest (iTerm2, WezTerm, Ghostty, foot, Windows Terminal). Terminals without
* either ignore it. In tmux it needs `set -g allow-passthrough on`.
*/
export function desktopNotify(title: string, body: string): void {
const clean = (text: string) => text.replace(/[\x00-\x1f\x7f;]/g, " ").slice(0, 200);
const sequence = process.env.KITTY_WINDOW_ID
? `\x1b]99;i=tui3:d=0;${clean(title)}\x1b\\\x1b]99;i=tui3:p=body;${clean(body)}\x1b\\`
: `\x1b]9;${clean(title)}: ${clean(body)}\x07`;
process.stdout.write(passthrough(sequence));
}