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:
1 parent
121bbd9137
commit
626d37a4e9
18 files changed
+1074
-49
No files matched your search
@@ -28,17 +28,20 @@ Any mode:
|
|||||||
| Key | Action |
|
| Key | Action |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `ctrl+k` | command palette: every action below, plus thread search |
|
| `ctrl+k` | command palette: every action below, plus thread search |
|
||||||
|
| `ctrl+j` | attach to the thread's terminal (see below) |
|
||||||
| `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread |
|
| `ctrl+n` / `ctrl+p` (or `alt+↓`/`alt+↑`) | next / previous thread |
|
||||||
| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation |
|
| `pgup`/`pgdn`, `ctrl+u`/`ctrl+d` | scroll the conversation |
|
||||||
| `ctrl+c` | quit |
|
| `ctrl+c` | quit |
|
||||||
|
|
||||||
Typing: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` or `ctrl+j` adds a newline (`shift+enter` needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines.
|
Typing: `enter` sends. While the agent is running, `enter` steers it (the message reaches it mid-run) and `alt+enter` queues the message for after the run, as in T3 Code. With an approval pending, a typed message declines it with your feedback. `shift+enter` adds a newline (it needs a terminal with the kitty keyboard protocol); so does ending the line with `\` and pressing `enter`. The box grows up to 8 lines. `ctrl+g` opens the message in `$VISUAL` or `$EDITOR` (falling back to `vi`); save and quit to bring it back.
|
||||||
|
|
||||||
Navigation:
|
Navigation:
|
||||||
|
|
||||||
| Key | Action |
|
| Key | Action |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| `j`/`k`, arrows | next / previous thread (scroll, in `attach`) |
|
| `j`/`k`, arrows | next / previous thread (scroll, in `attach`) |
|
||||||
|
| `c` | new thread (see below) |
|
||||||
|
| `m` | model, options (reasoning, fast mode…) and access mode |
|
||||||
| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval |
|
| `y` / `Y` / `n` | approve / always allow this session / decline the pending approval |
|
||||||
| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) |
|
| `1`–`9` | pick an option when the agent asks a question (also in an empty message box) |
|
||||||
| `x` | dismiss the agent's question |
|
| `x` | dismiss the agent's question |
|
||||||
@@ -52,7 +55,7 @@ Navigation:
|
|||||||
| `/` | filter threads by title or project (the box opens at the top of the thread list) |
|
| `/` | filter threads by title or project (the box opens at the top of the thread list) |
|
||||||
| `S` | stop the thread |
|
| `S` | stop the thread |
|
||||||
| `g` / `G` | top / bottom of the conversation |
|
| `g` / `G` | top / bottom of the conversation |
|
||||||
| `esc` / `q` | close the diff; otherwise `q` quits |
|
| `esc` / `q` | close the diff or cancel a new thread; otherwise `q` quits |
|
||||||
|
|
||||||
The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream):
|
The layout follows T3 Code's web app, and much of it uses the web app's own code (vendored from upstream):
|
||||||
|
|
||||||
@@ -68,6 +71,31 @@ The layout follows T3 Code's web app, and much of it uses the web app's own code
|
|||||||
- Threads open scrolled to the bottom.
|
- Threads open scrolled to the bottom.
|
||||||
- **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off.
|
- **Read state:** opening a thread marks it read after a moment, as the web app does. Set `TUI3_NO_VISIT=1` to turn that off.
|
||||||
|
|
||||||
|
## New threads
|
||||||
|
|
||||||
|
`c` (or `New thread` in the palette) opens a draft in the current thread's project, with the defaults T3 Code would use: the server's default model and mode for new threads, and the project folder or a new worktree as the project settings say. In the draft, `p` picks the project, `m` the model and mode, and `w` switches between the project folder and a new worktree off the default branch. Write the first message and send it: that starts the thread, which T3 then titles. `esc` cancels.
|
||||||
|
|
||||||
|
## Model, options and mode
|
||||||
|
|
||||||
|
`m` (or a click on the model under the message box) opens a picker with the access mode, the model's options as the server describes them (reasoning effort, fast mode and whatever else the provider offers), and every model from the providers that are enabled and available. As in the web app:
|
||||||
|
|
||||||
|
- A new model or option applies from the next message you send; the line under the box shows `· next message` until then.
|
||||||
|
- The access mode changes at once.
|
||||||
|
- Once a thread has run, it stays on its provider; you can still change models within it.
|
||||||
|
|
||||||
|
## Terminals
|
||||||
|
|
||||||
|
`ctrl+j` attaches to the thread's terminal on the T3 server, the same one the app's terminal drawer shows. If the thread has none, it starts one in the thread's worktree or project folder; with several, you pick one or start another. tui3 hands the whole screen to the terminal; `ctrl+j` or `ctrl+]` comes back. The terminal keeps running after you detach. The terminal's size is shared, so attaching resizes it for anyone else watching.
|
||||||
|
|
||||||
|
## Alerts
|
||||||
|
|
||||||
|
tui3 alerts when a thread you aren't watching finishes or needs you (approval, input, a request, a failure or a usage limit), using T3 Code's own rules for when to alert. Subagents don't alert. Depending on `notificationMode`:
|
||||||
|
|
||||||
|
- **Bell:** the terminal bell.
|
||||||
|
- **Desktop notifications:** sent through the terminal (OSC 9, or OSC 99 in kitty), only when the terminal window isn't focused. Under tmux they need `set -g allow-passthrough on`.
|
||||||
|
|
||||||
|
While the terminal is focused, alerts for other threads also show on the bottom line (`inAppNotificationsEnabled`).
|
||||||
|
|
||||||
## Settings
|
## Settings
|
||||||
|
|
||||||
Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a click changes one, and changes save to `~/.config/tui3/config.json`:
|
Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a click changes one, and changes save to `~/.config/tui3/config.json`:
|
||||||
@@ -78,15 +106,17 @@ Open them from the command palette (`Settings`). `j`/`k` move, `enter` or a clic
|
|||||||
| `sendShortcut` | `enter`, or `ctrl-enter` (then `enter` adds a line; needs the kitty keyboard protocol, and `alt+enter` also sends) | `enter` |
|
| `sendShortcut` | `enter`, or `ctrl-enter` (then `enter` adds a line; needs the kitty keyboard protocol, and `alt+enter` also sends) | `enter` |
|
||||||
| `timestampFormat` | `locale`, `12-hour`, `24-hour` | `locale` |
|
| `timestampFormat` | `locale`, `12-hour`, `24-hour` | `locale` |
|
||||||
| `diffIgnoreWhitespace` | `true`, `false` | `true` |
|
| `diffIgnoreWhitespace` | `true`, `false` | `true` |
|
||||||
|
| `notificationMode` | `off`, `sound` (bell), `notifications` (desktop), `notifications-and-sound` | `sound` |
|
||||||
|
| `inAppNotificationsEnabled` | `true`, `false` | `true` |
|
||||||
|
|
||||||
These use the web app's names and defaults. The web app keeps them in each browser, so tui3 can't read yours and keeps its own. The same view shows the server's settings that matter here (model and mode for new threads, auto-settle, rate-limited threads), read-only: change those in the app.
|
These use the web app's names, and its defaults except for the two alert settings, which the web app leaves off. The web app keeps them in each browser, so tui3 can't read yours and keeps its own. The same view shows the server's settings that matter here (model and mode for new threads, auto-settle, rate-limited threads), read-only: change those in the app.
|
||||||
|
|
||||||
Long threads load as a bounded window of recent turns; press `o` for older ones. If the connection drops, tui3 reconnects with backoff and resubscribes.
|
Long threads load as a bounded window of recent turns; press `o` for older ones. If the connection drops, tui3 reconnects with backoff and resubscribes.
|
||||||
|
|
||||||
## How it connects
|
## How it connects
|
||||||
|
|
||||||
- It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`).
|
- It finds the local server from `~/.t3/userdata/server-runtime.json` (override with `TUI3_SERVER`).
|
||||||
- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read`, `orchestration:operate`, `filesystem:read` (diffs), `source-control:write` (git actions) and `terminal:operate` (stopping servers), and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. A stored credential missing any of these scopes is replaced with a new one. For a remote server, pass a token in `TUI3_TOKEN`.
|
- On first run it mints its own bearer session with `t3 auth session issue --label tui3`, scoped to `orchestration:read`, `orchestration:operate`, `filesystem:read` (diffs), `source-control:write` (git actions), `terminal:read` and `terminal:operate` (terminals, stopping servers), and stores it in `~/.config/tui3/credentials.json` (mode 600). Revoke it any time with `t3 auth session revoke`. A stored credential missing any of these scopes is replaced with a new one. For a remote server, pass a token in `TUI3_TOKEN`.
|
||||||
- It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`).
|
- It speaks T3 Code's own WebSocket RPC protocol, typed by upstream's `@t3tools/contracts`, and applies thread updates with upstream's own reducers. Both come from `vendor/t3code`, a submodule pinned to the server version this was built against (`v0.1.6-nightly.20261030.3917`).
|
||||||
|
|
||||||
Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots.
|
Set `TUI3_DEBUG=/path/to/log` to log thread subscriptions and snapshots.
|
||||||
@@ -104,4 +134,4 @@ Type errors after a bump point at the protocol changes to adapt to.
|
|||||||
|
|
||||||
## Not yet supported
|
## Not yet supported
|
||||||
|
|
||||||
Starting new threads, editing queued messages, plan follow-ups, attachments, reviewing or commenting on diffs, and the integrated terminal. Use the T3 Code app for those.
|
Editing queued messages, plan follow-ups, attachments, forking threads, and reviewing or commenting on diffs. Use the T3 Code app for those.
|
||||||
+2
-2
@@ -4,9 +4,9 @@ import { dirname, join } from "node:path";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Scopes tui3 asks for: read and operate threads, read diffs, run git actions
|
* 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 {
|
export interface ServerTarget {
|
||||||
/** e.g. http://127.0.0.1:3773 */
|
/** e.g. http://127.0.0.1:3773 */
|
||||||
|
|||||||
+84
-1
@@ -20,6 +20,12 @@ import {
|
|||||||
type ScheduledTask,
|
type ScheduledTask,
|
||||||
type ScheduledTaskId,
|
type ScheduledTaskId,
|
||||||
type ServerConfig,
|
type ServerConfig,
|
||||||
|
type ModelSelection,
|
||||||
|
type RuntimeMode,
|
||||||
|
type TerminalAttachStreamEvent,
|
||||||
|
type TerminalSummary,
|
||||||
|
type VcsRef,
|
||||||
|
type OrchestrationV2ThreadLaunchInput,
|
||||||
type OrchestrationV2ThreadShell,
|
type OrchestrationV2ThreadShell,
|
||||||
type VcsStatusLocalResult,
|
type VcsStatusLocalResult,
|
||||||
type VcsStatusRemoteResult,
|
type VcsStatusRemoteResult,
|
||||||
@@ -366,7 +372,8 @@ export class T3Session {
|
|||||||
* Sends a message the way the web composer does: "auto" when idle, otherwise
|
* Sends a message the way the web composer does: "auto" when idle, otherwise
|
||||||
* "steer" (into the active run) or "queue" (after it). See resolveComposerDispatchMode.
|
* "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();
|
const commandId = newCommandId();
|
||||||
return this.dispatch({
|
return this.dispatch({
|
||||||
type: "message.dispatch",
|
type: "message.dispatch",
|
||||||
@@ -375,6 +382,7 @@ export class T3Session {
|
|||||||
messageId: MessageId.make(commandId),
|
messageId: MessageId.make(commandId),
|
||||||
text,
|
text,
|
||||||
attachments: [],
|
attachments: [],
|
||||||
|
...(modelSelection ? { modelSelection } : {}),
|
||||||
...(mode === "queue" ? { dispatchMode: { type: "queue_after_active" } } : { dispatchMode: { type: "start_immediately" }, deliveryIntent: mode }),
|
...(mode === "queue" ? { dispatchMode: { type: "queue_after_active" } } : { dispatchMode: { type: "start_immediately" }, deliveryIntent: mode }),
|
||||||
createdBy: "user",
|
createdBy: "user",
|
||||||
creationSource: "web",
|
creationSource: "web",
|
||||||
@@ -405,6 +413,81 @@ export class T3Session {
|
|||||||
return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId });
|
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> {
|
private async dispatch(command: OrchestrationV2Command): Promise<void> {
|
||||||
const rpc = this.requireConnection().rpc;
|
const rpc = this.requireConnection().rpc;
|
||||||
await Effect.runPromise(rpc[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](command));
|
await Effect.runPromise(rpc[ORCHESTRATION_V2_WS_METHODS.dispatchCommand](command));
|
||||||
|
|||||||
+7
-1
@@ -14,9 +14,13 @@ export interface Tui3Config {
|
|||||||
readonly sendShortcut: "enter" | "ctrl-enter";
|
readonly sendShortcut: "enter" | "ctrl-enter";
|
||||||
readonly timestampFormat: "locale" | "12-hour" | "24-hour";
|
readonly timestampFormat: "locale" | "12-hour" | "24-hour";
|
||||||
readonly diffIgnoreWhitespace: boolean;
|
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. */
|
/** Every setting with its choices in cycling order, for the settings view. */
|
||||||
export const CONFIG_CHOICES: { readonly [K in keyof Tui3Config]: readonly Tui3Config[K][] } = {
|
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"],
|
sendShortcut: ["enter", "ctrl-enter"],
|
||||||
timestampFormat: ["locale", "12-hour", "24-hour"],
|
timestampFormat: ["locale", "12-hour", "24-hour"],
|
||||||
diffIgnoreWhitespace: [true, false],
|
diffIgnoreWhitespace: [true, false],
|
||||||
|
notificationMode: ["off", "sound", "notifications", "notifications-and-sound"],
|
||||||
|
inAppNotificationsEnabled: [true, false],
|
||||||
};
|
};
|
||||||
|
|
||||||
export const configPath = () => join(configDir(), "config.json");
|
export const configPath = () => join(configDir(), "config.json");
|
||||||
|
|||||||
@@ -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";
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -88,3 +88,34 @@ export function paletteGroups(input: {
|
|||||||
export function paletteEntries(groups: readonly PaletteGroup[]): PaletteEntry[] {
|
export function paletteEntries(groups: readonly PaletteGroup[]): PaletteEntry[] {
|
||||||
return groups.flatMap((group) => group.entries);
|
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);
|
||||||
|
}
|
||||||
@@ -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)" } },
|
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" } },
|
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" } },
|
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. */
|
/** tui3's own settings, in display order, each cycled with enter. */
|
||||||
|
|||||||
+382
-37
@@ -8,23 +8,30 @@ import {
|
|||||||
togglePendingUserInputOptionSelection,
|
togglePendingUserInputOptionSelection,
|
||||||
type PendingUserInputDraftAnswer,
|
type PendingUserInputDraftAnswer,
|
||||||
} from "@t3tools/client-runtime/state/pending-user-input";
|
} 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 { homedir } from "node:os";
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
|
|
||||||
import type { FeedState, ServerConfigState, ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts";
|
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 { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts";
|
||||||
import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.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 { serverSettingLines, settingRows } from "../model/settings.ts";
|
||||||
import { buildTimeline, type Timeline } from "../model/timeline.ts";
|
import { buildTimeline, type Timeline } from "../model/timeline.ts";
|
||||||
import { threadRows, type Section } from "../model/threads.ts";
|
import { threadRows, type Section } from "../model/threads.ts";
|
||||||
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
|
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
|
||||||
import { DetailsPanel } from "./DetailsPanel.tsx";
|
import { DetailsPanel } from "./DetailsPanel.tsx";
|
||||||
import { DiffView, type DiffState } from "./DiffView.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 { Palette } from "./Palette.tsx";
|
||||||
import { QuestionPanel } from "./QuestionPanel.tsx";
|
import { QuestionPanel } from "./QuestionPanel.tsx";
|
||||||
import { SettingsView } from "./SettingsView.tsx";
|
import { SettingsView } from "./SettingsView.tsx";
|
||||||
|
import { attachTerminal } from "./terminalAttach.ts";
|
||||||
|
import { desktopNotify, ring } from "./terminalOut.ts";
|
||||||
import { colors } from "./theme.ts";
|
import { colors } from "./theme.ts";
|
||||||
import { ThreadList } from "./ThreadList.tsx";
|
import { ThreadList } from "./ThreadList.tsx";
|
||||||
import { ThreadView } from "./ThreadView.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.
|
* "details": j/k move through the details panel. "settings": j/k move through settings.
|
||||||
* The rest are overlays with their own input.
|
* 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. */
|
/** Holding j/k skims past threads; only subscribe to one you stop on. */
|
||||||
const SUBSCRIBE_DELAY_MS = 120;
|
const SUBSCRIBE_DELAY_MS = 120;
|
||||||
@@ -53,15 +60,15 @@ const COMPOSER_KEYS = {
|
|||||||
enter: [
|
enter: [
|
||||||
{ name: "return", action: "submit" },
|
{ name: "return", action: "submit" },
|
||||||
{ name: "return", shift: true, action: "newline" },
|
{ name: "return", shift: true, action: "newline" },
|
||||||
{ name: "j", ctrl: true, action: "newline" },
|
|
||||||
],
|
],
|
||||||
"ctrl-enter": [
|
"ctrl-enter": [
|
||||||
{ name: "return", action: "newline" },
|
{ name: "return", action: "newline" },
|
||||||
{ name: "return", ctrl: true, action: "submit" },
|
{ name: "return", ctrl: true, action: "submit" },
|
||||||
{ name: "return", shift: true, action: "newline" },
|
{ name: "return", shift: true, action: "newline" },
|
||||||
{ name: "j", ctrl: true, action: "newline" },
|
|
||||||
],
|
],
|
||||||
} as const;
|
} as const;
|
||||||
|
/** The composer's key while a new thread is being drafted. */
|
||||||
|
const DRAFT_KEY = "draft";
|
||||||
|
|
||||||
interface QuestionDraft {
|
interface QuestionDraft {
|
||||||
readonly index: number;
|
readonly index: number;
|
||||||
@@ -87,6 +94,14 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
const [config, setConfig] = useState(props.config);
|
const [config, setConfig] = useState(props.config);
|
||||||
const [settingsIndex, setSettingsIndex] = useState<number | null>(null);
|
const [settingsIndex, setSettingsIndex] = useState<number | null>(null);
|
||||||
const [serverConfig, setServerConfig] = useState<ServerConfigState | 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. */
|
/** Idle subagents the shell leaves out, fetched when you open one. */
|
||||||
const [familyShells, setFamilyShells] = useState<ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>>(new Map());
|
const [familyShells, setFamilyShells] = useState<ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>>(new Map());
|
||||||
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
|
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");
|
const returnMode = useRef<Mode>("nav");
|
||||||
|
|
||||||
useEffect(() => session.onShell(setShell), [session]);
|
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.
|
// Drives "Working for 12s" and the sidebar's durations.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const timer = setInterval(() => setNow(Date.now()), 1_000);
|
const timer = setInterval(() => setNow(Date.now()), 1_000);
|
||||||
@@ -132,6 +166,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
setSelectedId(id);
|
setSelectedId(id);
|
||||||
setDiff(null);
|
setDiff(null);
|
||||||
setSettingsIndex(null);
|
setSettingsIndex(null);
|
||||||
|
setDraft(null);
|
||||||
setDetailsSelected(null);
|
setDetailsSelected(null);
|
||||||
setMode((current) => (current === "details" || current === "settings" ? "nav" : current));
|
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 vcsCwd = threadShell ? detailsCwd(threadShell, project) : null;
|
||||||
const live = shell.status.type === "live";
|
const live = shell.status.type === "live";
|
||||||
useEffect(() => (live ? session.watchServerConfig(setServerConfig) : undefined), [session, 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.
|
// 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 supportsFamilies = serverConfig?.config?.shellThreadFamilies === true;
|
||||||
const unlisted = threadId !== undefined && !threadShell;
|
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),
|
(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) => {
|
const respond = (decision: ProviderApprovalDecision) => {
|
||||||
if (!threadId || !pendingApproval) return say("Nothing is waiting for approval.", true);
|
if (!threadId || !pendingApproval) return say("Nothing is waiting for approval.", true);
|
||||||
run(decision === "decline" ? "Declined" : "Approved", () => session.respond(threadId, pendingApproval.requestId, decision));
|
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");
|
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 settingsRows = settingRows(config);
|
||||||
const cycleSetting = (index: number) => {
|
const cycleSetting = (index: number) => {
|
||||||
const row = settingsRows[index];
|
const row = settingsRows[index];
|
||||||
@@ -441,6 +707,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const text = raw.trim();
|
const text = raw.trim();
|
||||||
|
if (draft) {
|
||||||
|
if (!text) return;
|
||||||
|
clearComposer();
|
||||||
|
return launchDraft(text);
|
||||||
|
}
|
||||||
if (!threadId) return;
|
if (!threadId) return;
|
||||||
if (pendingInput && questionDraft) {
|
if (pendingInput && questionDraft) {
|
||||||
const question = pendingInput.questions[questionDraft.index];
|
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"));
|
return run("Declined and redirected", () => session.sendMessage(threadId, text, "steer"));
|
||||||
}
|
}
|
||||||
const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior });
|
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 = () => {
|
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("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("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"] });
|
command("quit", "Quit tui3", quit, { shortcut: "q", keywords: ["exit"] });
|
||||||
|
|
||||||
const commandKey = commands.map((candidate) => `${candidate.id}:${candidate.title}`).join("|");
|
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 => {
|
const globalKey = (key: KeyEvent): boolean => {
|
||||||
if (key.ctrl && key.name === "c") return quit(), true;
|
if (key.ctrl && key.name === "c") return quit(), true;
|
||||||
if (key.ctrl && key.name === "k") return openPalette(), 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.
|
// One-line inputs keep ctrl+u and ctrl+d for editing.
|
||||||
const lineInput = mode === "filter" || mode === "palette" || mode === "confirm";
|
const lineInput = mode === "filter" || mode === "palette" || mode === "confirm";
|
||||||
if (key.name === "pagedown" || (!lineInput && key.ctrl && key.name === "d")) return scrollPage(1), true;
|
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) => {
|
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 (mode === "palette") {
|
||||||
if (key.ctrl && key.name === "c") return quit();
|
if (key.ctrl && key.name === "c") return quit();
|
||||||
if (key.name === "escape" || (key.ctrl && key.name === "k")) setMode(returnMode.current);
|
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();
|
return quit();
|
||||||
case "escape":
|
case "escape":
|
||||||
if (diff) setDiff(null);
|
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;
|
return;
|
||||||
case "j":
|
case "j":
|
||||||
case "down":
|
case "down":
|
||||||
@@ -674,7 +985,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
case "i":
|
case "i":
|
||||||
case "return":
|
case "return":
|
||||||
case "tab":
|
case "tab":
|
||||||
if (threadId) setMode("input");
|
if (threadId || draft) setMode("input");
|
||||||
return key.preventDefault();
|
return key.preventDefault();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -694,26 +1005,39 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
const placeholder =
|
const placeholder =
|
||||||
mode !== "input"
|
mode !== "input"
|
||||||
? "Press i to type"
|
? "Press i to type"
|
||||||
: pendingApproval
|
: draft
|
||||||
? pendingApproval.supportsFeedback
|
? "What should the new thread do?"
|
||||||
? "Send feedback to decline this request"
|
: pendingApproval
|
||||||
: "Send a message to decline and redirect the agent"
|
? pendingApproval.supportsFeedback
|
||||||
: pendingInput
|
? "Send feedback to decline this request"
|
||||||
? "Type your own answer, or leave this blank to use the selected option"
|
: "Send a message to decline and redirect the agent"
|
||||||
: working
|
: pendingInput
|
||||||
? config.followUpBehavior === "queue"
|
? "Type your own answer, or leave this blank to use the selected option"
|
||||||
? "Queue a message for after this run (alt+enter to steer instead)"
|
: working
|
||||||
: "Steer the agent (alt+enter to queue instead)"
|
? config.followUpBehavior === "queue"
|
||||||
: "Ask anything";
|
? "Queue a message for after this run (alt+enter to steer instead)"
|
||||||
const footer = threadShell
|
: "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,
|
{ key: "project", label: "Project", value: draftProject?.title ?? "—", shortcut: "p", onPick: openProjectPicker },
|
||||||
threadShell.interactionMode === "plan" ? "Plan" : "Build",
|
{ key: "model", label: "Model", value: modelSummary(providerConfig, draft.modelSelection), shortcut: "m", onPick: openModelPicker },
|
||||||
threadShell.runtimeMode === "full-access" ? "" : (RUNTIME_MODE_LABELS[threadShell.runtimeMode] ?? threadShell.runtimeMode),
|
{ 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) => (
|
const detailsPanel = (inPlace: boolean) => (
|
||||||
<DetailsPanel
|
<DetailsPanel
|
||||||
details={details}
|
details={details}
|
||||||
@@ -773,6 +1097,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
/>
|
/>
|
||||||
) : diff ? (
|
) : diff ? (
|
||||||
<DiffView diff={diff} scrollRef={scrollRef} />
|
<DiffView diff={diff} scrollRef={scrollRef} />
|
||||||
|
) : draft ? (
|
||||||
|
<DraftView lines={draftLines} />
|
||||||
) : threadId && detailsInPlace ? (
|
) : threadId && detailsInPlace ? (
|
||||||
<box flexGrow={1} minHeight={0} flexDirection="column">
|
<box flexGrow={1} minHeight={0} flexDirection="column">
|
||||||
{detailsPanel(true)}
|
{detailsPanel(true)}
|
||||||
@@ -810,7 +1136,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
}}
|
}}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : null}
|
||||||
{threadId ? (
|
{threadId || draft ? (
|
||||||
<box
|
<box
|
||||||
border
|
border
|
||||||
borderStyle="rounded"
|
borderStyle="rounded"
|
||||||
@@ -824,10 +1150,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
onMouseDown={() => setMode("input")}
|
onMouseDown={() => setMode("input")}
|
||||||
>
|
>
|
||||||
<textarea
|
<textarea
|
||||||
key={threadId}
|
key={composerKey}
|
||||||
ref={composerRef}
|
ref={composerRef}
|
||||||
focused={mode === "input"}
|
focused={mode === "input"}
|
||||||
initialValue={drafts.current.get(threadId) ?? ""}
|
initialValue={drafts.current.get(composerKey) ?? ""}
|
||||||
placeholder={placeholder}
|
placeholder={placeholder}
|
||||||
placeholderColor={colors.faint}
|
placeholderColor={colors.faint}
|
||||||
textColor={colors.text}
|
textColor={colors.text}
|
||||||
@@ -837,8 +1163,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
onContentChange={() => {
|
onContentChange={() => {
|
||||||
const composer = composerRef.current;
|
const composer = composerRef.current;
|
||||||
const text = composer?.plainText ?? "";
|
const text = composer?.plainText ?? "";
|
||||||
if (text) drafts.current.set(threadId, text);
|
if (text) drafts.current.set(composerKey, text);
|
||||||
else drafts.current.delete(threadId);
|
else drafts.current.delete(composerKey);
|
||||||
// Wrapped lines count too, so a long paragraph grows the box.
|
// 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.
|
// The wrapped count can lag a programmatic newline, so hard lines are a floor.
|
||||||
setComposerLines(Math.max(text.split("\n").length, composer?.virtualLineCount ?? 1));
|
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>
|
</box>
|
||||||
) : null}
|
) : null}
|
||||||
{threadId ? (
|
{threadId || draft ? (
|
||||||
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2}>
|
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2} onMouseDown={openModelPicker}>
|
||||||
<text fg={colors.faint}>{footer}</text>
|
<text fg={colors.faint}>{footer}</text>
|
||||||
|
{pendingModel ? <text fg={colors.accent}>{" · next message"}</text> : null}
|
||||||
</box>
|
</box>
|
||||||
) : null}
|
) : null}
|
||||||
</box>
|
</box>
|
||||||
@@ -859,7 +1186,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
{flash ? (
|
{flash ? (
|
||||||
<text fg={flash.bad ? colors.bad : colors.good}>{flash.text}</text>
|
<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>
|
</box>
|
||||||
{mode === "palette" ? (
|
{mode === "palette" ? (
|
||||||
@@ -877,16 +1204,33 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
|
|||||||
onPick={pick}
|
onPick={pick}
|
||||||
/>
|
/>
|
||||||
) : null}
|
) : 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>
|
</box>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function hints(
|
function hints(
|
||||||
mode: Mode,
|
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 {
|
): string {
|
||||||
if (mode === "filter") return "enter done · esc close";
|
if (mode === "filter") return "enter done · esc close";
|
||||||
if (mode === "palette") return "↑/↓ move · enter run · 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 === "confirm") return "enter confirm · esc cancel";
|
||||||
if (mode === "details") return "j/k move · enter open · t toggle automation · esc back";
|
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";
|
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 send = state.config.sendShortcut === "enter" ? "enter" : "ctrl+enter";
|
||||||
const other = state.config.followUpBehavior === "steer" ? "queue" : "steer";
|
const other = state.config.followUpBehavior === "steer" ? "queue" : "steer";
|
||||||
const newline = state.config.sendShortcut === "enter" ? "shift+enter or \\ newline" : "enter newline";
|
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.question) parts.unshift("1-9 pick");
|
||||||
if (state.approval) parts.unshift("approval waiting: esc, then y/n");
|
if (state.approval) parts.unshift("approval waiting: esc, then y/n");
|
||||||
if (!state.attached) parts.push("ctrl+n/p thread");
|
if (!state.attached) parts.push("ctrl+n/p thread");
|
||||||
return parts.join(" · ");
|
return parts.join(" · ");
|
||||||
}
|
}
|
||||||
if (state.diff) return "j/k scroll · esc close diff · l details";
|
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"];
|
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");
|
if (state.parent) parts.push("u parent");
|
||||||
parts.push("ctrl+k commands", "q quit");
|
parts.push("ctrl+k commands", "q quit");
|
||||||
if (state.question) parts.unshift("1-9 pick · x dismiss");
|
if (state.question) parts.unshift("1-9 pick · x dismiss");
|
||||||
|
|||||||
@@ -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
@@ -7,6 +7,7 @@ import { colors } from "./theme.ts";
|
|||||||
*/
|
*/
|
||||||
export function Palette(props: {
|
export function Palette(props: {
|
||||||
readonly query: string;
|
readonly query: string;
|
||||||
|
readonly placeholder?: string;
|
||||||
readonly groups: readonly PaletteGroup[];
|
readonly groups: readonly PaletteGroup[];
|
||||||
readonly selected: number;
|
readonly selected: number;
|
||||||
readonly width: 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 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">
|
<box paddingLeft={1} paddingRight={1} height={1} flexDirection="row">
|
||||||
<text fg={colors.accent}>{"› "}</text>
|
<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>
|
||||||
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}>
|
<box border={["top"]} borderColor={colors.border} flexDirection="column" height={listHeight + 1}>
|
||||||
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
|
{rows.length === 0 ? <text fg={colors.muted} paddingLeft={1}>No matches</text> : null}
|
||||||
|
|||||||
@@ -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();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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));
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import type { OrchestrationV2ShellSnapshot } from "@t3tools/contracts";
|
||||||
|
import * as DateTime from "effect/DateTime";
|
||||||
|
|
||||||
|
import { createAlerts, type Alert } from "../src/model/alerts.ts";
|
||||||
|
|
||||||
|
const at = (ms: number) => DateTime.makeUnsafe(ms);
|
||||||
|
const thread = (extra: Record<string, unknown> = {}) => ({
|
||||||
|
id: "t1",
|
||||||
|
title: "fix the build",
|
||||||
|
projectId: "p1",
|
||||||
|
status: "running",
|
||||||
|
activeRunId: "run-1",
|
||||||
|
latestRunId: "run-1",
|
||||||
|
latestRunRequestedAt: at(100),
|
||||||
|
latestRunStartedAt: at(110),
|
||||||
|
latestRunCompletedAt: null,
|
||||||
|
pendingRuntimeRequest: null,
|
||||||
|
latestUserMessageAt: null,
|
||||||
|
lineage: { relationshipToParent: null, parentThreadId: null },
|
||||||
|
modelSelection: { instanceId: "codex", model: "gpt" },
|
||||||
|
archivedAt: null,
|
||||||
|
deletedAt: null,
|
||||||
|
settledOverride: null,
|
||||||
|
settledAt: null,
|
||||||
|
pinnedAt: null,
|
||||||
|
lastVisitedAt: at(50),
|
||||||
|
hasActionableProposedPlan: false,
|
||||||
|
interactionMode: "default",
|
||||||
|
createdAt: at(0),
|
||||||
|
updatedAt: at(120),
|
||||||
|
...extra,
|
||||||
|
});
|
||||||
|
const snapshot = (threads: unknown[]) => ({ projects: [], threads }) as unknown as OrchestrationV2ShellSnapshot;
|
||||||
|
const approval = { pendingRuntimeRequest: { id: "q", kind: "command", createdAt: at(130) }, updatedAt: at(130) };
|
||||||
|
|
||||||
|
describe("alerts", () => {
|
||||||
|
test("say nothing about state that was there on connect, then alert once per new attention", () => {
|
||||||
|
const seen: Alert[] = [];
|
||||||
|
const alerts = createAlerts((alert) => seen.push(alert));
|
||||||
|
alerts.observe(snapshot([thread(approval)]));
|
||||||
|
expect(seen).toEqual([]);
|
||||||
|
|
||||||
|
alerts.clear();
|
||||||
|
alerts.observe(snapshot([thread()]));
|
||||||
|
alerts.observe(snapshot([thread(approval)]));
|
||||||
|
alerts.observe(snapshot([thread({ ...approval, updatedAt: at(140) })]));
|
||||||
|
expect(seen.map((alert) => [alert.title, alert.thread.title])).toEqual([["Approval needed", "fix the build"]]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("leave subagents to their parent", () => {
|
||||||
|
const seen: Alert[] = [];
|
||||||
|
const alerts = createAlerts((alert) => seen.push(alert));
|
||||||
|
const child = { id: "c1", lineage: { relationshipToParent: "subagent", parentThreadId: "t1" } };
|
||||||
|
alerts.observe(snapshot([thread(child)]));
|
||||||
|
alerts.observe(snapshot([thread({ ...child, ...approval })]));
|
||||||
|
expect(seen).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
+32
-1
@@ -1,5 +1,6 @@
|
|||||||
import { describe, expect, test } from "bun:test";
|
import { describe, expect, test } from "bun:test";
|
||||||
import { OrchestrationV2Command, ThreadId, RuntimeRequestId } from "@t3tools/contracts";
|
import { OrchestrationV2Command, OrchestrationV2ThreadLaunchInput, ProjectId, ProviderInstanceId, ThreadId, RuntimeRequestId } from "@t3tools/contracts";
|
||||||
|
import * as Effect from "effect/Effect";
|
||||||
import * as Schema from "effect/Schema";
|
import * as Schema from "effect/Schema";
|
||||||
|
|
||||||
import { T3Session } from "../src/client/session.ts";
|
import { T3Session } from "../src/client/session.ts";
|
||||||
@@ -63,4 +64,34 @@ describe("commands tui3 dispatches", () => {
|
|||||||
expect(isCommand(sent[0])).toBe(true);
|
expect(isCommand(sent[0])).toBe(true);
|
||||||
expect(sent[0]).toMatchObject({ type: "thread.stop", threadId });
|
expect(sent[0]).toMatchObject({ type: "thread.stop", threadId });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("a model change rides on the next message, and a mode change is its own command", async () => {
|
||||||
|
const { session, sent } = capturingSession();
|
||||||
|
const modelSelection = { instanceId: ProviderInstanceId.make("claude"), model: "claude-opus-5-5", options: [{ id: "effort", value: "high" }] };
|
||||||
|
await session.sendMessage(threadId, "carry on", "auto", modelSelection);
|
||||||
|
await session.setRuntimeMode(threadId, "approval-required");
|
||||||
|
expect(sent.every(isCommand)).toBe(true);
|
||||||
|
expect(sent[0]).toMatchObject({ type: "message.dispatch", modelSelection });
|
||||||
|
expect(sent[1]).toMatchObject({ type: "thread.runtime-mode.set", runtimeMode: "approval-required" });
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a new thread launches with a payload the server accepts", async () => {
|
||||||
|
const session = new T3Session();
|
||||||
|
let payload: unknown;
|
||||||
|
const rpc = { "orchestration.launchThread": (input: unknown) => ((payload = input), Effect.succeed({ threadId: ThreadId.make("new-1") })) };
|
||||||
|
(session as unknown as { connection: unknown }).connection = { rpc };
|
||||||
|
const id = await session.launchThread({
|
||||||
|
projectId: ProjectId.make("p1"),
|
||||||
|
title: "Fix the flaky test",
|
||||||
|
generateTitle: true,
|
||||||
|
modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5" },
|
||||||
|
runtimeMode: "full-access",
|
||||||
|
interactionMode: "default",
|
||||||
|
workspaceStrategy: { type: "worktree", baseRef: "main", startFromOrigin: true },
|
||||||
|
text: "Fix the flaky test",
|
||||||
|
});
|
||||||
|
expect(id as string).toBe("new-1");
|
||||||
|
expect(Schema.is(OrchestrationV2ThreadLaunchInput)(payload)).toBe(true);
|
||||||
|
expect(payload).toMatchObject({ initialMessage: { text: "Fix the flaky test", attachments: [] } });
|
||||||
|
});
|
||||||
});
|
});
|
||||||
+1
-1
@@ -28,7 +28,7 @@ describe("config", () => {
|
|||||||
|
|
||||||
test("labels settings for the settings view", () => {
|
test("labels settings for the settings view", () => {
|
||||||
const rows = settingRows({ ...DEFAULT_CONFIG, followUpBehavior: "queue" });
|
const rows = settingRows({ ...DEFAULT_CONFIG, followUpBehavior: "queue" });
|
||||||
expect(rows.map((row) => row.key)).toEqual(["followUpBehavior", "sendShortcut", "timestampFormat", "diffIgnoreWhitespace"]);
|
expect(rows.map((row) => row.key)).toEqual(["followUpBehavior", "sendShortcut", "timestampFormat", "diffIgnoreWhitespace", "notificationMode", "inAppNotificationsEnabled"]);
|
||||||
expect(rows[0]?.value).toBe("queues");
|
expect(rows[0]?.value).toBe("queues");
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import { describe, expect, test } from "bun:test";
|
||||||
|
import type { ModelSelection, ProviderInstanceId, ServerConfig } from "@t3tools/contracts";
|
||||||
|
|
||||||
|
import { modelSummary, optionValue, selectableProviders, withModel, withOption } from "../src/model/models.ts";
|
||||||
|
|
||||||
|
const effort = { id: "effort", label: "Thinking", type: "select", options: [{ id: "low", label: "Low" }, { id: "high", label: "High", isDefault: true }] } as const;
|
||||||
|
const fast = { id: "fast", label: "Fast", type: "boolean" } as const;
|
||||||
|
const config = {
|
||||||
|
providers: [
|
||||||
|
{
|
||||||
|
instanceId: "claude",
|
||||||
|
driver: "claude",
|
||||||
|
enabled: true,
|
||||||
|
models: [
|
||||||
|
{ slug: "opus", name: "Claude Opus", isCustom: false, isDefault: true, capabilities: { optionDescriptors: [effort, fast] } },
|
||||||
|
{ slug: "haiku", name: "Claude Haiku", isCustom: false, capabilities: { optionDescriptors: [fast] } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{ instanceId: "gone", driver: "codex", enabled: true, availability: "unavailable", models: [] },
|
||||||
|
{ instanceId: "off", driver: "codex", enabled: false, models: [] },
|
||||||
|
],
|
||||||
|
} as unknown as ServerConfig;
|
||||||
|
const opus: ModelSelection = { instanceId: "claude" as ProviderInstanceId, model: "opus" };
|
||||||
|
|
||||||
|
describe("models", () => {
|
||||||
|
test("lists only enabled, available providers", () => {
|
||||||
|
expect(selectableProviders(config).map((provider) => provider.instanceId as string)).toEqual(["claude"]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("summarises the model with its options, using defaults until chosen", () => {
|
||||||
|
expect(modelSummary(config, opus)).toBe("Claude Opus · High");
|
||||||
|
expect(modelSummary(config, withOption(withOption(opus, "effort", "low"), "fast", true))).toBe("Claude Opus · Low · Fast");
|
||||||
|
expect(optionValue(opus, effort)).toBe("high");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("switching model keeps only the options the new model has", () => {
|
||||||
|
const tuned = withOption(withOption(opus, "effort", "low"), "fast", true);
|
||||||
|
expect(withModel(config, tuned, "claude" as ProviderInstanceId, "haiku")).toEqual({ instanceId: "claude" as ProviderInstanceId, model: "haiku", options: [{ id: "fast", value: true }] });
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in new issue
Block a user