diff --git a/README.md b/README.md index 5bef157..901d0d3 100644 --- a/README.md +++ b/README.md @@ -51,6 +51,7 @@ Navigation: | --- | --- | | `j`/`k`, arrows | next / previous thread (scroll, in `attach`) | | `c` | new thread (see below) | +| `.` | thread actions (see below); a right-click on a thread opens them too | | `m` | model, options (reasoning, fast mode…) and access mode | | `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) | @@ -81,6 +82,19 @@ 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. - **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. +## Thread actions + +`.`, `Thread actions…` in the palette, or a right-click on a thread in the list opens T3 Code's thread menu, built by the web app's own code: + +- New thread on the thread's branch (in its worktree, if it has one) +- Pin or unpin, settle or un-settle, snooze (T3's presets or a custom time) or wake +- Rename, regenerate the title, mark unread +- Auto-settle on or off for the thread (on servers that support turning it off) +- Copy the workspace path, branch, thread link or thread ID +- Archive or delete + +Submenus open as their own list, and typing finds their items from the top (`thread id` finds `Copy › Thread ID`). A custom snooze takes a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`). Delete asks first, as the app does by default; it doesn't offer to remove the thread's worktree, which the app does. Copying goes through the terminal (OSC 52, so it works over SSH), and through `wl-copy`, `xclip` or `pbcopy` on a local desktop. The app's project settings, guest sharing and find-in-thread aren't here. + ## 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. diff --git a/src/client/session.ts b/src/client/session.ts index 536fc85..e5d8848 100644 --- a/src/client/session.ts +++ b/src/client/session.ts @@ -417,6 +417,88 @@ export class T3Session { return this.dispatch({ type: "thread.stop", commandId: newCommandId(), threadId }); } + // The thread menu's actions, as the web's useThreadActions sends them. + settleThread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.settle", commandId: newCommandId(), threadId }); + } + + /** reason "user" keeps it active until real activity, so auto-settle leaves it alone. */ + unsettleThread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.unsettle", commandId: newCommandId(), threadId, reason: "user" }); + } + + pinThread(threadId: ThreadId, orderKey?: string): Promise { + return this.dispatch({ type: "thread.pin", commandId: newCommandId(), threadId, ...(orderKey ? { orderKey } : {}) }); + } + + unpinThread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.unpin", commandId: newCommandId(), threadId }); + } + + snoozeThread(threadId: ThreadId, snoozedUntil: string): Promise { + return this.dispatch({ type: "thread.snooze", commandId: newCommandId(), threadId, snoozedUntil }); + } + + unsnoozeThread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.unsnooze", commandId: newCommandId(), threadId, reason: "user" }); + } + + setAutoSettle(threadId: ThreadId, enabled: boolean): Promise { + return this.dispatch({ type: "thread.auto-settle.set", commandId: newCommandId(), threadId, enabled }); + } + + markUnread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.mark-unread", commandId: newCommandId(), threadId }); + } + + renameThread(threadId: ThreadId, title: string): Promise { + return this.dispatch({ type: "thread.metadata.update", commandId: newCommandId(), threadId, title }); + } + + regenerateTitle(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.metadata.update", commandId: newCommandId(), threadId, regenerateTitle: true }); + } + + archiveThread(threadId: ThreadId): Promise { + return this.dispatch({ type: "thread.archive", commandId: newCommandId(), threadId }); + } + + /** + * Deletes the thread. One with a runtime has its provider sessions detached first, as the + * web's stopThreadSession does; their ids come from the thread's projection. + */ + async deleteThread(threadId: ThreadId, hasRuntime: boolean): Promise { + if (hasRuntime) { + const projection = await this.projectionOnce(threadId); + const commandId = newCommandId(); + for (const providerSession of projection.providerSessions) { + await this.dispatch({ type: "provider-session.detach", commandId: CommandId.make(`${commandId}:detach:${providerSession.id}`), threadId, providerSessionId: providerSession.id, reason: "client-requested" }); + } + } + return this.dispatch({ type: "thread.delete", commandId: newCommandId(), threadId }); + } + + /** The thread's projection, subscribing just long enough to get it. */ + private projectionOnce(threadId: ThreadId): Promise { + return new Promise((resolve, reject) => { + let unwatch: (() => void) | null = null; + let done = false; + const finish = (action: () => void) => { + if (done) return; + done = true; + clearTimeout(timer); + queueMicrotask(() => unwatch?.()); + action(); + }; + const timer = setTimeout(() => finish(() => reject(new Error("The thread did not load."))), 10_000); + unwatch = this.watchThread(threadId, (state) => { + if (state.projection) finish(() => resolve(state.projection!)); + else if (state.status === "error") finish(() => reject(new Error(state.error ?? "The thread did not load."))); + }); + if (done) unwatch(); + }); + } + setRuntimeMode(threadId: ThreadId, runtimeMode: RuntimeMode): Promise { return this.dispatch({ type: "thread.runtime-mode.set", commandId: newCommandId(), threadId, runtimeMode }); } diff --git a/src/model/models.ts b/src/model/models.ts index ee0f6b3..ba0e5c5 100644 --- a/src/model/models.ts +++ b/src/model/models.ts @@ -98,6 +98,8 @@ export interface DraftThread { readonly modelSelection: ModelSelection; readonly runtimeMode: RuntimeMode; readonly envMode: ThreadEnvMode; + /** Runs in another thread's worktree, from "New thread on ". */ + readonly existingWorktree?: { readonly path: string; readonly branch: string | null }; } /** diff --git a/src/model/palette.ts b/src/model/palette.ts index 49cb7d7..2e7fd53 100644 --- a/src/model/palette.ts +++ b/src/model/palette.ts @@ -95,6 +95,8 @@ export interface PickerItem { readonly title: string; /** Shown on the right: "current", a provider, a status. */ readonly hint?: string; + /** Only listed once you type: a submenu's items, found from the top. */ + readonly searchOnly?: boolean; readonly run: () => void; } @@ -114,7 +116,7 @@ export function pickerGroups(picker: Picker, query: string): PaletteGroup[] { .filter((candidate) => candidate.match !== null) .sort((a, b) => b.match!.score - a.match!.score) .map(({ item }) => item) - : group.items; + : group.items.filter((item) => !item.searchOnly); 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); diff --git a/src/model/threadMenu.ts b/src/model/threadMenu.ts new file mode 100644 index 0000000..a42dda4 --- /dev/null +++ b/src/model/threadMenu.ts @@ -0,0 +1,104 @@ +import { EnvironmentId, type ContextMenuItem, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type ServerConfig } from "@t3tools/contracts"; +import { presentThreadShell, threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models"; +import { canSnooze, effectiveSnoozed, pickSnoozePreset, resolveSnoozePresets, type SnoozePreset } from "@t3tools/client-runtime/state/thread-settled"; +import { pinOrderKeyBetween } from "@t3tools/client-runtime/state/thread-sort"; + +import type { Tui3Config } from "../config.ts"; +import { buildThreadActionMenuItems, type ThreadActionMenuId } from "../../vendor/t3code/apps/web/src/components/threadActionMenu.logic.ts"; + +export type { ThreadActionMenuId }; + +const LOCAL = EnvironmentId.make("local"); + +/** Web-only actions: finding in the thread, project settings, guest links, turning into a project. */ +const UNSUPPORTED: ReadonlySet = new Set(["find", "project-settings", "share-guest", "turn-into-project", "filter-by-project"]); + +export interface ThreadMenu { + readonly items: readonly ContextMenuItem[]; + readonly snoozePresets: readonly SnoozePreset[]; +} + +/** The web sidebar's thread menu (right-click), from the same builder, less what tui3 can't do. */ +export function threadMenu(input: { readonly thread: OrchestrationV2ThreadShell; readonly config: ServerConfig | null; readonly timestampFormat: Tui3Config["timestampFormat"]; readonly now?: Date }): ThreadMenu { + const { config } = input; + // The presented shell carries what the menu reads: pending requests, the runtime. + const thread = presentThreadShell(config?.environment.environmentId ?? LOCAL, input.thread); + const now = input.now ?? new Date(); + const loaded = config !== null; + const snoozePresets = snoozeMenu(config, input.timestampFormat, now); + const items = buildThreadActionMenuItems({ + canOperate: true, + canFind: false, + branch: thread.branch ?? null, + projectFilter: null, + isPinned: thread.pinnedAt != null, + isSettled: loaded && thread.settledOverride === "settled", + autoSettleEnabled: thread.autoSettleDisabledAt == null, + isSnoozed: loaded && effectiveSnoozed(thread, { now: now.toISOString() }), + canSnoozeNow: canSnooze(thread, { now: now.toISOString() }), + isRegeneratingTitle: thread.titleRegeneration != null, + isRunning: !threadRuntimeCanArchive(thread.runtime), + supports: { settlement: loaded, autoSettleOptOut: config?.environment.capabilities.threadAutoSettleOptOut === true, snooze: loaded, pinning: loaded, titleRegeneration: loaded }, + snoozePresets, + }); + return { items: items.filter((item) => !UNSUPPORTED.has(item.id)), snoozePresets }; +} + +function snoozeMenu(config: ServerConfig | null, timestampFormat: Tui3Config["timestampFormat"], now: Date): readonly SnoozePreset[] { + const presets = config?.settings.snoozePresets; + return resolveSnoozePresets(now, { ...(presets ? { presets } : {}), formatTime: (date) => formatTime(date, timestampFormat) }); +} + +/** A shown snooze choice, re-resolved now as the web does; undefined once its time has passed. */ +export function pickSnooze(shown: readonly SnoozePreset[], id: string, config: ServerConfig | null, timestampFormat: Tui3Config["timestampFormat"]): SnoozePreset | undefined { + const presets = config?.settings.snoozePresets; + return pickSnoozePreset({ shown, id, now: new Date(), ...(presets ? { presets } : {}), formatTime: (date) => formatTime(date, timestampFormat) }); +} + +function formatTime(date: Date, format: Tui3Config["timestampFormat"]): string { + return date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit", ...(format === "locale" ? {} : { hour12: format === "12-hour" }) }); +} + +/** + * A custom snooze, typed: a duration (`45m`, `3h`, `2d`, `1w`) or a time of day (`17:30`, the + * next time it comes round). The web's calendar picker doesn't fit a terminal. + */ +export function parseSnooze(text: string, now = new Date()): Date | null { + const input = text.trim().toLowerCase(); + const duration = /^(\d+)\s*(m|min|mins|minutes?|h|hrs?|hours?|d|days?|w|weeks?)$/.exec(input); + if (duration) { + const amount = Number(duration[1]); + const unit = duration[2]![0]!; + if (amount <= 0) return null; + if (unit === "m" || unit === "h") return new Date(now.getTime() + amount * (unit === "m" ? 60_000 : 3_600_000)); + const wake = new Date(now); + wake.setDate(wake.getDate() + amount * (unit === "w" ? 7 : 1)); + return wake; + } + const time = /^(\d{1,2}):(\d{2})$/.exec(input); + if (time) { + const hours = Number(time[1]); + const minutes = Number(time[2]); + if (hours > 23 || minutes > 59) return null; + const wake = new Date(now); + wake.setHours(hours, minutes, 0, 0); + if (wake.getTime() <= now.getTime()) wake.setDate(wake.getDate() + 1); + return wake; + } + return null; +} + +/** Whether the thread has a runtime, whose provider sessions a delete detaches first. */ +export function threadHasRuntime(thread: OrchestrationV2ThreadShell, config: ServerConfig | null): boolean { + return presentThreadShell(config?.environment.environmentId ?? LOCAL, thread).runtime != null; +} + +/** A pin goes to the top of the pinned run, as the web pins. */ +export function topPinOrderKey(snapshot: OrchestrationV2ShellSnapshot | null): string | undefined { + let first: string | null = null; + for (const thread of snapshot?.threads ?? []) { + if (thread.pinnedAt == null || thread.pinOrderKey == null) continue; + if (first === null || thread.pinOrderKey < first) first = thread.pinOrderKey; + } + return pinOrderKeyBetween(null, first) ?? undefined; +} diff --git a/src/ui/App.tsx b/src/ui/App.tsx index 8390b11..da7fabd 100644 --- a/src/ui/App.tsx +++ b/src/ui/App.tsx @@ -9,7 +9,8 @@ import { type PendingUserInputDraftAnswer, } from "@t3tools/client-runtime/state/pending-user-input"; 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 { threadChipCopyTarget } from "@t3tools/client-runtime/thread-reference"; +import { DEFAULT_TERMINAL_ID, type ContextMenuItem, type DiscoveredLocalServer, type ModelSelection, type OrchestrationV2ThreadShell, type ProviderApprovalDecision, type ScheduledTask, type TerminalSummary, type ThreadId } from "@t3tools/contracts"; import { homedir } from "node:os"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; @@ -17,6 +18,7 @@ import type { OrchestrationMessageContext, ProjectEntry, ThreadContextRecord } f 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 { configPath, cycleConfig, saveConfig, type Tui3Config } from "../config.ts"; import { detailsActions, detailsCwd, RUNTIME_MODE_LABELS, threadDetails, type DetailsAction, type GitAction } from "../model/details.ts"; @@ -34,7 +36,7 @@ import { Palette } from "./Palette.tsx"; import { QuestionPanel } from "./QuestionPanel.tsx"; import { SettingsView } from "./SettingsView.tsx"; import { attachTerminal } from "./terminalAttach.ts"; -import { desktopNotify, ring } from "./terminalOut.ts"; +import { copyText, desktopNotify, ring } from "./terminalOut.ts"; import { colors } from "./theme.ts"; import { ThreadList } from "./ThreadList.tsx"; import { ThreadView } from "./ThreadView.tsx"; @@ -174,7 +176,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C if (selectedId === undefined && rows[0]) setSelectedId(rows[0].thread.id); }, [selectedId, rows]); + /** A thread you marked unread, left unread until you open it again. */ + const noVisit = useRef(null); const openThread = useCallback((id: ThreadId) => { + noVisit.current = null; setSelectedId(id); setDiff(null); setSettingsIndex(null); @@ -199,7 +204,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C const unread = threadRow?.unread === true; useEffect(() => { - if (!watchedId || !unread) return; + if (!watchedId || !unread || noVisit.current === watchedId) return; const timer = setTimeout(() => void session.visit(watchedId).catch(() => {}), VISIT_DELAY_MS); return () => clearTimeout(timer); }, [session, watchedId, unread]); @@ -531,6 +536,148 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C }; // 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[]): 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["snoozePresets"]) => { + const id = target.id; + const title = target.title || "New thread"; + const leave = () => { + 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 "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]; @@ -573,15 +720,20 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C ], }); }; - const toggleWorkspace = () => draft && setDraft({ ...draft, envMode: draft.envMode === "local" ? "worktree" : "local" }); + 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) => { 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") { + 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 }; @@ -797,10 +949,11 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C command("filter", "Filter threads", () => setMode("filter"), { shortcut: "/", keywords: ["search"] }); command("settled", showFolded ? "Hide settled threads" : "Show settled threads", () => setShowFolded(!showFolded), { shortcut: "z", keywords: ["snoozed", "archive"] }); } + if (threadShell) command("thread-menu", "Thread actions…", openSelectedThreadMenu, { shortcut: ".", keywords: ["settle", "pin", "snooze", "rename", "archive", "delete", "copy", "unread", "menu"] }); 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-workspace", draft.envMode === "local" && !draft.existingWorktree ? "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"] }); @@ -1035,6 +1188,8 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C return startDraft(); case "m": return openModelPicker(); + case ".": + return openSelectedThreadMenu(); case "p": if (draft) openProjectPicker(); return; @@ -1131,7 +1286,7 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C { key: "project", label: "Project", value: draftProject?.title ?? "—", shortcut: "p", onPick: openProjectPicker }, { key: "model", label: "Model", value: modelSummary(providerConfig, draft.modelSelection), shortcut: "m", onPick: openModelPicker }, { key: "mode", label: "Mode", value: RUNTIME_MODE_LABELS[draft.runtimeMode] ?? draft.runtimeMode, shortcut: "m", onPick: openModelPicker }, - { key: "workspace", label: "Runs in", value: draft.envMode === "worktree" ? "a new worktree from the default branch" : "the project folder", shortcut: "w", onPick: toggleWorkspace }, + { 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) => ( @@ -1175,6 +1330,10 @@ export function App(props: { readonly session: T3Session; readonly config: Tui3C openThread(id); setMode("nav"); }} + onMenu={(id) => { + const target = allRows.find((row) => row.thread.id === id)?.thread; + if (target) openThreadMenu(target); + }} onUnfold={() => setShowFolded(true)} /> )} @@ -1347,7 +1506,7 @@ function hints( if (state.diff) return "j/k scroll · esc close diff · l details"; if (state.draft) return "i write the first message · p project · m model & mode · w worktree · esc cancel"; const parts = state.attached ? ["j/k scroll"] : ["j/k threads", "/ filter"]; - parts.push("i type", "c new", "m model", "ctrl+j terminal", "l details", "e expand"); + parts.push("i type", "c new", ". actions", "m model", "ctrl+j terminal", "l details"); if (state.parent) parts.push("u parent"); parts.push("ctrl+k commands", "q quit"); if (state.question) parts.unshift("1-9 pick · x dismiss"); diff --git a/src/ui/Palette.tsx b/src/ui/Palette.tsx index 0bb26df..f458b9d 100644 --- a/src/ui/Palette.tsx +++ b/src/ui/Palette.tsx @@ -19,10 +19,11 @@ export function Palette(props: { const width = Math.min(80, props.width - 4); const listHeight = Math.max(4, Math.min(props.height - 8, 22)); // Rows are entries plus a header per group; keep the selection in view. - const rows: ({ kind: "header"; label: string } | { kind: "entry"; entry: PaletteEntry; index: number })[] = []; + const rows: ({ kind: "header"; label: string; key: string } | { kind: "entry"; entry: PaletteEntry; index: number })[] = []; let index = 0; for (const group of props.groups) { - rows.push({ kind: "header", label: group.label }); + // Untitled groups (separators) share a label, so the key carries the position. + rows.push({ kind: "header", label: group.label, key: `h-${rows.length}-${group.label}` }); for (const entry of group.entries) rows.push({ kind: "entry", entry, index: index++ }); } const selectedRow = rows.findIndex((row) => row.kind === "entry" && row.index === props.selected); @@ -38,7 +39,7 @@ export function Palette(props: { {rows.length === 0 ? No matches : null} {rows.slice(start, start + listHeight).map((row) => row.kind === "header" ? ( - + {row.label} ) : ( diff --git a/src/ui/ThreadList.tsx b/src/ui/ThreadList.tsx index d7afde9..0af2d27 100644 --- a/src/ui/ThreadList.tsx +++ b/src/ui/ThreadList.tsx @@ -1,3 +1,4 @@ +import type { MouseEvent } from "@opentui/core"; import { needsAttention, relativeTime, rowTime, SECTION_LABELS, statusLabel, type Section, type ThreadRow } from "../model/threads.ts"; import type { ThreadId } from "@t3tools/contracts"; @@ -23,6 +24,8 @@ export function ThreadList(props: { readonly onFilter: (value: string) => void; readonly onFilterDone: () => void; readonly onPick: (threadId: ThreadId) => void; + /** A right-click: the thread's menu. */ + readonly onMenu: (threadId: ThreadId) => void; readonly onUnfold: () => void; }) { const { rows, selected, focused, width, height, now } = props; @@ -56,7 +59,7 @@ export function ThreadList(props: { paddingLeft={1} paddingRight={1} backgroundColor={isSelected ? (focused ? colors.selectedBg : colors.panel) : "transparent"} - onMouseDown={() => props.onPick(row.thread.id)} + onMouseDown={(event: MouseEvent) => (event.button === 2 ? props.onMenu(row.thread.id) : props.onPick(row.thread.id))} > {left} diff --git a/src/ui/terminalOut.ts b/src/ui/terminalOut.ts index b17c40a..328f3ff 100644 --- a/src/ui/terminalOut.ts +++ b/src/ui/terminalOut.ts @@ -1,4 +1,5 @@ -/** Escape sequences tui3 writes past the renderer: the bell and desktop notifications. */ +/** Escape sequences tui3 writes past the renderer: the bell, desktop notifications, the clipboard. */ +import type { CliRenderer } from "@opentui/core"; /** Inside tmux, escape sequences other than the bell need passthrough to reach the outer terminal. */ function passthrough(sequence: string): string { @@ -23,3 +24,22 @@ export function desktopNotify(title: string, body: string): void { : `\x1b]9;${clean(title)}: ${clean(body)}\x07`; process.stdout.write(passthrough(sequence)); } + +/** + * Copies text: through the terminal (OSC 52, which also works over SSH), and on a local + * desktop through its clipboard tool too, for terminals that ignore OSC 52. + */ +export function copyText(renderer: CliRenderer, text: string): void { + renderer.copyToClipboardOSC52(text); + if (process.env.SSH_CONNECTION) return; + const tool = + process.platform === "darwin" ? ["pbcopy"] : process.env.WAYLAND_DISPLAY ? ["wl-copy"] : process.env.DISPLAY ? ["xclip", "-selection", "clipboard"] : null; + if (!tool || !Bun.which(tool[0]!)) return; + try { + const child = Bun.spawn(tool, { stdin: "pipe", stdout: "ignore", stderr: "ignore" }); + child.stdin.write(text); + void child.stdin.end(); + } catch { + // OSC 52 already went out; the tool is a fallback. + } +} diff --git a/test/threadMenu.test.ts b/test/threadMenu.test.ts new file mode 100644 index 0000000..fcc8594 --- /dev/null +++ b/test/threadMenu.test.ts @@ -0,0 +1,115 @@ +import { describe, expect, test } from "bun:test"; +import { OrchestrationV2Command, ThreadId, type OrchestrationV2ShellSnapshot, type OrchestrationV2ThreadShell, type ServerConfig } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Schema from "effect/Schema"; + +import { T3Session } from "../src/client/session.ts"; +import { generateSpreadPinOrderKeys } from "@t3tools/client-runtime/state/thread-sort"; +import { parseSnooze, threadMenu, topPinOrderKey } from "../src/model/threadMenu.ts"; + +const config = { environment: { environmentId: "env-1", capabilities: { threadAutoSettleOptOut: true } }, settings: {} } as unknown as ServerConfig; +const at = (ms: number) => DateTime.makeUnsafe(ms); +const thread = { + id: "t1", + title: "Release supervisor", + projectId: "p1", + branch: "main", + worktreePath: null, + status: "completed", + activeRunId: null, + latestRunId: "run-1", + latestRunRequestedAt: at(100), + latestRunStartedAt: at(110), + latestRunCompletedAt: at(200), + pendingRuntimeRequest: null, + latestUserMessageAt: null, + lineage: { relationshipToParent: null, parentThreadId: null }, + modelSelection: { instanceId: "codex", model: "gpt" }, + archivedAt: null, + deletedAt: null, + settledOverride: null, + settledAt: null, + pinnedAt: null, + autoSettleDisabledAt: null, + snoozedUntil: null, + titleRegeneration: null, + lastVisitedAt: at(250), + hasActionableProposedPlan: false, + interactionMode: "default", + createdAt: at(0), + updatedAt: at(200), +} as unknown as OrchestrationV2ThreadShell; + +const ids = (items: ReturnType["items"]): string[] => items.flatMap((item) => [item.id, ...(item.children ?? []).map((child) => child.id)]); + +describe("thread menu", () => { + test("has the web's actions, less the web-only ones", () => { + const menu = ids(threadMenu({ thread, config, timestampFormat: "24-hour", now: new Date(2026, 10, 2, 10) }).items); + expect(menu).toContain("new-thread-on-branch"); + expect(menu).toContain("pin"); + expect(menu).toContain("settle"); + expect(menu).toContain("snooze:custom"); + expect(menu).toContain("rename"); + expect(menu).toContain("auto-settle:disabled"); + expect(menu).toContain("copy-thread-id"); + expect(menu).toContain("delete"); + expect(menu).not.toContain("project-settings"); + expect(menu).not.toContain("find"); + }); + + test("a settled, pinned thread offers to undo both", () => { + const menu = ids(threadMenu({ thread: { ...thread, settledOverride: "settled", pinnedAt: at(300) } as OrchestrationV2ThreadShell, config, timestampFormat: "24-hour" }).items); + expect(menu).toContain("unsettle"); + expect(menu).toContain("unpin"); + }); + + test("custom snooze takes durations and times of day", () => { + const now = new Date(2026, 10, 2, 10, 0); + expect(parseSnooze("45m", now)?.getTime()).toBe(now.getTime() + 45 * 60_000); + expect(parseSnooze("2d", now)?.getDate()).toBe(4); + expect(parseSnooze("17:30", now)?.getHours()).toBe(17); + expect(parseSnooze("09:00", now)?.getDate()).toBe(3); + expect(parseSnooze("soon", now)).toBeNull(); + }); + + test("a pin goes above the current first pin", () => { + const first = generateSpreadPinOrderKeys(1)[0]!; + const snapshot = { threads: [{ pinnedAt: "x", pinOrderKey: first }] } as unknown as OrchestrationV2ShellSnapshot; + const key = topPinOrderKey(snapshot); + expect(key !== undefined && key < first).toBe(true); + }); + + test("every action dispatches a valid command", async () => { + const session = new T3Session(); + const sent: unknown[] = []; + (session as unknown as { dispatch: (command: unknown) => Promise }).dispatch = async (command) => void sent.push(command); + const id = ThreadId.make("t1"); + await session.settleThread(id); + await session.unsettleThread(id); + await session.pinThread(id, "a0"); + await session.unpinThread(id); + await session.snoozeThread(id, "2026-11-03T09:00:00.000Z"); + await session.unsnoozeThread(id); + await session.setAutoSettle(id, false); + await session.markUnread(id); + await session.renameThread(id, "New name"); + await session.regenerateTitle(id); + await session.archiveThread(id); + await session.deleteThread(id, false); + expect(sent.filter((command) => !Schema.is(OrchestrationV2Command)(command))).toEqual([]); + expect(sent.map((command) => (command as { type: string }).type)).toEqual([ + "thread.settle", + "thread.unsettle", + "thread.pin", + "thread.unpin", + "thread.snooze", + "thread.unsnooze", + "thread.auto-settle.set", + "thread.mark-unread", + "thread.metadata.update", + "thread.metadata.update", + "thread.archive", + "thread.delete", + ]); + }); +});