diff --git a/AGENTS.md b/AGENTS.md index 1626f0c..b77a2ee 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; 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`), 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 `$`. | +| 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`), 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`. | | 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 059628e..7d20dc0 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -1911,6 +1911,29 @@ and reads tasks only while it is open. The composer's + menu has "Put it in a fo task", which types the `$`. ⌘/Ctrl+Shift+O (Settings → Keyboard › Hotkeys) starts a blank chat at Home from any page, ready for this (`docs/shortcuts.md` → Hotkeys). +#### Making a task with `$task` + +`$task` (or `$new`, from `$ta`/`$ne` on) leads the menu with **New task**, under +**Make a task**; a bare `$` lists it between the places and the tasks, and the + menu has +"New task, then chat about it". Picking it takes the `$…` out and turns the box into the +task's line: a **New task** strip above the words, a check where Send was, and whatever was +already typed as the start of the title. The words are read as the Tasks page's quick-add +line reads them (`web/src/todos/parse.ts`: "fri", "tomorrow", "p2", "#folder"), each shown +as a chip whose × keeps the word as text, plus a chip naming the folder it will be filed in: +the one the chat is being started in, unless a `#folder` says otherwise +(`web/src/chat/newTask.ts`, `NewTaskBar.tsx`). Return adds it (on a phone too: it is one +line), Escape or Backspace in an empty box makes the box a message again, and the menus for +`/` and `$` stay shut meanwhile. + +Adding it creates the task (`createTask` in `web/src/work/state.ts`, so the Tasks page and +the chats panel see it at once) and starts a new chat for it in its folder, the way picking +a task with `$` does (`newTask` in `useChatDrafts.ts`): the draft's files go along, its +words became the task, so the chat's box starts empty with the task strip above it. A task +the bridge refuses leaves the words in the box. Leaving for another draft or chat while it +is being added still adds it, says so, and stays where he went. Files still uploading hold +it, as they hold a pick. It is offered wherever the `$` places are (a chat not started yet, +not temporary); the iPhone app has no `$` menu. + Nothing loads tasks until a chat card with a task, a task strip or the `$` menu is on screen; while one is, the store (`web/src/work/state.ts`) reads the board, the sheet feed (its own two-minute cache) and the filings every minute and on focus. Changes are drawn at once and put back if the diff --git a/web/src/chat/Composer.tsx b/web/src/chat/Composer.tsx index 281f376..0a73f3b 100644 --- a/web/src/chat/Composer.tsx +++ b/web/src/chat/Composer.tsx @@ -11,18 +11,21 @@ import { attachmentRef, editableRefs, formatSize, refIds, splitRefs } from './re import type { ChipInfo } from './RefChip' import type { PromptEditorHandle } from './editor/PromptEditor' import { rankDestinations, stripToken, type Destination } from './destinations' +import { readNewTask, type NewTaskFields } from './newTask' +import NewTaskBar from './NewTaskBar' +import { folderNames } from '../todos/folders' import ProjectIcon from './ProjectIcon' import { useChat } from './store' import { getWork, subscribeWork } from '../work/state' import { dueLabel } from '../work/groups' import { micUnavailableReason, openMic, closeMic, recordUntilStopped } from './recorder' -import type { Attachment, DraftAttachment } from './types' +import type { Attachment, DraftAttachment, Project } from './types' import type { Answering } from './QuestionsPanel' import { TI, useDismiss } from './ui' import { IconArrowUp, IconPlayerStopFilled, IconPlus, IconPaperclip, IconPhoto, IconMicrophone, IconWaveSine, IconSparkles, IconX, IconCheck, IconLoader2, IconCornerUpRight, IconPuzzle, IconPlaylistAdd, IconPlayerPlayFilled, - IconHome, IconChecklist, IconTable, IconFolder, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, + IconHome, IconChecklist, IconTable, IconFolder, IconArrowsDiagonalMinimize2, IconArrowsDiagonal, IconSquarePlus, } from './icons' import { formatContextTokens } from './context' import type { ChatCommand } from '../studio' @@ -108,11 +111,16 @@ export interface ComposerProps { * A chat not started yet: `$` also offers where it goes (a project, a folder, * Home) and the tasks it can be for. Picking one takes the `$…` out of the * words and hands them over, since they move to the new place's draft. + * With `onNewTask`, `$task` also turns the box into a task line: Enter makes + * the task and resolves true once the chat for it has been started. */ destinations?: { projectId: string | null taskId: string | null onPick: (d: Destination, text: string, caret: number) => void + onNewTask?: (fields: NewTaskFields) => Promise + /** The draft on screen: a task line is that draft's, so another draft is a message again. */ + draftKey?: string } } @@ -141,10 +149,11 @@ const noSubscribe = () => () => {} type MenuItem = { kind: 'dest'; d: Destination } | { kind: 'cmd'; c: ChatCommand } const itemKey = (it: MenuItem) => (it.kind === 'dest' ? it.d.key : it.c.cmd) -const itemGroup = (it: MenuItem) => (it.kind === 'dest' ? (it.d.kind === 'task' ? 'Start it for a task' : 'Start it in') +const itemGroup = (it: MenuItem) => (it.kind === 'dest' ? (it.d.kind === 'new-task' ? 'Make a task' : 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) { +function destDesc(d: Destination, sheetName: string, here?: Project) { + 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 === 'home') return 'Chats in no project' if (d.kind === 'project') return d.parent ? `Folder in ${d.parent.name}` : 'Project' const due = d.task.dueDate ? dueLabel(d.task.dueDate, new Date()) : null @@ -154,6 +163,7 @@ function destDesc(d: Destination, sheetName: string) { function DestIcon({ d }: { d: Destination }) { if (d.kind === 'home') return + if (d.kind === 'new-task') return if (d.kind === 'project') return d.project.icon || d.project.imageUrl ? : return } @@ -257,6 +267,15 @@ const Composer = forwardRef(function Composer(pro const [confirmRemove, setConfirmRemove] = useState(null) const [menu, setMenu] = useState(false) const [sel, setSel] = useState(0) + // `$task`: the box is a new task's line until Enter makes it (newTask.ts). + const [taskMode, setTaskMode] = useState(false) + const [taskIgnore, setTaskIgnore] = useState([]) + const [taskBusy, setTaskBusy] = useState(false) + const projects = useChat((s) => s.projects) + const canMakeTask = !!destinations?.onNewTask && allowCommands + const inTask = taskMode && canMakeTask && !answering && !queueEdit + // Another draft on screen, or the chat started: the box is a message again. + useEffect(() => { setTaskMode(false); setTaskIgnore([]) }, [destinations?.draftKey, canMakeTask]) const [dictation, setDictation] = useState(null) const dictRef = useRef<{ stop: () => Promise; cancel: () => void; stream: MediaStream } | null>(null) const [, tick] = useState(0) @@ -455,7 +474,9 @@ const Composer = forwardRef(function Composer(pro return alternate ? (followUp === 'queue' ? 'steer' : 'queue') : followUp } const action = actionFor(useModifierHeld(followUps)) + const here = destinations?.projectId ? projects.find((p) => p.id === destinations.projectId) : undefined const placeholder = answering ? answering.placeholder + : inTask ? (here ? `A task for ${here.name}, e.g. “Renew passport fri p1”` : 'A task, e.g. “Renew passport fri p1 #folder”') : followUps ? (actionFor(false) === 'steer' ? 'Steer this reply: add context or change course' : 'Queue a message for when this reply finishes') : idlePlaceholder const handing = useRef(false) @@ -511,7 +532,7 @@ 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 ? mentionAtCaret(value, caret) : null + const token = allowCommands && !dictation && !inTask ? mentionAtCaret(value, caret) : 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() @@ -519,9 +540,9 @@ const Composer = forwardRef(function Composer(pro // `$` 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 work = useSyncExternalStore(dollar ? subscribeWork : noSubscribe, getWork, getWork) - const projects = useChat((s) => s.projects) const places = dollar && destinations ? rankDestinations({ projects, tasks: work.tasks, projectId: destinations.projectId, taskId: destinations.taskId }, query!.term) + .filter((d) => d.kind !== 'new-task' || canMakeTask) : [] const items: MenuItem[] = [...places.map((d): MenuItem => ({ kind: 'dest', d })), ...matches.map((c): MenuItem => ({ kind: 'cmd', c }))] useEffect(() => { setSel(0) }, [value]) @@ -551,9 +572,43 @@ const Composer = forwardRef(function Composer(pro if (!query || !destinations || placeHeld) 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 } destinations.onPick(it.d, next, pos) } + // --- `$task`: a new task typed in the box --------------------------------- + // Whatever is in the box already is the start of its title. Enter makes the task + // where the chat is being started (or its #folder) and the chat view moves this + // draft to a new chat for it, files and all; the box is then the chat's first message. + const task = useMemo(() => (inTask + ? readNewTask(value, { now: new Date(), folders: folderNames(projects), ignore: taskIgnore, projectId: destinations?.projectId ?? null }) + : null), [inTask, value, projects, taskIgnore, destinations?.projectId]) + const taskHeld = placeHeld || (taskBusy ? 'Adding the task' : '') + const taskReady = !!task?.fields && !taskHeld + + function startTask() { + setTaskIgnore([]) + setTaskMode(true) + requestAnimationFrame(() => focusBox()) + } + + function leaveTask() { + setTaskMode(false) + setTaskIgnore([]) + focusBox() + } + + async function submitTask() { + if (!task?.fields || !destinations?.onNewTask) return + if (taskHeld) { if (placeHeld) pushError(`${placeHeld}, then add the task.`); return } + setTaskBusy(true) + try { + if (await destinations.onNewTask(task.fields)) { setTaskMode(false); setTaskIgnore([]) } + } finally { + setTaskBusy(false) + } + } + function startMention(prefix: '/' | '$' = '/') { const sep = value && !/\s$/.test(value) ? ' ' : '' const next = `${value}${sep}${prefix}` @@ -575,6 +630,12 @@ const Composer = forwardRef(function Composer(pro /** The editor's keys first; true when the composer used the key. */ function onKeyDown(e: KeyboardEvent) { + if (inTask) { + // One line: Return adds it, on a phone too. Escape, or Backspace in an empty box, makes it a message again. + if (e.key === 'Enter' && !e.shiftKey) { void submitTask(); return true } + if (e.key === 'Escape') { leaveTask(); return true } + if (e.key === 'Backspace' && !value && !taskBusy) { leaveTask(); return true } + } if (items.length) { if (e.key === 'ArrowDown') { setSel((s) => (s + 1) % items.length); return true } if (e.key === 'ArrowUp') { setSel((s) => (s - 1 + items.length) % items.length); return true } @@ -640,7 +701,7 @@ const Composer = forwardRef(function Composer(pro const secs = dictation ? Math.floor((Date.now() - dictation.startedAt) / 1000) : 0 const compacting = !!compactSend && !compactSend.keep - const showVoice = !!onVoice && !busy && !value.trim() && !tray.length && !dictation && !onResume + const showVoice = !!onVoice && !busy && !value.trim() && !tray.length && !dictation && !onResume && !inTask const removing = drafts.find((d) => d.key === confirmRemove) return ( @@ -654,14 +715,14 @@ const Composer = forwardRef(function Composer(pro return ( {group !== prev &&
{group}
} - )} {allowCommands && (catalog.length > 0 || destinations) &&
} + {canMakeTask && !inTask && ( + + )} {allowCommands && catalog.length > 0 && ( + ) : inTask ? ( + ) : busy ? ( ) : onResume && !hasContent ? ( diff --git a/web/src/chat/NewTaskBar.tsx b/web/src/chat/NewTaskBar.tsx new file mode 100644 index 0000000..b074bd9 --- /dev/null +++ b/web/src/chat/NewTaskBar.tsx @@ -0,0 +1,64 @@ +// The strip atop the composer while `$task` has made the box a task line: what the +// words were read as (due day, priority, folder, as the Tasks page's quick-add line +// shows them), each with a × that keeps the word as text, and a × that turns the +// box back into a message. +import React from 'react' +import type { Project } from './types' +import type { Hint } from '../todos/parse' +import { hintKey } from '../todos/parse' +import { dueText } from '../todos/format' +import { folderFor, folderLabel } from '../todos/folders' +import { FolderIcon } from '../work/FolderField' +import { TI } from './ui' +import { IconChecklist, IconCalendar, IconFlag, IconLoader2, IconX } from './icons' + +const PRIORITY = { 4: 'P1', 3: 'P2', 2: 'P3', 1: 'P4' } as const + +export default function NewTaskBar({ hints, folderId, typedFolder, projects, now, busy, onIgnore, onLeave }: { + hints: readonly Hint[] + /** Where the task will be filed (typed with #folder, else where the chat is being started). */ + folderId: string | null + /** The folder came from a #word, so its chip can be undone like the others. */ + typedFolder: boolean + projects: readonly Project[] + now: Date + busy: boolean + onIgnore: (key: string) => void + onLeave: () => void +}) { + const folder = folderFor(folderId, projects) + const keep = (e: React.MouseEvent) => e.preventDefault() + return ( +
+ + {busy ? : } + New task + + + {hints.filter((h) => h.kind !== 'folder').map((h) => ( + + + {h.kind === 'due' && h.dueDate ? dueText(h.dueDate, now) : h.priority ? PRIORITY[h.priority] : h.text} + + + ))} + + + {folderLabel(folderId, projects)} + {typedFolder && (() => { + const h = hints.find((x) => x.kind === 'folder')! + return ( + + ) + })()} + + ↵ adds it and starts a chat +
+ ) +} diff --git a/web/src/chat/chat.css b/web/src/chat/chat.css index ca8f463..7189840 100644 --- a/web/src/chat/chat.css +++ b/web/src/chat/chat.css @@ -636,6 +636,26 @@ button.vc-ref:focus-visible { outline: 2px solid currentColor; outline-offset: 1 .vc-send.stop { background: var(--text); } .vc-send.voice { background: var(--text); } .vc-tray { display: flex; gap: 10px; flex-wrap: wrap; padding: 4px 2px 10px; } +/* `$task`: the box is a new task's line (NewTaskBar.tsx). */ +.vc-box.is-task, .vc-box.is-task:focus-within { border-color: color-mix(in srgb, var(--accent) 45%, transparent); } +.vc-newtask { display: flex; align-items: center; flex-wrap: wrap; gap: 6px; padding: 0 2px 8px; font-size: 12px; } +.vc-newtask-tag, .vc-newtask-chip { + display: inline-flex; align-items: center; gap: 5px; height: 22px; padding: 0 3px 0 8px; border-radius: 999px; + color: var(--text); white-space: nowrap; +} +.vc-newtask-tag { background: color-mix(in srgb, var(--accent) 22%, transparent); font-weight: 500; } +.vc-newtask-chip { background: var(--vc-raise); } +.vc-newtask-chip.priority { background: color-mix(in srgb, var(--amber) 18%, transparent); } +.vc-newtask-chip.folder { padding-right: 8px; max-width: 100%; overflow: hidden; text-overflow: ellipsis; } +.vc-newtask-chip.folder:has(button) { padding-right: 3px; } +.vc-newtask-chip svg, .vc-newtask-tag > svg { flex: none; color: var(--vc-soft); } +.vc-newtask button { + display: grid; place-items: center; width: 16px; height: 16px; padding: 0; border: 0; border-radius: 50%; + background: none; color: var(--vc-faint); cursor: pointer; +} +.vc-newtask button:hover { background: color-mix(in srgb, var(--text) 14%, transparent); color: var(--text); } +.vc-newtask-help { margin-left: auto; color: var(--vc-faint); } +@media (pointer: coarse) { .vc-newtask-help { display: none; } } .vc-plus-wrap { position: relative; } .vc-plus-menu { bottom: calc(100% + 8px); left: -4px; width: 300px; } .vc-dictation { display: flex; align-items: center; gap: 12px; height: 40px; padding: 0 8px; } diff --git a/web/src/chat/composerDestinations.test.tsx b/web/src/chat/composerDestinations.test.tsx index 777e922..e029da7 100644 --- a/web/src/chat/composerDestinations.test.tsx +++ b/web/src/chat/composerDestinations.test.tsx @@ -4,6 +4,7 @@ import { render, screen, fireEvent, cleanup, act, waitFor } from '@testing-libra import type { Editor } from '@tiptap/core' import type { Project } from './types' import type { Destination } from './destinations' +import type { NewTaskFields } from './newTask' // The composer's `$` menu in a chat not started yet: folders and tasks first, and // picking one takes the `$…` out of the words and hands them to the chat view. @@ -26,11 +27,14 @@ const { default: Composer } = await import('./Composer') afterEach(cleanup) -function Harness({ onPick, destinations = true }: { onPick: (d: Destination, text: string) => void; destinations?: boolean }) { +function Harness({ onPick, destinations = true, onNewTask, projectId = null, onSend = () => {} }: { + onPick: (d: Destination, text: string) => void; destinations?: boolean + onNewTask?: (fields: NewTaskFields) => Promise; projectId?: string | null; onSend?: () => void +}) { const [value, setValue] = useState('') return ( - {}} onStop={() => {}} busy={false} - destinations={destinations ? { projectId: null, taskId: null, onPick: (d, text) => onPick(d, text) } : undefined} /> + {}} busy={false} + destinations={destinations ? { projectId, taskId: null, onPick: (d, text) => onPick(d, text), onNewTask } : undefined} /> ) } @@ -94,3 +98,58 @@ describe('composer $ destinations', () => { expect(screen.queryAllByRole('option')).toHaveLength(0) }) }) + +describe('composer $task', () => { + it('turns the box into a task line, reads its hints and makes the task on Enter', async () => { + const onPick = vi.fn() + const onSend = vi.fn() + const onNewTask = vi.fn(async () => true) + render() + const box = await type('$task') + expect(screen.getAllByRole('option')[0].textContent).toContain('New task') + expect(screen.getAllByRole('option')[0].textContent).toContain('filed in harbor') + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onPick).not.toHaveBeenCalled() + expect(screen.getByLabelText('New task')).toBeTruthy() + // The folder chip says where it goes before anything is typed. + expect(screen.getByLabelText('New task').textContent).toContain('Work - Acme / harbor') + await type('Renew passport p1') + expect(screen.queryAllByRole('option')).toHaveLength(0) + expect(screen.getByLabelText('New task').textContent).toContain('P1') + await act(async () => { fireEvent.keyDown(box, { key: 'Enter' }) }) + expect(onSend).not.toHaveBeenCalled() + expect(onNewTask).toHaveBeenCalledWith({ title: 'Renew passport', dueDate: null, priority: 4, folderId: 'harbor' }) + expect(screen.queryByLabelText('New task')).toBeNull() + }) + + it('takes the words already typed as the title, and a #folder over where the chat is', async () => { + const onNewTask = vi.fn(async () => true) + render() + const box = await type('Fix the site map #harbor $new') + fireEvent.keyDown(box, { key: 'Enter' }) + await act(async () => { fireEvent.keyDown(box, { key: 'Enter' }) }) + expect(onNewTask).toHaveBeenCalledWith({ title: 'Fix the site map', dueDate: null, priority: null, folderId: 'harbor' }) + }) + + it('keeps the task line when the bridge refuses it, and Escape makes it a message again', async () => { + const onSend = vi.fn() + const onNewTask = vi.fn(async () => false) + render() + const box = await type('$task') + fireEvent.keyDown(box, { key: 'Enter' }) + await type('Call the bank') + await act(async () => { fireEvent.keyDown(box, { key: 'Enter' }) }) + expect(onNewTask).toHaveBeenCalledTimes(1) + expect(screen.getByLabelText('New task')).toBeTruthy() + fireEvent.keyDown(box, { key: 'Escape' }) + expect(screen.queryByLabelText('New task')).toBeNull() + fireEvent.keyDown(box, { key: 'Enter' }) + expect(onSend).toHaveBeenCalledTimes(1) + }) + + it('offers no New task where the chat view cannot make one', async () => { + render() + await type('$task') + expect(screen.queryAllByRole('option').map((o) => o.textContent).join()).not.toContain('New task') + }) +}) diff --git a/web/src/chat/destinations.test.ts b/web/src/chat/destinations.test.ts index 04ba948..6e40d86 100644 --- a/web/src/chat/destinations.test.ts +++ b/web/src/chat/destinations.test.ts @@ -46,6 +46,7 @@ describe('rankDestinations', () => { // A bare `$` keeps to four places, so the tasks are in view under them. expect(keys(rankDestinations(ctx, ''))).toEqual([ 'p:lp', 'p:harbor', 'p:mn', 'p:wp', + 'new-task', 't:t2', 't:t1', 't:sheet:1:2:abcd', ]) expect(keys(rankDestinations(ctx, 'r'))).toContain('p:gb') @@ -87,6 +88,22 @@ describe('stripToken', () => { }) }) +describe('$task', () => { + const ctx = { projects, tasks, projectId: null, taskId: null } + + it('leads with New task for $task, $new and $ta, and not for one letter or other words', () => { + for (const term of ['task', 'tas', 'ta', 'new', 'ne', 'newtask', 'new-task']) expect(keys(rankDestinations(ctx, term))[0]).toBe('new-task') + expect(keys(rankDestinations(ctx, 't'))).not.toContain('new-task') + expect(keys(rankDestinations(ctx, 'harb'))).not.toContain('new-task') + expect(keys(rankDestinations(ctx, 'tasks'))).not.toContain('new-task') + }) + + it('moves nothing when picked: the task is made first', () => { + const now = { taskId: null, projectId: 'harbor' } + expect(placeAfter(rankDestinations(ctx, 'task')[0], now, () => 'wp')).toEqual(now) + }) +}) + describe('placeAfter', () => { const home = () => null it('a place keeps the task; a task takes its own folder, else stays put', () => { diff --git a/web/src/chat/destinations.ts b/web/src/chat/destinations.ts index d523cb1..14a89c2 100644 --- a/web/src/chat/destinations.ts +++ b/web/src/chat/destinations.ts @@ -1,6 +1,7 @@ // Where a new chat goes, picked from the composer with `$`: `$harbor` puts the // chat being started in the harbor folder, `$expense` starts it for that task -// (in the task's own folder, as "New chat for this task" does). Pure, so the +// (in the task's own folder, as "New chat for this task" does), and `$task` makes +// a new task right in the composer, then starts the chat for it. Pure, so the // composer's menu and its tests read the same rules. import type { Project } from './types' import type { WorkTask } from '../work/groups' @@ -9,6 +10,12 @@ export type Destination = | { kind: 'home'; key: string; name: string } | { kind: 'project'; key: string; name: string; project: Project; parent?: Project } | { kind: 'task'; key: string; name: string; task: WorkTask } + | { kind: 'new-task'; key: 'new-task'; name: 'New task' } + +/** What `$` takes for "make a new task": `$task`, `$new`, `$newtask`, from two letters on. */ +const NEW_TASK_WORDS = ['task', 'new', 'new-task', 'newtask'] +export const wantsNewTask = (term: string) => term.length >= 2 && NEW_TASK_WORDS.some((w) => w.startsWith(term)) +const NEW_TASK: Destination = { kind: 'new-task', key: 'new-task', name: 'New task' } /** A name as `$` reaches it: lower case, every run of other characters one hyphen. */ export const slug = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') @@ -44,7 +51,8 @@ const PLACES_BARE = 4 /** * The `$` menu's places (Home, projects, folders) then tasks, best matches first. - * None for a price ("$40", "$4.99", "$1,000"): Enter should send it. + * "New task" leads when the term asks for it (`$task`) and sits between the places + * and the tasks for a bare `$`. None for a price ("$40", "$4.99", "$1,000"): Enter should send it. */ export function rankDestinations(ctx: DestinationContext, term: string): Destination[] { if (/^\d[\d.,]*$/.test(term)) return [] @@ -79,10 +87,10 @@ export function rankDestinations(ctx: DestinationContext, term: string): Destina || dueOrder(a.task) - dueOrder(b.task) || b.task.updatedAt - a.task.updatedAt) - return [ - ...places.slice(0, t ? PLACES : PLACES_BARE).map((x) => x.d), - ...tasks.slice(0, TASKS).map(({ task }): Destination => ({ kind: 'task', key: `t:${task.ref}`, name: task.title, task })), - ] + const found = tasks.slice(0, TASKS).map(({ task }): Destination => ({ kind: 'task', key: `t:${task.ref}`, name: task.title, task })) + const shown = places.slice(0, t ? PLACES : PLACES_BARE).map((x) => x.d) + if (wantsNewTask(t)) return [NEW_TASK, ...shown, ...found] + return [...shown, ...(t ? [] : [NEW_TASK]), ...found] } const dueOrder = (t: WorkTask) => (t.dueDate ? Date.parse(t.dueDate.slice(0, 10)) || Infinity : Infinity) @@ -105,6 +113,8 @@ export function stripToken(value: string, start: number, end: number) { * being started for; a task takes its own folder, else stays where it is. */ export function placeAfter(d: Destination, now: { taskId: string | null; projectId: string | null }, taskHome: (ref: string) => string | null) { + // "New task" moves nothing until the task exists (the composer makes it first). + if (d.kind === 'new-task') return now 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 1f026ce..6fdb146 100644 --- a/web/src/chat/icons.ts +++ b/web/src/chat/icons.ts @@ -26,6 +26,7 @@ export { default as IconWorld } from '@tabler/icons-react/dist/esm/icons/IconWor export { default as IconHandClick } from '@tabler/icons-react/dist/esm/icons/IconHandClick.mjs' export { default as IconDeviceDesktop } from '@tabler/icons-react/dist/esm/icons/IconDeviceDesktop.mjs' export { default as IconChecklist } from '@tabler/icons-react/dist/esm/icons/IconChecklist.mjs' +export { default as IconSquarePlus } from '@tabler/icons-react/dist/esm/icons/IconSquarePlus.mjs' export { default as IconTarget } from '@tabler/icons-react/dist/esm/icons/IconTarget.mjs' export { default as IconListCheck } from '@tabler/icons-react/dist/esm/icons/IconListCheck.mjs' export { default as IconBulb } from '@tabler/icons-react/dist/esm/icons/IconBulb.mjs' diff --git a/web/src/chat/newTask.ts b/web/src/chat/newTask.ts new file mode 100644 index 0000000..f3e76d6 --- /dev/null +++ b/web/src/chat/newTask.ts @@ -0,0 +1,25 @@ +// `$task` in a new chat's composer: the box becomes a task line. What is typed is +// read the way the Tasks page's quick-add line reads it (todos/parse.ts: "tomorrow", +// "p2", "#folder"), and the task is filed where the chat is being started unless a +// #folder says otherwise. Pure, so the composer and its tests read the same rules. +import { parseQuickAdd, type FolderName, type QuickAdd } from '../todos/parse' +import { plainRefs } from './refs' +import { messageText } from './editor/markdown' + +export interface NewTaskFields { + title: string + dueDate: string | null + priority: 1 | 2 | 3 | 4 | null + /** Where the task is filed (and the chat for it starts); null is Personal. */ + folderId: string | null +} + +/** The box's text as one line: a file chip reads as its name, lines run together. */ +export const taskLine = (value: string) => plainRefs(messageText(value)).replace(/\s+/g, ' ').trim() + +export function readNewTask(value: string, opts: { now: Date; folders: readonly FolderName[]; ignore: readonly string[]; projectId: string | null }): { parsed: QuickAdd; fields: NewTaskFields | null } { + const parsed = parseQuickAdd(taskLine(value), { now: opts.now, folders: opts.folders, ignore: opts.ignore }) + const title = parsed.title.slice(0, 500).trim() + if (!title) return { parsed, fields: null } + return { parsed, fields: { title, dueDate: parsed.dueDate, priority: parsed.priority, folderId: parsed.folderId ?? opts.projectId } } +} diff --git a/web/src/chat/useChatDrafts.test.ts b/web/src/chat/useChatDrafts.test.ts index 6344523..5a96162 100644 --- a/web/src/chat/useChatDrafts.test.ts +++ b/web/src/chat/useChatDrafts.test.ts @@ -18,10 +18,12 @@ vi.mock('./store', () => ({ })) vi.mock('./api', () => ({ holdUploads: vi.fn(async () => ({ held: [], missing: [] })), deleteUpload: vi.fn() })) vi.mock('../toast', () => ({ pushToast: vi.fn(), pushError: vi.fn() })) -vi.mock('../work/state', () => ({ taskHome: () => null })) +const createTask = vi.fn() +vi.mock('../work/state', () => ({ taskHome: () => null, createTask: (...args: unknown[]) => createTask(...args) })) const { useChatDrafts } = await import('./useChatDrafts') const { drafts } = await import('./draftsWeb') +const store = await import('./store') const thread = (id: string, extra: Partial): ChatThread => ({ id, kind: 'regular', messages: [], createdAt: 1, updatedAt: 1, ...extra }) as ChatThread const local = (id: string) => ({ id: `local-${id}`, role: 'user' as const, content: 'x', createdAt: 1 }) @@ -74,3 +76,28 @@ describe('a task picked from the new-chat page', () => { expect(drafts.keyAt({ kind: 'task', id: 't2' })).not.toBe('c1') }) }) + +describe('$task: a task made in the composer', () => { + const fields = { title: 'Renew passport', dueDate: null, priority: null, folderId: null } + + it('makes the task and starts a chat for it with an empty box', async () => { + fake.threads = [] + const home = drafts.keyAt({ kind: 'home' }) + drafts.write(home, { text: 'Renew passport' }, { place: { kind: 'home' } }) + createTask.mockResolvedValueOnce({ ref: 't9', title: 'Renew passport' }) + expect(await hook().newTask(fields)).toBe(true) + expect(createTask).toHaveBeenLastCalledWith(fields, null) + expect(drafts.get().drafts[home]).toBeUndefined() + expect(store.startTaskDraft).toHaveBeenLastCalledWith('t9', null) + }) + + it('keeps the words when the bridge refuses the task', async () => { + const home = drafts.keyAt({ kind: 'home' }) + drafts.write(home, { text: 'Renew passport' }, { place: { kind: 'home' } }) + createTask.mockResolvedValueOnce(null) + vi.mocked(store.startTaskDraft).mockClear() + expect(await hook().newTask(fields)).toBe(false) + expect(drafts.get().drafts[home].text).toBe('Renew passport') + expect(store.startTaskDraft).not.toHaveBeenCalled() + }) +}) diff --git a/web/src/chat/useChatDrafts.ts b/web/src/chat/useChatDrafts.ts index 8da7b75..3b759f3 100644 --- a/web/src/chat/useChatDrafts.ts +++ b/web/src/chat/useChatDrafts.ts @@ -11,7 +11,8 @@ import { } from './draftsShared' import { drafts, useDraftState, useMissingUploads, setShownDraft, takeOpenedDraft, openDraft } from './draftsWeb' import { placeAfter, type Destination } from './destinations' -import { taskHome } from '../work/state' +import { createTask, taskHome } from '../work/state' +import type { NewTaskFields } from './newTask' import { pushToast } from '../toast' import type { ComposerHandle, FollowUpPayload } from './Composer' import type { Attachment, ChatThread, Project } from './types' @@ -94,6 +95,23 @@ export function useChatDrafts({ activeId, active, scopeProject, draftTaskId, dra requestAnimationFrame(() => composer.current?.focus()) } + /** + * `$task`: the box's words were the task's title. Make the task, then start a chat + * for it with this draft (its files go along; its words are the task now, so the + * chat's box starts empty). False when the bridge refused it: the words stay. + */ + const newTask = async (fields: NewTaskFields) => { + const key = draftKey + const task = await createTask(fields, fields.folderId) + if (!task) return false + drafts.write(key, { text: '' }, at) + // He moved on while it was being added: the task is made, and he stays where he is. + if (keyRef.current !== key) { pushToast(`Added “${task.title}” to your tasks.`, 'info'); return true } + placeDraft({ taskId: task.ref, projectId: fields.folderId }) + requestAnimationFrame(() => composer.current?.focus()) + return true + } + // --- sending --------------------------------------------------------------- /** * The draft leaves the composer as it is sent. Returns what puts it back if the @@ -175,7 +193,7 @@ export function useChatDrafts({ activeId, active, scopeProject, draftTaskId, dra const keepEdit = (threadId: string, text: string, files: Attachment[]) => keepEditIn(drafts, threadId, text, files, atRef.current) return { - draftKey, input: rec?.text || '', setInput, askFresh, startIn, startForTask, pickDestination, takeForSend, fromDraft, onDiscarded, + draftKey, input: rec?.text || '', setInput, askFresh, startIn, startForTask, pickDestination, newTask, takeForSend, fromDraft, onDiscarded, onAttachmentsChange, showEditFiles, missingFiles, removeMissing, keepEdit, } } diff --git a/web/src/components/ChatView.tsx b/web/src/components/ChatView.tsx index eab2f05..f410a25 100644 --- a/web/src/components/ChatView.tsx +++ b/web/src/components/ChatView.tsx @@ -281,7 +281,7 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane const onEditFiles = useCallback((files: Attachment[]) => setQueueEdit((e) => (e ? { ...e, files } : e)), []) // What the composer shows: an open chat's own draft, or the new-chat draft its place shows now. const { - draftKey, input, setInput, askFresh, startIn, startForTask, pickDestination, takeForSend, fromDraft, onDiscarded, + draftKey, input, setInput, askFresh, startIn, startForTask, pickDestination, newTask, takeForSend, fromDraft, onDiscarded, onAttachmentsChange, showEditFiles, missingFiles, removeMissing, keepEdit, } = useChatDrafts({ activeId, active, scopeProject, draftTaskId, draftKind, setDraftKind, composer, visible, editing, onEditFiles, @@ -613,7 +613,7 @@ export default function ChatView({ onAuthError, visible = true, onOpenMenu, pane displace: (text) => setInput(input.trim() ? `${input.replace(/\s+$/, '')}\n${text}` : text), }) - const destinations = { projectId: scopeProject?.id ?? null, taskId: draftTaskId, onPick: pickDestination } + const destinations = { projectId: scopeProject?.id ?? null, taskId: draftTaskId, onPick: pickDestination, onNewTask: newTask, draftKey } const missingEl = missingFiles.length > 0 && !editing ? (