From 398219a05807f15bfaf0416db54f1e43a40dae2a Mon Sep 17 00:00:00 2001 From: ehonis Date: Wed, 25 Nov 2026 10:56:28 -0500 Subject: [PATCH] Composer: $regular / $back gets you out of a ghost chat Published from the private repository by oss-sync. - Composer: $regular / $back gets you out of a ghost chat 8 files changed, 122 insertions(+), 19 deletions(-) --- AGENTS.md | 2 +- docs/chat.md | 8 +++- web/src/chat/Composer.tsx | 46 ++++++++++++++++------ web/src/chat/composerDestinations.test.tsx | 36 ++++++++++++++++- web/src/chat/destinations.test.ts | 22 ++++++++++- web/src/chat/destinations.ts | 24 +++++++++-- web/src/chat/icons.ts | 1 + web/src/components/ChatView.tsx | 2 + 8 files changed, 122 insertions(+), 19 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 3e173e0..bdb1e98 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,7 +94,7 @@ open-ended work. The default provider and model come from Settings → Providers | Chat | `chat/`, the "Web chat" block in `bridge.mjs`, `web/src/chat/` | Server-owned threads and runs that outlive the browser, listed as summaries and read a window at a time with Load earlier (`GET /api/threads?view=summary`, `GET /api/threads/?turns=10&before=`; one merge file shared by web and app, `web/src/chat/history.ts`; each chat reopens where it was left, `scrollMemory.ts`; docs/chat.md → Loading chats) (`POST /api/chat` streams SSE; `GET /api/chat/runs//stream?since=` re-attaches; only `POST /api/chat/stop` ends a run early; `POST /api/chat/steer` sends the owner's words and files into a running reply, live for Claude, interrupt-and-resume for the rest, `chat/steer.mjs`; or the message waits in the thread's queue, which the bridge drains itself when a run ends and holds after a stop or failure, `chat/queue.mjs`, `POST /api/chat/queue`; Settings → Chat › Follow-up behaviour picks which Enter does, Ctrl/⌘ the other). T3 Code's saved drafts: one per chat, several per place for chats not started yet (`new:`), each its words and finished uploads, rows atop the chats list and a pencil on a chat with unsent words; pure store `web/src/chat/drafts.ts` and what both clients do with it in `draftsShared.ts` (both copied byte for byte to `mobile/src/lib/chat/`, whose storage side is `draftsApp.ts`: a record per bridge, the drawer's "Unsent" rows, swipe or long-press to discard with the drawer's Undo line, saved as the app leaves the foreground) with the web's storage, other tabs and Undo in `draftsWeb.ts` and the chat view's wiring in `useChatDrafts.ts`, and the bridge holds a draft's uploads past the orphan sweep for 30 days from the last renewal (`POST /api/chat/uploads/hold`, `createUploadHolds`); docs/chat.md → Drafts. Native per-provider session resume, attachments (in the tray and inline in the text as T3 Code-style chips: the composer is a minimal TipTap editor over the message string, `web/src/chat/editor/`, its own chunk; a chip is `![name](totem-ref://upload/)` or `[name](…)` in the text, `web/src/chat/refs.ts`, copied byte for byte to the app; the bridge turns each into `[Image: …; ref=upload_]` plus one `` block with paths, resolving only the message's own uploads, `chat/refs.mjs`; lists, titles and search show plain names; docs/chat.md → Attachments), Markdown formatted as it is typed (numbered, bullet and task lists and code fences as real nodes that keep the prefix each line was typed with; Return, Tab and Shift+Tab in a list are edits of the string, `web/src/chat/editor/markdown.ts`, so the message is exactly the Markdown typed; Settings → Chat › Format Markdown as you type turns the drawing off per device; docs/chat.md → Lists and code in the message box), named tool cards folded with the reply's in-between text into one line above the answer, led by the connectors' own logos stacked (`web/src/chat/workFold.ts`; Claude's `tool_use_meta`, `connectorLook` in `chat/tools.mjs`); a picture a tool returned (an image the agent read, a screenshot) stays on its card as a thumbnail (`images` on the tool part, from a `tool_image` event), and the reply shows one only when the agent writes `![…](path)`, from its outputs folder, the temp dir or an image Claude read that turn (which reuses the card's upload); the upload sweep keeps ids a message's text names (docs/chat.md → Pictures the agent looks at), per-reply stats (setting, effort, tokens, tok/s, cost; `chat/stats.mjs`, shown on hover by `TurnStats.tsx`), no modes (every chat run gets the browser, computer use where the account has it, and an hour; the agent decides, `chat/reach.mjs`), the model picker (`ModelPicker.tsx`; no automatic routing since Auto/Instant/Thinking were retired; picking another account mid-chat hands the chat over with what it missed, `handoffReplay`, docs/chat.md → Switching accounts), thread titles and icons, local whisper.cpp dictation and an optional OpenAI Realtime voice mode. `docs/chat.md`. | | Chat projects | `chat/projects.mjs`, `chat/memory-ref.mjs`, `web/src/chat/Project*.tsx` | A project's page is its composer (centred on desktop) and chats (the first five, then Show more: `FIRST_CHATS` in `ProjectHome.tsx`); its files, instructions, memory, model and settings are a T3 Code-style card pinned top right (`ProjectCard.tsx`, stacked over a task's pinned card in `.vc-pins`; in the page on a phone). Chats grouped with a shared default model (a new chat takes its own pick, else the folder's, else the project's, else Settings → Providers: `threadChoice`/`projectDefault` in `web/src/chat/store.ts`, `projectModelDefault` on the bridge; a pick in a draft never carries to another chat), owner-written instructions, an agent-kept `memory.md` and shared files (`data/chat-projects/`). Each turn names the memory file with a one-line summary (size, entries, last updated, headings) and the agent reads it on demand, again when the summary changed; only the owner's instructions are pasted (memory used to be, once per turn of a resumed session). OpenCode, which cannot read outside `AGENT_CWD` unattended, gets the file's start instead. One level of folders (`parentId`) that read the parent read-only and keep their own memory; nothing deletes a project or folder: archiving one (`archivedAt`; `archive`/`restore` in the store, `list()` leaving it out, `active(id)` for every route that files into one) hides it with its folders and chats until Settings → Archive restores it (`GET /api/chat/projects/archived`; `docs/chat.md` → Projects); a chat can turn project context off (`projectContextOff`); an uploaded image or a website's icon can stand in for the Tabler icon (`image`, `chat/favicon.mjs`); finished chats wait on the owner (`needsReply`) until the owner opens one, replies or marks it read; "Mark as unread" sets `keepUnread`, which opening does not clear. The chats panel has one Snoozed and one Settled shelf, a project's page its own, T3 Code style (`web/src/chat/settle.ts`; auto-settle and wake-up are computed on read, never written). An agent that finished a one-off request calls `mark_chat_done` (`chat/done.mjs`, on `/agent-mcp`): the row offers a one-tap Settle until the reply is read, then the chat settles itself once he moves off it (`doneAt`; dropped by a failed or stopped reply, or by anything he writes in the chat: `wakeOnOwnerMessage` in `chat/store.mjs`, which also takes it off the Settled shelf and ends a snooze). `docs/chat.md` → Projects. | | Chats panel | `web/src/chat/ChatsNav.tsx`, `web/src/chat/sidebar.ts`, `web/src/chat/ThreadList.tsx` (`ThreadItem`, `ShelfSection`), `web/src/work/TaskBadge.tsx` | Since 1.1, T3 Code's sidebar: one list of every chat in every project and folder (no tabs, no drilling into projects), as `sidebarLists` sorts it: unsent drafts, Pinned, everything still in play latest first, then Working (running and not waiting on him; starts open), Snoozed and one Settled shelf at the bottom. Recent / By task at the top (`totem.chats.order`, By task by default; `web/src/tasksnav/`): By task folds Working in, gathers chats on one open task under its row (`playByTask`), and lists the scope's next tasks below by due day, folding, with Snooze (Tomorrow, 3 days, a week) and New chat on hover and a click that starts a chat for the task, carrying a new chat's typed words (`pickTask`, `useChatDrafts.startForTask`). Live chats are cards: place ("Project › Folder" or Home) and status words (Awaiting input/approval, Your turn, Working, Woke, Done, else age), title, and the linked task as T3 shows a PR (`TaskBadge`: glyph coloured by due/done, title, due day; a click opens its task card, never the chat). A scope button (All chats, Home, a project or folder; `totem.chats.scope`) narrows the list without moving the page, with ↗ to the project's page and a dot for waiting chats it hides; New chat starts in the scoped project (`newChatInScope`). Totems' own chats are not listed (Totems is a rail item). The iPhone drawer is the same list (`mobile/src/features/chat/ChatsNav.tsx`, `mobile/AGENTS.md`). `docs/chat.md` → The chats panel. | -| Linked tasks | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | A chat's task, shown on its card in the chats panel (above). Tasks and sheet rows are filed under a chat project or folder (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose). The web panel's Tasks face (a list of every task with its chats, its add line and sort menu) was removed in 1.1; its By task order lists tasks with their chats now (Chats panel row), and the Tasks page edits them. A task's card (`web/src/work/TaskCard.tsx`: folder, due, priority, repeat, snooze, description, chats, Open in Tasks) is pinned at the open chat's top right for that chat's own task (`PinnedTask` in `ChatView`; folds, never closes, the log moves left to clear it; opening that task anywhere unfolds it, `pinTask` in `card.ts`), and any other task opens it as a modal dialog (`TaskCardHost`, mounted once in `App.tsx`; a bottom sheet on a phone), from a chat card's task badge. A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", the `$` menu, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). A chat whose task is finished (a local task done, a sheet row the owner marked done) settles as a `mark_chat_done` chat does, the way T3 Code settles a thread when its pull request merges: the bridge adds `taskDoneAt` to every chat it reads out (`chat/task-done.mjs`, worked out per read, never stored, so a task reopened brings the chat back and a task finished from the gateway counts), and `settle.ts` `taskDoneSince` counts it only when the task was finished after the owner last wrote in the chat (`docs/chat.md` → Settled and snoozed). A linked chat's composer shows the task (Done, change, unlink; `TaskBar.tsx`) and every non-voice turn carries a `LINKED TASK.` block (`linkedTaskBlock`). Filing a task, Move to… and Link to task… share one T3 Code-style project-selector popover (`ComboPicker.tsx`: search, arrows, Enter, "New folder/project/task …" from what was typed). Tasks load while the chats panel, a card's task badge, a strip or the composer's `$` menu is on screen. A chat not started yet is placed from its composer with `$` (Home, a project or folder, or a task, which starts it through `startTaskDraft` in the task's folder; `web/src/chat/destinations.ts`, `destinations` on `Composer`), `$ghost` makes it a ghost chat (a `temporary` chat at Home: gone at midnight, and listed nowhere once settled, `ghostGone` in `settle.ts`; settled by hand on the web it is deleted when its Undo toast passes), a name no place has (`$tax-returns`) offers New folder/New project by that name and starts the chat in it, `$opus` (any model or account name) picks the new chat's model, `$pin` pins it from the start and `$snooze` sends it and keeps it in Snoozed until a time even once answered (`snoozeHeld`, bridge-set, so its reply neither wakes it nor pushes), and `$task` makes a new task right there: the box becomes its quick-add line (`parseQuickAdd`, filed where the chat is unless `#folder`), Return creates it and starts the chat for it (`web/src/chat/newTask.ts`, `NewTaskBar.tsx`, `newTask` in `useChatDrafts.ts`), and ⌘/Ctrl+Shift+O starts a blank chat at Home from any page (a hotkey: `hotkeys` in `web/src/shortcuts.ts`, Settings → Keyboard › Hotkeys; `docs/shortcuts.md` → Hotkeys). The iPhone drawer is the same list since 1.1 (`mobile/src/features/chat/ChatsNav.tsx`, `lib/chat/sidebar.ts` byte for byte, `features/work/TaskBadge.tsx`; no Tasks face): a task opens its own page, which lists its chats, in place of the card; no `$` menu. `docs/chat.md` → Linked tasks, → Placing a new chat with `$`, → Making a task with `$task`, → More `$` actions. | +| Linked tasks | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | A chat's task, shown on its card in the chats panel (above). Tasks and sheet rows are filed under a chat project or folder (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose). The web panel's Tasks face (a list of every task with its chats, its add line and sort menu) was removed in 1.1; its By task order lists tasks with their chats now (Chats panel row), and the Tasks page edits them. A task's card (`web/src/work/TaskCard.tsx`: folder, due, priority, repeat, snooze, description, chats, Open in Tasks) is pinned at the open chat's top right for that chat's own task (`PinnedTask` in `ChatView`; folds, never closes, the log moves left to clear it; opening that task anywhere unfolds it, `pinTask` in `card.ts`), and any other task opens it as a modal dialog (`TaskCardHost`, mounted once in `App.tsx`; a bottom sheet on a phone), from a chat card's task badge. A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", the `$` menu, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). A chat whose task is finished (a local task done, a sheet row the owner marked done) settles as a `mark_chat_done` chat does, the way T3 Code settles a thread when its pull request merges: the bridge adds `taskDoneAt` to every chat it reads out (`chat/task-done.mjs`, worked out per read, never stored, so a task reopened brings the chat back and a task finished from the gateway counts), and `settle.ts` `taskDoneSince` counts it only when the task was finished after the owner last wrote in the chat (`docs/chat.md` → Settled and snoozed). A linked chat's composer shows the task (Done, change, unlink; `TaskBar.tsx`) and every non-voice turn carries a `LINKED TASK.` block (`linkedTaskBlock`). Filing a task, Move to… and Link to task… share one T3 Code-style project-selector popover (`ComboPicker.tsx`: search, arrows, Enter, "New folder/project/task …" from what was typed). Tasks load while the chats panel, a card's task badge, a strip or the composer's `$` menu is on screen. A chat not started yet is placed from its composer with `$` (Home, a project or folder, or a task, which starts it through `startTaskDraft` in the task's folder; `web/src/chat/destinations.ts`, `destinations` on `Composer`), `$ghost` makes it a ghost chat (a `temporary` chat at Home: gone at midnight, and listed nowhere once settled, `ghostGone` in `settle.ts`; settled by hand on the web it is deleted when its Undo toast passes), and in a ghost chat `$regular` (or `$back`, `$keep`) is its only `$` row, which makes it an ordinary chat again (`ghostDestinations`), a name no place has (`$tax-returns`) offers New folder/New project by that name and starts the chat in it, `$opus` (any model or account name) picks the new chat's model, `$pin` pins it from the start and `$snooze` sends it and keeps it in Snoozed until a time even once answered (`snoozeHeld`, bridge-set, so its reply neither wakes it nor pushes), and `$task` makes a new task right there: the box becomes its quick-add line (`parseQuickAdd`, filed where the chat is unless `#folder`), Return creates it and starts the chat for it (`web/src/chat/newTask.ts`, `NewTaskBar.tsx`, `newTask` in `useChatDrafts.ts`), and ⌘/Ctrl+Shift+O starts a blank chat at Home from any page (a hotkey: `hotkeys` in `web/src/shortcuts.ts`, Settings → Keyboard › Hotkeys; `docs/shortcuts.md` → Hotkeys). The iPhone drawer is the same list since 1.1 (`mobile/src/features/chat/ChatsNav.tsx`, `lib/chat/sidebar.ts` byte for byte, `features/work/TaskBadge.tsx`; no Tasks face): a task opens its own page, which lists its chats, in place of the card; no `$` menu. `docs/chat.md` → Linked tasks, → Placing a new chat with `$`, → Making a task with `$task`, → More `$` actions. | | Chat files | `chat/files.mjs`, `web/src/chat/FilesPanel.tsx`, `/api/chat/files*` in `bridge.mjs`, `openFile` in `web/src/chat/store.ts`, `web/src/links.ts` | T3 Code's files viewer: the chat's outputs folder as a tree beside the chat, every file openable in the canvas and downloadable from any device. It, the canvas, Browser and Agents panels share one slot, drag-resizable per panel (`docs/chat.md` → Side panel widths). Serves `CHAT_OUTPUTS_DIR` plus `FILES_ROOTS`, by real path, never Totem's `data/`, `secrets/` or `.env`. A reply's link to an absolute path opens there, and the same path opened as a URL redirects to the chat (`?file=`). Every opener goes through `openFile(path)`: `GET /api/chat/files/link` checks the path and returns a signed link (real path + 12 h expiry + HMAC under a random per-process key), which the canvas, its frames and the native download read without the bearer (a Files row's Download signs on the click; the listing carries no links); only the exact spelling `/api/chat/files/raw?…&sig=` skips the sign-in gate, and the roots/deny check runs on every read. A bearer-only dashboard read the bare raw URL with no header and showed `{"error":"unauthorized"}`; `chat/files-bridge.test.mjs` boots a bridge to hold this. `docs/chat.md` → Files panel. | | Download activity | `web/src/downloads.ts`, `web/src/components/DownloadActivity.tsx`, `desktop/src-tauri/src/lib.rs` | App-wide activity for download links, chat and question attachments, generated files, previews, project files, Messages files and journal audio. Active repeats join one transfer; different files have separate progress, cancel/retry and dismiss controls. Browsers offering a save-file picker stream directly to the chosen file; otherwise transfers buffer at most 32 MiB before handing larger files to the browser. Browser handoff and application transfer completion explicitly tell the owner to check Downloads, never claim an OS save. Native wrappers advertising `downloads` stream through Tauri and report real saved/failed events (indeterminate: Tauri has no byte progress); this requires a new desktop build. A saved native download gets Show in folder (Show in Finder on a Mac): the app keeps the path (`Downloads` in `lib.rs`, the last 50) and the page asks by the download's URL through a cancelled `totem-desktop://reveal?u=` navigation, never seeing a path; older wrappers do not send `reveal`, so no button. Raw chat files and signed uploads accept authenticated HEAD preflights without reading file bodies; bearer-only users need a session or a signed URL (an upload's `?sig=`, a chat file's signed link) for native/browser navigation handoff. | | Sub-agents | `chat/subagents.mjs`, `web/src/chat/AgentsPanel.tsx` | Agents a chat's agent starts: Claude's Agent/Task sub-agents (events tagged `parent_tool_use_id`), Codex collab children, and another CLI run from a shell (`codex exec`, `claude -p`, …), whose own session log is found by start time and prompt and tailed. Each folds into its tool card as `part.agent` (status, model, tokens, steps). The Agents panel beside the chat lists them and opens each one's live log. Each writes an `agent.delegate` line to the action log. `docs/chat.md` → Agents panel. | diff --git a/docs/chat.md b/docs/chat.md index edc0dc6..2ffc737 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -1963,7 +1963,13 @@ lists the first two between the places and the tasks. snoozed). The words and files move to the ghost chat's draft at Home, out of any project or task it was being started in (ghost chats live outside projects), as the header's ghost switch does for a chat at Home (`placeDraft(…, ghost)` in `useChatDrafts.ts`). A ghost - chat's composer offers no `/` or `$` menu; the header's switch turns it back. + chat's composer offers no `/` skills and no places, but its `$` menu has one row, the way + out: **`$regular`** (also `$back`, `$keep`, `$normal`, `$exit`, `$unghost`, `$leave`, + `$off` and `$ghost` again, from two letters; a bare `$` shows it too; + `ghostDestinations` in `destinations.ts`). Before the first send it is **Regular chat**, + which moves the words and files to Home's ordinary draft, as the header's switch does; once + the chat has started it is **Keep this chat**, the header's Keep (`keepThread`), and the + words stay in the box. A price (`$40`) or any other word offers nothing, so Enter sends it. - **A name nothing has yet** (`$tax-returns`, three letters on) ends the menu with **New project “Tax returns”**, and, in a project or one of its folders, first **New folder “Tax returns”** in that project (one level of folders). The name is the term as diff --git a/web/src/chat/Composer.tsx b/web/src/chat/Composer.tsx index f0e8b13..63dac86 100644 --- a/web/src/chat/Composer.tsx +++ b/web/src/chat/Composer.tsx @@ -10,7 +10,7 @@ import { insertMention, mentionAtCaret } from './mentions' import { attachmentRef, editableRefs, formatSize, refIds, splitRefs } from './refs' import type { ChipInfo } from './RefChip' import type { PromptEditorHandle } from './editor/PromptEditor' -import { rankDestinations, stripToken, type Destination } from './destinations' +import { ghostDestinations, rankDestinations, stripToken, type Destination } from './destinations' import { readNewTask, type NewTaskFields } from './newTask' import NewTaskBar from './NewTaskBar' import { folderNames } from '../todos/folders' @@ -25,7 +25,7 @@ import { TI, ProviderLogo, useDismiss } from './ui' import { IconArrowUp, IconPlayerStopFilled, IconPlus, IconPaperclip, IconPhoto, IconMicrophone, IconWaveSine, IconSparkles, IconX, IconCheck, IconLoader2, IconCornerUpRight, IconPuzzle, IconPlaylistAdd, IconPlayerPlayFilled, - IconHome, IconChecklist, IconTable, IconFolder, IconFolderPlus, IconGhost2, IconPinned, IconZzz, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus, + IconHome, IconChecklist, IconTable, IconFolder, IconFolderPlus, IconGhost2, IconGhostOff, IconPinned, IconZzz, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus, } from './icons' import { formatContextTokens } from './context' import type { ChatCommand } from '../studio' @@ -128,6 +128,12 @@ export interface ComposerProps { /** The draft on screen: a task line is that draft's, so another draft is a message again. */ draftKey?: string } + /** + * A ghost chat. Its `/` and `$` menus are off (`allowCommands` false) but for one + * row, the way out: `$regular`, `$back`, `$keep`. Not started yet, it goes through + * `destinations.onPick` (the words move to Home's regular draft); started, `onKeep`. + */ + ghost?: { started: boolean; onKeep?: () => void } } const coarse = () => window.matchMedia?.('(pointer: coarse)').matches @@ -157,15 +163,17 @@ type MenuItem = { kind: 'dest'; d: Destination } | { kind: 'cmd'; c: ChatCommand const itemKey = (it: MenuItem) => (it.kind === 'dest' ? it.d.key : it.c.cmd) const NO_PROVIDERS: ProviderRow[] = [] const NO_CATALOGS: Record = {} -const QUICK = new Set(['new-task', 'ghost', 'pin']) +const QUICK = new Set(['new-task', 'ghost', 'leave-ghost', 'pin']) /** Picks that leave the draft where it is, so a file still uploading doesn't hold them. */ const STAYS = new Set(['new-task', 'model', 'pin', 'snooze']) +const stays = (d: Destination) => STAYS.has(d.kind) || (d.kind === 'leave-ghost' && d.started) const itemGroup = (it: MenuItem) => (it.kind === 'dest' ? (QUICK.has(it.d.kind) ? 'Quick actions' : it.d.kind === 'snooze' ? 'Send it, back later' : it.d.kind === 'model' ? 'Start on a model' : it.d.kind === 'new-folder' ? 'Make a folder' : it.d.kind === 'task' ? 'Start it for a task' : 'Start it in') : it.c.kind === 'agent' ? 'Your agent skills' : 'Totem skills') function destDesc(d: Destination, sheetName: string, here?: Project, forTask = false) { if (d.kind === 'new-task') return here ? `Type it here, filed in ${here.name}, then chat about it` : 'Type it here, then start a chat for it' if (d.kind === 'ghost') return here || forTask ? 'Not kept: moves to Home, gone at midnight' : 'Not kept: gone at midnight, or as soon as you settle it' + if (d.kind === 'leave-ghost') return d.started ? 'Kept after midnight, like any other chat' : 'Kept: an ordinary chat at Home' if (d.kind === 'new-folder') return d.parent ? `New folder in ${d.parent.name}, then start the chat in it` : 'New project, then start the chat in it' if (d.kind === 'model') return d.note ? `${d.provider.name} · ${d.note}` : d.provider.name if (d.kind === 'pin') return 'Pinned to the top of your chats once it starts' @@ -181,6 +189,7 @@ function DestIcon({ d }: { d: Destination }) { if (d.kind === 'home') return if (d.kind === 'new-task') return if (d.kind === 'ghost') return + if (d.kind === 'leave-ghost') return if (d.kind === 'new-folder') return if (d.kind === 'model') return if (d.kind === 'pin') return @@ -273,7 +282,7 @@ const PlainBox = forwardRef(function Composer(props, ref) { - const { value, onChange, onAttachmentsChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', autoFocus, compact, allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, rightSlot, leftSlot, compactSend, answering, above, destinations } = props + const { value, onChange, onAttachmentsChange, onSend, onStop, onSteer, onQueue, followUp = 'queue', queueEdit, onResume, onVoice, busy, placeholder: idlePlaceholder = 'Ask Totem anything', autoFocus, compact, allowCommands = true, maxUploadBytes = 25 * 1024 * 1024, rightSlot, leftSlot, compactSend, answering, above, destinations, ghost } = props const ed = useRef(null) const fileInput = useRef(null) const photoInput = useRef(null) @@ -553,13 +562,16 @@ const Composer = forwardRef(function Composer(pro // A message that is only a Totem command still runs that skill on its own. const catalog = useSyncExternalStore(subscribeChatCommands, getChatCommands, getChatCommands) const known = useMentionSet() - const token = allowCommands && !dictation && !inTask ? mentionAtCaret(value, caret) : null + // A ghost chat reads only `$`, for its way out (no skills, no places). + const ghostOnly = !allowCommands && !!ghost + const rawToken = (allowCommands || ghostOnly) && !dictation && !inTask ? mentionAtCaret(value, caret) : null + const token = rawToken && (!ghostOnly || rawToken.prefix === '$') ? rawToken : null const query = token && token.start !== dismissed ? token : null // Only the token in an otherwise empty box can take a fill-mode skill's prefix. const alone = !!query && query.start === 0 && !value.slice(query.end).trim() - const matches: ChatCommand[] = query ? rankCommands(catalog, query.prefix, query.term, alone) : [] + const matches: ChatCommand[] = query && !ghostOnly ? rankCommands(catalog, query.prefix, query.term, alone) : [] // `$` in a chat not started yet: where it goes and which task it is for, before the `$` skills. - const dollar = !!query && query.prefix === '$' && !!destinations + const dollar = !!query && query.prefix === '$' && !!destinations && !ghostOnly const work = useSyncExternalStore(dollar ? subscribeWork : noSubscribe, getWork, getWork) const providers = useChat((s) => s.providers) || NO_PROVIDERS const catalogs = useChat((s) => s.models) || NO_CATALOGS @@ -567,7 +579,9 @@ const Composer = forwardRef(function Composer(pro // Every account's models, so `$opus` finds a model on any of them (the picker loads them the same way). useEffect(() => { if (wantModels) for (const p of providers) ensureModels(p.id) }, [wantModels, providers]) const accounts = useMemo(() => providers.map((provider) => ({ provider, models: catalogs[provider.id] || [] })), [providers, catalogs]) - const places = dollar && destinations + const places = ghostOnly && query?.prefix === '$' + ? ghostDestinations(query.term, ghost!.started) + : dollar && destinations ? rankDestinations({ projects, tasks: work.tasks, projectId: destinations.projectId, taskId: destinations.taskId, models: destinations.onModel ? accounts : [], startOptions: !!destinations.onStartOption, pinned: destinations.pinned, @@ -599,9 +613,17 @@ const Composer = forwardRef(function Composer(pro function chooseItem(it: MenuItem) { if (it.kind === 'cmd') { chooseCommand(it.c); return } - if (!query || !destinations) return - // Only a move waits for uploads: a model, pin or snooze leaves the files where they are. - if (placeHeld && !STAYS.has(it.d.kind)) return + if (!query) return + // Only a move waits for uploads: a model, pin, snooze or Keep leaves the files where they are. + if (placeHeld && !stays(it.d)) return + if (it.d.kind === 'leave-ghost' && it.d.started) { + const { value: next, caret: pos } = stripToken(value, query.start, query.end) + setDismissed(null) + placeCaret(next, pos) + ghost?.onKeep?.() + return + } + if (!destinations) return const { value: next, caret: pos } = stripToken(value, query.start, query.end) setDismissed(null) if (it.d.kind === 'new-task') { placeCaret(next, pos); startTask(); return } @@ -757,7 +779,7 @@ const Composer = forwardRef(function Composer(pro {it.d.kind === 'new-folder' ? `New ${it.d.parent ? 'folder' : 'project'} “${it.d.name}”` : it.d.kind === 'snooze' ? `Snooze · ${it.d.name}` : it.d.name} - {(!STAYS.has(it.d.kind) && placeHeld) || destDesc(it.d, work.sheetName, here, !!destinations?.taskId)} + {(!stays(it.d) && placeHeld) || destDesc(it.d, work.sheetName, here, !!destinations?.taskId)} ) : ( diff --git a/web/src/chat/composerDestinations.test.tsx b/web/src/chat/composerDestinations.test.tsx index 3bd6caf..f2a8339 100644 --- a/web/src/chat/composerDestinations.test.tsx +++ b/web/src/chat/composerDestinations.test.tsx @@ -33,14 +33,16 @@ const { default: Composer } = await import('./Composer') afterEach(cleanup) -function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {}, onModel, onStartOption, valueSpy }: { +function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {}, onModel, onStartOption, valueSpy, ghost }: { onPick: (d: Destination, text: string) => void; destinations?: boolean onNewTask?: (fields: NewTaskFields) => Promise; projectId?: string | null; onSend?: () => void onModel?: (d: any) => void; onStartOption?: (d: any) => void; valueSpy?: (v: string) => void + ghost?: { started: boolean; onKeep?: () => void } }) { const [value, setValue] = useState('') return ( { valueSpy?.(v); setValue(v) }} onSend={onSend} onStop={() => {}} busy={false} + allowCommands={!ghost} ghost={ghost} destinations={destinations ? { projectId, taskId: null, onPick: (d, text) => onPick(d, text), onNewTask, onModel, onStartOption } : undefined} /> ) } @@ -109,6 +111,38 @@ describe('composer $ destinations', () => { expect(onPick.mock.calls[0][1]).toBe('just between us') }) + it('in a ghost chat not started, $regular is the only row and moves the words to a regular chat', async () => { + const onPick = vi.fn() + render() + const box = await type('on second thought $regu') + const options = screen.getAllByRole('option').map((o) => o.textContent) + expect(options).toHaveLength(1) + expect(options[0]).toContain('Regular chat') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onPick.mock.calls[0][0]).toMatchObject({ kind: 'leave-ghost', started: false }) + expect(onPick.mock.calls[0][1]).toBe('on second thought') + }) + + it('in a started ghost chat, $back keeps it and leaves the words in the box', async () => { + const onPick = vi.fn() + const onKeep = vi.fn() + const valueSpy = vi.fn() + render() + const box = await type('one more thing $back') + expect(screen.getAllByRole('option')[0].textContent).toContain('Keep this chat') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onKeep).toHaveBeenCalledTimes(1) + expect(onPick).not.toHaveBeenCalled() + expect(valueSpy).toHaveBeenLastCalledWith('one more thing') + }) + + it('a ghost chat still offers no places, tasks or skills', async () => { + const onPick = vi.fn() + render() + await type('$harb') + expect(screen.queryAllByRole('option')).toHaveLength(0) + }) + it('offers a new folder in the project, and a new project, for a name nothing has, with his capitals', async () => { const onPick = vi.fn() render() diff --git a/web/src/chat/destinations.test.ts b/web/src/chat/destinations.test.ts index e240971..3cbc4a7 100644 --- a/web/src/chat/destinations.test.ts +++ b/web/src/chat/destinations.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest' -import { matchScore, nameFromTerm, placeAfter, rankDestinations, slug, stripToken } from './destinations' +import { ghostDestinations, matchScore, nameFromTerm, placeAfter, rankDestinations, slug, stripToken } from './destinations' import type { Project } from './types' import type { WorkTask } from '../work/groups' @@ -215,3 +215,23 @@ describe('$opus, $pin and $snooze', () => { for (const term of ['opus', 'pin', 'snooze-tom']) expect(placeAfter(rankDestinations(ctx, term)[0], now, () => 'wp')).toEqual(now) }) }) + +describe('ghostDestinations', () => { + it('offers only the way out, for a bare $ or a word that asks for it', () => { + expect(ghostDestinations('', false)).toEqual([{ kind: 'leave-ghost', key: 'leave-ghost', name: 'Regular chat', started: false }]) + for (const t of ['re', 'regular', 'back', 'ba', 'keep', 'normal', 'exit', 'unghost', 'leave', 'gh', 'off']) { + expect(ghostDestinations(t, false).map((d) => d.kind)).toEqual(['leave-ghost']) + } + expect(ghostDestinations('back', true)[0]).toMatchObject({ name: 'Keep this chat', started: true }) + }) + + it('offers nothing for a price or any other word, so Enter sends it', () => { + expect(ghostDestinations('40', false)).toEqual([]) + expect(ghostDestinations('r', false)).toEqual([]) + expect(ghostDestinations('harbor', false)).toEqual([]) + }) + + it('leaves to Home, out of any task', () => { + expect(placeAfter(ghostDestinations('back', false)[0], { taskId: 't1', projectId: 'wp' }, () => 'wp')).toEqual({ taskId: null, projectId: null }) + }) +}) diff --git a/web/src/chat/destinations.ts b/web/src/chat/destinations.ts index e179e10..cd7f093 100644 --- a/web/src/chat/destinations.ts +++ b/web/src/chat/destinations.ts @@ -5,7 +5,9 @@ // a ghost chat (not kept: gone at midnight), and a name no place has yet // (`$tax-returns`) offers a new folder or project by that name, `$opus` (any model // or account name) picks the chat's model, `$pin` pins it from the start, and -// `$snooze` sends it now and keeps it out of the way until a time. Pure, so the +// `$snooze` sends it now and keeps it out of the way until a time. In a ghost chat +// `$` offers one thing, the way out: `$regular` (or `$back`, `$keep`) makes it a +// chat that is kept, as the header's switch or Keep does. Pure, so the // composer's menu and its tests read the same rules. import type { ModelRow, Project, ProviderRow } from './types' import type { WorkTask } from '../work/groups' @@ -18,6 +20,8 @@ export type Destination = | { kind: 'task'; key: string; name: string; task: WorkTask } | { kind: 'new-task'; key: 'new-task'; name: 'New task' } | { kind: 'ghost'; key: 'ghost'; name: 'Ghost chat' } + /** Out of a ghost chat: a kept chat at Home (not started yet), or Keep (started). */ + | { kind: 'leave-ghost'; key: 'leave-ghost'; name: string; started: boolean } /** A folder (in `parent`) or a top-level project, made by that name, then the chat starts in it. */ | { kind: 'new-folder'; key: string; name: string; parent?: Project } /** A model to start on (no `modelId`: the account's own default). */ @@ -36,6 +40,20 @@ const GHOST_WORDS: Array<[string, number]> = [['ghost', 2], ['temporary', 4], [' export const wantsGhost = (term: string) => GHOST_WORDS.some(([w, min]) => term.length >= min && w.startsWith(term)) const GHOST: Destination = { kind: 'ghost', key: 'ghost', name: 'Ghost chat' } +/** The way out of a ghost chat: `$regular`, `$back`, `$keep`, `$normal`, `$exit`, `$unghost`, `$leave`, `$ghost` again, from two letters. */ +const LEAVE_GHOST_WORDS = ['regular', 'back', 'keep', 'normal', 'exit', 'unghost', 'leave', 'ghost', 'off'] +export const wantsLeaveGhost = (term: string) => term.length >= 2 && LEAVE_GHOST_WORDS.some((w) => w.startsWith(term)) + +/** + * A ghost chat's `$` menu: only the way out, for a bare `$` or a term that asks for it. + * `started`: the chat has messages, so it is kept where it is (Keep) rather than moved. + */ +export function ghostDestinations(term: string, started: boolean): Destination[] { + const t = term.toLowerCase() + if (t && !wantsLeaveGhost(t)) return [] + return [{ kind: 'leave-ghost', key: 'leave-ghost', name: started ? 'Keep this chat' : 'Regular chat', started }] +} + /** `$pin` from `$pi`. */ export const wantsPin = (term: string) => term.length >= 2 && 'pin'.startsWith(term) const PIN: Destination = { kind: 'pin', key: 'pin', name: 'Pin it' } @@ -223,8 +241,8 @@ export function placeAfter(d: Destination, now: { taskId: string | null; project // "New task" and "New folder" move nothing until the task or folder exists (made first); // a model, a pin or a snooze changes how it starts, not where. if (d.kind === 'new-task' || d.kind === 'new-folder' || d.kind === 'model' || d.kind === 'pin' || d.kind === 'snooze') return now - // A ghost chat lives at Home, outside any project or task. - if (d.kind === 'ghost') return { taskId: null, projectId: null } + // A ghost chat lives at Home, outside any project or task, and leaving one stays there. + if (d.kind === 'ghost' || d.kind === 'leave-ghost') return { taskId: null, projectId: null } if (d.kind === 'home') return { taskId: now.taskId, projectId: null } if (d.kind === 'project') return { taskId: now.taskId, projectId: d.project.id } return { taskId: d.task.ref, projectId: taskHome(d.task.ref) ?? now.projectId } diff --git a/web/src/chat/icons.ts b/web/src/chat/icons.ts index e5a8f02..51bb62c 100644 --- a/web/src/chat/icons.ts +++ b/web/src/chat/icons.ts @@ -48,6 +48,7 @@ export { default as IconEdit } from '@tabler/icons-react/dist/esm/icons/IconEdit export { default as IconLayoutSidebar } from '@tabler/icons-react/dist/esm/icons/IconLayoutSidebar.mjs' export { default as IconPinned } from '@tabler/icons-react/dist/esm/icons/IconPinned.mjs' export { default as IconGhost2 } from '@tabler/icons-react/dist/esm/icons/IconGhost2.mjs' +export { default as IconGhostOff } from '@tabler/icons-react/dist/esm/icons/IconGhostOff.mjs' export { default as IconPuzzle } from '@tabler/icons-react/dist/esm/icons/IconPuzzle.mjs' export { default as IconMessageCircleQuestion } from '@tabler/icons-react/dist/esm/icons/IconMessageCircleQuestion.mjs' export { default as IconBolt } from '@tabler/icons-react/dist/esm/icons/IconBolt.mjs' diff --git a/web/src/components/ChatView.tsx b/web/src/components/ChatView.tsx index 2f755f0..b75e391 100644 --- a/web/src/components/ChatView.tsx +++ b/web/src/components/ChatView.tsx @@ -698,6 +698,8 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane placeholder={waitingApproval ? DECLINE_PLACEHOLDER : !active && draftTaskId ? 'What should we do about it?' : temporary ? 'Ghost chat — gone at midnight' : project && empty ? `New chat in ${project.name}` : 'Ask Totem anything'} allowCommands={!temporary} destinations={active ? undefined : destinations} + // `$regular` / `$back` / `$keep`: out of a ghost chat, before it starts or after. + ghost={temporary ? { started: !!active, onKeep: active ? () => keepThread(active.id) : undefined } : undefined} maxUploadBytes={caps?.maxUploadBytes} onAuthError={onAuthError} />