Skip to content

Workspace Panels

Wijanarko Putra Rajeb edited this page Nov 20, 2026 · 28 revisions

Workspace panels

Right panel — the view a new session opens

  • A session that has never picked a view opens Files, from a constant — never from app_settings. The pre-per-session layout wrote a GLOBAL activeRightPanel row on every rail click; builds up to 0004c95d then seeded each new session's layout.activeRightPanel slot from that row, so a new chat opened whatever panel was last selected ANYWHERE. Measured on this machine's database: app_settings.activeRightPanel = browser, and a fresh session drew the Browser Agent instead of the Files tree. DEFAULT_RIGHT_PANEL_TYPE (shared/lib/workspace/right-panels.ts) is now the only source, read by the desktop layout and the phone's drawer; the per-session slot remembers what the user picks after that. Verified end-to-end: with the stale row present, the old fallback left Files at aria-pressed="false" and the fix makes it true (Chromium, e2e).

Right-Panel Repo Scope (Files / Search / Git / Terminal / Wiki)

  • The five right-panel views share one repo picker (repo-picker/index.tsx is a thin wrapper over the KIT's RepoPicker, so a plugin panel draws the same control; the panel owns the data) and one scope hook, src/client/hooks/workspace/repo-scope/. A repo is a path relative to the active workspace root (projects/jns6_5/token only names a directory under ~/JatisMobile/Workspace), so both the choice and the discovered list are meaningless without the root they belong to.
  • All five views share ONE selection slot, workspace.activeRepo (REPO_SCOPE_STATE_KEY). They describe the same working tree, so a repo picked in the Files tree has to move the search scope, the Source Control view and a terminal's cwd with it — that is also what makes the drop-down feel like one setting rather than five. useRepoScope(rootPath) takes no key for this reason: a per-panel key is not an option the API offers, so the views cannot drift back into disagreeing about which repository is on screen. useRepoList(rootPath, active) stays as it was (one shared discovery store per root).
  • A session that picked before the views shared a slot keeps its repo. The retired per-panel keys are adopted once, in the order git.activeRepo → files.activeRepo → search.activeRepo → terminal.activeRepo (git first: that pick is the one the root-level fallback and the Source Control indicator were built around), and only a value whose recorded root matches the current workspace is adopted — the shared slot is per session, so consuming it with a value for another workspace would burn the one chance to migrate and leave the panel on the root. All four keys are then cleared (clearSessionKey), so the store holds the selection in exactly one place.
  • Every repo value is stored with its root, never bare. useRepoScope persists { root, repo } per session and reports '.' when the pick is not for the current root; the discovery store (repo-scope/store.ts) keys its snapshot by root. Bare values are what leaked: a workspace switch left the picker listing the previous workspace's repos and showing one of them as the selection, while every request named a path that did not exist under the new root. Storing the pairing invalidates by construction, so no reset effect has to be ordered against the per-session state restore — and a session returned to inside the same workspace keeps its repo.
  • Repo discovery is one shared store, not a fetch per panel. repo-scope/store.ts subscribes to the repos:<root> realtime topic (the server discovers nested repos in the background and republishes the topic the moment its walk finishes), so the five views share one subscription per root instead of five, and cannot disagree. It is injected with fetch (only a rescan goes over HTTP), and store.test.ts drives it through a real socket: a new root never reports the old root's list, one subscription serves every listener of the same root, a snapshot is adopted, a republish reaches the listener, and a rescan goes out over HTTP.
  • Discovery's list is SORTED, because two consumers pick a DEFAULT out of it. With no repository chosen and the workspace root not itself a repo, the git route takes repos[0] as the implicit repo and the panel's resolveRepoForPanel takes the same — so an unordered list makes "which repository am I looking at" a property of the filesystem. findGitDirs pushes entries in readdir order, which differs between machines and after a directory is rewritten; measured, a scratch root whose entries were created alpha, conflicted came back ['conflicted', 'alpha']. That is what made the repository-modal browser spec pass locally and fail in CI on the same commit: it asserted Show alpha for a row that reads Already showing this repository once alpha IS the pick. getRepos sorts now (groupRepos already did, for display), and git-repos.test.ts pins the order, the root-first convention and the repeatability of two scans of one root. The spec no longer names which repo leads — it clicks the row titled Show (the one that is NOT showing, and therefore the only clickable one) and asserts the picker moved to that row's own name.
  • The root row is SYNTHESIZED, because discovery omits it for a non-repo root. getRepos returns '.' only when the root itself is a repo (the git route's implicit-repo fallback depends on that), so a picker that mapped the list straight through lost the root the moment the walk found a nested repo: the trigger fell back to the first nested repo while the panel was still browsing the root, and the root could not be selected at all. repoRows (src/shared/lib/fs/repo-label.ts) always leads with '.' and is the one place the host picker and the plugin scope build their rows; measured in the browser on a workspace root holding projects/alpha, the dropdown listed only projects/alpha before the fix and Workspace + projects/alpha after.
  • The picker's list is PORTALED and the trigger has NO fixed label cap, because the right panel clips at 268px. The list was w-56 inside the panel: widening it cut it off at the Source Control column's edge (overflow: hidden on the resizer's panel, whose git default is 268px), and the trigger capped its own label at max-w-[130px], so a nested repo's name ellipsized while the header still had room. RepoPicker (packages/kabmo-ui/src/repo-picker.tsx) now measures the trigger and renders the list as a position: fixed child of <body> at min(352px, 100vw - 16px), clamped to the viewport and re-measured on scroll/resize; the label is a min-w-0 truncate flex item, so it sheds width only when the panel actually runs out. Verified in the browser at a 268px Source Control column: the 352px list drew outside the panel (left clamp 1080 at 1440px), instead of being clipped.
  • GET /api/fs/git does NOT echo the repo back. repos / reposPending / activeRepo travel only on the ?reposOnly=1 branch, keyed to the root they were discovered for. The status response used to echo activeRepo, and the git panel wrote that echo into its stored pick — so a repo the user never chose was adopted under whichever workspace was active when the response arrived. Resolve the fallback (first discovered repo when the root is not itself a repo) client-side in resolveRepoForPanel instead, and only when the session has NO pick (null): an explicit '.' is the root and is honored even when it is not a repo, so the picker's root row is a real choice (the git panel then draws its init state). Only git applies the fallback; Files/Search/Terminal keep '.' as the root itself, because browsing a workspace that is a folder of nested repos is legitimate.
  • Everything read for a scope is tagged with it and dropped when the scope moves. The file listing carries its root\0repo (Listing.scope) and renders empty until the new root's read lands — its children cache and expansion set are keyed by paths relative to the listed root, so src/ in one workspace would otherwise rehydrate into src/ in the next. Search results carry their scope through useSearchStream, and the git panel gates fetcher.data on the scope the payload was requested for, so a switch never shows the old branch, changes or branch list under the new header. useGitStatus applies the same rule inside the hook — its state is tagged with the tree it was read from and a superseded read is dropped, so the "uncommitted changes" dot cannot describe the repository the user just left, and the state is thrown away when the scope changes because the same scope string can be a revisit (root → repo → root), where the earlier visit's changes would otherwise reappear.
  • The editor's "file is gone" probe asks the SAME scope the read used, and one predicate decides which tabs may ask at all. GET /api/fs/exists resolves root + repo + path exactly as /api/fs/read does, so a tab whose path came from a NESTED repo's tree (paths there are repo-relative) must send its repo; without it the route resolved src/inner.ts against the workspace root. Measured against a live server on a nested repo: ?root=<ws>&repo=pkg&path=src/inner.ts → {"exists":true}, the same request without repo → {"exists":false} — the file was read fine and then struck through as deleted, which is the reported "file di sub folder terdeteksi terhapus". The phone's probe built its scope by hand and dropped repo (LayoutWrapper → useMissingFiles([{ id, path, root }])); the scope is now mobileProbeTabs() (components/mobile/open-file-payload.ts), which carries repo, content, handleId and deviceFile. Which tabs are probed at all is isProbeableTab (hooks/workspace/missing-files.ts) and it lives in the HOOK, not at a call site: the desktop filtered inline-content chips itself and the phone did not, so every attachment chip, launched handle (handleId) and device file opened on a phone was reported deleted on sight. A diff tab is refused by the same predicate (its path names a change, not a document). missing-files.test.ts pins the skip for all four shapes and fs/exists.test.ts pins both scope resolutions.
  • A surface that FOLLOWS a panel's pick reads it shared, not from its own copy. The Source Control dot in the activity bar and the phone's tab bar are the same indicator on two layouts, and they describe the repo the git panel is on: useResolvedRepo(rootPath, active) — the shared pick, the same list, the same resolveRepoForPanel fallback — passed to useGitStatus instead of the previous hard-coded '.' (which reported the workspace root's changes, usually nothing, under a repo whose tree was dirty; measured: projects/jns6_5/personalschedulertrigger with 14 changes showed no dot while selected). useSessionState hands every caller a private copy, so the pick is read through useSharedSessionState (src/client/hooks/workspace/session-state/index.ts) instead: the store notifies per (session, key) on setSessionKey, on a blob arriving, on a migrate and on a delete (subscribeSessionKey, src/shared/lib/workspace/session-state/store.ts), and the follower re-reads — a private copy left it on the previous repo until something unrelated re-mounted it. Verified live in both layouts: picking a clean repo in the panel's picker turned the dot off (and the dot's own read switched to repo=projects/jns6_6/…) with no reload, and picking the 14-change repo turned it back on.
  • The panels refresh PER TOOL CALL, not only at the run boundary. tool_execution_end (frame-fold.ts) now emits workspace-dirty and calls publishSidebarStructure(), and a terminal agent_end calls the latter too (the final answer appends after the last tool). The old turn-boundary-only shape left a long run's git/files panels AND the sidebar blind for minutes: the sidebar's updated_at — its LATEST_SESSION ordering and the row's time-ago label — is a transcript-scan product that only re-runs on sidebar-structure, and sessions-watch deliberately ignores transcript appends (change; only rename is structural). Cost is bounded by existing machinery, not new: schedulePublish coalesces 120 ms per topic and dedupes identical payloads (a 3-call burst → 1 delta; a publish whose resolve lands inside the 4 s SIDEBAR_DATA_TTL_MS with an unchanged scan publishes nothing), only SUBSCRIBED topics are resolved, and invalidateOmpSidebarData-then-rescan over a warm per-file mtime cache is ~9 ms against 1211 ms cold. The session-data topics (todos, telemetry, queue) stay turn-boundary-only on purpose — their resolvers parse the whole transcript. Verified server-level with a temp agent dir: append → tool_execution_end fold → delta; append → agent_end fold → second delta with the newer updated_at; identical scan → zero deltas.

Files panel — collapsed folder chains (the fold, and how levels become reachable)

  • The fold is a RENDERING decision with a NAVIGATION cost, and the rows it hides were unreachable. listDirectoryEntries folds a run of single-child directories into ONE row (listDirectoryEntries → folderChain, src/server/lib/fs/listing.ts; the client mirrors it in foldSingleChildFolders, src/shared/lib/fs/folder-chain.ts), so dev/src/main/code is one row whose path is the DEEPEST directory. That identity is all the row had, which made the levels inside its label — main in particular — not rows at all: a drop aimed at main posted targetPath: "dev/src/main/code", and typing dev2/src/main into Rename moved code while leaving dev/src/main behind (both reproduced against the real /api/fs/action, which moved exactly one directory either way — so this was never a route bug). Renaming the chain row's label likewise only ever named one directory.
  • One mechanism fixes both surfaces: unfold the chain into a real row per directory (unfoldChains, src/shared/lib/fs/folder-chain.ts; state in src/client/hooks/workspace/unfolded-chains.ts). chainLevelPaths recovers the levels from the row's own LABEL plus its path — the label carries every directory, the path the deepest one — and unfoldChains rebuilds them outside-in so the deepest row keeps its own children, its git answer and therefore its ONE read. It is driven from two places: useFileRowDrag's onHoverAccept (a drag hovering an accepting row unfolds it, so the level appears under the pointer before the drop) and the row menu's Unfold Folders.
  • isChainRow is the single "does this row hide levels?" predicate (name.includes('/')). It must be the LABEL, not name !== path: a chain folded at the listing's own root is labelled with its whole path (name === path === 'dev/src/main/code') while still standing for four directories — the comparison shipped and the rename dialog's explanation never appeared. Drop targets, the rename/delete dialogs and the unfold menu row all read this one answer.
  • Unfolding OPENS what it exposes, and folding CLOSES it. A hidden level hides the next destination further down, so Unfold adds every level above the deepest to the panel's expansion set; Fold removes them again. Unfold is otherwise a one-way, explicit decision — a hovered drag does not silently refold, because the expansion set would then hold paths nothing draws and the next refresh would read each of them from disk for nothing.
  • A rename that SPLITS the chain drops the unfold; one that preserves it re-keys it. Only a rename of a level ABOVE the chain or of its deepest directory preserves the single-child run; a rename of a level in between leaves dev/ empty and dev2/src/main/ holding the rest, which is a different row — so rekey deletes that entry rather than re-pointing it at a chain that no longer exists. The expansion re-key runs BEFORE the local placement is attempted: an unfolded level is not in the tree's own coordinates, so that placement answers "not in this tree" and falls back to a reload, and an expansion re-key placed after it never ran (measured: an unfolded chain collapsed back to one row after replacing dev).
  • A drop highlight is the row under the POINTER, not every legal target. acceptsDrop (useFileRowDrag) is a CAPABILITY — "a drop here would be legal" — and both the row's bg-info/10 ring-1 block and the background's bg-info/[0.06] wash were drawn from it, so the whole tree turned blue the instant a drag started and stayed blue for the entire gesture (measured through the panel harness: dragging a.ts across b and c highlighted BOTH rows, and the background tint covered the tree). It reads as "everything is selected" and promises a drop the pointer is not on. The condition is now isDropHovered — the row's own dragover/dragleave state, cleared when the drag ends — and the background tints only while the pointer is on its own drop area (dragenter reaching it, since a row claims dragover with stopPropagation) and its dragleave ignores moves onto a child. The capability still decides preventDefault, which is the only thing it was ever for.
  • The harness rename must move a SUBTREE. moveOnDisk (src/test-support/file-explorer-disk.test-util.ts) re-deleted only the top entry, so a spec could not tell a real folder rename from one that abandoned its children — the exact failure being fixed. It now rekeys every directory the old path owned and creates the destination's parents, the way fs.rename and the route's mkdir -p do.
  • Reopening the panel IS a read: the view stays mounted while it is hidden. The desktop stack keeps every built-in view mounted and hides it with CSS, and a collapsed right column is a <Panel collapsed> — width 0, children still mounted. active was isActiveView alone, so it reported a view nobody could see as on screen, and FileExplorer's reload effect (keyed on scope, refreshKey) never re-ran on the way back: a reopened panel drew the tree it last read, including the children cache of every folder still expanded. active now means selected and the column is open (WorkspacePanels.tsx), and the effect in file-explorer/index.tsx reloads when it flips true — root plus every open folder, so an entry added or deleted while hidden is drawn/dropped. Regression: index.test.ts "reopening the panel re-reads…", driven by the harness's setActive (a re-render, not a remount — file-explorer-render.test-util.ts).
  • The regression net is collapsed-chain.test.ts (panel, real DOM) plus two specs in tests/e2e/specs/files-nested.e2e.ts (real browser, real disk): a hovered drag lands in main, the menu unfolds and a rename then moves main with its subtree, Fold Folders restores the one row, and a chain-start rename keeps the unfold at its new paths.

Source Control — merge, conflicts and branch management (the git view)

  • A folder with no repository is a STATE, not an empty change list — and the panel's one control there is init. readGitStatus folded git's refusal into {changes: [], branch: 'main'}, which is the exact shape of a CLEAN tree, so the panel drew its branch toolbar, commit box and "No changes found." over a directory where every one of them fails with fatal: not a git repository (only the repository dropdown worked). The payload now carries isRepo, set false only for git's own not a git repository — a missing binary or a locked index is deliberately NOT that answer, or the panel would offer to nest a second repository inside a real one — and the panel renders GitInitRepository (git-panel/InitRepository.tsx) in place of the toolbar, commit box, change list and stash, keeping the header because the picker can still point at a nested repository. The action is a row in the worktree table (GIT_ACTIONS.init → git init) guarded by git rev-parse --git-dir: init on an existing repository prints "Reinitialized existing Git repository" and exits 0, so a stale client would be told it created something it did not. Pinned by git-init-action.test.ts (created, refused, and refused inside another repository), init-state.test.ts (the chrome is gone, the click posts init) and git-panel.e2e.ts (a real folder, a real click, .git on disk).
  • A conflicted file is a THIRD kind of change, and reading its porcelain pair like a clean one is the bug that shipped. The two letters of UU/AA/DD/AU/UA/DU/UD are the two SIDES of a conflict, not an index/worktree pair. parsePorcelainZ derived staged from status[0] !== ' ', so every conflicted file was reported STAGED — and because ChangesList splits on the same columns, a UU path satisfied BOTH filters and rendered twice (under "Staged Changes" and under "Changes"), while getGitStatusInfo fell through to the untracked branch and labelled UU/UA/UD "Untracked". isUnmergedCode (src/shared/lib/fs/git-unmerged.ts) is the one predicate every surface tests; the status list, the tree roll-up and the staged-count all exclude unmerged pairs, and the file gets its own Conflicts section with its own count. git-status.test.ts used to PIN the wrong labels ("unmerged porcelain pairs carry no dedicated branch") — that test was deleted, not re-pinned.
  • An operation in progress is a first-class READ (readGitState, src/server/lib/fs/git-state.ts), and its state lives in FILES in the git dir, not in an exit code. One git rev-parse --absolute-git-dir (absolute, resolves from a subdirectory and for a linked worktree) plus a stat of MERGE_HEAD/rebase-merge/rebase-apply/CHERRY_PICK_HEAD/REVERT_HEAD. git rev-parse --git-path <name> is NOT usable: it takes a single name (five names give one path then fatal: ambiguous argument 'rebase-merge') and returns a path relative to the cwd. fs.existsSync, not Bun.file().exists() — measured, rebase-merge is a DIRECTORY and Bun.file(<dir>).exists() answers false for it, which reported a rebase as the stash-pop fallthrough and offered reset --merge HEAD instead of rebase --abort. The state rides the existing git:<root>\0<repo> realtime topic (it is part of readGitStatus), so a merge started by a tool call reaches the panel with no second read path.
  • stash-pop is a distinct operation because a conflicting git stash pop leaves NO operation file. Measured: UU f with no MERGE_HEAD/rebase-merge/CHERRY_PICK_HEAD, so every --abort verb exits 128 with its own fatal. Its abort is git reset --merge HEAD (verified: clears the conflict and KEEPS the stash entry, so the pop can be retried), and it has no Continue — resolving its files leaves the changes in the working tree with no sequencer to conclude, so the bar hides the button rather than offering one whose only outcome is a refusal (continueArgsFor returns null for it and the route says "Nothing to conclude").
  • Continue is PER OPERATION, and git commit --no-edit is only right for a merge. Measured on a real rebase conflict: resolving the file and running git commit --no-edit makes the commit and leaves the rebase RUNNING (rebase-merge still present, git status reading "interactive rebase in progress"), so the operation bar would never clear. continueArgsFor maps merge → commit --no-edit, rebase/rebase-apply → rebase --continue, cherry-pick → cherry-pick --continue, revert → revert --continue. runGit sets GIT_EDITOR=true on every spawn for the same reason it sets GIT_TERMINAL_PROMPT=0: measured, --continue with no editor fails ("Terminal is dumb, but EDITOR unset") and with a real GIT_EDITOR=vim inherited it BLOCKS on vim until the timeout kills it.
  • --ours/--theirs are INVERTED during a rebase, so the resolve buttons are labelled from the file's own conflict markers. Measured on the same two commits: a merge conflict's --ours yields the branch you are on while a rebase conflict's --ours yields the branch being rebased ONTO — a button that says "ours" and runs --ours silently takes the other side in half the conflict states. parseConflictMarkers reads the <<<<<<</>>>>>>> labels off the working file (via GET /api/fs/git?conflictMarkers=1&file=…, one read when the row's menu opens — NOT part of the status payload, which republishes on every tool call), and the buttons read take HEAD / take feature/payments. A failed read falls back to the words ours/theirs; the actions still work.
  • revertPath REFUSES a conflicted path (src/server/lib/fs/git-revert.ts). The three-step discard (reset → checkout → clean) succeeds on a UU path while doing something the user did not ask for: measured, it threw the conflicted content away, restored the pre-merge version, and LEFT MERGE_HEAD in place — git status afterwards read "All conflicts fixed but you are still merging". A trash icon that silently ends a conflict by picking one side, and leaves the operation open, is worse than no trash icon.
  • Merge is merged BY NAME, not by SHA. git merge <sha> writes Merge commit '<sha>'; git merge <branch> writes Merge branch '<name>' (measured, both). The commit modal's merge_commit still takes a hash (a legitimate need) but gained a -- separator and a hash-shape guard — measured, git merge --abort ran when the "hash" was --abort. Every hash operand is guarded (hashFor), every client path is resolveRepoPath-checked, and a branch name is validated with git check-ref-format --branch.
  • The commit modal opens with EVERY row collapsed, and a row is its own toggle. The modal seeded selectedHash from the first commit, so History arrived with one commit already grown — action strip, body and file list all rendered — pushing every other commit down before the reader asked, and a second click on that row could not collapse it. The state is now one hash in useCommitExpansion (hooks/workspace/commit-expansion.ts), '' on open: clicking a row opens it, clicking the open row closes it, opening another closes the previous one. The page is part of that state, so a refresh or a reopen starts collapsed again — the modal stays mounted while closed, so state alone would carry the last open row forward. A row with neither a body nor changed files is not a toggle at all (no cursor-pointer, no aria-expanded), because "opening" it could only light its graph node. GraphCanvas's halo and the row re-measurement key off the same hash (expandedHash), so the node and the detail cannot disagree about which row is open.
  • Sync PULLS WITH A MERGE, because --ff-only cannot reconcile a diverged branch. pullBranch (src/server/lib/fs/git-publish.ts) runs git pull --ff --no-rebase --no-edit. The previous --ff-only exits 128 with fatal: Not possible to fast-forward, aborting. on exactly the state a Sync button exists for — one local commit and one on origin — so Sync threw before it reached the push, the badge stayed at ↑1 ↓1, and the panel reported git's advice text as an error. The flags are stated rather than inherited: measured, pull.ff=only reproduces the refusal and pull.rebase=true rewrites local commits, and a Sync button must not mean two things per repository. A fast-forward still happens where one is possible (verified against a behind-only branch). A pull that stops on a conflict is SUCCESS, not failure — measured: exit 1 with MERGE_HEAD in place and UU rows, which is the state the operation bar exists to show — so the handler accepts a started merge the way expectStarted does. The sync action (git-actions-branch.ts) then SKIPS the push (git refuses it while the merge is unresolved, and reporting that as a failed Sync hid the conflict surface) and refuses outright when an operation was ALREADY in progress, naming it. The Sync control carries aria-label="Sync with upstream": its row's only text is the count, so an accessible name built from it would read ↑1 ↓1. Its in-flight mark ROTATES the glyph it already has (RefreshCw + animate-spin), and is derived from the ACTION, not from the panel's isBusy — a swapped-in spinner changes the control's identity mid-press and moves nothing for the reader who learned the refresh mark, while isBusy also covers the status read and every other mutation, so a commit or a topic refresh would spin the badge; GitPanel passes syncing only while sync/push/pull is in flight, and the e2e spec holds the POST open to observe it (an unheld pull+push finished before a static glyph could be told apart from an unpressed button).
  • Branch rename: git branch -m does NOT move the upstream. Measured: after renaming feature → feat2 the config still reads branch.feat2.merge = refs/heads/feature, and a plain git push then REFUSES ("The upstream branch of your current branch does not match…"). The remote half is therefore push -u <remote> <new> (which re-points the upstream as it publishes — verified) + push <remote> --delete <old> + fetch --prune (without the prune the stale origin/<old> survives and the dropdown keeps offering it). It is a checkbox, OFF by default, and the dialog names the three commands. A collision is git's own refusal, including a case-only rename (fatal: a branch named 'Main' already exists) — and -M does NOT help that case either, so the dialog must not offer "force" as a way around it.
  • Branch delete is -d first, -D only on an explicit second step. git branch -d refuses an unmerged branch (error: the branch 'feat' is not fully merged — verified) and that refusal IS the safety net. The flag travels as force=1 and is read as exactly that: the confirm path once dropped it, so ticking the box deleted with -d anyway — a bug the e2e spec now pins.
  • The branch list is ONE for-each-ref, and its hardest case is the EMPTY track. %(upstream:track) measured in every form: [ahead 1], [behind 3], [ahead 1, behind 3], [gone], and EMPTY for a branch with no upstream — including a branch several commits ahead of everything, so an empty track renders unpublished and never "in sync". %(ahead-behind:HEAD) is deliberately unused: it answers "ahead of the CURRENT branch", not "ahead of the upstream" (measured: a branch two commits ahead of main reads [2 0] while its track is empty). Cost on 501 branches: 0.01s → 0.03s. A detached HEAD is dropped from the branch list (it reported the literal string HEAD as a checkoutable branch) and the toolbar shows it as a sha.
  • The amend checkbox PRE-FILLS the draft with the message it is about to rewrite. git commit --amend REPLACES the message, so an empty box asks the user to retype what is already in the repository — and the common amend is a tweak to the previous subject (a typo, a missing scope, a ticket id). Ticking Amend loads HEAD's message via ?headMessage=1 (readHeadCommitMessage, lib/fs/git-log.ts — %B, so a multi-line message and a merge commit's own message round-trip whole) and seeds the draft. The read is ON DEMAND, never part of the status payload: that read travels on the realtime git: topic and is republished on every tool call, so a payload carrying it would pay one git log per tool call for a checkbox nobody ticked. Three rules keep the seeding from becoming its own bug, and all three live in useCommitBox (client/hooks/workspace/commit-box.ts, unit-tested): a draft the user already typed is NEVER overwritten (the check runs against the LIVE draft when the answer lands, not the one seen when the box was ticked, so typing during the fetch wins); the read's answer is discarded if the box was un-ticked while it was in flight; and un-ticking clears the seeded text ONLY — seededRef records what the hook wrote, so a draft the user edited survives, which is what makes "ganti total" work. The seeded text is ordinary editable text, not a placeholder, and the box says where it came from (previous message loaded, hidden on the first edit) so an auto-filled draft does not read as a stale one. A repository whose HEAD is unborn answers null and nothing is seeded — the placeholder stays, exactly as before.
  • The stash section is pinned to the panel's FLOOR, below the change list, and its body rises. The panel is a flex column and GitChangesList is the flex-1 member, so the stash (a flex-shrink-0 sibling, rendered last) stays on screen while the list above it scrolls — and opening it SHRINKS that list instead of pushing the section down a scroller the reader would have to chase. Measured in the browser: expanded, the list went 567px → 478px while the section's bottom stayed at the panel's own bottom edge; a section merely placed after the list in DOM order but INSIDE the scroller sat 394px above the floor. The e2e spec pins both halves (below the commit box, and within 48px of the panel's floor), because either alone is satisfied by the wrong layout.
  • The reveal is grid-template-rows: 0fr → 1fr (.section-reveal, src/client/tailwind.css), not max-height. The wrapper is the grid, the open state is a data-expanded attribute, and the CHILD carries min-height: 0 + overflow: hidden — without either the track cannot collapse below the content's min-content size and the section renders at full height with no animation. The clamp child must carry no padding: overflow: hidden clips the content box, never the padding box, so a pb-2 on it left an 8px sliver of empty body under a collapsed section (measured in the browser; the padding moved one level in). The body stays MOUNTED in both states — that is what the reveal animates — so it is marked inert while collapsed, or the hidden message field stays tabbable and its controls are announced (verified: focus is refused on the input, the checkbox and a row's Drop button while collapsed, and the toggle itself stays focusable; all three take focus once open). prefers-reduced-motion turns off the transition and nothing else — the layout is identical either way (verified: 0 → 88.5px in one frame).
  • The disclosure glyph is the change list's own (▾ open, ▸ closed, in a w-3 track, aria-hidden), not a Lucide chevron — and it must carry font-mono. Three sections in this panel already taught the reader that mark, and a fourth drawn as an SVG icon in a different size and colour reads as a different control. The glyph is a TEXT character, so its face decides its size, and that was the whole bug: the change list renders inside a font-mono container (12px, ui-monospace) while the stash header inherited the app's sans stack, so the IDENTICAL codepoint at the IDENTICAL font-size came out a quarter smaller — measured ink 4.65×4.65px mono against 3.49×3.56px sans (getComputedStyle reports 12px in both cases, which is why comparing font-size proves nothing). The fix is one font-mono on the glyph span; verified in the live panel: all three headers now measure x=1074, box 12×16, ui-monospace, 12px, weight 600, ink 4.65. git-panel.e2e.ts compares the stash glyph's computed font and ink against the live Changes header's own glyph, and that spec's fixture now leaves a real working-tree change behind — on a clean tree the Changes header does not render at all, so the reference silently resolved to the stash glyph itself and the assertion passed with font-mono removed (measured).
  • The whole row toggles, and the toggle is a full-width <button> — not a <div onClick> like the change list's headers. It used to wrap the LABEL alone, which left a measured 189px dead strip in the middle of a 334px row: clicking "the section row" did nothing and only the words Stash responded. The button now carries the row's own padding (pl-3 pr-2) plus flex-1, spanning everything up to Save (1062→1328px on a 334px panel; a click at five positions across that span toggles every time, and a real trusted CDP click confirms it). A <button> rather than a clickable div because the row needs aria-expanded/aria-controls and a Tab stop; Save is a SIBLING button (a button inside a button is invalid HTML and its click is swallowed), so no propagation guard is needed — verified: Save stashes without toggling the section. The e2e spec clicks the row's EMPTY MIDDLE, not the label, because a label click passes with the bug still in place; it also asserts the click point is inside the toggle's own box (1146 vs <1015.6 with the old markup).
  • The open flag persists per session (git.stashExpanded, beside the change list's own section flags), restored through the real session-state provider (verified: reload comes back expanded). The list is still fetched ONLY when the section is opened, so a section nobody opened costs nothing, and Save stays available while collapsed because it needs no list.
  • The panel's modals live in PanelModals.tsx and the action dispatch in git-actions*.ts. The route (routes/fs/git.ts) was at the repo's 350-line ceiling with twenty inline branches and this feature added a dozen more; the handlers are now two domain tables (git-actions-worktree.ts, git-actions-branch.ts) merged into one GIT_ACTIONS dispatch. Every modal built on the shared common/Modal.tsx shell now carries role="dialog" + aria-modal — the hand-rolled git-panel shells already did, and a screen reader cannot announce a panel it does not know is a dialog.
  • tests/e2e/specs/git-panel.e2e.ts is the regression net for all of it (10 specs, real mode, a real repository per test via seedWorkingRepo). The bugs above are invisible to a unit test — they are a real DOM, a real git state and a real click. It pins: a conflicted file listed once under Conflicts with the bar present, resolve-through-the-UI concluding a merge with a real merge commit, abort restoring the tree, a rebase concluded by rebase --continue, a stash pop offering no Continue, discard refused, rename in place, -d refused then -D via the checkbox, stash drop confirmed, the stash section's pinned placement, and amend rewriting rather than appending. A fixture's git calls that FAIL by design must use gitAllowFail (execFileSync throws on a non-zero exit, and a conflicting merge/rebase/stash pop exits 1 with the state left behind — the whole point).

Diff panel — what a load costs, and the badge's second diff

  • The change badge is read OFF the merge view's chunks, never re-diffed (countChunks, diff-panel/changes.ts; the handle's counts(), diff-panel/merge.ts). It used to call Chunk.build(a, b) itself, and a bare Chunk.build uses NO diff config (scanLimit: 1e9), while the view builds its chunks with the package's defaultDiffConfig (scanLimit: 500, coarse fallback on a big file). So the panel paid a SECOND, far more expensive diff on every load and could print a number describing a diff nobody was looking at. Measured on a 27 000-line pair with 540 changed lines: the badge's own diff 4.0 s and 540 additions/deletions while the rows on screen read 26 951; on a fully rewritten file the unconfigured scan was 3.4 s at 500 lines, 14.5 s at 1 000, 55 s at 2 000. Now the badge costs 0.1 ms on the same 27 000-line pair and cannot disagree with the rows. merge.test.ts pins both shapes' numbers, including after setDocuments (the unified view's original lives in its own state — a stale read here would count the previous pair).
  • The cost tracks how much CHANGED, not how many lines — which is why a file under 1 000 lines could still feel slow. The badge's own scan on small rewritten pairs: 200 lines rewritten = 667 ms, 400 = 2.9 s, 600 = 7.0 s, against 59 ms for 900 lines with 30% scattered edits and 1 ms for 900 lines with 4 edits. A diff opened in an idle harness cost 276 ms end to end (94 ms for the request, the rest mount + tokenize), so the panel's own mount is not what a reader notices; a dense rewrite was. countChunks reads the view's chunks, which are already built: 0.04–0.1 ms on every one of those pairs.
  • The whitespace fold is memoized, because it is a character diff of both documents. With the toggle on, foldWhitespaceOnly ran in the render body and the panel re-renders for its own reasons (the count report, the hunk label, a busy flag): one fold of a 30 000-line untouched file cost 324 ms, and a 5 000-line pair that was wholly rewritten cost 12.7 s. It is now useMemo'd on (ignoreWhitespace, original, next). Note the fold is not what makes the panel slow on a +-heavy file — the view's own diff is (below).
  • What is left is the diff itself, and @codemirror/merge gives up on large inputs. The mount is where the cost lives: measured in happy-dom, a 2 000-line pair mounts in ~90 ms and 30 000 lines in ~280 ms (unified; the split shape's MergeView is faster because it shares one diff), while 200 000 lines takes 6.6 s — and past the scanLimit the fallback reports nearly the whole file as changed, which is also why such a file's badge says "everything". There is no size guard on this path today; a very large generated file is the remaining "the diff panel is slow" case.
  • The server is not the bottleneck: one GET /api/fs/git?fileDiff=1 measured 40–65 ms end to end against a live server (five sequential git probes on a cold path), and the same request against a registered workspace outside the app root measured 50–145 ms. A slow diff panel is client-side.
  • A markdown diff was slow in the TOKENIZER, and only markdown showed it because the editor opens a .md in its rendered preview (so the diff is the one place that tokenizes markdown prose by default). Shiki's markdown grammar states bold/italic as nested lookarounds, and with the JS regex engine the cost grows with the number of spans on a line: measured on .wiki/App-Shell-and-Layout.md, one 140-line viewport cost 6.3 s at the 12 000-char guard, 4.1 s at 4 000, 500 ms at 2 000 and 12–38 ms at 1 000; those dense single-line bullets are how the wiki is written. code-surface/shiki.ts therefore has LINE_CHAR_LIMITS (markdown: 1 000) beside the minified-bundle default, and lines at or past the guard render plain. Mounting the same pair through mountUnifiedDiff in happy-dom went 506 ms → 38 ms (an identical pair, 12.9 s → 123 ms). The other grammars keep the 12 000 guard.

Worktrees (a chat born in its own checkout)

  • A worktree session is born there, never relocated. Kabmo owns the worktree (no /wt, no omp worktree): POST /api/agent/new is sent with the worktree as cwd, so omp --mode rpc-ui --cwd <worktree> writes its session under the worktree's own project directory and --resume reports the same cwd. omp's own /wt is the wrong foundation for exactly the reasons measured against it — it rewrites the JSONL header and MOVES the file (wrapper.sessionFile goes stale, so reconcileSpawnApprovalMode silently no-ops), its session_info_update carries no cwd, and it carries every uncommitted change into a second checkout.
  • The composer's target is TWO dropdowns, and the split is the feature. WorkspacePicker (chat-timeline/target-picker/WorkspacePicker.tsx) answers which project and lists folders only; WorktreePicker answers which checkout of it and lists the root, the two create paths and the worktrees. They were merged into one menu once and it read as a workspace picker with branch rows buried in it — a user looking for another project scrolled through worktrees, and a user looking for a worktree had no control of its own to look for. OpenChamber's composer draws the same pair (DraftTargetSelectors.tsx: a Popover for the project, a separate Select for the directory), which is why its trigger never has to mean two things. Each trigger carries the accessible name that says which question it answers (Workspace: kabmo, Worktree: wt/fix-socket), because two unlabelled triggers reading kabmo and main are both ambiguous.
  • The worktree trigger reads the BRANCH, not the word "root". A repository sitting on main and one sitting on wt/scratch are different places to start a chat, so the trigger shows the checkout's branch (main, wt/fix-socket, detached) and replaces the glyph with a ⚠ when that checkout has uncommitted files — the notice has to be visible before the first prompt, not in a tooltip. That is why the list is read on MOUNT rather than only when the menu opens (measured on this repository: ~150 ms, one spawn per worktree for its dirty count); opening re-reads, so a worktree made in another tab is in the list being looked at.
  • A workspace that is not a git repository gets NO worktree control, and the server decides. GET /api/worktrees answers isRepo: false with an empty list for a plain folder — a 200, not the 500 the identity read used to throw (it derives the repository id from the root commit, which a notes folder has none of) — and WorktreePicker draws nothing. A permanently disabled control in every notes folder is noise, and a control that can only refuse promises a worktree the folder cannot hold. isRepo is null until the payload lands, and the control waits for the answer rather than guessing from the folder's shape. Settings → Projects → Worktrees names the same distinction ("Worktrees need a Git repository." rather than "No worktrees yet.").
  • Picking a folder CLEARS the worktree pick, from the workspace control's own handler. A checkout of the previous project names a path the new one cannot resolve. It is deliberately not an effect comparing target.folderId with the selected folder: a reload restores chat.spawnTarget a beat before the folder resolves, and a mismatch check in that window wipes the very pick it was meant to protect.
  • chat.spawnTarget ({folderId, worktreePath}) is read through a REF at send time (spawn-target.ts), because the composer is remounted by a stretch, a tab switch and a reload while the send handler is created once per deps record — the same hazard waiting/choice.ts documents. The send path resolves worktreePath ?? project_path.
  • isWorkTree (lib/fs/worktree/list.ts) is the ONE "is this a repository" probe, used by the list route and by planWorktree/removeWorktree. They had their own copies of git rev-parse --is-inside-work-tree, which is how the list route came to have no check at all.
  • The worktree list is NOT on the realtime git: topic. That payload republishes on every tool call, and this read costs a git status per worktree plus a session scan (sessionCwdsUnder, ~150 ms measured) — the same reasoning git-repo-details.ts records for keeping the repo modal off it. It is read by hand: the composer's control, Settings → Projects → Worktrees, and the delete dialog.
  • The tests are per rule, not per component. target-picker/WorkspacePicker.test.tsx pins that the folder menu contains NOTHING about worktrees (a worktree row there is the merged menu returning) and that a folder pick clears the worktree; target-picker/WorktreePicker.test.tsx pins that a non-repository draws no control, that the trigger names the root branch before the menu is opened, the three menu groups with creating above the list, and the root row clearing the pick; worktree-modal/index.test.tsx pins the generated branch in the FIRST paint (an effect-seeded field is the window a user types into, and the dialog then created wt/calm-iguana instead of reporting that main is taken). tests/e2e/specs/worktree.e2e.ts is the assembled proof: a real create through the menu, a real send that spawns inside the worktree (the sidebar chip is derived from the session's own cwd), and a real inline refusal — it addresses the two triggers separately, because a spec that clicks one trigger for both is the merged menu coming back.

Search Panel (right-panel Search view)

  • The result list is VIRTUALIZED, and the reason is measurable. A search for a common word matches tens of thousands of lines: const in this repo produced 19,376 hits, and mounting them all cost 385,706 DOM nodes and 34 s of blocked main thread for one five-step scroll (headless Chromium, 4x CPU throttle, mobile viewport) — the profile put 70% of it inside Shiki's JS regex engine (findNextMatchSync), because every mounted row re-tokenized its line on each re-render. Only the rows a viewport can show are mounted now: 44 rows, 1,290 nodes, 0 ms blocked for the same scroll.
  • The layout is arithmetic in src/shared/lib/fs/search-list.ts, not measurement at render time. Rows are a flat sequence (group headers then their hits), each row's height is the measured text box PLUS its gap, and searchWindow binary-searches the prefix sums for the mounted range. Gaps live in the heights rather than in space-y-* because a windowed list has a different set of siblings on every scroll — a CSS margin would be drawn between whichever two rows happened to be adjacent. The wrapper carries the layout's height and the measurement targets the TEXT box inside it ([data-search-header] > div, [data-search-hit] > button): measuring the wrapper would feed the gap back into the value that defines it, and rendering natural heights instead of the layout's would leave every row a gap short so a jump landed on the wrong hit — verified by comparing 1,779 rendered rows across 41 scroll positions against the captured SSE payload: 0 mismatches, total height exact to the pixel.
  • scrollTop is measured in the spacer's coordinates, so the container's padding is carried by the top spacer and the total is the last row's offset plus its height. overflow-anchor: none is set because the browser's own scroll anchoring fights a list whose rows mount and unmount underneath it.
  • A row's highlight is memoized TWICE, and both halves are needed. SearchRow is memo'd (with a useCallback onOpen — without a stable identity the memo is useless), and highlightSearchLine (src/shared/lib/code/highlight-cache.ts) is a bounded LRU in front of highlightCode, because a virtualized list unmounts rows as they leave the viewport and would otherwise re-tokenize a line every time it scrolled back. A line whose grammar is not ready is deliberately NOT cached: highlightCode requests the grammar on the way through and falls back for that pass, and nothing re-renders when it lands — so a cached fallback would pin the row to plain text for the life of the cache (verified in the browser with css, a non-eager grammar: the rows are tokenized once the grammar arrives). The bound is 2,000 entries and the cache size is exposed (highlightCacheSize) because a hit and a recompute return equal strings — the map is the only observable.
  • The scroll-fade is ONE document listener, not a per-component hook. installScrollbarActivity() (src/client/lib/scrollbar-activity.ts, called from main.tsx before the first render) registers a single CAPTURE-phase scroll listener on document and puts data-scrollbar-active on event.target for 5s after each scroll the USER caused; tailwind.css declares ::-webkit-scrollbar-thumb transparent and paints it for [data-scrollbar-active]. The gate is an ARM, not a time window, and that is what made it work in WebKit. One wheel/touch/keydown/pointer-press arms exactly ONE reveal, which the next scroll consumes; a held pointer is tracked as state instead. Two window shapes had already failed: Date.now() inside the handler threw away the user's own scroll whenever a frame ran long (Chrome), and comparing Event.timeStamp on both sides still failed in WebKit, which stamps a scroll when it is DISPATCHED — measured in WebKit 27.2, a wheel followed by a 700ms blocked frame produced a scroll stamped 703ms after that wheel and the bar stayed dark while the container moved 240px. An arm asks no clock question, so it holds under either stamping rule, and being one-shot it still cannot pin a bar during a stream (verified: one wheel, then 60 programmatic scrolls over 3s — lit, then dark 5s after the wheel). The arm expires after SCROLLBAR_INPUT_ARM_MS (2s), and a window blur clears it. The arm is also BOUND to the container the input landed in: a wheel that cannot move its container fires no scroll, so its arm would otherwise stay unspent and the next programmatic scroll in ANY panel could spend it — measured as a bar lighting 250ms after a dead wheel for a scroll nobody made. Only a scroll inside that subtree spends it, and an input naming the document/window itself (a keydown with nothing focused) stays unbound.Capture is the whole mechanism — scroll does not bubble, so a bubble-phase document listener would only ever see the page's own scroll and every panel's bar would stay hidden with no error anywhere; event.target is the scroller, verified in Chromium. The viewport's scroll reports document while the bar belongs to the root element, so that case maps to documentElement. This replaced useScrollbarFadeRef (src/client/hooks/ui/scrollbar-fade.ts, deleted, and the copy in @kabmo-labs/kabmo-ui, removed as a breaking change): a per-component hook could only cover the ~11 containers that opted in, so a modal, a dropdown, the git panel and every plugin panel drew a permanently visible bar while the chat timeline and the sidebar faded. The hook was also re-render-free for the same reason it existed (a useState version re-rendered every row on scroll — the trigger for the 34 s search-panel profile above), and the listener keeps that property: it touches one attribute on one element and never enters the component tree. Two counters went with the hook — isScrolling (hooks/chat/timeline/scroll.ts, threaded through ChatTimeline → TimelineBody) and the timeline-scrollbar-* class pair — and scrollbar-overlay-static / scrollbar-overlay-scrolling / the bare scrollbar-overlay are gone from all ~55 call sites, since a container no longer states its own reveal. .scrollbar-overlay-container remains as the shared scroll-surface marker and the selector the tests address a scroller by; it now declares overflow-y: auto, not overlay (Chrome computes overlay to auto — measured on 150 — so the declaration had already stopped doing anything). The reveal is gated on recent INPUT, and that gate is the fix for a bar that never disappeared. A programmatic scroll fires a real scroll event with isTrusted: true — verified in Chromium for el.scrollTop = n and for a smooth scrollTo — so a listener keyed on the event alone cannot tell the page's own scrolling from the reader's. Measured on the chat timeline against a live stream: the run's stick-to-bottom pinToBottom re-armed the fade on every frame, the attribute never lapsed across 24 s of one turn, and the bar was still painted with the pointer parked in a corner — the reported "the scrollbar does not disappear when there is no user activity". The same shape covers every scrollIntoView (a rail jump, a search reveal, an outline jump) and the editor's scroll restore. SCROLLBAR_INPUT_WINDOW_MS (250) therefore marks the user as scrolling from a wheel/touch*/keydown, and a scroll inside that window is theirs; a HELD POINTER (pointerdown/mousedown until pointerup/mouseup/pointercancel, plus window blur so a release that never arrives cannot leave the flag stuck) covers a scrollbar drag, which outlasts any input window. A scroll that arrives outside both leaves an existing reveal and its timer alone rather than re-arming them, so the fade runs on the user's clock and a bar disappears mid-run on schedule. scrollbar-activity.test.ts pins the capture reach, the per-element fade, the restart-on-scroll-during-cool-down, the root mapping, the install idempotency, and the gate in both directions (a user-driven scroll reveals; a bare one reveals nothing and does not extend a live reveal; a drag longer than the input window stays lit; a release that never arrives does not stick). Each case mounts its OWN Window, because the install guard and the input clock are per document — a shared document made every case inherit the previous one's wheel. Verified in real Chrome against the dev server: a wheel revealed the bar and it was gone 6 s later, while a 12 s programmatic scroll (the streaming pin's shape) left it unpainted throughout. bundler/css.test.ts pins the built sheet against the module's own SCROLLBAR_ACTIVE_ATTRIBUTE, so a rename on one side cannot silently disable the fade.
  • Every scrollbar in the app is ONE size and ONE palette. :root holds --scrollbar-size: 8px, --scrollbar-radius: 4px and the three thumb colours (idle: transparent, active and hover as color-mix over --theme-ink), and the global ::-webkit-scrollbar* rules are the only place any of them is declared. Colour therefore follows the theme on every bar, including a palette switched at runtime (verified: the resolved thumb went #141310 → #EDECEE on a light→dark flip). The terminal's own 8px/22%/42% block with a painted track was deleted — it was the drift this exists to remove — and since the renderer swap the terminal draws its scrollbar inside its canvas (8px at the right edge, only while scrolling), so there is no DOM bar of its own to diverge — and the track is transparent rather than --theme-canvas (a painted track draws a stripe across a dropdown or a modal card). ::-webkit-scrollbar-thumb:hover is declared AFTER the active-state rule at equal specificity, so the thumb under the pointer wins in either state. Note the platform limit when verifying visually: under macOS overlay scrollbars (this Chromium's default) ::-webkit-scrollbar painting is ignored entirely and the gutter measures 0, so a headless screenshot cannot show the bar — the mechanism is still testable through getComputedStyle(el, '::-webkit-scrollbar-thumb'), which resolves the cascade either way.
  • One run delivers at most MAX_SEARCH_RESULTS (5,000) matches, and the cap is stated in one place. The route stops at the cap and kills the rg child (runRipgrep's signal) rather than draining a walk whose output is discarded, reports truncated on the done frame, and the panel prints "Showing the first 5000 matches" from the same constant. Measured: const went from a 3 MB payload and 19,376 rows to 848 KB and 5,000, in 51 ms. A batch that crosses the cap is trimmed rather than overshot, so the number in the notice is the number of hits the panel holds.
  • The panel is two components because the result list is expensive to re-render. index.tsx owns the state and the search effect; Body.tsx owns the markup (fields + SearchResults). A keystroke in the Replace field re-renders Body and leaves the memoized rows alone — with the fields and the list in one component every replace keystroke rebuilt the whole list.
  • Both fields carry a clear (×) inside their own box, and it hands focus back. The button lives in the SAME wrapper the <input> does (a control that empties an input belongs to that input — parked beside it, the panel reads as two unrelated controls and the × looks like it clears the panel), it exists only while the field holds text (an always-present × is a control that can do nothing), and it focuses the input after clearing, because the reason to clear a query is to type a different one. The replace field therefore became a wrapper too — its border moved from the <input> to the box so the × sits inside the visible field rather than over the panel edge. Body.test.ts pins the same-parent relationship, the empty-state absence and the focus; search-panel.e2e.ts measures the button against the field's own box in a real browser.
  • On the phone the drawer's active tab is PERSISTED (layout.mobileRightPanel), and that is a performance decision as much as a convenience: MobileRightSidebar unmounts with the drawer, so whichever view is selected is the one that mounts and re-runs its own fetch on the next open. Coming back on Search re-ran a query that can hold thousands of hits, for a user who never asked for a search.

Terminal panel — a shell starts when the panel is OPENED, not when it mounts

  • Mounting is not opening, and the difference is one idle shell per session visited. The desktop stack keeps every built-in view mounted and hides it with CSS, and the terminal is liveWhileHidden so its stream survives a switch — so a socket opened on mount started a PTY for every session the user merely looked at. Measured against a live server: 18 idle /bin/zsh -i -l children of the Kabmo pid in 3h58m, in bursts of seven inside two minutes, ages from 2h12m down to 19s, with a matching terminal.id minted for each distinct session. The decision is one pure table (hooks/workspace/terminal/connection.ts): connect when the panel is ON SCREEN (active && enabled) or the session has already opened it; persist the opening only on the first on-screen render, and only once the session-state blob has loaded.
  • Once opened, the shell belongs to the SESSION, not to the view. terminal.opened is persisted beside terminal.id, so switching to Files, collapsing the right column or reloading the page reattaches to the same PTY instead of leaving it unviewed for the 30-minute idle reaper. The socket effect is keyed on that decision, so leaving the panel visible keeps the viewer (and the shell) and hiding it does not tear the stream down.
  • The screen-side flag is visible: active && enabled from TerminalPanel; active already means selected and the column is open, and enabled carries the workspace gate a shell cannot launch without. A phone drawer mounts only its active tab, so there the first mount IS the opening — no extra latch needed.
  • Opening the panel also takes focus, and the request survives the async renderer mount. Neither layout unmounts a hidden view, so the terminal's <canvas> and its focusable container (Terminal.open stamps tabindex=0 contenteditable="true" on the root; the textarea beside it is only a paste sink) already exist from an earlier open — and nothing in the panel moved focus there, so the first command after a click on the rail went to the document and only a click on the canvas fixed it. TerminalPanel therefore focuses on active && enabled (terminal-panel/index.tsx), and focus.ts holds that request until mountTerminal resolves on a fresh open, when there is still no terminal to take it. The grid announcer no longer focuses on onReady: focus 120 ms after the grid settles is focus stolen from whatever the user clicked in the meantime. tests/e2e/specs/terminal.e2e.ts asserts [data-terminal-root] is focused both on the first open and after switching Files → Terminal.
  • A streaming panel HOLDS the viewport, and a press holds it before the engine has a selection. ghostty-web's writeInternal ends with viewportY !== 0 && scrollToBottom(), so every PTY chunk re-anchored the view to the live end: a wheel-up during tail -F was undone by the next frame (the "Latest" button never appeared) and nothing above the live line could be read. Worse for copying, a drag only starts a selection once it passes the engine's half-cell threshold, so a measured 2-row drag during a 100 lines/s stream copied 12 lines — the rows moved under the pointer between press and release. terminal-panel/scroll-hold.ts is the rule and the fix: a write holds the view when viewportY > 0, when a selection exists, or while a pointer is down on the canvas (captured on the container, released on the WINDOW so a drag ending outside the panel still lets go). The hold is an ABSOLUTE buffer row, not a distance from the bottom, because the same content must stay on screen as lines append; the restore goes through scrollLines, which clamps, fires onScroll (what keeps "Latest" honest) and repaints — assigning viewportY skips all three. The write is synchronous, so the library's own snap is never painted. Re-measured: the view holds 1.2 s into a stream, a 2-row drag copies 2 lines, the selection survives 1.2 s of arriving output for a later ⌘C, and clicking "Latest" releases the hold.
  • ⌘C in the macOS shell arrives as a DOM copy event, not a keydown, so the terminal listens for both. The shell's Edit menu claims the chord (that is what makes ⌘V work in the composer at all), and a measured WKWebView probe showed the page's keydown listener never fires for ⌘C or ⌘V while the menu is installed — the native copy: action fires a copy event on the focused element instead. ghostty-web only copies from its own keydown handler, so the canvas selection was lost and the native action copied the empty DOM selection. terminal-panel/copy.ts installs a copy listener on the terminal container: a non-empty getSelection() is written to event.clipboardData and the default is prevented; an empty selection is left to the platform. The browser path is unchanged (ghostty's keydown still copies and prevents the default, so no copy event follows). Windows and Linux have no native Edit menu in the way, but ghostty-web binds copy to Meta+C only and Ctrl+C must stay SIGINT, so installTerminalCopyChords adds the terminal convention Ctrl+Shift+C / Ctrl+Shift+V in the CAPTURE phase on the container — a bubble-phase chord would reach ghostty's encoder and be sent to the PTY instead. The copy chord writes through copyToClipboard; the paste chord reads through readClipboardText and feeds term.paste, so a bracketed-paste shell still gets its markers. Right-click Copy is ghostty's own contextmenu handler: it puts the selection in the hidden textarea and focuses it, so the native menu's Copy acts on that selection rather than the empty DOM one; tests/e2e/specs/terminal.e2e.ts asserts the textarea holds the full selection after a right-click (the native item itself is browser UI and cannot be clicked from the page).

Panel Plugin Kit (@kabmo-labs/kabmo-ui)

  • The kit is the seam between the host and every panel — built-in or installed — so the surface a built-in view is allowed to use is the surface a plugin gets. It is a published package (packages/kabmo-ui/), which is why it reads the host through configureUiKit-injected services instead of importing @/…: an in-tree panel importing the kit and a plugin bundle importing it take the SAME code path, and the build shims the specifier to globalThis.__kabmoPluginRuntime.ui for a bundle while it is a plain import for the app.

  • The surface is four modules, not one file (packages/kabmo-ui/src/): services.ts (the injected services and the two prop contracts), panels.ts (usePanelInfo, useTheme, useSessionValue, useSessionState, useWorkspaceFile), fetch.ts (useKabmoFetch), panel-host.tsx (PanelHostProvider + usePanelHost), and components.tsx (the presentation kit plus Markdown). index.tsx is the package's public entry and re-exports them; the app and the shim both read the package root. The scrollbar fade is deliberately NOT part of the kit any more: it is a host-level document listener that covers a plugin's containers without the plugin knowing, so there is nothing to export.

  • usePanelHost is a Preact CONTEXT, never a module singleton, and that is load-bearing. The desktop stack keeps every built-in view mounted at once (hidden with CSS, so a tree's expansion and a terminal's buffer survive a switch), so "the panel currently being rendered" is not one process-wide fact — there are eleven of them live at the same time. A module-level value handed the wiki panel the terminal's rootPath and its onClose. Both layouts wrap each panel body in PanelHostProvider with the SAME props object they hand panel.render(props), so a component nested inside a view reads exactly what its top-level one was given.

  • useKabmoFetch is the kit's own reader, for a plugin panel that reaches Kabmo's HTTP API. Kabmo's own data-backed views have moved to the realtime socket (useRealtimeTopic), but the kit keeps this because a plugin cannot import the host's hooks: it carries the three behaviours a hand-rolled fetcher gets wrong — a late answer for a request the user has moved past is DROPPED (a sequence guard), a new URL clears the previous payload BEFORE reading (so a stale list never renders under a new session's name), and a hidden or disabled view issues no request at all. packages/kabmo-ui/src/fetch.test.tsx pins all three, plus the error path keeping the server's own reason.

  • A plugin's background service can be the thing that kills the server, so the process boundary contains its rejections. api.background.service(id, { start }) runs start() at declaration and background.server.ts attaches a .catch to whatever it RETURNS — but the shipped stats plugin starts a floating async IIFE inside start(), so its promise is undefined and the .catch never sees it. Measured: a data directory deleted under a running server produced SQLITE_IOERR_VNODE from that IIFE's readSampleMs(), Bun's default exit-on-unhandled-rejection took the process down with exit 1 mid-session, and every live session and every other plugin went with it. installRejectionGuard (src/server/lib/lifecycle/rejection-guard.ts, called from src/server/index.ts before any timer, plugin or socket starts) logs [kabmo] unhandled rejection (contained): <stack> instead. After the fix the same deleted directory leaves the server answering 200 and /api/settings reporting {"error":"disk I/O error"} — a reported failure, not a dead process. uncaughtException is deliberately NOT handled: a synchronous throw out of a handler leaves the process in an unknown state, and continuing from there is how a server answers from half-applied writes.

  • The Stats panel names an ACP chat from a lease Kabmo writes, because argv names neither the chat nor the harness. omp's RPC hosts hold an OS lock on ~/.omp/run/session-owners/<id>.lock (flock on macOS, an open-file-description lock on Linux since omp 19.0.1), and the panel read that descriptor to name a session; an ACP agent holds no such lease, so the panel fell back to argv and drew every claude/codex/opencode chat as a bare npx row inside Kabmo's own group — measured against the real launch table, 12 of the 13 ACP harnesses (only omp acp had an argv shape the panel recognised). src/server/lib/harness/session-lease.server.ts now writes <data>/run/harness-sessions/<pid>.json at spawn (state starting), rewrites it after the handshake with the session id and the stored title, and removes it on destroy; a prewarm gets a prewarm record that the claim overwrites while keeping startedAt. The reader (marketplace/plugins/stats/src/harness-leases.ts) rejects a record whose startedAt is more than 5 s from the probe's own start time, so a recycled pid is never named after a chat that no longer exists. The record is a FILE rather than a database row because the reader is a plugin: its server half runs in Kabmo's process but has no database handle, and opening a second one is forbidden.

  • useRealtime answers null, never undefined, and every plugin render sits inside ONE boundary — the pair is what kept a broken plugin from doubling the whole app. The host answers undefined for a topic with no value yet (a restart's resync notifies every watched topic before its plugin's server half has published), and PluginRealtimeState.value is declared T | null, so a plugin that guards value !== null and then reads a field is CORRECT by that contract — the undefined threw inside StatsHeaderReadout (Cannot read properties of undefined (reading 'probe')). The throw escaped into the app's ROOT diff, Preact's queued render then re-created the tree from the container, and the console drew two identical navbars, two of every control, until a manual reload — measured on the assembled prod build: #app had 2 children, header.titlebar-drag-region ×2, insertBefore called twice from Preact's own diffChildren with the rerender queue (I/H) in the stack. After the guard the same restart flow reports 1 child, 1 navbar, no pageerror, twice over. The boundary (src/client/components/common/plugin-render-boundary/) is the second half and covers any plugin throw, not just this one: it wraps a navbar entry, a pending-interaction control and a right-panel plugin view, so a throw takes that one control off screen with a chip naming the plugin and the reason instead of reaching the host's root. packages/kabmo-ui/src/participant.test.tsx pins the null contract (it fails on the old code) and header-panel-buttons/index.test.tsx pins that a throwing entry leaves its siblings drawn.

  • useSessionState is useSessionValue for values that are not strings — a collapsed-phase map, a picked file — through getSessionJson/setSessionJson/subscribeSessionJson on the injected services. JSON-encoding them into the string slot would make every reader parse it back.

  • Markdown renders through Kabmo's pipeline by INJECTION, not by bundling it. The marked / KaTeX / mermaid / Shiki chain plus the file-opening and clipboard hooks is a large tree, and a plugin must not carry a second copy; the host hands the kit the MarkdownRenderer component (UiKitServices.markdown). A host that injects nothing renders the source as plain text rather than failing.

  • A plugin RPC that 404s during a restart's BOOT WINDOW is retried once, and GET /api/health is what makes that decidable. The console reloads the page the moment health reports a different pid/startedAt, but the listener answers health BEFORE the boot imports any plugin half (src/server/index.ts: serve → sync bundled plugins → import halves). Measured after a restart: the Stats header's watch fired 194 ms into the new page, the route answered 404 {"error":"No plugin \"stats\" is loaded"}, useRpc's effect never re-ran (its deps are the call's identity), and the readout sat on — for as long as the page lived — the halves were answering ~500 ms later. So health now carries pluginsReady (markPluginPlatformReady in src/server/lib/plugins/loader.server.ts, set in a finally so a failing plugin cannot wedge it false), and callRpc (src/client/lib/plugins/kit.ts) retries a plugin_not_loaded once, and only when the wait actually OBSERVED a boot window (src/client/lib/plugins/readiness.ts returns ready/booted/unavailable). A 404 on a settled server is the plugin genuinely not being loaded and is returned as it stands; a health probe that fails, or an older server with no field, is unavailable — never evidence of a boot, so no 15-second stall is put in front of a call that already has its answer. kit.test.ts pins all four paths and src/server/routes/health/probe.test.ts pins the payload field.

  • The repo scope IS in the kit, and it is the one Kabmo-specific store that had to be (packages/kabmo-ui/src/repo.ts + repo-picker.tsx). A plugin panel that lists a repository's commands needs the same nested-repo picker the Files / Search / Source Control / Terminal panels share, and the kit cannot reach the shared slot through its own session services — those carry a plugin. prefix, so a plugin reading workspace.activeRepo reads plugin.workspace.activeRepo, which nothing writes. So the host exposes it as four optional services (repoScope / setRepoScope / subscribeRepoScope / rescanRepoScope, implemented in src/client/lib/plugins/repo-scope-service.ts over the session slot plus repoStore), and the kit draws RepoPicker from them. Three rules are load-bearing. The stored value is a { root, repo } PAIR and a pair from another root is not this root's pick — the slot is per session, so a session moved to another workspace still holds the old value and a bare read would hand a plugin a path that does not exist under the root it describes (resolveRepoScope is pure and unit-tested for exactly that). No workspace is root: null, never root: '' — an empty string is a real value to a server that resolves it against its own cwd. And the rows carry their LABELS ({ repo, label, short }): the naming rule lives in the host's repo-label (the root reads as its folder's name, a list row keeps its whole path so jns6_5/token and jns7/token differ, a trigger truncates to the last segment), and the kit is a published package that cannot import it — a second copy is how one repo gets labelled two ways. subscribeRepoScope fans in BOTH the pick's slot bus and the plugin context, because switching SESSIONS changes the effective scope while the stored key is untouched. The host's own GitRepoPicker (src/client/components/workspace/repo-picker/) is a thin wrapper over the kit component now, keeping only what is host-specific: the modal it opens as the picker's optional onManage row, and the scope handle it assembles from the props its panel already holds.

  • HOST_CAPABILITIES names what ships, and it had fallen behind by five rows. src/shared/lib/panels/capabilities.ts is the ONE table a manifest's capabilities is checked against, and it said ['panel'] while a plugin's server half, its storage, RPC methods, a realtime topic and declared settings had all been part of the API for releases — so a manifest requiring any of them was refused BY NAME (manifest requires capability "server" which this Kabmo does not provide) for something the host did perfectly well. The rows are backfilled, repo-scope is the one this feature added, and capabilities.test.ts asserts each row individually plus the refusal for a capability nobody provides.

  • What the kit deliberately does NOT own: useRepoList (the discovery store and its invalidation tests stay host-side; the kit's scope service reads the same store), the terminal renderer (ghostty-web), CDP screencast, the file tree and the diff parser. Those stay host hooks — a plugin that needs one depends on the library itself. Terminal, Files, Search, Git, Wiki, Context and both Browsers therefore still import @/client/hooks/**; Kabmo's own Todo and Plan views read the realtime socket through the host's useRealtimeTopic, and useKabmoFetch remains the kit's reader for plugin panels.

  • The agent browser panel seeds its first frame with Page.captureScreenshot, because a screencast only pushes frames for a page that PAINTS. The panel sat on "Menunggu frame pertama dari browser…" for a live, idle tab — the normal state of a tab the agent finished with — and for the first paint after a load. Measured on Chromium 1248 (chrome-headless-shell and --headless=new, identical): a static page attached to and left alone delivered 0 Page.screencastFrame events in 3 s at everyNthFrame 1, 2 and 3, and a page that changed once and went idle swallowed the change at 2 (shown at 1); an animated page delivered 180/90/59 frames per 3 s, so the knob counts produced frames and discards the odd ones. Page.captureScreenshot answered in 8–40 ms for the same background tab, and decoding with ffmpeg showed the PAGE's pixels, not a blank surface (yellow #ffff00 for a yellow tab, magenta after it navigated to magenta). So frame-pipeline.ts snapshots on attach and after Page.loadEventFired, a live frame cancels an in-flight snapshot, and SCREENCAST_PARAMS is back to everyNthFrame: 1 — the frame-rate lever moved to frame-gate.ts, which can only DEFER a frame, never swallow a lone paint. Page.enable is now sent explicitly because Page.loadEventFired does not arrive without it.

  • A held frame must never be a dropped frame at the SSE boundary either. emitFrame in routes/browser/stream.ts used to return when the consumer was backpressured. That is harmless while the page keeps painting and fatal for an idle tab: the seeding snapshot is the ONLY frame it will ever get, so the drop is what re-created the "waiting for the first frame" hang downstream of a correct viewer. It now holds the newest frame and re-offers it every 120 ms.

  • The screencast paints into a CANVAS, because WebKit never releases a replaced <img>'s decoded frame. The panel used to hand each frame to <img src="data:image/jpeg;base64,…">. Measured on this machine (WebKit, 1 760 frames at 16 fps, footprint of the WebContent process): canvas only (no image) 15 → 29 MB, img.src = data URL 14 → 148 MB (~76 KB per frame), img.src = blob: revoked each frame 13 → 229 MB (~123 KB per frame), decode to an ImageBitmap → drawImage → close() 15 → 28 MB. A tab left on the panel for half an hour receives ~28 800 frames, so the img sink is gigabytes; client/lib/browser/frame-canvas.ts is the sink now, and it closes the bitmap in a finally because the decoded surface is the only thing that would hold a full RGBA frame (1 440 × 900 × 4 = 5.2 MB) per image. The frame RATE is a second lever on the same axis: SCREENCAST_PARAMS asks for everyNthFrame: 2 at 1 280 × 800 (it was every frame at 1 600 × 1 000, a size no panel in the app renders).

  • The archive verbs hand a Windows path to a tool that reads C: as a HOST, so the archive goes in on STDIN. extractArchive built tar -xf 'C:\…\src.tar.gz' -C 'C:\…\out', and GNU tar parses a C:\… file argument as a REMOTE host:path: the Windows gate failed the tar.gz round trip with tar: Cannot connect to C: resolve failed while the same command worked on macOS. The archive is now fed through the shell (tar -xzf - -C <dest> < <archive>), so the path never reaches tar's file-spec parser and bsdtar — which has no such syntax — reads the same stream. The decompressor is then named per kind (-z/-j/-J), because a stream is not sniffed the way a named file is: the first version of this fix used a bare -xf - and the Linux gate answered tar: Archive is compressed. Use -z option for a .tar.gz the same command opened by path — the same command that worked on macOS. archive.test.ts now round-trips a .tar.bz2 and a .tar.xz through the tools that produce them, so each flag is exercised rather than assumed. The same change moved the tool lookup AFTER the request's own validation: a destination that already exists and a source outside the destination folder are 409/400 whatever is installed, and on a machine without zip they used to answer "zip is not installed" (501) instead. archive.test.ts pins the ordering with rar, the format least likely to be present, so the case fails on the ordering wherever it runs. The trap is not the product's alone: the bz2/xz fixtures packed with tar -cjf "C:\…" and failed the same way on the Windows gate, so a fixture that shells out to tar uses the temp dir as its cwd and relative names.

  • useSessionState's fallback must be a STABLE reference, or the panel renders forever. The hook's read effect is keyed on the fallback's identity AND writes that fallback into state, so an inline {}/[] re-arms it every render and every run stores a fresh object. Measured with a probe holding one useSessionState(key, {}): 301 renders and still climbing, while the same hook with a module-level {} settled in 2. It hung the first app-level test written for the Commands panel for the full 240 s wall clock (the runner never reported), and the panel had passed every existing test because those mount its sub-components, not the panel. The git-forge panel had already recorded the rule for its own DEFAULT_FILTER; command-runner's two per-command flag maps now share one module constant (NO_FLAGS).

  • A panel's own Refresh must re-read EVERY page it draws, and a write must re-read what it changed. git-forge's header Refresh called only the list read, so a reader checking on an open merge request got a fresh list and an item whose state, checks, files and conversation stayed at their mount values; the panel now calls the detail hook's own reload too (a credential is deliberately read once per mount — a token does not appear mid-session). A write re-read only the detail, but the item's state badge is drawn from the LIST row, so a closed issue still read open behind it: the write's onDone re-reads both. command-runner's Rescan had the same shape — it re-read the command files and not the run topic, so a socket that missed a publish left a finished job reading running; the press now also asks useRealtime().refresh(). Stats is covered by one forced sample plus that same topic resync. A panel whose refresh only moves some of its reads is a control that answers a different question than the one asked.

  • A plugin glyph that mirrors a host icon copies lucide's geometry, subpaths and all. A plugin bundle is handed only its two @kabmo-labs/* packages, so it cannot import lucide-preact (the host's own dependency); the refresh marks in git-forge/command-runner's Glyph.tsx and stats' RefreshButton.tsx therefore carry RefreshCw's four ds verbatim, which is why those Glyphs accept string | readonly string[]. Merging the four into one d is NOT equivalent: measured against the same geometry rasterized at 384px, one path differed in 82 of 147 456 pixels (max alpha delta 62) at the arrow tips, where overlapping round caps composite inside one path but alpha-blend between elements; the array form measured 0. Installed lucide is 1.47.0 — a bump means re-copying the four ds (node_modules/lucide-preact/dist/esm/icons/refresh-cw.mjs).

Clone this wiki locally