Move the draft, model picker and thread menu out of App into hooks

Each hook owns its state and returns the bindings for its keys, so App
only orders them.
This commit is contained in:
Callum Alpass committed 2026-11-02 22:48:41 +11:00
1 parent 8a0475ed63
commit 1ee6979e83
4 files changed
+525 -360

No files matched your search

+80 -360
View File
@@ -8,19 +8,16 @@ import {
togglePendingUserInputOptionSelection,
type PendingUserInputDraftAnswer,
} from "@t3tools/client-runtime/state/pending-user-input";
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import { ATTACHMENT_ONLY_BOOTSTRAP_PROMPT } from "@t3tools/shared/composerContextReferences";
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import { type ChatAttachment, type ContextMenuItem, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type ThreadId } from "@t3tools/contracts";
import { type DiscoveredLocalServer, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type ThreadId } from "@t3tools/contracts";
import { homedir } from "node:os";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ComposerContextRecord, OrchestrationMessageContext, ProjectEntry } from "@t3tools/contracts";
import type { ComposerContextRecord, ProjectEntry } from "@t3tools/contracts";
import type { FeedState, ServerConfigState, ShellState, T3Session, ThreadState, VcsState } from "../client/session.ts";
import { createAlerts, type Alert } from "../model/alerts.ts";
import { applyComposerItem, composerTrigger, cursorAtIndex, indexAtCursor, messageContext, PATH_SEARCH_LIMIT, pathItems, skillItems, slashItems, threadItems, type ComposerItem } from "../model/composerMenu.ts";
import { parseSnooze, pickSnooze, threadHasRuntime, threadMenu, topPinOrderKey, type ThreadActionMenuId } from "../model/threadMenu.ts";
import { draftDefaults, lockedProviderInstance, modelSummary, optionDescriptors, optionValue, optionValueLabel, providerName, RUNTIME_MODES, sameSelection, selectableProviders, withModel, withOption, type DraftThread } from "../model/models.ts";
import { modelSummary } from "../model/models.ts";
import { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts";
import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts";
import { paletteEntries, paletteGroups, pickerGroups, type PaletteCommand, type Picker, type PickerItem } from "../model/palette.ts";
@@ -33,7 +30,10 @@ import { ComposerMenu } from "./ComposerMenu.tsx";
import { ConfirmBar, type Confirmation } from "./ConfirmBar.tsx";
import { DetailsPanel } from "./DetailsPanel.tsx";
import { DiffView, type DiffState } from "./DiffView.tsx";
import { DraftView, type DraftLine } from "./DraftView.tsx";
import { DraftView } from "./DraftView.tsx";
import { useDraft } from "./useDraft.ts";
import { useModelPicker } from "./useModelPicker.ts";
import { useThreadMenu } from "./useThreadMenu.ts";
import { editInEditor } from "./editor.ts";
import { Palette } from "./Palette.tsx";
import { QuestionPanel } from "./QuestionPanel.tsx";
@@ -127,13 +127,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const [config, setConfig] = useState(props.config);
const [settingsIndex, setSettingsIndex] = useState<number | null>(null);
const [serverConfig, setServerConfig] = useState<ServerConfigState | null>(null);
/** A new thread before its first message; the composer sends it. */
const [draft, setDraft] = useState<DraftThread | null>(null);
const [picker, setPicker] = useState<Picker | null>(null);
const [pickerQuery, setPickerQuery] = useState("");
const [pickerIndex, setPickerIndex] = useState(0);
/** Model changes waiting for each thread's next message, as the web composer holds them. */
const [pendingModels, setPendingModels] = useState<ReadonlyMap<ThreadId, ModelSelection>>(new Map());
/** Idle subagents the shell leaves out, fetched when you open one. */
const [familyShells, setFamilyShells] = useState<ReadonlyMap<ThreadId, OrchestrationV2ThreadShell>>(new Map());
const [confirmation, setConfirmation] = useState<Confirmation | null>(null);
@@ -199,6 +195,24 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const selectedIndex = rows.findIndex((row) => row.thread.id === threadId);
const threadRow = allRows.find((row) => row.thread.id === threadId);
const threadShell = threadRow?.thread ?? shell.snapshot?.threads.find((thread) => thread.id === threadId) ?? library.archive?.threads.find((thread) => thread.id === threadId) ?? library.merged?.threads.find((thread) => thread.id === threadId) ?? (threadId ? familyShells.get(threadId) : undefined);
const newThread = useDraft({
session,
snapshot: shell.snapshot,
config: serverConfig?.config ?? null,
thread: threadShell,
openPicker: (next) => openPicker(next),
say: (text, bad) => say(text, bad),
onStart: () => {
setDiff(null);
setSettingsIndex(null);
setMode("input");
},
onLaunched: (id) => {
drafts.current.delete(DRAFT_KEY);
openThread(id);
},
});
const draft = newThread.draft;
const composerKey: string = draft ? DRAFT_KEY : (threadId ?? "");
const activeComposerKey = useRef(composerKey);
activeComposerKey.current = composerKey;
@@ -214,7 +228,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setSelectedId(id);
setDiff(null);
setSettingsIndex(null);
setDraft(null);
newThread.cancel();
setDetailsSelected(null);
setMode((current) => (current === "details" || current === "settings" || current === "pull-request" ? "nav" : current));
}, []);
@@ -374,13 +388,24 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
(error) => say(`${label} failed: ${messageOf(error)}`, true),
);
};
const models = useModelPicker({
session,
config: serverConfig?.config ?? null,
draft,
updateDraft: newThread.update,
thread: threadShell,
projection,
openPicker: (next) => openPicker(next),
run,
say,
});
const queue = useQueue({
session,
threadId: draft ? undefined : threadId,
projection,
composer: () => composerRef.current,
openQuestionCount: current?.pending.userInputs.length ?? 0,
modelSelection: threadId ? pendingModels.get(threadId) : undefined,
modelSelection: models.pendingFor(threadId),
run,
say,
toInput: () => setMode("input"),
@@ -547,310 +572,36 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
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.
/** The web sidebar's thread menu as a picker: separators become groups, submenus open their own picker. */
const openThreadMenu = (target: OrchestrationV2ThreadShell) => {
const menu = threadMenu({ thread: target, config: providerConfig, timestampFormat: config.timestampFormat });
const toPicker = (title: string, items: readonly ContextMenuItem<ThreadActionMenuId>[]): Picker => {
const groups: { label: string; items: PickerItem[] }[] = [{ label: title, items: [] }];
for (const item of items) {
if (item.separatorBefore && groups[groups.length - 1]!.items.length > 0) groups.push({ label: "", items: [] });
const hint = item.disabled ? "unavailable" : item.checked ? "current" : item.children ? "›" : undefined;
groups[groups.length - 1]!.items.push({
id: `thread-menu:${item.id}`,
title: item.label,
...(hint ? { hint } : {}),
run: () => {
if (item.disabled) return say(`${item.label} is unavailable for this thread right now.`, true);
if (item.children) return openPicker(toPicker(`${target.title || "New thread"} › ${item.label}`, item.children));
runThreadAction(target, item.id, menu.snoozePresets);
},
});
// A submenu's items are found by typing at the top too: "thread id" finds Copy › Thread ID.
for (const child of item.disabled ? [] : (item.children ?? [])) {
if (child.disabled) continue;
groups[groups.length - 1]!.items.push({ id: `thread-menu:${child.id}`, title: `${item.label} › ${child.label}`, ...(child.checked ? { hint: "current" } : {}), searchOnly: true, run: () => runThreadAction(target, child.id, menu.snoozePresets) });
}
}
return { placeholder: "Thread actions", groups };
};
openPicker(toPicker(target.title || "New thread", menu.items));
};
const openSelectedThreadMenu = () => threadShell && openThreadMenu(threadShell);
const runThreadAction = (target: OrchestrationV2ThreadShell, action: ThreadActionMenuId, snoozePresets: ReturnType<typeof threadMenu>["snoozePresets"]) => {
const id = target.id;
const title = target.title || "New thread";
const leave = () => {
const draftProject = newThread.project;
const currentModel = models.current;
const runtimeMode = models.runtimeMode;
const threadMenu = useThreadMenu({
session,
renderer,
snapshot: shell.snapshot,
config: providerConfig,
timestampFormat: config.timestampFormat,
thread: threadShell,
openPicker,
confirm: (confirmation, prefill) => {
confirm(confirmation);
if (prefill) setConfirmMessage(prefill);
},
run,
say,
openThread,
openFind,
left: (id) => {
if (threadId === id) setSelectedId(undefined);
};
if (action === "snooze:custom") {
confirm({
title: `Snooze "${title}"`,
detail: "For a while (45m, 3h, 2d, 1w) or until a time (17:30).",
message: { placeholder: "3h" },
confirmLabel: "snooze",
run: (text) => {
const wake = parseSnooze(text);
if (!wake) return say("Type a duration like 3h or 2d, or a time like 17:30.", true);
run(`Snoozed until ${wake.toLocaleString(undefined, { weekday: "short", hour: "numeric", minute: "2-digit" })}`, () => session.snoozeThread(id, wake.toISOString()));
},
});
return;
}
if (action.startsWith("snooze:")) {
const preset = pickSnooze(snoozePresets, action.slice("snooze:".length), providerConfig, config.timestampFormat);
if (!preset) return say("That snooze time has passed. Choose another time.", true);
return run(`Snoozed until ${preset.whenLabel}`, () => session.snoozeThread(id, preset.snoozedUntil));
}
switch (action) {
case "find":
openThread(id);
return openFind();
case "settle":
return run("Settled", () => session.settleThread(id));
case "unsettle":
return run("Un-settled", () => session.unsettleThread(id));
case "unsnooze":
return run("Woke the thread", () => session.unsnoozeThread(id));
case "pin":
return run("Pinned", () => session.pinThread(id, topPinOrderKey(shell.snapshot)));
case "unpin":
return run("Unpinned", () => session.unpinThread(id));
case "auto-settle:enabled":
case "auto-settle:disabled":
return run(action === "auto-settle:enabled" ? "Auto-settle on" : "Auto-settle off", () => session.setAutoSettle(id, action === "auto-settle:enabled"));
case "regenerate-title":
return run("Regenerating the title", () => session.regenerateTitle(id));
case "mark-unread":
// Opening a thread marks it read; stay unread until you open it again.
noVisit.current = id;
return run("Marked unread", () => session.markUnread(id));
case "rename":
confirm({
title: "Rename thread",
message: { placeholder: title },
confirmLabel: "rename",
run: (text) => {
const next = text.trim();
if (next && next !== target.title) run("Renamed", () => session.renameThread(id, next));
},
});
setConfirmMessage(target.title);
return;
case "new-thread-on-branch": {
const project = shell.snapshot?.projects.find((candidate) => candidate.id === target.projectId);
if (!project) return say("The thread's project is gone.", true);
setDraft({
...draftDefaults({ config: providerConfig, project, currentModel: target.modelSelection, projectHasThreads: true }),
envMode: target.worktreePath ? "worktree" : "local",
...(target.worktreePath ? { existingWorktree: { path: target.worktreePath, branch: target.branch } } : {}),
});
setDiff(null);
setSettingsIndex(null);
setMode("input");
return;
}
case "copy-path": {
const path = target.worktreePath ?? shell.snapshot?.projects.find((candidate) => candidate.id === target.projectId)?.workspaceRoot;
if (!path) return say("This thread does not have a workspace path to copy.", true);
copyText(renderer, path);
return say(`Path copied: ${path}`);
}
case "copy-branch":
if (!target.branch) return;
copyText(renderer, target.branch);
return say(`Branch copied: ${target.branch}`);
case "copy-thread": {
const environmentId = providerConfig?.environment.environmentId;
if (!environmentId) return say("Server details are still loading.", true);
copyText(renderer, threadChipCopyTarget({ environmentId, threadId: id }, title).value);
return say(`Thread copied: ${title}`);
}
case "copy-thread-id":
copyText(renderer, id);
return say(`Thread ID copied: ${id}`);
case "archive":
return run("Archived", async () => {
await session.archiveThread(id);
leave();
});
case "delete":
// The web confirms deletes by default (confirmThreadDelete).
confirm({
title: `Delete thread "${title}"?`,
detail: `This permanently clears conversation history for this thread.${target.worktreePath ? " Its worktree stays on disk." : ""}`,
confirmLabel: "delete",
run: () =>
run("Deleted", async () => {
await session.deleteThread(id, threadHasRuntime(target, providerConfig));
leave();
}),
});
return;
default:
return;
}
};
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 = () => {
if (!draft) return;
const { existingWorktree: _, ...rest } = draft;
setDraft({ ...rest, envMode: draft.existingWorktree ? "local" : draft.envMode === "local" ? "worktree" : "local" });
};
const launchDraft = (text: string, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []) => {
if (!draft || !draftProject) return;
const launching = draft;
const project = draftProject;
say("Starting thread…");
void (async () => {
let workspaceStrategy: { type: "root" } | { type: "existing_worktree"; worktreePath: string } | { type: "worktree"; baseRef: string; startFromOrigin?: boolean } = { type: "root" };
if (launching.existingWorktree) workspaceStrategy = { type: "existing_worktree", worktreePath: launching.existingWorktree.path };
else 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: [...attachments] }),
generateTitle: true,
modelSelection: launching.modelSelection,
runtimeMode: launching.runtimeMode,
interactionMode: "default",
workspaceStrategy,
text,
context,
attachments,
});
})().then(
(id) => {
drafts.current.delete(DRAFT_KEY);
openThread(id);
say("Thread started");
},
(error) => say(`Could not start the thread: ${messageOf(error)}`, true),
);
};
},
keepUnread: (id) => (noVisit.current = id),
startDraftOn: (target) => {
const targetProject = shell.snapshot?.projects.find((candidate) => candidate.id === target.projectId);
if (!targetProject) return say("The thread's project is gone.", true);
newThread.start({ project: targetProject, model: target.modelSelection, worktree: target.worktreePath ? { path: target.worktreePath, branch: target.branch } : null });
},
});
const workspace = useWorkspace({ session, renderer, live, thread: threadShell, project, serverConfig: serverConfig?.config ?? null, draft: draft !== null, diff, openPicker, confirm, run, say });
@@ -939,7 +690,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
if (!text && attachedFiles.length === 0) return;
const taken = attach.take();
clearComposer();
return launchDraft(text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, context, taken);
return newThread.launch(text || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT, context, taken);
}
if (!threadId) return;
if (pendingInput && questionDraft) {
@@ -962,14 +713,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
return run("Declined and redirected", () => session.sendMessage(threadId, sendText, "steer", undefined, context, taken));
}
const dispatchMode = resolveComposerDispatchMode({ running: working, alternateModifier: alternate, activeTurnDefault: config.followUpBehavior });
const pendingModel = pendingModels.get(threadId);
if (pendingModel) {
setPendingModels((previous) => {
const next = new Map(previous);
next.delete(threadId);
return next;
});
}
const pendingModel = models.take(threadId);
run(dispatchMode === "queue" ? "Queued" : dispatchMode === "steer" ? "Steered" : "Sent", () => session.sendMessage(threadId, sendText, dispatchMode, pendingModel, context, taken));
};
@@ -1015,21 +759,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
setMode("pull-request");
},
hideView: () => setMode("nav"),
startDraftFromPullRequest: (targetProject, prepared) => {
setDraft({
...draftDefaults({
config: providerConfig,
project: targetProject,
currentModel: threadShell?.modelSelection ?? null,
projectHasThreads: shell.snapshot?.threads.some((candidate) => candidate.projectId === targetProject.id) ?? false,
}),
envMode: prepared.worktreePath ? "worktree" : "local",
...(prepared.worktreePath ? { existingWorktree: { path: prepared.worktreePath, branch: prepared.branch } } : {}),
});
setDiff(null);
setSettingsIndex(null);
setMode("input");
},
startDraftFromPullRequest: (targetProject, prepared) => newThread.start({ project: targetProject, worktree: prepared.worktreePath ? { path: prepared.worktreePath, branch: prepared.branch } : null }),
});
// The command palette: everything the keys do, plus what the details panel offers.
@@ -1121,7 +851,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}
syncComposerState();
setComposerLines(composerLineCount(composer));
if (item.action === "model") openModelPicker();
if (item.action === "model") models.open();
};
// Keys. Each state has its bindings in hint order; the first one that takes a key runs it.
// The same bindings name the hints, make them clickable, and give the palette its shortcuts.
@@ -1164,13 +894,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
const scrollDiffDown: Binding = { keys: ["j", "↓"], label: "j/k", run: () => scrollBy(1), hint: "scroll" };
const closeDiff: Binding = { keys: ["esc", "q"], run: () => setDiff(null), hint: "close diff" };
const typeKey: Binding = { keys: ["i", "enter", "tab"], run: toInput, hint: "type", ...(threadId ? { command: { id: "type", title: "Write a message", keywords: ["compose", "send", "steer"] } } : {}) };
const projectKey: Binding | null = draft ? { keys: ["p"], run: openProjectPicker, hint: "project", command: { id: "draft-project", title: "New thread: choose project" } } : null;
const modelKey: Binding | null = currentModel ? { keys: ["m"], run: openModelPicker, hint: "model", command: { id: "model", title: "Change model, options or mode", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] } } : null;
const worktreeKey: Binding | null = draft
? { keys: ["w"], run: toggleWorkspace, hint: "worktree", command: { id: "draft-workspace", title: draft.envMode === "local" && !draft.existingWorktree ? "New thread: use a new worktree" : "New thread: run in the project folder", keywords: ["worktree", "local", "branch"] } }
: null;
const projectKey = newThread.keys?.project;
const modelKey = models.key;
const worktreeKey = newThread.keys?.workspace;
const detailsKey: Binding = { keys: ["l", "→"], run: focusDetails, hint: "details", ...(threadShell ? { command: { id: "focus-details", title: "Focus thread details" } } : {}) };
const cancelDraftKey: Binding | null = draft ? { keys: ["esc"], run: () => setDraft(null), hint: "cancel", command: { id: "draft-cancel", title: "Cancel new thread", keywords: ["discard"] } } : null;
const cancelDraftKey = newThread.keys?.cancel;
const navKeys = keys(
diff && [scrollDiffDown, { keys: ["k", "↑"], run: () => scrollBy(-1) }, closeDiff],
turns.bindings,
@@ -1194,9 +922,9 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
!attached && { keys: ["/"], run: () => setMode("filter"), hint: "filter", command: { id: "filter", title: "Filter threads", keywords: ["search"] } },
typeKey,
projectKey,
{ keys: ["c"], run: startDraft, hint: "new", command: { id: "new-thread", title: "New thread", keywords: ["create", "start", "chat"] } },
{ keys: ["c"], run: () => newThread.start(), hint: "new", command: { id: "new-thread", title: "New thread", keywords: ["create", "start", "chat"] } },
hasComposer && attach.commands.map((command) => fromCommand(command, command.id === "attach-file" ? "attach" : undefined)),
threadShell && { keys: ["."], run: openSelectedThreadMenu, hint: "actions", command: { id: "thread-menu", title: "Thread actions…", keywords: ["settle", "pin", "snooze", "rename", "archive", "delete", "copy", "unread", "menu"] } },
threadMenu.key,
modelKey,
worktreeKey,
hinted(terminalKey, "terminal"),
@@ -1492,7 +1220,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
: "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 pendingModel = !draft && threadShell ? pendingModels.get(threadShell.id) : undefined;
const pendingModel = draft ? undefined : models.pendingFor(threadShell?.id);
const footer =
currentModel && runtimeMode
? [
@@ -1502,14 +1230,6 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
.filter(Boolean)
.join(" · ")
: "";
const draftLines: DraftLine[] = draft
? [
{ key: "project", label: "Project", value: draftProject?.title ?? "—", shortcut: "p", onPick: openProjectPicker },
{ key: "model", label: "Model", value: modelSummary(providerConfig, draft.modelSelection), shortcut: "m", onPick: openModelPicker },
{ key: "mode", label: "Mode", value: RUNTIME_MODE_LABELS[draft.runtimeMode] ?? draft.runtimeMode, shortcut: "m", onPick: openModelPicker },
{ key: "workspace", label: "Runs in", value: draft.existingWorktree ? `the ${draft.existingWorktree.branch ?? "thread's"} worktree` : draft.envMode === "worktree" ? "a new worktree from the default branch" : "the project folder", shortcut: "w", onPick: toggleWorkspace },
]
: [];
const detailsPanel = (inPlace: boolean) => (
<DetailsPanel
details={details}
@@ -1566,7 +1286,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
}}
onMenu={(id) => {
const target = allRows.find((row) => row.thread.id === id)?.thread;
if (target) openThreadMenu(target);
if (target) threadMenu.open(target);
}}
onUnfold={() => setShowFolded(true)}
showMore={unfold && library.hasOlder}
@@ -1595,7 +1315,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
) : diff ? (
<DiffView diff={diff} scrollRef={scrollRef} selected={turns.diffContext.selected} expanded={turns.diffContext.expanded} onFile={turns.diffContext.click} />
) : draft ? (
<DraftView lines={draftLines} />
<DraftView lines={newThread.lines(models.open)} />
) : threadId && detailsInPlace && mode !== "find" ? (
<box flexGrow={1} minHeight={0} flexDirection="column">
{detailsPanel(true)}
@@ -1701,7 +1421,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C
</box>
) : null}
{threadId || draft ? (
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2} onMouseDown={openModelPicker}>
<box flexDirection="row" height={1} flexShrink={0} paddingLeft={2} paddingRight={2} onMouseDown={models.open}>
<text fg={colors.faint}>{footer}</text>
{pendingModel ? <text fg={colors.accent}>{" · next message"}</text> : null}
</box>
+147
View File
@@ -0,0 +1,147 @@
import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
import type { ChatAttachment, ModelSelection, OrchestrationMessageContext, OrchestrationProjectShell, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
import { homedir } from "node:os";
import { useState } from "react";
import type { T3Session } from "../client/session.ts";
import { RUNTIME_MODE_LABELS } from "../model/details.ts";
import type { Binding } from "../model/keymap.ts";
import { draftDefaults, modelSummary, type DraftThread } from "../model/models.ts";
import type { Picker } from "../model/palette.ts";
import type { DraftLine } from "./DraftView.tsx";
type WorkspaceStrategy = { type: "root" } | { type: "existing_worktree"; worktreePath: string } | { type: "worktree"; baseRef: string; startFromOrigin?: boolean };
/**
* A new thread, as the web's: a local draft of where it runs and with what, which becomes a
* thread when its first message is sent.
*/
export function useDraft(deps: {
readonly session: T3Session;
readonly snapshot: OrchestrationV2ShellSnapshot | null;
readonly config: ServerConfig | null;
/** The open thread, whose project and model a new draft starts from. */
readonly thread: OrchestrationV2ThreadShell | undefined;
readonly openPicker: (picker: Picker) => void;
readonly say: (text: string, bad?: boolean) => void;
/** A draft started: show it and take the keys to the composer. */
readonly onStart: () => void;
/** The thread the draft became. */
readonly onLaunched: (threadId: ThreadId) => void;
}) {
const { session, snapshot, config, say } = deps;
const [draft, setDraft] = useState<DraftThread | null>(null);
const projects = snapshot?.projects ?? [];
const project = draft ? projects.find((candidate) => candidate.id === draft.projectId) : undefined;
const hasThreads = (projectId: string) => snapshot?.threads.some((candidate) => candidate.projectId === projectId) ?? false;
/**
* Starts a draft: in the open thread's project with its model unless told otherwise, and in
* an existing worktree when one is given (a thread's branch, a checked-out pull request).
* Without `worktree`, the project's settings choose between its folder and a new worktree.
*/
const start = (options: { readonly project?: OrchestrationProjectShell; readonly model?: ModelSelection | null; readonly worktree?: { readonly path: string; readonly branch: string | null } | null } = {}) => {
const target = options.project ?? projects.find((candidate) => candidate.id === deps.thread?.projectId) ?? projects[0];
if (!target) return say("No projects on this server yet; add one in T3 Code.", true);
const defaults = draftDefaults({ config, project: target, currentModel: options.model === undefined ? (deps.thread?.modelSelection ?? null) : options.model, projectHasThreads: hasThreads(target.id) });
const worktree = options.worktree;
// null: a thread or pull request without a worktree, so the project folder.
setDraft(worktree ? { ...defaults, envMode: "worktree", existingWorktree: { path: worktree.path, branch: worktree.branch } } : worktree === null ? { ...defaults, envMode: "local" } : defaults);
deps.onStart();
};
const update = (patch: Partial<DraftThread>) => {
if (draft) setDraft({ ...draft, ...patch });
};
const openProjectPicker = () => {
if (!draft) return;
deps.openPicker({
placeholder: "Project",
groups: [
{
label: "Projects",
items: projects.map((candidate) => ({
id: `project:${candidate.id}`,
title: candidate.title,
hint: candidate.id === draft.projectId ? "current" : candidate.workspaceRoot.replace(homedir(), "~"),
run: () => setDraft(draftDefaults({ config, project: candidate, currentModel: draft.modelSelection, projectHasThreads: hasThreads(candidate.id) })),
})),
},
],
});
};
/** Project folder ↔ new worktree; an existing worktree goes back to the project folder. */
const toggleWorkspace = () => {
if (!draft) return;
const { existingWorktree: _, ...rest } = draft;
setDraft({ ...rest, envMode: draft.existingWorktree ? "local" : draft.envMode === "local" ? "worktree" : "local" });
};
/** Sends the first message, which creates the thread. */
const launch = (text: string, context?: OrchestrationMessageContext, attachments: readonly ChatAttachment[] = []) => {
if (!draft || !project) return;
const launching = draft;
const root = project.workspaceRoot;
say("Starting thread…");
const workspaceStrategy = async (): Promise<WorkspaceStrategy> => {
if (launching.existingWorktree) return { type: "existing_worktree", worktreePath: launching.existingWorktree.path };
if (launching.envMode !== "worktree") return { type: "root" };
// A worktree starts from the default branch; outside a git repository it runs in place, as the web's.
const refs = await session.defaultRef(root);
return refs.isRepo && refs.ref ? { type: "worktree", baseRef: refs.ref.name, startFromOrigin: config?.settings.newWorktreesStartFromOrigin ?? true } : { type: "root" };
};
workspaceStrategy()
.then((strategy) =>
session.launchThread({
projectId: launching.projectId,
title: deriveThreadTitleSeed({ text, attachments: [...attachments] }),
generateTitle: true,
modelSelection: launching.modelSelection,
runtimeMode: launching.runtimeMode,
interactionMode: "default",
workspaceStrategy: strategy,
text,
context,
attachments,
}),
)
.then(
(id) => {
setDraft(null);
deps.onLaunched(id);
say("Thread started");
},
(error) => say(`Could not start the thread: ${error instanceof Error ? error.message : String(error)}`, true),
);
};
const cancel = () => setDraft(null);
/** The draft's settings as the draft view lists them; each opens what changes it. */
const lines = (openModelPicker: () => void): DraftLine[] =>
draft
? [
{ key: "project", label: "Project", value: project?.title ?? "—", shortcut: "p", onPick: openProjectPicker },
{ key: "model", label: "Model", value: modelSummary(config, draft.modelSelection), shortcut: "m", onPick: openModelPicker },
{ key: "mode", label: "Mode", value: RUNTIME_MODE_LABELS[draft.runtimeMode] ?? draft.runtimeMode, shortcut: "m", onPick: openModelPicker },
{ key: "workspace", label: "Runs in", value: draft.existingWorktree ? `the ${draft.existingWorktree.branch ?? "thread's"} worktree` : draft.envMode === "worktree" ? "a new worktree from the default branch" : "the project folder", shortcut: "w", onPick: toggleWorkspace },
]
: [];
const keys = draft
? {
project: { keys: ["p"], run: openProjectPicker, hint: "project", command: { id: "draft-project", title: "New thread: choose project" } },
workspace: {
keys: ["w"],
run: toggleWorkspace,
hint: "worktree",
command: { id: "draft-workspace", title: draft.envMode === "local" && !draft.existingWorktree ? "New thread: use a new worktree" : "New thread: run in the project folder", keywords: ["worktree", "local", "branch"] },
},
cancel: { keys: ["esc"], run: cancel, hint: "cancel", command: { id: "draft-cancel", title: "Cancel new thread", keywords: ["discard"] } },
} satisfies Record<string, Binding>
: null;
return { draft, project, start, update, launch, cancel, lines, keys };
}
+122
View File
@@ -0,0 +1,122 @@
import type { ModelSelection, OrchestrationV2ThreadProjection, ProviderOptionDescriptor, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
import { useState } from "react";
import type { T3Session } from "../client/session.ts";
import { RUNTIME_MODE_LABELS } from "../model/details.ts";
import type { Binding } from "../model/keymap.ts";
import { lockedProviderInstance, optionDescriptors, optionValue, optionValueLabel, providerName, RUNTIME_MODES, sameSelection, selectableProviders, withModel, withOption, type DraftThread } from "../model/models.ts";
import type { Picker, PickerItem } from "../model/palette.ts";
type RuntimeMode = (typeof RUNTIME_MODES)[number];
/**
* Model, options and mode, for the draft or the open thread. As in the web composer, a thread's
* model change waits for its next message; its mode changes straight away.
*/
export function useModelPicker(deps: {
readonly session: T3Session;
readonly config: ServerConfig | null;
readonly draft: DraftThread | null;
readonly updateDraft: (patch: Partial<DraftThread>) => void;
readonly thread: OrchestrationV2ThreadShell | undefined;
readonly projection: OrchestrationV2ThreadProjection | null | undefined;
readonly openPicker: (picker: Picker) => void;
readonly run: (label: string, action: () => Promise<unknown>) => void;
readonly say: (text: string, bad?: boolean) => void;
}) {
const { config, draft, thread } = deps;
const [pending, setPending] = useState<ReadonlyMap<ThreadId, ModelSelection>>(new Map());
const current: ModelSelection | null = draft ? draft.modelSelection : thread ? (pending.get(thread.id) ?? thread.modelSelection) : null;
const runtimeMode = draft ? draft.runtimeMode : thread?.runtimeMode;
const setPendingFor = (id: ThreadId, selection: ModelSelection | null) =>
setPending((previous) => {
const next = new Map(previous);
if (selection) next.set(id, selection);
else next.delete(id);
return next;
});
const setModel = (selection: ModelSelection) => {
if (draft) return deps.updateDraft({ modelSelection: selection });
if (!thread) return;
setPendingFor(thread.id, sameSelection(config, selection, thread.modelSelection) ? null : selection);
};
const setRuntime = (next: RuntimeMode) => {
if (draft) return deps.updateDraft({ runtimeMode: next });
if (thread) deps.run(`Mode: ${RUNTIME_MODE_LABELS[next] ?? next}`, () => deps.session.setRuntimeMode(thread.id, next));
};
/** A choice of option values, in a picker of its own. */
const openChoices = (selection: ModelSelection, descriptor: Exclude<ProviderOptionDescriptor, { type: "boolean" }>) =>
deps.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)),
})),
},
],
});
/** Mode, then options, then each provider's models. */
const open = () => {
const selection = current;
if (!selection) return;
if (!config) return deps.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(deps.projection);
const groups: { label: string; items: PickerItem[] }[] = [];
if (runtimeMode) {
groups.push({
label: "Mode",
items: RUNTIME_MODES.map((candidate) => ({
id: `mode:${candidate}`,
title: RUNTIME_MODE_LABELS[candidate] ?? candidate,
...(candidate === runtimeMode ? { hint: "current" } : {}),
run: () => setRuntime(candidate),
})),
});
}
const options: PickerItem[] = optionDescriptors(config, selection).map((descriptor) => ({
id: `option:${descriptor.id}`,
title: `${descriptor.label}: ${optionValueLabel(descriptor, optionValue(selection, descriptor))}`,
run: () => (descriptor.type === "boolean" ? setModel(withOption(selection, descriptor.id, optionValue(selection, descriptor) !== true)) : openChoices(selection, descriptor)),
}));
if (options.length > 0) groups.push({ label: "Options", items: options });
for (const provider of selectableProviders(config)) {
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(config, selection, provider.instanceId, model.slug)),
})),
});
}
deps.openPicker({ placeholder: locked ? "Model, options and mode (this thread stays on its provider)" : "Model, options and mode", groups });
};
/** The model change waiting for a thread's next message, taken as that message goes. */
const take = (id: ThreadId): ModelSelection | undefined => {
const selection = pending.get(id);
if (selection) setPendingFor(id, null);
return selection;
};
const key: Binding | null = current
? { keys: ["m"], run: open, hint: "model", command: { id: "model", title: "Change model, options or mode", keywords: ["provider", "thinking", "reasoning", "effort", "speed", "fast", "access", "approval"] } }
: null;
return { current, runtimeMode, pendingFor: (id: ThreadId | undefined) => (id ? pending.get(id) : undefined), take, open, key };
}
+176
View File
@@ -0,0 +1,176 @@
import type { CliRenderer } from "@opentui/core";
import { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference";
import type { ContextMenuItem, OrchestrationV2ShellSnapshot, OrchestrationV2ThreadShell, ServerConfig, ThreadId } from "@t3tools/contracts";
import type { T3Session } from "../client/session.ts";
import type { Tui3Config } from "../config.ts";
import type { Binding } from "../model/keymap.ts";
import type { Picker, PickerItem } from "../model/palette.ts";
import { parseSnooze, pickSnooze, threadHasRuntime, threadMenu, topPinOrderKey, type ThreadActionMenuId } from "../model/threadMenu.ts";
import type { Confirmation } from "./ConfirmBar.tsx";
import { copyText } from "./terminalOut.ts";
type SnoozePresets = ReturnType<typeof threadMenu>["snoozePresets"];
/** The web sidebar's thread menu as a picker: separators become groups, submenus open their own picker. */
export function useThreadMenu(deps: {
readonly session: T3Session;
readonly renderer: CliRenderer;
readonly snapshot: OrchestrationV2ShellSnapshot | null;
readonly config: ServerConfig | null;
readonly timestampFormat: Tui3Config["timestampFormat"];
/** The open thread: the menu's key and palette command act on it. */
readonly thread: OrchestrationV2ThreadShell | undefined;
readonly openPicker: (picker: Picker) => void;
/** `prefill` puts text in the confirmation's message box. */
readonly confirm: (confirmation: Confirmation, prefill?: string) => void;
readonly run: (label: string, action: () => Promise<unknown>) => void;
readonly say: (text: string, bad?: boolean) => void;
readonly openThread: (id: ThreadId) => void;
readonly openFind: () => void;
/** The thread was archived or deleted: stop showing it. */
readonly left: (id: ThreadId) => void;
/** Marked unread: don't mark it read again until it's opened again. */
readonly keepUnread: (id: ThreadId) => void;
readonly startDraftOn: (target: OrchestrationV2ThreadShell) => void;
}) {
const { session, renderer, config, run, say } = deps;
const copy = (text: string, message: string) => {
copyText(renderer, text);
say(message);
};
const snooze = (target: OrchestrationV2ThreadShell, action: ThreadActionMenuId, presets: SnoozePresets) => {
const id = target.id;
if (action === "snooze:custom") {
return deps.confirm({
title: `Snooze "${target.title || "New thread"}"`,
detail: "For a while (45m, 3h, 2d, 1w) or until a time (17:30).",
message: { placeholder: "3h" },
confirmLabel: "snooze",
run: (text) => {
const wake = parseSnooze(text);
if (!wake) return say("Type a duration like 3h or 2d, or a time like 17:30.", true);
run(`Snoozed until ${wake.toLocaleString(undefined, { weekday: "short", hour: "numeric", minute: "2-digit" })}`, () => session.snoozeThread(id, wake.toISOString()));
},
});
}
const preset = pickSnooze(presets, action.slice("snooze:".length), config, deps.timestampFormat);
if (!preset) return say("That snooze time has passed. Choose another time.", true);
run(`Snoozed until ${preset.whenLabel}`, () => session.snoozeThread(id, preset.snoozedUntil));
};
const runAction = (target: OrchestrationV2ThreadShell, action: ThreadActionMenuId, presets: SnoozePresets) => {
const id = target.id;
const title = target.title || "New thread";
const workspacePath = target.worktreePath ?? deps.snapshot?.projects.find((candidate) => candidate.id === target.projectId)?.workspaceRoot;
if (action.startsWith("snooze:")) return snooze(target, action, presets);
switch (action) {
case "find":
deps.openThread(id);
return deps.openFind();
case "settle":
return run("Settled", () => session.settleThread(id));
case "unsettle":
return run("Un-settled", () => session.unsettleThread(id));
case "unsnooze":
return run("Woke the thread", () => session.unsnoozeThread(id));
case "pin":
return run("Pinned", () => session.pinThread(id, topPinOrderKey(deps.snapshot)));
case "unpin":
return run("Unpinned", () => session.unpinThread(id));
case "auto-settle:enabled":
case "auto-settle:disabled":
return run(action === "auto-settle:enabled" ? "Auto-settle on" : "Auto-settle off", () => session.setAutoSettle(id, action === "auto-settle:enabled"));
case "regenerate-title":
return run("Regenerating the title", () => session.regenerateTitle(id));
case "mark-unread":
deps.keepUnread(id);
return run("Marked unread", () => session.markUnread(id));
case "rename":
return deps.confirm(
{
title: "Rename thread",
message: { placeholder: title },
confirmLabel: "rename",
run: (text) => {
const next = text.trim();
if (next && next !== target.title) run("Renamed", () => session.renameThread(id, next));
},
},
target.title,
);
case "new-thread-on-branch":
return deps.startDraftOn(target);
case "copy-path":
if (!workspacePath) return say("This thread does not have a workspace path to copy.", true);
return copy(workspacePath, `Path copied: ${workspacePath}`);
case "copy-branch":
if (target.branch) copy(target.branch, `Branch copied: ${target.branch}`);
return;
case "copy-thread": {
const environmentId = config?.environment.environmentId;
if (!environmentId) return say("Server details are still loading.", true);
return copy(threadChipCopyTarget({ environmentId, threadId: id }, title).value, `Thread copied: ${title}`);
}
case "copy-thread-id":
return copy(id, `Thread ID copied: ${id}`);
case "archive":
return run("Archived", async () => {
await session.archiveThread(id);
deps.left(id);
});
case "delete":
// The web confirms deletes by default (confirmThreadDelete).
return deps.confirm({
title: `Delete thread "${title}"?`,
detail: `This permanently clears conversation history for this thread.${target.worktreePath ? " Its worktree stays on disk." : ""}`,
confirmLabel: "delete",
run: () =>
run("Deleted", async () => {
await session.deleteThread(id, threadHasRuntime(target, config));
deps.left(id);
}),
});
default:
return;
}
};
const open = (target: OrchestrationV2ThreadShell) => {
const menu = threadMenu({ thread: target, config, timestampFormat: deps.timestampFormat });
const toPicker = (title: string, items: readonly ContextMenuItem<ThreadActionMenuId>[]): Picker => {
const groups: { label: string; items: PickerItem[] }[] = [{ label: title, items: [] }];
for (const item of items) {
if (item.separatorBefore && groups[groups.length - 1]!.items.length > 0) groups.push({ label: "", items: [] });
const group = groups[groups.length - 1]!;
const hint = item.disabled ? "unavailable" : item.checked ? "current" : item.children ? "›" : undefined;
group.items.push({
id: `thread-menu:${item.id}`,
title: item.label,
...(hint ? { hint } : {}),
run: () => {
if (item.disabled) return say(`${item.label} is unavailable for this thread right now.`, true);
if (item.children) return deps.openPicker(toPicker(`${target.title || "New thread"} › ${item.label}`, item.children));
runAction(target, item.id, menu.snoozePresets);
},
});
// A submenu's items are found by typing at the top too: "thread id" finds Copy › Thread ID.
for (const child of item.disabled ? [] : (item.children ?? [])) {
if (child.disabled) continue;
group.items.push({ id: `thread-menu:${child.id}`, title: `${item.label} › ${child.label}`, ...(child.checked ? { hint: "current" } : {}), searchOnly: true, run: () => runAction(target, child.id, menu.snoozePresets) });
}
}
return { placeholder: "Thread actions", groups };
};
deps.openPicker(toPicker(target.title || "New thread", menu.items));
};
const thread = deps.thread;
const key: Binding | null = thread
? { keys: ["."], run: () => open(thread), hint: "actions", command: { id: "thread-menu", title: "Thread actions…", keywords: ["settle", "pin", "snooze", "rename", "archive", "delete", "copy", "unread", "menu"] } }
: null;
return { open, key };
}