From 8245aab40ba1fc92abe358bd1776a75721e39f85 Mon Sep 17 00:00:00 2001 From: ehonis Date: Mon, 16 Nov 2026 16:05:28 -0500 Subject: [PATCH] Folder page: a T3 Code-style card for what its chats share Published from the private repository by oss-sync. - Folder page: a T3 Code-style card for what its chats share 12 files changed, 893 insertions(+), 497 deletions(-) --- AGENTS.md | 2 +- docs/chat.md | 39 ++- docs/search.md | 2 +- web/src/chat/ProjectCard.tsx | 521 ++++++++++++++++++++++++++++++ web/src/chat/ProjectHome.tsx | 433 ++----------------------- web/src/chat/chat.css | 63 +++- web/src/chat/pins.ts | 59 ++++ web/src/chat/projectCard.test.tsx | 155 +++++++++ web/src/chat/ui.tsx | 8 + web/src/components/ChatView.tsx | 16 +- web/src/work/TaskCard.tsx | 55 +--- web/src/work/work.css | 37 ++- 12 files changed, 893 insertions(+), 497 deletions(-) create mode 100644 web/src/chat/ProjectCard.tsx create mode 100644 web/src/chat/pins.ts create mode 100644 web/src/chat/projectCard.test.tsx diff --git a/AGENTS.md b/AGENTS.md index fd5d02c..a29310c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -92,7 +92,7 @@ open-ended work. The default provider and model come from Settings → Providers | Source health | `sources/`, `web/src/sources/`, `mobile/src/features/settings/panes/ConnectionsPane.tsx` | One sync-run log every connector writes to (`data/source-runs.db`, `SOURCE_RUNS_DB`), one run per operation, not per request: a connector takes `runs` and wraps each operation in `tracker(runs)(id, fn)` (`sources/track.mjs`; calls nested inside join it). Strava and WHOOP calls that reach the provider through Bushido (not Bushido's cache reads; its `status` is noted), Calendar, Gmail and Drive per account, the task sheet feed (`task-sheet`), feed scans and MCP servers in the gateway status check. Health is folded from the runs (`sources/health.mjs`): degraded, then failing after three failures in a row over ten minutes; not set up; last OK, failing since, error, rows. Errors are scrubbed in layers before they are stored, runs kept 30 days. A run log that cannot be opened turns health off instead of stopping the bridge (`openSourceRuns`). `GET /api/sources` names the goals each source feeds (`GOAL_SOURCE_IDS`, `goalService.sourcedGoals()`); Settings → Connections › Data sources shows only failing and erroring sources in full (with the goals they feed) and folds working and not-set-up ones into a count each (`sortSources`), leaving MCP servers to the MCP section on the web, and a metric whose source is failing says so on its goal card. The owner is told once per outage, with no error text (`sources/notice.mjs`, key `source::failing:`, marked sent only once queued, dropped at delivery if the source recovered). `docs/source-health.md`. | | Apple data | `apple/`, the "Apple" block in `bridge.mjs`, the Messages view in `web/src/messages/` | macOS only, off unless `APPLE_ENABLED=true`. Reads Messages (`chat.db`), Contacts and Photos (`Photos.sqlite` plus Photos' own search index) read-only; sends through the Messages app with `osascript`. The owner sends from the Messages tab (last on the desktop rail, not on the phone drawer; `/messages` still opens); agents only stage an `imessage` inbox proposal (`totem_apple_propose_message`), which only the dashboard can accept. `docs/apple.md`. | | 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). Native per-provider session resume, attachments, 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`), 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` | 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. Every list (Home, project, folder) ends with its own Snoozed and Settled shelves, 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, a steer or his next message). The chats panel is scoped to Home or one project; chats drag onto folders and projects. `docs/chat.md` → Projects. | +| Chat projects | `chat/projects.mjs`, `chat/memory-ref.mjs`, `web/src/chat/Project*.tsx` | A project's page is its composer and chats; 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. Every list (Home, project, folder) ends with its own Snoozed and Settled shelves, 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, a steer or his next message). The chats panel is scoped to Home or one project; chats drag onto folders and projects. `docs/chat.md` → Projects. | | Tasks panel | `web/src/work/`, `chat/task-folders.mjs`, `chat/task-link.mjs`, `/api/chat/task-folders` in `bridge.mjs` | The chats panel's third face (Chats · Totems · Tasks): open local tasks and the shared sheet's action items, grouped by the chat project or folder each is filed under (a task's `folderId`; a sheet row's filing in `data/task-folders.json`, `TASK_FOLDERS_FILE`, `none` meaning Personal on purpose), each with its linked chats under it. 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). A chat names at most one task (`thread.taskId`: a task id or a sheet row id), linked from its "…", by dropping it on a task, or by starting a chat from the task (`startTaskDraft`; the first send carries `taskId`, kept by `startChatTurn` on a new chat only). 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 only while the face, 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). Not in the iPhone app yet. `docs/chat.md` → Tasks panel, → Placing a new chat with `$`. | | 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. | diff --git a/docs/chat.md b/docs/chat.md index 7986ff2..58880d3 100644 --- a/docs/chat.md +++ b/docs/chat.md @@ -1035,10 +1035,26 @@ do (`chat/projects.mjs`, `web/src/chat/Project*.tsx`): | Shared | Where | Who writes it | |---|---|---| -| Default account and model | `project.json` → `provider`, `modelSettings` | The owner (Settings tab). A new chat in the project starts on it; any one chat can still pick another. Optional: see Which model a new chat starts on. | +| Default account and model | `project.json` → `provider`, `modelSettings` | The owner (the card's Model row). A new chat in the project starts on it; any one chat can still pick another. Optional: see Which model a new chat starts on. | | Instructions | `project.json` → `instructions` | The owner. | -| Memory | `//memory.md` | The agent, with its own file tools; the owner can edit it on the Memory tab. | -| Files | `project.json` → `files` (upload ids) | Uploaded on the Files tab, attached in any of the project's chats, or made by the agent in one (`source`: `upload`, `chat`, `agent`). | +| Memory | `//memory.md` | The agent, with its own file tools; the owner can edit it from the card's Memory row. | +| Files | `project.json` → `files` (upload ids) | Uploaded from the card's Files row, attached in any of the project's chats, or made by the agent in one (`source`: `upload`, `chat`, `agent`). | + +A project's or folder's page (the chat pane with the place open and no chat) is its +composer over its folders and chats. What those chats share is its **card** +(`web/src/chat/ProjectCard.tsx`), T3 Code's thread card for the place: its icon and name +(a folder says which project it is in), then one row each for Files, Instructions, +Memory, Model and Settings (name, icon or picture, delete), each with a one-line summary +that opens its editor under the row, one at a time. On desktop it is pinned at the pane's +top right; when a new chat is started from a task, the task's card (Tasks panel → The +task card) is stacked under it in the same column (`.vc-pins` in `ChatView`), each +folding to its title row on its own (`web/src/chat/pins.ts`; the folder's choice is +`totem.projectPin.folded`). While either is unfolded the page moves left to clear the +column (340px with the folder's card in it, 300px for the task alone). A section once +opened stays mounted while another row is open or the card is folded, so a half-typed +edit survives the card folding itself when the column narrows (the canvas opening, say). +On a phone the card sits in the page under the composer, folded to one row. A search hit on a +project's instructions or memory opens that row (`openProjectSection`) and flashes it. ### Which model a new chat starts on @@ -1057,7 +1073,7 @@ Most specific first, the same in the dashboard, the app and the bridge A project's or folder's `modelSettings` only apply on its own account. A new project or folder has no default of its own, so it follows its project or Settings → Providers until -the owner picks one; "Use …" on the Settings tab clears a picked one back to that. +the owner picks one; "Use …" under the card's Model row clears a picked one back to that. (One made from the dashboard before 2026-11 holds a copy of the global default taken when it was made, which reads as its own pick until cleared.) An account that is no longer enabled is passed over. An existing chat never takes a model picked in another chat. A chat an agent @@ -1109,7 +1125,7 @@ chat's conclusions reach the next. still shows it. **Deleting a project** deletes its files, instructions and memory (and its folders') and moves its chats to Home. Thread deletion and the orphan sweep leave project files alone. -- **A picture instead of an icon.** Settings → Icon also takes an uploaded image or a +- **A picture instead of an icon.** The card's Settings → Icon also takes an uploaded image or a website's own icon (`image`, an upload id; the bridge adds a signed `imageUrl`). "Use site icon" has the bridge read the page's ``/apple-touch-icon tags, then `/apple-touch-icon.png` and `/favicon.ico`, and keep the first that is really a PNG, @@ -1131,11 +1147,11 @@ context (`projectBlock(..., { parent })`; the parent memory is named only when i entries, and Claude is denied writing it) and keep only the folder's memory, so a side topic never leaks into the project. The owner moves what should be shared up by hand: -- **Memory:** the folder's Memory tab → "Move to " lists entries (top-level +- **Memory:** the folder card's Memory row → "Move to " lists entries (top-level bullets with their indented lines, or paragraphs, under their heading: `memoryEntries` in `chat/projects.mjs`, twinned in `web/src/chat/memoryEntries.ts`). Picked entries land under the same heading in the parent and leave the folder. -- **Files:** pick files on the folder's Files tab → "Move to ". +- **Files:** pick files under the folder card's Files row → "Move up" (to the project). - **Deleting a folder** moves its chats up to its project. In the panel, a project's folders sit above its own chats and unfold in place. Dragging @@ -1314,12 +1330,13 @@ moves between a task and any of its chats (`web/src/work/`). but for its folder, with Open in the sheet. It is drawn two ways: - **Pinned.** The open chat's own task (a linked chat's `taskId`, or the task a new chat is being started from) sits at the chat's top right under the header for as - long as the chat is open (`PinnedTask`, mounted by `ChatView`). Nothing outside + long as the chat is open (`PinnedTask`, mounted by `ChatView`), under the folder's + own card on a folder's page (Projects), the two stacked in one column (`.vc-pins`). Nothing outside closes it; its chevron folds it to its title row, kept per device (`totem.taskPin.folded`), and with no choice made it starts folded while the chat - column is under 1000px. Unfolded, the messages and composer move left just enough to - clear it (a `:has()` rule in `work.css`, percentages of `.vc`, no JS), keeping at - least 520px. Opening that task anywhere (the strip, its row in the chats panel) + column is under 1000px. While any card in the column is unfolded, the messages and + composer move left just enough to clear it (a `:has()` rule in `work.css`, percentages + of `.vc`, no JS), keeping at least 520px. Opening that task anywhere (the strip, its row in the chats panel) unfolds and flashes it rather than opening a dialog (`pinTask` in `card.ts`), but only while the chat is the page on screen. Not on a phone. - **A dialog.** Any other task, opened from the chats panel's Tasks face (or the chat's diff --git a/docs/search.md b/docs/search.md index 0791543..39e0455 100644 --- a/docs/search.md +++ b/docs/search.md @@ -73,7 +73,7 @@ Appearance), a still outline that clears after the same second. On the web this | `list` | the list, then the item the query matched (`target.item`); a title match lands on the list's header. The app opens the list's own screen. | | `journal` | the entry's card. | | `note` | the heading its section starts at (`target.line`; text before the first heading lands on the note's start). The app shows a note as a sheet of that section, so nothing to scroll. | -| `project` | the Instructions or Memory tab (`target.section`), flashed. The app has no such tabs; it flashes the instructions on the project page. | +| `project` | the Instructions or Memory row of the project's card (`target.section`), opened and flashed. The app has no such card; it flashes the instructions on the project page. | | `totem` | the totem's Settings tab at its instructions, or its Memory tab (`target.section`). | `target.item` is chosen at search time: a source may give a doc `parts` (`[{ id, text }]`, a diff --git a/web/src/chat/ProjectCard.tsx b/web/src/chat/ProjectCard.tsx new file mode 100644 index 0000000..1f56b85 --- /dev/null +++ b/web/src/chat/ProjectCard.tsx @@ -0,0 +1,521 @@ +import React, { useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react' +import { + useChat, updateProject, saveProjectMemory, addProjectFiles, removeProjectFiles, deleteProject, openArtifact, + setActive, threadTitle, threadChoice, foldersOf, moveMemoryUp, moveFilesUp, setProjectFavicon, +} from './store' +import { memoryEntries } from './memoryEntries' +import { uploadFile } from './api' +import { ARTIFACT_PREVIEWABLE, artifactIcon } from './ArtifactPanel' +import ModelPicker, { chipLabel } from './ModelPicker' +import ProjectIcon, { PROJECT_ICONS } from './ProjectIcon' +import { THREAD_ICONS } from './threadIcons.gen' +import type { Project, ProjectFile } from './types' +import { TI, formatBytes, when } from './ui' +import { + IconUpload, IconTrash, IconExternalLink, IconPaperclip, IconFolderUp, IconWorld, IconX, + IconBrain, IconChevronDown, IconChevronUp, IconFiles, IconFileText, IconSettings, IconSparkles, +} from './icons' +import { usePinFold } from './pins' +import { pushError, pushToast } from '../toast' +import { downloads } from '../downloads' +import { LANDING_TIMEOUT_MS, landKey } from '../landing' +import '../work/work.css' + +// A project's or folder's card, T3 Code's thread card for the place a chat lives: +// its name, then one row per thing its chats share (files, instructions, memory, +// default model, settings), each opening under its row, one at a time. On the +// place's own page (ProjectHome) it is pinned at the chat pane's top right, over +// the chat's task card when a new chat is being started from a task (ChatView +// stacks both in `.vc-pins`); it folds to its name like the task card. On a phone +// it sits in the page, under the composer. + +export type CardSection = 'files' | 'instructions' | 'memory' | 'model' | 'settings' + +const PIN_FOLD_KEY = 'totem.projectPin.folded' + +// A section asked for from outside (a search hit on the instructions or memory). +// Kept until a card for that place takes it, since the card may mount after the ask. +// It lapses with the landing that asked (LANDING_TIMEOUT_MS), so a later visit opens nothing unasked. +let asked: { projectId: string; section: CardSection; at: number } | null = null +const askSubs = new Set<() => void>() +export function openProjectSection(projectId: string, section: CardSection, now = Date.now()) { + asked = { projectId, section, at: now } + for (const fn of askSubs) fn() +} +const subscribeAsk = (fn: () => void) => { askSubs.add(fn); return () => { askSubs.delete(fn) } } + +/** Where a search hit on a section lands: the open section carries this key. */ +export const sectionLandKey = (projectId: string, section: CardSection) => landKey('project-section', `${projectId}:${section}`) + +const plural = (n: number, one: string) => `${n} ${one}${n === 1 ? '' : 's'}` + +interface CardProps { projectId: string; mode: 'pinned' | 'inline'; maxUploadBytes?: number } + +export default function ProjectCard(props: CardProps) { + const known = useChat((s) => s.projects.some((p) => p.id === props.projectId) || !!s.projectDetail[props.projectId]) + // The card measures its column once mounted (usePinFold), so it mounts only with a project to draw. + return known ? : null +} + +function Card({ projectId, mode, maxUploadBytes }: CardProps) { + const summary = useChat((s) => s.projects.find((p) => p.id === projectId)) + const detail = useChat((s) => s.projectDetail[projectId]) + const parent = useChat((s) => (summary?.parentId ? s.projects.find((p) => p.id === summary.parentId) : undefined)) + const models = useChat((s) => s.models) + const card = useRef(null) + const pinned = mode === 'pinned' + const fold = usePinFold(PIN_FOLD_KEY, card) + // On a phone the card sits in the page, folded to one row so the chats stay on the first screen. + const [inlineFolded, setInlineFolded] = useState(true) + const folded = pinned ? fold.folded : inlineFolded + const setFolded = pinned ? fold.setFolded : setInlineFolded + const [current, setCurrent] = useState(null) + // A section once opened stays mounted, only hidden, while another row is open or the card is + // folded (as it does by itself when the column narrows, say for the canvas): a draft survives. + const [visited, setVisited] = useState([]) + const open = (section: CardSection | null) => { + setCurrent(section) + if (section) setVisited((v) => (v.includes(section) ? v : [...v, section])) + } + + const ask = useSyncExternalStore(subscribeAsk, () => asked) + useEffect(() => { + if (!ask || ask.projectId !== projectId) return + asked = null + if (Date.now() - ask.at > LANDING_TIMEOUT_MS) return + open(ask.section) + fold.reveal() + setInlineFolded(false) + }, [ask, projectId]) + + const project = detail || (summary ? { ...summary, files: undefined } : null) + const memoryCount = useMemo(() => (detail ? memoryEntries(detail.memory || '').length : null), [detail?.memory]) + if (!project) return null + + const kind = parent ? 'folder' : 'project' + const follows = parent ? `${parent.name}’s model` : 'the default in Settings → Providers' + const choice = threadChoice(null, { provider: project.provider, modelSettings: project.modelSettings, projectId: project.id }) + const instructionsLine = (project.instructions || '').split('\n').map((l) => l.trim()).find(Boolean) + + const rows: { id: CardSection; icon: React.ComponentType; label: string; value: string; empty?: boolean; title?: string }[] = [ + { id: 'files', icon: IconFiles, label: 'Files', value: project.fileCount ? plural(project.fileCount, 'file') : 'None', empty: !project.fileCount }, + { id: 'instructions', icon: IconFileText, label: 'Instructions', value: instructionsLine || 'None', empty: !instructionsLine }, + { id: 'memory', icon: IconBrain, label: 'Memory', value: memoryCount == null ? '…' : memoryCount ? plural(memoryCount, 'note') : 'Empty', empty: !memoryCount }, + { + id: 'model', icon: IconSparkles, label: 'Model', value: `${chipLabel(choice.settings, choice.provider, models)}${project.provider ? '' : parent ? ` · from ${parent.name}` : ' · default'}`, + title: project.provider ? `New chats here start on this` : `Follows ${follows}`, + }, + { id: 'settings', icon: IconSettings, label: 'Settings', value: 'Name, icon', empty: true }, + ] + + const body = (section: CardSection) => { + switch (section) { + case 'files': return detail ? :

Loading files…

+ case 'instructions': return ( + updateProject(project.id, { instructions: v })} + placeholder="e.g. This is my day job at a logistics company. Answer like a senior colleague: short, concrete, no hedging. Use British spelling." + intro={parent + ? `Every chat in this folder follows these, on top of ${parent.name}’s instructions.` + : 'Every chat in this project follows these. Say who it’s for, what you’re working on, and how you want answers.'} + rows={8} + /> + ) + case 'memory': return detail ? :

Loading memory…

+ case 'model': return ( +
+

+ {project.provider + ? `New chats in this ${kind} start on this. You can still change it in any one chat.` + : `New chats here start on ${follows} until you pick one for this ${kind}.`} +

+
+ updateProject(project.id, patch)} /> + {project.provider && ( + + )} +
+
+ ) + case 'settings': return + } + } + + const label = `${parent ? 'Folder' : 'Project'}: ${project.name}` + const classes = ['wk-card', 'vc-pcard', pinned ? 'vc-pin pinned' : 'inline', folded ? 'folded' : ''].filter(Boolean).join(' ') + const foldLabel = folded ? `Show what ${project.name}’s chats share` : pinned ? `Fold ${project.name}’s card` : `Hide what ${project.name}’s chats share` + return ( +
+ {pinned ? ( +
+ + {folded ? ( + + ) : ( + + {project.name} + {parent && in {parent.name}} + + )} + +
+ ) : ( + // In the page the heading already names the place, so the head is one button naming what the card holds. + + )} + +
+ ) +} + +const SOURCE_LABEL: Record = { upload: 'Uploaded', chat: 'From a chat', agent: 'Made by Totem' } +type SourceFilter = 'all' | ProjectFile['source'] + +function FilesSection({ project, maxUploadBytes }: { project: Project; maxUploadBytes?: number }) { + const threads = useChat((s) => s.threads) + const parent = useChat((s) => (project.parentId ? s.projects.find((p) => p.id === project.parentId) : undefined)) + const [filter, setFilter] = useState('all') + const [picked, setPicked] = useState>(new Set()) + const [uploading, setUploading] = useState<{ name: string; progress: number }[]>([]) + const [dragging, setDragging] = useState(false) + const input = useRef(null) + const files = useMemo(() => [...(project.files || [])].sort((a, b) => b.addedAt - a.addedAt), [project.files]) + const shown = filter === 'all' ? files : files.filter((f) => f.source === filter) + const counts = useMemo(() => files.reduce((acc, f) => ({ ...acc, [f.source]: (acc[f.source] || 0) + 1 }), {} as Record), [files]) + useEffect(() => { setPicked((p) => new Set([...p].filter((id) => files.some((f) => f.id === id)))) }, [files]) + + async function upload(list: FileList | File[]) { + const all = Array.from(list) + const tooBig = all.filter((f) => maxUploadBytes && f.size > maxUploadBytes) + if (tooBig.length) pushError(`${tooBig.map((f) => f.name).join(', ')} ${tooBig.length === 1 ? 'is' : 'are'} over ${formatBytes(maxUploadBytes!)}.`) + const ok = all.filter((f) => !tooBig.includes(f)) + if (!ok.length) return + setUploading(ok.map((f) => ({ name: f.name, progress: 0 }))) + const ids: string[] = [] + await Promise.all(ok.map(async (f, i) => { + try { + const att = await uploadFile(f, f.name, { onProgress: (p) => setUploading((u) => u.map((x, j) => (j === i ? { ...x, progress: p } : x))) }) + ids.push(att.id) + } catch (e: any) { pushError(`${f.name}: ${e.message}`) } + })) + await addProjectFiles(project.id, ids) + setUploading([]) + } + + function remove(ids: string[]) { + if (!ids.length) return + removeProjectFiles(project.id, ids) + setPicked(new Set()) + pushToast(ids.length === 1 ? 'Removed the file from the project' : `Removed ${ids.length} files from the project`, 'info') + } + + async function moveUp(ids: string[]) { + if (!parent || !ids.length) return + try { + const n = await moveFilesUp(project.id, ids) + setPicked(new Set()) + pushToast(`Moved ${n === 1 ? 'the file' : `${n} files`} to ${parent.name}`, 'info') + } catch (e: any) { pushError(`Couldn't move the files: ${e.message}`) } + } + + function open(f: ProjectFile) { + if (ARTIFACT_PREVIEWABLE.test(f.mime) || f.kind === 'image') openArtifact({ uploadId: f.id, name: f.name, mime: f.mime, url: f.url, size: f.size }) + else if (f.url) downloads.start(f.url, f.name) + } + + const toggle = (id: string) => setPicked((p) => { const n = new Set(p); n.has(id) ? n.delete(id) : n.add(id); return n }) + const allShownPicked = shown.length > 0 && shown.every((f) => picked.has(f.id)) + + return ( +
{ if (Array.from(e.dataTransfer.types).includes('Files')) e.stopPropagation() }} + onDragOver={(e) => { if (Array.from(e.dataTransfer.types).includes('Files')) { e.preventDefault(); e.stopPropagation(); setDragging(true) } }} + onDragLeave={() => setDragging(false)} + onDrop={(e) => { e.preventDefault(); e.stopPropagation(); setDragging(false); if (e.dataTransfer.files?.length) upload(e.dataTransfer.files) }} + > +
+ + + {picked.size > 0 ? ( + <> + + {parent && } + + + ) : ( + + )} + { if (e.target.files?.length) upload(e.target.files); e.target.value = '' }} /> +
+ + {uploading.map((u) => ( +
+ + {u.name}Uploading {Math.round(u.progress * 100)}% +
+ ))} + + {!files.length && !uploading.length && ( + + )} + + {shown.length > 0 && ( + + )} + {shown.map((f) => { + const from = f.threadId ? threads.find((t) => t.id === f.threadId) : null + return ( +
+ toggle(f.id)} aria-label={`Select ${f.name}`} /> + + {f.url && ( + + )} + +
+ ) + })} + {dragging &&
Drop to add to {project.name}
} +
+ ) +} + +/** A text box saved with an explicit button, so a half-written edit never goes out. */ +function TextSection({ value, onSave, placeholder, intro, rows = 14, extra }: { + value: string + onSave: (v: string) => Promise + placeholder: string + intro: React.ReactNode + rows?: number + extra?: (draft: string, set: (v: string) => void) => React.ReactNode +}) { + const [draft, setDraft] = useState(value) + const [saving, setSaving] = useState(false) + const dirty = draft !== value + // Take the server's copy when it changes underneath (the agent edited the memory) unless he is mid-edit. + const last = useRef(value) + useEffect(() => { + const previous = last.current + last.current = value + setDraft((d) => (d === previous ? value : d)) + }, [value]) + async function save() { + setSaving(true) + try { await onSave(draft); pushToast('Saved', 'info') } catch (e: any) { pushError(`Couldn't save: ${e.message}`) } finally { setSaving(false) } + } + return ( +
+

{intro}

+