From 17c5889e2f027295f85ac7d7090ec729cc94d113 Mon Sep 17 00:00:00 2001 From: Ashot Petrosian Date: Thu, 26 Nov 2026 23:38:02 -0500 Subject: [PATCH 1/3] feat(code): finish the code editor: agent editing, blame, app-wide entry points, polish Codecast-Session: https://codecast.sh/conversation/jx7d599e2sfadf5gfa2fazhvss8jp1ge --- docs/architecture/code-editor.md | 151 +++++- packages/cli/src/blame.test.ts | 7 + packages/cli/src/blame.ts | 27 +- packages/cli/src/code/codeBlame.ts | 2 + .../cli/src/terminal/terminalServer.test.ts | 6 + packages/cli/src/terminal/terminalServer.ts | 17 +- packages/cli/src/vault/vaultServer.test.ts | 4 + packages/cli/src/vault/vaultServer.ts | 4 + packages/electron/main.js | 2 + packages/shared/blame/index.ts | 12 + packages/shared/blame/sessionTrailer.test.ts | 11 +- packages/shared/contracts/codeProtocol.ts | 5 + packages/shared/contracts/shortcutCatalog.ts | 5 + .../app/commit/[owner]/[repo]/[sha]/page.tsx | 9 +- packages/web/app/files/page.tsx | 86 ++- packages/web/app/globals.css | 65 ++- .../app/pr/[owner]/[repo]/[number]/page.tsx | 14 +- packages/web/app/tasks/[id]/page.tsx | 7 +- packages/web/components/CommandPalette.tsx | 10 +- packages/web/components/ConversationView.tsx | 7 +- packages/web/components/InlineDiff.tsx | 8 +- .../web/components/KeyboardShortcutsHelp.tsx | 25 +- .../web/components/OpenInEditorButton.tsx | 5 +- packages/web/components/PlanDetailPanel.tsx | 11 +- .../KeyboardShortcutsHelp.mount.test.tsx | 27 + .../__tests__/inlineDiffEdit.mount.test.tsx | 82 +++ packages/web/components/code/CodeEditor.tsx | 14 +- packages/web/components/code/CodeFileBar.tsx | 144 ++++- packages/web/components/code/CodeFileView.tsx | 200 +++++-- .../web/components/code/OverwriteReview.tsx | 25 + .../code/__tests__/codeFileBar.test.ts | 12 + .../code/__tests__/firstRun.mount.test.tsx | 111 ++++ .../typingAllFeatures.mount.test.tsx | 270 +++++++++ .../vaultFileViewRead.mount.test.tsx | 72 ++- .../code/__tests__/vimFirstRun.mount.test.tsx | 64 +++ .../__tests__/workspaceFocus.mount.test.tsx | 147 +++++ .../web/components/code/agent/AgentLayer.tsx | 76 ++- .../components/code/agent/SessionPicker.tsx | 99 ++-- .../__tests__/SessionPicker.mount.test.tsx | 31 +- .../components/code/blame/BlameHoverCard.tsx | 17 +- .../code/workspace/CodeWorkspace.tsx | 512 ++++++++++++++---- .../components/code/workspace/EditorGroup.tsx | 93 +++- .../code/workspace/FileStateMark.tsx | 42 ++ .../components/code/workspace/QuickOpen.tsx | 81 ++- .../web/components/code/workspace/TabBar.tsx | 172 +++++- .../components/code/workspace/TabSwitcher.tsx | 33 +- .../workspace/__tests__/splitRoom.test.ts | 26 + .../components/code/workspace/pickerAria.ts | 21 + .../conversation/blocks/toolBlocks.tsx | 25 +- packages/web/components/pr/PRThread.tsx | 4 + packages/web/components/repo/BlobContent.tsx | 23 +- .../web/components/repo/LocalEditButton.tsx | 84 +++ .../components/repo/RepoCompareContent.tsx | 6 +- .../repo/__tests__/localEditAt.mount.test.tsx | 63 +++ .../web/components/stage/StageSplitView.tsx | 7 +- .../web/components/tasks/TaskInlineThread.tsx | 7 +- .../terminal/ConversationTerminal.tsx | 1 + packages/web/components/ui/LoadingBar.tsx | 11 + .../web/components/vault/FileUnavailable.tsx | 112 ++++ .../web/components/vault/VaultFileView.tsx | 99 ++-- .../web/components/vault/VaultScopeLine.tsx | 2 +- .../web/components/vault/useVaultSidePanel.ts | 9 +- .../web/hooks/__tests__/useOnRequest.test.tsx | 29 + packages/web/hooks/useOnRequest.ts | 15 + .../lib/__tests__/castDiffFirstLine.test.ts | 19 + .../__tests__/codeEditorChunk.guard.test.ts | 42 ++ .../__tests__/editorPaletteCommands.test.ts | 9 +- packages/web/lib/__tests__/filesPane.test.ts | 28 + .../lib/__tests__/folderPathContext.test.tsx | 33 ++ packages/web/lib/__tests__/stage.test.ts | 23 +- .../standaloneBootGraph.guard.test.ts | 57 +- .../lib/__tests__/terminalFileLinks.test.ts | 43 ++ packages/web/lib/castDiff.ts | 14 + .../web/lib/code/__tests__/buffers.test.ts | 25 + .../__tests__/codeHighlightParity.test.ts | 240 ++++++++ .../web/lib/code/__tests__/fileSync.test.ts | 152 +++++- .../code/__tests__/foldMarkers.mount.test.ts | 38 ++ .../code/__tests__/idleNetwork.mount.test.ts | 125 +++++ .../code/__tests__/jumpHistory.mount.test.ts | 35 ++ packages/web/lib/code/__tests__/merge.test.ts | 12 +- .../code/__tests__/mergeView.mount.test.ts | 47 ++ .../web/lib/code/__tests__/statusBar.test.ts | 22 +- .../__tests__/statusBarVault.mount.test.ts | 44 ++ packages/web/lib/code/__tests__/theme.test.ts | 24 +- .../agent/__tests__/editorMarks.mount.test.ts | 65 ++- .../agent/__tests__/feature.mount.test.ts | 71 ++- .../lib/code/agent/__tests__/sessions.test.ts | 48 +- packages/web/lib/code/agent/agentStore.ts | 31 ++ packages/web/lib/code/agent/editorMarks.ts | 161 ++++-- packages/web/lib/code/agent/feature.ts | 144 ++++- packages/web/lib/code/agent/live.ts | 4 +- packages/web/lib/code/agent/sessions.ts | 67 ++- .../lib/code/blame/__tests__/actions.test.ts | 33 +- .../blame/__tests__/feature.mount.test.ts | 53 +- .../lib/code/blame/__tests__/model.test.ts | 13 +- packages/web/lib/code/blame/actions.ts | 17 +- packages/web/lib/code/blame/gutter.ts | 58 +- packages/web/lib/code/blame/index.ts | 13 +- packages/web/lib/code/blame/model.ts | 25 +- packages/web/lib/code/buffers.ts | 33 +- packages/web/lib/code/commands.ts | 39 +- packages/web/lib/code/editorHost.ts | 24 +- packages/web/lib/code/features.ts | 8 + packages/web/lib/code/fileSync.ts | 189 +++++-- .../code/git/__tests__/feature.mount.test.ts | 42 +- .../code/git/__tests__/gutter.mount.test.ts | 47 ++ packages/web/lib/code/git/gitTheme.ts | 16 +- packages/web/lib/code/git/gutter.ts | 95 +++- packages/web/lib/code/git/index.ts | 78 ++- packages/web/lib/code/git/split.ts | 25 +- packages/web/lib/code/git/status.ts | 18 +- packages/web/lib/code/gutterSlots.ts | 19 +- packages/web/lib/code/icons.ts | 29 + packages/web/lib/code/idle.ts | 18 + packages/web/lib/code/jump.ts | 26 + packages/web/lib/code/languages.ts | 13 +- .../code/lsp/__tests__/declarations.test.ts | 27 + .../web/lib/code/lsp/__tests__/lsp.test.ts | 2 +- packages/web/lib/code/lsp/declarations.ts | 82 +++ packages/web/lib/code/lsp/definitionClick.ts | 81 +++ packages/web/lib/code/lsp/feature.ts | 32 +- packages/web/lib/code/lsp/host.ts | 12 +- packages/web/lib/code/lsp/navigation.ts | 141 +++-- packages/web/lib/code/lsp/register.ts | 22 +- packages/web/lib/code/lsp/symbols.ts | 73 ++- packages/web/lib/code/lsp/ui/list.ts | 10 + packages/web/lib/code/lsp/ui/peek.ts | 10 +- packages/web/lib/code/lsp/ui/quickPick.ts | 28 +- packages/web/lib/code/lsp/ui/status.ts | 20 +- packages/web/lib/code/lsp/ui/theme.ts | 12 +- packages/web/lib/code/merge.ts | 120 +++- .../code/search/__tests__/controller.test.ts | 14 + .../__tests__/excerptHighlight.mount.test.ts | 38 ++ packages/web/lib/code/search/controller.ts | 13 +- .../web/lib/code/search/excerptHighlight.ts | 109 ++++ packages/web/lib/code/search/multibuffer.ts | 9 +- packages/web/lib/code/setup.ts | 21 +- packages/web/lib/code/statusBar.ts | 152 +++++- packages/web/lib/code/theme.ts | 317 +++++++---- .../web/lib/code/vim/__tests__/engine.test.ts | 162 ++++++ .../lib/code/vim/__tests__/exWrite.test.ts | 12 + packages/web/lib/code/vim/apply.ts | 4 + packages/web/lib/code/vim/complete.ts | 145 +++++ packages/web/lib/code/vim/completionSource.ts | 33 ++ packages/web/lib/code/vim/exAdapters.ts | 138 +++-- packages/web/lib/code/vim/gdefault.ts | 67 +++ packages/web/lib/code/vim/index.ts | 35 +- packages/web/lib/code/vim/keyLayer.ts | 17 +- packages/web/lib/code/vim/mode.ts | 14 +- packages/web/lib/code/vim/options.ts | 4 +- packages/web/lib/code/vim/plugins.ts | 43 +- packages/web/lib/code/vim/theme.ts | 24 +- packages/web/lib/code/vim/translate.ts | 58 +- packages/web/lib/code/vim/types.ts | 2 +- packages/web/lib/code/vimFeature.ts | 38 +- packages/web/lib/code/workspace/controller.ts | 10 +- .../web/lib/code/workspace/editorWorkspace.ts | 37 +- .../lib/code/workspace/followFiles.test.ts | 80 ++- .../web/lib/code/workspace/followFiles.ts | 136 ++++- .../web/lib/code/workspace/groupRegistry.ts | 9 + packages/web/lib/code/workspace/model.test.ts | 116 +++- packages/web/lib/code/workspace/model.ts | 380 ++++++++++++- .../web/lib/code/workspace/navHistory.test.ts | 22 +- packages/web/lib/code/workspace/navHistory.ts | 24 +- packages/web/lib/code/workspace/persist.ts | 2 +- .../web/lib/code/workspace/quickOpen.test.ts | 70 ++- packages/web/lib/code/workspace/quickOpen.ts | 197 ++++++- .../web/lib/code/workspace/symbolPath.test.ts | 35 ++ packages/web/lib/code/workspace/symbolPath.ts | 92 +--- packages/web/lib/editorPaletteCommands.ts | 107 +++- packages/web/lib/filePathLinks.ts | 21 +- packages/web/lib/filesPane.ts | 109 ++-- packages/web/lib/stage.ts | 36 +- packages/web/lib/terminal/endpoint.ts | 34 +- packages/web/lib/terminal/fileLinks.ts | 136 +++++ packages/web/lib/terminal/termRegistry.ts | 3 + packages/web/lib/terminal/termSessions.ts | 42 ++ packages/web/lib/vault/client.ts | 41 +- .../web/lib/vault/hosts/VaultMachineBar.tsx | 27 +- packages/web/lib/vault/vaultHref.ts | 9 + packages/web/perf/README.md | 52 ++ packages/web/plugins/contentOnlyHmr.test.ts | 112 +++- packages/web/plugins/contentOnlyHmr.ts | 109 ++-- packages/web/plugins/tailwindWorker.test.ts | 23 +- packages/web/plugins/tailwindWorker.ts | 49 +- packages/web/scripts/perf-budgets.sh | 3 + packages/web/shortcuts/keyOwnership.ts | 1 + packages/web/store/codeStore.ts | 14 +- packages/web/store/vaultStore.ts | 173 +++++- packages/web/store/vaultTypes.ts | 19 +- packages/web/test-helpers/importGraph.ts | 61 +++ 191 files changed, 8945 insertions(+), 1509 deletions(-) create mode 100644 packages/web/components/__tests__/inlineDiffEdit.mount.test.tsx create mode 100644 packages/web/components/code/OverwriteReview.tsx create mode 100644 packages/web/components/code/__tests__/codeFileBar.test.ts create mode 100644 packages/web/components/code/__tests__/firstRun.mount.test.tsx create mode 100644 packages/web/components/code/__tests__/typingAllFeatures.mount.test.tsx create mode 100644 packages/web/components/code/__tests__/vimFirstRun.mount.test.tsx create mode 100644 packages/web/components/code/__tests__/workspaceFocus.mount.test.tsx create mode 100644 packages/web/components/code/workspace/FileStateMark.tsx create mode 100644 packages/web/components/code/workspace/__tests__/splitRoom.test.ts create mode 100644 packages/web/components/code/workspace/pickerAria.ts create mode 100644 packages/web/components/repo/LocalEditButton.tsx create mode 100644 packages/web/components/repo/__tests__/localEditAt.mount.test.tsx create mode 100644 packages/web/components/ui/LoadingBar.tsx create mode 100644 packages/web/components/vault/FileUnavailable.tsx create mode 100644 packages/web/hooks/__tests__/useOnRequest.test.tsx create mode 100644 packages/web/hooks/useOnRequest.ts create mode 100644 packages/web/lib/__tests__/castDiffFirstLine.test.ts create mode 100644 packages/web/lib/__tests__/codeEditorChunk.guard.test.ts create mode 100644 packages/web/lib/__tests__/folderPathContext.test.tsx create mode 100644 packages/web/lib/__tests__/terminalFileLinks.test.ts create mode 100644 packages/web/lib/code/__tests__/codeHighlightParity.test.ts create mode 100644 packages/web/lib/code/__tests__/foldMarkers.mount.test.ts create mode 100644 packages/web/lib/code/__tests__/idleNetwork.mount.test.ts create mode 100644 packages/web/lib/code/__tests__/jumpHistory.mount.test.ts create mode 100644 packages/web/lib/code/__tests__/mergeView.mount.test.ts create mode 100644 packages/web/lib/code/icons.ts create mode 100644 packages/web/lib/code/jump.ts create mode 100644 packages/web/lib/code/lsp/__tests__/declarations.test.ts create mode 100644 packages/web/lib/code/lsp/declarations.ts create mode 100644 packages/web/lib/code/lsp/definitionClick.ts create mode 100644 packages/web/lib/code/search/__tests__/excerptHighlight.mount.test.ts create mode 100644 packages/web/lib/code/search/excerptHighlight.ts create mode 100644 packages/web/lib/code/vim/__tests__/exWrite.test.ts create mode 100644 packages/web/lib/code/vim/complete.ts create mode 100644 packages/web/lib/code/vim/completionSource.ts create mode 100644 packages/web/lib/code/vim/gdefault.ts create mode 100644 packages/web/lib/code/workspace/symbolPath.test.ts create mode 100644 packages/web/lib/terminal/fileLinks.ts create mode 100644 packages/web/test-helpers/importGraph.ts diff --git a/docs/architecture/code-editor.md b/docs/architecture/code-editor.md index 024298c868..a01c0ac71c 100644 --- a/docs/architecture/code-editor.md +++ b/docs/architecture/code-editor.md @@ -34,7 +34,8 @@ conversation the person is steering. The editor shows those facts in place. default) would hand half-typed code to watchers, typecheckers and agents reading the disk. A setting turns autosave on. - **Vim is on when a vimrc is found**, off otherwise, toggled from the status - bar mode chip and in Settings > Editor. + bar mode chip (on screen while off too, as a dim "Vim") and in Settings > + Editor. - **The daemon is the backend.** Reads, writes, search (ripgrep), git, blame, vimrc and language servers all run on the machine that holds the files, behind the loopback bridge's existing envelope (`authorizeLocalRequest`). @@ -56,7 +57,8 @@ packages/shared/contracts/codeProtocol.ts every request/response type above packages/web/lib/code/ editor engine, no React buffers.ts open buffers: EditorState cache, base etag, dirty, hot exit languages.ts lazy language loading (@codemirror/language-data) - theme.ts sol token theme + highlight style (shared with VaultEditor) + theme.ts sol token theme, highlight roles, overlay look; syntax colors + match Prism's (codeHighlightParity.test.ts) vim/ vim setup, vimrc parser + translator, ex adapters, plugins lsp/ transport over /lsp/ws, client pool git/ gutter + diff-vs-HEAD extensions @@ -110,6 +112,43 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv 9. **One "editor the person was in".** Commands run without a view (the palette, a chip) act on `focusedEditorView()` from features.ts, never a tracker of their own. +10. **Idle costs what is on screen.** Agents save files all day, so an open + editor pays per save only for what it shows: watcher events land in + batches, the daemon is asked once per burst, one request per kind is in + flight, a hidden page asks nothing until it is shown (`whenVisible`, + idle.ts), and a file no buffer holds is not read again. The budgets and + their numbers are in packages/web/perf/README.md ("Editor"). + +## When disk and the daemon disagree + +Every state below is a strip over the editor and a mark on the file's tab +(the dot's slot: yellow waits on the person, red is deleted or refused), the +same mark in the tab switcher and quick open (`FileStateMark`). Nothing in +any of them drops text: hot exit holds every dirty buffer. + +- **Read-only mode (0444).** The daemon's read sends `X-Vault-Writable: 0` + and the mode, so the status bar's lock shows the mode before any save; the + file stays editable, as in vim. A save the daemon refuses (403 read-only) + opens the "Read-only on disk" strip; its Overwrite, the lock itself and + `:w!` go through the shared confirm, then resend with `force=1`, still on + the buffer's etag, the mode bits kept. +- **Read-only in the editor.** The lock names why: `mirror` (another + machine's vault), `offline` (held text shown while the daemon + reconnects; the lock reconnects), `encoding` (text that did not decode). A + save that writes nothing flashes the lock. +- **Daemon unreachable.** A save that got no answer (no endpoint, a refused + connection, a timeout) is "Not saved · Reconnecting", and runs again when + Files reconnects; any answer from the daemon is a refusal ("Save failed" + with its reason word). After a reconnect's rescan, open code files whose + mtime moved are read again. +- **Deleted under the app.** An agent's `rm`, a branch switch or a stash + keeps the tab, struck through, with Recreate; the file returning drops + back into it. Only the person's own delete in the tree closes clean tabs. +- **Renamed under the app.** The watcher's removed plus add is followed as a + rename when the added file has the same size and its etag is the buffer's + base: tabs, unsaved text, hot exit and history move to the new path. +- **Large files** (past `LARGE_FILE_BYTES`) say "Large file" in the status + bar; language servers, word completion and selection matches are off. ## Vim @@ -132,13 +171,22 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv its body is a plain ex command. macOS option-key glyphs (`˙`, `∆`) map as the characters they are. - **Ex adapters.** Ex commands that name editor or plugin features run the - codecast equivalent: `:w :q :wq :x :e :sp :vs :bn :bp :bd :tabnew`, `` - window moves to split groups, NERDTree/netrw/Explore to the file tree, + codecast equivalent: `:w :q :wq :x :e :sp :vs :bn :bp :bd :tabnew`, `:b#`, + `:e#` and `` to the alternate tab, every `` key to split groups + (moves, `w`/`W`/`p`/`t`/`b` focus, `x`/`r` swap, `H J K L` to an edge, + `=`, `_`, `|` and counted `+ - < >` sizes; a key with no counterpart is + spent with a note, never passed to the engine as a command), NERDTree/netrw/Explore to the file tree, CtrlP/FZF/Files/Telescope find_files to quick open, CtrlPBuffer/Buffers to the tab switcher, grep/Rg/Ag/Ack/Telescope live_grep to project search, Gdiffsplit/Gvdiffsplit/DiffviewOpen to diff vs HEAD, Git blame to the session blame gutter. A map whose right side calls an adapted command works through the adapter. +- **Command line.** gdefault flips `:s`'s `g` flag on the way into the + engine (vim/gdefault.ts), which has no such option. Tab completes command + names, paths for `:e :sp :vs :tabe` and open tabs for `:b`, wildmenu style + (vim/complete.ts). While vim runs, ``/`` stops are the engine's + own jumps (G, gg, /, n, *, %, marks) plus file switches, never a line + distance. - **Plugins built in.** commentary (`gc`, `gcc`), surround (`ys`, `cs`, `ds`, visual `S`), `ae`/`ie` and `ii`/`ai` text objects, and LSP motions (`gd`, `gr`, `K`, `[d`/`]d`). @@ -160,12 +208,14 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv the file at those lines. Cmd-K asks for an instruction inline and sends it to the linked session with the range; the agent's edit then streams into the buffer. A vimrc's own Cmd maps win over both (vim takes the key first), so - each has vim ways in that never collide: `:Ask [instruction]` opens the box - on the line, a typed range or the visual selection (prefilled with the - argument), `:Quote` quotes it, and `k` / `l` (normal and + each has vim ways in that never collide: `:Ask instruction` sends it about + the line, a typed range or the visual selection to the linked session at + once (bare `:Ask`, or no linked session, opens the box instead, prefilled), + `:Quote` quotes it, and `k` / `l` (normal and visual) are bound unless the vimrc maps those keys or keys that start with them. -- **Which session.** A session the person picks for the folder wins, then the +- **Which session.** A session the person picks for the folder wins (kept per + vault in localStorage beside the code workspace), then the conversation beside this editor's Files pane (the one it was opened from, `AppTab.editorOpenedFrom`, while it is on stage; when the active tab holds Files only that tab counts, and a conversation on another tab counts only @@ -186,20 +236,81 @@ packages/web/app/settings/editor/ Settings > Editor (vim, vimrc report, LSP serv for presence dots, and used to name the writer of a change only when no other open tab in the vault shares the name. An edit no working session names takes a neutral color, never a guessed name. -- **Sent marker.** After a Cmd-K send the range says "sent to " - until the file changes under it or the turn that read the message ends: +- **Sent marker.** After a Cmd-K send the range says "sent to ", + with a dot that is hollow while the message waits and filled in the + session's color once its turn runs, until that range's lines change (typed, + or written on disk; a write elsewhere only maps it) or the turn that read + the message ends: keyed by the message's client id, it waits for the message to reach the transcript before a turn end counts, so an instruction queued behind a running turn keeps its marker past that turn. - **Agent edits, live.** When a session writes an open file, the changed - ranges flash in that session's color and stay marked until the person moves - on; the tab shows which session is editing the file now. + ranges flash in that session's color (the fade starts when the buffer is + first on screen) and keep a bar and a scrollbar tick until the cursor + enters them (the bar is drawn over the git bar's place, so it takes no + column, and a session's color is never git's green, red or blue), the bar is clicked, or `:AgentClear` / the status item's × + clears them; Escape never does. The status bar counts them in the writer's + color, and a press on the count, `]a`/`[a` or Alt-F6/Shift-Alt-F6 (beside the git hunk pair on Alt-F5; Cmd-Alt-arrows move between groups) steps through + them. Over unsaved edits the write merges at once: lines only disk changed + land (marked the same way) and the person's own stay unsaved; a region both + wrote opens the merge view, its conflicts red-barred, counted apart from the + person's clean edits and stepped to first. Keep mine writes the person's + text over that disk version on its etag; Take disk drops theirs. The tab + shows which session is editing the file now. - **Session blame.** A gutter names the session that wrote each line (git - trailer for committed lines, content match for uncommitted ones); a click - opens that conversation. -- **Review.** Diff vs HEAD (and vs a session's base) opens as a merge view - with per-hunk revert. -- **Elsewhere.** The command palette opens any file and runs editor commands; - the repo blob page opens a local checkout in the editor; the terminal dock - opens at the editor's root. Mobile is out of scope (phones read code in - transcripts and diffs). + trailer for committed lines, content match for uncommitted ones), in the + same color the session takes everywhere in the editor (sessionColor); a + click opens that conversation beside, scrolled to the message that made + the edit (`/conversation/#msg-` as a stage leaf). +- **Review.** Diff vs HEAD or any ref (the picker: previous commit, + upstream, merge base, and each session's base, in its color) opens inline + or side by side, with Revert as the one per-hunk action. A session's base + is read off its own commits (`sessionGitRefs`, lib/code/agent/sessions.ts): + the parent of its first commit, HEAD while it has committed nothing, never + the branch's merge base, which on a trunk checkout holds other sessions' + commits. The conversation diff's Edit opens the same refs (Session, Commit + as the session's last commit, Branch as the merge base), and the picker + offers the linked session's and every blamed writer's. A PR, commit or + compare diff gives each file an Edit into this machine's checkout, with the + diff against the PR base, the commit's parent or the compare base when the + checkout holds that revision. A new file (untracked or added) has no gutter + and diffs against nothing ("New file") or an older ref. The side-by-side + pane's commands (vim's `]c`, Alt-F5) act on its diff. An edit tool card + opens at the edit's text where it is now, with its old lines peeked. +- **Terminals.** A path in terminal output (the dock's shells, a + conversation's attached pane, a host's relayed pane) is a link: `x.ts:12:4`, + tsc's `x.ts(12,4)`, a grep hit, a `git status` line (lib/terminal/fileLinks.ts, + the prose grammar of filePathLinks plus the `(line,col)` suffix). A relative + path resolves where the shell is now: the daemon's `/term/sessions` carries + tmux's `pane_current_path` as `cwd`, read at the click with a 400 ms cap + and without touching the panel's probe state (most shells never report a + `cd`), else what OSC 7 last reported, else the start directory. In + an agent's pane it resolves in the conversation's project. It opens on the + pane's machine. +- **Messages.** A ```cast-diff fence's file cards carry Edit, at the file's + first changed line, the path resolved from the session's checkout root + (a git diff names files from there). Outside a conversation nothing + resolves it and the card has none. A plain code fence carries no path the + agents write, so it has no Edit. +- **Tasks and plans.** Paths cited in a task's comments, an inline task + thread's description and a plan's doc resolve in the task's or plan's + `project_path` (useFolderPathContext), so `lib/x.ts:38` opens that + project's file; a row with no project keeps the context around it (a + thread inside a conversation keeps the conversation's). Task and plan rows + name no machine, so the folder opens on the editor's default vault, which + is wrong when the row came from another machine. The task description is a rich-text editor and does not link paths. +- **Review threads.** A PR line thread on the new side carries Edit: its lines, + where the thread sits now, in this machine's worktree on the head branch. + With no worktree on that branch the thread has no Edit: another tree's + lines at those numbers are different lines. +- **The conversation.** The header menu's Open project in editor opens the + session's project folder on the session's machine and links the + conversation; the palette's Open project files on a session row opens it on + that session's machine. +- **Elsewhere.** The command palette opens any file (code files of a local + vault rank beside notes) and runs editor commands; the repo blob page opens + a local checkout in the editor; the terminal dock opens at the editor's + root; the desktop app's Go menu has Files; a `codecast://open/files?path=&l=` + link opens the editor at that line (deep links carry any in-app path); the + keyboard shortcuts panel has an Editor section. Mobile is out of scope + (phones read code in transcripts and diffs). diff --git a/packages/cli/src/blame.test.ts b/packages/cli/src/blame.test.ts index 99eb34bf08..cefa0446ae 100644 --- a/packages/cli/src/blame.test.ts +++ b/packages/cli/src/blame.test.ts @@ -388,6 +388,13 @@ describe("readSessionTrailers", () => { // More shas than fit on a command line (ARG_MAX is 1 MiB on macOS). const many = [...Array.from({ length: 30_000 }, (_, i) => i.toString(16).padStart(40, "0")), trailed]; expect([...(await readSessionTrailers(many, dir))]).toEqual([[trailed, id]]); + // A sweep (several sessions' work in one commit) names no one session. + fs.writeFileSync(path.join(dir, "a.txt"), "three\n"); + git("commit", "-q", "-am", "sweep", "--trailer", `Codecast-Session: ${id}`, "--trailer", "Codecast-Session: jx70e0f"); + const sweep = git("rev-parse", "HEAD"); + const sweeps = new Map(); + expect([...(await readSessionTrailers([trailed, sweep], dir, sweeps))]).toEqual([[trailed, id]]); + expect([...sweeps]).toEqual([[sweep, 2]]); } finally { fs.rmSync(dir, { recursive: true, force: true }); } diff --git a/packages/cli/src/blame.ts b/packages/cli/src/blame.ts index ff28e36bca..6d47d5fd75 100644 --- a/packages/cli/src/blame.ts +++ b/packages/cli/src/blame.ts @@ -13,7 +13,7 @@ import * as fs from "node:fs"; import * as path from "node:path"; import open from "open"; import { cliFetchRead } from "./cliHttp.js"; -import { contentLinesToMatch as selectContentLines, extractSessionTrailer, overlapLinesBySha, type ContentLine } from "@codecast/shared/blame"; +import { contentLinesToMatch as selectContentLines, extractSessionTrailer, overlapLinesBySha, sessionTrailerCount, type ContentLine } from "@codecast/shared/blame"; import { git } from "./code/codeGit.js"; import { defaultConfigDir } from "./config/configDir.js"; import { webBaseUrl } from "./config/readLocalConfig.js"; @@ -71,6 +71,11 @@ export interface BlameResolution { // is a bot organizing other sessions' work — the authoring session is the // one whose reasoning you want to read. byLine: Map; + // sha → how many sessions a sweep commit names in its Codecast-Session + // trailers. Such a commit carries several sessions' work, so the session + // that ran `git commit` (found by hash, commit row or subject) wrote none + // of it in particular and is never the answer for its lines. + sweeps?: Map; } export const EMPTY_RESOLUTION: BlameResolution = { @@ -298,7 +303,7 @@ export interface CommitDescriptor { // commit objects in one `git cat-file --batch`. The shas go in on stdin, so a // file with any number of blamed commits fits, and a commit git cannot read (a // shallow clone missing it) answers "missing" and costs only itself. -export async function readSessionTrailers(shas: string[], cwd: string): Promise> { +export async function readSessionTrailers(shas: string[], cwd: string, sweeps?: Map): Promise> { const found = new Map(); const wanted = [...new Set(shas)].filter((sha) => /^[0-9a-f]{4,64}$/i.test(sha)); if (wanted.length === 0) return found; @@ -321,7 +326,13 @@ export async function readSessionTrailers(shas: string[], cwd: string): Promise< if (type !== "commit") continue; const text = body.toString("utf-8"); const headerEnd = text.indexOf("\n\n"); - const session = extractSessionTrailer(headerEnd < 0 ? "" : text.slice(headerEnd + 2)); + const message = headerEnd < 0 ? "" : text.slice(headerEnd + 2); + const count = sessionTrailerCount(message); + if (count > 1) { + sweeps?.set(sha, count); + continue; + } + const session = extractSessionTrailer(message); if (session) found.set(sha, session); } return found; @@ -395,7 +406,8 @@ export async function resolveFromParsed( ): Promise { if (!config.auth_token || !config.convex_url) return EMPTY_RESOLUTION; const shas = [...new Set(parsed.lines.map((l) => l.sha))].filter((s) => s !== ZERO_SHA); - const trailers = await readSessionTrailers(shas, path.dirname(absFilePath)); + const sweeps = new Map(); + const trailers = await readSessionTrailers(shas, path.dirname(absFilePath), sweeps); const overlapLines = overlapLinesBySha( parsed.lines .filter((line) => line.sha !== ZERO_SHA && !trailers.has(line.sha)) @@ -415,7 +427,12 @@ export async function resolveFromParsed( const contentLines = contentLinesToMatch(parsed, Date.now()); const siteUrl = config.convex_url.replace(".cloud", ".site"); try { - return await resolveSessions(siteUrl, config.auth_token, commits, absFilePath, contentLines); + const resolution = await resolveSessions(siteUrl, config.auth_token, commits, absFilePath, contentLines); + if (sweeps.size === 0) return resolution; + // A sweep's lines belong to whoever wrote them: keep an overlap match, + // drop an answer that only found the session that committed the sweep. + const bySha = new Map([...resolution.bySha].filter(([sha, ref]) => !sweeps.has(sha) || ref.via === "overlap")); + return { ...resolution, bySha, sweeps }; } catch (error) { console.error( `cast blame: session resolution unavailable (${error instanceof Error ? error.message : error})`, diff --git a/packages/cli/src/code/codeBlame.ts b/packages/cli/src/code/codeBlame.ts index d4066ab318..51fc7b4da2 100644 --- a/packages/cli/src/code/codeBlame.ts +++ b/packages/cli/src/code/codeBlame.ts @@ -60,12 +60,14 @@ export function blameHunks(parsed: ParsedBlame, resolution: BlameResolution): Co const meta = parsed.commits.get(line.sha); const uncommitted = line.sha === ZERO_SHA; const session = hunkSession(ref); + const sweep = !session && !uncommitted ? resolution.sweeps?.get(line.sha) : undefined; hunks.push({ start: line.finalLine, end: line.finalLine, ...(uncommitted ? { uncommitted: true } : { sha: line.sha, author: meta?.author, summary: meta?.summary }), ...(meta?.authorTime ? { time: meta.authorTime * 1000 } : {}), ...(session ? { session } : {}), + ...(sweep ? { sweep_sessions: sweep } : {}), }); } return hunks; diff --git a/packages/cli/src/terminal/terminalServer.test.ts b/packages/cli/src/terminal/terminalServer.test.ts index 56c0c585fe..c4a1ebb6ab 100644 --- a/packages/cli/src/terminal/terminalServer.test.ts +++ b/packages/cli/src/terminal/terminalServer.test.ts @@ -116,6 +116,12 @@ describe("parseTerminalSessionRows", () => { expect(rows[2].attached).toBe(2); }); + it("reads the active pane's cwd after the start path", () => { + const [row] = parseTerminalSessionRows("cast-term-a1|1700000100|1|zsh|/Users/me/src|=cwd=|/Users/me/src/a|b/pkg"); + expect(row.path).toBe("/Users/me/src"); + expect(row.cwd).toBe("/Users/me/src/a|b/pkg"); + }); + it("returns nothing for empty output", () => { expect(parseTerminalSessionRows("")).toEqual([]); expect(parseTerminalSessionRows("\n\n")).toEqual([]); diff --git a/packages/cli/src/terminal/terminalServer.ts b/packages/cli/src/terminal/terminalServer.ts index a872681e98..933604c1f6 100644 --- a/packages/cli/src/terminal/terminalServer.ts +++ b/packages/cli/src/terminal/terminalServer.ts @@ -64,6 +64,10 @@ export interface TerminalSessionInfo { command: string; created: number; attached: number; + /** The directory the session's active pane is in now (the shell's cwd + * after a `cd`), where `path` is where the session started. The panel + * resolves a relative path printed in the terminal against it. */ + cwd?: string; } // NB: separators must be printable: tmux sanitizes control chars (tabs @@ -71,7 +75,10 @@ export interface TerminalSessionInfo { // goes LAST and is re-joined, since it is the one field that may itself // contain the separator. pane_current_command expands through the session's // active pane, so one list call carries it and no per session query is needed. -const SESSION_LIST_FORMAT = "#{session_name}|#{session_created}|#{session_attached}|#{pane_current_command}|#{session_path}"; +// The live cwd rides after the start path behind a marker no real path holds, +// since both may contain "|". +const CWD_MARK = "|=cwd=|"; +const SESSION_LIST_FORMAT = `#{session_name}|#{session_created}|#{session_attached}|#{pane_current_command}|#{session_path}${CWD_MARK}#{pane_current_path}`; /** Parse `tmux list-sessions -F SESSION_LIST_FORMAT` output: the panel's own * sessions (cast-term-*), oldest first. */ @@ -81,9 +88,13 @@ export function parseTerminalSessionRows(stdout: string): TerminalSessionInfo[] if (!line.trim()) continue; const [name, created, attached, command, ...pathParts] = line.split("|"); if (!name || !name.startsWith(TERM_SESSION_PREFIX)) continue; + const tail = pathParts.join("|"); + const mark = tail.lastIndexOf(CWD_MARK); + const cwd = mark >= 0 ? tail.slice(mark + CWD_MARK.length) : ""; out.push({ name, - path: pathParts.join("|"), + path: mark >= 0 ? tail.slice(0, mark) : tail, + ...(cwd ? { cwd } : {}), command: (command ?? "").trim(), created: (parseInt(created ?? "", 10) || 0) * 1000, attached: parseInt(attached ?? "", 10) || 0, @@ -202,7 +213,7 @@ export function corsHeaders(origin: string | undefined, opts: TerminalServerOpti "Access-Control-Allow-Methods": "GET, POST, PUT, OPTIONS", // The browser can only read these off a cross-origin response if they're // exposed; the vault's write guard depends on the client seeing the ETag. - "Access-Control-Expose-Headers": "ETag, X-Vault-Mtime, X-Vault-Size", + "Access-Control-Expose-Headers": "ETag, X-Vault-Mtime, X-Vault-Size, X-Vault-Writable, X-Vault-Mode", // Chrome Private Network Access: a public https page fetching loopback // must see this on the preflight or the request is blocked. "Access-Control-Allow-Private-Network": "true", diff --git a/packages/cli/src/vault/vaultServer.test.ts b/packages/cli/src/vault/vaultServer.test.ts index 4909d62fc9..773acef937 100644 --- a/packages/cli/src/vault/vaultServer.test.ts +++ b/packages/cli/src/vault/vaultServer.test.ts @@ -471,6 +471,10 @@ describe("PUT /vault/file", () => { const locked = path.join(root, "notes/generated.ts"); fs.writeFileSync(locked, "old\n"); fs.chmodSync(locked, 0o444); + // The read says so first, so the editor shows the lock before a save. + const read = await api(filePath("notes/generated.ts")); + expect(read.headers.get("X-Vault-Writable")).toBe("0"); + expect(read.headers.get("X-Vault-Mode")).toBe("0444"); const refused = await api(filePath("notes/generated.ts"), { method: "PUT", body: "new\n" }); expect(refused.status).toBe(403); expect((await refused.json()).error).toBe("read-only"); diff --git a/packages/cli/src/vault/vaultServer.ts b/packages/cli/src/vault/vaultServer.ts index 2e2e54096d..c7e9c4b326 100644 --- a/packages/cli/src/vault/vaultServer.ts +++ b/packages/cli/src/vault/vaultServer.ts @@ -168,6 +168,9 @@ async function handleGetFile( return sendJson(res, 413, headers, { error: "too large", size: stat.size }); } const data = await fsp.readFile(target.abs); + // A file its mode refuses to write (0444) says so up front, so the editor can + // show the lock before a save is refused, and confirm the force-overwrite. + const writable = await fsp.access(target.abs, fs.constants.W_OK).then(() => true, () => false); res.writeHead(200, { ...headers, ...vaultResponseSecurityHeaders(target.rel), @@ -177,6 +180,7 @@ async function handleGetFile( ETag: vaultContentHash(data), "X-Vault-Mtime": String(Math.round(stat.mtimeMs)), "X-Vault-Size": String(stat.size), + ...(writable ? {} : { "X-Vault-Writable": "0", "X-Vault-Mode": (stat.mode & 0o7777).toString(8).padStart(4, "0") }), }); res.end(data); } diff --git a/packages/electron/main.js b/packages/electron/main.js index ac8c9b4d71..65bf8ec57c 100644 --- a/packages/electron/main.js +++ b/packages/electron/main.js @@ -3257,6 +3257,8 @@ function buildAppMenu() { { label: "Tasks", click: () => routeToWindow("/tasks") }, { label: "Docs", click: () => routeToWindow("/docs") }, { label: "Plans", click: () => routeToWindow("/plans") }, + // The code editor (Files); Cmd-P inside it goes to a file. + { label: "Files", click: () => routeToWindow("/files") }, { type: "separator" }, // Same chords as the renderer's nav.back/nav.forward, following the // person's rebinding (menuKeys.js): the page handles the key first and diff --git a/packages/shared/blame/index.ts b/packages/shared/blame/index.ts index 93927881be..db35774da7 100644 --- a/packages/shared/blame/index.ts +++ b/packages/shared/blame/index.ts @@ -208,6 +208,18 @@ export function extractSessionTrailer(message: string | null | undefined): strin return splitSessionTrailer(message).session; } +/** + * How many Codecast-Session trailers a commit message's last paragraph carries, + * whatever their values (short ids included). More than one marks a sweep: one + * session committed several sessions' work, so the commit alone does not say + * which of them wrote a given line. + */ +export function sessionTrailerCount(message: string | null | undefined): number { + if (!message) return 0; + const paragraphs = message.replace(/\r\n/g, "\n").trimEnd().split(/\n[ \t]*\n/); + return (paragraphs[paragraphs.length - 1] ?? "").split("\n").filter((line) => TRAILER_LINE.test(line.trim())).length; +} + /** * A commit message with the Codecast-Session trailer lines that * extractSessionTrailer reads taken out (a paragraph left empty goes with diff --git a/packages/shared/blame/sessionTrailer.test.ts b/packages/shared/blame/sessionTrailer.test.ts index 80365e8a32..a744f9b910 100644 --- a/packages/shared/blame/sessionTrailer.test.ts +++ b/packages/shared/blame/sessionTrailer.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test"; -import { extractSessionTrailer, sessionTrailerValue, SESSION_TRAILER_KEY, splitSessionTrailer } from "./index"; +import { extractSessionTrailer, sessionTrailerCount, sessionTrailerValue, SESSION_TRAILER_KEY, splitSessionTrailer } from "./index"; const ID = "jx7bq5kz13a2eypp4a6vdqznas7zvrw2"; const trailer = `${SESSION_TRAILER_KEY}: ${sessionTrailerValue(ID)}`; @@ -84,3 +84,12 @@ describe("splitSessionTrailer", () => { } }); }); + +describe("sessionTrailerCount", () => { + test("counts every trailer in the last paragraph, short ids included; quoted ones don't count", () => { + expect(sessionTrailerCount(`fix: a\n\n${trailer}`)).toBe(1); + expect(sessionTrailerCount("feat: sweep\n\nCodecast-Session: jx70369\nCodecast-Session: jx70e0f\nCodecast-Session: jx70gmc")).toBe(3); + expect(sessionTrailerCount(`feat: about trailers\n\n${trailer}\n\nmore prose`)).toBe(0); + expect(sessionTrailerCount(undefined)).toBe(0); + }); +}); diff --git a/packages/shared/contracts/codeProtocol.ts b/packages/shared/contracts/codeProtocol.ts index f60311173b..466fb117c8 100644 --- a/packages/shared/contracts/codeProtocol.ts +++ b/packages/shared/contracts/codeProtocol.ts @@ -114,6 +114,11 @@ export interface CodeBlameHunk { /** The codecast session that wrote these lines, from the Codecast-Session * trailer or, for uncommitted lines, a content match against session edits. */ session?: CodeBlameSession; + /** Set when the commit is a sweep naming this many sessions in its + * Codecast-Session trailers and no single one of them could be matched to + * these lines; `session` is then absent rather than the session that ran + * the commit. */ + sweep_sessions?: number; } export interface CodeBlameResponse { diff --git a/packages/shared/contracts/shortcutCatalog.ts b/packages/shared/contracts/shortcutCatalog.ts index 9aa420741a..78327f0b51 100644 --- a/packages/shared/contracts/shortcutCatalog.ts +++ b/packages/shared/contracts/shortcutCatalog.ts @@ -315,6 +315,11 @@ export const SHORTCUTS: ShortcutDef[] = [ { key: 'ctrl+.', action: 'ui.zenToggle', skipInputCheck: true, description: 'Toggle zen mode' }, { key: 'ctrl+,', action: 'inbox.toggleFlatView', skipInputCheck: true, description: 'Cycle inbox view (grouped / time / label)' }, { key: '?', action: 'ui.toggleShortcutsHelp', description: 'Toggle shortcuts help' }, + // The same from inside a field or a focused code editor, where "?" is typed + // text (or vim's backward search). shift+slash arrives as '/' or '?' + // depending on browser/layout: both spellings. + { key: 'ctrl+shift+/', mac: 'meta+shift+/', action: 'ui.toggleShortcutsHelp', skipInputCheck: true, description: 'Toggle shortcuts help' }, + { key: 'ctrl+shift+?', mac: 'meta+shift+?', action: 'ui.toggleShortcutsHelp', skipInputCheck: true, description: 'Toggle shortcuts help' }, // meta+, is the OS settings convention on mac; ctrl+, is taken by the inbox // view cycle above, so non-mac gets the shifted variant. shift+comma arrives // as ',' or '<' depending on browser/layout — register both spellings. diff --git a/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx b/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx index 014903044d..1f1f7864ac 100644 --- a/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx +++ b/packages/web/app/commit/[owner]/[repo]/[sha]/page.tsx @@ -27,6 +27,7 @@ import { CodeMenuItem, CodeShareMenu } from "../../../../../components/menus/Cod import { copyText } from "../../../../../lib/copyText"; import { CommitRail } from "../../../../../components/repo/CommitRail"; import { RepoPageShell } from "../../../../../components/repo/RepoPageShell"; +import { useLocalEditAction } from "../../../../../components/repo/LocalEditButton"; import { RepoWindowControl } from "../../../../../components/repo/RepoWindowControl"; import { useRepoFamily } from "../../../../../components/repo/useRepoFamily"; import { FileDiffLayout, type DiffFile, type FileLineThreads } from "../../../../../components/FileDiffLayout"; @@ -505,6 +506,12 @@ function CommitContent({ (path: string) => repoBlobHref(repository, sha, path, family), [repository, sha, family], ); + // Each file's "Edit": the file in this machine's checkout, with the + // editor's diff against the commit's parent when the checkout sits on this + // commit (anywhere else that diff would mix in other commits' changes). + const editAction = useLocalEditAction(repository, "", (c) => + c.head && c.head === commit?.sha ? { ref: `${commit.sha}^`, label: "Parent" } : null, + ); const jumpToThread = useCallback( (path: string, line?: number) => goTo(path, line ? { side: "RIGHT", lineNumber: line } : undefined), [goTo], @@ -574,7 +581,7 @@ function CommitContent({ )} - + )} diff --git a/packages/web/app/files/page.tsx b/packages/web/app/files/page.tsx index 296de5e42c..26089f1f76 100644 --- a/packages/web/app/files/page.tsx +++ b/packages/web/app/files/page.tsx @@ -9,6 +9,7 @@ import { Suspense, useCallback, useMemo, useRef, useState } from "react"; import { useWatchEffect } from "../../hooks/useWatchEffect"; +import { useOnRequest } from "../../hooks/useOnRequest"; import { useTabContext } from "../../lib/tabParams"; import { useVaultLocalPath } from "../../hooks/useVaultLocalPath"; import { useRouter, useSearchParams } from "next/navigation"; @@ -21,6 +22,7 @@ import { } from "react-resizable-panels"; import { ArrowUpDown, + ChevronRight, CopyMinus, FilePlus2, FolderPlus, @@ -32,10 +34,10 @@ import { RefreshCw, Search, Waypoints, - WifiOff, X, } from "lucide-react"; import { AuthGuard } from "../../components/AuthGuard"; +import { LoadingBar } from "../../components/ui/LoadingBar"; import { LocalDaemonUnreachable } from "../../components/LocalDaemonUnreachable"; import { DropdownMenu, @@ -56,9 +58,9 @@ import { VaultRightPanel } from "../../components/vault/VaultRightPanel"; import { VaultFindBar } from "../../components/vault/VaultFindBar"; import { HoverPreviewProvider } from "../../components/vault/VaultHoverPreview"; import { VaultSearchPane } from "../../components/vault/VaultSearchPane"; +import { projectSearch } from "../../lib/code/search/controller"; import { VaultPicker } from "../../components/vault/VaultPicker"; import { VaultMachineBar } from "../../lib/vault/hosts/VaultMachineBar"; -import { hostOfVault } from "../../lib/vault/hosts/routes"; import { EmptyVaultTeaching } from "../../components/vault/EmptyVaultTeaching"; import { VaultScopeLine } from "../../components/vault/VaultScopeLine"; import { useDocForFile, useVaultTeamResolver } from "../../components/vault/useVaultScope"; @@ -66,7 +68,7 @@ import { vaultPresence } from "../../lib/vault/scopeModel"; import { vaultLandingPath } from "../../lib/vault/projectVault"; import { filesHref } from "../../lib/vault/vaultHref"; import { collapsePanelSoon } from "../../lib/vault/collapsePanelSoon"; -import { useVaultStore } from "../../store/vaultStore"; +import { readTreeLayout, useVaultStore, writeTreeLayout, type TreeLayout } from "../../store/vaultStore"; import { SIDE_MIN_PX, useVaultSidePanel } from "../../components/vault/useVaultSidePanel"; import { toggleVaultEditMode, @@ -78,6 +80,7 @@ import { import { useTitlebarHead } from "../../hooks/useTitlebarHead"; import { lazyNamed } from "../../lib/lazyNamed"; import { CodeWorkspace } from "../../components/code/workspace/CodeWorkspace"; +import { LinkedFilePending } from "../../components/vault/FileUnavailable"; import { workspaceFor } from "../../store/codeStore"; // sigma + graphology are ~40kB gzip: nobody who doesn't open the graph pays. @@ -151,7 +154,11 @@ function VaultContent() { // is known to be wide enough — mounting it into a pane that cannot satisfy // its pixel minimums livelocks the panel library. const [paneNarrow, setPaneNarrow] = useState(null); - const [treeOpen, setTreeOpen] = useState(!inSplitPane); + // A full tab comes back with the tree as it was left; a split leaf starts closed. + const savedTreeRef = useRef(undefined); + if (savedTreeRef.current === undefined) savedTreeRef.current = inSplitPane ? null : readTreeLayout(); + const savedTree = savedTreeRef.current; + const [treeOpen, setTreeOpen] = useState(savedTree?.open ?? false); const treeAppliedRef = useRef(null); const treeExpandingRef = useRef(false); const firstMeasureRef = useRef(true); @@ -190,7 +197,11 @@ function VaultContent() { collapsePanelSoon(treePanelRef, () => treeAppliedRef.current === false); return; } - if (firstSync) return; // the panel mounts expanded already + if (firstSync) { + // The panel mounts expanded at the default share; a saved width wins. + if (savedTree?.px) ref.resize(`${savedTree.px}px`); + return; + } treeExpandingRef.current = true; ref.resize("20%"); // 20% of a modest pane can fall under the pixel minimum and the library @@ -202,6 +213,14 @@ function VaultContent() { }); }); }, [treeOpen, paneNarrow, connection]); + // Only a choice made on a wide pane is remembered: the narrow overlay + // closes itself after every pick. + useWatchEffect(() => { + if (savedTree && paneNarrow === false && treeOpen !== savedTree.open) { + savedTree.open = treeOpen; + writeTreeLayout({ open: treeOpen }); + } + }, [treeOpen, paneNarrow]); // Picking a file from the overlay closes it — on a narrow pane the reader // is the point, and the drawer covers most of it. useWatchEffect(() => { @@ -261,10 +280,13 @@ function VaultContent() { // binding, which shares it. const searchInputRef = useRef(null); usePaneShortcutAction("vault.search", () => { - setLeftTab("search"); - requestAnimationFrame(() => searchInputRef.current?.select()); + useVaultStore.getState().openSearch(); + projectSearch.requestBox(); return true; }); + // Every way of asking for search (the chord, :grep, the palette, a saved + // search) goes through openSearch; a hidden tree opens to show it. + useOnRequest(useVaultStore((s) => s.searchPaneRequest), () => setTreeOpen(true)); const [editModeBump, bumpEditMode] = useState(0); // Mode memory is per vault: scoping it here means a vault switch forgets the @@ -422,19 +444,13 @@ function VaultContent() { ); if ((connection === "connected" || connection === "cached") && vaults.length === 0 && !activeVaultId) return ; - if (connection === "idle" || connection === "discovering") { - return ( -
- Connecting to your files… -
- ); - } + if (connection === "idle" || connection === "discovering") return ; // The explorer column, rendered either as a split panel (wide pane) or an // overlay drawer (narrow pane). const treePane = (
-
+
router.push(href)} /> - {/* A host vault's reconnect shows on its machine chip above. */} - {connection === "cached" && !hostOfVault(activeVaultId) && ( -
- - Showing cached copy — reconnecting to the local daemon… -
- )} {opError && (
@@ -615,6 +624,14 @@ function VaultContent() { { + // A drag ended: remember the tree's width. + const px = treePanelRef.current?.getSize().inPixels; + if (savedTree && paneNarrow === false && treeOpen && px && px >= 180 && Math.round(px) !== savedTree.px) { + savedTree.px = Math.round(px); + writeTreeLayout({ px: savedTree.px }); + } + }} defaultLayout={{ "vault-tree": treeOpen ? 20 : 0, "vault-content": 100 - (treeOpen ? 20 : 0) - (rightPanelOpen ? 22 : 0), @@ -695,6 +712,9 @@ function VaultContent() { onClose={toggleGraph} /> + ) : localPath && !opError ? ( + // The link's file, until its folder resolves: never the last vault's tab. + ) : activeVaultId ? ( openNote(p)}> {findOpen && setFindOpen(false)} />} @@ -752,6 +772,28 @@ function VaultContent() { ); } +/** Files while this machine's daemon is first reached: the file a link asked + * for, named where its breadcrumbs will be, over the loading sweep. */ +function ConnectingShell({ path }: { path: string | null }) { + const segments = path ? path.split("/").filter(Boolean) : []; + const name = segments.pop(); + const dir = segments.slice(-2); + return ( +
+
+ {dir.map((seg, i) => ( + + {seg} + + + ))} + {name && {name}} +
+ +
+ ); +} + export default function VaultPage() { return ( diff --git a/packages/web/app/globals.css b/packages/web/app/globals.css index 1dcceb74a9..eaf09f864c 100644 --- a/packages/web/app/globals.css +++ b/packages/web/app/globals.css @@ -547,17 +547,6 @@ html, body { (tailwind amber-600). One token so every surface's links match. */ --sol-link: #d97706; - /* Syntax highlighting - Light mode optimized */ - --hljs-keyword: #859900; - --hljs-string: #2aa198; - --hljs-number: #d33682; - --hljs-function: #268bd2; - --hljs-comment: #93a1a1; - --hljs-type: #b58900; - --hljs-variable: #cb4b16; - --hljs-attr: #b58900; - --hljs-tag: #268bd2; - --hljs-built-in: #dc322f; } /* The homepage hero renders real product views in light Classic whatever the @@ -583,9 +572,6 @@ html, body { --sol-text-muted0: #839496; --logo-c: #93a1a1; - - /* Syntax highlighting - Dark mode (same accent colors work well) */ - --hljs-comment: #586e75; } .minimal-style { @@ -703,6 +689,42 @@ html, body { --ring: 45 4% 60%; } +/* Syntax colors: the theme's own accents, so code in a transcript, a diff + and the editor all follow the colour theme (lib/code/theme.ts reads these). + A var() resolves on the element that declares it, so the map is declared + on every element that redefines the palette; a colour theme writes its + tokens inline on , which :root covers. Comments take the dim ink, + which every theme tunes to read on its own background. */ +:root, +.hero-sandbox, +.dark, +.minimal-style { + --hljs-keyword: var(--sol-green); + --hljs-string: var(--sol-cyan); + --hljs-number: var(--sol-magenta); + --hljs-function: var(--sol-blue); + --hljs-comment: var(--sol-text-dim); + --hljs-type: var(--sol-yellow); + --hljs-variable: var(--sol-orange); + --hljs-attr: var(--sol-yellow); + --hljs-tag: var(--sol-blue); + --hljs-built-in: var(--sol-red); + /* Diff tints, the one set every diff draws (Pierre's cards, the editor's + merge and review views, the git peek): a line's wash, opaque over the + page, and the stronger mark on the words that changed in it. */ + --diff-add-line: color-mix(in srgb, var(--sol-green) 10%, var(--sol-bg)); + --diff-del-line: color-mix(in srgb, var(--sol-red) 8%, var(--sol-bg)); + --diff-add-word: color-mix(in srgb, var(--sol-green) 25%, transparent); + --diff-del-word: color-mix(in srgb, var(--sol-red) 22%, transparent); +} +/* On a dark page the same wash all but disappears, so it is a little stronger. */ +.dark { + --diff-add-line: color-mix(in srgb, var(--sol-green) 12%, var(--sol-bg)); + --diff-del-line: color-mix(in srgb, var(--sol-red) 10%, var(--sol-bg)); + --diff-add-word: color-mix(in srgb, var(--sol-green) 30%, transparent); + --diff-del-word: color-mix(in srgb, var(--sol-red) 25%, transparent); +} + @layer components { .sol-card { @apply bg-sol-bg-alt border border-sol-border rounded-xl; @@ -1582,20 +1604,13 @@ diffs-container { --diffs-modified-color-override: var(--sol-blue); --diffs-bg-context-override: transparent; --diffs-bg-context-gutter-override: transparent; - --diffs-bg-addition-override: color-mix(in srgb, var(--sol-green) 10%, var(--sol-bg)); - --diffs-bg-deletion-override: color-mix(in srgb, var(--sol-red) 8%, var(--sol-bg)); - --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--sol-green) 25%, transparent); - --diffs-bg-deletion-emphasis-override: color-mix(in srgb, var(--sol-red) 22%, transparent); + --diffs-bg-addition-override: var(--diff-add-line); + --diffs-bg-deletion-override: var(--diff-del-line); + --diffs-bg-addition-emphasis-override: var(--diff-add-word); + --diffs-bg-deletion-emphasis-override: var(--diff-del-word); --diffs-bg-separator-override: var(--sol-bg-alt); } -.dark diffs-container { - --diffs-bg-addition-override: color-mix(in srgb, var(--sol-green) 12%, var(--sol-bg)); - --diffs-bg-deletion-override: color-mix(in srgb, var(--sol-red) 10%, var(--sol-bg)); - --diffs-bg-addition-emphasis-override: color-mix(in srgb, var(--sol-green) 30%, transparent); - --diffs-bg-deletion-emphasis-override: color-mix(in srgb, var(--sol-red) 25%, transparent); -} - /* --row-h is set from JS (undoActions.ts) to the row's measured height just before the class is applied, so the collapse spans the real content — a single card or a parent plus its subagent rows — instead of a hardcoded cap. */ diff --git a/packages/web/app/pr/[owner]/[repo]/[number]/page.tsx b/packages/web/app/pr/[owner]/[repo]/[number]/page.tsx index a1f9e17116..c2722df31c 100644 --- a/packages/web/app/pr/[owner]/[repo]/[number]/page.tsx +++ b/packages/web/app/pr/[owner]/[repo]/[number]/page.tsx @@ -26,6 +26,7 @@ import { useCurrentUser } from "../../../../../hooks/useCurrentUser"; import { useEventListener } from "../../../../../hooks/useEventListener"; import { useWatchEffect } from "../../../../../hooks/useWatchEffect"; import { repoBlobHref } from "../../../../../lib/repoView"; +import { useLocalEditAction, useLocalEditAt } from "../../../../../components/repo/LocalEditButton"; import { landOn, useDiffAddress } from "../../../../../hooks/useDiffAddress"; import { useFollowScroll } from "../../../../../hooks/useFollowSurface"; import { useLinkedSessions } from "../../../../../hooks/useLinkedSessions"; @@ -299,6 +300,9 @@ export function PRContent({ [createComment, noteMode, pr, repository, user?._id], ); + // A thread on the new side opens its lines (where they are now) in this + // machine's checkout of the head branch. + const editAt = useLocalEditAt(repository, pr?.head_ref ?? ""); const lineThreads: FileLineThreads = useMemo( () => ({ threadsFor: (filename) => threadsByFile.get(filename), @@ -312,6 +316,7 @@ export function PRContent({ lineNumber={anchor.lineNumber} lineEnd={anchor.lineEnd} placement={placement} + editAction={items.length && anchor.side !== "LEFT" && placement?.state !== "outdated" ? editAt?.(filename, placement?.line ?? anchor.lineNumber, placement ? placement.lineEnd : anchor.lineEnd) : undefined} noteMode={noteMode} onNoteMode={setNoteMode} pendingCount={notes.length} @@ -348,7 +353,7 @@ export function PRContent({ if (anchor) setComposing({ file: filename, anchor, anchorLines }); }, }), - [threadsByFile, isAuthenticated, post, repository, pr?.head_sha, noteMode, setNoteMode, notes.length, landing, number, family, goTo, composing], + [threadsByFile, isAuthenticated, post, repository, pr?.head_sha, noteMode, setNoteMode, notes.length, landing, number, family, goTo, composing, editAt], ); // What the tree shows beside each file: open threads, waiting notes, viewed. @@ -458,6 +463,12 @@ export function PRContent({ changes: f.changes, patch: f.patch, })), [prFiles]); + // Each file's "Edit": the file in this machine's checkout of the head + // branch, with the editor's diff against the pull request's base. A checkout + // on another branch holds another version: the file opens alone there. + const editAction = useLocalEditAction(repository, pr?.head_ref ?? "", (c) => + c.onRef && pr?.base_sha ? { ref: pr.base_sha, label: "PR base" } : null, + ); if (!pr) { const error = prFeed.error?.message || lookup.error; @@ -571,6 +582,7 @@ export function PRContent({ flow={flow} // The name opens the whole file as the pull request has it. fileHref={pr.head_sha ? (path) => repoBlobHref(repository, pr.head_sha, path, family) : undefined} + fileAction={editAction} lineThreads={lineThreads} fileMarks={fileMarks} onToggleViewed={isAuthenticated ? toggleViewed : undefined} diff --git a/packages/web/app/tasks/[id]/page.tsx b/packages/web/app/tasks/[id]/page.tsx index 7ddf45a341..83826760b5 100644 --- a/packages/web/app/tasks/[id]/page.tsx +++ b/packages/web/app/tasks/[id]/page.tsx @@ -77,6 +77,7 @@ import { useNavClose } from "../../../hooks/useNavTrail"; import { useIsModernStyle } from "../../../hooks/useVisualStyle"; import { TaskHeadIdRow, TaskHeadTitle, TaskModernHeader, TaskParentLine, type TaskTitleEdit } from "./TaskHead"; import { modernPill, modernPillShape } from "../../../components/ui/modernLook"; +import { FilePathContext, useFolderPathContext } from "../../../lib/filePathLinks"; const PRIORITY_OPTIONS = [ { key: "urgent", icon: AlertTriangle, label: "Urgent", color: "text-sol-red" }, @@ -287,6 +288,7 @@ export function TaskDetailContent({ taskId, variant = "page", onClose, onOpen, c // writes the thread to the store, and a task opened before paints it from // the cache. const comments = useTaskComments(data?._id); + const taskFileCtx = useFolderPathContext(data?.project_path); const taskTeamId = data?.team_id as string | undefined; // A blocking question outranks the description: nothing in the body can be // acted on until it is answered, so the body folds and the card comes up @@ -818,7 +820,10 @@ export function TaskDetailContent({ taskId, variant = "page", onClose, onOpen, c
)} - + {/* A path a comment cites (`lib/x.ts:38`) is relative to the task's project. */} + + + {/* Comment input */} diff --git a/packages/web/components/CommandPalette.tsx b/packages/web/components/CommandPalette.tsx index 8434f976b7..5269cee2da 100644 --- a/packages/web/components/CommandPalette.tsx +++ b/packages/web/components/CommandPalette.tsx @@ -44,7 +44,7 @@ import { useVaultStore } from "../store/vaultStore"; import { filesHref, isFilesPath } from "../lib/vault/vaultHref"; import { openFiles } from "../lib/filesPane"; import { rankPaletteFiles } from "../lib/paletteFiles"; -import { EDITOR_PALETTE_COMMANDS, editorCommandsLead, runEditorPaletteCommand } from "../lib/editorPaletteCommands"; +import { EDITOR_PALETTE_COMMANDS, editorCommandsLead, editorPaletteKey, editorPaletteLabel, runEditorPaletteCommand } from "../lib/editorPaletteCommands"; import { useInboxStore, isConvexId, InboxSession, TaskItem, DocItem, BucketItem, BucketAssignmentItem, placeInboxRows, lastPlacedInbox, filterInboxScopeFromState, convBucketMap, sortLabels, computeChipCounts, projectOfFromState, getProjectName, RecentVisit, selectSessionRailOpen, sessionRowFromSummary } from "../store/inboxStore"; import { projectChipLabel } from "../store/workProjects"; import { resolveRecentVisits, visitTimeAgo, visitObjectLabel, type ResolvedVisit } from "../lib/recentVisits"; @@ -2416,7 +2416,7 @@ function CommandPaletteImpl({ standalone = false }: { standalone?: boolean }) { // The palette's row can predate a toggle; the store says what the star shows now. if (actionKey === "session_parent") { navigate(`/conversation/${session.parent_conversation_id}`); return; } if (actionKey === "session_branch") { void copyToClipboard(session.git_branch || "").then(() => toast.success("Branch copied")); closePalette(); return; } - if (actionKey === "session_files") { navigate(filesHref({ localPath: session.project_path || session.git_root })); return; } + if (actionKey === "session_files") { navigate(filesHref({ localPath: session.project_path || session.git_root, device: session.owner_device_id })); return; } const each: Record void> = { session_restore: (id) => state.restoreSession(id), // The teardown rides the hide transition server side (dispatch.applyPatches); @@ -2747,8 +2747,8 @@ function CommandPaletteImpl({ standalone = false }: { standalone?: boolean }) { {EDITOR_PALETTE_COMMANDS.map((c) => ( { closePalette(); runEditorPaletteCommand(c); @@ -2756,7 +2756,7 @@ function CommandPaletteImpl({ standalone = false }: { standalone?: boolean }) { className={itemClass} > - {c.label} + {editorPaletteLabel(c)} {c.shortcut && } {c.editorKey && ( diff --git a/packages/web/components/ConversationView.tsx b/packages/web/components/ConversationView.tsx index 009d3ae3ee..c0f92f7b43 100644 --- a/packages/web/components/ConversationView.tsx +++ b/packages/web/components/ConversationView.tsx @@ -166,8 +166,7 @@ import { openSessionAtMessage } from "../lib/openSessionAtMessage"; import type { MentionItem } from "./editor/MentionList"; import { HeaderPinMenuItem } from "./anchor/AnchorPanel"; import { Headphones, MessageSquare, CornerDownRight, Split, Workflow, Loader2, Bot, Forward, ArrowRightLeft, Cpu, FolderTree, ChevronLeft } from "lucide-react"; -import { filesHref } from "../lib/vault/vaultHref"; -import { openFiles } from "../lib/filesPane"; +import { openInEditor } from "../lib/filesPane"; import { openForwardToChat } from "../lib/forwardToChat"; import { useCallsAvailable, useTeamFeature } from "../lib/teamFeatures"; import { CursorPopover, useContextMenu } from "./ui/context-menu"; @@ -4910,9 +4909,9 @@ const ConversationViewInner = ( {filePathBase && !guest && ( - setTimeout(() => openFiles(filesHref({ localPath: filePathBase })))}> + setTimeout(() => openInEditor({ path: filePathBase, ctx: filePathCtx }))}> - Browse project files + Open project in editor )} {hasAnyThinking && ( diff --git a/packages/web/components/InlineDiff.tsx b/packages/web/components/InlineDiff.tsx index a9ef10ebd6..c23a1e4f50 100644 --- a/packages/web/components/InlineDiff.tsx +++ b/packages/web/components/InlineDiff.tsx @@ -1,7 +1,9 @@ import { useContext, useMemo, useState, memo } from "react"; import type { ReactNode } from "react"; import { getFileStatus } from "../lib/patchParser"; -import { DIFF_FENCE, parseCastDiff, type DiffFileSection } from "../lib/castDiff"; +import { DIFF_FENCE, firstChangedNewLine, parseCastDiff, type DiffFileSection } from "../lib/castDiff"; +import { FilePathContext } from "../lib/filePathLinks"; +import { OpenInEditorButton } from "./OpenInEditorButton"; import { DiffView } from "./DiffView"; import { CodeBlock } from "./CodeBlock"; import { MessageIdentity } from "../lib/conversationBlockContexts"; @@ -86,6 +88,9 @@ function DiffFileCard({ identity: { conversationId: string; messageId: string; live?: boolean } | null; }) { const [expanded, setExpanded] = useState(false); + // A git diff names files from the checkout's root, not the session's cwd. + const fileCtx = useContext(FilePathContext); + const editCtx = useMemo(() => (fileCtx?.gitRoot ? { ...fileCtx, base: fileCtx.gitRoot } : fileCtx), [fileCtx]); const statusMeta = getFileStatus(file.status); const language = languageFromPath(file.path); const commentContext = identity && !identity.live @@ -104,6 +109,7 @@ function DiffFileCard({ {file.path} + {editCtx && file.status !== "deleted" && } {file.additions > 0 && +{file.additions}} {file.deletions > 0 && −{file.deletions}} {file.fullContext && ( diff --git a/packages/web/components/KeyboardShortcutsHelp.tsx b/packages/web/components/KeyboardShortcutsHelp.tsx index 45a1e23baf..a2dcd18dbe 100644 --- a/packages/web/components/KeyboardShortcutsHelp.tsx +++ b/packages/web/components/KeyboardShortcutsHelp.tsx @@ -7,6 +7,8 @@ import { visibleShortcutSections } from "../shortcuts/visibleSections"; import { useKeyBindingsVersion, useShortcutParts } from "../shortcuts/registry"; import { rebindShortcut } from "../lib/keyboardSettings"; import { SEND_CHORDS } from "../shortcuts/sendChords"; +import { EDITOR_PALETTE_COMMANDS, editorPaletteKey } from "../lib/editorPaletteCommands"; +import type { ShortcutSection } from "../shortcuts/visibleSections"; import { useTrackedStore } from "../store/inboxStore"; import { useEventListener } from "../hooks/useEventListener"; import { DESKTOP_SHORTCUTS, getDesktopShortcutConfig } from "../lib/desktop"; @@ -20,6 +22,8 @@ import { useWorkspaceFeature } from "../lib/teamFeatures"; export { KeyCap }; +const isEditorAction = (action: string) => action.startsWith("code."); + export function KeyboardShortcutsPanel() { const s = useTrackedStore([ s => s.shortcutsPanelOpen, @@ -62,9 +66,26 @@ export function KeyboardShortcutsPanel() { const sections = useMemo(() => { type Row = { key: string; description: string; parts: string[]; action?: ShortcutAction }; const result: { label: string; accent: string; rows: Row[] }[] = []; + const rowOf = (a: ShortcutSection["actions"][number]): Row => ({ key: a.action, action: a.def.fixed ? undefined : a.action, description: a.label, parts: formatShortcutParts(a.def) }); + // The code editor's keys in one section: its app shortcuts (code.*), + // then each key the editor claims itself, read from the palette's list, + // so the panel and the palette show one set. + const editor = { + label: "Editor", + accent: "bg-sol-cyan", + rows: [ + ...visibleShortcutSections(flowsOn, getShortcutsByContext).flatMap((sec) => sec.actions.filter((a) => isEditorAction(a.action)).map(rowOf)), + ...EDITOR_PALETTE_COMMANDS.filter((c) => c.editorKey).map((c) => ({ key: `editor:${editorPaletteKey(c)}`, description: c.label, parts: formatAcceleratorParts(c.editorKey!) })), + ], + }; for (const sec of visibleShortcutSections(flowsOn, getShortcutsByContext)) { - if (sec.actions.length > 0) { - result.push({ label: sec.label, accent: sec.accent, rows: sec.actions.map((a) => ({ key: a.action, action: a.def.fixed ? undefined : a.action, description: a.label, parts: formatShortcutParts(a.def) })) }); + const actions = sec.actions.filter((a) => !isEditorAction(a.action)); + if (actions.length > 0) result.push({ label: sec.label, accent: sec.accent, rows: actions.map(rowOf) }); + // After Global, or first while a code editor is on screen. + if (sec.when === undefined) { + const editorOnScreen = s.shortcutsPanelOpen && typeof document !== "undefined" && !!document.querySelector("[data-code-workspace]"); + if (editorOnScreen) result.unshift(editor); + else result.push(editor); } // The composer's send chords live in their own table (they run from a // focused textarea, outside the registry); they read as the diff --git a/packages/web/components/OpenInEditorButton.tsx b/packages/web/components/OpenInEditorButton.tsx index 111e7a7aa1..476690627a 100644 --- a/packages/web/components/OpenInEditorButton.tsx +++ b/packages/web/components/OpenInEditorButton.tsx @@ -22,6 +22,7 @@ import { cn } from "../lib/utils"; export function OpenInEditorButton({ target, diffAgainst, + peek, label, editorOnly, className, @@ -29,6 +30,8 @@ export function OpenInEditorButton({ /** `ctx` resolves a relative path; the conversation's own when absent. */ target: EditorTarget; diffAgainst?: OpenInEditorOptions["diffAgainst"]; + /** Peek the change at the landed line once the file shows (an edit card). */ + peek?: boolean; /** Shown beside the icon; icon only when absent. */ label?: string; /** Not drawn when the editor cannot reach the file (a surface that already @@ -59,7 +62,7 @@ export function OpenInEditorButton({ aria-label={label ? undefined : reachable ? "Open in editor" : "Open in session changes"} onClick={(e) => { e.stopPropagation(); - openConversationPath({ ...target, ctx }, { fromLeaf, diffAgainst }); + openConversationPath({ ...target, ctx }, { fromLeaf, diffAgainst, peek }); }} className={cn( "inline-flex items-center gap-1 shrink-0 rounded px-0.5 text-sol-text-dim hover:text-sol-text hover:bg-sol-bg-alt transition-colors", diff --git a/packages/web/components/PlanDetailPanel.tsx b/packages/web/components/PlanDetailPanel.tsx index 27fa10c495..abc2c375d1 100644 --- a/packages/web/components/PlanDetailPanel.tsx +++ b/packages/web/components/PlanDetailPanel.tsx @@ -63,6 +63,7 @@ import { useRunCost } from "./consequential/useRunCost"; import { workflowAgentSteps, workflowRunLedger, workflowSteps } from "./work/startLedgers"; import { useWorkflow } from "../hooks/useSyncWorkflows"; import { teamMembersOf } from "../lib/activeTeam"; +import { FilePathContext, useFolderPathContext } from "../lib/filePathLinks"; const api = _api as any; @@ -220,8 +221,10 @@ export function DriveRoundIndicator({ driveState }: { driveState: { current_roun ); } -function CollapsibleDoc({ content }: { content: string }) { +function CollapsibleDoc({ content, projectPath }: { content: string; projectPath?: string }) { const [expanded, setExpanded] = useState(false); + // A path the doc cites (`lib/x.ts:38`) is relative to the plan's project. + const fileCtx = useFolderPathContext(projectPath); const MAX_HEIGHT = 200; return ( @@ -234,7 +237,9 @@ function CollapsibleDoc({ content }: { content: string }) { prose-code:text-sol-cyan prose-code:bg-sol-bg-highlight prose-code:px-1 prose-code:rounded prose-code:text-xs prose-strong:text-sol-text prose-a:text-sol-cyan [&_pre]:overflow-x-auto [&_pre]:max-w-full"> - {content} + + {content} +
+ + + )} + {segments.map((seg, i) => + i < hide ? null : ( + // The nearest folder alone may truncate, when even it has no room. + 0 || segments.length === 1) ? "min-w-0" : "shrink-0"}`}> + + + + ), + )} + + {(n) => ( + <> + {segments.slice(0, n).map((seg, i) => ( + + {seg} + + ))} + + )} + + + ); +} + export const CodeFileBar = memo(function CodeFileBar({ path, actions }: { path: string; actions?: ReactNode }) { const canReveal = useVaultStore((s) => !!s.endpoint && !s.isRemote); const group = useCodeGroup(); + const navRef = useRef(null); const symbolsRef = useRef(null); useWatchEffect(() => { const el = symbolsRef.current; if (!el || !group) return; return bindGroupCrumbs(group.key, el); }, [group?.key]); - const segments = path.split("/"); - const name = segments[segments.length - 1]; + const name = path.slice(path.lastIndexOf("/") + 1); return ( -
- diff --git a/packages/web/components/code/CodeFileView.tsx b/packages/web/components/code/CodeFileView.tsx index cf6b1604ae..b70c8dc5d0 100644 --- a/packages/web/components/code/CodeFileView.tsx +++ b/packages/web/components/code/CodeFileView.tsx @@ -4,75 +4,150 @@ // bundle. Above the editor sits the strip for the one state that needs a // person: disk and the buffer disagree. -import { useMemo, useRef, useState } from "react"; +import { useMemo, useRef, useState, type ReactNode } from "react"; +import type { EditorView } from "@codemirror/view"; import { useWatchEffect } from "../../hooks/useWatchEffect"; import { useVaultStore } from "../../store/vaultStore"; import { useCodeStore, type CodeConflict } from "../../store/codeStore"; -import { bufferKey, codeBuffers } from "../../lib/code/buffers"; +import { bufferKey, codeBuffers, currentState, diskLockField, type CodeBuffer } from "../../lib/code/buffers"; +import { registerCodeCommands, runCodeCommand, type CodeCommandContext, type CodeCommandId } from "../../lib/code/commands"; +import { featureContext, focusedEditorView } from "../../lib/code/features"; +import { formatAcceleratorParts } from "../../shortcuts"; +import { KeyCap } from "../KeyCap"; import { parseCursorTarget, type EditorHost } from "../../lib/code/editorHost"; -import { diskRemoved, mergeWithDisk, recreateFile, saveBuffer, takeDisk } from "../../lib/code/fileSync"; -import { loadMergeKit } from "../../lib/code/merge"; +import { diskRemoved, keepMine, mergeWithDisk, overwriteLocked, recreateFile, saveBuffer, takeDisk } from "../../lib/code/fileSync"; +import { loadMergeKit, stepMerge } from "../../lib/code/merge"; import { loadHotExit } from "../../lib/code/hotExit"; import { useIsNewFile } from "../../lib/code/newFiles"; import { CodeEditor } from "./CodeEditor"; import { BlameCardHost } from "./blame/BlameCardHost"; import { modernButton } from "../ui/modernLook"; import { ConflictWriter } from "./agent/ConflictWriter"; +import { DaemonReconnecting, useStalled } from "../vault/FileUnavailable"; +import { LoadingBar } from "../ui/LoadingBar"; +import { Lock, WifiOff } from "lucide-react"; +import { OverwriteReview } from "./OverwriteReview"; const stripButton = modernButton({ variant: "outline", size: "xs" }); -function ConflictStrip({ conflict, bufferId, hostRef }: { conflict: CodeConflict; bufferId: string; hostRef: React.MutableRefObject }) { - const buffer = () => codeBuffers.get(bufferId); - const run = (fn: (b: NonNullable>) => unknown) => () => { - const b = buffer(); +// The strip's verbs as commands, so the palette and the keys reach them with +// focus in the editor: each acts on the buffer of the editor the person was +// in (contract 9) and declines when that buffer has no change to settle. +registerCodeCommands( + Object.fromEntries( + ( + [ + ["merge.withDisk", ["stale"], (b) => b.stale && mergeWithDisk(b, b.stale)], + ["merge.takeDisk", ["stale", "merge"], (b) => takeDisk(b)], + ["merge.keepMine", ["stale", "merge"], (b) => keepMine(b)], + ["merge.next", ["merge"], (_b, view) => loadMergeKit().then((kit) => stepMerge(kit, view, 1))], + ["merge.prev", ["merge"], (_b, view) => loadMergeKit().then((kit) => stepMerge(kit, view, -1))], + ] as [CodeCommandId, CodeConflict["kind"][], (b: CodeBuffer, view: EditorView) => unknown][] + ).map(([id, kinds, verb]) => [ + id, + (_args: unknown, ctx: CodeCommandContext) => { + const view = ctx.view ?? focusedEditorView(); + const at = view?.state.facet(featureContext); + if (!view || !at) return false; + const key = bufferKey(at.vaultId, at.path); + const b = codeBuffers.get(key); + const kind = useCodeStore.getState().conflicts[key]?.kind; + if (!b || !kind || !kinds.includes(kind)) return false; + void verb(b, view); + view.focus(); + }, + ]), + ), +); + +/** A strip button that runs its command, and shows the key when it has one. */ +function StripAction({ id, label, keys, name, view }: { id: CodeCommandId; label: ReactNode; keys?: string; name?: string; view: () => EditorView | undefined }) { + const parts = keys ? formatAcceleratorParts(keys) : null; + return ( + + ); +} + +const STRIP_TITLE: Record = { + error: "Save failed", + deleted: "Deleted on disk", + stale: "Changed on disk", + merge: "Changed on disk", + readonly: "Read-only on disk", + offline: "Not saved", +}; + +function ConflictStrip({ conflict, bufferId, hostRef, onOverwrite }: { conflict: CodeConflict; bufferId: string; hostRef: React.MutableRefObject; onOverwrite: () => void }) { + const run = (fn: (b: NonNullable>) => unknown) => () => { + const b = codeBuffers.get(bufferId); if (b) void fn(b); hostRef.current?.view.focus(); }; - const step = (dir: 1 | -1) => () => { - const view = hostRef.current?.view; - if (!view) return; - void loadMergeKit().then((kit) => (dir === 1 ? kit.goToNextChunk : kit.goToPreviousChunk)(view)); - view.focus(); - }; + const view = () => hostRef.current?.view; const alarm = conflict.kind === "error" || conflict.kind === "deleted"; const tone = alarm ? "border-sol-red/40 bg-sol-red/10" : "border-sol-yellow/40 bg-sol-yellow/10"; - const title = { error: "Save failed", deleted: "Deleted on disk", stale: "Changed on disk", merge: "Changed on disk" }[conflict.kind]; return ( -
- {title} +
+ {conflict.kind === "readonly" && } + {conflict.kind === "offline" && } + {STRIP_TITLE[conflict.kind]} + {conflict.kind === "readonly" && {conflict.mode}} + {conflict.kind === "offline" && ( + + + Reconnecting + + )} {(conflict.kind === "stale" || conflict.kind === "merge") && } {conflict.kind === "merge" && ( - - {conflict.remaining} {conflict.remaining === 1 ? "difference" : "differences"} - {conflict.conflicts > 0 && ` · ${conflict.conflicts} ${conflict.conflicts === 1 ? "conflict" : "conflicts"}`} + + {conflict.conflicts > 0 && ( + + {conflict.conflicts} {conflict.conflicts === 1 ? "conflict" : "conflicts"} + + )} + {conflict.conflicts > 0 && ·} + + {conflict.remaining} {conflict.remaining === 1 ? "difference" : "differences"} + + + )} + {conflict.kind === "error" && ( + + {conflict.message} )} - {conflict.kind === "error" && {conflict.message}} {conflict.kind === "merge" && ( <> - - + 0 ? "Previous conflict" : "Previous difference"} /> + 0 ? "Next conflict" : "Next difference"} /> )} - {conflict.kind === "stale" && ( - )} - {(conflict.kind === "stale" || conflict.kind === "merge") && ( - )} - {conflict.kind === "deleted" ? ( - - ) : ( + {(conflict.kind === "merge" || conflict.kind === "error") && ( )} @@ -121,15 +196,66 @@ export function CodeFileView({ path, line, missing = false, newFile: noFile = fa }, [waiting, key]); const preview = waiting && held?.key === key ? held.text : null; + // A cached boot reads the file once the daemon answers. When that takes + // longer than a beat, the wait turns into the read-failure state, with a + // Retry that reconnects, rather than an empty editor with no end. + const reconnecting = useVaultStore((s) => s.connection === "cached" && !s.endpoint && !s.isRemote); + const [stalled, retryStalled] = useStalled(waiting && preview === null && reconnecting, key); + + // Writing a file its mode refuses asks first: the strip's Overwrite, and + // vim's `:w!` (file.overwrite) from this editor. On a writable file `:w!` is + // a plain save. + const [overwriting, setOverwriting] = useState(null); + const askOverwrite = () => { + const b = codeBuffers.get(key); + if (!b) return; + const mode = conflict?.kind === "readonly" ? conflict.mode : currentState(b).field(diskLockField); + if (mode) setOverwriting(mode); + else void saveBuffer(b); + }; + const askRef = useRef(askOverwrite); + askRef.current = askOverwrite; + useWatchEffect(() => { + if (!key) return; + return registerCodeCommands({ + "file.overwrite": (_args, ctx) => { + const view = ctx.view ?? focusedEditorView(); + if (!view || view !== hostRef.current?.view) return false; + askRef.current(); + }, + }); + }, [key]); + if (!vaultId) return null; // While the file's text is on its way the editor stays mounted, empty, so // opening a file never rebuilds the view or jumps the layout. return (
- {conflict && } + {conflict && } + {overwriting && ( + { + setOverwriting(null); + hostRef.current?.view.focus(); + }} + onConfirm={() => { + setOverwriting(null); + const b = codeBuffers.get(key); + if (b) void overwriteLocked(b); + hostRef.current?.view.focus(); + }} + /> + )}
{waiting && !preview && ( -
Loading…
+ + )} + {stalled && ( +
+ +
)} void; onConfirm: () => void }) { + return ; +} diff --git a/packages/web/components/code/__tests__/codeFileBar.test.ts b/packages/web/components/code/__tests__/codeFileBar.test.ts new file mode 100644 index 0000000000..698f56ac4f --- /dev/null +++ b/packages/web/components/code/__tests__/codeFileBar.test.ts @@ -0,0 +1,12 @@ +import { expect, test } from "bun:test"; +import { foldedFolders } from "../CodeFileBar"; + +test("leading folders fold first; the nearest one never folds", () => { + const widths = [70, 40, 80, 60]; + expect(foldedFolders(widths, 300)).toBe(0); + // 250 px of folders in 220: dropping the first (70) leaves 180 plus the "…" crumb (30). + expect(foldedFolders(widths, 220)).toBe(1); + expect(foldedFolders(widths, 100)).toBe(3); + expect(foldedFolders(widths, 10)).toBe(3); + expect(foldedFolders([], 0)).toBe(0); +}); diff --git a/packages/web/components/code/__tests__/firstRun.mount.test.tsx b/packages/web/components/code/__tests__/firstRun.mount.test.tsx new file mode 100644 index 0000000000..5d3f984d93 --- /dev/null +++ b/packages/web/components/code/__tests__/firstRun.mount.test.tsx @@ -0,0 +1,111 @@ +// The first screens of the editor: an empty group lists the files opened +// lately and the two ways to find another, and stays blank while a deep link +// resolves; quick open offers a typed path the scan does not list. +import { afterEach, expect, test } from "bun:test"; +import { installEditorDom, settle } from "./editorDom"; + +installEditorDom(); + +const React = await import("react"); +const { act } = React; +const { createRoot } = await import("react-dom/client"); +const { useVaultStore } = await import("../../../store/vaultStore"); +const { EditorGroup } = await import("../workspace/EditorGroup"); +const { QuickOpen } = await import("../workspace/QuickOpen"); +const { registerCodeCommand } = await import("../../../lib/code/commands"); + +const roots: { unmount(): void }[] = []; +afterEach(() => act(() => roots.splice(0).forEach((r) => r.unmount()))); + +async function mount(node: React.ReactNode): Promise { + const host = document.createElement("div"); + document.body.append(host); + const root = createRoot(host); + roots.push(root); + await act(async () => { + root.render(node); + await settle(); + }); + return host; +} + +useVaultStore.setState({ + activeVaultId: "vault-1", + files: { + "src/a.ts": { path: "src/a.ts", mtime: 1, size: 1 }, + "README.md": { path: "README.md", mtime: 1, size: 1 }, + } as any, +}); + +const noop = () => {}; +const group = (recent: string[], deepLinking: boolean, onOpen: (g: string, p: string) => void) => ( + null} + onFocusGroup={noop} + onActivate={noop} + onOpen={onOpen} + onClose={noop} + onKeep={noop} + onMove={noop} + onMenu={noop} + onSplit={noop} + /> +); + +test("an empty group lists recent files still on disk and opens one on click", async () => { + const opened: string[] = []; + const host = await mount(group(["src/a.ts", "src/gone.ts", "README.md"], false, (_g, p) => opened.push(p))); + const rows = [...host.querySelectorAll('[aria-label="Recent files"] button')]; + expect(rows.map((r) => r.textContent)).toEqual(["a.tssrc", "README.md"]); + await act(async () => (rows[0] as HTMLButtonElement).click()); + expect(opened).toEqual(["src/a.ts"]); + expect(host.textContent).toContain("Go to file"); + expect(host.textContent).toContain("Search"); +}); + +test("its key hints are buttons that run their commands", async () => { + const ran: string[] = []; + const offs = [registerCodeCommand("quickOpen", () => void ran.push("quickOpen")), registerCodeCommand("search.project", () => void ran.push("search"))]; + try { + const host = await mount(group([], false, noop)); + expect(host.querySelector('[aria-label="Recent files"]')).toBeNull(); + const buttons = [...host.querySelectorAll("button")]; + await act(async () => { + buttons.find((b) => b.textContent?.startsWith("Go to file"))!.click(); + buttons.find((b) => b.textContent?.startsWith("Search"))!.click(); + }); + expect(ran).toEqual(["quickOpen", "search"]); + } finally { + offs.forEach((off) => off()); + } +}); + +test("while a deep link resolves the empty group draws nothing", async () => { + const host = await mount(group(["src/a.ts"], true, noop)); + expect(host.textContent).not.toContain("Go to file"); + expect(host.querySelector('[aria-label="Recent files"]')).toBeNull(); +}); + +test("quick open offers a typed path the scan lacks, and opens it on Enter", async () => { + const opened: string[] = []; + const host = await mount( opened.push(`${p}@${at}`)} onGotoLine={noop} onClose={noop} />); + expect(host.textContent).toContain("Opendist/gen/out.js"); + const input = host.querySelector("input")!; + await act(async () => input.dispatchEvent(new KeyboardEvent("keydown", { key: "Enter", bubbles: true }))); + expect(opened).toEqual(["dist/gen/out.js@12"]); +}); + +test("quick open with no match and no path says so in two words", async () => { + const host = await mount(); + expect(host.textContent).toContain("No match"); + expect(host.textContent).not.toContain("Open"); +}); diff --git a/packages/web/components/code/__tests__/typingAllFeatures.mount.test.tsx b/packages/web/components/code/__tests__/typingAllFeatures.mount.test.tsx new file mode 100644 index 0000000000..66a4dab33b --- /dev/null +++ b/packages/web/components/code/__tests__/typingAllFeatures.mount.test.tsx @@ -0,0 +1,270 @@ +// Contract 1 of docs/architecture/code-editor.md with everything on: the +// workspace shows a 5,000-line TypeScript file with vim (from a vimrc), a +// language server, the git gutter, session blame and the agent layer (a working +// session linked to the folder). Typing in insert mode, moving in normal mode, +// and the server publishing diagnostics and progress while the person types +// commit React zero times and write no store. Each keystroke's cost here is +// logged, not asserted: jsdom does no layout, so the browser number lives in +// perf/README.md ("Editor"). +// +// Keystrokes are the transactions CodeMirror's input handling produces +// (userEvent "input.type") behind vim's insert mode, and vim's own key handler +// for normal mode; jsdom has no beforeinput for CodeMirror's DOM observer. +import { afterAll, expect, mock, test } from "bun:test"; +import { installEditorDom, settle } from "./editorDom"; + +installEditorDom(); +localStorage.setItem("codecast.code.blameGutter", "1"); + +const realPanels = { ...(await import("react-resizable-panels")) }; +mock.module("react-resizable-panels", () => ({ + ...realPanels, + Group: ({ children }: { children: unknown }) => children, + Panel: ({ children }: { children: unknown }) => children, + Separator: () => null, +})); +const realConvex = { ...(await import("convex/react")) }; +mock.module("convex/react", () => ({ ...realConvex, useConvex: () => ({}) })); + +const LINES = 5_000; +const lines: string[] = []; +for (let i = 0; i < LINES; i++) lines.push(i % 10 === 0 ? `export function f${i}(a: number) {` : i % 10 === 9 ? "}" : ` const v${i} = a + ${i}; // line ${i}`); +const text = lines.join("\n") + "\n"; +const small = "export const small = 1;\n"; +const base = text.replace("const v1 = a + 1;", "const v1 = a - 1;").replace("const v2001 =", "let v2001 ="); + +const calls = { status: 0, base: 0, blame: 0, vimrc: 0 }; +const realClient = { ...(await import("../../../lib/code/daemonClient")) }; +mock.module("../../../lib/code/daemonClient", () => ({ + ...realClient, + fetchVimrcText: async () => { + calls.vimrc++; + return JSON.stringify({ sources: [{ path: "/home/test/.vimrc", content: 'let mapleader=","\nset relativenumber\nnoremap H ^\n' }], overlay: null }); + }, + fetchGitStatus: async () => { + calls.status++; + return { repo: true, branch: "main", head: "h1", ahead: 0, behind: 0, files: { "src/big.ts": "modified" } }; + }, + fetchGitBase: async (_ep: unknown, _v: string, path: string) => { + calls.base++; + return { path, ref: "HEAD", exists: true, content: base }; + }, + fetchBlame: async (_ep: unknown, _v: string, path: string) => { + calls.blame++; + const session = { id: "jx7aaaa", conversation_id: "a".repeat(32), title: "Big refactor", message_id: "m1" }; + return { path, hunks: [{ start: 1, end: LINES, sha: "a".repeat(40), author: "Ada", summary: "first", time: Date.now() - 3_600_000, session }] }; + }, +})); + +// The daemon's language server, behind /lsp/ws. +class FakeLspSocket { + static all: FakeLspSocket[] = []; + readyState = 0; + sent: string[] = []; + onopen: (() => void) | null = null; + onmessage: ((ev: { data: string }) => void) | null = null; + onclose: (() => void) | null = null; + onerror: (() => void) | null = null; + constructor(readonly url: string) { + FakeLspSocket.all.push(this); + setTimeout(() => { + this.readyState = 1; + this.onopen?.(); + this.say({ type: "ready", server: SERVER, root_uri: "file:///tmp/repo" }); + }, 0); + } + send(data: string) { + this.sent.push(data); + const m = JSON.parse(data); + if (m.method === "initialize") queueMicrotask(() => this.say({ jsonrpc: "2.0", id: m.id, result: { capabilities: { textDocumentSync: 2, hoverProvider: true } } })); + else if (m.id !== undefined && m.method) queueMicrotask(() => this.say({ jsonrpc: "2.0", id: m.id, result: null })); + } + close() {} + say(msg: object) { + this.onmessage?.({ data: JSON.stringify(msg) }); + } + methods(): string[] { + return this.sent.map((s) => JSON.parse(s).method ?? ""); + } +} +const SERVER = { id: "typescript", name: "TypeScript", languages: ["typescript"], available: true, command: "/bin/tsls" }; +const realWebSocket = globalThis.WebSocket; +const realFetch = globalThis.fetch; +globalThis.WebSocket = FakeLspSocket as unknown as typeof WebSocket; +globalThis.fetch = (async (url: string) => + String(url).includes("/lsp/servers") ? new Response(JSON.stringify({ servers: [SERVER] })) : new Response("{}", { status: 404 })) as unknown as typeof fetch; + +const React = await import("react"); +const { act, Profiler } = React; +const { createRoot } = await import("react-dom/client"); +const { EditorView } = await import("@codemirror/view"); +const { getCM, Vim } = await import("@replit/codemirror-vim"); +const { useVaultStore } = await import("../../../store/vaultStore"); +const { useInboxStore } = await import("../../../store/inboxStore"); +const { useCodeStore } = await import("../../../store/codeStore"); +const { useGitStatusStore } = await import("../../../lib/code/git/status"); +const { useAgentStore } = await import("../../../lib/code/agent/agentStore"); +const { codeBuffers } = await import("../../../lib/code/buffers"); +const { emptyWorkspace, openTab } = await import("../../../lib/code/workspace/model"); +const { workspaceActions } = await import("../../../lib/code/workspace/controller"); +const { disposeLspPool } = await import("../../../lib/code/lsp/pool"); +const { CodeWorkspace } = await import("../workspace/CodeWorkspace"); +await import("../CodeFileView"); + +const VAULT = "vault-all-features"; +const ROOT = "/tmp/repo"; +for (const old of codeBuffers.all()) codeBuffers.close(old.key); +useVaultStore.setState({ + activeVaultId: VAULT, + isRemote: false, + endpoint: { port: 1, token: "t" } as any, + vaults: [{ id: VAULT, root: ROOT, name: "repo" }] as any, + files: { "src/big.ts": { path: "src/big.ts", mtime: 1, size: text.length }, "src/small.ts": { path: "src/small.ts", mtime: 1, size: small.length } } as any, + bodies: { "src/big.ts": { content: text, mtime: 1, etag: "e1" }, "src/small.ts": { content: small, mtime: 1, etag: "e2" } }, +}); +const inboxBefore = useInboxStore.getState(); +useInboxStore.setState({ + sessions: { + s1: { _id: "s1", title: "Big refactor", agent_type: "claude_code", project_path: ROOT, git_root: ROOT, status: "working", updated_at: Date.now(), last_activity_at: Date.now() }, + }, +} as never); +useCodeStore.setState({ dirty: {}, conflicts: {}, workspaces: { [VAULT]: openTab(emptyWorkspace(), "src/big.ts") } }); + +afterAll(() => { + globalThis.WebSocket = realWebSocket; + globalThis.fetch = realFetch; + disposeLspPool(); + useInboxStore.setState(inboxBefore as never, true); + globalThis.localStorage?.removeItem("codecast.code.blameGutter"); +}); + +const host = document.createElement("div"); +host.style.width = "1200px"; +host.style.height = "800px"; +document.body.append(host); +let commits = 0; +const root = createRoot(host); + +const until = async (check: () => boolean, what: string) => { + for (let i = 0; i < 300 && !check(); i++) await act(settle); + if (!check()) throw new Error(`timed out waiting for ${what}`); +}; + +test("5,000 lines with vim, LSP, git gutter, blame and agent: typing costs React and every store nothing", async () => { + await act(async () => { + root.render( + commits++}> + {}} + onToggleTree={() => {}} + renderNote={() => null} + /> + , + ); + }); + const viewEl = () => host.querySelector(".cm-editor") as HTMLElement | null; + await until(() => !!viewEl(), "the editor"); + const view = EditorView.findFromDOM(viewEl()!)!; + // Every feature on before a key is typed. + await until(() => !!getCM(view), "vim"); + await until(() => !!host.querySelector(".cm-git-gutter") && calls.base > 0, "the git gutter"); + await until(() => !!host.querySelector(".cm-blame-gutter") && calls.blame > 0, "the blame gutter"); + await until(() => FakeLspSocket.all.some((ws) => ws.methods().includes("textDocument/didOpen")), "the language server"); + await until(() => useAgentStore.getState().links[VAULT]?.sessionId === "s1", "the linked session"); + expect(view.state.doc.lines).toBe(LINES + 1); + const lsp = FakeLspSocket.all.find((ws) => ws.methods().includes("textDocument/didOpen"))!; + const cm = getCM(view)!; + + // Into insert mode on line 2, and the first keystroke flips the buffer dirty. + await act(async () => { + view.dispatch({ selection: { anchor: view.state.doc.line(2).from } }); + Vim.handleKey(cm, "i", "user"); + }); + const typeChar = (ch: string) => { + const pos = view.state.selection.main.head; + view.dispatch({ changes: { from: pos, insert: ch }, selection: { anchor: pos + 1 }, userEvent: "input.type" }); + }; + await act(async () => typeChar("x")); + await act(settle); + + const writes = { vault: 0, code: 0, git: 0, agent: 0, inbox: 0 }; + const offs = [ + useVaultStore.subscribe(() => writes.vault++), + useCodeStore.subscribe(() => writes.code++), + useGitStatusStore.subscribe(() => writes.git++), + useAgentStore.subscribe(() => writes.agent++), + useInboxStore.subscribe(() => writes.inbox++), + ]; + const commitsBefore = commits; + const uri = "file:///tmp/repo/src/big.ts"; + const times: number[] = []; + + await act(async () => { + for (let i = 0; i < 200; i++) { + const t = performance.now(); + typeChar(String.fromCharCode(97 + (i % 26))); + times.push(performance.now() - t); + if (i % 10 === 9) { + // The server answers typing with diagnostics and progress, as tsserver does. + lsp.say({ jsonrpc: "2.0", method: "$/progress", params: { token: "t1", value: { kind: "report", message: `${i}` } } }); + lsp.say({ + jsonrpc: "2.0", + method: "textDocument/publishDiagnostics", + params: { uri, diagnostics: [{ range: { start: { line: 1, character: 2 }, end: { line: 1, character: 8 } }, severity: 1, message: `e${i}` }] }, + }); + } + } + // Normal mode: out of insert, motions, back in. + Vim.handleKey(cm, "", "user"); + for (const key of ["j", "j", "w", "b", "k", "$", "0", "j"]) Vim.handleKey(cm, key, "user"); + Vim.handleKey(cm, "i", "user"); + for (let i = 0; i < 20; i++) typeChar("y"); + }); + await act(settle); + + for (const off of offs) off(); + times.sort((x, y) => x - y); + console.log(`[typing, all features, 5k lines, jsdom] median ${times[100].toFixed(2)}ms p95 ${times[190].toFixed(2)}ms per keystroke`); + expect(commits - commitsBefore).toBe(0); + expect(writes).toEqual({ vault: 0, code: 0, git: 0, agent: 0, inbox: 0 }); + expect(view.state.doc.line(2).text.startsWith("x")).toBe(true); + // The server hears the typing (incremental sync, on the client's own clock). + await until(() => lsp.methods().includes("textDocument/didChange"), "didChange"); + await act(async () => root.unmount()); +}); + +test("a warm tab switch shows the other file in the same task; the 5,000-line buffer comes back as it was", async () => { + useCodeStore.setState({ workspaces: { [VAULT]: openTab(openTab(emptyWorkspace(), "src/small.ts"), "src/big.ts") } }); + const again = createRoot(host); + await act(async () => { + again.render( + {}} onToggleTree={() => {}} renderNote={() => null} />, + ); + }); + await until(() => !!host.querySelector(".cm-editor .cm-line"), "the editor"); + const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!; + await act(async () => { + workspaceActions.activate(VAULT, "g1", "src/small.ts"); + await settle(); + }); + const times: number[] = []; + for (let i = 0; i < 10; i++) { + for (const path of ["src/big.ts", "src/small.ts"]) { + const t = performance.now(); + await act(async () => workspaceActions.activate(VAULT, "g1", path)); + // Same task: the view already holds the file, before any frame or timer. + expect(view.state.doc.lines).toBe(path === "src/small.ts" ? 2 : LINES + 1); + times.push(performance.now() - t); + } + } + times.sort((x, y) => x - y); + console.log(`[tab switch, all features, jsdom] median ${times[10].toFixed(2)}ms max ${times[19].toFixed(2)}ms`); + expect(view.state.doc.lines).toBe(2); + expect(EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)).toBe(view); + await act(async () => again.unmount()); +}); diff --git a/packages/web/components/code/__tests__/vaultFileViewRead.mount.test.tsx b/packages/web/components/code/__tests__/vaultFileViewRead.mount.test.tsx index b5b80ee818..d01bf01ba5 100644 --- a/packages/web/components/code/__tests__/vaultFileViewRead.mount.test.tsx +++ b/packages/web/components/code/__tests__/vaultFileViewRead.mount.test.tsx @@ -45,7 +45,7 @@ function setVault(state: Partial>) { test("a cached boot waits for the daemon instead of claiming the read failed", async () => { setVault({ endpoint: null, isRemote: false, connection: "cached" }); const host = await render(); - expect(host.textContent).not.toContain("Couldn't read this file."); + expect(host.textContent).not.toContain("Couldn't read"); expect(host.querySelector(".cm-editor")).not.toBeNull(); expect(host.textContent).toContain("Loading"); }); @@ -53,7 +53,7 @@ test("a cached boot waits for the daemon instead of claiming the read failed", a test("no daemon at all says the file could not be read", async () => { setVault({ endpoint: null, isRemote: false, connection: "no-daemon" }); const host = await render(); - expect(host.textContent).toContain("Couldn't read this file."); + expect(host.textContent).toContain("Couldn't read"); }); test("a cached boot shows unsaved text held for hot exit, read-only, then loads the file", async () => { @@ -219,7 +219,7 @@ test("a clean file removed and restored on disk comes back in its editor", async await settle(); }); // The editor stays, saying so, with a way to write the file back. - expect(host.textContent).not.toContain("This file does not exist."); + expect(host.textContent).not.toContain("Not on disk"); expect(host.textContent).toContain("Deleted on disk"); expect(host.textContent).toContain("Recreate"); await act(async () => { @@ -240,14 +240,14 @@ test("a clean file removed and restored on disk comes back in its editor", async test("while discovery runs it waits for the read instead", async () => { setVault({ endpoint: null, isRemote: false, connection: "discovering" }); const host = await render(); - expect(host.textContent).not.toContain("Couldn't read this file."); + expect(host.textContent).not.toContain("Couldn't read"); }); test("a remote vault without the file's text says it could not be read", async () => { // No Convex client: the remote read returns without a body. setVault({ endpoint: null, isRemote: true, connection: "connected" }); const host = await render(); - expect(host.textContent).toContain("Couldn't read this file."); + expect(host.textContent).toContain("Couldn't read"); }); test("unsaved edits outlive their file leaving disk and see it come back", async () => { @@ -288,3 +288,65 @@ test("unsaved edits outlive their file leaving disk and see it come back", async expect(host.textContent).toContain("Changed on disk"); expect(view.state.doc.toString()).toBe(`// mine\n${text}`); }); + +test("a failed read names why, keeps the file bar, and Retry reads again", async () => { + const { EditorView } = await import("@codemirror/view"); + const file = "src/denied.ts"; + const text = "export const d = 1;\n"; + const realFetch = globalThis.fetch; + let reads = 0; + globalThis.fetch = (async (url: string) => { + if (!String(url).includes("/vault/file")) return new Response("{}", { status: 404 }); + if (reads++ === 0) return new Response("no", { status: 403 }); + return new Response(text, { status: 200, headers: { "X-Vault-Mtime": "1", "X-Vault-Size": String(text.length), ETag: "e1" } }); + }) as any; + try { + setVault({ endpoint: { port: 1, token: "t" } as any, isRemote: false, connection: "connected", files: { [file]: { path: file, mtime: 1, size: text.length } } as any }); + const host = await render(file); + for (let i = 0; i < 20 && !host.textContent?.includes("Couldn't read"); i++) await act(() => settle()); + expect(host.textContent).toContain("Couldn't read"); + expect(host.textContent).toContain("No permission"); + // The breadcrumbs row stays: the file's name is still on screen. + expect(host.querySelector("nav")?.textContent).toContain("denied.ts"); + const retry = [...host.querySelectorAll("button")].find((b) => b.textContent?.includes("Retry"))!; + await act(async () => { + retry.click(); + await settle(); + }); + for (let i = 0; i < 20 && !host.querySelector(".cm-editor"); i++) await act(() => settle()); + const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!; + for (let i = 0; i < 20 && view.state.doc.toString() !== text; i++) await act(() => settle()); + expect(view.state.doc.toString()).toBe(text); + expect(reads).toBe(2); + } finally { + globalThis.fetch = realFetch; + } +}); + +test("a cached boot that waits past a beat offers Retry, which reconnects", async () => { + setVault({ endpoint: null, isRemote: false, connection: "cached", files: { "src/slow.ts": { path: "src/slow.ts", mtime: 1, size: 9 } } as any }); + let reconnects = 0; + const realReconnect = useVaultStore.getState().reconnect; + useVaultStore.setState({ reconnect: async () => void reconnects++ }); + try { + const host = await render("src/slow.ts"); + expect(host.querySelector('[role="progressbar"]')).not.toBeNull(); + expect(host.textContent).not.toContain("Couldn't read"); + await act(() => new Promise((r) => setTimeout(r, 4100))); + expect(host.textContent).toContain("Daemon reconnecting"); + const retry = [...host.querySelectorAll("button")].find((b) => b.textContent?.includes("Retry"))!; + await act(async () => retry.click()); + expect(reconnects).toBe(1); + expect(host.textContent).not.toContain("Daemon reconnecting"); + } finally { + useVaultStore.setState({ reconnect: realReconnect }); + } +}, 10000); + +test("a text file past the editor's limit says its size and the limit", async () => { + setVault({ endpoint: null, isRemote: false, connection: "connected", files: { "big.log": { path: "big.log", mtime: 1, size: 40 * 1024 * 1024 } } as any }); + const host = await render("big.log"); + expect(host.textContent).toContain("Too large"); + expect(host.textContent).toContain("40 MB · limit"); + expect(host.querySelector("nav")?.textContent).toContain("big.log"); +}); diff --git a/packages/web/components/code/__tests__/vimFirstRun.mount.test.tsx b/packages/web/components/code/__tests__/vimFirstRun.mount.test.tsx new file mode 100644 index 0000000000..9f1ead1adb --- /dev/null +++ b/packages/web/components/code/__tests__/vimFirstRun.mount.test.tsx @@ -0,0 +1,64 @@ +// A person with no vimrc: vim stays off, and the status bar still offers it +// (a dim "Vim" chip that turns it on), and the palette names what its command +// would do now. +import { expect, mock, test } from "bun:test"; +import { installEditorDom, settle } from "./editorDom"; +import type { CodeVimrcResponse } from "@codecast/shared/contracts"; + +installEditorDom(); +localStorage.clear(); + +const empty: CodeVimrcResponse = { sources: [], overlay: null }; +const realClient = { ...(await import("../../../lib/code/daemonClient")) }; +mock.module("../../../lib/code/daemonClient", () => ({ + ...realClient, + fetchVimrcText: async () => JSON.stringify(empty), +})); + +const React = await import("react"); +const { act } = React; +const { createRoot } = await import("react-dom/client"); +const { EditorView } = await import("@codemirror/view"); +const { getCM } = await import("@replit/codemirror-vim"); +const { useVaultStore } = await import("../../../store/vaultStore"); +const { codeCommandLabel } = await import("../../../lib/code/commands"); +const { editorSetting } = await import("../../../lib/code/editorSettings"); +const { CodeFileView } = await import("../CodeFileView"); + +const text = "const a = 1;\n"; +useVaultStore.setState({ + activeVaultId: "vault-1", + isRemote: false, + endpoint: { port: 1, token: "t" } as any, + files: { "src/a.ts": { path: "src/a.ts", mtime: 1, size: text.length } } as any, + bodies: { "src/a.ts": { content: text, mtime: 1, etag: "ea" } }, +}); + +const host = document.createElement("div"); +document.body.append(host); +const root = createRoot(host); +await act(async () => root.render()); +for (let i = 0; i < 10; i++) await act(settle); +const view = EditorView.findFromDOM(host.querySelector(".cm-editor") as HTMLElement)!; +const chip = () => host.querySelector(".cm-vim-mode")!; + +test("no vimrc: vim is off and the chip offers it", () => { + expect(editorSetting("vimMode")).toBe("auto"); + expect(getCM(view)).toBeNull(); + expect(chip().hidden).toBe(false); + expect(chip().textContent).toBe("Vim"); + expect(chip().dataset.mode).toBe("off"); + expect(chip().title).toBe("Turn vim on"); + expect(codeCommandLabel("vim.toggle")).toBe("Vim: turn on"); +}); + +test("clicking the chip turns vim on, and the palette's name follows", async () => { + await act(async () => chip().click()); + for (let i = 0; i < 20 && !getCM(view); i++) await act(settle); + expect(getCM(view)).not.toBeNull(); + expect(chip().textContent).toBe("NORMAL"); + expect(editorSetting("vimMode")).toBe("on"); + expect(codeCommandLabel("vim.toggle")).toBe("Vim: turn off"); + await act(async () => root.unmount()); + host.remove(); +}); diff --git a/packages/web/components/code/__tests__/workspaceFocus.mount.test.tsx b/packages/web/components/code/__tests__/workspaceFocus.mount.test.tsx new file mode 100644 index 0000000000..48fe5322b2 --- /dev/null +++ b/packages/web/components/code/__tests__/workspaceFocus.mount.test.tsx @@ -0,0 +1,147 @@ +// Focus never falls to when what held it in the workspace goes away: +// closing the only tab, or Escape on a dialog over an empty group. On +// the next Cmd-W would close the app tab instead of an editor tab. +import { expect, mock, test } from "bun:test"; +import { installEditorDom, settle } from "./editorDom"; + +installEditorDom(); +const realPanels = { ...(await import("react-resizable-panels")) }; +mock.module("react-resizable-panels", () => ({ + ...realPanels, + Group: ({ children }: { children: unknown }) => children, + Panel: ({ children }: { children: unknown }) => children, + Separator: () => null, +})); +const realConvex = { ...(await import("convex/react")) }; +mock.module("convex/react", () => ({ ...realConvex, useConvex: () => ({}) })); + +const React = await import("react"); +const { act } = React; +const { createRoot } = await import("react-dom/client"); +const { useVaultStore } = await import("../../../store/vaultStore"); +const { useCodeStore } = await import("../../../store/codeStore"); +const { codeBuffers } = await import("../../../lib/code/buffers"); +const { workspaceActions } = await import("../../../lib/code/workspace/controller"); +const { emptyWorkspace, openTab } = await import("../../../lib/code/workspace/model"); +const { runCodeCommand } = await import("../../../lib/code/commands"); +const { CodeWorkspace } = await import("../workspace/CodeWorkspace"); +await import("../CodeFileView"); + +const VAULT = "vault-ws-focus"; +for (const old of codeBuffers.all()) codeBuffers.close(old.key); +const a = "export const a = 1;\n"; +useVaultStore.setState({ + activeVaultId: VAULT, + isRemote: false, + files: { "src/a.ts": { path: "src/a.ts", mtime: 1, size: a.length } } as any, + bodies: { "src/a.ts": { content: a, mtime: 1, etag: "e1" } }, +}); +useCodeStore.setState({ dirty: {}, conflicts: {}, workspaces: { [VAULT]: openTab(emptyWorkspace(), "src/a.ts") } }); + +const host = document.createElement("div"); +document.body.append(host); +const root = createRoot(host); +const frame = () => new Promise((r) => requestAnimationFrame(() => r(null))); +const inWorkspace = () => !!document.activeElement?.closest("[data-code-workspace]"); + +test("closing the only tab keeps focus in the workspace", async () => { + await act(async () => { + root.render( + {}} onToggleTree={() => {}} renderNote={() => null} />, + ); + await settle(); + }); + const content = host.querySelector(".cm-content")!; + content.focus(); + expect(inWorkspace()).toBe(true); + await act(async () => { + workspaceActions.close(VAULT, "g1", "src/a.ts"); + await settle(); + await frame(); + }); + expect(host.querySelector(".cm-editor")).toBeNull(); + expect(document.activeElement?.hasAttribute("data-group-body")).toBe(true); +}); + +test("Escape on quick open over an empty group returns focus to the group", async () => { + await act(async () => { + runCodeCommand("quickOpen"); + await settle(); + await frame(); + }); + const input = host.querySelector('[role="dialog"] input')!; + input.focus(); + expect(document.activeElement).toBe(input); + await act(async () => { + input.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); + await settle(); + await frame(); + }); + expect(host.querySelector('[role="dialog"]')).toBeNull(); + expect(inWorkspace()).toBe(true); +}); + +test("focus moved out by the person stays out", async () => { + await act(async () => { + workspaceActions.open(VAULT, "src/a.ts"); + await settle(); + }); + host.querySelector(".cm-content")!.focus(); + const outside = document.createElement("button"); + document.body.append(outside); + outside.focus(); + outside.blur(); // then a click on nothing: , by choice + await act(async () => { + await settle(); + workspaceActions.close(VAULT, "g1", "src/a.ts"); + await settle(); + await frame(); + }); + expect(document.activeElement).toBe(document.body); + await act(async () => root.unmount()); +}); + +test("tabs are named with their state, walk by arrows, close by Delete, and the menu's verbs are commands", async () => { + const b = "export const b = 2;\n"; + useVaultStore.setState({ + files: { ...useVaultStore.getState().files, "src/b.ts": { path: "src/b.ts", mtime: 1, size: b.length } } as any, + bodies: { ...useVaultStore.getState().bodies, "src/b.ts": { content: b, mtime: 1, etag: "e2" } }, + }); + useCodeStore.setState({ workspaces: { [VAULT]: openTab(openTab(emptyWorkspace(), "src/a.ts"), "src/b.ts", { preview: true }) } }); + const again = createRoot(host); + await act(async () => { + again.render( + {}} onToggleTree={() => {}} renderNote={() => null} />, + ); + await settle(); + }); + const tabs = () => [...host.querySelectorAll("[role=tab]")]; + expect(host.querySelector("[role=tablist]")!.getAttribute("aria-label")).toBe("Editor tabs"); + expect(tabs().map((t) => t.getAttribute("aria-label"))).toEqual(["a.ts", "b.ts, preview"]); + // One Tab stop, on the active tab, which controls the group's panel. + expect(tabs().map((t) => t.tabIndex)).toEqual([-1, 0]); + expect(document.getElementById(tabs()[1].getAttribute("aria-controls")!)?.getAttribute("role")).toBe("tabpanel"); + + const key = (el: HTMLElement, k: string) => el.dispatchEvent(new KeyboardEvent("keydown", { key: k, bubbles: true })); + tabs()[1].focus(); + await act(async () => void key(tabs()[1], "ArrowLeft")); + expect(document.activeElement).toBe(tabs()[0]); + + // The menu's Pin runs tabs.pin; with no tab named, the active tab. + await act(async () => { + runCodeCommand("tabs.pin"); + await settle(); + }); + expect(useCodeStore.getState().workspaces[VAULT].groups[0].tabs.find((t) => t.path === "src/b.ts")?.pinned).toBe(true); + + const a = tabs().find((t) => t.dataset.tabPath === "src/a.ts")!; + a.focus(); + await act(async () => { + key(a, "Delete"); + await settle(); + await frame(); + }); + expect(useCodeStore.getState().workspaces[VAULT].groups[0].tabs.map((t) => t.path)).toEqual(["src/b.ts"]); + expect(inWorkspace()).toBe(true); + await act(async () => again.unmount()); +}); diff --git a/packages/web/components/code/agent/AgentLayer.tsx b/packages/web/components/code/agent/AgentLayer.tsx index 5c9cebf95e..dfc53b5ad3 100644 --- a/packages/web/components/code/agent/AgentLayer.tsx +++ b/packages/web/components/code/agent/AgentLayer.tsx @@ -15,6 +15,8 @@ import { Link2Off } from "lucide-react"; import { useInboxStore } from "../../../store/inboxStore"; import { useWatchEffect } from "../../../hooks/useWatchEffect"; import { useAgentStore } from "../../../lib/code/agent/agentStore"; +import { openBeside, sessionPanePath } from "../../../lib/stage"; +import { openConversationHere } from "../../../lib/code/blame/actions"; import { computeVaultAgentState, vaultAgentSig, vaultMachineOf } from "../../../lib/code/agent/live"; import { InlineInstruction } from "./InlineInstruction"; import { SessionMark } from "./SessionMark"; @@ -30,6 +32,7 @@ function useAgentLinking(vaultId: string, root: string | null): void { useAgentStore.getState().setLink(vaultId, { sessionId: null, source: "none" }); return; } + useAgentStore.getState().restoreOverride(vaultId); let lastSig = ""; let lastOverride: unknown = undefined; const recompute = (force: boolean) => { @@ -62,38 +65,61 @@ function useAgentLinking(vaultId: string, root: string | null): void { }, [vaultId, root]); } -/** The status bar chip: the linked session, and how many quotes wait in its - * composer. A press opens the picker. */ +/** Open the linked session's composer beside the editor, where its queued + * quotes wait in the tray. A pane that opens takes focus into its composer; + * one already beside is focused and its composer focused after. Where the + * stage has no room the conversation opens in the main view. */ +function openComposerBeside(sessionId: string): void { + if (!openBeside(sessionPanePath(sessionId))) { + openConversationHere(sessionId); + return; + } + requestAnimationFrame(() => document.querySelector(".stage-cell--focused [data-chat-input]")?.focus()); +} + +/** The status bar chip: the linked session, drawn dim while it is only the + * folder's latest (no pick, nothing beside), and how many quotes wait in its + * composer, which opens it. A press on the session opens the picker. */ const AgentChip = memo(function AgentChip({ vaultId, host, newSession }: { vaultId: string; host: HTMLElement; newSession?: () => boolean }) { const link = useAgentStore((s) => s.links[vaultId]); const id = link?.sessionId ?? null; const queued = useInboxStore((s) => (id ? (s.reviewComments[id]?.length ?? 0) : 0)); - const how = link?.source === "picked" ? "picked" : link?.source === "beside" ? "open beside" : "latest in this folder"; + const guessed = link?.source === "folder"; + const how = link?.source === "picked" ? "Picked" : link?.source === "beside" ? "Open beside" : "Latest in this folder"; return ( - + {id && queued > 0 && ( + )} - + ); }); diff --git a/packages/web/components/code/agent/SessionPicker.tsx b/packages/web/components/code/agent/SessionPicker.tsx index decadb27f8..4c9d05bfff 100644 --- a/packages/web/components/code/agent/SessionPicker.tsx +++ b/packages/web/components/code/agent/SessionPicker.tsx @@ -1,6 +1,8 @@ // The linked-session picker: the sessions working in this folder (title, // agent, state, last activity) plus None. Picking one links it to the folder // and runs whatever action was waiting on a session (Cmd-L with no link). +// The filter on top is focused on open: empty, it lists the most recent; +// typed, it searches every session in the folder by title. import { memo, useMemo, useRef, useState } from "react"; import { Ban, Plus } from "lucide-react"; @@ -12,8 +14,9 @@ import { modernDialog } from "../../ui/modernLook"; import { formatRelativeTime } from "../../../lib/conversationFormat"; import { useAgentStore, type PickerRequest } from "../../../lib/code/agent/agentStore"; import { composeInVault, placeCandidates, steerableRow, vaultAgentSig, vaultMachineOf } from "../../../lib/code/agent/live"; -import type { AgentSessionRow } from "../../../lib/code/agent/sessions"; +import { matchesSessionQuery, type AgentSessionRow } from "../../../lib/code/agent/sessions"; import { SessionMark } from "./SessionMark"; +import { usePickerAria } from "../workspace/pickerAria"; const STATE_COLOR: Record = { working: "var(--sol-green)", @@ -25,6 +28,8 @@ const STATE_COLOR: Record = { const STATE_LABEL: Record = { working: "Working", needs_input: "Needs input", done: "Done", dormant: "Dormant", idle: "Idle" }; const WIDTH = 380; +/** Sessions listed while the filter is empty, most recent first. */ +const RECENT = 12; /** The option keys of the "New session here" and "None" rows; a session row's * key is its id. */ const NEW = "\u0000new"; @@ -34,17 +39,20 @@ export const SessionPicker = memo(function SessionPicker({ request, root }: { re const { vaultId } = request; const sig = useInboxStore((s) => (root ? vaultAgentSig(s, { root, machine: vaultMachineOf(vaultId, s) }) : "")); const linked = useAgentStore((s) => s.links[vaultId]?.sessionId ?? null); + const [query, setQuery] = useState(""); + const searching = query.trim().length > 0; const rows = useMemo(() => { const s = useInboxStore.getState(); - const list: AgentSessionRow[] = root ? placeCandidates(s, { root, machine: vaultMachineOf(vaultId, s) }) : []; + const all: AgentSessionRow[] = root ? placeCandidates(s, { root, machine: vaultMachineOf(vaultId, s) }, searching ? Infinity : RECENT) : []; + const list = searching ? all.filter((r) => matchesSessionQuery(r, query)) : all; // The linked session stays listed even when it works elsewhere (beside). if (linked && !list.some((r) => r._id === linked)) { const row = steerableRow(s, linked); - if (row) list.unshift(row); + if (row && matchesSessionQuery(row, query)) list.unshift(row); } return list; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [sig, root, linked, vaultId]); + }, [sig, root, linked, vaultId, query]); const now = Date.now(); // Sessions, then "New session here", then None. Rows re-sort by activity while // the picker is open, so the selection is held by key, never by position: @@ -54,12 +62,35 @@ export const SessionPicker = memo(function SessionPicker({ request, root }: { re // A selected session that left the list highlights nothing and Enter does // nothing until an arrow picks a row again. const selected = options.indexOf(selectedKey); + const aria = usePickerAria(selected >= 0 ? selectedKey : null); const move = (by: number) => setSelectedKey(options[selected < 0 ? 0 : Math.max(0, Math.min(options.length - 1, selected + by))]); - const listRef = useRef(null); + const inputRef = useRef(null); useWatchEffect(() => { - requestAnimationFrame(() => listRef.current?.focus()); + requestAnimationFrame(() => inputRef.current?.focus()); }, []); + // A typed query puts the best match under Enter. + useWatchEffect(() => { + if (searching) setSelectedKey(rows[0]?._id ?? NEW); + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [query]); + + const onKeyDown = (e: React.KeyboardEvent) => { + e.stopPropagation(); + if (e.key === "Escape") { + e.preventDefault(); + close(); + } else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n")) { + e.preventDefault(); + move(1); + } else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p")) { + e.preventDefault(); + move(-1); + } else if (e.key === "Enter" && !e.nativeEvent.isComposing) { + e.preventDefault(); + if (selected >= 0) pick(selectedKey); + } + }; const close = () => useAgentStore.getState().closePicker(); const pick = (key: string) => { @@ -85,37 +116,29 @@ export const SessionPicker = memo(function SessionPicker({ request, root }: { re return (
e.stopPropagation()}> -
{title}
-
{ - if (e.key === "Escape") { - e.preventDefault(); - e.stopPropagation(); - close(); - } else if (e.key === "ArrowDown" || (e.ctrlKey && e.key === "n") || e.key === "j") { - e.preventDefault(); - move(1); - } else if (e.key === "ArrowUp" || (e.ctrlKey && e.key === "p") || e.key === "k") { - e.preventDefault(); - move(-1); - } else if (e.key === "Enter") { - e.preventDefault(); - if (selected >= 0) pick(selectedKey); - } - }} - > +
+ {title} + setQuery(e.target.value)} + onKeyDown={onKeyDown} + placeholder="Filter" + aria-label="Filter sessions" + {...aria.field} + spellCheck={false} + className="min-w-0 flex-1 bg-transparent text-[13px] text-sol-text outline-none placeholder:text-sol-text-dim" + /> +
+
{rows.map((r) => { const state = sessionWorkState(r as InboxSession, now); return ( ); })} - {rows.length === 0 &&
No sessions in this folder
} + {rows.length === 0 &&
{searching ? "No match" : "No sessions in this folder"}
}
+ + ↑ + ↓ move + ↵ {verb} diff --git a/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx b/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx index 09519f9592..e41e1e373d 100644 --- a/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx +++ b/packages/web/components/code/agent/__tests__/SessionPicker.mount.test.tsx @@ -46,11 +46,17 @@ async function render() { const root = createRoot(host); roots.push(root); await act(async () => root.render()); - const list = host.querySelector("[role=listbox]") as HTMLElement; - const press = (key: string) => act(() => void list.dispatchEvent(new window.KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }))); + // Keys go to the filter, which has focus while the picker is open. + const input = host.querySelector("input[aria-label='Filter sessions']") as HTMLInputElement; + const press = (key: string, opts: KeyboardEventInit = {}) => act(() => void input.dispatchEvent(new window.KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...opts }))); + const type = (text: string) => + act(() => { + Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value")!.set!.call(input, text); + input.dispatchEvent(new window.Event("input", { bubbles: true })); + }); const titles = () => [...host.querySelectorAll("[role=option]")].map((o) => o.textContent ?? ""); const highlighted = () => host.querySelector("[aria-selected=true]")?.textContent ?? ""; - return { press, titles, highlighted }; + return { press, type, titles, highlighted }; } describe("the session picker", () => { @@ -85,4 +91,23 @@ describe("the session picker", () => { expect(picked).toEqual([]); expect(useAgentStore.getState().picker).not.toBeNull(); }); + + it("typing filters every session in the folder by title, past the recent cap, and Enter takes the best match", async () => { + const many = Object.fromEntries(Array.from({ length: 20 }, (_, i) => [`s${i}`, row(`s${i}`, `Session ${i}`, 100 + i)])); + useInboxStore.setState((s) => ({ sessions: { ...s.sessions, ...many } }) as never); + const { press, type, titles, highlighted } = await render(); + // Alpha (updated 20) is past the twelve most recent. + expect(titles().some((t) => t.includes("Alpha"))).toBe(false); + type("alp"); + expect(titles().filter((t) => !/New session|None/.test(t)).map((t) => t.includes("Alpha"))).toEqual([true]); + expect(highlighted()).toContain("Alpha"); + // j and k are letters of the query, never moves. + press("j"); + expect(highlighted()).toContain("Alpha"); + press("n", { ctrlKey: true }); + expect(highlighted()).toContain("New session"); + press("p", { ctrlKey: true }); + press("Enter"); + expect(picked).toEqual(["a"]); + }); }); diff --git a/packages/web/components/code/blame/BlameHoverCard.tsx b/packages/web/components/code/blame/BlameHoverCard.tsx index 8b65d3a3b1..b2fcc4575b 100644 --- a/packages/web/components/code/blame/BlameHoverCard.tsx +++ b/packages/web/components/code/blame/BlameHoverCard.tsx @@ -2,14 +2,14 @@ // agent, when, the commit, the lines, and the ways into it. import { useState } from "react"; -import { Check, Columns2, Copy, CornerDownRight, GitCommitHorizontal } from "lucide-react"; +import { Check, Columns2, Copy, GitCommitHorizontal } from "lucide-react"; import { EntityIdPill } from "../../EntityIdPill"; import { AgentTypeIcon, formatAgentType } from "../../AgentTypeIcon"; import { Button } from "../../ui/button"; import { useInboxStore } from "../../../store/inboxStore"; import { blameViaLabel, isBlameVia } from "../../../lib/repoView"; import { copyToClipboard, formatDateFull, formatRelative } from "../../../lib/utils"; -import { openBlameMessage, openBlameSession } from "../../../lib/code/blame/actions"; +import { openBlameSession } from "../../../lib/code/blame/actions"; import { closeBlameHover, type BlameHover } from "../../../lib/code/blame/hover"; import { runName } from "../../../lib/code/blame/model"; @@ -92,19 +92,6 @@ export function BlameHoverCard({ hover }: { hover: BlameHover }) { > Open beside - {session?.message_id && ( - - )}
)}
diff --git a/packages/web/components/code/workspace/CodeWorkspace.tsx b/packages/web/components/code/workspace/CodeWorkspace.tsx index 0df1fa75a1..655b897529 100644 --- a/packages/web/components/code/workspace/CodeWorkspace.tsx +++ b/packages/web/components/code/workspace/CodeWorkspace.tsx @@ -1,5 +1,5 @@ -// The Files content area as a code workspace: up to three editor groups side -// by side (or stacked), each with its own tabs, plus quick open, the tab +// The Files content area as a code workspace: up to three editor groups in a +// two-level split (columns that stack, or rows that divide), each with its own tabs, plus quick open, the tab // switcher and the line prompt. The workspace lives in codeStore per vault // and persists across reloads; the URL's ?f= stays the address of the file in // the focused group, so links, history, Share and the app's own tabs work as @@ -11,29 +11,51 @@ import { memo, useCallback, useMemo, useRef, useState, type ReactNode } from "react"; import { useConvex } from "convex/react"; -import { Group, Panel, Separator } from "react-resizable-panels"; +import { Group, Panel, Separator, useGroupRef } from "react-resizable-panels"; import type { EditorView } from "@codemirror/view"; import { useCodeStore, workspaceFor } from "../../../store/codeStore"; import { useInboxStore } from "../../../store/inboxStore"; import { useVaultStore } from "../../../store/vaultStore"; import { useMountEffect } from "../../../hooks/useMountEffect"; +import { useDerivedSize } from "../../../hooks/useDerivedSize"; import { useWatchEffect } from "../../../hooks/useWatchEffect"; import { useTabActive } from "../../../hooks/usePagePresence"; import { usePaneShortcutAction } from "../../../shortcuts"; -import { registerCodeCommands, type CodeCommandContext } from "../../../lib/code/commands"; +import { registerCodeCommands, runCodeCommand, type CodeCommandContext, type CodeCommandId } from "../../../lib/code/commands"; import { isVirtualTab, SEARCH_RESULTS_TAB } from "../../../lib/code/workspace/virtualTabs"; import { workspaceActions as A } from "../../../lib/code/workspace/controller"; -import { groupKeyOfView, viewOfGroup } from "../../../lib/code/workspace/groupRegistry"; +import { focusGroup, groupKeyOfView, viewOfGroup } from "../../../lib/code/workspace/groupRegistry"; import { followVaultFiles, forgetFile, isFolderPath } from "../../../lib/code/workspace/followFiles"; import { peekHistory, stepHistory } from "../../../lib/code/workspace/navHistory"; import { persistWorkspaces } from "../../../lib/code/workspace/persist"; -import { MAX_GROUPS, activeGroup, groupById, mruTabs, neighborGroup, type FocusDirection, type MruEntry } from "../../../lib/code/workspace/model"; +import { registerExCompletionSource } from "../../../lib/code/vim/completionSource"; +import { + MIN_GROUP_SIZE, + activeGroup, + alternateTab, + canSplitMore, + cycleGroup, + groupById, + groupRects, + laneGroups, + lanesOf, + mruTabs, + neighborGroup, + previousGroup, + type FocusDirection, + type GroupEdge, + type MruEntry, + type SplitDirection, + type Workspace, + type WsGroup, +} from "../../../lib/code/workspace/model"; import { EditorGroup } from "./EditorGroup"; import { QuickOpen } from "./QuickOpen"; import { TabSwitcher } from "./TabSwitcher"; import { GotoLine } from "./GotoLine"; import type { TabMenuAction } from "./TabBar"; import { resolveVaultPath } from "../../../lib/code/vaultPath"; +import { filesHref, navigateToFiles } from "../../../lib/vault/vaultHref"; import { AgentLayer } from "../agent/AgentLayer"; let persisting = false; @@ -45,6 +67,16 @@ function startPersistence(): void { let instances = 0; +/** What a group with tabs gets for its recent list: the same empty array + * every render, so a tab change elsewhere leaves it alone. */ +const NO_RECENT: readonly string[] = []; + +/** The real file the focused group shows, if any. */ +const activeOf = (ws: Parameters[0]): string | null => { + const path = activeGroup(ws).active; + return path && !isVirtualTab(path) ? path : null; +}; + // A hairline between groups with a wider grab area, lit while dragged. // One status bar for the workspace: every group keeps the bar's row, so the // editors end on one line, but only the focused group draws its items. A @@ -59,9 +91,47 @@ const separatorClass = { "relative z-10 h-px bg-sol-border/50 before:absolute before:inset-x-0 before:-top-[2px] before:-bottom-[2px] before:content-[''] before:transition-colors before:duration-150 hover:before:bg-sol-cyan data-[resize-handle-active]:before:bg-sol-cyan", }; +/** The smallest a group may be, in px: a tab, the breadcrumbs and a status + * row still fit, and a few lines of code under them. */ +const MIN_GROUP_PX = { width: 260, height: 160 } as const; +/** Size changes smaller than this re-render nothing. */ +const SIZE_QUANTUM = 20; + +/** A group's minimum share of a split `px` long holding `n` groups: the pixel + * floor as a percentage, never more than an equal share, so it can always + * be met (a pixel minimum the pane cannot meet livelocks the panel library). */ +export function minShare(px: number, n: number, floor: number): number { + if (!px) return MIN_GROUP_SIZE; + return Math.min(100 / n - 0.5, Math.max(MIN_GROUP_SIZE, (floor / px) * 100)); +} + +/** Whether `groupId` has room to split in `dir`: under the group limit, and + * each half at least the pixel floor (an unmeasured workspace has room). */ +export function roomToSplit(ws: Workspace, groupId: string, dir: SplitDirection, size: { w: number; h: number }): boolean { + if (!canSplitMore(ws)) return false; + const r = groupRects(ws).get(groupId); + if (!r) return false; + const [len, floor] = dir === "right" ? [r.w * size.w, MIN_GROUP_PX.width] : [r.h * size.h, MIN_GROUP_PX.height]; + return !len || len / 2 >= floor; +} + +/** What each item of a tab's menu runs. */ +const TAB_MENU_COMMANDS: Record?]> = { + close: ["file.close"], + closeOthers: ["file.closeOthers"], + closeRight: ["tabs.closeRight"], + pin: ["tabs.pin"], + keep: ["tabs.keep"], + splitRight: ["split.right"], + copyPath: ["file.copyPath"], + copyRelative: ["file.copyPath", { relative: true }], + reveal: ["file.reveal"], +}; + type Overlay = | { kind: "quickOpen"; query?: string } | { kind: "switcher"; held: boolean } + | { kind: "groupTabs"; groupId: string } | { kind: "gotoLine"; line: number; lines: number } | null; @@ -90,8 +160,17 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro const rootRef = useRef(null); const [overlay, setOverlay] = useState(null); const tabActive = useTabActive(); - const live = useRef({ props, ws, tabActive, convex }); - live.current = { props, ws, tabActive, convex }; + const sizeKey = useDerivedSize( + rootRef, + (w, h) => `${Math.round(w / SIZE_QUANTUM) * SIZE_QUANTUM}x${Math.round(h / SIZE_QUANTUM) * SIZE_QUANTUM}`, + () => "0x0", + ); + const size = useMemo(() => { + const [w, h] = sizeKey.split("x").map(Number); + return { w, h }; + }, [sizeKey]); + const live = useRef({ props, ws, tabActive, convex, size }); + live.current = { props, ws, tabActive, convex, size }; // page.tsx keys this component by vault, so `vaultId` is fixed for its life // and every verb below may close over it. @@ -184,6 +263,24 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro [instance], ); + /** The tab a tab verb acts on: the one a tab's menu names (args.group is + * the group's key, `:`), else the active tab of the + * command's group. Null when the command belongs to another workspace. */ + const tabFor = (args: Record | undefined, ctx: CodeCommandContext | undefined): { group: WsGroup; path: string } | null => { + const key = typeof args?.group === "string" ? args.group : null; + if (key && !key.startsWith(`${instance}:`)) return null; + const group = groupById(live.current.ws, key ? key.slice(instance.length + 1) : groupFor(ctx)); + const path = typeof args?.path === "string" ? args.path : group?.active; + return group && path && group.tabs.some((t) => t.path === path) ? { group, path } : null; + }; + + /** Split a group, when it has room; false (vim's E36) when it has none. */ + const split = (groupId: string, path: string, dir: SplitDirection, opts?: { at?: string; preview?: boolean }) => { + if (!roomToSplit(live.current.ws, groupId, dir, live.current.size)) return false; + A.split(vaultId, groupId, path, dir, opts); + return true; + }; + const copy = (text: string) => void navigator.clipboard?.writeText(text).catch(() => {}); const absolute = (path: string) => (live.current.props.vaultRoot ? `${live.current.props.vaultRoot.replace(/\/$/, "")}/${path}` : path); @@ -209,6 +306,16 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro return !!target; }; + /** Run a layout verb with the command's group focused; false when the + * command came from another workspace. */ + const onGroup = (ctx: CodeCommandContext | undefined, verb: () => void) => { + const g = groupFor(ctx); + if (!g) return false; + A.focusGroup(vaultId, g); + verb(); + }; + const axisOf = (args: Record | undefined) => (args?.axis === "height" ? "height" : "width"); + const showGotoLine = () => { const key = `${instance}:${live.current.ws.activeGroup}`; const view = viewOfGroup(key) as EditorView | null; @@ -235,6 +342,17 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro else terms.openTerminal({ endpoint, kind: "shell", cwd: root }); }; + // The `:` line's Tab completion reads this folder's files and tabs. + useMountEffect(() => + registerExCompletionSource((view) => { + if (!groupKeyOfView(view)?.startsWith(`${instance}:`)) return null; + return { + files: () => useVaultStore.getState().files, + tabs: () => [...new Set(mruTabs(live.current.ws).map((e) => e.path))].filter((p) => !isVirtualTab(p)), + }; + }), + ); + useMountEffect(() => registerCodeCommands({ // The results editor is a tab: brought forward where it is open, else @@ -252,35 +370,57 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro const { path } = resolved; const line = typeof args?.line === "number" ? args.line : undefined; const at = line ? (typeof args?.column === "number" ? `${line}:${args.column}` : `${line}`) : undefined; - const split = args?.split === "right" || args?.split === "down" ? args.split : null; - if (split) A.split(vaultId, g, path, split, { at }); - else A.open(vaultId, path, { groupId: g, at }); + const splitDir = args?.split === "right" || args?.split === "down" ? args.split : null; + if (splitDir) return split(g, path, splitDir, { at }); + A.open(vaultId, path, { groupId: g, at }); }, - "file.close": (_a, ctx) => { - const g = groupFor(ctx); - const group = groupById(live.current.ws, g); - if (!group?.active) return false; - A.close(vaultId, group.id, group.active); + "file.close": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.close(vaultId, t.group.id, t.path); }, - "file.closeOthers": (_a, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; - A.closeOthers(vaultId, group.id, group.active); + "file.closeOthers": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.closeOthers(vaultId, t.group.id, t.path); + }, + "tabs.closeRight": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.closeToRight(vaultId, t.group.id, t.path); + }, + "tabs.pin": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.pin(vaultId, t.group.id, t.path); + }, + "tabs.keep": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + A.keepOpen(vaultId, t.group.id, t.path); }, "file.reopenClosed": (_a, ctx) => { if (!groupFor(ctx) || !live.current.ws.closed.length) return false; A.reopen(vaultId); }, "file.copyPath": (args, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; - copy(args?.relative ? group.active : absolute(group.active)); + const t = tabFor(args, ctx); + if (!t || isVirtualTab(t.path)) return false; + copy(args?.relative ? t.path : absolute(t.path)); }, - "file.reveal": (_a, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; + "file.reveal": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t || isVirtualTab(t.path)) return false; live.current.props.onToggleTree(true); - useVaultStore.getState().requestReveal(group.active); + useVaultStore.getState().requestReveal(t.path); + }, + // The breadcrumbs take focus at the file's own crumb; arrows walk them + // and Escape comes back (CodeFileBar). + "breadcrumbs.focus": (_a, ctx) => { + const g = groupFor(ctx); + const crumb = g && rootRef.current?.querySelector(`[data-code-group="${g}"] [data-crumbs] [aria-current]`); + if (!crumb) return false; + crumb.focus(); }, quickOpen: (args, ctx) => { if (!groupFor(ctx)) return false; @@ -316,15 +456,15 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro }, "nav.back": (_a, ctx) => navStep(ctx, -1), "nav.forward": (_a, ctx) => navStep(ctx, 1), - "split.right": (_a, ctx) => { - const group = groupById(live.current.ws, groupFor(ctx)); - if (!group?.active) return false; - A.split(vaultId, group.id, group.active, "right"); + "split.right": (args, ctx) => { + const t = tabFor(args, ctx); + if (!t) return false; + return split(t.group.id, t.path, "right"); }, "split.down": (_a, ctx) => { const group = groupById(live.current.ws, groupFor(ctx)); if (!group?.active) return false; - A.split(vaultId, group.id, group.active, "down"); + return split(group.id, group.active, "down"); }, "split.close": (_a, ctx) => { const g = groupFor(ctx); @@ -336,6 +476,36 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro if (!g) return false; A.only(vaultId, g); }, + "tabs.alternate": (_a, ctx) => { + const g = groupFor(ctx); + if (!g) return false; + A.focusGroup(vaultId, g); + const alt = alternateTab(live.current.ws); + if (!alt) return false; + A.activate(vaultId, alt.groupId, alt.path); + }, + // Window commands act on the group the command came from. + "split.equalize": (_a, ctx) => onGroup(ctx, () => A.equalize(vaultId)), + "split.maximize": (args, ctx) => onGroup(ctx, () => A.maximize(vaultId, axisOf(args))), + "split.resize": (args, ctx) => onGroup(ctx, () => A.resize(vaultId, axisOf(args), typeof args?.by === "number" ? args.by : 1)), + "split.exchange": (_a, ctx) => onGroup(ctx, () => A.exchange(vaultId)), + "split.rotate": (args, ctx) => onGroup(ctx, () => A.rotate(vaultId, args?.delta === -1 ? -1 : 1)), + "split.moveToEdge": (args, ctx) => onGroup(ctx, () => A.moveToEdge(vaultId, (args?.edge as GroupEdge) ?? "left")), + "focus.previous": (_a, ctx) => { + if (!groupFor(ctx)) return false; + const target = previousGroup(live.current.ws); + if (target) A.focusGroup(vaultId, target); + return !!target; + }, + "focus.cycle": (args, ctx) => { + const g = groupFor(ctx); + if (!g) return false; + A.focusGroup(vaultId, g); + const w = live.current.ws; + const target = args?.to === "first" ? w.groups[0].id : args?.to === "last" ? w.groups[w.groups.length - 1].id : cycleGroup(w, args?.delta === -1 ? -1 : 1); + if (target) A.focusGroup(vaultId, target); + return !!target; + }, "focus.left": (_a, ctx) => !!groupFor(ctx) && focusDir("left"), "focus.right": (_a, ctx) => !!groupFor(ctx) && focusDir("right"), "focus.up": (_a, ctx) => !!groupFor(ctx) && focusDir("up"), @@ -376,8 +546,16 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro return !!surface && !!rootRef.current && surface.contains(rootRef.current); }; usePaneShortcutAction("code.closeTab", () => { - const group = activeGroup(live.current.ws); - if (!surfaceHasFocus() || !group.active) return false; + const w = live.current.ws; + const group = activeGroup(w); + if (!surfaceHasFocus()) return false; + // An empty group in a split closes, as in Zed; the last one leaves the + // press to the app. + if (!group.active) { + if (w.groups.length < 2) return false; + A.closeGroup(vaultId, group.id); + return true; + } A.close(vaultId, group.id, group.active); return true; }); @@ -388,39 +566,19 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro }); usePaneShortcutAction("code.splitRight", () => { const group = activeGroup(live.current.ws); - if (!group.active || live.current.ws.groups.length >= MAX_GROUPS) return false; - A.split(vaultId, group.id, group.active, "right"); - return true; + return !!group.active && split(group.id, group.active, "right"); }); // ── render ──────────────────────────────────────────────────────────────── + // A tab's menu runs the same commands the palette and the keys do, on the + // tab it was opened on. const onMenu = useCallback( (groupId: string, action: TabMenuAction, path: string) => { - switch (action) { - case "close": - return A.close(vaultId, groupId, path); - case "closeOthers": - return A.closeOthers(vaultId, groupId, path); - case "closeRight": - return A.closeToRight(vaultId, groupId, path); - case "pin": - return A.pin(vaultId, groupId, path); - case "keep": - return A.keepOpen(vaultId, groupId, path); - case "splitRight": - return A.split(vaultId, groupId, path, "right"); - case "copyPath": - return copy(absolute(path)); - case "copyRelative": - return copy(path); - case "reveal": - live.current.props.onToggleTree(true); - return useVaultStore.getState().requestReveal(path); - } + const [id, extra] = TAB_MENU_COMMANDS[action]; + runCodeCommand(id, { ...extra, group: `${instance}:${groupId}`, path }, { source: "menu" }); }, - // eslint-disable-next-line react-hooks/exhaustive-deps - [vaultId], + [instance], ); const handlers = useMemo( () => ({ @@ -428,11 +586,13 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro onActivate: (g: string, p: string) => A.activate(vaultId, g, p), onClose: (g: string, p: string) => A.close(vaultId, g, p), onKeep: (g: string, p: string) => A.keepOpen(vaultId, g, p), + onOpen: (g: string, p: string) => A.open(vaultId, p, { groupId: g, preview: true }), onMove: (from: string, p: string, to: string, i: number) => A.move(vaultId, from, p, to, i), onSplit: (g: string) => { const group = groupById(live.current.ws, g); - if (group?.active) A.split(vaultId, g, group.active, "right"); + if (group?.active) split(g, group.active, "right"); }, + onListTabs: (g: string) => setOverlay({ kind: "groupTabs", groupId: g }), }), [vaultId], ); @@ -446,21 +606,79 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro return out; }, [ws]); - const closeOverlay = useCallback(() => { - setOverlay(null); - const view = viewOfGroup(`${instance}:${live.current.ws.activeGroup}`) as EditorView | null; - requestAnimationFrame(() => view?.focus()); - }, [instance]); + const closeOverlay = useCallback(() => setOverlay(null), []); + + // Focus that was in the workspace stays in it when what held it goes away: + // a tab or a group closing by any route (Cmd-W, :q, the close button, a + // file deleted on disk), or a dialog closing. It lands on the focused + // group's editor, else on the group's body, never on , where the + // next Cmd-W would close the app tab. + const lastFocus = useRef(null); + useMountEffect(() => { + const root = rootRef.current; + if (!root) return; + const onIn = (e: FocusEvent) => void (lastFocus.current = e.target as Element); + // Focus the person moved out (a click elsewhere) is theirs; only focus + // whose element was removed comes back. + const onOut = (e: FocusEvent) => { + const el = e.target as Element; + queueMicrotask(() => { + if (el.isConnected && lastFocus.current === el && !root.contains(document.activeElement)) lastFocus.current = null; + }); + }; + root.addEventListener("focusin", onIn); + root.addEventListener("focusout", onOut); + return () => { + root.removeEventListener("focusin", onIn); + root.removeEventListener("focusout", onOut); + }; + }); + useWatchEffect(() => { + const raf = requestAnimationFrame(() => { + const was = lastFocus.current; + const now = document.activeElement; + if (!was || was.isConnected || (now && now !== document.body)) return; + focusGroup(`${instance}:${live.current.ws.activeGroup}`); + }); + return () => cancelAnimationFrame(raf); + }, [ws, overlay]); const horizontal = ws.orientation === "horizontal"; const groups = ws.groups; const multi = groups.length > 1; - const canSplit = groups.length < MAX_GROUPS; - const layout = useMemo(() => { - const sizes = ws.sizes && ws.sizes.length === groups.length ? ws.sizes : groups.map(() => 100 / groups.length); - return Object.fromEntries(groups.map((g, i) => [g.id, sizes[i]])); - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [groups.map((g) => g.id).join(","), ws.orientation]); + const lanes = lanesOf(ws); + const blocks = useMemo(() => laneGroups(ws), [ws]); + const rects = useMemo(() => groupRects(ws), [ws]); + // Each split's minimum share: its pixel floor over its own length. Lanes + // run along the outer axis; the groups in a lane across it. + const outerPx = horizontal ? size.w : size.h; + const innerPx = horizontal ? size.h : size.w; + const outerFloor = horizontal ? MIN_GROUP_PX.width : MIN_GROUP_PX.height; + const innerFloor = horizontal ? MIN_GROUP_PX.height : MIN_GROUP_PX.width; + const outerOrientation = horizontal ? "horizontal" : "vertical"; + const innerOrientation = horizontal ? "vertical" : "horizontal"; + + const renderGroup = (g: WsGroup) => { + const r = rects.get(g.id); + const top = !r || r.y < 1e-6; + return ( + 1 - 1e-6)} + canSplit={roomToSplit(ws, g.id, "right", size)} + groupNumber={groupNumbers?.get(g.id)} + recent={g.tabs.length ? NO_RECENT : recent} + deepLinking={!!props.deepLinking} + renderNote={renderNote} + onMenu={onMenu} + {...handlers} + /> + ); + }; const groupNumbers = useMemo(() => (multi ? new Map(groups.map((g, i) => [g.id, i + 1])) : null), [groups, multi]); @@ -482,35 +700,31 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro > - { - if (multi) A.sizes(vaultId, groups.map((g) => l[g.id] ?? 0)); - }} + `lane:${b[0].id}`)} + sizes={ws.sizes} + minSize={minShare(outerPx, blocks.length, outerFloor)} + onSizes={(sizes) => A.sizes(vaultId, null, sizes)} > - {groups.map((g, i) => ( - 0 ? (horizontal ? "horizontal" : "vertical") : null}> - - - ))} - + {(laneId, li) => ( + g.id)} + sizes={lanes[li]?.sizes ?? null} + minSize={minShare(innerPx, blocks[li].length, innerFloor)} + onSizes={(sizes) => A.sizes(vaultId, li, sizes)} + > + {(_id, gi) => renderGroup(blocks[li][gi])} + + )} + {overlay?.kind === "quickOpen" && ( { + onOpen={(path, at, toSide) => { setOverlay(null); const group = activeGroup(live.current.ws); - if (split) A.split(vaultId, group.id, path, "right", { at, preview: true }); - else A.open(vaultId, path, { preview: true, at }); + // No room beside it: the file opens here. + if (!(toSide && split(group.id, path, "right", { at, preview: true }))) A.open(vaultId, path, { preview: true, at }); + }} + onSymbols={(scope, query) => { + setOverlay(null); + // Once the dialog is gone and focus is back in the editor (contract 9). + setTimeout(() => runCodeCommand(scope === "file" ? "goto.symbol" : "goto.workspaceSymbol", { query }, { source: "palette" }), 0); + }} + onOpenLocal={(localPath, at) => { + setOverlay(null); + navigateToFiles(filesHref({ localPath, line: at })); }} /> )} @@ -540,6 +763,17 @@ export const CodeWorkspace = memo(function CodeWorkspace(props: CodeWorkspacePro }} /> )} + {overlay?.kind === "groupTabs" && ( + { + setOverlay(null); + A.activate(vaultId, e.groupId, e.path); + }} + /> + )} {overlay?.kind === "gotoLine" && ( (group ? group.tabs.map((t) => ({ groupId: group.id, path: t.path })) : []), [group]); + const pinned = useMemo(() => new Set(group?.tabs.filter((t) => t.pinned).map((t) => t.path)), [group]); + if (!group || !entries.length) return null; + return ( + e.path === group.active))} + pinned={pinned} + onClose={onClose} + onPick={onPick} + /> + ); +} + +/** One run of a split: panels along one axis with hairlines between them. + * Sizes set by a command (=, _, 5<) reach the panels here; a + * drag already shows its sizes and comes back equal, so it sets nothing. */ +function SplitRun({ + orientation, + ids, + sizes, + minSize, + onSizes, + children, +}: { + orientation: "horizontal" | "vertical"; + ids: string[]; + sizes: number[] | null; + /** Percent, so it can always be met. */ + minSize: number; + onSizes(sizes: number[]): void; + children(id: string, index: number): ReactNode; +}) { + const key = ids.join(","); + const want = sizes && sizes.length === ids.length ? sizes : ids.map(() => 100 / ids.length); + // eslint-disable-next-line react-hooks/exhaustive-deps + const defaultLayout = useMemo(() => Object.fromEntries(ids.map((id, i) => [id, want[i]])), [key]); + const groupRef = useGroupRef(); + const live = useRef({ ids, onSizes }); + live.current = { ids, onSizes }; + useWatchEffect(() => { + const handle = groupRef.current; + if (!handle || ids.length < 2) return; + const have = handle.getLayout(); + if (ids.every((id, i) => Math.abs((have[id] ?? 0) - want[i]) < 0.5)) return; + handle.setLayout(Object.fromEntries(ids.map((id, i) => [id, want[i]]))); + }, [want.join(","), key]); + return ( + { + const { ids: now, onSizes: emit } = live.current; + if (now.length > 1) emit(now.map((id) => l[id] ?? 0)); + }} + > + {ids.map((id, i) => ( + 0 ? orientation : null} minSize={minSize}> + {children(id, i)} + + ))} + + ); +} + +function SplitPanel({ id, separator, minSize, children }: { id: string; separator: "horizontal" | "vertical" | null; minSize: number; children: ReactNode }) { return ( <> {separator && } - {/* A percentage minimum can always be met; a pixel one in a pane too - narrow for it livelocks the panel library (see app/files/page.tsx). */} - + {children} diff --git a/packages/web/components/code/workspace/EditorGroup.tsx b/packages/web/components/code/workspace/EditorGroup.tsx index 5a48f9149c..ec79d7203d 100644 --- a/packages/web/components/code/workspace/EditorGroup.tsx +++ b/packages/web/components/code/workspace/EditorGroup.tsx @@ -5,11 +5,14 @@ // editor (docs/architecture/code-editor.md, contract 2). import { memo, useMemo, useRef, useState, type ReactNode } from "react"; -import { FolderTree } from "lucide-react"; +import { File, FileText } from "lucide-react"; import { isVaultMarkdownPath } from "@codecast/shared/contracts"; import { VaultFileView } from "../../vault/VaultFileView"; import { KeyCap } from "../../KeyCap"; import { useShortcutParts } from "../../../shortcuts"; +import type { ShortcutAction } from "../../../shortcuts/registry"; +import { useVaultStore } from "../../../store/vaultStore"; +import { runCodeCommand } from "../../../lib/code/commands"; import { CodeGroupContext } from "./groupContext"; import { TabBar, type TabMenuAction } from "./TabBar"; import { isDraggingTab, takeTabDrag } from "../../../lib/code/workspace/tabDrag"; @@ -20,6 +23,9 @@ import { SearchResultsTab } from "../search/SearchResultsEditorHost"; /** Tabs whose saved cursor was already put back this page load. */ const restored = new Set(); +/** How many recent files an empty group lists. */ +const EMPTY_RECENT = 8; + export interface EditorGroupProps { instance: string; vaultId: string; @@ -28,33 +34,76 @@ export interface EditorGroupProps { leftInset: boolean; rightInset: boolean; canSplit: boolean; + /** Its number among the groups, when there are several. */ + groupNumber?: number; + /** Files opened lately, for the group while it has no tab. */ + recent: readonly string[]; + /** A deep link is resolving into this workspace: an empty group stays blank + * rather than flash its choices before the file lands. */ + deepLinking: boolean; renderNote(path: string, line: string | null): ReactNode; onFocusGroup(groupId: string): void; onActivate(groupId: string, path: string): void; + onOpen(groupId: string, path: string): void; onClose(groupId: string, path: string): void; onKeep(groupId: string, path: string): void; onMove(fromGroupId: string, path: string, toGroupId: string, toIndex: number): void; onMenu(groupId: string, action: TabMenuAction, path: string): void; onSplit(groupId: string): void; + onListTabs(groupId: string): void; } -function EmptyGroup() { - const keys = useShortcutParts("code.quickOpen"); +/** A key hint that is also the button: name, then its keys. */ +function KeyAction({ label, action, onClick }: { label: string; action: ShortcutAction; onClick(): void }) { + const keys = useShortcutParts(action); return ( -
- + + ); +} + +/** A group with no tab: the files opened lately, one click each, and the two + * ways to find another. */ +function EmptyGroup({ recent, onOpen }: { recent: readonly string[]; onOpen(path: string): void }) { + // Only files still on disk; a string, so a watcher event re-renders nothing. + const present = useVaultStore((s) => recent.filter((p) => s.files[p]).slice(0, EMPTY_RECENT).join("\n")); + const rows = present ? present.split("\n") : []; + return ( +
+ {rows.length > 0 && ( +
+ {rows.map((p) => { + const slash = p.lastIndexOf("/"); + const Icon = isVaultMarkdownPath(p) ? FileText : File; + return ( + + ); + })}
)} +
+ runCodeCommand("quickOpen")} /> + runCodeCommand("search.project", {})} /> +
); } @@ -67,14 +116,19 @@ export const EditorGroup = memo(function EditorGroup({ leftInset, rightInset, canSplit, + groupNumber, + recent, + deepLinking, renderNote, onFocusGroup, onActivate, + onOpen, onClose, onKeep, onMove, onMenu, onSplit, + onListTabs, }: EditorGroupProps) { const ctx = useMemo(() => ({ key: `${instance}:${group.id}`, groupId: group.id, active: focused }), [instance, group.id, focused]); const [dropping, setDropping] = useState(false); @@ -87,7 +141,8 @@ export const EditorGroup = memo(function EditorGroup({ const restore = useRef<{ path: string | null; at: string | null }>({ path: null, at: null }); if (restore.current.path !== path) { const key = `${vaultId}\u0000${path}`; - const saved = path && tab?.cursor && !restored.has(key) ? `${tab.cursor.line}:${tab.cursor.col}` : null; + const c = tab?.cursor; + const saved = path && c && !restored.has(key) ? `${c.line}:${c.col}${c.top ? `@${c.top}` : ""}` : null; if (path) restored.add(key); restore.current = { path, at: saved }; } @@ -111,19 +166,23 @@ export const EditorGroup = memo(function EditorGroup({ leftInset={leftInset} rightInset={rightInset} canSplit={canSplit} + groupNumber={groupNumber} onActivate={onActivate} onClose={onClose} onKeep={onKeep} onMove={onMove} onMenu={onMenu} onSplit={onSplit} + onListTabs={onListTabs} /> {/* Focusable, so a press on a group with no editor in it (a missing file, an empty group) keeps focus in the workspace and Cmd-W closes the editor tab, not the app tab. */}
{ if (!isDraggingTab()) return; @@ -142,7 +201,7 @@ export const EditorGroup = memo(function EditorGroup({ }} > {!path ? ( - + deepLinking ? null : onOpen(group.id, p)} /> ) : path === SEARCH_RESULTS_TAB ? ( onClose(group.id, path)} /> ) : isVaultMarkdownPath(path) ? ( diff --git a/packages/web/components/code/workspace/FileStateMark.tsx b/packages/web/components/code/workspace/FileStateMark.tsx new file mode 100644 index 0000000000..672f08dbae --- /dev/null +++ b/packages/web/components/code/workspace/FileStateMark.tsx @@ -0,0 +1,42 @@ +// What a file needs from the person, marked where it is listed (a tab, the +// tab switcher, quick open's open files): unsaved edits, or a state its strip +// holds (changed on disk, a merge, deleted, read-only, a save that failed or +// waits on the daemon). The same mark everywhere, so a background tab says +// which file wants attention without opening it. +import { conflictTone, type CodeConflict } from "../../../store/codeStore"; + +const WORD: Record = { + stale: "changed on disk", + merge: "merging", + deleted: "deleted on disk", + readonly: "read-only on disk", + offline: "not saved, reconnecting", + error: "save failed", +}; + +/** The words a list row's label adds for this state, or null for none. */ +export function fileStateWords(conflict: CodeConflict | undefined, dirty: boolean): string | null { + if (conflict?.kind === "merge" && conflict.conflicts > 0) return `${conflict.conflicts} ${conflict.conflicts === 1 ? "conflict" : "conflicts"}`; + if (conflict) return WORD[conflict.kind]; + return dirty ? "unsaved" : null; +} + +/** A deleted file's name is struck through where it is listed. */ +export const deletedNameClass = (conflict: CodeConflict | undefined) => (conflict?.kind === "deleted" ? "line-through opacity-60" : ""); + +/** The dot in the slot a dirty file's dot takes; a merge with conflicts shows + * their count. Nothing for a clean file with nothing pending. */ +export function FileStateMark({ conflict, dirty, className = "" }: { conflict: CodeConflict | undefined; dirty: boolean; className?: string }) { + const tone = conflictTone(conflict); + const words = fileStateWords(conflict, dirty); + if (!words) return null; + const color = tone === "alarm" ? "bg-sol-red" : tone === "warn" ? "bg-sol-yellow" : "bg-sol-text-muted"; + if (conflict?.kind === "merge" && conflict.conflicts > 0) { + return ( + + {conflict.conflicts} + + ); + } + return ; +} diff --git a/packages/web/components/code/workspace/QuickOpen.tsx b/packages/web/components/code/workspace/QuickOpen.tsx index afcb61c8de..d1ecb3b4b2 100644 --- a/packages/web/components/code/workspace/QuickOpen.tsx +++ b/packages/web/components/code/workspace/QuickOpen.tsx @@ -1,9 +1,12 @@ // Quick open (Cmd-P, vim's CtrlP / :Files / Telescope find_files): every file -// in the vault, fuzzy matched, recent files first. `name:42` or `name:42:5` -// opens at the line; a bare `:42` goes to the line in the current file. +// in the vault, fuzzy matched, recent files first, then files near the one +// being edited. `dir name` narrows by folder. A pasted location opens where it +// points (`name:42:5`, `path:L42-50`, `#L42`, `(42,5)`, an absolute path, a +// diff's `a/` path); a bare `:42` goes to the line in the current file. // Enter opens in a preview tab, Cmd-Enter in a split. A file with unsaved // edits carries the tab's dirty dot, closed tab or not. +import { FileStateMark } from "./FileStateMark"; import { memo, useMemo, useRef, useState } from "react"; import { Clock, File, FileText } from "lucide-react"; import { isVaultMarkdownPath } from "@codecast/shared/contracts"; @@ -15,15 +18,25 @@ import { isMac } from "../../../shortcuts"; import { hoverFocus } from "../../../shortcuts/focusSource"; import { modernDialog, modernScrim } from "../../ui/modernLook"; import { useGroupAnchor } from "./groupAnchor"; -import { parseQuickOpenQuery, quickOpenIndex, rankFiles } from "../../../lib/code/workspace/quickOpen"; +import { usePickerAria } from "./pickerAria"; +import { parseQuickOpenQuery, queryAt, targetAt, quickOpenIndex, rankFiles } from "../../../lib/code/workspace/quickOpen"; export interface QuickOpenProps { vaultId: string; + /** The vault's absolute root, for pasted absolute paths. */ + root: string | null; + /** The file being edited, which nearby files rank around. */ + activePath: string | null; initialQuery?: string; /** Files opened lately in this workspace, most recent first. */ recent: string[]; onOpen(path: string, at: string | undefined, split: boolean): void; + /** An absolute path outside this folder. */ + onOpenLocal(absPath: string, at: string | undefined): void; onGotoLine(at: string): void; + /** `@name` (this file's symbols) or `#name` (the project's): the symbol + * picker takes over with the rest as its filter. */ + onSymbols(scope: "file" | "project", query: string): void; onClose(): void; } @@ -50,19 +63,32 @@ function Marked({ text, indexes, offset = 0 }: { text: string; indexes: readonly return <>{out}; } -export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", recent, onOpen, onGotoLine, onClose }: QuickOpenProps) { +export const QuickOpen = memo(function QuickOpen({ vaultId, root, activePath, initialQuery = "", recent, onOpen, onOpenLocal, onGotoLine, onSymbols, onClose }: QuickOpenProps) { // The index is the same array while the vault names the same files, so a // save or a watcher event re-renders nothing here. const targets = useVaultStore((s) => quickOpenIndex(s.files)); const dirty = useCodeStore((s) => s.dirty); + const conflicts = useCodeStore((s) => s.conflicts); const [query, setQuery] = useState(initialQuery); const [selected, setSelected] = useState(0); const inputRef = useRef(null); const listRef = useRef(null); - const parsed = useMemo(() => parseQuickOpenQuery(query), [query]); - const results = useMemo(() => rankFiles(targets, parsed.text, recent), [targets, parsed.text, recent]); - const at = parsed.line ? (parsed.column ? `${parsed.line}:${parsed.column}` : `${parsed.line}`) : undefined; + const parsed = useMemo(() => { + const files = useVaultStore.getState().files; + return parseQuickOpenQuery(query, { root, isFile: (p) => !!files[p] && !files[p].dir }); + }, [query, root]); + // An exact path is the answer, ahead of anything fuzzy. + const exact = parsed.text ? targetAt(targets, parsed.text) : undefined; + const results = useMemo( + () => (parsed.outside ? [] : exact ? [{ target: exact, nameIndexes: null, pathIndexes: null, score: 2 }] : rankFiles(targets, parsed.text, recent, { activePath })), + [targets, parsed.text, parsed.outside, exact, recent, activePath], + ); + const at = queryAt(parsed); const gotoOnly = !parsed.text && !!parsed.line; + // A path the scan does not list (ignored, generated, past the cap) still + // opens by name: the file view asks the daemon for it. One outside this + // folder opens through Files' local-path link. + const openTyped = results.length === 0 && (parsed.outside || parsed.text.includes("/")) ? parsed.text : null; useWatchEffect(() => { requestAnimationFrame(() => inputRef.current?.select()); @@ -73,6 +99,7 @@ export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", r const activate = (i: number, split: boolean) => { if (gotoOnly) return onGotoLine(at!); + if (openTyped) return parsed.outside ? onOpenLocal(openTyped, at) : onOpen(openTyped, at, split); const r = results[i]; if (r) onOpen(r.target.path, at, split); }; @@ -94,6 +121,7 @@ export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", r }; const recentSet = useMemo(() => new Set(recent), [recent]); + const aria = usePickerAria(gotoOnly ? null : openTyped ? "typed" : results.length ? selected : null); const anchor = useGroupAnchor(620); return ( @@ -113,17 +141,20 @@ export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", r ref={inputRef} value={query} onChange={(e) => { - setQuery(e.target.value); + const v = e.target.value; + if (v.startsWith("@") || v.startsWith("#")) return onSymbols(v[0] === "@" ? "file" : "project", v.slice(1)); + setQuery(v); setSelected(0); }} onKeyDown={onKeyDown} + {...aria.field} placeholder="Go to file" aria-label="File name, or name:line" className="w-full border-b border-sol-border/30 bg-transparent px-4 py-2.5 text-sm text-sol-text outline-none placeholder:text-sol-text-dim" spellCheck={false} autoComplete="off" /> -
+
{gotoOnly ? (
Line {at} @@ -138,6 +169,8 @@ export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", r key={t.path} type="button" data-row={i} + {...aria.option(i, i === selected)} + tabIndex={-1} onClick={(e) => activate(i, e.metaKey || e.ctrlKey)} {...hoverFocus(() => setSelected(i))} className={`flex w-full items-center gap-2.5 px-4 py-1 text-left text-[13px] ${i === selected ? "bg-sol-bg-highlight text-sol-text" : "text-sol-text-muted"}`} @@ -148,18 +181,36 @@ export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", r {t.dir && ( - + )} {at && i === selected && :{at}} - {dirty[bufferKey(vaultId, t.path)] && } + ); }) )} - {!gotoOnly && results.length === 0 &&
No matching files
} + {openTyped ? ( + + ) : ( + !gotoOnly && results.length === 0 &&
No match
+ )}
@@ -172,6 +223,12 @@ export const QuickOpen = memo(function QuickOpen({ vaultId, initialQuery = "", r : line + + @ symbol + + + # project +
diff --git a/packages/web/components/code/workspace/TabBar.tsx b/packages/web/components/code/workspace/TabBar.tsx index e7b5ea344b..9759ab3b91 100644 --- a/packages/web/components/code/workspace/TabBar.tsx +++ b/packages/web/components/code/workspace/TabBar.tsx @@ -3,8 +3,10 @@ // at the left with a pin and no close button. A dirty tab shows a dot where // its close button is, and the button on hover. Middle click closes; tabs drag // to reorder and between groups; the strip scrolls sideways with the active -// tab kept in view. +// tab kept in view. Pinned tabs stay put at the left, outside the scroll, and +// a count of the tabs scrolled out of view opens the group's tab list. +import { FileStateMark, deletedNameClass, fileStateWords } from "./FileStateMark"; import { memo, useMemo, useRef, useState } from "react"; import { File, FileStack, FileText, Image as ImageIcon, Pin, SquareSplitHorizontal, X } from "lucide-react"; import { isVaultAssetPath, isVaultMarkdownPath } from "@codecast/shared/contracts"; @@ -16,6 +18,8 @@ import { ContextMenu, CtxItem, CtxSeparator, useContextMenu } from "../../ui/con import { withShortcut } from "../../../shortcuts"; import type { WsGroup, WsTab } from "../../../lib/code/workspace/model"; import { PresenceDot } from "../agent/PresenceDot"; +import { focusGroup } from "../../../lib/code/workspace/groupRegistry"; +import { useCodeGroup } from "./groupContext"; import { endTabDrag, isDraggingTab, startTabDrag, takeTabDrag } from "../../../lib/code/workspace/tabDrag"; const DRAG_TYPE = "application/x-codecast-tab"; @@ -28,6 +32,8 @@ export interface TabBarProps { leftInset: boolean; rightInset: boolean; canSplit: boolean; + /** Its number among the groups, when there are several. */ + groupNumber?: number; /** Each takes the group, so one stable set serves every group. */ onActivate(groupId: string, path: string): void; onClose(groupId: string, path: string): void; @@ -35,6 +41,8 @@ export interface TabBarProps { onMove(fromGroupId: string, path: string, toGroupId: string, toIndex: number): void; onMenu(groupId: string, action: TabMenuAction, path: string): void; onSplit(groupId: string): void; + /** List this group's tabs (the strip hides some). */ + onListTabs(groupId: string): void; } /** A tab's handlers: one object per strip that never changes, so a tab @@ -43,7 +51,9 @@ interface TabEvents { activate(path: string): void; close(path: string): void; keep(path: string): void; - context(e: React.MouseEvent, path: string): void; + context(e: React.MouseEvent | React.KeyboardEvent, path: string): void; + /** Back to the group's editor (a press on a tab leaves focus there). */ + focusView(): void; dragStart(e: React.DragEvent, path: string): void; dragOver(e: React.DragEvent, path: string): void; drop(e: React.DragEvent, path: string): void; @@ -64,10 +74,31 @@ const nameOf = (path: string) => (isVirtualTab(path) ? virtualTabTitle(path) : p /** Width of the fade over a clipped edge of the strip. */ const FADE_PX = 28; -/** Fade whichever edges hide tabs. */ -function paintClip(strip: HTMLElement): void { +/** A name's tail that stays whole when the name is cut: its extension, with a + * test or spec marker before it. */ +const NAME_TAIL = /(?:\.(?:test|spec|stories|mount\.test|d))?\.[^.]+$/; + +/** Fade whichever edges hide tabs, and count the tabs not wholly in view. */ +function paintClip(strip: HTMLElement, chip: HTMLElement | null): void { const left = strip.scrollLeft > 1; const right = strip.scrollLeft + strip.clientWidth < strip.scrollWidth - 1; + if (chip) { + let hidden = 0; + if (left || right) { + const from = strip.scrollLeft; + const to = from + strip.clientWidth; + for (const el of strip.children) { + const t = el as HTMLElement; + if (t.dataset.tabPath && (t.offsetLeft < from - 1 || t.offsetLeft + t.offsetWidth > to + 1)) hidden++; + } + } + const label = hidden ? `+${hidden}` : ""; + if (chip.textContent !== label) { + chip.textContent = label; + chip.setAttribute("aria-label", `${hidden} more tabs`); + } + chip.hidden = !hidden; + } const clip = left && right ? "both" : left ? "left" : right ? "right" : ""; if ((strip.dataset.clip ?? "") === clip) return; if (clip) strip.dataset.clip = clip; @@ -89,6 +120,18 @@ function revealTab(strip: HTMLElement, tab: HTMLElement): void { else if (end + (last ? 0 : FADE_PX) > strip.scrollLeft + strip.clientWidth) strip.scrollLeft = last ? strip.scrollWidth : end + FADE_PX - strip.clientWidth; } +/** The name, at most 22ch: the middle goes, the extension stays. */ +function TabName({ name, italic, className = "" }: { name: string; italic: boolean; className?: string }) { + const tail = NAME_TAIL.exec(name)?.[0] ?? ""; + const stem = tail && tail.length < name.length ? name.slice(0, -tail.length) : name; + return ( + + {stem} + {stem !== name && {tail}} + + ); +} + const Tab = memo(function Tab({ vaultId, tab, @@ -96,9 +139,11 @@ const Tab = memo(function Tab({ focused, duplicateName, dropBefore, + panelId, events, }: { vaultId: string; + panelId: string; tab: WsTab; active: boolean; focused: boolean; @@ -107,17 +152,33 @@ const Tab = memo(function Tab({ events: TabEvents; }) { const dirty = useCodeStore((s) => !!s.dirty[bufferKey(vaultId, tab.path)]); + const conflict = useCodeStore((s) => s.conflicts[bufferKey(vaultId, tab.path)]); const isNew = useIsNewFile(bufferKey(vaultId, tab.path)); const name = nameOf(tab.path); const dir = duplicateName ? tab.path.slice(0, Math.max(0, tab.path.length - name.length - 1)).split("/").pop() : null; + const state = fileStateWords(conflict, dirty); + // Anything pending holds the close button's slot, as a dirty dot does. + const marked = !!state; + const label = [dir ? `${name} (${dir})` : name, state, tab.pinned && "pinned", tab.preview && "preview", isNew && "new file"].filter(Boolean).join(", "); + const pressed = useRef(false); return (
void (pressed.current = true)} + // A press focuses the editor, as in Zed; only keys stop on the tab. + onFocus={() => { + if (pressed.current) events.focusView(); + pressed.current = false; + }} onMouseDown={(e) => { if (e.button === 0) events.activate(tab.path); }} @@ -133,7 +194,7 @@ const Tab = memo(function Tab({ onDragOver={(e) => events.dragOver(e, tab.path)} onDrop={(e) => events.drop(e, tab.path)} onDragEnd={endTabDrag} - className={`group/tab relative flex h-full shrink-0 cursor-default select-none items-center gap-1.5 border-r border-sol-border/30 pl-2.5 pr-1 text-meta transition-colors ${ + className={`group/tab relative flex h-full shrink-0 cursor-default select-none items-center gap-1.5 border-r border-sol-border/30 pl-2.5 pr-1 text-meta outline-none transition-colors focus-visible:ring-1 focus-visible:ring-inset focus-visible:ring-sol-cyan ${ active ? "bg-sol-bg text-sol-text" : "text-sol-text-dim hover:bg-sol-bg/50 hover:text-sol-text-muted" }`} > @@ -141,11 +202,11 @@ const Tab = memo(function Tab({ {active && } {dropBefore && } {tab.pinned ? : tabIcon(tab.path)} - {name} + {dir && {dir}} - {isNew && new} + {isNew && new} {!isVirtualTab(tab.path) && } - {tab.pinned && !dirty ? ( + {tab.pinned && !marked ? ( ) : ( )}
@@ -174,14 +235,19 @@ export const TabBar = memo(function TabBar({ leftInset, rightInset, canSplit, + groupNumber, onActivate, onClose, onKeep, onMove, onMenu, onSplit, + onListTabs, }: TabBarProps) { + const groupCtx = useCodeGroup(); + const groupKey = groupCtx?.key ?? group.id; const stripRef = useRef(null); + const chipRef = useRef(null); const [dropAt, setDropAt] = useState(null); const menu = useContextMenu(); @@ -194,7 +260,7 @@ export const TabBar = memo(function TabBar({ const el = [...tabs].find((t) => t.dataset.tabPath === group.active); const reveal = () => { if (el) revealTab(strip, el); - paintClip(strip); + paintClip(strip, chipRef.current); }; reveal(); // The tab can grow after it is shown (its "new" or dirty mark arriving). @@ -208,7 +274,7 @@ export const TabBar = memo(function TabBar({ useWatchEffect(() => { const strip = stripRef.current; if (!strip) return; - const paint = () => paintClip(strip); + const paint = () => paintClip(strip, chipRef.current); paint(); strip.addEventListener("scroll", paint, { passive: true }); const ro = typeof ResizeObserver === "function" ? new ResizeObserver(paint) : null; @@ -239,14 +305,36 @@ export const TabBar = memo(function TabBar({ if (d) onMove(d.groupId, d.path, group.id, index); }; - const latest = useRef({ group, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }); - latest.current = { group, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }; + const pinned = group.tabs.filter((t) => t.pinned); + const rest = pinned.length ? group.tabs.filter((t) => !t.pinned) : group.tabs; + const tabProps = (t: WsTab) => ({ + vaultId, + tab: t, + active: t.path === group.active, + focused, + duplicateName: (names.get(nameOf(t.path)) ?? 0) > 1, + dropBefore: dropAt === indexOf(t.path), + panelId: `${groupKey}:panel`, + }); + + const latest = useRef({ group, groupKey, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }); + latest.current = { group, groupKey, accept, drop, dropIndex, menu, onActivate, onClose, onKeep }; const events = useMemo( () => ({ activate: (path) => latest.current.onActivate(latest.current.group.id, path), close: (path) => latest.current.onClose(latest.current.group.id, path), keep: (path) => latest.current.onKeep(latest.current.group.id, path), - context: (e, path) => latest.current.menu.open(e, path, { force: true }), + context: (e, path) => { + // From the keyboard (Shift-F10, the menu key) the menu opens under + // the tab; a click opens it at the pointer. + if ("key" in e || (e.clientX === 0 && e.clientY === 0)) { + e.preventDefault(); + const r = (e.currentTarget as HTMLElement).getBoundingClientRect(); + return latest.current.menu.openAt(r.left, r.bottom + 2, path); + } + latest.current.menu.open(e, path, { force: true }); + }, + focusView: () => focusGroup(latest.current.groupKey), dragStart: (e, path) => { startTabDrag({ groupId: latest.current.group.id, path }); e.dataTransfer.effectAllowed = "move"; @@ -269,8 +357,40 @@ export const TabBar = memo(function TabBar({ return (
{ + const el = e.target as HTMLElement; + const path = el.getAttribute("role") === "tab" ? el.dataset.tabPath : undefined; + if (!path) return; + const tabs = [...e.currentTarget.querySelectorAll("[role=tab]")]; + const i = tabs.indexOf(el); + const to = (j: number) => tabs[(j + tabs.length) % tabs.length]?.focus(); + if (e.key === "ArrowRight") to(i + 1); + else if (e.key === "ArrowLeft") to(i - 1); + else if (e.key === "Home") to(0); + else if (e.key === "End") to(tabs.length - 1); + else if (e.key === "Enter" || e.key === " ") { + onActivate(group.id, path); + requestAnimationFrame(() => focusGroup(groupKey)); + } else if (e.key === "Escape") focusGroup(groupKey); + else if (e.key === "Delete" || e.key === "Backspace") { + onClose(group.id, path); + // Focus stays in the strip, on the tab that took its place. + requestAnimationFrame(() => stripRef.current?.parentElement?.querySelector("[role=tab][tabindex='0']")?.focus()); + } else if (e.key === "ContextMenu" || (e.key === "F10" && e.shiftKey)) events.context(e, path); + else return; + e.preventDefault(); + e.stopPropagation(); + }} className={`flex h-8 shrink-0 items-stretch border-b border-sol-border/30 bg-sol-bg-alt/50 ${leftInset ? "pl-9" : ""} ${rightInset ? "pr-9" : ""}`} > + {pinned.length > 0 && ( +
+ {pinned.map((t) => ( + + ))} +
+ )}
- {group.tabs.map((t, i) => ( - 1} - dropBefore={dropAt === i} - events={events} - /> + {rest.map((t) => ( + ))} {dropAt === group.tabs.length && }
+ {/* Filled in by paintClip; React never renders the count. */} + ); diff --git a/packages/web/components/code/workspace/__tests__/splitRoom.test.ts b/packages/web/components/code/workspace/__tests__/splitRoom.test.ts new file mode 100644 index 0000000000..4e7e8694e1 --- /dev/null +++ b/packages/web/components/code/workspace/__tests__/splitRoom.test.ts @@ -0,0 +1,26 @@ +import { expect, test } from "bun:test"; +import { minShare, roomToSplit } from "../CodeWorkspace"; +import { emptyWorkspace, openTab, splitTo } from "../../../../lib/code/workspace/model"; + +test("the pixel floor becomes a share that can always be met", () => { + // 260 px of a 900 px stage leaf. + expect(Math.round(minShare(900, 2, 260))).toBe(29); + // Three groups in a narrow pane: an equal share at most, so it never livelocks. + expect(minShare(500, 3, 260)).toBeLessThan(100 / 3); + // Wide or unmeasured: the old 12% minimum. + expect(minShare(4000, 2, 260)).toBe(12); + expect(minShare(0, 2, 260)).toBe(12); +}); + +test("a split needs both halves above the floor, and refuses at three groups", () => { + let ws = openTab(emptyWorkspace(), "a"); + expect(roomToSplit(ws, "g1", "right", { w: 900, h: 700 })).toBe(true); + expect(roomToSplit(ws, "g1", "right", { w: 480, h: 700 })).toBe(false); + ws = splitTo(ws, "g1", "b", "right"); + // 450 px each in a 900 px leaf: no third column, but room to stack. + expect(roomToSplit(ws, "g2", "right", { w: 900, h: 700 })).toBe(false); + expect(roomToSplit(ws, "g2", "down", { w: 900, h: 700 })).toBe(true); + ws = splitTo(ws, "g2", "c", "down"); + expect(roomToSplit(ws, "g1", "right", { w: 4000, h: 4000 })).toBe(false); + expect(roomToSplit(openTab(emptyWorkspace(), "a"), "g1", "right", { w: 0, h: 0 })).toBe(true); +}); diff --git a/packages/web/components/code/workspace/pickerAria.ts b/packages/web/components/code/workspace/pickerAria.ts new file mode 100644 index 0000000000..37c52a5346 --- /dev/null +++ b/packages/web/components/code/workspace/pickerAria.ts @@ -0,0 +1,21 @@ +// The listbox pattern every editor picker shares (quick open, the tab +// switcher, the session picker): focus stays on one control (a filter field, +// or the list itself), the arrows move a highlight, and aria-activedescendant +// names the highlighted row, so a screen reader hears each step. + +import { useId } from "react"; + +export function usePickerAria(selected: string | number | null) { + const id = useId(); + const listId = `${id}list`; + // Keys may hold characters an id should not (a NUL-prefixed sentinel). + const optionId = (key: string | number) => `${id}o${String(key).replace(/[^\w-]/g, "_")}`; + const active = selected == null ? undefined : optionId(selected); + return { + /** For the filter field that keeps focus while the arrows move. */ + field: { role: "combobox" as const, "aria-controls": listId, "aria-expanded": true, "aria-autocomplete": "list" as const, "aria-activedescendant": active }, + /** For the list; with no field, the list holds focus itself. */ + list: (focusable = false) => ({ id: listId, role: "listbox" as const, ...(focusable ? { tabIndex: -1, "aria-activedescendant": active } : {}) }), + option: (key: string | number, isSelected: boolean) => ({ id: optionId(key), role: "option" as const, "aria-selected": isSelected }), + }; +} diff --git a/packages/web/components/conversation/blocks/toolBlocks.tsx b/packages/web/components/conversation/blocks/toolBlocks.tsx index be86cf91fa..45d98a734e 100644 --- a/packages/web/components/conversation/blocks/toolBlocks.tsx +++ b/packages/web/components/conversation/blocks/toolBlocks.tsx @@ -813,14 +813,13 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti const startLine = getStartLine(); // Where the card's "Open in editor" lands: the lines a Read read, the lines - // an Edit wrote (flashed on arrival), the top of a written file, a patch's + // an Edit wrote (flashed on arrival, and found again by their text when the + // file has moved under them since), the top of a written file, a patch's // first file at its first hunk. A deleted file has nothing to open. const editorTarget = useMemo(() => { if (isApplyPatch) { const first = applyPatchDiffs.find((d) => d.operation !== "Delete"); - if (!first) return null; - const at = first.hunks.find((h) => h.newStart > 0)?.newStart; - return { path: first.filePath, ...(at ? { line: at } : {}) }; + return first ? patchSectionTarget(first) : null; } if (!filePath || (!isStandardEdit && !isMultiEdit && !isRead)) return null; if (isRead) { @@ -833,7 +832,7 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti const range = result && !result.is_error ? editedLineRange(safeString(result.content), newTexts[0]) : undefined; // A result with no line numbers (MultiEdit's "Applied N edits") leaves the // editor to find the edit's new text in the file once it shows. - return { path: filePath, ...(range ?? (newTexts.length ? { find: newTexts } : {})) }; + return { path: filePath, ...range, ...(newTexts.length ? { find: newTexts } : {}) }; }, [isApplyPatch, applyPatchDiffs, filePath, isStandardEdit, isMultiEdit, isRead, parsedInput, tool.name, result]); const toolColor = toolColorClass(isApplyPatch ? "apply_patch" : tool.name); @@ -920,7 +919,8 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti )} {editorTarget && ( - + // An edit opens with what it replaced peeked inline at its lines. + )} {browserTab && } {gitOutcome && } @@ -1092,8 +1092,11 @@ export function ToolBlock({ tool, result, changeIndex, changeRange, shareSelecti const diffStartLine = diff.hunks[0]?.oldStart || diff.hunks[0]?.newStart || 1; return (
0 ? "border-t border-sol-border/20" : ""}> -
- {getRelativePath(diff.filePath)} +
+ {getRelativePath(diff.filePath)} + {isApplyPatch && "operation" in diff && diff.operation !== "Delete" && ( + + )}
}): { path: string; line?: number } { + const at = section.hunks.find((h) => h.newStart > 0)?.newStart; + return { path: section.filePath, ...(at ? { line: at } : {}) }; +} diff --git a/packages/web/components/pr/PRThread.tsx b/packages/web/components/pr/PRThread.tsx index cc4316c52c..1a5121c6b6 100644 --- a/packages/web/components/pr/PRThread.tsx +++ b/packages/web/components/pr/PRThread.tsx @@ -193,7 +193,10 @@ export function PRLineThread({ linkHref, onSelectLines, placement, + editAction, }: { + /** Opens the thread's lines in this machine's checkout, where there is one. */ + editAction?: ReactNode; /** Where the thread's passage is now, when it moved or is gone. */ placement?: AnchorPlacement | null; /** The address of the lines this thread is on, and selecting them. */ @@ -257,6 +260,7 @@ export function PRLineThread({
{span}
))} + {editAction} {noteMode && onNoteMode && (comments.length === 0 || replying) && ( )} diff --git a/packages/web/components/repo/BlobContent.tsx b/packages/web/components/repo/BlobContent.tsx index ea6fdd0464..de34d87c30 100644 --- a/packages/web/components/repo/BlobContent.tsx +++ b/packages/web/components/repo/BlobContent.tsx @@ -18,11 +18,8 @@ import { BlobView } from "./BlobView"; import { useCodeComments, useSyncFileCodeComments } from "../../hooks/useSyncCodeComments"; import { useAttributedSession, useLineComments } from "../../hooks/useLineComments"; import { useEventListener } from "../../hooks/useEventListener"; -import { useRepoBlame, useRepoBlameSessions, useRepoBlob, useRepoLog, useRepoWorktrees } from "../../hooks/useRepoBrowse"; -import { localCheckoutFile } from "../../lib/filesPane"; -import { OpenInEditorButton } from "../OpenInEditorButton"; -import { useInboxStore } from "../../store/inboxStore"; -import { localDeviceIdOf } from "../../hooks/useLocalDeviceId"; +import { useRepoBlame, useRepoBlameSessions, useRepoBlob, useRepoLog } from "../../hooks/useRepoBrowse"; +import { LocalEditButton } from "./LocalEditButton"; import { useWatchEffect } from "../../hooks/useWatchEffect"; import { serverCommentId, type CodeCommentRow } from "../../lib/prView"; import { @@ -304,22 +301,6 @@ export function BlobContent({ ); } -// "Open in editor": the same file at the same line in this machine's own -// checkout of the repository, when it has one. -function LocalEditButton({ repository, refName, path, line }: { repository: string; refName: string; path: string; line?: number }) { - const checkouts = useRepoWorktrees(repository).data?.checkouts; - const deviceId = useInboxStore(localDeviceIdOf); - const local = checkouts ? localCheckoutFile(checkouts, deviceId, refName, path) : null; - if (!local) return null; - return ( - - ); -} - function CommentedBlobView({ repository, path, anchorRef, content, selection, selectLine, blameRanges, blameMode, sessionRanges, sessionColors, focusSession }: { repository: string; path: string; anchorRef: string; content: string; selection: LineRange | null; selectLine: (line: number, extend: boolean) => void; diff --git a/packages/web/components/repo/LocalEditButton.tsx b/packages/web/components/repo/LocalEditButton.tsx new file mode 100644 index 0000000000..ca3b636932 --- /dev/null +++ b/packages/web/components/repo/LocalEditButton.tsx @@ -0,0 +1,84 @@ +"use client"; + +// "Open in editor" from a repository surface (a blob page, a pull request's +// files, a commit, a comparison): the same file in this machine's own checkout +// of the repository, in the code editor, optionally with the editor's diff +// against the ref the surface compares with. Not drawn when this machine has +// no checkout of the repository. + +import { useCallback, useMemo } from "react"; +import { useRepoWorktrees } from "../../hooks/useRepoBrowse"; +import { useInboxStore } from "../../store/inboxStore"; +import { localDeviceIdOf } from "../../hooks/useLocalDeviceId"; +import { firstChangedLine, localCheckout, type OpenInEditorOptions } from "../../lib/filesPane"; +import { OpenInEditorButton } from "../OpenInEditorButton"; +import type { DiffFile } from "../FileDiffLayout"; + +type DiffAgainst = NonNullable; + +/** This machine's checkout of `repository` on `refName` (localCheckout), once + * the published checkouts have arrived. */ +function useLocalCheckout(repository: string, refName: string) { + const checkouts = useRepoWorktrees(repository).data?.checkouts; + const deviceId = useInboxStore(localDeviceIdOf); + return checkouts ? localCheckout(checkouts, deviceId, refName) : null; +} + +const join = (root: string, path: string) => `${root}/${path.replace(/^\/+/, "")}`; + +export function LocalEditButton({ repository, refName, path, line }: { repository: string; refName: string; path: string; line?: number }) { + const local = useLocalCheckout(repository, refName); + if (!local) return null; + return ( + + ); +} + +/** + * The per-file "Edit" a repository diff (FileDiffLayout's `fileAction`) puts in + * each file header: the file in this machine's checkout at its first changed + * line, with the editor's diff against `diffAgainst` when the checkout holds + * the revision the page shows (`diffFor` decides from the checkout, null for + * the file alone). A removed file has nothing to open. Undefined when this + * machine has no checkout, so the headers carry nothing. + */ +export function useLocalEditAction( + repository: string, + refName: string, + diffFor: (checkout: { onRef: boolean; head?: string }) => DiffAgainst | null, +): ((filename: string, file: DiffFile) => React.ReactNode) | undefined { + const local = useLocalCheckout(repository, refName); + const diff = local ? diffFor(local) : null; + const root = local?.root; + const diffKey = diff ? `${diff.ref}\n${diff.label ?? ""}` : ""; + const action = useCallback( + (_original: string, file: DiffFile) => + !root || file.status === "removed" || file.status === "deleted" ? null : ( + // The file's current name: a renamed file lives under its new one. + + ), + // diff is keyed by its content: diffFor builds a new object every render. + // eslint-disable-next-line react-hooks/exhaustive-deps + [root, diffKey], + ); + return root ? action : undefined; +} + +/** + * The Edit a review thread carries: the lines it is about, in this machine's + * checkout of `refName`, so a person answers a note by fixing the line. + * Undefined unless a worktree here is on `refName`: in any other tree the + * thread's line numbers name different lines. + */ +export function useLocalEditAt(repository: string, refName: string): ((path: string, line: number, endLine?: number) => React.ReactNode) | undefined { + const local = useLocalCheckout(repository, refName); + const root = local?.onRef ? local.root : undefined; + return useMemo( + () => (root ? (path: string, line: number, endLine?: number) => : undefined), + [root], + ); +} diff --git a/packages/web/components/repo/RepoCompareContent.tsx b/packages/web/components/repo/RepoCompareContent.tsx index dacdf08f6b..97db465e04 100644 --- a/packages/web/components/repo/RepoCompareContent.tsx +++ b/packages/web/components/repo/RepoCompareContent.tsx @@ -7,6 +7,7 @@ import { useRepoCompare } from "../../hooks/useRepoBrowse"; import { commitPageHref, repoCompareHref, type RepoRouteFamily } from "../../lib/repoView"; import { serverErrorText } from "../../lib/errorCause"; import { useDiffAddress } from "../../hooks/useDiffAddress"; +import { useLocalEditAction } from "./LocalEditButton"; export function RepoCompareContent({ repository, base, head, family }: { repository: string; base: string; head: string; family: RepoRouteFamily; @@ -19,6 +20,9 @@ export function RepoCompareContent({ repository, base, head, family }: { const rootRef = useRef(null); const diffHref = useCallback((hash: string) => repoCompareHref(repository, base, head, family) + hash, [repository, base, head, family]); const { flow } = useDiffAddress({ diffHref, here: true, ready: files.length > 0, rootRef, stickyTop: 0 }); + // Each file's "Edit": the file in this machine's checkout of the head, with + // the editor's diff against the base, when a worktree sits on the head. + const editAction = useLocalEditAction(repository, head, (c) => (c.onRef ? { ref: base, label: base } : null)); return
{ event.preventDefault(); const fields = new FormData(event.currentTarget); @@ -49,7 +53,7 @@ export function RepoCompareContent({ repository, base, head, family }: { {commit.author_login || commit.author_name} )} } - {files.length ? :

No file changes between these refs.

} + {files.length ? :

No file changes between these refs.

} }
; } diff --git a/packages/web/components/repo/__tests__/localEditAt.mount.test.tsx b/packages/web/components/repo/__tests__/localEditAt.mount.test.tsx new file mode 100644 index 0000000000..48a67042bf --- /dev/null +++ b/packages/web/components/repo/__tests__/localEditAt.mount.test.tsx @@ -0,0 +1,63 @@ +import { afterAll, describe, expect, mock, test } from "bun:test"; +import { JSDOM } from "jsdom"; +import { replaceGlobals } from "../../../test-helpers/globals"; +import { closeDomWindow } from "../../../test-helpers/domGlobals"; + +// A pull request review thread's Edit opens its lines in this machine's +// worktree on the head branch. Only there: a checkout on another branch has +// different lines at those numbers, so the thread carries no Edit. + +const dom = new JSDOM("", { url: "http://localhost/", pretendToBeVisual: true }); +const restoreGlobals = replaceGlobals({ + window: dom.window, + document: dom.window.document, + navigator: dom.window.navigator, + HTMLElement: dom.window.HTMLElement, + Element: dom.window.Element, + Node: dom.window.Node, + IS_REACT_ACT_ENVIRONMENT: true, +}); +afterAll(() => { + closeDomWindow(dom); + restoreGlobals(); +}); + +let worktrees: Array<{ path: string; branch?: string; main?: boolean }> = []; +mock.module("../../../hooks/useRepoBrowse", () => ({ + useRepoWorktrees: () => ({ data: { checkouts: [{ root: "/src/app", device_id: "dev-1", worktrees }] } }), +})); +mock.module("../../OpenInEditorButton", () => ({ + OpenInEditorButton: ({ target }: { target: { path: string; line?: number } }) => , +})); + +const { act } = await import("react"); +const { createRoot } = await import("react-dom/client"); +const { useLocalEditAt } = await import("../LocalEditButton"); +const { useInboxStore } = await import("../../../store/inboxStore"); +useInboxStore.setState({ localDevice: { viewer: "u1", deviceId: "dev-1" }, currentUser: { _id: "u1" } } as never); + +function Thread() { + const editAt = useLocalEditAt("ada/app", "feature"); + return
{editAt ? editAt("lib/x.ts", 12) : "none"}
; +} + +async function render() { + const host = dom.window.document.createElement("div"); + const root = createRoot(host); + await act(async () => root.render()); + const out = host.querySelector("[data-target]")?.getAttribute("data-target") ?? host.textContent; + await act(async () => root.unmount()); + return out; +} + +describe("review thread Edit", () => { + test("opens the line in the worktree on the head branch", async () => { + worktrees = [{ path: "/src/app", branch: "main", main: true }, { path: "/src/app-feature", branch: "feature" }]; + expect(await render()).toBe("/src/app-feature/lib/x.ts:12"); + }); + + test("no worktree on the head branch, no Edit", async () => { + worktrees = [{ path: "/src/app", branch: "main", main: true }]; + expect(await render()).toBe("none"); + }); +}); diff --git a/packages/web/components/stage/StageSplitView.tsx b/packages/web/components/stage/StageSplitView.tsx index 772b1aef5d..7caa151c11 100644 --- a/packages/web/components/stage/StageSplitView.tsx +++ b/packages/web/components/stage/StageSplitView.tsx @@ -27,7 +27,7 @@ import { type StageNode, } from "../../store/stageSplit"; import { StageRail } from "./StageRail"; -import { paneSessionId, stageClose, stageExpand, stageFocus, stageNavigateLeaf, startPaneDrag } from "../../lib/stage"; +import { stageLeafSession, stageClose, stageExpand, stageFocus, stageNavigateLeaf, startPaneDrag } from "../../lib/stage"; import { pathLabel } from "../../lib/pathLabel"; import { browserPathLabel, isBrowserRoutePath, subscribeBrowserTitles } from "../../lib/browserPane"; import { isSimulatorRoutePath } from "../../lib/simulatorPane"; @@ -151,7 +151,8 @@ const StageCell = memo(function StageCell({ solo: boolean; rail: "left" | "right" | null; }) { - const sessionId = paneSessionId(path); + const leafSession = stageLeafSession(path); + const sessionId = leafSession?.sessionId ?? null; const title = usePaneTitle(path); const restore = useCallback(() => { useInboxStore.getState().setStageWide(null); @@ -192,7 +193,7 @@ const StageCell = memo(function StageCell({ expand, so the drag handle is a grip that surfaces on hover. */} {!solo && } - + ) : ownsHeader ? ( diff --git a/packages/web/components/tasks/TaskInlineThread.tsx b/packages/web/components/tasks/TaskInlineThread.tsx index 5fe03a7aec..ef1eef708c 100644 --- a/packages/web/components/tasks/TaskInlineThread.tsx +++ b/packages/web/components/tasks/TaskInlineThread.tsx @@ -8,6 +8,7 @@ // reconciles exactly as it does on the task page. import type { ReactNode } from "react"; +import { FilePathContext, useFolderPathContext } from "../../lib/filePathLinks"; import { useSyncTaskDetail, useTaskComments } from "../../hooks/useSyncTasks"; import { useTaskRow } from "../../hooks/useThreadPreviews"; import { TaskCommentStream, type TaskOwnerRef } from "./TaskCommentStream"; @@ -28,8 +29,10 @@ export function TaskInlineThread({ taskId, newSince, focusComposer = false, owne const task = useTaskRow(taskId); const comments = useTaskComments(taskId); const desc = (task?.description ?? "").trim(); + // A path the description or a comment cites is relative to the task's project. + const fileCtx = useFolderPathContext(task?.project_path); return ( - <> + {desc && (
Description @@ -38,6 +41,6 @@ export function TaskInlineThread({ taskId, newSince, focusComposer = false, owne )} {children} - + ); } diff --git a/packages/web/components/terminal/ConversationTerminal.tsx b/packages/web/components/terminal/ConversationTerminal.tsx index d2db01bc67..793f5dd80e 100644 --- a/packages/web/components/terminal/ConversationTerminal.tsx +++ b/packages/web/components/terminal/ConversationTerminal.tsx @@ -166,6 +166,7 @@ function SplitBody({ convKey, split, tmuxSession }: { convKey: string; split: Sp target, title: target, detached: true, + conversationId: convKey, // Interactive, same as a manual `tmux attach` — the pill is just the // safe version of it (ignore-size, no nesting). interactive: true, diff --git a/packages/web/components/ui/LoadingBar.tsx b/packages/web/components/ui/LoadingBar.tsx new file mode 100644 index 0000000000..d5cca6da02 --- /dev/null +++ b/packages/web/components/ui/LoadingBar.tsx @@ -0,0 +1,11 @@ +// A 2px sweep along the top edge of whatever is loading: says "on its way" +// without moving anything below it. Position it with `className` (it fills +// its parent's width); the label is for screen readers and text queries. +export function LoadingBar({ className = "" }: { className?: string }) { + return ( +
+ Loading +
+
+ ); +} diff --git a/packages/web/components/vault/FileUnavailable.tsx b/packages/web/components/vault/FileUnavailable.tsx new file mode 100644 index 0000000000..fa36c3970d --- /dev/null +++ b/packages/web/components/vault/FileUnavailable.tsx @@ -0,0 +1,112 @@ +// What a file's body area shows when it cannot show the file: too large, a +// type with no preview, a read that failed, a daemon still out of reach. An +// icon, a short title, one dim fact (a size, a status), and the actions that +// get past it: Retry when trying again can help, Reveal when this machine +// holds the file. Shared by the vault views and the code editor's loading +// state, so every dead end on Files has the same shape and a way out. + +import { useState, type ReactNode } from "react"; +import { RotateCw, WifiOff } from "lucide-react"; +import { useWatchEffect } from "../../hooks/useWatchEffect"; +import { LoadingBar } from "../ui/LoadingBar"; +import { useVaultStore } from "../../store/vaultStore"; +import { fileManagerName } from "../../lib/vault/reveal"; +import { RevealButton } from "./VaultFileHeader"; +import { buttonVariants } from "../ui/button"; + +const actionClass = buttonVariants({ variant: "outline", size: "xs" }); + +export function FileUnavailable({ + path, + icon, + title, + detail, + onRetry, +}: { + path: string; + icon: ReactNode; + title: string; + detail?: string; + onRetry?: () => void; +}) { + const canReveal = useVaultStore((s) => !!s.endpoint && !s.isRemote); + return ( +
+ {icon} +
{title}
+ {detail &&
{detail}
} + {(onRetry || canReveal) && ( +
+ {onRetry && ( + + )} + {canReveal && ( + + Show in {fileManagerName()} + + )} +
+ )} +
+ ); +} + +/** How long a read waits on a reconnecting daemon before saying so. */ +export const FILE_STALL_MS = 4000; + +/** True once `waiting` has held for FILE_STALL_MS for the same `key`; the + * second value starts the wait over (a Retry). */ +export function useStalled(waiting: boolean, key: string): [boolean, () => void] { + const [stalled, setStalled] = useState(null); + const [attempt, setAttempt] = useState(0); + useWatchEffect(() => { + if (!waiting) return; + const t = setTimeout(() => setStalled(key), FILE_STALL_MS); + return () => clearTimeout(t); + }, [waiting, key, attempt]); + const retry = () => { + setStalled(null); + setAttempt((n) => n + 1); + }; + return [waiting && stalled === key, retry]; +} + +/** The daemon is being reached and the file cannot be read yet. */ +export function DaemonReconnecting({ path, onRetry }: { path: string; onRetry?: () => void }) { + return ( + } + title="Couldn't read" + detail="Daemon reconnecting" + onRetry={() => { + onRetry?.(); + void useVaultStore.getState().reconnect(); + }} + /> + ); +} + +/** A link to a file (`/files?path=`) while its folder is being resolved: the + * file it names, loading, never whatever the last vault had open. Past the + * stall with the daemon out of reach, the reconnecting state and its Retry. */ +export function LinkedFilePending({ path }: { path: string }) { + const offline = useVaultStore((s) => s.connection !== "connected"); + const [stalled, retry] = useStalled(offline, path); + const name = path.split("/").filter(Boolean).pop() ?? path; + const dir = path.slice(0, Math.max(0, path.length - name.length)); + return ( +
+
+ {dir} + {name} +
+
+ {!stalled && } + {stalled && } +
+
+ ); +} diff --git a/packages/web/components/vault/VaultFileView.tsx b/packages/web/components/vault/VaultFileView.tsx index c2b8a2a79a..dff93236e5 100644 --- a/packages/web/components/vault/VaultFileView.tsx +++ b/packages/web/components/vault/VaultFileView.tsx @@ -6,15 +6,15 @@ import { memo, Suspense, useMemo, useState } from "react"; import { lazyNamed } from "../../lib/lazyNamed"; import { useWatchEffect } from "../../hooks/useWatchEffect"; import { FileQuestion, FileWarning } from "lucide-react"; +import { FileUnavailable } from "./FileUnavailable"; import { VAULT_MAX_PREVIEW_BYTES, vaultFileKind } from "@codecast/shared/contracts"; import { CODE_EDITOR_MAX_BYTES } from "../../lib/code/limits"; -import { vaultAssetUrl } from "../../lib/vault/client"; +import { readFailureLabel, vaultAssetUrl } from "../../lib/vault/client"; import { useVaultStore } from "../../store/vaultStore"; import { bufferKey, useCodeStore } from "../../store/codeStore"; -import { VaultFileHeader, RevealButton } from "./VaultFileHeader"; +import { VaultFileHeader } from "./VaultFileHeader"; import { CodeFileBar } from "../code/CodeFileBar"; import { useVaultEntryState } from "./useVaultEntry"; -import { buttonVariants } from "../ui/button"; /** Bytes, in the unit a person would say out loud. */ function formatSize(bytes: number): string { @@ -29,36 +29,6 @@ function formatSize(bytes: number): string { return `${value < 10 ? value.toFixed(1) : Math.round(value)} ${units[i]}`; } -/** A centered dead end with one honest sentence and a way out to Finder. */ -function NoPreview({ - path, - icon, - title, - detail, -}: { - path: string; - icon: React.ReactNode; - title: string; - detail: string; -}) { - const canReveal = useVaultStore((s) => !!s.endpoint && !s.isRemote); - return ( -
- {icon} -
{title}
-
{detail}
- {canReveal && ( - - Show in Finder - - )} -
- ); -} - // The editor is its own chunk: nobody who only browses images pays for // CodeMirror. Files prewarms it once the browser is idle, so the first source // file opens without waiting on the download. @@ -99,7 +69,10 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: // asked yet" never flashes as "couldn't read", and a file that returns (an // add or change event) is read again. const readKey = `${path}@${entry?.mtime ?? ""}`; - const [failedRead, setFailedRead] = useState(null); + // The last failed read: which version of the entry, and why (a status a + // person can act on). Retry clears it and asks again. + const [failedRead, setFailedRead] = useState<{ key: string; reason: string } | null>(null); + const [attempt, setAttempt] = useState(0); useWatchEffect(() => { if (kind !== "text" || body) return; const store = useVaultStore.getState(); @@ -109,18 +82,24 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: ? store.loadTextBody(path, { maxBytes: CODE_EDITOR_MAX_BYTES }) : null; void read?.then( - () => { + (reason) => { const s = useVaultStore.getState(); - if (!s.bodies[path] && !s.loadingPaths[path]) setFailedRead(readKey); + if (!s.bodies[path] && !s.loadingPaths[path]) setFailedRead({ key: readKey, reason: reason ?? "Unreadable" }); }, - () => setFailedRead(readKey), + (e) => setFailedRead({ key: readKey, reason: readFailureLabel(e) }), ); - }, [kind, readKey, !!body, endpoint, isRemote]); + }, [kind, readKey, !!body, endpoint, isRemote, attempt]); // No daemon and none coming: no read will run, so say so rather than load - // forever. A cached boot is not that: the daemon is still being reached (the - // page says so in its banner), and the read runs once the endpoint lands. + // forever. A cached boot is not that: the daemon is still being reached, and + // the read runs once the endpoint lands (CodeFileView marks a long wait). const unreachable = !isRemote && !endpoint && connection === "no-daemon"; - const readFailedRaw = !body && !unsaved && (failedRead === readKey || unreachable); + const failReason = failedRead?.key === readKey ? failedRead.reason : unreachable ? "No daemon" : null; + const readFailedRaw = !body && !unsaved && failReason !== null; + const retryRead = () => { + setFailedRead(null); + if (unreachable) void useVaultStore.getState().reconnect(); + else setAttempt((n) => n + 1); + }; const missing = entryState === "missing"; // A text path with nothing on disk, in a vault this machine writes: the // editor stays (CodeFileView opens an empty buffer under that name, created @@ -129,12 +108,7 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: const readFailed = !newFile && readFailedRaw; if (missing && !newFile && !(kind === "text" && unsaved)) { - return ( -
- -
This file does not exist.
-
- ); + return } title="Not on disk" />; } const assetSrc = @@ -143,11 +117,11 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: const renderBody = () => { if (tooLarge) { return ( - } - title="Too large to preview" - detail={`${formatSize(size)} — open it in your editor instead.`} + title="Too large" + detail={`${formatSize(size)} · limit ${formatSize(kind === "text" ? CODE_EDITOR_MAX_BYTES : VAULT_MAX_PREVIEW_BYTES)}`} /> ); } @@ -175,17 +149,23 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: } // Only the scan's own size can tell "empty" from "we don't have it": // calling a failed read "empty" would be a quiet lie about the file. - return ( -
- {size === 0 ? "This file is empty." : "Couldn't read this file."} -
+ return size === 0 ? ( + } title="Empty file" /> + ) : ( + } + title="Couldn't read" + detail={failReason ?? undefined} + onRetry={retryRead} + /> ); } return ( - } - title="No preview for this file type" + title="No preview" detail={formatSize(size)} /> ); @@ -194,8 +174,9 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: // A text file fills the pane and scrolls inside the editor, which renders // only what is on screen; everything else scrolls as a page. One compact row // names the file; the editor owns the rest of the height. A text file keeps - // this layout while its body loads, so the editor is never rebuilt. - if (kind === "text" && !tooLarge && !readFailed) { + // this layout while its body loads, and when it cannot be shown, so the + // breadcrumbs, reveal and bookmark stay put. + if (kind === "text") { return (
@@ -206,7 +187,7 @@ export const VaultFileView = memo(function VaultFileView({ path, line }: { path: return (
-
+
{renderBody()}
diff --git a/packages/web/components/vault/VaultScopeLine.tsx b/packages/web/components/vault/VaultScopeLine.tsx index 043f5693b1..8d74ed9460 100644 --- a/packages/web/components/vault/VaultScopeLine.tsx +++ b/packages/web/components/vault/VaultScopeLine.tsx @@ -74,7 +74,7 @@ export function VaultScopeLine({ return (
diff --git a/packages/web/components/vault/useVaultSidePanel.ts b/packages/web/components/vault/useVaultSidePanel.ts index 43418d7b14..005ddbc37d 100644 --- a/packages/web/components/vault/useVaultSidePanel.ts +++ b/packages/web/components/vault/useVaultSidePanel.ts @@ -1,6 +1,7 @@ import { useRef, useState } from "react"; import { usePanelRef } from "react-resizable-panels"; import { useWatchEffect } from "../../hooks/useWatchEffect"; +import { useOnRequest } from "../../hooks/useOnRequest"; import { collapsePanelSoon } from "../../lib/vault/collapsePanelSoon"; import { useVaultStore } from "../../store/vaultStore"; @@ -20,13 +21,7 @@ export function useVaultSidePanel(inSplitPane: boolean, showGraph: boolean, conn const [paneRightPanelOpen, setPaneRightPanelOpen] = useState(false); const rightPanelOpen = inSplitPane ? paneRightPanelOpen : storeRightPanelOpen; const setRightPanelOpen = inSplitPane ? setPaneRightPanelOpen : setStoreRightPanelOpen; - const tagPaneRequest = useVaultStore((s) => s.tagPaneRequest); - const seenTagPaneRequest = useRef(tagPaneRequest); - useWatchEffect(() => { - if (seenTagPaneRequest.current === tagPaneRequest) return; - seenTagPaneRequest.current = tagPaneRequest; - setRightPanelOpen(true); - }, [tagPaneRequest]); + useOnRequest(useVaultStore((s) => s.tagPaneRequest), () => setRightPanelOpen(true)); const sidePanelRef = usePanelRef(); const sideAppliedRef = useRef(null); useWatchEffect(() => { diff --git a/packages/web/hooks/__tests__/useOnRequest.test.tsx b/packages/web/hooks/__tests__/useOnRequest.test.tsx new file mode 100644 index 0000000000..7a75246b7c --- /dev/null +++ b/packages/web/hooks/__tests__/useOnRequest.test.tsx @@ -0,0 +1,29 @@ +// The Files page opens its hidden tree on each search request and its side +// panel on each tag request; a request made before it mounted is not replayed. +import { expect, test } from "bun:test"; +import { installModernDom } from "../../test-helpers/modernDom"; + +installModernDom("https://app.test/files"); +const React = await import("react"); +const { act } = React; +const { createRoot } = await import("react-dom/client"); +const { useVaultStore } = await import("../../store/vaultStore"); +const { useOnRequest } = await import("../useOnRequest"); + +test("each openSearch after mount runs the page's handler once", async () => { + useVaultStore.getState().openSearch("before mount"); + let opened = 0; + function Page() { + useOnRequest(useVaultStore((s) => s.searchPaneRequest), () => opened++); + return null; + } + const root = createRoot(document.createElement("div")); + await act(async () => root.render()); + expect(opened).toBe(0); + // The Search tab is already the chosen one: the request still counts. + await act(async () => useVaultStore.getState().openSearch()); + await act(async () => useVaultStore.getState().openSearch()); + expect(opened).toBe(2); + expect(useVaultStore.getState().searchQuery).toBe("before mount"); + await act(async () => root.unmount()); +}); diff --git a/packages/web/hooks/useOnRequest.ts b/packages/web/hooks/useOnRequest.ts new file mode 100644 index 0000000000..d32ebb6fcf --- /dev/null +++ b/packages/web/hooks/useOnRequest.ts @@ -0,0 +1,15 @@ +import { useRef } from "react"; +import { useWatchEffect } from "./useWatchEffect"; + +/** Run `fn` each time a store request counter moves past the value this + * component mounted with. The counter is how a store asks a page to do + * something only the page owns (open its tree, its side panel); a request + * made before the page mounted is not replayed. */ +export function useOnRequest(request: number, fn: () => void): void { + const seen = useRef(request); + useWatchEffect(() => { + if (seen.current === request) return; + seen.current = request; + fn(); + }, [request]); +} diff --git a/packages/web/lib/__tests__/castDiffFirstLine.test.ts b/packages/web/lib/__tests__/castDiffFirstLine.test.ts new file mode 100644 index 0000000000..54dc4c52f8 --- /dev/null +++ b/packages/web/lib/__tests__/castDiffFirstLine.test.ts @@ -0,0 +1,19 @@ +import { describe, expect, test } from "bun:test"; +import { firstChangedNewLine, parseCastDiff } from "../castDiff"; + +const diff = (body: string) => `diff --git a/src/x.ts b/src/x.ts\n--- a/src/x.ts\n+++ b/src/x.ts\n${body}`; + +describe("where a cast-diff file card's Edit lands", () => { + test("an addition lands on its own line", () => { + const [file] = parseCastDiff(diff("@@ -10,3 +10,4 @@\n a\n b\n+c\n d\n")); + expect(file.path).toBe("src/x.ts"); + expect(firstChangedNewLine(file)).toBe(12); + }); + test("a removal lands on the line that follows it", () => { + const [file] = parseCastDiff(diff("@@ -4,3 +4,2 @@\n a\n-b\n c\n")); + expect(firstChangedNewLine(file)).toBe(5); + }); + test("no change, no line", () => { + expect(firstChangedNewLine({ hunks: [] })).toBeUndefined(); + }); +}); diff --git a/packages/web/lib/__tests__/codeEditorChunk.guard.test.ts b/packages/web/lib/__tests__/codeEditorChunk.guard.test.ts new file mode 100644 index 0000000000..94f1811634 --- /dev/null +++ b/packages/web/lib/__tests__/codeEditorChunk.guard.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, test } from "bun:test"; +import { join } from "node:path"; +import { WEB, rel, staticImports, walk } from "../../test-helpers/importGraph"; + +// Contract 3 of docs/architecture/code-editor.md: the code editor never joins +// the main bundle. The app's entry and boot (src/main.tsx, src/boot.tsx, which +// every page loads) must not reach CodeMirror, its language packages, Lezer or +// vim through a static import. lib/code files may sit in boot's graph only +// while they import none of those (the command registry and session matching +// do today); the editor itself loads behind `import()` from Files, a path link +// or a diff. Measured 2026-11-26 (perf/README.md, "Editor"): boot is 2,383 KB +// gzipped and the editor adds 85 KB on top of the Files route. + +const EDITOR_PACKAGES = /^(@codemirror\/|@replit\/codemirror|@lezer\/|codemirror$|@uiw\/)/; + +/** Each path from the entry to a file that imports an editor package. */ +function editorLeaks(entry: string): string[] { + const out: string[] = []; + for (const [file, chain] of walk(join(WEB, entry))) { + const pkgs = staticImports(file).filter((s) => EDITOR_PACKAGES.test(s)); + if (pkgs.length) out.push(`${chain.join(" -> ")} imports ${pkgs.join(", ")}`); + } + return out; +} + +describe("the code editor stays out of the main bundle", () => { + test("the entry and boot reach no CodeMirror, Lezer or vim module", () => { + expect(editorLeaks("src/main.tsx")).toEqual([]); + expect(editorLeaks("src/boot.tsx")).toEqual([]); + }); + + test("the lib/code files boot reaches are the ones known to be CodeMirror-free", () => { + const reached = [...walk(join(WEB, "src/boot.tsx")).keys()].map(rel).filter((p) => p.startsWith("lib/code/") || p.startsWith("components/code/")); + // A new entry here is fine only if it imports no editor package (the test + // above says so); list it to keep the boundary a decision, not a drift. + expect(reached.sort()).toEqual(["lib/code/agent/sessions.ts", "lib/code/commands.ts"]); + }); + + test("the walker sees the editor (a self check: the editor host is a leak)", () => { + expect(editorLeaks("lib/code/editorHost.ts").length).toBeGreaterThan(0); + }); +}); diff --git a/packages/web/lib/__tests__/editorPaletteCommands.test.ts b/packages/web/lib/__tests__/editorPaletteCommands.test.ts index 0411967ce6..cf2cb591d2 100644 --- a/packages/web/lib/__tests__/editorPaletteCommands.test.ts +++ b/packages/web/lib/__tests__/editorPaletteCommands.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; import { CODE_COMMAND_IDS } from "../code/commands"; -import { EDITOR_PALETTE_COMMANDS, editorCommandsLead } from "../editorPaletteCommands"; +import { EDITOR_PALETTE_COMMANDS, editorCommandsLead, editorPaletteKey } from "../editorPaletteCommands"; import { formatAcceleratorParts } from "../../shortcuts"; describe("editor palette commands", () => { @@ -20,6 +20,13 @@ describe("editor palette commands", () => { expect(formatAcceleratorParts(quote.editorKey!).length).toBe(2); }); + test("the review commands are offered, each entry under its own key", () => { + const keys = EDITOR_PALETTE_COMMANDS.map(editorPaletteKey); + expect(new Set(keys).size).toBe(keys.length); + const labels = EDITOR_PALETTE_COMMANDS.filter((c) => c.id.startsWith("git.")).map((c) => c.label); + expect(labels).toEqual(["Diff vs HEAD", "Diff against…", "Diff side by side", "Next change", "Previous change", "Peek change", "Revert change"]); + }); + // With Files focused, the words the editor shares with the app's pane // commands lead with the Editor group. test("split, close and search lead with the editor's commands; other words don't", () => { diff --git a/packages/web/lib/__tests__/filesPane.test.ts b/packages/web/lib/__tests__/filesPane.test.ts index 0156dec7de..58a6dbf95a 100644 --- a/packages/web/lib/__tests__/filesPane.test.ts +++ b/packages/web/lib/__tests__/filesPane.test.ts @@ -22,6 +22,8 @@ describe("the editor address", () => { expect(parseCursorTarget(l)).toEqual({ line: 10, column: 3, endLine: 14 }); expect(parseCursorTarget("12-20")).toEqual({ line: 12, column: undefined, endLine: 20 }); expect(parseCursorTarget("12:4")).toEqual({ line: 12, column: 4 }); + // A restored tab names the line at the top of its view too. + expect(parseCursorTarget("380:5@400")).toEqual({ line: 380, column: 5, top: 400 }); // A raw `l` off a URL rides through the ?path= → ?f= rewrite as it came. expect(filesHref({ path: "x.ts", line: "10:3-14" })).toBe("/files?f=x.ts&l=10%3A3-14"); }); @@ -92,14 +94,40 @@ describe("ranges", () => { expect(findTextRange(file, [" return null;"])).toEqual({ line: 2 }); }); + test("findTextRange takes the occurrence nearest a hint line", () => { + const file = "a\n return null;\nb\nc\nd\n return null;\ne\n"; + expect(findTextRange(file, [" return null;"], 5)).toEqual({ line: 6 }); + expect(findTextRange(file, [" return null;"], 1)).toEqual({ line: 2 }); + // A text that occurs once wins wherever the hint is. + expect(findTextRange(file, [" return null;", "d"], 1)).toEqual({ line: 5 }); + }); + test("a diff base maps to the git ref the editor diffs against", () => { expect(gitRefForDiffBase("session", [])).toEqual({ ref: "HEAD", label: "HEAD" }); + // A commit whose hash went unrecorded falls back. expect(gitRefForDiffBase("session", [{ changeType: "commit" }])?.ref).toBe("@merge-base"); expect(gitRefForDiffBase("commit", [{ changeType: "commit" }])?.ref).toBe("HEAD"); expect(gitRefForDiffBase("branch", [])?.ref).toBe("@merge-base"); expect(gitRefForDiffBase("turn", [])).toBeNull(); }); + test("a trunk session's refs come from its own commits, not the branch", () => { + // Committed and pushed on main: the merge base with origin would be its + // own last commit, and the diff would read "No changes". + const pushed = [{ changeType: "edit" }, { changeType: "commit", commitHash: "aaaa111" }, { changeType: "edit" }, { changeType: "commit", commitHash: "bbbb222" }]; + expect(gitRefForDiffBase("session", pushed)).toEqual({ ref: "aaaa111^", label: "Session base" }); + expect(gitRefForDiffBase("commit", pushed)).toEqual({ ref: "bbbb222", label: "Last commit" }); + expect(gitRefForDiffBase("branch", pushed)?.ref).toBe("@merge-base"); + }); + + test("another session's later commits do not move this session's last commit", () => { + // Only this session's changes are listed: someone else committing on top + // leaves "Commit" at this session's own commit, never HEAD. + const mine = [{ changeType: "write" }, { changeType: "commit", commitHash: "cccc333" }, { changeType: "edit" }]; + expect(gitRefForDiffBase("commit", mine)?.ref).toBe("cccc333"); + expect(gitRefForDiffBase("session", mine)?.ref).toBe("cccc333^"); + }); + test("localCheckoutFile picks this machine's worktree on the ref", () => { const checkouts = [ { root: "/m/app", device_id: "other", mine: true, worktrees: [{ path: "/m/app", main: true }] }, diff --git a/packages/web/lib/__tests__/folderPathContext.test.tsx b/packages/web/lib/__tests__/folderPathContext.test.tsx new file mode 100644 index 0000000000..403990f886 --- /dev/null +++ b/packages/web/lib/__tests__/folderPathContext.test.tsx @@ -0,0 +1,33 @@ +import { describe, expect, test } from "bun:test"; +import { useContext } from "react"; +import { renderToString } from "react-dom/server"; +import { FilePathContext, useFolderPathContext } from "../filePathLinks"; + +// A task or plan with a project folder resolves relative paths there; one +// without keeps whatever context it is drawn inside (a conversation's). + +function Probe() { + return {useContext(FilePathContext)?.base ?? "none"}; +} + +function Thread({ folder }: { folder?: string }) { + const ctx = useFolderPathContext(folder); + return ( + + + + ); +} + +const inConversation = (folder?: string) => + renderToString( + + + , + ); + +describe("useFolderPathContext", () => { + test("the row's project wins", () => expect(inConversation("/src/task")).toContain("/src/task")); + test("no project keeps the conversation's", () => expect(inConversation()).toContain("/src/conv")); + test("no project and nothing around it resolves nothing", () => expect(renderToString()).toContain("none")); +}); diff --git a/packages/web/lib/__tests__/stage.test.ts b/packages/web/lib/__tests__/stage.test.ts index edd37544cf..048f0d1f4f 100644 --- a/packages/web/lib/__tests__/stage.test.ts +++ b/packages/web/lib/__tests__/stage.test.ts @@ -2,7 +2,7 @@ import { replaceGlobals } from "../../test-helpers/globals"; import { afterAll, beforeAll, beforeEach, describe, expect, it } from "bun:test"; import { useInboxStore, type AppTab } from "../../store/inboxStore"; import { besideLeafId, leavesOf, seedLeafId } from "../../store/stageSplit"; -import { openBeside, openBrowserPane, openSessionInFocusedPane, paneSessionId, performStageDrop, stageRenderLayout } from "../stage"; +import { openBeside, openBrowserPane, openSessionInFocusedPane, paneSessionId, performStageDrop, sessionPanePath, stageLeafSession, stageRenderLayout } from "../stage"; import { parseBrowserRoute } from "../browserPane"; // performStageDrop is the one entry point every drag source funnels into; @@ -265,6 +265,14 @@ describe("openBeside — the reused Option-click target", () => { expect(t.path).toBe("/tasks"); }); + it("a conversation already beside moves to the message instead of opening twice", () => { + const id = "jx78ksdh85pw088a1d2ce6ndgx83z42a"; + expect(openBeside(sessionPanePath(id))).toBe(true); + expect(openBeside(sessionPanePath(id, "m9"))).toBe(true); + const paths = leavesOf(activeTab().layout!).map((l) => l.path); + expect(paths).toEqual(["/tasks", `/conversation/${id}#msg-m9`]); + }); + it("a path already on stage opens nothing and moves nothing", () => { state().stageInsertLeaf("root", "right", "/docs"); const before = activeTab(); @@ -376,3 +384,16 @@ describe("paneSessionId", () => { expect(paneSessionId("/conversation/3f2c9a1e-7b1d-4c55-9a0e-1c2d3e4f5a6b")).toBeNull(); }); }); + +describe("stageLeafSession", () => { + const id = "jx78ksdh85pw088a1d2ce6ndgx83z42a"; + it("a leaf at a message is that conversation, opened at the message", () => { + expect(sessionPanePath(id, "m1")).toBe(`/conversation/${id}#msg-m1`); + expect(stageLeafSession(sessionPanePath(id, "m1"))).toEqual({ sessionId: id, messageId: "m1" }); + expect(stageLeafSession(sessionPanePath(id))).toEqual({ sessionId: id, messageId: undefined }); + }); + it("keeps share links and short ids page entries", () => { + expect(stageLeafSession(`/conversation/${id}?share=t#msg-m1`)).toBeNull(); + expect(stageLeafSession("/conversation/jx7etg8#msg-m1")).toBeNull(); + }); +}); diff --git a/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts b/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts index aec5c87320..16b42bce22 100644 --- a/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts +++ b/packages/web/lib/__tests__/standaloneBootGraph.guard.test.ts @@ -1,6 +1,6 @@ import { describe, expect, test } from "bun:test"; -import { existsSync, readFileSync } from "node:fs"; -import { dirname, join, relative, resolve } from "node:path"; +import { join } from "node:path"; +import { ALIASES, WEB, rel, walk } from "../../test-helpers/importGraph"; // The standalone boots (src/shareBoot.tsx: the share pages and a guest's // /meet page) exist so that a stranger's page carries nothing of the app: no @@ -17,61 +17,8 @@ import { dirname, join, relative, resolve } from "node:path"; // runs, which is how a module the guest never exercises (the error reporter // behind notificationDelivery, say) stays out of what the page loads. -const WEB = resolve(import.meta.dir, "../.."); -const ALIASES: Record = { - "next/navigation": "src/compat/next-navigation.ts", - "next/link": "src/compat/next-link.tsx", -}; const FORBIDDEN = [/^store\//, /^lib\/calls\/callManager\.ts$/, /^src\/compat\/next-navigation\.ts$/]; -const IMPORT_RE = /(?:^|[\s;])(?:import|export)\s+(type\s+)?(?:[^'"]*?\sfrom\s+)?["']([^"']+)["']/g; - -function resolveFile(base: string): string | null { - for (const ext of ["", ".ts", ".tsx", "/index.ts", "/index.tsx"]) { - const p = base + ext; - if (existsSync(p) && !p.endsWith("/")) { - try { - readFileSync(p); - return p; - } catch { - // a directory - } - } - } - return null; -} - -function resolveSpec(from: string, spec: string): string | null { - if (ALIASES[spec]) return join(WEB, ALIASES[spec]); - if (spec.startsWith("@/")) return resolveFile(join(WEB, spec.slice(2))); - if (spec.startsWith(".")) return resolveFile(resolve(dirname(from), spec)); - return null; // a package: never the app -} - -/** Every web file the entry reaches, with the chain that reached it. */ -function walk(entry: string): Map { - const seen = new Map([[entry, [rel(entry)]]]); - const queue = [entry]; - while (queue.length) { - const file = queue.shift()!; - if (!/\.(ts|tsx)$/.test(file)) continue; - const src = readFileSync(file, "utf8"); - for (const m of src.matchAll(IMPORT_RE)) { - if (m[1]) continue; // `import type` erases - const spec = m[2]; - const target = resolveSpec(file, spec); - if (!target || seen.has(target)) continue; - seen.set(target, [...seen.get(file)!, rel(target)]); - queue.push(target); - } - } - return seen; -} - -function rel(p: string): string { - return relative(WEB, p); -} - function leaks(entry: string): string[] { const out: string[] = []; for (const [file, chain] of walk(join(WEB, entry))) { diff --git a/packages/web/lib/__tests__/terminalFileLinks.test.ts b/packages/web/lib/__tests__/terminalFileLinks.test.ts new file mode 100644 index 0000000000..0d8530a7a8 --- /dev/null +++ b/packages/web/lib/__tests__/terminalFileLinks.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from "bun:test"; +import { cwdFromOsc7, scanTerminalPaths, terminalPathContext } from "../terminal/fileLinks"; +import { editorHref } from "../filesPane"; + +const linked = (text: string) => scanTerminalPaths(text).map((l) => ({ text: text.slice(l.start, l.end), path: l.path, line: l.line, column: l.column })); + +describe("file paths in terminal output", () => { + test("compiler, linter and grep forms carry their line and column", () => { + expect(linked("src/lib/x.ts(12,4): error TS2322: Type 'a' is not assignable")).toEqual([ + { text: "src/lib/x.ts(12,4)", path: "src/lib/x.ts", line: 12, column: 4 }, + ]); + expect(linked("packages/web/lib/a.tsx:38:7 error no-unused-vars")).toEqual([ + { text: "packages/web/lib/a.tsx:38:7", path: "packages/web/lib/a.tsx", line: 38, column: 7 }, + ]); + expect(linked("/Users/me/src/app/main.go:120: return nil")).toEqual([ + { text: "/Users/me/src/app/main.go:120", path: "/Users/me/src/app/main.go", line: 120, column: undefined }, + ]); + expect(linked(" --> src/main.rs:5:9")[0]).toMatchObject({ path: "src/main.rs", line: 5, column: 9 }); + }); + + test("git status and plain listings link the path alone", () => { + expect(linked("\tmodified: packages/web/lib/filesPane.ts")).toEqual([ + { text: "packages/web/lib/filesPane.ts", path: "packages/web/lib/filesPane.ts", line: undefined, column: undefined }, + ]); + }); + + test("URLs, prose slashes and a sentence's full stop stay out", () => { + expect(linked("see https://github.com/owner/repo/blob/main/x.ts and/or km/h")).toEqual([]); + expect(linked("wrote lib/x.ts.")).toEqual([{ text: "lib/x.ts", path: "lib/x.ts", line: undefined, column: undefined }]); + }); + + test("a relative path opens against the terminal's directory, on its machine", () => { + const ctx = terminalPathContext({ cwd: "/Users/me/src/app", deviceId: "dev-1" }); + expect(ctx.home).toBe("/Users/me"); + const [hit] = scanTerminalPaths("src/x.ts(3,2): error"); + expect(editorHref({ path: hit.path, line: hit.line, column: hit.column, ctx })).toBe("/files?path=%2FUsers%2Fme%2Fsrc%2Fapp%2Fsrc%2Fx.ts&d=dev-1&l=3%3A2"); + }); + + test("OSC 7 names the shell's directory", () => { + expect(cwdFromOsc7("file://mac.local/Users/me/src/my%20app")).toBe("/Users/me/src/my app"); + expect(cwdFromOsc7("not a url")).toBeNull(); + }); +}); diff --git a/packages/web/lib/castDiff.ts b/packages/web/lib/castDiff.ts index ef1e314c32..7d3859cdc8 100644 --- a/packages/web/lib/castDiff.ts +++ b/packages/web/lib/castDiff.ts @@ -78,3 +78,17 @@ export function parseCastDiff(raw: string): DiffFileSection[] { } return files; } + +/** The line in the file as it is now where a section's first change sits: an + * added line's own number, or for a removal the line that follows it. */ +export function firstChangedNewLine(file: Pick): number | undefined { + for (const hunk of file.hunks) { + let next = hunk.newStart; + for (const line of hunk.lines) { + if (line.type === "addition") return line.newLineNumber ?? next; + if (line.type === "deletion") return Math.max(1, next); + next = (line.newLineNumber ?? next) + 1; + } + } + return undefined; +} diff --git a/packages/web/lib/code/__tests__/buffers.test.ts b/packages/web/lib/code/__tests__/buffers.test.ts index 0313cef11f..bfb59c1b57 100644 --- a/packages/web/lib/code/__tests__/buffers.test.ts +++ b/packages/web/lib/code/__tests__/buffers.test.ts @@ -3,6 +3,8 @@ import { EditorState } from "@codemirror/state"; import { history, undo } from "@codemirror/commands"; import { BufferCache, + MAX_BUFFER_CHARS, + MAX_CLEAN_BUFFERS, bufferKey, decodeFileText, utf8Length, @@ -48,6 +50,29 @@ describe("BufferCache", () => { expect(cache.get(c.key)).toBe(c); }); + it("30 tabs with three 12M-character files, then 40 more: both bounds hold and every eviction lets go", () => { + const cache = new BufferCache(); + const dropped: string[] = []; + cache.onDrop = (b) => dropped.push(b.path); + const chars = () => cache.all().reduce((n, b) => n + b.state.doc.length, 0); + const big = "x".repeat(120) + "\n"; + const heapBefore = process.memoryUsage().heapUsed; + for (let i = 0; i < 30; i++) open(cache, `f${i}.ts`, i % 10 === 0 ? big.repeat(100_000) : "y".repeat(50_000)); + // 36M characters in 30 buffers: inside both limits, nothing goes. + expect(cache.all().length).toBe(30); + expect(dropped).toEqual([]); + for (let i = 30; i < 70; i++) open(cache, `f${i}.ts`, i % 10 === 0 ? big.repeat(100_000) : "y".repeat(50_000)); + expect(cache.all().length).toBeLessThanOrEqual(MAX_CLEAN_BUFFERS); + expect(chars()).toBeLessThanOrEqual(MAX_BUFFER_CHARS); + expect(dropped.length).toBe(70 - cache.all().length); + // The oldest went first. + expect(dropped[0]).toBe("f0.ts"); + const heapMb = (process.memoryUsage().heapUsed - heapBefore) / 1024 / 1024; + console.log(`[buffers] ${cache.all().length} held, ${(chars() / 1e6).toFixed(1)}M chars, heap +${heapMb.toFixed(0)} MB`); + cache.close("missing"); + expect(dropped.length).toBe(70 - cache.all().length); + }); + it("evicts clean off-screen buffers past the total document size, oldest first", () => { const cache = new BufferCache(40, 100); const a = open(cache, "a", "x".repeat(40)); diff --git a/packages/web/lib/code/__tests__/codeHighlightParity.test.ts b/packages/web/lib/code/__tests__/codeHighlightParity.test.ts new file mode 100644 index 0000000000..be8999d5da --- /dev/null +++ b/packages/web/lib/code/__tests__/codeHighlightParity.test.ts @@ -0,0 +1,240 @@ +// A file reads the same in a transcript's code block (Prism, colored by the +// `.token.*` rules in globals.css) and in the editor (Lezer, colored by +// theme.ts). Each fixture is tokenized both ways and every visible character +// is resolved to the color it paints in; any difference fails, naming the +// characters. The Prism side reads the real stylesheet, so a change to either +// side's colors is caught here. + +import { describe, expect, it } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import Prism from "prismjs"; +import "prismjs/components/prism-typescript"; +import "prismjs/components/prism-json"; +import "prismjs/components/prism-css"; +import "prismjs/components/prism-yaml"; +import "prismjs/components/prism-markdown"; +import "prismjs/components/prism-python"; +import { highlightTree } from "@lezer/highlight"; +import type { LanguageSupport } from "@codemirror/language"; +import { CODE_HIGHLIGHT_STYLES, CODE_HIGHLIGHTERS, SYNTAX } from "../theme"; +import { describeLanguage, loadLanguage } from "../languages"; + +// ── Prism: token classes to colors, as the stylesheet resolves them ───────── + +const css = readFileSync(join(import.meta.dir, "../../../app/globals.css"), "utf8"); +const base = /code\[class\*="language-"\],\s*pre\[class\*="language-"\]\s*\{[^}]*?color:\s*([^;]+);/.exec(css)![1].trim(); + +/** `.token.x` rules with a color, in stylesheet order (a later rule wins). */ +const tokenRules: { classes: string[]; color: string }[] = []; +for (const m of css.matchAll(/((?:\.token\.[\w-]+\s*,?\s*)+)\{([^}]*)\}/g)) { + const color = /(?:^|;|\s)color:\s*([^;]+);/.exec(m[2])?.[1].trim(); + if (!color) continue; + for (const sel of m[1].split(",")) tokenRules.push({ classes: [sel.trim().replace(/^\.token\./, "")], color }); +} + +function prismColor(classes: readonly string[]): string | null { + let color: string | null = null; + for (const r of tokenRules) if (r.classes.every((c) => classes.includes(c))) color = r.color; + return color; +} + +function prismColors(code: string, lang: string): string[] { + const out: string[] = []; + const walk = (tokens: (string | Prism.Token)[], inherited: string) => { + for (const tok of tokens) { + if (typeof tok === "string") { + for (let i = 0; i < tok.length; i++) out.push(inherited); + continue; + } + const aliases = tok.alias ? (Array.isArray(tok.alias) ? tok.alias : [tok.alias]) : []; + const color = prismColor([tok.type, ...aliases]) ?? inherited; + const content = tok.content; + if (typeof content === "string") for (let i = 0; i < content.length; i++) out.push(color); + else walk(Array.isArray(content) ? content : [content], color); + } + }; + walk(Prism.tokenize(code, Prism.languages[lang]!), base); + return out; +} + +// ── Lezer: the editor's highlighters, class to the color its rule paints ──── + +/** Each class a highlighter emits has one rule in its style's module; the + * color comes from there, so the test sees what the editor paints. */ +async function lezerColors(code: string, file: string): Promise { + const support = (await loadLanguage(describeLanguage(file))) as LanguageSupport; + const out: string[] = Array.from({ length: code.length }, () => SYNTAX.plain); + highlightTree(support.language.parser.parse(code), CODE_HIGHLIGHTERS, (from, to, classes) => { + const color = colorOfClasses(classes); + if (color) for (let i = from; i < to; i++) out[i] = color; + }); + return out; +} + +/** The color a span's classes paint: the last of its classes' rules that + * sets one (each style's rules are written in spec order). */ +function colorOfClasses(classes: string): string | null { + let color: string | null = null; + for (const cls of classes.split(" ")) { + const c = ruleColors().get(cls); + if (c) color = c; + } + return color; +} + +let rules: Map | null = null; +/** Each style's module holds its rules as text: `.ͼx {color: ...}`. */ +function ruleColors(): Map { + if (rules) return rules; + rules = new Map(); + for (const style of CODE_HIGHLIGHT_STYLES) { + for (const m of style.module!.getRules().matchAll(/\.([^\s{]+)\s*\{([^}]*)\}/g)) { + const color = /color:\s*([^;]+)/.exec(m[2]!)?.[1]!.trim(); + if (color) rules.set(m[1]!, color); + } + } + return rules; +} + +// ── fixtures ──────────────────────────────────────────────────────────────── + +/** Text (every occurrence) whose color the two sides are not expected to + * share, with why. Each is a place Prism guesses from a pattern where the + * editor's parser knows the construct, or the reverse; nothing a tag could + * tell apart is waived. */ +type Waiver = { text: string; why: string }; + +const FIXTURES: { name: string; file: string; prism: string; code: string; waive?: Waiver[] }[] = [ + { + name: "TypeScript", + file: "a.ts", + prism: "typescript", + code: [ + `import { join } from "node:path";`, + `// a comment`, + `export interface Row { id: string; count: number }`, + `const limit = 42, on = true, none = null;`, + `export function total(rows: Row[]): number {`, + ` const seen = { first: 1, "second": 2 };`, + ` return rows.reduce((n, r) => n + r.count, 0) * limit;`, + `}`, + `class Box extends Base { constructor() { super(); this.x = /a+b/g; } }`, + `const s = \`tpl \${limit}\`;`, + ].join("\n"), + waive: [ + { text: "string", why: "a primitive type is Prism's `builtin`; the parser's TypeName does not say which types are primitive" }, + { text: "number", why: "the same" }, + { text: "Row[]", why: "Prism colors a type only after `class`/`interface`/`extends`; the parser marks every type reference" }, + { text: "Row {", why: "the same, at its declaration" }, + { text: "Base", why: "Prism takes the name after `extends` for a class; the parser reads it as the variable it is" }, + { text: `"second"`, why: "a quoted key is a string to the parser and a property to Prism's pattern" }, + { text: "constructor", why: "Prism calls any `name(` a function; to the parser a method name is a property definition, like a key" }, + { text: "${limit}", why: "Prism's TypeScript leaves a template's interpolation inside the string; the parser colors the expression" }, + ], + }, + { + name: "JavaScript", + file: "a.js", + prism: "javascript", + code: [`// keys are properties in JavaScript`, `const row = { id: 1, on: false, none: null };`, `export const f = (a, ...rest) => a ? rest : [];`].join("\n"), + waive: [{ text: "f =", why: "Prism calls a name assigned an arrow a function, by pattern; the parser reads a variable definition" }], + }, + { + name: "JSON", + file: "a.json", + prism: "json", + code: `{\n "name": "codecast",\n "count": 3,\n "on": true,\n "none": null,\n "list": [1, "two"]\n}`, + waive: [{ text: ":", why: "Prism's JSON calls `:` an operator; the parser tags it with `,` as one separator" }], + }, + { + name: "CSS", + file: "a.css", + prism: "css", + code: [ + `/* a comment */`, + `.card > a:hover, #main {`, + ` color: #fff;`, + ` margin: 0 4px;`, + `}`, + `@media (max-width: 600px) { body { padding: 0; } }`, + ].join("\n"), + waive: [ + { text: ".card > a:hover, #main", why: "Prism paints a whole selector, punctuation included, as one token; the parser tags its marks as punctuation" }, + { text: "0", why: "Prism's CSS has no numbers; the parser colors them as everywhere else" }, + { text: "4px", why: "the same" }, + { text: "600px", why: "the same, inside an at-rule Prism paints as one" }, + ], + }, + { + name: "YAML", + file: "a.yaml", + prism: "yaml", + code: `# a comment\nname: codecast\ncount: 3\non: true\nlist:\n - one\n - "two"\n`, + waive: [ + { text: "3", why: "the YAML parser does not type a plain scalar (number, boolean): every one is content" }, + { text: "true", why: "the same" }, + ], + }, + { + name: "Markdown", + file: "a.md", + prism: "markdown", + code: `# Title\n\nSome **bold** and _italic_ words.\n\n- item\n`, + }, + { + name: "Python", + file: "a.py", + prism: "python", + code: [`# a comment`, `def total(rows):`, ` return sum(r.count for r in rows) + 42`, `name = "codecast"`].join("\n"), + waive: [ + { text: ":", why: "the Python parser gives `:` no tag" }, + { text: "sum", why: "Prism knows Python's builtins by name; to the parser `sum` is a call like any other" }, + ], + }, +]; + +function mismatches(code: string, a: string[], b: string[], waive: Waiver[] = []): string[] { + const waived = new Set(); + for (const w of waive) { + let at = code.indexOf(w.text); + if (at < 0) throw new Error(`waiver text not in fixture: ${w.text}`); + for (; at >= 0; at = code.indexOf(w.text, at + 1)) for (let i = at; i < at + w.text.length; i++) waived.add(i); + } + const out: string[] = []; + let run: { from: number; to: number; prism: string; editor: string } | null = null; + const flush = () => { + if (run) out.push(`${JSON.stringify(code.slice(run.from, run.to))}: prism ${run.prism}, editor ${run.editor}`); + run = null; + }; + for (let i = 0; i < code.length; i++) { + if (/\s/.test(code[i]!) || waived.has(i) || a[i] === b[i]) { + flush(); + continue; + } + if (run && run.to === i && run.prism === a[i] && run.editor === b[i]) run.to++; + else { + flush(); + run = { from: i, to: i + 1, prism: a[i]!, editor: b[i]! }; + } + } + flush(); + return out; +} + +describe("syntax colors in the editor match the transcript's code blocks", () => { + it("reads the Prism rules from the stylesheet", () => { + expect(base).toBe(SYNTAX.plain); + expect(prismColor(["keyword"])).toBe(SYNTAX.keyword); + expect(prismColor(["comment"])).toBe(SYNTAX.comment); + }); + + for (const f of FIXTURES) { + it(f.name, async () => { + const prism = prismColors(f.code, f.prism); + const editor = await lezerColors(f.code, f.file); + expect(prism.length).toBe(f.code.length); + expect(mismatches(f.code, prism, editor, f.waive)).toEqual([]); + }); + } +}); diff --git a/packages/web/lib/code/__tests__/fileSync.test.ts b/packages/web/lib/code/__tests__/fileSync.test.ts index 4f11119fa3..7b5cd80382 100644 --- a/packages/web/lib/code/__tests__/fileSync.test.ts +++ b/packages/web/lib/code/__tests__/fileSync.test.ts @@ -5,16 +5,19 @@ import { afterAll, beforeEach, describe, expect, it } from "bun:test"; import { indexedDB, IDBKeyRange } from "fake-indexeddb"; import { EditorState, type Transaction } from "@codemirror/state"; import { history } from "@codemirror/commands"; -import { VaultWriteConflict } from "../../vault/client"; +import { VaultRequestError, VaultWriteConflict } from "../../vault/client"; import { useCodeStore } from "../../../store/codeStore"; -import { codeBuffers, currentState, encodeFileText, fileFormatField, isDirty, type CodeBuffer } from "../buffers"; +import { codeBuffers, currentState, diskLockField, encodeFileText, fileFormatField, isDirty, syncDiskLock, type CodeBuffer } from "../buffers"; import { featureBase } from "../features"; import { + _retryUnsentForTests, _setDiskIOForTests, applyDiskVersion, + overwriteLocked, applyToBuffer as updateBuffer, externalChange, fileSyncExtensions, + keepMine, recreateFile, restoreHotExit, revertBuffer, @@ -33,6 +36,12 @@ interface Disk { etag: string; writes: string[]; deleted?: boolean; + /** The mode refuses writes (0444): the daemon's 403 unless forced. */ + locked?: boolean; + /** The daemon is not answering (restarting). */ + down?: boolean; + /** Each write's force flag and If-Match, in order. */ + sent?: { force: boolean; etag: string }[]; } let disk: Disk; let n = 0; @@ -45,7 +54,10 @@ function land(content: string) { return { etag: disk.etag, mtime: n, size: content.length }; } const fakeIO: DiskIO = { - write: async (_b, content, baseEtag) => { + write: async (_b, content, baseEtag, opts) => { + (disk.sent ??= []).push({ force: !!opts?.force, etag: baseEtag }); + if (disk.down) throw new TypeError("Failed to fetch"); + if (disk.locked && !opts?.force) throw new VaultRequestError("vault write: 403 read-only", 403, "read-only"); // The daemon's answer for a guarded write to a file that is gone. if (disk.deleted) throw new VaultWriteConflict({ content: '{"error":"conflict"}', etag: "", mtime: 0, size: 0 }); if (baseEtag !== disk.etag) throw conflict(); @@ -308,6 +320,59 @@ describe("save", () => { }); }); +describe("read-only on disk and offline", () => { + it("a 0444 file refuses the save, then overwrites on confirm, still guarded by the etag", async () => { + const b = openBuffer(base); + disk.locked = true; + type(b, 0, "x"); + expect(await saveBuffer(b)).toBe("locked"); + expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "readonly", mode: "read-only" }); + expect(currentState(b).field(diskLockField)).toBe("read-only"); + expect(disk.writes).toEqual([]); + const etag = b.baseEtag; + expect(await overwriteLocked(b)).toBe("saved"); + expect(disk.sent?.at(-1)).toEqual({ force: true, etag }); + expect(disk.content).toBe(`x${base}`); + expect(useCodeStore.getState().conflicts[b.key]).toBeUndefined(); + // The mode is kept: the lock stays shown. + expect(currentState(b).field(diskLockField)).toBe("read-only"); + }); + + it("shows the mode the read reported", async () => { + const b = openBuffer(base); + syncDiskLock(b, "0444"); + disk.locked = true; + type(b, 0, "x"); + await saveBuffer(b); + expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "readonly", mode: "0444" }); + }); + + it("a save the daemon never received waits, and goes once Files is back", async () => { + const b = openBuffer(base); + disk.down = true; + type(b, 0, "x"); + expect(await saveBuffer(b)).toBe("offline"); + expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "offline" }); + disk.down = false; + type(b, 1, "y"); + _retryUnsentForTests(); + await new Promise((r) => setTimeout(r, 0)); + await saveBuffer(b); + expect(disk.content).toBe(`xy${base}`); + expect(useCodeStore.getState().conflicts[b.key]).toBeUndefined(); + }); + + it("a refusal names the daemon's reason, not the request", async () => { + const b = openBuffer(base); + const io = _setDiskIOForTests({ ...fakeIO, write: async () => { throw new VaultRequestError("vault write src/x: 415 binary", 415, "binary"); } }); + type(b, 0, "x"); + expect(await saveBuffer(b)).toBe("error"); + expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "error", message: "binary" }); + io(); + _setDiskIOForTests(fakeIO); + }); +}); + describe("external change", () => { it("lands in a clean buffer as line edits, annotated, cursor kept", async () => { const b = openBuffer(base); @@ -331,17 +396,88 @@ describe("external change", () => { expect(external.length).toBe(0); }); - it("marks a dirty buffer stale and merges at the save", async () => { + it("merges into a dirty buffer at once: disk's lines land as an external change, mine stay unsaved", async () => { const b = openBuffer(base); type(b, 0, "// mine\n"); const theirs = agentWrites(base.replace("return 2;", "return 22;")); await applyDiskVersion(b, theirs); - expect(text(b)).toBe(`// mine\n${base}`); - expect(b.stale?.etag).toBe(theirs.etag); - expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "stale" }); + expect(text(b)).toBe(`// mine\n${theirs.content}`); + expect(b.stale).toBeNull(); + expect(b.baseEtag).toBe(theirs.etag); + expect(b.dirty).toBe(true); + expect(useCodeStore.getState().conflicts[b.key]).toBeUndefined(); + // Only disk's line moved in that transaction: what agent marks color. + expect(external.length).toBe(1); + expect(external[0].annotation(externalChange)).toEqual({ etag: theirs.etag }); + const changed: string[] = []; + external[0].changes.iterChanges((_a, _b, _fromB, _toB, inserted) => changed.push(inserted.toString())); + expect(changed.join("")).toContain("return 22;"); + expect(changed.join("")).not.toContain("// mine"); expect(await saveBuffer(b)).toBe("saved"); - expect(disk.content).toBe(`// mine\n${base.replace("return 2;", "return 22;")}`); + expect(disk.content).toBe(`// mine\n${theirs.content}`); + }); + + it("opens the merge view at once on a conflict, counting conflicts apart from my clean edits", async () => { + const b = openBuffer(base); + type(b, 0, "// mine\n"); + const one = text(b).indexOf("1;"); + updateBuffer(b, { changes: { from: one, to: one + 1, insert: "'mine'" } }); + const theirs = agentWrites(base.replace("return 1;", "return 'disk';")); + await applyDiskVersion(b, theirs); + expect(b.merging?.etag).toBe(theirs.etag); + expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "merge", remaining: 2, conflicts: 1 }); + // Taking disk's side of the conflict resolves it; my clean edit still differs. + const at = text(b).indexOf("return 'mine';"); + updateBuffer(b, { changes: { from: at, to: at + "return 'mine';".length, insert: "return 'disk';" } }); + await Promise.resolve(); + await new Promise((r) => setTimeout(r, 0)); + expect(useCodeStore.getState().conflicts[b.key]).toEqual({ kind: "merge", remaining: 1, conflicts: 0 }); + expect(await saveBuffer(b)).toBe("saved"); + expect(disk.content).toBe(`// mine\n${theirs.content}`); + }); + + it("Keep mine writes my text over disk's version, on its etag", async () => { + const b = openBuffer(base); + const one = base.indexOf("1;"); + updateBuffer(b, { changes: { from: one, to: one + 1, insert: "'mine'" } }); + const mine = text(b); + agentWrites(base.replace("return 1;", "return 'disk';").replace("import a", "import disk")); + await applyDiskVersion(b, { content: disk.content, etag: disk.etag, mtime: n }); + expect(b.merging).not.toBeNull(); + // The merge view took disk's clean line in; Keep mine leaves it out. + expect(text(b)).toContain("import disk"); + expect(await keepMine(b)).toBe("saved"); + expect(disk.content).toBe(mine); + expect(text(b)).toBe(mine); + expect(b.merging).toBeNull(); + expect(b.dirty).toBe(false); + expect(useCodeStore.getState().conflicts[b.key]).toBeUndefined(); }); + + it("decides a disk version that arrives during a save once the save lands", async () => { + const b = openBuffer(base); + type(b, 0, "x"); + // The save's own write, reported before the PUT answers: nothing to merge. + const saving = saveBuffer(b); + const own = { content: `x${base}`, etag: `e${n + 1}`, mtime: n + 1 }; + await applyDiskVersion(b, own); + expect(await saving).toBe("saved"); + await new Promise((r) => setTimeout(r, 0)); + expect(b.merging).toBeNull(); + expect(external.length).toBe(0); + expect(useCodeStore.getState().conflicts[b.key]).toBeUndefined(); + // Someone else's write reported during a save comes in after it. + type(b, text(b).length, "// tail\n"); + const again = saveBuffer(b); + const theirs = { content: `x${base}`.replace("return 1;", "return 10;"), etag: "e-theirs", mtime: 99 }; + await applyDiskVersion(b, theirs); + await again; + await new Promise((r) => setTimeout(r, 0)); + await new Promise((r) => setTimeout(r, 0)); + expect(text(b)).toContain("return 10;"); + expect(b.baseEtag).toBe("e-theirs"); + }); + }); describe("hot exit", () => { diff --git a/packages/web/lib/code/__tests__/foldMarkers.mount.test.ts b/packages/web/lib/code/__tests__/foldMarkers.mount.test.ts new file mode 100644 index 0000000000..18905f3e13 --- /dev/null +++ b/packages/web/lib/code/__tests__/foldMarkers.mount.test.ts @@ -0,0 +1,38 @@ +// Fold markers are the breadcrumbs' lucide chevrons, not text glyphs, and an +// open marker is told apart from a folded one so the theme can show open +// markers only on the cursor's line or a hovered gutter. +import { installEditorDom } from "../../../components/code/__tests__/editorDom"; + +installEditorDom(); + +const { expect, it } = await import("bun:test"); +const { EditorState } = await import("@codemirror/state"); +const { EditorView } = await import("@codemirror/view"); +const { foldAll, foldService } = await import("@codemirror/language"); +const { codeSetup, DEFAULT_EDITOR_OPTIONS } = await import("../setup"); +const { bufferFields } = await import("../buffers"); + +// The first line folds the rest of the document. +const firstLineFolds = foldService.of((state, from, to) => (from === 0 ? { from: to, to: state.doc.length } : null)); + +it("draws open and folded markers as SVG chevrons with their state", () => { + const parent = document.createElement("div"); + document.body.append(parent); + const doc = "function a() {\n return 1;\n}\n"; + const view = new EditorView({ + parent, + state: EditorState.create({ + doc, + extensions: [bufferFields({ lineSeparator: "\n", bom: false, lossy: false } as never), codeSetup({ options: DEFAULT_EDITOR_OPTIONS, indent: { unit: " ", tabs: false, width: 2, detected: true }, readOnly: false, largeFile: false }), firstLineFolds], + }), + }); + const markers = () => [...view.dom.querySelectorAll(".cm-fold-marker")] as HTMLElement[]; + const open = markers().filter((m) => m.dataset.fold === "open"); + expect(open.length).toBeGreaterThan(0); + expect(open[0].querySelector("svg")?.getAttribute("width")).toBe("12"); + expect(open[0].textContent).toBe(""); + foldAll(view); + expect(markers().some((m) => m.dataset.fold === "folded")).toBe(true); + view.destroy(); + parent.remove(); +}); diff --git a/packages/web/lib/code/__tests__/idleNetwork.mount.test.ts b/packages/web/lib/code/__tests__/idleNetwork.mount.test.ts new file mode 100644 index 0000000000..b3c366335e --- /dev/null +++ b/packages/web/lib/code/__tests__/idleNetwork.mount.test.ts @@ -0,0 +1,125 @@ +// The editor's idle budget against a busy repo (docs/architecture/code-editor.md, +// perf/README.md "Editor"): agents save files all day, and an open Files page +// pays for each save in store writes and daemon requests. A burst of watcher +// events is one file-table write and one git status; a hidden page asks the +// daemon nothing until it is shown, and then asks once; a file no editor +// holds is never read again on a save. +import { afterAll, expect, mock, test } from "bun:test"; +import { installEditorDom } from "../../../components/code/__tests__/editorDom"; + +installEditorDom(); + +const calls = { status: 0 }; +const realClient = { ...(await import("../daemonClient")) }; +mock.module("../daemonClient", () => ({ + ...realClient, + fetchGitStatus: async () => { + calls.status++; + return { repo: true, branch: "main", head: "h1", ahead: 0, behind: 0, files: {} }; + }, +})); + +const reads: string[] = []; +const realVault = { ...(await import("../../vault/client")) }; +mock.module("../../vault/client", () => ({ + ...realVault, + readVaultFile: async (_ep: unknown, _v: string, path: string) => { + reads.push(path); + return { content: "new", mtime: 5000, etag: "e-new", size: 3 }; + }, + scanVault: async () => ({ files: Object.values(scanRows), scanned_at: Date.now(), repo: true }), +})); +/** What the next rescan (refresh) returns. */ +let scanRows: Record = {}; + +const { useVaultStore, _queueVaultWsEventForTests, _applyVaultWsEventForTests } = await import("../../../store/vaultStore"); +const { codeBuffers } = await import("../buffers"); +await import("../fileSync"); +const { holdGitStatusFeed } = await import("../git/status"); + +const VAULT = "vault-idle"; +const FILES = 20_000; +const files: Record = {}; +for (let i = 0; i < FILES; i++) files[`src/m${i % 97}/f${i}.ts`] = { path: `src/m${i % 97}/f${i}.ts`, mtime: 1, size: 10 }; +useVaultStore.setState({ + activeVaultId: VAULT, + isRemote: false, + endpoint: { url: "http://127.0.0.1:1", token: "t" } as any, + files: files as any, + bodies: {}, +}); + +const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); +const release = holdGitStatusFeed(); +afterAll(() => release()); +await wait(20); +const save = (i: number) => + _queueVaultWsEventForTests({ type: "change", vault: VAULT, path: `src/m${i % 97}/f${i}.ts`, mtime: 1000 + i, size: 11 } as any); + +test("a burst of 500 agent saves: one file-table write, one git status", async () => { + let writes = 0; + const off = useVaultStore.subscribe((s, p) => void (s.files !== p.files && writes++)); + const before = calls.status; + for (let i = 0; i < 500; i++) save(i); + expect(writes).toBe(0); + await wait(800); + off(); + expect(writes).toBe(1); + expect(calls.status - before).toBe(1); + expect(useVaultStore.getState().files["src/m3/f3.ts"].mtime).toBe(1003); + expect(Object.keys(useVaultStore.getState().files).length).toBe(FILES); +}); + +test("a hidden page asks for no git status until it is shown, then once", async () => { + let visibility = "hidden"; + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility }); + try { + const before = calls.status; + for (let round = 0; round < 3; round++) { + for (let i = 0; i < 20; i++) save(round * 100 + i); + await wait(700); + } + expect(calls.status).toBe(before); + visibility = "visible"; + document.dispatchEvent(new Event("visibilitychange")); + await wait(20); + expect(calls.status - before).toBe(1); + } finally { + delete (document as { visibilityState?: unknown }).visibilityState; + } +}); + +test("a save to a file no editor holds drops its text; a held one is read once", async () => { + const closed = "src/m1/f1.ts"; + const open = "src/m2/f2.ts"; + useVaultStore.setState((s) => ({ bodies: { ...s.bodies, [closed]: { content: "old", mtime: 1, etag: "a" }, [open]: { content: "old", mtime: 1, etag: "b" } } })); + const buffer = codeBuffers.open({ vaultId: VAULT, path: open, content: "old", etag: "b", extensions: () => [] }); + reads.length = 0; + _applyVaultWsEventForTests({ type: "change", vault: VAULT, path: closed, mtime: 4000, size: 3 } as any); + _applyVaultWsEventForTests({ type: "change", vault: VAULT, path: open, mtime: 5000, size: 3 } as any); + await wait(20); + expect(reads).toEqual([open]); + expect(useVaultStore.getState().bodies[closed]).toBeUndefined(); + expect(useVaultStore.getState().bodies[open]?.etag).toBe("e-new"); + // The buffer leaves the cache: the store lets go of its text too. + codeBuffers.close(buffer.key); + expect(useVaultStore.getState().bodies[open]).toBeUndefined(); +}); + +test("a rescan after the socket was down reads an open file disk changed, and no other code", async () => { + const open = "src/m4/f4.ts"; + const closed = "src/m5/f5.ts"; + useVaultStore.setState((s) => ({ bodies: { ...s.bodies, [open]: { content: "old", mtime: 1, etag: "b" } } })); + const buffer = codeBuffers.open({ vaultId: VAULT, path: open, content: "old", etag: "b", extensions: () => [] }); + scanRows = { [open]: { path: open, mtime: 9000, size: 3 }, [closed]: { path: closed, mtime: 9000, size: 3 } }; + reads.length = 0; + await useVaultStore.getState().refresh(); + expect(reads).toEqual([open]); + expect(useVaultStore.getState().bodies[open]?.etag).toBe("e-new"); + // Unchanged since: nothing to read. + reads.length = 0; + useVaultStore.setState((s) => ({ bodies: { ...s.bodies, [open]: { ...s.bodies[open]!, mtime: 9000 } } })); + await useVaultStore.getState().refresh(); + expect(reads).toEqual([]); + codeBuffers.close(buffer.key); +}); diff --git a/packages/web/lib/code/__tests__/jumpHistory.mount.test.ts b/packages/web/lib/code/__tests__/jumpHistory.mount.test.ts new file mode 100644 index 0000000000..1940234d3a --- /dev/null +++ b/packages/web/lib/code/__tests__/jumpHistory.mount.test.ts @@ -0,0 +1,35 @@ +// An explicit jump (definition, symbol, crumb, `:line`) is a back/forward stop +// however near it lands, with vim on or off, and even while a picker holds focus. + +import { expect, it } from "bun:test"; +import { installEditorDom } from "../../../components/code/__tests__/editorDom"; + +installEditorDom(); + +const { EditorState } = await import("@codemirror/state"); +const { EditorView } = await import("@codemirror/view"); +const { attachFeatureHost, featureBase, syncEditorFeatures } = await import("../features"); +const { registerWorkspaceEditorFeatures } = await import("../workspace/editorWorkspace"); +const { _resetNavHistory, stepHistory } = await import("../workspace/navHistory"); +const { jumpTo } = await import("../jump"); + +const ctx = { vaultId: "v", path: "a.ts", languageId: "typescript", languageName: "TypeScript", sizeBytes: 1, largeFile: false }; +const tick = () => new Promise((r) => setTimeout(r, 0)); + +for (const vim of [false, true]) { + it(`a jump five lines away is a stop (${vim ? "vim" : "no vim"})`, async () => { + _resetNavHistory(); + registerWorkspaceEditorFeatures(); + const view = new EditorView({ parent: document.body }); + const release = attachFeatureHost(view); + view.setState(EditorState.create({ doc: Array.from({ length: 200 }, (_, i) => `line ${i + 1}`).join("\n"), extensions: featureBase(ctx) })); + syncEditorFeatures(view); + await tick(); + if (vim) view.scrollDOM.classList.add("cm-vimMode"); + jumpTo(view, view.state.doc.line(100).from); + jumpTo(view, view.state.doc.line(95).from); + expect(stepHistory(-1)?.line).toBe(100); + release(); + view.destroy(); + }); +} diff --git a/packages/web/lib/code/__tests__/merge.test.ts b/packages/web/lib/code/__tests__/merge.test.ts index 6a25b5a043..a7e3228181 100644 --- a/packages/web/lib/code/__tests__/merge.test.ts +++ b/packages/web/lib/code/__tests__/merge.test.ts @@ -37,24 +37,26 @@ describe("threeWayMerge", () => { expect(threeWayMerge(kit, base, disk, mine)).toEqual({ text: base.replace("return 1;", "return 10;").replace("return 2;", "return 20;"), conflicts: 0, + regions: [], }); }); it("takes an identical change once", () => { const both = base.replace("import a", "import b"); - expect(threeWayMerge(kit, base, both, both)).toEqual({ text: both, conflicts: 0 }); + expect(threeWayMerge(kit, base, both, both)).toEqual({ text: both, conflicts: 0, regions: [] }); }); it("keeps mine where both changed the same lines differently, and counts it", () => { const disk = base.replace("return 1;", "return 'disk';"); const mine = base.replace("return 1;", "return 'mine';").replace("import a", "import z"); - expect(threeWayMerge(kit, base, disk, mine)).toEqual({ text: mine, conflicts: 1 }); + const at = mine.indexOf(" return 'mine';"); + expect(threeWayMerge(kit, base, disk, mine)).toEqual({ text: mine, conflicts: 1, regions: [{ from: at, to: at + " return 'mine';\n".length }] }); }); it("merges an append on one side with an edit elsewhere on the other", () => { const disk = base + L("", "function three() {}"); const mine = base.replace("import a", "import a, b"); - expect(threeWayMerge(kit, base, disk, mine)).toEqual({ text: mine + L("", "function three() {}"), conflicts: 0 }); + expect(threeWayMerge(kit, base, disk, mine)).toEqual({ text: mine + L("", "function three() {}"), conflicts: 0, regions: [] }); }); it("treats edits on adjacent lines as a conflict, as git does", () => { @@ -65,7 +67,7 @@ describe("threeWayMerge", () => { it("short-circuits when a side did not move", () => { const moved = base.replace("two", "dos"); - expect(threeWayMerge(kit, base, base, moved)).toEqual({ text: moved, conflicts: 0 }); - expect(threeWayMerge(kit, base, moved, base)).toEqual({ text: moved, conflicts: 0 }); + expect(threeWayMerge(kit, base, base, moved)).toEqual({ text: moved, conflicts: 0, regions: [] }); + expect(threeWayMerge(kit, base, moved, base)).toEqual({ text: moved, conflicts: 0, regions: [] }); }); }); diff --git a/packages/web/lib/code/__tests__/mergeView.mount.test.ts b/packages/web/lib/code/__tests__/mergeView.mount.test.ts new file mode 100644 index 0000000000..6626923b51 --- /dev/null +++ b/packages/web/lib/code/__tests__/mergeView.mount.test.ts @@ -0,0 +1,47 @@ +// The merge view tells the conflicts (both sides wrote the lines) apart from +// the person's clean edits: red-barred, stepped to first, and counted only +// while they still differ from disk. +import { installEditorDom } from "../../../components/code/__tests__/editorDom"; + +installEditorDom(); + +const { describe, expect, it } = await import("bun:test"); +const { EditorSelection, EditorState } = await import("@codemirror/state"); +const { EditorView } = await import("@codemirror/view"); +const kit = await import("@codemirror/merge"); +const { mergeChunkCount, mergeViewExtension, openConflicts, stepMerge, threeWayMerge } = await import("../merge"); + +const L = (...ls: string[]) => ls.map((l) => `${l}\n`).join(""); +const base = L("import a", "", "function one() {", " return 1;", "}", "", "function two() {", " return 2;", "}"); +const disk = base.replace("return 1;", "return 'disk';"); +const mine = base.replace("return 1;", "return 'mine';").replace("return 2;", "return 22;"); + +function mount() { + const merged = threeWayMerge(kit, base, disk, mine); + const parent = document.createElement("div"); + document.body.append(parent); + const view = new EditorView({ parent, state: EditorState.create({ doc: merged.text, extensions: [mergeViewExtension(kit, disk, merged.regions)] }) }); + return view; +} + +describe("the merge view's conflicts", () => { + it("are marked apart from a clean edit, stepped to first, and resolved by taking a side", () => { + const view = mount(); + expect(mergeChunkCount(kit, view.state)).toBe(2); + expect(openConflicts(kit, view.state)).toHaveLength(1); + const barred = [...view.dom.querySelectorAll(".cm-line")].filter((l) => l.classList.contains("cm-code-mergeConflict")).map((l) => l.textContent); + expect(barred).toEqual([" return 'mine';"]); + + view.dispatch({ selection: EditorSelection.cursor(view.state.doc.length) }); + expect(stepMerge(kit, view, 1)).toBe(true); + expect(view.state.doc.lineAt(view.state.selection.main.head).text).toBe(" return 'mine';"); + + // Taking disk's side of the conflict: the clean edit still differs. + const at = view.state.doc.toString().indexOf("return 'mine';"); + view.dispatch({ changes: { from: at, to: at + "return 'mine';".length, insert: "return 'disk';" } }); + expect(openConflicts(kit, view.state)).toEqual([]); + expect(mergeChunkCount(kit, view.state)).toBe(1); + expect(view.dom.querySelector(".cm-code-mergeConflict")).toBeNull(); + view.destroy(); + }); +}); diff --git a/packages/web/lib/code/__tests__/statusBar.test.ts b/packages/web/lib/code/__tests__/statusBar.test.ts index 5431df88b8..d28f4931e3 100644 --- a/packages/web/lib/code/__tests__/statusBar.test.ts +++ b/packages/web/lib/code/__tests__/statusBar.test.ts @@ -1,6 +1,7 @@ import { expect, it } from "bun:test"; import { EditorState } from "@codemirror/state"; -import { cursorLabel, dropOrder } from "../statusBar"; +import { cursorLabel, dropOrder, formatSegments } from "../statusBar"; +import { fileFormatField } from "../buffers"; const at = (doc: string, head: number) => cursorLabel(EditorState.create({ doc, selection: { anchor: head }, extensions: EditorState.tabSize.of(4) })); @@ -20,3 +21,22 @@ it("a narrow bar drops the lowest priorities first, the later one first between // vim mode, branch, cursor, file format, server chip, selection expect(dropOrder([100, 20, 90, 30, 40, 30])).toEqual([1, 5, 3, 4, 2, 0]); }); + +it("shows the line ending and encoding only when a file differs from LF and plain UTF-8", () => { + const plain = EditorState.create({ doc: "x", extensions: [fileFormatField] }); + expect(formatSegments(plain)).toEqual({ language: "Plain Text", indent: "Spaces: 2", lineEnding: "", encoding: "", largeFile: "" }); + const crlf = EditorState.create({ doc: "x", extensions: [fileFormatField.init(() => ({ lineSeparator: "\r\n", bom: true, lossy: false }))] }); + expect(formatSegments(crlf)).toMatchObject({ lineEnding: "CRLF", encoding: "UTF-8 with BOM" }); +}); + +it("the cursor segment's width covers its document's last line at a three-digit column", async () => { + const { cursorWidthCh } = await import("../statusBar"); + expect(cursorWidthCh(120)).toBe("Ln 120, Col 999".length); +}); + +it("rows are whole pixels at any font size and line height", async () => { + const { codeLineHeightPx } = await import("../setup"); + expect(codeLineHeightPx(13, 1.6)).toBe(21); + expect(codeLineHeightPx(12, 1.6)).toBe(19); + expect(codeLineHeightPx(14, 1.5)).toBe(21); +}); diff --git a/packages/web/lib/code/__tests__/statusBarVault.mount.test.ts b/packages/web/lib/code/__tests__/statusBarVault.mount.test.ts index a78d42d017..4c1bf11377 100644 --- a/packages/web/lib/code/__tests__/statusBarVault.mount.test.ts +++ b/packages/web/lib/code/__tests__/statusBarVault.mount.test.ts @@ -43,3 +43,47 @@ it("needsVault items skip a pseudo vault and mount for a real one", () => { parent.remove(); offs.forEach((off) => off()); }); + +it("the cursor segment holds the widest label its document can show, so cursor moves never shift the bar", () => { + const { cursorWidthCh } = require("../statusBar") as typeof import("../statusBar"); + const parent = document.createElement("div"); + document.body.append(parent); + const doc = Array.from({ length: 120 }, (_, i) => `line ${i}`).join("\n"); + const view = new EditorView({ parent, state: EditorState.create({ doc, extensions: [fields(), statusBar()] }) }); + const cursor = view.dom.querySelector(".cm-code-status-cursor") as HTMLElement; + expect(cursor.style.minWidth).toBe(`${cursorWidthCh(120)}ch`); + view.dispatch({ selection: { anchor: doc.length } }); + expect(cursor.textContent).toBe("Ln 120, Col 9"); + expect(cursor.style.minWidth).toBe(`${cursorWidthCh(120)}ch`); + // The line count gaining a digit widens it. + view.dispatch({ changes: { from: 0, insert: "\n".repeat(900) } }); + expect(cursor.style.minWidth).toBe(`${cursorWidthCh(1020)}ch`); + view.destroy(); + parent.remove(); +}); + +it("the lock names why the file cannot be written, and a mode lock offers the overwrite", () => { + const { setDiskLock } = require("../buffers") as typeof import("../buffers"); + const { registerCodeCommands } = require("../commands") as typeof import("../commands"); + const ctx = { vaultId: "v-lock", path: "gen.ts", languageId: "typescript", languageName: "TypeScript", sizeBytes: 1, largeFile: false }; + const parent = document.createElement("div"); + document.body.append(parent); + const view = new EditorView({ parent, state: EditorState.create({ doc: "x", extensions: [fields(), featureBase(ctx), statusBar()] }) }); + const lock = () => view.dom.querySelector(".cm-code-status-lock") as HTMLButtonElement; + expect(lock().hidden).toBe(true); + // A 0444 file: editable, the mode on the lock, a press asks to overwrite. + view.dispatch({ effects: setDiskLock.of("0444") }); + expect(lock().hidden).toBe(false); + expect(lock().textContent).toBe("0444"); + let asked = 0; + const off = registerCodeCommands({ "file.overwrite": () => void asked++ }); + lock().click(); + expect(asked).toBe(1); + off(); + // Read-only with no buffer behind it: the held text shown while the daemon reconnects. + view.setState(EditorState.create({ doc: "x", extensions: [fields(), featureBase(ctx), statusBar(), EditorState.readOnly.of(true)] })); + expect(lock().textContent).toBe("Read-onlyoffline"); + expect(lock().getAttribute("aria-label")).toBe("Read-only, offline"); + view.destroy(); + parent.remove(); +}); diff --git a/packages/web/lib/code/__tests__/theme.test.ts b/packages/web/lib/code/__tests__/theme.test.ts index 53f65abb12..d59cfd0d93 100644 --- a/packages/web/lib/code/__tests__/theme.test.ts +++ b/packages/web/lib/code/__tests__/theme.test.ts @@ -1,4 +1,6 @@ import { describe, expect, it } from "bun:test"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; import type { ThemePalette } from "@codecast/shared/contracts/theme"; import { blockCursorColors } from "../theme"; import { BUILTIN_THEMES, ORIGINAL_PREVIEW } from "../../theme/builtinThemes"; @@ -48,9 +50,21 @@ describe("the vim block cursor", () => { }); }); -it("diff tints are stronger on a dark background than on a light one", async () => { - const { diffTint } = await import("../theme"); - expect(diffTint({ bg: "#fbf5e2" }, 0.08)).toBe(0.08); - expect(diffTint({ bg: "#20252e" }, 0.08)).toBe(0.16); - expect(diffTint({ bg: "not a color" }, 0.08)).toBe(0.08); +describe("syntax and diff colors follow the color theme", () => { + const css = readFileSync(join(import.meta.dir, "../../../app/globals.css"), "utf8"); + const decls = (name: string) => [...css.matchAll(new RegExp(`${name}:\\s*([^;]+);`, "g"))].map((m) => m[1]!.trim()); + + it("declares every --hljs-* and --diff-* color from the theme's own tokens, never a fixed hex", () => { + const names = [...new Set([...css.matchAll(/(--(?:hljs|diff)-[\w-]+):/g)].map((m) => m[1]!))]; + expect(names.length).toBeGreaterThan(10); + for (const name of names) for (const value of decls(name)) expect({ name, value, fixed: /#[\da-f]{3,8}\b/i.test(value) }).toEqual({ name, value, fixed: false }); + }); + + it("paints comments in the dim ink, which reads on its page in every shipped theme", () => { + expect(decls("--hljs-comment")).toEqual(["var(--sol-text-dim)"]); + for (const [name, p] of palettes) { + if (!p.bg || !p["text-dim"]) continue; + expect({ name, ok: contrast(p["text-dim"], p.bg) >= 4.4 }).toEqual({ name, ok: true }); + } + }); }); diff --git a/packages/web/lib/code/agent/__tests__/editorMarks.mount.test.ts b/packages/web/lib/code/agent/__tests__/editorMarks.mount.test.ts index bd9a80d0dd..b6f90f8064 100644 --- a/packages/web/lib/code/agent/__tests__/editorMarks.mount.test.ts +++ b/packages/web/lib/code/agent/__tests__/editorMarks.mount.test.ts @@ -12,7 +12,7 @@ const { EditorView } = await import("@codemirror/view"); const { featureBase } = await import("../../features"); const { externalChange } = await import("../../fileSync"); const marks = await import("../editorMarks"); -const { addSentMark, agentMarks, agentMarksExtension, clearSentMarks, dismissAgentEdits, dropFlashes, setAgentMarkHooks, stepAgentEdit } = marks; +const { addSentMark, agentMarks, agentMarksExtension, clearSentMarks, dismissAgentEdits, dropFlashes, setAgentMarkHooks, setSentState, stepAgentEdit } = marks; const writers: Record = { "src/a.ts": "s1" }; const restore = setAgentMarkHooks({ @@ -40,7 +40,7 @@ const lineOf = (view: InstanceType, pos: number) => view.stat const editLines = (view: InstanceType) => agentMarks(view.state).edits.map((e) => [lineOf(view, e.from), lineOf(view, e.to)]); describe("external changes", () => { - it("are marked in the color of the session that wrote them, with a fading flash", () => { + it("are marked in the color of the session that wrote them, with a fading flash", async () => { const view = mount(); const two = view.state.doc.line(2); adopt(view, two.from, two.to, "TWO\nTWO-b"); @@ -51,6 +51,10 @@ describe("external changes", () => { expect(st.flashes[0]).toMatchObject({ kind: "edit", color: "c-s1" }); expect(view.dom.querySelector(".cm-agentFlash")).not.toBeNull(); expect(view.dom.querySelector(".cm-agentBar")).not.toBeNull(); + // The fade's clock starts once the view has drawn it. + expect(st.flashes[0].until).toBe(0); + await Promise.resolve(); + expect(agentMarks(view.state).flashes[0].until).toBeGreaterThan(Date.now()); // Flashes drop once faded; the gutter mark stays. view.dispatch({ effects: dropFlashes.of(Date.now() + 10_000) }); expect(agentMarks(view.state).flashes).toEqual([]); @@ -136,11 +140,38 @@ describe("mapping and dismissal", () => { view.destroy(); }); - it("Escape dismisses all edits", () => { + it("Escape leaves them: vim presses it on every return to normal mode", () => { const view = mount(); adopt(view, 0, 3, "ONE"); view.contentDOM.dispatchEvent(new window.KeyboardEvent("keydown", { key: "Escape", bubbles: true })); - expect(agentMarks(view.state).edits).toEqual([]); + expect(agentMarks(view.state).edits).toHaveLength(1); + view.destroy(); + }); + + it("an edit that lands in a background buffer keeps its fade until the buffer is shown", async () => { + let state = EditorState.create({ doc: DOC, extensions: [featureBase(ctx()), agentMarksExtension()] }); + state = state.update({ changes: { from: 0, to: 3, insert: "ONE" }, annotations: externalChange.of({ etag: "e" }) }).state; + // Hours later, still unshown: nothing is due. + state = state.update({ effects: dropFlashes.of(Date.now() + 3_600_000) }).state; + expect(agentMarks(state).flashes).toHaveLength(1); + const parent = document.createElement("div"); + document.body.append(parent); + const view = new EditorView({ parent, state }); + expect(view.dom.querySelector(".cm-agentFlash")).not.toBeNull(); + await Promise.resolve(); + expect(agentMarks(view.state).flashes[0].until).toBeGreaterThan(Date.now() + 1000); + view.destroy(); + }); + + it("draws a scrollbar tick per edit, by line, in the writer's color", () => { + const view = mount(); + adopt(view, view.state.doc.line(6).from, view.state.doc.line(6).to, "SIX"); + const ticks = [...view.dom.querySelectorAll(".cm-agentTicks .cm-agentTick")]; + expect(ticks).toHaveLength(1); + expect(ticks[0].style.top).toBe(`${(5 / 7) * 100}%`); + expect(ticks[0].style.getPropertyValue("--agent-c")).toBe("c-s1"); + view.dispatch({ effects: dismissAgentEdits.of("all") }); + expect(view.dom.querySelector(".cm-agentTicks")).toBeNull(); view.destroy(); }); }); @@ -191,14 +222,30 @@ describe("sent marker", () => { view.destroy(); }); - it("ends when the file changes on disk, or the person edits the quoted text", () => { + it("ends when its own lines change, on disk or by the person; a write elsewhere maps it", () => { const view = mount(); - sent(view, 3); - adopt(view, 0, 3, "ONE"); + sent(view, 3, "c1"); + sent(view, 6, "c2"); + // An agent rewrites line 1: both markers hold, on their text. + adopt(view, 0, 3, "ONE\nONE-b"); + expect(agentMarks(view.state).sent.map((x) => view.state.sliceDoc(x.from, x.to))).toEqual(["three", "six"]); + // It then writes line 3 (the first instruction's range): only that one ends. + const three = view.state.doc.line(4); + adopt(view, three.from, three.to, "THREE"); + expect(agentMarks(view.state).sent.map((x) => x.key)).toEqual(["c2"]); + view.dispatch({ changes: { from: view.state.doc.line(7).from, insert: "x" } }); expect(agentMarks(view.state).sent).toEqual([]); + view.destroy(); + }); + + it("shows where the message is: queued, then worked on", () => { + const view = mount(); sent(view, 3); - view.dispatch({ changes: { from: view.state.doc.line(3).from, insert: "x" } }); - expect(agentMarks(view.state).sent).toEqual([]); + const note = () => view.dom.querySelector(".cm-agentSentNote"); + expect(note()?.dataset.sentState).toBe("queued"); + expect(note()?.querySelector(".cm-agentSentDot")).not.toBeNull(); + view.dispatch({ effects: setSentState.of({ key: "c1", state: "working" }) }); + expect(note()?.dataset.sentState).toBe("working"); view.destroy(); }); diff --git a/packages/web/lib/code/agent/__tests__/feature.mount.test.ts b/packages/web/lib/code/agent/__tests__/feature.mount.test.ts index 8614781c1e..d5324a297f 100644 --- a/packages/web/lib/code/agent/__tests__/feature.mount.test.ts +++ b/packages/web/lib/code/agent/__tests__/feature.mount.test.ts @@ -14,7 +14,9 @@ const { useInboxStore } = await import("../../../../store/inboxStore"); const { useVaultStore } = await import("../../../../store/vaultStore"); const { useAgentStore } = await import("../agentStore"); const { addSentMark, agentMarks, agentMarksExtension } = await import("../editorMarks"); -const { agentKeys, checkSentTurns, openInlineInstruction, quoteSelection, selectedRange, watchTurn } = await import("../feature"); +const { externalChange } = await import("../../fileSync"); +const { agentKeys, askNow, editsItem, checkSentTurns, openInlineInstruction, quoteSelection, selectedRange, sessionDiffTargets, watchTurn } = await import("../feature"); +const { useDiffViewerStore } = await import("../../../../store/diffViewerStore"); const { codeBuffers } = await import("../../buffers"); const { instructionMessage, sendInstruction } = await import("../compose"); @@ -151,6 +153,25 @@ describe("Cmd-K", () => { }); }); +describe(":Ask with the instruction typed", () => { + it("sends at once to the linked session and leaves the box's marker, no box", () => { + const view = mount(); + view.dispatch({ selection: EditorSelection.cursor(view.state.doc.line(4).from) }); + expect(askNow(view, "s1", "use checked addition")).toBe(true); + expect(useAgentStore.getState().inline).toBeNull(); + const range = selectedRange(view, "/r/app")!; + const text = instructionMessage(range, "use checked addition"); + expect(sends).toEqual([ + ["optimistic", "s1", text], + ["send", "s1", text, undefined, "client-1"], + ]); + const sent = agentMarks(view.state).sent; + expect(sent).toHaveLength(1); + expect(sent[0]).toMatchObject({ key: "client-1", sessionId: "s1", state: "queued" }); + expect(view.state.doc.lineAt(sent[0].from).number).toBe(4); + }); +}); + describe("Cmd-K's target", () => { it("is the session linked when the box opened; with none, the box asks", () => { const view = mount(); @@ -221,6 +242,7 @@ describe("the sent marker", () => { useInboxStore.setState({ sessions: { s1: busy }, pendingMessages: {}, messages: { s1: [{ _id: "m1", role: "user", client_id: "c-q", timestamp: t0 + 2000 }] } } as never); checkSentTurns(state(), t0 + 2000); expect(agentMarks(buffer.view!.state).sent).toHaveLength(1); + expect(agentMarks(buffer.view!.state).sent[0].state).toBe("working"); useInboxStore.setState({ sessions: { s1: idle } } as never); checkSentTurns(state(), t0 + 3000); expect(agentMarks(buffer.view!.state).sent).toEqual([]); @@ -242,3 +264,50 @@ describe("the sent marker", () => { expect(agentMarks(view.state).sent.map((x) => x.key)).toEqual(["k2"]); }); }); + +describe("the agent edits status item", () => { + it("counts the buffer's edits, steps to the next on a press, and clears them on x", () => { + const view = mount(); + const item = editsItem(view)!; + const sync = () => item.update?.({ startState: prev, state: view.state } as never); + let prev = view.state; + expect(item.dom.hidden).toBe(true); + for (const n of [2, 6]) { + const l = view.state.doc.line(n); + prev = view.state; + view.dispatch({ changes: { from: l.from, to: l.to, insert: "X" }, annotations: externalChange.of({ etag: "e" }) }); + sync(); + } + expect(item.dom.hidden).toBe(false); + expect(item.dom.textContent).toContain("2"); + // Its name says what the bare count is and what a press does. + expect(item.dom.querySelector(".cm-agent-editsNext")!.getAttribute("aria-label")).toBe("2 agent edits, go to next"); + view.dispatch({ selection: EditorSelection.cursor(0) }); + item.dom.querySelector(".cm-agent-editsNext")!.click(); + expect(view.state.doc.lineAt(view.state.selection.main.head).number).toBe(2); + prev = view.state; + item.dom.querySelector(".cm-agent-editsClear")!.click(); + sync(); + expect(agentMarks(view.state).edits).toEqual([]); + expect(item.dom.hidden).toBe(true); + }); +}); + +describe("the diff picker's session refs", () => { + it("offers the linked session's base from the changes the panel holds, in its color", () => { + useAgentStore.setState({ links: { v: { sessionId: "s1", source: "beside" } } } as never); + const state = EditorState.create({ doc: "x" }); + useDiffViewerStore.setState({ conversationId: "s1", changes: [{ changeType: "edit" }] } as never); + // Nothing committed: it stands on HEAD, which the picker lists already. + expect(sessionDiffTargets("v", state)).toEqual([]); + useDiffViewerStore.setState({ conversationId: "s1", changes: [{ changeType: "commit", commitHash: "abc1234" }, { changeType: "commit", commitHash: "def5678" }] } as never); + const [t] = sessionDiffTargets("v", state); + expect(t.ref).toBe("abc1234^"); + expect(t.label).toBe("Fix the parser base"); + expect(t.color).toBeTruthy(); + // Another conversation's changes say nothing about the linked session. + useDiffViewerStore.setState({ conversationId: "s9" } as never); + expect(sessionDiffTargets("v", state)).toEqual([]); + useDiffViewerStore.setState({ conversationId: null, changes: [] } as never); + }); +}); diff --git a/packages/web/lib/code/agent/__tests__/sessions.test.ts b/packages/web/lib/code/agent/__tests__/sessions.test.ts index 8e73c0fd83..121ba4afc1 100644 --- a/packages/web/lib/code/agent/__tests__/sessions.test.ts +++ b/packages/web/lib/code/agent/__tests__/sessions.test.ts @@ -1,7 +1,7 @@ // The linked session's rules: a pick wins, then the conversation beside Files on // the stage, then the most recently active session working in the folder. import { describe, expect, it } from "bun:test"; -import { besideSessionId, candidateSessions, pathWithin, resolveLink, sessionColor, sessionOfPanePath, sessionShortTitle, steerable, type AgentSessionRow } from "../sessions"; +import { besideSessionId, blameSessionBases, candidateSessions, sessionGitRefs, matchesSessionQuery, pathWithin, resolveLink, sessionColor, sessionOfPanePath, sessionShortTitle, steerable, type AgentSessionRow } from "../sessions"; const row = (id: string, over: Partial = {}): AgentSessionRow => ({ _id: id, agent_type: "claude_code", updated_at: 0, project_path: "/r/app", ...over }); @@ -160,4 +160,50 @@ describe("faces", () => { expect(sessionColor("abc")).toBe(sessionColor({ _id: "abc" })); expect(sessionColor(null)).toBe("var(--sol-text-dim)"); }); + + it("never hashes a session to git's added, deleted or modified color", () => { + const seen = new Set(Array.from({ length: 200 }, (_, i) => sessionColor(`session-${i}`))); + expect(seen.size).toBe(5); + for (const git of ["var(--sol-green)", "var(--sol-red)", "var(--sol-blue)"]) expect(seen.has(git)).toBe(false); + }); +}); + +describe("the picker's filter", () => { + it("matches every word in the title or short title, any case", () => { + const s = row("a", { title: "Fix the auth race in the sync host", short_title: "Auth race" }); + expect(matchesSessionQuery(s, "")).toBe(true); + expect(matchesSessionQuery(s, "AUTH race")).toBe(true); + expect(matchesSessionQuery(s, "sync auth")).toBe(true); + expect(matchesSessionQuery(s, "parser")).toBe(false); + }); + + it("searches past the recent cap", () => { + const rows = Array.from({ length: 30 }, (_, i) => row(`s${i}`, { updated_at: 100 - i, title: i === 29 ? "Oldest one" : `Session ${i}` })); + expect(candidateSessions(rows, "/r/app", null, null)).toHaveLength(12); + expect(candidateSessions(rows, "/r/app", null, null, Infinity).filter((r) => matchesSessionQuery(r, "oldest")).map((r) => r._id)).toEqual(["s29"]); + }); +}); + +describe("a session's git refs", () => { + it("stands on HEAD until it commits, then on its first commit's parent", () => { + expect(sessionGitRefs([{ changeType: "edit" }])).toEqual({ committed: false, base: "HEAD", last: null }); + expect(sessionGitRefs([{ changeType: "commit", commitHash: "abc1234" }, { changeType: "commit", commitHash: "def5678" }])).toEqual({ committed: true, base: "abc1234^", last: "def5678" }); + // A hash the commit's output never named (or a garbled one) gives no ref. + expect(sessionGitRefs([{ changeType: "commit", commitHash: "not a sha" }])).toEqual({ committed: true, base: null, last: null }); + }); + + it("reads each writer's base off the file's blame: the parent of its oldest standing commit", () => { + const s1 = { id: "jx1", conversation_id: "c1", title: "Fix parser" }; + const bases = blameSessionBases([ + { sha: "bbbbbbb", time: 20, session: s1 }, + { sha: "aaaaaaa", time: 10, session: s1 }, + { sha: "ccccccc", time: 5, session: { id: "jx2" } }, + { uncommitted: true, session: { id: "jx3" } }, + { sha: "ddddddd", time: 1 }, + ]); + expect([...bases]).toEqual([ + ["c1", { ref: "aaaaaaa^", title: "Fix parser" }], + ["jx2", { ref: "ccccccc^", title: undefined }], + ]); + }); }); diff --git a/packages/web/lib/code/agent/agentStore.ts b/packages/web/lib/code/agent/agentStore.ts index cde503d24b..0e206b9c86 100644 --- a/packages/web/lib/code/agent/agentStore.ts +++ b/packages/web/lib/code/agent/agentStore.ts @@ -78,6 +78,8 @@ interface AgentStoreState { addChip(el: HTMLElement, vaultId: string, newSession?: () => boolean): void; removeChip(el: HTMLElement): void; setOverride(vaultId: string, value: LinkOverride): void; + /** Read the vault's saved pick into the store, once. */ + restoreOverride(vaultId: string): void; setLink(vaultId: string, link: AgentLink): void; /** `digest` names the evidence; an unchanged digest writes nothing. */ setPresence(vaultId: string, root: string, index: EditIndex, digest: string): void; @@ -92,6 +94,29 @@ interface AgentStoreState { let inlineIds = 0; +// The person's pick per vault outlives a reload, beside the vault's code +// workspace (lib/code/workspace/persist): a vault is one folder on one +// machine, so the pick is this browser's. A pick whose session is gone is +// passed over by resolveLink until the person picks again. +const OVERRIDE_KEY = (vaultId: string) => `codecast:code-agent-link:v1:${vaultId}`; + +function readOverride(vaultId: string): LinkOverride { + try { + return (typeof localStorage === "undefined" ? null : localStorage.getItem(OVERRIDE_KEY(vaultId))) ?? undefined; + } catch { + return undefined; + } +} + +function writeOverride(vaultId: string, value: LinkOverride): void { + try { + if (value) localStorage.setItem(OVERRIDE_KEY(vaultId), value); + else localStorage.removeItem(OVERRIDE_KEY(vaultId)); + } catch { + // Storage full or blocked: the pick lasts for this page. + } +} + const sameLink = (a: AgentLink | undefined, b: AgentLink) => !!a && a.sessionId === b.sessionId && a.source === b.source; export const useAgentStore = create((set, get) => ({ @@ -112,6 +137,12 @@ export const useAgentStore = create((set, get) => ({ }, setOverride: (vaultId, value) => { if (get().overrides[vaultId] === value) return; + writeOverride(vaultId, value); + set((s) => ({ overrides: { ...s.overrides, [vaultId]: value } })); + }, + restoreOverride: (vaultId) => { + if (vaultId in get().overrides) return; + const value = readOverride(vaultId); set((s) => ({ overrides: { ...s.overrides, [vaultId]: value } })); }, setLink: (vaultId, link) => { diff --git a/packages/web/lib/code/agent/editorMarks.ts b/packages/web/lib/code/agent/editorMarks.ts index e43ce831a7..d28f65bee0 100644 --- a/packages/web/lib/code/agent/editorMarks.ts +++ b/packages/web/lib/code/agent/editorMarks.ts @@ -2,13 +2,15 @@ // (never React, never a store write on a keystroke): // // - agent edits: ranges a session wrote while the file was open, in that -// session's color. A soft background fades over ~2 s; a gutter bar stays -// until the cursor enters the range (a click on the bar or Escape -// dismisses too). ]a / [a step between them. +// session's color. A soft background fades over ~2 s from when the buffer +// is first on screen; a gutter bar and a scrollbar tick stay until the +// cursor enters the range (a click on the bar, `:AgentClear` and the +// status item's clear dismiss too). ]a / [a step between them. // - quote flash: the range Cmd-L just quoted, pulsing once. -// - sent marker: the range a Cmd-K instruction went out about, with a quiet -// "sent to " note, until the file changes under it or the -// session's turn ends. +// - sent marker: the range a Cmd-K instruction went out about, with a +// "sent to " note and a dot for where the message is (queued, +// being worked on), until the file changes under that range or the turn +// that read it ends. // - the inline instruction's host: a block widget under the selection that // the React layer portals the input into. // @@ -62,10 +64,16 @@ export interface Flash { to: number; color: string; kind: "edit" | "quote"; - /** Epoch ms after which the flash is dropped. */ + /** Epoch ms after which the flash is dropped; 0 until the buffer is on + * screen, where its clock starts (a change to a background tab keeps its + * fade for when the tab is shown). */ until: number; } +/** Where a sent instruction is: not yet read by the agent, or in the turn + * working on it. */ +export type SentState = "queued" | "working"; + export interface SentMark { from: number; to: number; @@ -74,6 +82,7 @@ export interface SentMark { sessionId: string; color: string; label: string; + state?: SentState; } export interface InlineSpot { @@ -97,6 +106,10 @@ export const QUOTE_FLASH_MS = 900; export const addAgentEdits = StateEffect.define<{ edits: AgentEdit[]; flashUntil: number }>(); export const dismissAgentEdits = StateEffect.define<"all" | number[]>(); export const dropFlashes = StateEffect.define(); // drop those due by this time +/** Starts the clock of flashes waiting for the screen, at this time. */ +export const startFlashes = StateEffect.define(); +/** A sent instruction moved on (its client id, and where it is now). */ +export const setSentState = StateEffect.define<{ key: string; state: SentState }>(); export const addFlash = StateEffect.define(); export const addSentMark = StateEffect.define(); /** Clears the marker of one sent message (its client id), or all. */ @@ -147,9 +160,9 @@ export const agentMarksField = StateField.define({ if (tr.docChanged) { edits = edits.map((e) => mapRange(e, tr.changes)); flashes = flashes.map((f) => mapRange(f, tr.changes)); - if (tr.annotation(externalChange)) sent = []; - else if (sent.length) { - // The person editing the quoted text ends the marker for that range. + if (sent.length) { + // A change to the marked text, the person's or a writer's on disk, + // ends that range's marker; one elsewhere in the file maps it. const touched = changedRanges(tr); sent = sent.map((s) => mapRange(s, tr.changes)).filter((s) => !touched.some((c) => c.from <= s.to && c.to >= s.from)); } @@ -166,7 +179,13 @@ export const agentMarksField = StateField.define({ const drop = e.value; edits = drop === "all" ? [] : edits.filter((_x, i) => !drop.includes(i)); } else if (e.is(dropFlashes)) { - flashes = flashes.filter((f) => f.until > e.value); + flashes = flashes.filter((f) => f.until === 0 || f.until > e.value); + } else if (e.is(startFlashes)) { + const at = e.value; + if (flashes.some((f) => f.until === 0)) flashes = flashes.map((f) => (f.until ? f : { ...f, until: at + (f.kind === "quote" ? QUOTE_FLASH_MS : EDIT_FLASH_MS) })); + } else if (e.is(setSentState)) { + const { key, state } = e.value; + if (sent.some((s) => s.key === key && s.state !== state)) sent = sent.map((s) => (s.key === key ? { ...s, state } : s)); } else if (e.is(addFlash)) { flashes = [...flashes, e.value]; } else if (e.is(addSentMark)) { @@ -191,8 +210,11 @@ export const agentMarksField = StateField.define({ }, }); -/** Holds the agent gutter only while the buffer has agent edits, so a file no - * agent touched carries no empty strip beside the git gutter. */ +/** Holds the agent gutter only while the buffer has agent edits. The column + * is zero wide and its bar sits exactly over the git bar beside it (the + * theme below), so an agent's edit shows in its session's color where the + * git change would, hands back to git once dismissed, and the text never + * moves when the column comes or goes (contract 8). */ const gutterSlot = new Compartment(); /** An external change (fileSync's adopt) gets its ranges marked as one agent @@ -207,7 +229,9 @@ const markExternalChanges = EditorState.transactionExtender.of((tr) => { const color = hooks.colorOf(sessionId); const edits = changedRanges(tr).map((r) => ({ ...r, sessionId, color })); if (edits.length) { - effects.push(addAgentEdits.of({ edits, flashUntil: Date.now() + EDIT_FLASH_MS })); + // The clock starts on screen (flashTimer), not here: the buffer may be + // in a background tab. + effects.push(addAgentEdits.of({ edits, flashUntil: 0 })); adding = true; } } @@ -221,18 +245,22 @@ class SentNote extends WidgetType { constructor( readonly label: string, readonly color: string, + readonly state: SentState, ) { super(); } eq(other: SentNote) { - return other.label === this.label && other.color === this.color; + return other.label === this.label && other.color === this.color && other.state === this.state; } toDOM() { const el = document.createElement("span"); el.className = "cm-agentSentNote"; + el.dataset.sentState = this.state; el.style.setProperty("--agent-c", this.color); - el.textContent = `sent to ${this.label}`; - el.title = `Instruction sent to ${this.label}`; + const dot = document.createElement("span"); + dot.className = "cm-agentSentDot"; + el.append(dot, `sent to ${this.label}`); + el.title = this.state === "working" ? `${this.label} is working on it` : `Waiting for ${this.label} to read it`; return el; } } @@ -281,7 +309,7 @@ function buildDecorations(state: EditorState): DecorationSet { for (const s of sent) { if (s.to > s.from) items.push({ from: s.from, to: s.to, deco: Decoration.mark({ class: "cm-agentSent", attributes: { style: `--agent-c: ${s.color}` } }) }); const end = doc.lineAt(Math.min(s.to, doc.length)).to; - items.push({ from: end, to: end, deco: Decoration.widget({ widget: new SentNote(s.label, s.color), side: 2 }) }); + items.push({ from: end, to: end, deco: Decoration.widget({ widget: new SentNote(s.label, s.color, s.state ?? "queued"), side: 2 }) }); } if (inline) { const pos = Math.min(inline.pos, doc.length); @@ -342,11 +370,13 @@ const editGutter = gutter({ }, }); -/** Drops flashes once they have faded, so a line scrolled back into view does - * not replay its fade. */ +/** Starts the clock of flashes that arrived off screen, and drops flashes once + * they have faded, so a line scrolled back into view does not replay its + * fade. A view update cannot dispatch, so the start waits a microtask. */ const flashTimer = ViewPlugin.fromClass( class { timer: ReturnType | null = null; + starting = false; constructor(readonly view: EditorView) { this.schedule(); } @@ -358,6 +388,15 @@ const flashTimer = ViewPlugin.fromClass( this.timer = null; const { flashes } = this.view.state.field(agentMarksField); if (!flashes.length) return; + if (flashes.some((f) => f.until === 0)) { + if (this.starting) return; + this.starting = true; + queueMicrotask(() => { + this.starting = false; + if (this.view.dom.isConnected && agentMarks(this.view.state).flashes.some((f) => f.until === 0)) this.view.dispatch({ effects: startFlashes.of(Date.now()) }); + }); + return; + } const due = Math.min(...flashes.map((f) => f.until)); this.timer = setTimeout( () => { @@ -393,15 +432,49 @@ const gutterHider = ViewPlugin.fromClass( }, ); -const escapeDismisses = EditorView.domEventHandlers({ - keydown(e, view) { - if (e.key !== "Escape" || e.defaultPrevented) return false; - const st = view.state.field(agentMarksField); - if (st.edits.length) view.dispatch({ effects: dismissAgentEdits.of("all") }); - // Escape still does what it does (vim's normal mode, closing a panel). - return false; +/** A tick on the scrollbar's edge for each agent edit, in its writer's + * color, so an edit below the fold is seen. Placed by line fraction: no + * layout read, redrawn only when the edits change. */ +const scrollTicks = ViewPlugin.fromClass( + class { + rail: HTMLElement | null = null; + constructor(readonly view: EditorView) { + this.draw(); + } + update(u: ViewUpdate) { + if (u.startState.field(agentMarksField).edits !== u.state.field(agentMarksField).edits) this.draw(); + } + draw() { + const { edits } = this.view.state.field(agentMarksField); + const doc = this.view.state.doc; + if (!edits.length) { + this.rail?.remove(); + this.rail = null; + return; + } + if (!this.rail) { + this.rail = document.createElement("div"); + this.rail.className = "cm-agentTicks"; + this.rail.setAttribute("aria-hidden", "true"); + this.view.dom.append(this.rail); + } + const ticks: HTMLElement[] = []; + for (const e of edits) { + const [a, b] = lineSpan(doc, e); + const tick = document.createElement("div"); + tick.className = "cm-agentTick"; + tick.style.top = `${((a - 1) / doc.lines) * 100}%`; + tick.style.height = `max(2px, ${((b - a + 1) / doc.lines) * 100}%)`; + tick.style.setProperty("--agent-c", e.color); + ticks.push(tick); + } + this.rail.replaceChildren(...ticks); + } + destroy() { + this.rail?.remove(); + } }, -}); +); const theme = EditorView.baseTheme({ "@keyframes cm-agent-fade": { @@ -410,10 +483,25 @@ const theme = EditorView.baseTheme({ }, ".cm-agentFlash": { animation: `cm-agent-fade ${EDIT_FLASH_MS}ms ease-out forwards` }, ".cm-agentQuoted": { animation: `cm-agent-fade ${QUOTE_FLASH_MS}ms ease-out forwards` }, - ".cm-agentGutter": { width: "3px", minWidth: "3px" }, - ".cm-agentGutter .cm-gutterElement": { padding: "0 !important", cursor: "pointer" }, - ".cm-agentBar": { width: "3px", height: "100%", backgroundColor: "var(--agent-c)", borderRadius: "1px" }, + // Zero wide, drawn over the git bar (gitTheme.ts: 3px at 2px in the next + // column), above it. + ".cm-gutters .cm-agentGutter": { width: "0", minWidth: "0", overflow: "visible", position: "relative", zIndex: 1 }, + ".cm-agentGutter .cm-gutterElement": { padding: "0 !important", position: "relative" }, + ".cm-agentBar": { position: "absolute", left: "2px", top: 0, bottom: 0, width: "3px", backgroundColor: "var(--agent-c)", borderRadius: "1px", cursor: "pointer" }, + ".cm-agentBar:hover": { width: "5px", left: "1px" }, ".cm-agentSent": { backgroundColor: "color-mix(in srgb, var(--agent-c) 9%, transparent)" }, + ".cm-agentTicks": { position: "absolute", top: 0, bottom: 0, right: 0, width: "3px", pointerEvents: "none", zIndex: 3 }, + ".cm-agentTick": { position: "absolute", right: 0, width: "3px", backgroundColor: "var(--agent-c)", opacity: 0.8 }, + ".cm-agentSentDot": { + display: "inline-block", + width: "6px", + height: "6px", + marginRight: "0.5em", + borderRadius: "50%", + verticalAlign: "middle", + boxShadow: "inset 0 0 0 1px color-mix(in srgb, var(--agent-c) 60%, var(--sol-text-dim))", + }, + "[data-sent-state=working] .cm-agentSentDot": { backgroundColor: "var(--agent-c)", boxShadow: "none" }, ".cm-agentSentNote": { marginLeft: "1.5em", fontSize: "0.85em", @@ -423,10 +511,19 @@ const theme = EditorView.baseTheme({ pointerEvents: "auto", }, ".cm-agentInline": { padding: "4px 0 6px" }, + // The edits status item (feature.ts): bar and count in the writer's color. + ".cm-agent-edits": { display: "inline-flex", alignItems: "center", gap: "2px" }, + ".cm-agent-edits[hidden]": { display: "none" }, + ".cm-agent-edits button": { font: "inherit", background: "none", border: "none", padding: "0 3px", borderRadius: "3px", cursor: "pointer", color: "var(--agent-c)" }, + ".cm-agent-edits button:hover": { background: "var(--sol-bg-alt)" }, + ".cm-agent-editsNext": { display: "inline-flex", alignItems: "center", gap: "5px", fontVariantNumeric: "tabular-nums" }, + ".cm-agent-editsBar": { width: "3px", height: "11px", borderRadius: "1px", backgroundColor: "var(--agent-c)" }, + ".cm-agent-editsClear": { opacity: "0.6", color: "var(--sol-text-dim) !important" }, + ".cm-agent-editsClear:hover": { opacity: "1" }, }); export function agentMarksExtension(): Extension { - return [agentMarksField, markExternalChanges, decorations, gutterSlot.of([]), gutterHider, flashTimer, escapeDismisses, theme]; + return [agentMarksField, markExternalChanges, decorations, gutterSlot.of([]), gutterHider, flashTimer, scrollTicks, theme]; } // ── verbs ────────────────────────────────────────────────────────────────── diff --git a/packages/web/lib/code/agent/feature.ts b/packages/web/lib/code/agent/feature.ts index c350e08515..14ab90fb01 100644 --- a/packages/web/lib/code/agent/feature.ts +++ b/packages/web/lib/code/agent/feature.ts @@ -1,7 +1,9 @@ // The agent integration inside the editor chunk: the marks extension, the // Cmd-L / Cmd-K keys, the status bar chip's host, and the commands // (agent.quoteSelection, agent.inlineInstruction, agent.newSession, -// agent.nextEdit / prevEdit, agent.pickSession, agent.dismissEdits). +// agent.nextEdit / prevEdit, agent.pickSession, agent.dismissEdits), and the +// edits status item (how many agent edits the buffer holds, in the writer's +// color: a press steps to the next, its × clears them). // Registered once from the editor core (editorHost.registerCoreFeatures). // // The linked session is resolved by AgentLayer (components/code/agent), which @@ -13,9 +15,9 @@ import { useInboxStore, sessionWorkState, type InboxSession } from "../../../sto import { useCodeStore } from "../../../store/codeStore"; import { codeBuffers, currentState, updateBuffer } from "../buffers"; import { registerCodeCommands, type CodeCommandContext } from "../commands"; -import { featureContext, focusedEditorView, registerEditorFeature, registerStatusItem, type StatusItemView } from "../features"; +import { featureContext, focusedEditorView, nameStatusItem, registerEditorFeature, registerStatusItem, type StatusItemView } from "../features"; import { inlineDraft, useAgentStore, joinRoot } from "./agentStore"; -import { codeQuoteComment, fenceLang, newSessionText, type CodeRange } from "./compose"; +import { codeQuoteComment, fenceLang, newSessionText, sendInstruction, type CodeRange } from "./compose"; import { QUOTE_FLASH_MS, addFlash, @@ -27,10 +29,15 @@ import { hasAgentMarks, setAgentMarkHooks, setInlineSpot, + setSentState, stepAgentEdit, + type SentMark, } from "./editorMarks"; import { composeInVault, sessionRow, vaultRootOf, writerNow } from "./live"; -import { sessionColor, sessionShortTitle, UNKNOWN_WRITER_COLOR } from "./sessions"; +import { blameSessionBases, sessionColor, sessionGitRefs, sessionShortTitle, UNKNOWN_WRITER_COLOR } from "./sessions"; +import { addGitDiffTargets, type GitDiffTarget } from "../git"; +import { blameHunksOf } from "../blame"; +import { useDiffViewerStore } from "../../../store/diffViewerStore"; const FEATURE = "agent"; /** Lines of context kept around a quoted range for its comment anchor. */ @@ -163,9 +170,7 @@ export function openInlineInstruction(view: EditorView, sessionId: string | null // The spot's range has mapped through every edit since the box opened // (an agent edit above it, the person's typing). const spot = agentMarks(holder.state).inline!; - const row = sessionRow(target); - const mark = { from: spot.from, to: spot.to, key: clientId, sessionId: target, color: sessionColor(row ?? target), label: sessionShortTitle(row) }; - holder.apply({ effects: [setInlineSpot.of(null), addSentMark.of(mark)] }); + holder.apply({ effects: [setInlineSpot.of(null), addSentMark.of(sentMark(spot, target, clientId))] }); watchTurn(target, clientId); if (holder.state === view.state) view.focus(); }, @@ -181,6 +186,28 @@ export function openInlineInstruction(view: EditorView, sessionId: string | null return true; } +/** The marker for a range sent to `target` as message `clientId`. */ +function sentMark(range: { from: number; to: number }, target: string, clientId: string): SentMark { + const row = sessionRow(target); + return { from: range.from, to: range.to, key: clientId, sessionId: target, color: sessionColor(row ?? target), label: sessionShortTitle(row), state: "queued" }; +} + +/** Send `text` about the range to `sessionId` now, with no box: `:Ask fix + * this` typed whole on the command line. The marker and its turn watch are + * the box's own (sentMark, watchTurn). */ +export function askNow(view: EditorView, sessionId: string, text: string): boolean { + const vaultId = vaultOf(view); + const root = vaultId ? vaultRootOf(vaultId) : null; + const range = root ? selectedRange(view, root) : null; + if (!range) return false; + const clientId = sendInstruction(useInboxStore.getState(), sessionId, range, text); + if (!clientId) return false; + view.dispatch({ effects: addSentMark.of(sentMark(lineBounds(view, range), sessionId, clientId)) }); + watchTurn(sessionId, clientId); + leaveVisual(view); + return true; +} + export function newSession(view: EditorView): boolean { const vaultId = vaultOf(view); const root = vaultId ? vaultRootOf(vaultId) : null; @@ -214,12 +241,15 @@ const QUICK_TURN_MS = 60_000; const watched = new Map(); let unwatch: (() => void) | null = null; -function clearSentEverywhere(clientId: string): void { +/** Apply an effect to every buffer holding the sent message's marker. */ +function forSentMark(clientId: string, effect: () => TransactionSpec["effects"]): void { for (const b of codeBuffers.all()) { - if (agentMarks(currentState(b)).sent.some((s) => s.key === clientId)) updateBuffer(b, { effects: clearSentMarks.of(clientId) }); + if (agentMarks(currentState(b)).sent.some((s) => s.key === clientId)) updateBuffer(b, { effects: effect() }); } } +const clearSentEverywhere = (clientId: string) => forSentMark(clientId, () => clearSentMarks.of(clientId)); + type InboxState = ReturnType; /** The agent has the message: its echo is in the transcript, or its pending @@ -246,8 +276,10 @@ export function checkSentTurns(s: InboxState = useInboxStore.getState(), now = D } const row = s.sessions[sid] as InboxSession | undefined; const working = !!row && sessionWorkState(row, now) === "working"; - if (working) w.seenWorking = true; - else if (w.seenWorking || now - w.deliveredAt > QUICK_TURN_MS) { + if (working) { + if (!w.seenWorking) forSentMark(clientId, () => setSentState.of({ key: clientId, state: "working" })); + w.seenWorking = true; + } else if (w.seenWorking || now - w.deliveredAt > QUICK_TURN_MS) { watched.delete(clientId); clearSentEverywhere(clientId); } @@ -289,6 +321,54 @@ function chipItem(view: EditorView): StatusItemView | null { }; } +// ── agent edits status item ─────────────────────────────────────────────── + +/** How many agent edits the buffer holds, as a bar in the latest writer's + * color and a count. A press steps to the next; × clears them all. Hidden + * while there are none. Rewritten only when the count or color changes, so + * typing (which maps the edits) writes nothing. */ +export function editsItem(view: EditorView): StatusItemView | null { + const dom = document.createElement("span"); + dom.className = "cm-agent-edits"; + dom.hidden = true; + const next = document.createElement("button"); + next.type = "button"; + next.className = "cm-agent-editsNext"; + const bar = document.createElement("span"); + bar.className = "cm-agent-editsBar"; + const count = document.createTextNode("0"); + next.append(bar, count); + next.onclick = () => { + stepAgentEdit(view, 1); + view.focus(); + }; + const clear = document.createElement("button"); + clear.type = "button"; + clear.className = "cm-agent-editsClear"; + clear.title = "Clear agent edits"; + clear.setAttribute("aria-label", "Clear agent edits"); + clear.textContent = "×"; + clear.onclick = () => { + view.dispatch({ effects: dismissAgentEdits.of("all") }); + view.focus(); + }; + dom.append(next, clear); + let shown = ""; + const render = (state: EditorState) => { + const { edits } = agentMarks(state); + const color = edits.length ? edits.reduce((a, b) => (b.from > a.from ? b : a)).color : ""; + const sig = `${edits.length}|${color}`; + if (sig === shown) return; + shown = sig; + dom.hidden = edits.length === 0; + count.nodeValue = String(edits.length); + nameStatusItem(next, `${edits.length} agent edits, go to next`, "Next agent edit"); + dom.style.setProperty("--agent-c", color); + }; + render(view.state); + return { dom, update: (u) => void (agentMarks(u.startState).edits !== agentMarks(u.state).edits && render(u.state)) }; +} + // ── a disk change waiting on unsaved edits: who wrote it ────────────────── function watchConflicts(): void { @@ -300,7 +380,7 @@ function watchConflicts(): void { const before = prev.conflicts[key]; if (now === before) continue; if (!now) agent.setConflictWriter(key, null); - else if (now.kind === "stale" && before?.kind !== "stale" && before?.kind !== "merge") { + else if ((now.kind === "stale" || now.kind === "merge") && before?.kind !== "stale" && before?.kind !== "merge") { const [vaultId, path] = key.split("\u0000"); agent.setConflictWriter(key, writerNow(vaultId, path)); } @@ -310,14 +390,41 @@ function watchConflicts(): void { // ── registration ─────────────────────────────────────────────────────────── -/** Cmd-L and Cmd-K. Exported for mount tests. */ +/** Cmd-L and Cmd-K, and Alt-F6 / Shift-Alt-F6 to step through agent edits, + * beside the git hunk pair on Alt-F5 (vim has ]a / [a). Cmd-Alt-arrows stay + * the workspace's focus moves. Exported for mount tests. */ export const agentKeys = Prec.high( keymap.of([ { key: "Mod-l", preventDefault: true, run: quoteToLinked }, { key: "Mod-k", preventDefault: true, run: (v) => openInlineInstruction(v, linkedOf(v)) }, + { key: "Alt-F6", preventDefault: true, run: (v) => stepAgentEdit(v, 1) }, + { key: "Shift-Alt-F6", preventDefault: true, run: (v) => stepAgentEdit(v, -1) }, ]), ); +/** + * The diff picker's session refs: the linked session's base (the parent of + * its first commit, from the changes the diff panel holds for it: the same + * refs the panel's Edit opens, sessionGitRefs) and the base of every other + * session the file's blame names, each in the session's color. A session + * that has committed nothing stands on HEAD, which the picker lists already. + */ +export function sessionDiffTargets(vaultId: string, state: EditorState): GitDiffTarget[] { + const out: GitDiffTarget[] = []; + const target = (id: string, ref: string, title?: string): GitDiffTarget => { + const row = sessionRow(id); + return { ref, label: `${row ? sessionShortTitle(row) : (title ?? "Session")} base`, color: sessionColor(row ?? id) }; + }; + const linked = useAgentStore.getState().links[vaultId]?.sessionId ?? null; + const panel = useDiffViewerStore.getState(); + if (linked && panel.conversationId === linked) { + const { base } = sessionGitRefs(panel.changes); + if (base && base !== "HEAD") out.push(target(linked, base)); + } + for (const [id, b] of blameSessionBases(blameHunksOf(state))) if (id !== linked) out.push(target(id, b.ref, b.title)); + return out; +} + let registered = false; export function registerAgentFeature(): void { @@ -331,7 +438,9 @@ export function registerAgentFeature(): void { }); registerEditorFeature(FEATURE, () => [agentMarksExtension(), agentKeys], { needsVault: true }); registerStatusItem({ id: "agent.link", side: "right", order: 5, priority: 60, needsVault: true, create: chipItem }); + registerStatusItem({ id: "agent.edits", side: "right", order: 4, priority: 65, needsVault: true, create: (v) => (hasAgentMarks(v.state) ? editsItem(v) : null) }); watchConflicts(); + addGitDiffTargets(({ vaultId, state }) => sessionDiffTargets(vaultId, state)); const withView = (fn: (view: EditorView, args: Record | undefined) => boolean) => (args: Record | undefined, ctx: CodeCommandContext) => { const view = viewFor(ctx); @@ -339,7 +448,14 @@ export function registerAgentFeature(): void { }; registerCodeCommands({ "agent.quoteSelection": withView(quoteToLinked), - "agent.inlineInstruction": withView((v, args) => openInlineInstruction(v, linkedOf(v), typeof args?.text === "string" ? args.text : "")), + // With the instruction already typed (`:Ask fix this`) and a session + // linked, it goes at once; otherwise the box opens with it filled in. + "agent.inlineInstruction": withView((v, args) => { + const text = typeof args?.text === "string" ? args.text : ""; + const linked = linkedOf(v); + if (text.trim() && linked) return askNow(v, linked, text); + return openInlineInstruction(v, linked, text); + }), "agent.newSession": withView((v) => newSession(v)), "agent.nextEdit": withView((v) => stepAgentEdit(v, 1)), "agent.prevEdit": withView((v) => stepAgentEdit(v, -1)), diff --git a/packages/web/lib/code/agent/live.ts b/packages/web/lib/code/agent/live.ts index 7987eb34ea..b2d4c781e6 100644 --- a/packages/web/lib/code/agent/live.ts +++ b/packages/web/lib/code/agent/live.ts @@ -143,8 +143,8 @@ export interface VaultAgentState { /** The picker's sessions for a place. Every candidate works in a folder * holding the root, so it overlaps it. */ -export function placeCandidates(s: InboxState, place: VaultPlace): AgentSessionRow[] { - return candidateSessions(overlapping(s, place), place.root, place.machine, viewerId(s)); +export function placeCandidates(s: InboxState, place: VaultPlace, limit?: number): AgentSessionRow[] { + return candidateSessions(overlapping(s, place), place.root, place.machine, viewerId(s), limit); } /** Everything AgentLayer keeps current for one vault. */ diff --git a/packages/web/lib/code/agent/sessions.ts b/packages/web/lib/code/agent/sessions.ts index abd531761b..c8bce7e347 100644 --- a/packages/web/lib/code/agent/sessions.ts +++ b/packages/web/lib/code/agent/sessions.ts @@ -118,7 +118,8 @@ export function candidateSessions(rows: Iterable, * (/conversation/, the stage's own rule), an inbox deep link * (/inbox?s=), or the bare inbox showing the focused conversation. */ export function sessionOfPanePath(path: string, currentSessionId: string | null): string | null { - const direct = directConversationId(path) ?? inboxTabSessionId(path); + // A pane opened at a message (`/conversation/#msg-`) is still that conversation. + const direct = directConversationId(path.replace(/#msg-[^#]*$/, "")) ?? inboxTabSessionId(path); if (direct) return direct; const pathname = path.split("?")[0]; return pathname === "/inbox" || pathname.startsWith("/inbox/") ? currentSessionId : null; @@ -181,6 +182,15 @@ export function resolveLink(opts: { return first ? { sessionId: first._id, source: "folder" } : { sessionId: null, source: "none" }; } +/** The picker's filter: every word of the query appears in the session's + * title or short title, ignoring case. An empty query matches all. */ +export function matchesSessionQuery(s: Pick, query: string): boolean { + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + if (!words.length) return true; + const hay = `${s.short_title ?? ""} ${s.title ?? ""}`.toLowerCase(); + return words.every((w) => hay.includes(w)); +} + /** What a session is called in tight chrome. */ export function sessionShortTitle(s: Pick | null | undefined): string { const raw = (s?.short_title || s?.title || "").replace(/<[^>]+>/g, " ").replace(/\s+/g, " ").trim(); @@ -190,8 +200,15 @@ export function sessionShortTitle(s: Pick h !== "var(--sol-green)" && h !== "var(--sol-red)" && h !== "var(--sol-blue)", +); + /** A session's color: its own icon color when it has one, else a stable hue - * from the palette session blame uses. */ + * from EDITOR_SESSION_HUES. */ export function sessionColor(s: Pick | string | null | undefined): string { if (!s) return "var(--sol-text-dim)"; const row = typeof s === "string" ? { _id: s } : s; @@ -202,8 +219,52 @@ export function sessionColor(s: Pick | st } let h = 0; for (let i = 0; i < row._id.length; i++) h = (h * 31 + row._id.charCodeAt(i)) >>> 0; - return SESSION_BLAME_HUES[h % SESSION_BLAME_HUES.length]; + return EDITOR_SESSION_HUES[h % EDITOR_SESSION_HUES.length]; } /** The neutral color of an edit no session can be named for. */ export const UNKNOWN_WRITER_COLOR = "var(--sol-text-muted)"; + +// ── the session's git refs ────────────────────────────────────────────────── + +/** A session's change as the diff panel holds it: a commit carries its hash + * when the commit's output named one. */ +export interface SessionChangeRef { + changeType: string; + commitHash?: string; +} + +/** + * The git refs a session's own work stands on, from its commits in order: + * `base` is where its work starts (the parent of its first commit; HEAD while + * it has committed nothing, so all its work is uncommitted) and `last` is its + * last commit. A commit whose hash went unrecorded leaves that ref null, and + * the caller falls back. Read off the session's own commits, never the + * branch's: on a trunk checkout other sessions' commits sit beside its own. + */ +export function sessionGitRefs(changes: readonly SessionChangeRef[]): { committed: boolean; base: string | null; last: string | null } { + const commits = changes.filter((c) => c.changeType === "commit"); + if (!commits.length) return { committed: false, base: "HEAD", last: null }; + const hash = (c: SessionChangeRef | undefined) => (c?.commitHash && /^[0-9a-f]{7,64}$/i.test(c.commitHash) ? c.commitHash : null); + const first = hash(commits[0]); + return { committed: true, base: first ? `${first}^` : null, last: hash(commits[commits.length - 1]) }; +} + +/** + * The base of each session that wrote committed lines of a file, from the + * file's blame: the parent of the session's oldest commit still standing in + * it, keyed by the session's full conversation id (its short one when that + * is all the blame carries). Lines a session wrote but has not committed + * name no commit and count for nothing here. + */ +export function blameSessionBases(hunks: readonly { sha?: string; time?: number; uncommitted?: boolean; session?: { id: string; conversation_id?: string; title?: string } }[]): Map { + const oldest = new Map(); + for (const h of hunks) { + if (!h.session || h.uncommitted || !h.sha || !/^[0-9a-f]{7,64}$/i.test(h.sha)) continue; + const id = h.session.conversation_id ?? h.session.id; + const time = h.time ?? Number.MAX_SAFE_INTEGER; + const was = oldest.get(id); + if (!was || time < was.time) oldest.set(id, { sha: h.sha, time, title: h.session.title }); + } + return new Map([...oldest].map(([id, o]) => [id, { ref: `${o.sha}^`, title: o.title }])); +} diff --git a/packages/web/lib/code/blame/__tests__/actions.test.ts b/packages/web/lib/code/blame/__tests__/actions.test.ts index cfc9c56e10..bb169ebb24 100644 --- a/packages/web/lib/code/blame/__tests__/actions.test.ts +++ b/packages/web/lib/code/blame/__tests__/actions.test.ts @@ -6,7 +6,7 @@ let stageOpens = false; const calls: string[] = []; mock.module("../../../stage", () => ({ - sessionPanePath: (id: string) => `/conversation/${id}`, + sessionPanePath: (id: string, msg?: string | null) => `/conversation/${id}${msg ? `#msg-${msg}` : ""}`, openBeside: (p: string) => { calls.push(`beside ${p}`); return stageOpens; }, })); mock.module("../../../openSessionAtMessage", () => ({ @@ -17,7 +17,7 @@ mock.module("../../../openIntent", () => ({ navigateHere: (p: string) => { calls.push(`go ${p}`); }, })); -const { openBlameMessage, openBlameSession, openConversationHere } = await import("../actions"); +const { openBlameSession, openConversationHere } = await import("../actions"); const session = { conversation_id: "c1", message_id: "m1" } as never; const noMessage = { conversation_id: "c1" } as never; @@ -25,32 +25,23 @@ const noMessage = { conversation_id: "c1" } as never; beforeEach(() => { calls.length = 0; path = "/files"; stageOpens = false; }); describe("blame actions", () => { - test("At message from the editor page follows the deep link, leaving no request in the store", () => { - expect(openBlameMessage(session)).toBe(true); - expect(calls).toEqual(["go /conversation/c1#msg-m1"]); - }); - - test("At message on a thread route uses the store's navigate request", () => { - path = "/inbox"; - openBlameMessage(session); - expect(calls).toEqual(["store c1 m1"]); - }); - - test("At message without a message id or conversation does nothing", () => { - expect(openBlameMessage(noMessage)).toBe(false); - expect(openBlameMessage(undefined)).toBe(false); - expect(calls).toEqual([]); - }); - - test("the bar opens the session beside the editor when the stage has room", () => { + test("the bar opens the session beside the editor, at the message that made the edit", () => { stageOpens = true; expect(openBlameSession(session)).toBe(true); + expect(calls).toEqual(["beside /conversation/c1#msg-m1"]); + calls.length = 0; + openBlameSession(noMessage); expect(calls).toEqual(["beside /conversation/c1"]); }); test("with no room beside, the bar opens the conversation in the main view at the message", () => { openBlameSession(session); - expect(calls).toEqual(["beside /conversation/c1", "go /conversation/c1#msg-m1"]); + expect(calls).toEqual(["beside /conversation/c1#msg-m1", "go /conversation/c1#msg-m1"]); + }); + + test("nothing to open without a conversation", () => { + expect(openBlameSession(undefined)).toBe(false); + expect(calls).toEqual([]); }); test("with no message id, the main view opens the conversation itself", () => { diff --git a/packages/web/lib/code/blame/__tests__/feature.mount.test.ts b/packages/web/lib/code/blame/__tests__/feature.mount.test.ts index c795990967..ea04f95f1d 100644 --- a/packages/web/lib/code/blame/__tests__/feature.mount.test.ts +++ b/packages/web/lib/code/blame/__tests__/feature.mount.test.ts @@ -10,12 +10,14 @@ installEditorDom(); localStorage.removeItem("codecast.code.blameGutter"); import type { CodeBlameHunk } from "@codecast/shared/contracts"; +import { Text } from "@codemirror/state"; let repo = true; let hunks: CodeBlameHunk[] = []; const calls = { blame: 0, status: 0 }; let statusFails = false; let blameFails: Error | null = null; +let blameHold: Promise | null = null; const realClient = { ...(await import("../../daemonClient")) }; mock.module("../../daemonClient", () => ({ @@ -28,6 +30,7 @@ mock.module("../../daemonClient", () => ({ fetchGitBase: async (_ep: unknown, _v: string, path: string) => ({ path, ref: "HEAD", exists: true, content: "" }), fetchBlame: async (_ep: unknown, _v: string, path: string) => { calls.blame++; + if (blameHold) await blameHold; if (blameFails) throw blameFails; return { path, hunks }; }, @@ -37,7 +40,7 @@ const { useVaultStore } = await import("../../../../store/vaultStore"); const { EditorHost, openCodeBuffer } = await import("../../editorHost"); const { runCodeCommand } = await import("../../commands"); const { refreshGitStatus, useGitStatusStore } = await import("../../git/status"); -const { setSavedDoc, codeBuffers, bufferKey } = await import("../../buffers"); +const { setSavedDoc, savedDocField, codeBuffers, bufferKey } = await import("../../buffers"); const { setEditorSetting } = await import("../../editorSettings"); const { _clearBlameCache } = await import("../data"); const blame = await import("../gutter"); @@ -147,6 +150,54 @@ test("a save asks again, and an edited buffer's unsaved lines start uncommitted" ]); }); +test("an agent writing the open file: one blame in flight, none while the page is hidden", async () => { + const buffer = codeBuffers.get(bufferKey("v1", "src/a.ts"))!; + // A write the buffer took in: a new saved version, same text, so the tests + // after this one see the document they expect. + const write = (etag: string) => { + buffer.baseEtag = etag; + view.dispatch({ effects: setSavedDoc.of(Text.of(view.state.doc.toJSON())) }); + }; + const wait = (ms: number) => new Promise((r) => setTimeout(r, ms)); + const saved = { doc: view.state.field(savedDocField), etag: buffer.baseEtag }; + let release!: () => void; + blameHold = new Promise((r) => (release = r)); + const before = calls.blame; + // Five writes, each past the refetch delay, while the first blame is held. + for (let i = 0; i < 5; i++) { + write(`agent-${i}`); + await wait(450); + } + expect(calls.blame - before).toBe(1); + blameHold = null; + release(); + await until(() => calls.blame - before === 2, "the one follow-up"); + await wait(450); + expect(calls.blame - before).toBe(2); + + let visibility = "hidden"; + Object.defineProperty(document, "visibilityState", { configurable: true, get: () => visibility }); + try { + const hiddenFrom = calls.blame; + write("agent-hidden-1"); + await wait(450); + write("agent-hidden-2"); + await wait(450); + expect(calls.blame).toBe(hiddenFrom); + visibility = "visible"; + document.dispatchEvent(new Event("visibilitychange")); + await until(() => calls.blame === hiddenFrom + 1, "the refetch on show"); + await wait(450); + expect(calls.blame).toBe(hiddenFrom + 1); + } finally { + delete (document as { visibilityState?: unknown }).visibilityState; + } + // Back to the version the tests after this one start from. + buffer.baseEtag = saved.etag; + view.dispatch({ effects: setSavedDoc.of(saved.doc) }); + await until(() => runsView()[0]?.[2] === "edited", "restored"); +}); + test("inline blame follows the cursor without React", async () => { setEditorSetting("inlineBlame", true); await until(() => !!view.dom.querySelector(".cm-blame-inline") || view.state.selection.main.head > 0, "inline on"); diff --git a/packages/web/lib/code/blame/__tests__/model.test.ts b/packages/web/lib/code/blame/__tests__/model.test.ts index da36bec16d..b4c05ca2e9 100644 --- a/packages/web/lib/code/blame/__tests__/model.test.ts +++ b/packages/web/lib/code/blame/__tests__/model.test.ts @@ -1,12 +1,12 @@ // Session blame's model: hunks placed on the document, carried through edits // (vim's dd, o, J, typing inside a line, Enter mid-line), the runs the gutter // draws, and the labels on them. +import { sessionColor } from "../../agent/sessions"; import { describe, expect, test } from "bun:test"; import { EditorState, type TransactionSpec } from "@codemirror/state"; import type { CodeBlameHunk } from "@codecast/shared/contracts"; import { NEUTRAL_HUE, - SESSION_BLAME_HUES, UNCOMMITTED_LABEL, blameRuns, hueOf, @@ -218,11 +218,14 @@ describe("labels", () => { expect(inlineText("edited", null, now)).toBe(UNCOMMITTED_LABEL); }); - test("colors rank sessions by lines written; lines without one are neutral", () => { + test("each session takes its own color, the one live edits use; lines without one are neutral", () => { const big = { ...B, start: 6, end: 20, session: { id: "jx7cccc", conversation_id: "conv-c", title: "Big" } }; - const hues = sessionHues([A, B, C, big]); - expect(hueOf(big, hues)).toBe(SESSION_BLAME_HUES[0]); - expect(hueOf(A, hues)).toBe(SESSION_BLAME_HUES[1]); + const hues = sessionHues([A, B, C, big], (id) => (id === "conv-c" ? "magenta" : undefined)); + expect(hueOf(big, hues)).toBe(sessionColor({ _id: "conv-c", icon_color: "magenta" })); + expect(hueOf(big, hues)).toBe("var(--sol-magenta)"); + // Whatever else is in the file, a session keeps its color. + expect(hueOf(A, hues)).toBe(sessionColor(A.session!.conversation_id ?? A.session!.id)); + expect(hueOf(A, sessionHues([A]))).toBe(hueOf(A, hues)); expect(hueOf(B, hues)).toBe(NEUTRAL_HUE); expect(hueOf(null, hues)).toBe(NEUTRAL_HUE); }); diff --git a/packages/web/lib/code/blame/actions.ts b/packages/web/lib/code/blame/actions.ts index a49e2435dd..45e57584f1 100644 --- a/packages/web/lib/code/blame/actions.ts +++ b/packages/web/lib/code/blame/actions.ts @@ -26,22 +26,15 @@ export function openConversationHere(conversationId: string, messageId?: string } /** - * Open the session beside the editor. A stage pane opens a conversation at - * its latest turn; where the stage has no room, the conversation opens in - * the main view, at the message that made the edit when it is known. + * Open the conversation that wrote a line beside the editor, scrolled to the + * message that made the edit when it is known (a pane already showing that + * conversation moves to it). Where the stage has no room, the conversation + * opens in the main view at that message. */ export function openBlameSession(session: CodeBlameSession | undefined): boolean { const id = blameConversationId(session); if (!id) return false; - if (openBeside(sessionPanePath(id))) return true; + if (openBeside(sessionPanePath(id, session?.message_id))) return true; openConversationHere(id, session?.message_id); return true; } - -/** Go to the message that made the edit, in the main view. */ -export function openBlameMessage(session: CodeBlameSession | undefined): boolean { - const id = blameConversationId(session); - if (!id || !session?.message_id) return false; - openConversationHere(id, session.message_id); - return true; -} diff --git a/packages/web/lib/code/blame/gutter.ts b/packages/web/lib/code/blame/gutter.ts index f16d3da861..c4061db108 100644 --- a/packages/web/lib/code/blame/gutter.ts +++ b/packages/web/lib/code/blame/gutter.ts @@ -11,11 +11,13 @@ import { ChangeSet, Facet, Prec, RangeSet, RangeSetBuilder, StateEffect, StateFi import { Decoration, EditorView, GutterMarker, ViewPlugin, WidgetType, gutter, type DecorationSet, type ViewUpdate } from "@codemirror/view"; import type { CodeBlameHunk, CodeBlameResponse } from "@codecast/shared/contracts"; import { useVaultStore } from "../../../store/vaultStore"; +import { useInboxStore } from "../../../store/inboxStore"; import { bufferKey, codeBuffers, savedDocField } from "../buffers"; import { featureContext } from "../features"; import { lineChanges, loadMergeKit } from "../merge"; -import { BLAME_GUTTER_COLUMN } from "../gutterSlots"; +import { BLAME_EDITOR_CONTAINER, BLAME_GUTTER_COLUMN, BLAME_NARROW, BLAME_NARROW_COLUMN } from "../gutterSlots"; import { ensureGitStatus, useGitStatusStore } from "../git/status"; +import { whenVisible } from "../idle"; import { NOT_CONNECTED, blameAvailability, blameFailure, blameKey, forgetBlame, loadBlame } from "./data"; import { closeBlameHover, hoverBlameRun, hoverStays, leaveBlameHover, pinBlameRun } from "./hover"; import { openBlameSession } from "./actions"; @@ -39,6 +41,9 @@ import { type RunKind, } from "./model"; +/** A session's own icon color, when the inbox holds its row. */ +const iconColorOf = (id: string): string | undefined => (useInboxStore.getState().sessions[id] as { icon_color?: string } | undefined)?.icon_color; + export type BlameStatus = "idle" | "loading" | "ready" | "unavailable"; export interface BlameValue { @@ -211,7 +216,7 @@ export const blameField = StateField.define({ } else if (e.is(setData)) { next = deriveBlame( - { ...EMPTY, status: "ready", key: e.value.key, hunks: e.value.hunks, placed: e.value.placed, edits: e.value.edits, hues: sessionHues(e.value.hunks) }, + { ...EMPTY, status: "ready", key: e.value.key, hunks: e.value.hunks, placed: e.value.placed, edits: e.value.edits, hues: sessionHues(e.value.hunks, iconColorOf) }, tr.state.doc, ); } else if (e.is(rederive) && (next.stale || (e.value.force && next.status === "ready"))) next = deriveBlame(next, tr.state.doc); @@ -275,6 +280,11 @@ const AGE_REFRESH_MS = 10 * 60_000; const runner = ViewPlugin.fromClass( class { private refetchTimer: ReturnType | null = null; + private cancelVisible: (() => void) | null = null; + /** One blame request at a time per editor: versions that move while one + * runs cost one more request after it, for the newest version. */ + private inflight = false; + private again: { fresh: boolean } | null = null; private settleTimer: ReturnType | null = null; private retryTimer: ReturnType | null = null; private failures = 0; @@ -320,11 +330,18 @@ const runner = ViewPlugin.fromClass( }); } + /** A save or an agent's write moved the version: ask again once writes + * pause, and not while the page is hidden (a blame costs the daemon a + * `git blame` of the whole file). */ private refetchSoon() { if (this.refetchTimer) clearTimeout(this.refetchTimer); this.refetchTimer = setTimeout(() => { this.refetchTimer = null; - this.kick(true); + if (this.cancelVisible) return; + this.cancelVisible = whenVisible(() => { + this.cancelVisible = null; + this.kick(true); + }); }, REFETCH_MS); } @@ -382,17 +399,31 @@ const runner = ViewPlugin.fromClass( const key = blameKey(ctx.vaultId, ctx.path, etag, head); const v = this.view.state.field(blameField); if (v.key === key && (v.status === "ready" || v.status === "loading") && !fresh) return; + if (this.inflight) { + this.again = { fresh: fresh || !!this.again?.fresh }; + return; + } if (fresh) forgetBlame(key); if (v.key !== key || v.status !== "ready") this.dispatchSoon(setLoading.of(key)); - loadBlame(key, ctx.vaultId, ctx.path).then( - (res) => void this.land(key, res), - (e: unknown) => { - if (!this.current(key)) return; - const { reason, transient } = blameFailure(e); - if (transient) this.failSoftly(null, reason); - else this.dispatchSoon(setUnavailable.of({ key, reason })); - }, - ); + this.inflight = true; + loadBlame(key, ctx.vaultId, ctx.path) + .then( + (res) => this.land(key, res), + (e: unknown) => { + if (!this.current(key)) return; + const { reason, transient } = blameFailure(e); + if (transient) this.failSoftly(null, reason); + else this.dispatchSoon(setUnavailable.of({ key, reason })); + }, + ) + // A broken land path still shows up, and the runner is freed either way. + .catch((e: unknown) => console.error("[blame] landing failed", e)) + .finally(() => { + this.inflight = false; + const next = this.again; + this.again = null; + if (next && !this.destroyed) this.kick(next.fresh); + }); } /** Still showing the file version `key` names. */ @@ -417,6 +448,7 @@ const runner = ViewPlugin.fromClass( destroy() { this.destroyed = true; if (this.refetchTimer) clearTimeout(this.refetchTimer); + this.cancelVisible?.(); if (this.settleTimer) clearTimeout(this.settleTimer); if (this.retryTimer) clearTimeout(this.retryTimer); this.offGit(); @@ -534,7 +566,9 @@ const HATCH = "repeating-linear-gradient(-45deg, var(--blame-hue) 0 1.5px, trans const blameTheme = EditorView.theme({ // A fixed column: labels truncate inside it, so nothing moves as lines // with longer or shorter names scroll past. + ...BLAME_EDITOR_CONTAINER, ".cm-blame-gutter": { ...BLAME_GUTTER_COLUMN, cursor: "default" }, + [BLAME_NARROW]: { ".cm-blame-gutter": BLAME_NARROW_COLUMN, ".cm-blame-name, .cm-blame-age": { display: "none" } }, ".cm-blame-gutter .cm-gutterElement": { position: "relative", overflow: "hidden", padding: "0" }, ".cm-blame-line": { cursor: "pointer" }, ".cm-blame-cell": { diff --git a/packages/web/lib/code/blame/index.ts b/packages/web/lib/code/blame/index.ts index 319872cfd7..cee9f6029f 100644 --- a/packages/web/lib/code/blame/index.ts +++ b/packages/web/lib/code/blame/index.ts @@ -7,6 +7,8 @@ // text and the fetch (gutter.ts) load the first time either turns on. import { EditorView } from "@codemirror/view"; +import type { EditorState } from "@codemirror/state"; +import type { CodeBlameHunk } from "@codecast/shared/contracts"; import { useVaultStore } from "../../../store/vaultStore"; import { registerCodeCommand } from "../commands"; import { editorSetting, onEditorSettingsChange } from "../editorSettings"; @@ -14,6 +16,7 @@ import { featureContext, reconfigureEditorFeature, registerEditorFeature, regist import { useGitStatusStore } from "../git/status"; import { blameAvailability } from "./data"; import { blameGutterStandIn } from "../gutterSlots"; +import { lineIcon } from "../icons"; type GutterModule = typeof import("./gutter"); @@ -33,6 +36,11 @@ function loadGutter(): Promise { return loading; } +/** The blame an editor holds, once its gutter or inline blame has read it. */ +export function blameHunksOf(state: EditorState): readonly CodeBlameHunk[] { + return gutterModule?.blameValue(state)?.hunks ?? []; +} + function readGutterOn(): boolean { try { return typeof localStorage !== "undefined" && localStorage.getItem(STORAGE_KEY) === "1"; @@ -91,8 +99,7 @@ export function blameRetryReason(view: EditorView): string | null { // ── status bar chip ───────────────────────────────────────────────────────── -const BLAME_SVG = - ''; +const BLAME_ICON = ''; const chipTheme = EditorView.theme({ ".cm-blame-chip": { padding: "0 6px", borderRadius: "3px" }, @@ -107,7 +114,7 @@ function blameChip(view: EditorView): StatusItemView { const dom = document.createElement("button"); dom.type = "button"; dom.className = "cm-blame-chip"; - dom.innerHTML = BLAME_SVG; + dom.append(lineIcon(BLAME_ICON)); dom.append(document.createTextNode("Blame")); dom.setAttribute("aria-label", "Session blame"); dom.onmousedown = (e) => e.preventDefault(); diff --git a/packages/web/lib/code/blame/model.ts b/packages/web/lib/code/blame/model.ts index 3a56381348..c36be2b1a2 100644 --- a/packages/web/lib/code/blame/model.ts +++ b/packages/web/lib/code/blame/model.ts @@ -13,7 +13,8 @@ import type { ChangeDesc, ChangeSet, Text } from "@codemirror/state"; import type { CodeBlameHunk } from "@codecast/shared/contracts"; import { relTimeShort, formatRelative } from "@codecast/shared/time"; -import { SESSION_BLAME_HUES, sessionBlameColors, summarizeSessionBlame, type SessionBlameRange } from "../../repoView"; +import { SESSION_BLAME_HUES } from "../../repoView"; +import { sessionColor } from "../agent/sessions"; /** A range of whole lines: from a line start to the next line's start (or the * document's end). */ @@ -209,6 +210,7 @@ export function runName(kind: RunKind, hunk: CodeBlameHunk | null): string { const s = hunk.session; if (s) return s.title?.trim() || `Session ${s.id}`; if (hunk.uncommitted) return UNCOMMITTED_LABEL; + if (hunk.sweep_sessions) return `${hunk.sweep_sessions} sessions`; return hunk.author?.trim() || hunk.sha?.slice(0, 7) || "Unknown"; } @@ -234,23 +236,20 @@ export function inlineText(kind: RunKind, hunk: CodeBlameHunk | null, now: numbe export const NEUTRAL_HUE = "var(--sol-text-dim)"; /** - * Session id to color for one file, the repo page's way: sessions ranked by - * how many lines they wrote, each taking the next accent (SESSION_BLAME_HUES). + * Session id to color for one file: each session's own color (sessionColor: + * its icon color, else a hue fixed by its id), the one every agent surface in + * the editor draws it in, so a line's blame bar matches the live edit bar, + * the presence dot and the chip of the session that wrote it. `iconOf` reads + * a session's icon color where the caller has the rows. */ -export function sessionHues(hunks: readonly CodeBlameHunk[]): Map { - const ranges: SessionBlameRange[] = []; +export function sessionHues(hunks: readonly CodeBlameHunk[], iconOf: (id: string) => string | undefined = () => undefined): Map { + const hues = new Map(); for (const h of hunks) { const s = h.session; const id = s?.conversation_id ?? s?.id; - ranges.push({ - start_line: h.start, - end_line: h.end, - session: s && id ? { conversation_id: id, title: s.title ?? id, via: h.uncommitted ? "edit" : "trailer" } : null, - git: undefined, - newest_at: h.time ?? 0, - }); + if (id && !hues.has(id)) hues.set(id, sessionColor({ _id: id, icon_color: iconOf(id) })); } - return sessionBlameColors(summarizeSessionBlame(ranges)); + return hues; } export function hueOf(hunk: CodeBlameHunk | null, hues: ReadonlyMap): string { diff --git a/packages/web/lib/code/buffers.ts b/packages/web/lib/code/buffers.ts index 067d3d320e..30c96e5ac5 100644 --- a/packages/web/lib/code/buffers.ts +++ b/packages/web/lib/code/buffers.ts @@ -119,6 +119,8 @@ export interface DiskVersion { etag: string; mtime: number; size?: number; + /** The mode, when it refuses writes (VaultFileContent.lockedMode). */ + lockedMode?: string; } export interface CodeBuffer { @@ -171,8 +173,26 @@ export interface OpenBufferInput { /** The fields every state showing a file carries (the status bar and saving * read them): the text as last saved, and the file's format. */ +/** The file's mode refuses writes ("0444"): the editor still edits it, as vim + * does, and a save asks before forcing the write (fileSync, kind "readonly"). */ +export const setDiskLock = StateEffect.define(); + +export const diskLockField = StateField.define({ + create: () => null, + update: (lock, tr) => { + for (const e of tr.effects) if (e.is(setDiskLock)) return e.value; + return lock; + }, +}); + export function bufferFields(format: FileFormat): Extension { - return [savedDocField, fileFormatField.init(() => format)]; + return [savedDocField, fileFormatField.init(() => format), diskLockField]; +} + +/** Follow what disk says of the file's mode; writes nothing when unchanged. */ +export function syncDiskLock(buffer: CodeBuffer, lock: string | null | undefined): void { + if (currentState(buffer).field(diskLockField) === (lock ?? null)) return; + updateBuffer(buffer, { effects: setDiskLock.of(lock ?? null) }); } export const MAX_CLEAN_BUFFERS = 40; @@ -190,6 +210,9 @@ export const MAX_BUFFER_CHARS = 64 * 1024 * 1024; export class BufferCache { private buffers = new Map(); private clock = 0; + /** A buffer left the cache (closed or evicted): whatever else holds its + * text for it can let go (fileSync drops the vault store's copy). */ + onDrop: ((buffer: CodeBuffer) => void) | null = null; constructor( private readonly limit = MAX_CLEAN_BUFFERS, @@ -245,8 +268,13 @@ export class BufferCache { buffer.lastUsed = ++this.clock; } - close(key: string): void { + /** `keepText`: what else holds this path's text stays (a file renamed onto + * the path brought it, and the next buffer opens from it). */ + close(key: string, opts?: { keepText?: boolean }): void { + const buffer = this.buffers.get(key); + if (!buffer) return; this.buffers.delete(key); + if (!opts?.keepText) this.onDrop?.(buffer); } /** Drop clean, off-screen buffers, oldest first, until both limits hold @@ -264,6 +292,7 @@ export class BufferCache { for (const b of candidates) { if (count <= this.limit && chars <= this.charLimit) break; this.buffers.delete(b.key); + this.onDrop?.(b); count--; chars -= size(b); } diff --git a/packages/web/lib/code/commands.ts b/packages/web/lib/code/commands.ts index c5eb4d24f3..9249ea7a31 100644 --- a/packages/web/lib/code/commands.ts +++ b/packages/web/lib/code/commands.ts @@ -15,22 +15,37 @@ export const CODE_COMMAND_IDS = [ "file.save", "file.saveAll", "file.saveAndClose", // vim's :wq / :x; close only once the write lands. Unhandled: vim runs file.save then file.close + // The tab verbs take args?: { group?: ":"; path?: string } + // (a tab's menu names its tab); without them, the active tab of the + // command's group. "file.close", "file.closeOthers", "file.reopenClosed", "file.open", // args: { path: string; line?: number; column?: number; split?: "right" | "down" } "file.revert", + "file.overwrite", // vim's :w!: write a file its mode refuses (0444), after the confirm "file.copyPath", // args?: { relative?: boolean } "file.reveal", + "tabs.pin", // pins, or unpins a pinned tab + "tabs.closeRight", + "tabs.keep", // a preview tab stays open + // a file changed on disk under unsaved edits (the conflict strip's verbs) + "merge.withDisk", + "merge.takeDisk", + "merge.keepMine", + "merge.next", + "merge.prev", + "breadcrumbs.focus", // navigation "quickOpen", // args?: { query?: string } "tabs.switcher", "tabs.next", "tabs.prev", "tabs.goto", // args: { index: number } + "tabs.alternate", // vim's :b# and : the tab used before this one "goto.line", // args?: { line?: number } - "goto.symbol", - "goto.workspaceSymbol", + "goto.symbol", // args?: { query?: string; container?: string | null; current?: string } + "goto.workspaceSymbol", // args?: { query?: string } "nav.back", "nav.forward", // layout @@ -38,10 +53,18 @@ export const CODE_COMMAND_IDS = [ "split.down", "split.close", "split.only", + "split.equalize", + "split.maximize", // args: { axis: "width" | "height" } + "split.resize", // args: { axis: "width" | "height"; by: number (percent, negative shrinks) } + "split.exchange", + "split.rotate", // args?: { delta: 1 | -1 } + "split.moveToEdge", // args: { edge: "left" | "right" | "top" | "bottom" } "focus.left", "focus.right", "focus.up", "focus.down", + "focus.previous", // vim's p: the group focused before this one + "focus.cycle", // args: { delta: 1 | -1 } in layout order, wrapping; or { to: "first" | "last" } "tree.toggle", "tree.reveal", "terminal.toggle", @@ -131,3 +154,15 @@ export function runCodeCommand(id: CodeCommandId, args?: Record export function hasCodeCommand(id: CodeCommandId): boolean { return (handlers.get(id)?.length ?? 0) > 0; } + +const labels = new Map string>(); + +/** A command whose name depends on state (vim on or off) says what running it + * would do now; menus read it through codeCommandLabel when they draw. */ +export function registerCodeCommandLabel(id: CodeCommandId, label: () => string): void { + labels.set(id, label); +} + +export function codeCommandLabel(id: CodeCommandId): string | undefined { + return labels.get(id)?.(); +} diff --git a/packages/web/lib/code/editorHost.ts b/packages/web/lib/code/editorHost.ts index f183e456b4..422135f984 100644 --- a/packages/web/lib/code/editorHost.ts +++ b/packages/web/lib/code/editorHost.ts @@ -6,7 +6,8 @@ // (features.ts), so a buffer that was off screen when the theme flipped, or // whose parser was still loading, catches up the moment it is shown. -import { Compartment, EditorSelection, EditorState, type Extension } from "@codemirror/state"; +import { jumpTo } from "./jump"; +import { Compartment, EditorState, type Extension } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; import { bufferFields, bufferKey, codeBuffers, currentState, decodeFileText, fileFormatField, updateBuffer, type CodeBuffer, type FileFormat } from "./buffers"; import { @@ -18,7 +19,7 @@ import { syncEditorFeatures, type EditorFeatureContext, } from "./features"; -import { describeLanguage, languageByName, loadLanguage, lspLanguageId } from "./languages"; +import { describeLanguage, languageByName, loadedLanguage, loadLanguage, lspLanguageId } from "./languages"; import { detectIndent } from "./indent"; import { codeSetup, DEFAULT_EDITOR_OPTIONS, editorSettingsExtension, readOnlyEffect, type CodeEditorOptions } from "./setup"; import { editorSetting, explicitEditorSettings, onEditorSettingsChange, registerEditorSettingsCommands } from "./editorSettings"; @@ -45,7 +46,7 @@ function registerCoreFeatures(): void { // transaction as the buffer's first paint; only a first use waits on a chunk. registerEditorFeature("core.language", (ctx) => { const desc = languageByName(ctx.languageName); - return desc?.support ?? loadLanguage(desc); + return loadedLanguage(desc) ?? loadLanguage(desc); }); observeCodeTheme(() => reconfigureEditorFeature("core.theme")); // Settings > Editor, live: a change (here or on another device) reaches @@ -168,21 +169,27 @@ export interface CursorTarget { column?: number; /** The last line of a range that flashes on arrival (an agent's edit). */ endLine?: number; + /** The line to put at the top of the view (a reload restoring where a tab + * was scrolled); the cursor's line is centered when absent. */ + top?: number; } /** `12`, `12:3`, `L12`, `12-20` / `12:3-20` (a range: cursor on its first * line, the range flashed) as a cursor target. The spelling filesHref - * (lib/vault/vaultHref cursorParam) writes. */ + * (lib/vault/vaultHref cursorParam) writes. A restored tab adds `@400`, the + * line at the top of its view. */ export function parseCursorTarget(raw: string | null | undefined): CursorTarget | null { - const m = raw ? /^L?(\d+)(?:[:.,](\d+))?(?:-L?(\d+))?/.exec(raw.trim()) : null; + const m = raw ? /^L?(\d+)(?:[:.,](\d+))?(?:-L?(\d+))?(?:@(\d+))?/.exec(raw.trim()) : null; if (!m) return null; const line = parseInt(m[1], 10); if (!(line > 0)) return null; const end = m[3] ? parseInt(m[3], 10) : 0; + const top = m[4] ? parseInt(m[4], 10) : 0; return { line, column: m[2] ? Math.max(1, parseInt(m[2], 10)) : undefined, ...(end > line ? { endLine: end } : {}), + ...(top > 0 ? { top } : {}), }; } @@ -191,11 +198,8 @@ export function revealTarget(view: EditorView, target: CursorTarget): void { const doc = view.state.doc; const line = doc.line(Math.min(target.line, doc.lines)); const col = target.column ? target.column - 1 : (/^\s*/.exec(line.text)?.[0].length ?? 0); - const pos = line.from + Math.min(col, line.length); - view.dispatch({ - selection: EditorSelection.cursor(pos), - effects: EditorView.scrollIntoView(pos, { y: "center" }), - }); + const top = target.top ? doc.line(Math.min(target.top, doc.lines)).from : undefined; + jumpTo(view, line.from + Math.min(col, line.length), { scrollTop: top }); if (target.endLine) flashLines(view, line.number, target.endLine); } diff --git a/packages/web/lib/code/features.ts b/packages/web/lib/code/features.ts index 559254a7ea..4e39c79c5b 100644 --- a/packages/web/lib/code/features.ts +++ b/packages/web/lib/code/features.ts @@ -237,6 +237,14 @@ export interface StatusItemView { * and returns the unsubscribe (null when there is nothing to follow); it runs * at creation and again after every reconfiguration, never on a keystroke. */ +/** Name a status item for a screen reader and a pointer at once: what it + * shows and what a press does, since its visible text is a bare count or a + * mode. Writes only when the name changes, so it may sit in a render path. */ +export function nameStatusItem(el: HTMLElement, name: string, title = name): void { + if (el.getAttribute("aria-label") !== name) el.setAttribute("aria-label", name); + if (el.title !== title) el.title = title; +} + export function liveStatusItem(dom: HTMLElement, bind: () => (() => void) | null): StatusItemView { let unsubscribe = bind(); return { diff --git a/packages/web/lib/code/fileSync.ts b/packages/web/lib/code/fileSync.ts index 701ee53a99..ae812487a8 100644 --- a/packages/web/lib/code/fileSync.ts +++ b/packages/web/lib/code/fileSync.ts @@ -8,13 +8,15 @@ // a region both sides changed differently opens the merge view, where each // chunk is kept or taken and the save writes the result. // -// A change on disk while the buffer is clean lands as the smallest line edits, -// annotated `externalChange` so features (agent highlights) can color exactly -// what moved. While the buffer is dirty it waits, marked stale, for the save. +// A change on disk lands as the smallest line edits, annotated +// `externalChange` so features (agent highlights) can color exactly what +// moved. Over unsaved edits it merges at once: lines only disk changed come +// in and the person's own edits stay unsaved; a region both changed opens the +// merge view. Only when the diff code cannot load does it wait, marked stale. import { Annotation, Compartment, type Extension, type TransactionSpec } from "@codemirror/state"; import { EditorView } from "@codemirror/view"; -import { readVaultFile, vaultOp, writeVaultFile, VaultWriteConflict } from "../vault/client"; +import { isVaultUnreachable, readVaultFile, vaultOp, writeVaultFile, VaultRequestError, VaultWriteConflict } from "../vault/client"; import { requestEndpointOf, setCodeBodyHolder, useVaultStore } from "../../store/vaultStore"; import { useCodeStore } from "../../store/codeStore"; import { @@ -22,12 +24,14 @@ import { codeBuffers, currentState, decodeFileText, + diskLockField, encodeFileText, fileFormatField, isDirty, savedDocField, setFileFormat, setSavedDoc, + syncDiskLock, textToDoc, updateBuffer, utf8Length, @@ -37,7 +41,7 @@ import { import { featureContext, LARGE_FILE_BYTES } from "./features"; import { clearHotExit, flushHotExit, loadHotExit, scheduleHotExit, type HotExitDraft } from "./hotExit"; import { clearNewFile, isNewFile } from "./newFiles"; -import { lineChanges, loadMergeKit, mergeChunkCount, mergeViewExtension, threeWayMerge, type MergeKit } from "./merge"; +import { lineChanges, loadMergeKit, mergeChunkCount, mergeViewExtension, openConflicts, threeWayMerge, type MergeKit } from "./merge"; /** Marks a transaction that brought in a version someone else wrote. */ export const externalChange = Annotation.define<{ etag: string }>(); @@ -48,8 +52,9 @@ const mergeSlot = new Compartment(); type Written = { etag: string; mtime: number; size: number }; export interface DiskIO { - /** Throws VaultWriteConflict when disk is no longer at `baseEtag`. */ - write(buffer: CodeBuffer, content: string, baseEtag: string): Promise; + /** Throws VaultWriteConflict when disk is no longer at `baseEtag`. `force` + * writes a file whose mode refuses writes, keeping the mode. */ + write(buffer: CodeBuffer, content: string, baseEtag: string, opts?: { force?: boolean }): Promise; /** Create the file empty; refused (throws) when it already exists. */ createEmpty(buffer: CodeBuffer): Promise; read(buffer: CodeBuffer): Promise; @@ -60,7 +65,9 @@ export interface DiskIO { function connectedEndpoint() { // Any endpoint will do: the request is routed by the buffer's vault. const endpoint = requestEndpointOf(useVaultStore.getState()); - if (!endpoint) throw new Error("Files is not connected to this machine"); + // A TypeError, as loopbackFetch throws for a daemon it cannot reach: the + // save waits for the reconnect rather than failing (isVaultUnreachable). + if (!endpoint) throw new TypeError("Files is not connected to this machine"); return endpoint; } @@ -72,10 +79,10 @@ function writeOptions(b: CodeBuffer) { } const vaultIO: DiskIO = { - write: (b, content, baseEtag) => { + write: (b, content, baseEtag, opts) => { // An empty etag would turn into a PUT without If-Match: an overwrite. if (!baseEtag) throw new Error("No disk version to save over"); - return writeVaultFile(connectedEndpoint(), b.vaultId, b.path, content, baseEtag, writeOptions(b)); + return writeVaultFile(connectedEndpoint(), b.vaultId, b.path, content, baseEtag, { ...writeOptions(b), force: !!opts?.force }); }, createEmpty: async (b) => { await vaultOp(connectedEndpoint(), b.vaultId, { op: "create", path: b.path, content: "" }, writeOptions(b)); @@ -88,6 +95,10 @@ let io: DiskIO = vaultIO; // A file that leaves disk and returns comes back into any editor still open on it. setCodeBodyHolder((vaultId, path) => !!codeBuffers.get(bufferKey(vaultId, path))); +// A buffer gone from the cache takes the store's copy of its text with it: +// the store would otherwise hold every file opened this session, and keep +// reading each one again on every agent write. Shown again, it is read again. +codeBuffers.onDrop = (b) => useVaultStore.getState().releaseCodeBody(b.vaultId, b.path); /** Tests: swap the disk. Returns the restore. */ export function _setDiskIOForTests(next: DiskIO): () => void { @@ -131,7 +142,8 @@ function noteChange(b: CodeBuffer, docChanged: boolean): void { if (!dirty) { void clearHotExit(b.key); // A failed save of text that is no longer there is not news. - if (useCodeStore.getState().conflicts[b.key]?.kind === "error") chrome().setConflict(b.key, null); + const kind = useCodeStore.getState().conflicts[b.key]?.kind; + if (kind === "error" || kind === "offline" || kind === "readonly") chrome().setConflict(b.key, null); } } // A large file's text is megabytes to encode and clone: hold it less often. @@ -197,23 +209,34 @@ function isBaseVersion(b: CodeBuffer, disk: DiskVersion): boolean { return encodeFileText(state, state.field(savedDocField)) === disk.content; } -/** Someone else wrote the file. A clean buffer takes it in; a dirty one waits - * for its save; a merging one already has a newer question to answer. */ +/** Someone else wrote the file. A clean buffer takes it in; a dirty one + * merges with it at once (a conflict opens the merge view); a merging one + * already has a newer question to answer. A save in flight answers it by its + * compare-and-swap: the version may be that save's own write landing. */ export async function applyDiskVersion(b: CodeBuffer, disk: DiskVersion): Promise { // A version on disk means the file is back, whatever it holds. if (chrome().conflicts[b.key]?.kind === "deleted") chrome().setConflict(b.key, null); if (isBaseVersion(b, disk) || b.merging) return; - const before = currentState(b); - if (isDirty(before)) { - b.stale = disk; - chrome().setConflict(b.key, { kind: "stale" }); + const saving = inflight.get(b.key); + if (saving) { + // Decided once the save lands: its own write is the base by then. + const again = () => applyDiskVersion(b, disk); + void saving.then(again, again); return; } + const before = currentState(b); const kit = await loadMergeKit().catch(() => null); // Typing while the diff code loaded: decide again on the text as it is now. if (currentState(b).doc !== before.doc) return applyDiskVersion(b, disk); if (isBaseVersion(b, disk) || b.merging) return; - adopt(b, disk, kit); + if (inflight.has(b.key)) return applyDiskVersion(b, disk); + if (!isDirty(before)) return adopt(b, disk, kit); + if (!kit) { + b.stale = disk; + chrome().setConflict(b.key, { kind: "stale" }); + return; + } + await mergeWithDisk(b, disk); } /** The file left disk. Unsaved edits wait for a Recreate. A clean buffer has @@ -237,19 +260,29 @@ function rebaseOnto(b: CodeBuffer, disk: DiskVersion): void { chrome().setConflict(b.key, null); } +/** The merge strip's numbers: chunks still differing from disk, and how many + * of them sit in a region both sides wrote. */ +function mergeCounts(kit: MergeKit, b: CodeBuffer) { + const state = currentState(b); + return { kind: "merge" as const, remaining: mergeChunkCount(kit, state), conflicts: openConflicts(kit, state).length }; +} + async function refreshMergeCount(b: CodeBuffer): Promise { const kit = await loadMergeKit(); - const current = useCodeStore.getState().conflicts[b.key]; - if (!b.merging || current?.kind !== "merge") return; - chrome().setConflict(b.key, { ...current, remaining: mergeChunkCount(kit, currentState(b)) }); + if (!b.merging || useCodeStore.getState().conflicts[b.key]?.kind !== "merge") return; + chrome().setConflict(b.key, mergeCounts(kit, b)); } +/** The person's own text from before a merge view opened, and the document the + * merge left, so "Keep mine" can put it back while the merge is untouched. */ +const premerge = new WeakMap(); + /** * Three-way merge the buffer with a disk version, its saved text as the base. * Without a conflict the merged text simply becomes the buffer, rebased onto * disk ("merged"); with one, the editor turns into a merge view ("merging"). */ -export async function mergeWithDisk(b: CodeBuffer, disk: DiskVersion): Promise<"merged" | "merging"> { +export async function mergeWithDisk(b: CodeBuffer, disk: DiskVersion, opts: { restoring?: boolean } = {}): Promise<"merged" | "merging"> { clearNewFile(b.key); const kit = await loadMergeKit(); const state = currentState(b); @@ -258,23 +291,27 @@ export async function mergeWithDisk(b: CodeBuffer, disk: DiskVersion): Promise<" const mine = state.doc.toString(); const result = threeWayMerge(kit, base, diskText, mine); const changes = lineChanges(kit, mine, result.text); + // The lines this brings in are disk's: marked as someone else's change + // (agent edit marks), except a reload's own text coming back. + const annotations = opts.restoring ? [] : [externalChange.of({ etag: disk.etag })]; if (result.conflicts === 0) { - applyToBuffer(b, { changes, userEvent: "merge" }); + applyToBuffer(b, { changes, userEvent: "merge", annotations }); rebaseOnto(b, disk); return "merged"; } b.stale = null; b.merging = disk; - applyToBuffer(b, { changes, userEvent: "merge", effects: mergeSlot.reconfigure(mergeViewExtension(kit, diskText)) }); - chrome().setConflict(b.key, { - kind: "merge", - remaining: mergeChunkCount(kit, currentState(b)), - conflicts: result.conflicts, - }); + applyToBuffer(b, { changes, userEvent: "merge", annotations, effects: mergeSlot.reconfigure(mergeViewExtension(kit, diskText, result.regions)) }); + premerge.set(b, { mine, merged: currentState(b).doc }); + chrome().setConflict(b.key, mergeCounts(kit, b)); return "merging"; } -export type SaveOutcome = "unchanged" | "saved" | "merging" | "adopted" | "deleted" | "readonly" | "error"; +/** `readonly`: the editor holds the text read-only (a mirror, text that did + * not decode) and wrote nothing. `locked`: the file's mode refused the write + * and the person has not confirmed an overwrite. `offline`: the daemon was + * not reached; the save runs again on reconnect. */ +export type SaveOutcome = "unchanged" | "saved" | "merging" | "adopted" | "deleted" | "readonly" | "locked" | "offline" | "error"; const inflight = new Map>(); @@ -314,9 +351,68 @@ async function discard(b: CodeBuffer, run: () => Promise): Promise { /** Save a buffer. Saves of one buffer queue behind each other, so a second * Cmd-S during a slow write writes again only if there is something new. */ -export function saveBuffer(b: CodeBuffer, opts: { recreate?: boolean } = {}): Promise { +export function saveBuffer(b: CodeBuffer, opts: { recreate?: boolean; force?: boolean } = {}): Promise { const custom = vaultSavers.get(b.vaultId); - const run = (inflight.get(b.key) ?? Promise.resolve("unchanged" as SaveOutcome)).then(() => (custom ? custom(b) : writeBuffer(b, !!opts.recreate))); + return queueSave(b, () => (custom ? custom(b) : writeBuffer(b, !!opts.recreate, !!opts.force))); +} + +/** Write a file its mode refuses (0444), the mode kept: the person confirmed + * the overwrite. Still compare-and-swap, so disk that moved merges first. */ +export function overwriteLocked(b: CodeBuffer): Promise { + return saveBuffer(b, { force: true }); +} + +/** Buffers whose save never reached the daemon: saved again, in one pass, + * once Files is connected again. */ +const unsent = new Set(); + +function retryUnsent(): void { + for (const key of [...unsent]) { + unsent.delete(key); + const b = codeBuffers.get(key); + if (b && chrome().conflicts[key]?.kind === "offline") void saveBuffer(b); + } +} + +// Files is back: the socket reconnected (a daemon restart, a dropped WS) or a +// new endpoint was found. Each save is still compare-and-swap, so disk that +// moved meanwhile merges rather than being written over. +let lastEndpoint = requestEndpointOf(useVaultStore.getState()); +let lastConnection = useVaultStore.getState().connection; +useVaultStore.subscribe((s) => { + const endpoint = requestEndpointOf(s); + const back = (endpoint !== lastEndpoint && !!endpoint) || (s.connection === "connected" && lastConnection !== "connected"); + lastEndpoint = endpoint; + lastConnection = s.connection; + if (back && unsent.size) retryUnsent(); +}); + +/** Tests: run the reconnect retry as if the endpoint had come back. */ +export const _retryUnsentForTests = retryUnsent; + +/** Write the person's text over the disk version they were shown changed + * (the strip's Keep mine): their text from before the merge view opened, or + * what the editor holds once they worked in the merge. Still compare-and-swap, + * on that version's etag, so a newer write is merged with, never lost. */ +export function keepMine(b: CodeBuffer): Promise { + return queueSave(b, async () => { + const disk = b.merging ?? b.stale; + if (!disk) return writeBuffer(b, false); + const held = premerge.get(b); + premerge.delete(b); + if (b.merging && held && currentState(b).doc === held.merged) { + const kit = await loadMergeKit(); + applyToBuffer(b, { changes: lineChanges(kit, currentState(b).doc.toString(), held.mine), userEvent: "merge" }); + } + rebaseOnto(b, disk); + if (!isDirty(currentState(b))) return "unchanged"; + return writeOut(b, (content) => io.write(b, content, disk.etag)); + }); +} + +/** Saves of one buffer run one after another. */ +function queueSave(b: CodeBuffer, save: () => Promise): Promise { + const run = (inflight.get(b.key) ?? Promise.resolve("unchanged" as SaveOutcome)).then(save); inflight.set(b.key, run); void run.finally(() => { if (inflight.get(b.key) === run) inflight.delete(b.key); @@ -337,7 +433,7 @@ export function recreateFile(b: CodeBuffer): Promise { return saveBuffer(b, { recreate: true }); } -async function writeBuffer(b: CodeBuffer, recreate: boolean): Promise { +async function writeBuffer(b: CodeBuffer, recreate: boolean, force = false): Promise { const start = currentState(b); if (start.readOnly || start.field(fileFormatField).lossy) return "readonly"; // A new file (`:e newfile.ts`) is created on its first save, empty or not, @@ -356,7 +452,7 @@ async function writeBuffer(b: CodeBuffer, recreate: boolean): Promise io.write(b, content, base)); + return writeOut(b, (content) => io.write(b, content, base, { force }), force); } /** Write a file deleted on disk back, never over a file that has returned. @@ -376,7 +472,7 @@ async function recreateWrite(b: CodeBuffer, content: string): Promise { return io.write(b, content, disk.etag); } -async function writeOut(b: CodeBuffer, write: (content: string) => Promise): Promise { +async function writeOut(b: CodeBuffer, write: (content: string) => Promise, force = false): Promise { const state = currentState(b); const doc = state.doc; const content = encodeFileText(state); @@ -397,18 +493,33 @@ async function writeOut(b: CodeBuffer, write: (content: string) => Promise { view.dispatch({ changes: { from: view.state.doc.length - 20, to: view.state.doc.length } }); }); -test("an untracked file gets no gutter", async () => { +test("an untracked file gets no gutter, and its diff reads as a new file", async () => { + const before = calls.base; const buffer = openCodeBuffer({ vaultId: "v1", path: "src/new.ts", content: "x\n", etag: "e2", readOnly: false }); host.show(buffer); - await settle(); - await settle(); - expect(git.hasGitGutter(host.view.state)).toBe(false); - expect(runCodeCommand("git.nextHunk", undefined, { view: host.view, source: "vim" })).toBe(false); + await until(() => git.hasGitGutter(host.view.state), "the git feature"); + const view = host.view; + // Nothing at HEAD to read, no column, no hunk to step outside the diff. + expect(calls.base).toBe(before); + expect(view.dom.querySelector(".cm-git-gutter")).toBeNull(); + expect(git.gitLineMarks(view.state)).toEqual([]); + expect(runCodeCommand("git.nextHunk", undefined, { view, source: "vim" })).toBe(false); + expect(runCodeCommand("git.diffHead", undefined, { view, source: "vim" })).toBe(true); + await until(() => view.dom.querySelector(".cm-git-count")?.textContent === "New file", "the new file count"); + // An older ref still diffs: a file added on the branch against where it began. + expect(runCodeCommand("git.diffAgainst", { ref: "main~3" }, { view, source: "vim" })).toBe(true); + await until(() => /change/.test(view.dom.querySelector(".cm-git-count")?.textContent ?? ""), "the ref's count"); + runCodeCommand("git.diffHead", undefined, { view, source: "vim" }); + expect(git.gitDiffState(view.state)).toBeNull(); }); test("a moved HEAD rereads the base", async () => { @@ -153,3 +165,23 @@ test("an unknown ref shows as not found, a file missing at a real ref as all new expect(count()?.textContent).toBe("1 change"); git.closeGitDiff(host.view); }); + +test("hunk commands from the side-by-side's right pane act on its diff", async () => { + const buffer = openCodeBuffer({ vaultId: "v1", path: "src/a.ts", content: "one\nTWO\nthree\nfour\n", etag: "e1", readOnly: false }); + host.show(buffer); + await until(() => git.hasGitGutter(host.view.state), "the gutter"); + git.openGitDiff(host.view, { ref: "HEAD" }, "split"); + const right = () => { + const editors = host.view.dom.querySelectorAll(".cm-git-split .cm-mergeViewEditor .cm-editor"); + return editors.length === 2 ? (EditorView.findFromDOM(editors[1] as HTMLElement) as InstanceType) : null; + }; + await until(() => !!right(), "the split"); + const b = right()!; + b.dispatch({ selection: { anchor: b.state.doc.line(2).from } }); + // vim's ]c and :GitGutterUndoHunk run with the right pane as their view. + expect(runCodeCommand("git.nextHunk", undefined, { view: b, source: "vim" })).toBe(true); + b.dispatch({ selection: { anchor: b.state.doc.line(2).from } }); + expect(runCodeCommand("git.revertHunk", undefined, { view: b, source: "vim" })).toBe(true); + expect(host.view.state.doc.line(2).text).toBe("two"); + git.closeGitDiff(host.view); +}); diff --git a/packages/web/lib/code/git/__tests__/gutter.mount.test.ts b/packages/web/lib/code/git/__tests__/gutter.mount.test.ts index 569166229a..aa802cf045 100644 --- a/packages/web/lib/code/git/__tests__/gutter.mount.test.ts +++ b/packages/web/lib/code/git/__tests__/gutter.mount.test.ts @@ -115,6 +115,30 @@ describe("hunk actions", () => { }); }); +describe("peek colors", () => { + it("paints the old lines with the buffer's own language", async () => { + const { StreamLanguage, syntaxHighlighting, defaultHighlightStyle } = await import("@codemirror/language"); + const { javascript } = await import("@codemirror/legacy-modes/mode/javascript"); + const view = new EditorView({ + parent, + state: EditorState.create({ + doc: "const a = 2;\n", + extensions: [ + StreamLanguage.define(javascript), + syntaxHighlighting(defaultHighlightStyle), + git.gitEditorExtension({ kit, vaultId: "v", path: "a.js", base: Text.of(["const a = 1;", ""]), fetchBase: async () => null, targets: () => [] }), + ], + }), + }); + git.toggleGitPeek(view, 0); + const old = view.dom.querySelector(".cm-git-peek-old")!; + expect(old.textContent).toBe("const a = 1;"); + // The keyword and the number each carry a highlight class. + expect(old.querySelectorAll("span").length).toBeGreaterThanOrEqual(2); + view.destroy(); + }); +}); + describe("diff view", () => { it("opens an inline diff against HEAD that stays editable, then closes", () => { const view = mount(); @@ -234,6 +258,29 @@ describe("side by side", () => { view.destroy(); }); + it("knows the editor its right side mirrors, so hunk keys there act on the diff", async () => { + const view = mount(); + git.openGitDiff(view, { ref: "HEAD" }, "split"); + await settle(); + const b = rightSide(view)!; + expect(git.splitOwner(b)).toBe(view); + expect(git.splitOwner(view)).toBe(view); + git.closeGitDiff(view); + await settle(); + expect(git.splitOwner(b)).toBe(b); + view.destroy(); + }); + + it("offers Revert as the inline diff's one per-hunk action", async () => { + const view = mount(); + git.openGitDiff(view, { ref: "HEAD" }); + await settle(); + expect(view.dom.querySelectorAll(".cm-git-merge-reject").length).toBeGreaterThan(0); + expect(view.dom.querySelector("[class*='cm-git-merge-accept']")).toBeNull(); + expect([...view.dom.querySelectorAll(".cm-chunkButtons button, .cm-chunkButtons span:not([hidden])")].map((e) => e.textContent).filter(Boolean)).not.toContain("Keep"); + view.destroy(); + }); + it("puts back the base's unterminated last line exactly", async () => { const view = mount("x\nY\nz\n", "x\ny"); git.openGitDiff(view, { ref: "HEAD" }, "split"); diff --git a/packages/web/lib/code/git/gitTheme.ts b/packages/web/lib/code/git/gitTheme.ts index a1fb0b028d..897b000159 100644 --- a/packages/web/lib/code/git/gitTheme.ts +++ b/packages/web/lib/code/git/gitTheme.ts @@ -1,7 +1,7 @@ // The git gutter's styles: change bars, the peek widget, the diff bar and // the ref picker. gutter.ts adds this theme with the git feature. import { EditorView } from "@codemirror/view"; -import { EDITOR_FONT } from "../theme"; +import { EDITOR_FONT, OVERLAY } from "../theme"; import { GIT_GUTTER_COLUMN } from "../gutterSlots"; export const gitTheme = EditorView.theme({ @@ -55,7 +55,7 @@ export const gitTheme = EditorView.theme({ fontSize: "13px", lineHeight: "1.6", color: "var(--sol-text-muted)", - backgroundColor: "color-mix(in srgb, var(--sol-red) 8%, transparent)", + backgroundColor: "var(--diff-del-line)", tabSize: "4", }, ".cm-git-btn": { @@ -86,8 +86,9 @@ export const gitTheme = EditorView.theme({ ".cm-git-seg:first-child": { borderRadius: "3px 0 0 3px" }, ".cm-git-seg:last-child": { borderRadius: "0 3px 3px 0", marginLeft: "-1px" }, ".cm-git-seg-on": { color: "var(--sol-text)", backgroundColor: "var(--sol-bg-alt)" }, - // The editor's own popup look (the completion list in theme.ts). + // The editor's own popup look (OVERLAY in theme.ts). ".cm-git-menu": { + ...OVERLAY, position: "absolute", top: "26px", left: "8px", @@ -96,10 +97,6 @@ export const gitTheme = EditorView.theme({ flexDirection: "column", minWidth: "220px", padding: "4px", - border: "1px solid color-mix(in srgb, var(--sol-border) 50%, transparent)", - borderRadius: "4px", - backgroundColor: "var(--sol-bg)", - boxShadow: "0 6px 20px rgb(0 0 0 / 0.18)", fontSize: "12px", }, ".cm-git-menu-list": { display: "flex", flexDirection: "column", maxHeight: "16em", overflowY: "auto", marginTop: "4px" }, @@ -116,8 +113,11 @@ export const gitTheme = EditorView.theme({ textAlign: "left", cursor: "pointer", }, - ".cm-git-menu-item[aria-selected]": { backgroundColor: "color-mix(in srgb, var(--sol-cyan) 18%, transparent)", color: "var(--sol-text)" }, + ".cm-git-menu-item[aria-selected]": { backgroundColor: "color-mix(in srgb, var(--sol-cyan) 16%, transparent)", color: "var(--sol-text)" }, ".cm-git-menu-on": { color: "var(--sol-text)" }, + // A session's ref: its color, then its name, the ref at the right edge. + ".cm-git-menu-dot": { flex: "none", alignSelf: "center", width: "6px", height: "6px", borderRadius: "50%", marginRight: "-6px" }, + ".cm-git-menu-dot + span": { marginRight: "auto" }, ".cm-git-menu-input": { padding: "3px 6px", border: "1px solid color-mix(in srgb, var(--sol-border) 40%, transparent)", diff --git a/packages/web/lib/code/git/gutter.ts b/packages/web/lib/code/git/gutter.ts index b56435a9fa..01c2af2d14 100644 --- a/packages/web/lib/code/git/gutter.ts +++ b/packages/web/lib/code/git/gutter.ts @@ -22,6 +22,8 @@ import { type ViewUpdate, } from "@codemirror/view"; import type { Chunk } from "@codemirror/merge"; +import { highlightingFor, language as languageFacet } from "@codemirror/language"; +import { highlightTree } from "@lezer/highlight"; import { bufferKey, codeBuffers, savedDocField, textToDoc, decodeFileText } from "../buffers"; import type { MergeKit } from "../merge"; import { holdGitStatusFeed, requestGitStatusRefresh } from "./status"; @@ -39,13 +41,20 @@ import { type Hunk, } from "./hunks"; import { mountSplit, splitTheme, type SplitHandle } from "./split"; +export { splitOwner } from "./split"; import { gitTheme } from "./gitTheme"; +import { formatAcceleratorParts, isMac } from "../../../shortcuts/registry"; + +/** A button title with the key that does the same, as the platform writes it. */ +const withKey = (title: string, accelerator: string) => `${title} (${formatAcceleratorParts(accelerator).join(isMac ? "" : "+")})`; export interface GitDiffTarget { /** Anything `git rev-parse` takes that names a commit: HEAD, a sha, a branch. */ ref: string; /** What the picker shows; the ref when absent. */ label?: string; + /** A dot in the picker: the color of the session the ref belongs to. */ + color?: string; } export type DiffLayout = "unified" | "split"; @@ -56,10 +65,14 @@ export interface GitEditorConfig { path: string; /** The file at HEAD, decoded the way the buffer is. */ base: Text; + /** Nothing at HEAD (untracked or added): `base` is empty, there is no + * gutter and no hunk to step outside the diff, and the diff against HEAD + * reads as a new file. */ + newFile?: boolean; /** The file's text at a ref, null when it does not exist there. */ fetchBase: (ref: string) => Promise; - /** Refs the picker offers besides HEAD. */ - targets: () => GitDiffTarget[]; + /** Refs the picker offers besides HEAD, for the editor's current state. */ + targets: (state: EditorState) => GitDiffTarget[]; } const gitConfig = Facet.define({ combine: (v) => v[0] ?? null }); @@ -157,6 +170,29 @@ function button(label: string, title: string, onPress: () => void, cls = ""): HT return b; } +/** Past this the old lines show plain: a peek never stalls on a huge hunk. */ +const PEEK_HIGHLIGHT_MAX = 20_000; + +/** The old lines as the editor would color them: parsed with the buffer's + * language and painted by its highlight styles. */ +function oldLinesPre(view: EditorView, text: string): HTMLElement { + const pre = el("pre", "cm-git-peek-old"); + const lang = view.state.facet(languageFacet); + if (!lang || text.length > PEEK_HIGHLIGHT_MAX) { + pre.textContent = text; + return pre; + } + let pos = 0; + // The way @codemirror/merge paints deleted lines (syntaxHighlightDeletions). + highlightTree(lang.parser.parse(text), { style: (tags) => highlightingFor(view.state, tags) }, (from, to, cls) => { + if (from > pos) pre.append(text.slice(pos, from)); + pre.append(el("span", cls, text.slice(from, to))); + pos = to; + }); + if (pos < text.length) pre.append(text.slice(pos)); + return pre; +} + class PeekWidget extends WidgetType { constructor( readonly hunk: Hunk, @@ -179,8 +215,8 @@ class PeekWidget extends WidgetType { // The actions sit beside the counts: the widget is as wide as the longest // line, so anything pushed to its right edge can land out of view. head.append( - button("↑", "Previous change", () => stepGitHunk(view, -1, true)), - button("↓", "Next change", () => stepGitHunk(view, 1, true)), + button("↑", withKey("Previous change", "Shift+Alt+F5"), () => stepGitHunk(view, -1, true)), + button("↓", withKey("Next change", "Alt+F5"), () => stepGitHunk(view, 1, true)), button("Revert", "Put the old lines back", () => revertGitHunk(view)), button("Copy", "Copy the old lines", () => void navigator.clipboard?.writeText(this.old).catch(() => {})), button("×", "Close", () => { @@ -189,7 +225,7 @@ class PeekWidget extends WidgetType { }, "cm-git-btn-icon"), ); box.append(head); - if (this.old) box.append(el("pre", "cm-git-peek-old", this.old)); + if (this.old) box.append(oldLinesPre(view, this.old)); return box; } ignoreEvent() { @@ -217,7 +253,7 @@ function buildPeek(state: EditorState, value: Pick({ function recompute(view: EditorView): void { const config = view.state.facet(gitConfig); const value = view.state.field(gitDiffField, false); - if (!config || !value?.pending) return; + if (!config || config.newFile || !value?.pending) return; const chunks = updateChunks(config.kit, value.chunks, config.base, view.state.doc, value.pending); view.dispatch({ effects: recomputed.of(chunks) }); } @@ -291,10 +327,18 @@ function unifiedDiff(kit: MergeKit, original: Text): Extension { highlightChanges: true, syntaxHighlightDeletions: true, diffConfig: GIT_DIFF_CONFIG, + // Revert is the one per-hunk action. The engine's "accept" only folds the + // hunk into this in-memory original (nothing staged, nothing kept), so it + // draws as nothing. mergeControls: (type, action) => { - const b = el("button", `cm-git-merge-${type}`, type === "accept" ? "Keep" : "Revert"); + if (type === "accept") { + const none = document.createElement("span"); + none.hidden = true; + return none; + } + const b = el("button", "cm-git-merge-reject", "Revert"); b.type = "button"; - b.title = type === "accept" ? "Keep this change and hide it" : "Put the old lines back"; + b.title = "Put the old lines back"; b.onmousedown = action; return b; }, @@ -404,6 +448,7 @@ export function stepGitHunk(view: EditorView, dir: 1 | -1, keepPeek = false): bo if (split) return split.step(dir); return (dir === 1 ? config.kit.goToNextChunk : config.kit.goToPreviousChunk)(view); } + if (config.newFile) return false; const doc = view.state.doc; const hunks = liveHunks(value.chunks, value.pending, doc.length); const line = doc.lineAt(view.state.selection.main.head).number; @@ -437,6 +482,7 @@ export function revertGitHunk(view: EditorView): boolean { if (value.diff.layout === "split") return view.plugin(splitPlugin)?.handle?.revertAtCursor() ?? false; return config.kit.rejectChunk(view); } + if (config.newFile) return false; if (view.state.readOnly) return true; const h = hunkAtCursor(view); if (!h) return true; @@ -449,7 +495,7 @@ export function revertGitHunk(view: EditorView): boolean { /** Show or hide the old lines of the hunk under the cursor. */ export function toggleGitPeek(view: EditorView, at?: number): boolean { const value = view.state.field(gitDiffField, false); - if (!value || value.diff) return false; + if (!value || value.diff || view.state.facet(gitConfig)?.newFile) return false; if (at === undefined && value.peek !== null) { view.dispatch({ effects: setPeek.of(null) }); return true; @@ -463,6 +509,17 @@ export function toggleGitPeek(view: EditorView, at?: number): boolean { return true; } +/** Show the old lines of the change at `pos`, leaving an open peek of it + * open. False while the diff view is open (it shows them already). */ +export function showGitPeek(view: EditorView, pos: number): boolean { + const value = view.state.field(gitDiffField, false); + if (!value || value.diff || view.state.facet(gitConfig)?.newFile) return false; + const doc = view.state.doc; + const h = hunkAtLine(liveHunks(value.chunks, value.pending, doc.length), doc, doc.lineAt(Math.min(pos, doc.length)).number); + if (h && value.peek !== h.fromB) view.dispatch({ effects: setPeek.of(h.fromB) }); + return true; +} + // ── the diff panel ────────────────────────────────────────────────────────── function createDiffPanel(view: EditorView): Panel { @@ -473,8 +530,8 @@ function createDiffPanel(view: EditorView): Panel { const refLabel = el("span", "", ""); refButton.append(el("span", "cm-git-dim", "vs"), refLabel, el("span", "cm-git-caret", "▾")); const count = el("span", "cm-git-count"); - const prev = button("↑", "Previous change", () => stepGitHunk(view, -1)); - const next = button("↓", "Next change", () => stepGitHunk(view, 1)); + const prev = button("↑", withKey("Previous change", "Shift+Alt+F5"), () => stepGitHunk(view, -1)); + const next = button("↓", withKey("Next change", "Alt+F5"), () => stepGitHunk(view, 1)); const unified = button("Inline", "Inline diff", () => setGitDiffLayout(view, "unified"), "cm-git-seg"); const split = button("Side by side", "Side by side", () => setGitDiffLayout(view, "split"), "cm-git-seg"); const seg = el("span", "cm-git-segs"); @@ -504,7 +561,8 @@ function createDiffPanel(view: EditorView): Panel { const config = view.state.facet(gitConfig); if (!config || menu) return; const current = view.state.field(gitDiffField, false)?.diff?.ref; - const targets: GitDiffTarget[] = [{ ref: "HEAD" }, ...config.targets()]; + const seen = new Set(); + const targets = [{ ref: "HEAD" } as GitDiffTarget, ...config.targets(view.state)].filter((t) => !seen.has(t.ref) && !!seen.add(t.ref)); menu = el("div", "cm-git-menu"); menu.setAttribute("role", "listbox"); // Typing filters the listed refs; text matching none is taken as a ref. @@ -534,6 +592,11 @@ function createDiffPanel(view: EditorView): Panel { item.type = "button"; item.tabIndex = -1; item.setAttribute("role", "option"); + if (t.color) { + const dot = el("span", "cm-git-menu-dot"); + dot.style.background = t.color; + item.append(dot); + } item.append(el("span", "", t.label ?? t.ref)); if (t.label && t.label !== t.ref) item.append(el("span", "cm-git-dim", t.ref)); item.onmousedown = (e) => e.preventDefault(); @@ -580,7 +643,8 @@ function createDiffPanel(view: EditorView): Panel { let n: number | null = null; if (diff.layout === "split") n = view.plugin(splitPlugin)?.handle?.count() ?? null; else if (config && diff.original) n = config.kit.getChunks(state)?.chunks.length ?? null; - count.textContent = diff.error ? diff.error.state : !diff.original ? "Loading…" : n === null ? "" : n === 0 ? "No changes" : n === 1 ? "1 change" : `${n} changes`; + const created = diff.ref === "HEAD" && !!config?.newFile; + count.textContent = diff.error ? diff.error.state : !diff.original ? "Loading…" : created ? "New file" : n === null ? "" : n === 0 ? "No changes" : n === 1 ? "1 change" : `${n} changes`; count.title = diff.error?.message ?? ""; count.classList.toggle("cm-git-error", !!diff.error); prev.disabled = next.disabled = !n; @@ -729,5 +793,6 @@ const peekKeys = Prec.high( export function gitEditorExtension(config: GitEditorConfig): Extension { // Lowest precedence puts the change bars last among the gutters, against // the text, whichever feature (lint, folding) happened to load first. - return [gitConfig.of(config), gitDiffField, diffSlot.of([]), runner, splitPlugin, Prec.lowest(gitGutter), peekKeys, gitTheme, splitTheme]; + // A new file draws no gutter: every bar would be green. + return [gitConfig.of(config), gitDiffField, diffSlot.of([]), runner, splitPlugin, config.newFile ? [] : Prec.lowest(gitGutter), peekKeys, gitTheme, splitTheme]; } diff --git a/packages/web/lib/code/git/index.ts b/packages/web/lib/code/git/index.ts index f8112252f3..5f08556a58 100644 --- a/packages/web/lib/code/git/index.ts +++ b/packages/web/lib/code/git/index.ts @@ -9,16 +9,18 @@ // in the same transaction as its first paint. import type { EditorView } from "@codemirror/view"; +import type { EditorState } from "@codemirror/state"; import { CODE_GIT_MERGE_BASE_REF as MERGE_BASE_REF } from "@codecast/shared/contracts"; import { useVaultStore } from "../../../store/vaultStore"; import { registerCodeCommands, type CodeCommandContext } from "../commands"; import { fetchGitBase } from "../daemonClient"; -import { featureContext, focusedEditorView, reconfigureEditorFeature, registerEditorFeature, registerStatusItem, type EditorFeatureContext, type StatusItemView } from "../features"; +import { featureContext, focusedEditorView, nameStatusItem, reconfigureEditorFeature, registerEditorFeature, registerStatusItem, type EditorFeatureContext, type StatusItemView } from "../features"; import { decodeFileText, textToDoc } from "../buffers"; import { loadMergeKit, type MergeKit } from "../merge"; import { gitGutterStandIn } from "../gutterSlots"; import { ensureGitStatus, gitStatusOf, lastNoHeadPaths, onGitHeadChange, useGitStatusStore, type VaultGitStatus } from "./status"; import type { DiffLayout, GitDiffTarget } from "./gutter"; +import { lineIcon } from "../icons"; export type { DiffLayout, GitDiffTarget }; @@ -88,36 +90,52 @@ function dropBases(vaultId: string): void { // ── diff targets ──────────────────────────────────────────────────────────── -type TargetProvider = (ctx: { vaultId: string; path: string }) => GitDiffTarget[]; +/** `state` is the editor's, for providers that read its other features. */ +type TargetProvider = (ctx: { vaultId: string; path: string; state: EditorState }) => GitDiffTarget[]; const targetProviders = new Set(); -/** Offer more refs in the diff picker (a session's base commit, say). */ +/** Offer more refs in the diff picker (a session's base commit, say). A + * provider that throws offers nothing. */ export function addGitDiffTargets(provider: TargetProvider): () => void { targetProviders.add(provider); return () => targetProviders.delete(provider); } -function targetsFor(vaultId: string, path: string): GitDiffTarget[] { +function targetsFor(vaultId: string, path: string, state: EditorState): GitDiffTarget[] { const status = gitStatusOf(vaultId); const out: GitDiffTarget[] = [{ ref: "HEAD~1", label: "Previous commit" }]; if (status?.upstream) out.push({ ref: "@{u}", label: "Upstream" }); // Everything this branch changed since it left the default branch. out.push({ ref: MERGE_BASE_REF, label: "Merge base" }); - for (const p of targetProviders) out.push(...p({ vaultId, path })); + for (const p of targetProviders) { + try { + out.push(...p({ vaultId, path, state })); + } catch { + // One provider's failure never empties the picker. + } + } return out; } // ── the feature ───────────────────────────────────────────────────────────── -function eligible(ctx: EditorFeatureContext, status: VaultGitStatus | undefined): boolean { +/** Whether a file gets git, and how: "tracked" (the gutter against HEAD), + * "new" (untracked or added: nothing at HEAD, so no gutter, whose bars would + * all be green, but the diff opens against nothing or an older ref), or + * false. */ +function eligibility(ctx: EditorFeatureContext, status: VaultGitStatus | undefined): "tracked" | "new" | false { const vault = useVaultStore.getState(); if (!vault.endpoint || vault.isRemote || vault.activeVaultId !== ctx.vaultId) return false; if (!status?.repo) return false; // Ignored files never appear in the status and have nothing at HEAD. if (vault.files[ctx.path]?.ignored) return false; const state = status.files[ctx.path]; - // Nothing at HEAD to compare with: the tree's color says it is new. - return state !== "untracked" && state !== "added"; + return state === "untracked" || state === "added" ? "new" : "tracked"; +} + +/** The file gets the change gutter. */ +function eligible(ctx: EditorFeatureContext, status: VaultGitStatus | undefined): boolean { + return eligibility(ctx, status) === "tracked"; } /** The gutter's column while its module, the status and HEAD's copy load: @@ -133,29 +151,39 @@ export function gitPlaceholder(ctx: EditorFeatureContext) { return gitGutterStandIn; } -function build(ctx: EditorFeatureContext, m: GutterModule, k: MergeKit, base: string | null) { - if (base === null) return null; +function build(ctx: EditorFeatureContext, m: GutterModule, k: MergeKit, base: string | null, newFile = false) { + if (base === null && !newFile) return null; return m.gitEditorExtension({ kit: k, vaultId: ctx.vaultId, path: ctx.path, - base: textToDoc(decodeFileText(base).text), + newFile, + base: textToDoc(decodeFileText(base ?? "").text), fetchBase: (ref) => readBase(ctx.vaultId, ctx.path, ref).promise, - targets: () => targetsFor(ctx.vaultId, ctx.path), + targets: (state) => targetsFor(ctx.vaultId, ctx.path, state), }); } function gitFeature(ctx: EditorFeatureContext) { const held = gitStatusOf(ctx.vaultId); - if (held && !eligible(ctx, held)) return null; + const kind = held ? eligibility(ctx, held) : undefined; + if (kind === false) return null; + // A new file reads nothing at HEAD: it has no gutter to wait for. + if (kind === "new" && gutterModule && kit) return build(ctx, gutterModule, kit, null, true); // Everything already loaded: land with the file's first paint. - if (held && gutterModule && kit) { + if (kind === "tracked" && gutterModule && kit) { const base = readBase(ctx.vaultId, ctx.path, "HEAD"); if (base.value !== undefined) return build(ctx, gutterModule, kit, base.value); } return (async () => { const status = held ?? (await ensureGitStatus(ctx.vaultId)); - if (!eligible(ctx, status)) return null; + const now = eligibility(ctx, status); + if (!now) return null; + if (now === "new") { + const [m, k] = await Promise.all([loadGutter(), loadMergeKit()]); + kit = k; + return build(ctx, m, k, null, true); + } // No HEAD yet (a repo with no commits) or a file too large to diff: no gutter. const head = readBase(ctx.vaultId, ctx.path, "HEAD").promise.catch((e: { status?: number }) => { if (e?.status === 404 || e?.status === 413) return null; @@ -170,7 +198,10 @@ function gitFeature(ctx: EditorFeatureContext) { // ── commands ──────────────────────────────────────────────────────────────── function viewFor(ctx: CodeCommandContext): EditorView | null { - const view = ctx.view ?? focusedEditorView(); + const at = ctx.view ?? focusedEditorView(); + // The side-by-side diff's right pane runs vim and keys of its own; its + // commands act on the editor it mirrors, which holds the git state. + const view = at && gutterModule ? gutterModule.splitOwner(at) : at; return view && gutterModule?.hasGitGutter(view.state) ? view : null; } @@ -183,8 +214,7 @@ function withView(fn: (m: GutterModule, view: EditorView, args: Record