agentleFS
coding-by-fengcoding-by-feng/ai-agent-session-center/CLAUDE.md

ai-agent-session-center

CLAUDE.md83 starsChanged 4 months agoMITView on GitHub

Localhost dashboard (port 3333) that monitors AI coding agent sessions (Claude Code, Codex) via hooks. Sessions are visualized as 3D robot characters in an interactive cyberdrome. Supports SSH terminals, team/subagent tracking, prompt queuing, workspace snapshots, and session resume. All feature logic is documented in docs/feature/. Each doc covers function, purpose, source files, implementation, cross-feature dependencies, and change risks. MANDATORY WORKFLOW — Before implementing any new feature or modifying an existing one: 1. Read this CLAUDE.md to identify which feature domain…

The file

We split this CLAUDE.md into the rules it gives an agent

6 rules. About 0 are common, 4 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Read this CLAUDE.md to identify which feature domain is involved

    line 46
  2. Very specific:

    Read the corresponding feature doc(s) in docs/feature/ to understand the current implementation, source files, dependencies, and change …

    line 47
  3. Distinctive:

    Check the Impact Matrix below to identify connected features that may be affected

    line 48
  4. Distinctive:

    Read those connected feature docs too, so you don't introduce regressions

    line 49
  5. Very specific:

    After completing the work, update every feature doc that was affected by the change (via /update-feature-docs)

    line 50
  6. Distinctive:

    Before modifying a feature, check what else it can break:

    line 195

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

AI Agent Session Center

Localhost dashboard (port 3333) that monitors AI coding agent sessions (Claude Code, Codex) via hooks. Sessions are visualized as 3D robot characters in an interactive cyberdrome. Supports SSH terminals, team/subagent tracking, prompt queuing, workspace snapshots, and session resume.

Tech Stack

LayerTechnology
BackendNode.js 18+ (ESM), Express 5, ws 8, tsx
FrontendReact 19, Three.js / @react-three/fiber, Zustand 5, Vite 7
DesktopElectron 34, electron-builder 25
Terminalnode-pty, server-owned, streamed over WebSocket (Electron's IPC PTY host has no renderer caller)
HooksBash script → JSONL file-based MQ (HTTP POST fallback)
PersistenceSQLite / better-sqlite3 (server) + IndexedDB / Dexie (browser)

Commands

npm run dev              # Vite + tsx watch (HMR)
npm run build            # Production build
npm start                # Start production server
npm test                 # Vitest
npm run test:e2e         # Playwright E2E
npm run test:coverage    # Coverage report
npm run typecheck        # tsc --noEmit (src/ only — see Key Invariants)
npm run typecheck:server # tsc --noEmit -p tsconfig.server.json (server/ + src/types)
npm run typecheck:all    # both, in sequence
npm run lint             # ESLint src/
npm run format           # Prettier
npm run electron:dev     # Build + launch Electron app
npm run electron:build   # Build distributable (DMG/NSIS)
npm run electron:rebuild # Rebuild native deps (better-sqlite3) for Electron's ABI
npm run install-hooks    # Install hooks into CLI settings
npm run uninstall-hooks  # Remove all dashboard hooks
npm run uninstall-gemini-hooks # Remove only the Gemini-CLI hooks
npm run setup            # Interactive setup wizard
npm run set-password     # Set the dashboard password (packaged app — `setup` writes the wrong config path there)
npm run reset            # Remove hooks, clean config, backup

Feature Documentation

All feature logic is documented in docs/feature/. Each doc covers function, purpose, source files, implementation, cross-feature dependencies, and change risks.

MANDATORY WORKFLOW — Before implementing any new feature or modifying an existing one:

  1. Read this CLAUDE.md to identify which feature domain is involved
  2. Read the corresponding feature doc(s) in docs/feature/ to understand the current implementation, source files, dependencies, and change risks
  3. Check the Impact Matrix below to identify connected features that may be affected
  4. Read those connected feature docs too, so you don't introduce regressions
  5. After completing the work, update every feature doc that was affected by the change (via /update-feature-docs)

Feature docs are manifest-backed. docs/feature/.manifest.json is the machine-readable source of truth for file→doc mapping, symbol inventory, and last-aligned timestamps. Skills read and update it — do not edit it by hand. If it drifts, run /align-existing-feature-docs (use --rebuild-manifest if the manifest itself is corrupted).

DomainDocsWhat they cover
server/18Agent Resources, Multi-Device Presence, Hook System, Session Management, Session Matching, Approval Detection, WebSocket, API, Database, Terminal/SSH, Teams, Process Monitor, Auth, File Index Cache, Floating Session Spawner, Session Visibility, Remote Control Daemon, Plan Usage
frontend/28Resources Tab, State, Persistence, WS Client, Detail Panel, Conversation View, Session Summary, File Browser, Terminal UI, Settings, Shortcuts, Queue, Queue Scheduler, Command Autocomplete, Views, Agenda, Workspace Snapshot, Setup Wizard, Auth UI, Project Browser, Floating Terminal Fork, Review Tab, Session Creation Modals, UI Primitives, File Open Chooser, Saved Prompts, Auto-Resume Watchdog, Prompt Trace
3d/3Cyberdrome Scene, Robot System, Particles/Effects
multimedia/2Sound & Alarm System, TTS Voice Output
electron/3App Lifecycle, PTY Host, IPC Transport

See docs/feature/README.md for the full index (54 docs), dependency graph, and impact matrix.

docs/feature/ is the only feature-doc tree: one source file, one owning doc. A second tree (docs/BE/) duplicated docs/feature/server/, rotted until it contradicted the code, and was retired in Aug 2026. → README

Architecture

Data Flow

AI CLI (Claude/Codex)
  → hooks/dashboard-hook.sh (jq enrichment, ~2-5ms)
  → /tmp/claude-session-center/queue.jsonl (atomic append ~0.1ms)
  → server/mqReader.ts (fs.watch + debounce)
  → server/hookProcessor.ts (validate + route)
  → server/sessionStore.ts (state machine + coordinator)
  → server/wsManager.ts (broadcast to browsers)
  → Browser (Zustand stores → React render)
Total: 3-17ms end-to-end

Server Modules

server/
  index.ts              — thin orchestrator
  hookInstaller.js      — auto-install hooks on startup
  portManager.ts        — port resolution, conflict kill
  hookRouter.ts         — POST /api/hooks (HTTP fallback)
  apiRouter.ts          — all REST endpoints (~128KB, largest file)
  mqReader.ts           — JSONL queue reader
  hookProcessor.ts      — validation + event processing
  interruptionDetector.ts — edge-triggered PTY scan for transient-failure banners (API 5xx / rate limit / network)
  fileIndexCache.ts     — cached + fs.watch'd fuzzy file index
  commandIndex.ts       — slash-command + skill catalog for prompt autocomplete (Codex skills via $CODEX_HOME)
  floatingSessionSpawner.ts — fork-translate / fork-explain floating PTY spawner
  floatingPrompt.ts     — synthesizes the prompt body for floating fork sessions
  extractPreviousAnswer.ts  — pulls last assistant turn for translate-answer mode
  ttsManager.ts         — Google Cloud TTS proxy
  noteMedia.ts          — note image/video store (files on disk + note_media metadata, hourly orphan sweep)
  ptyRing.ts            — lazily-grown terminal replay ring (dup of electron/ptyRing.ts)
  sessionTrim.ts        — per-session in-memory text caps + ArchivedSession builder
  codexModelCatalog.ts  — spawns Codex to list its models; 5min TTL cache, 8s query timeout
  terminalCapacity.ts   — session-vs-PTY budget (MAX_SESSIONS = 50, MAX_TERMINALS = 130; ops shells excluded)
  sessionStore.ts       — coordinator (~79KB, delegates to sub-modules)
    sessionMatcher.ts   — 11-step priority cascade (0→5) session matching
    sessionAliasResolver.ts — follows session-id alias chains (null on gap/cycle)
    sessionKillPolicy.ts    — Codex-session detection + live PID peer lookup for kills
    sessionUpdateCoalescer.ts — merges throttled session updates, preserving one-shot `replacesId`
    sessionTitle.ts     — derives/normalizes session display titles
    approvalDetector.ts — tool approval timeouts
    teamManager.ts      — subagent team tracking
    processMonitor.ts   — PID liveness checking
    autoIdleManager.ts  — idle transition timers
  wsManager.ts          — WebSocket broadcast + terminal relay + per-session write gate
  presenceManager.ts    — connected devices, one-shot workspace-restore claim, per-session control baton, workspace-writer election
  ptySubscribers.ts     — pure multi-subscriber PTY fan-out + dead-socket pruning
  sshManager.ts         — SSH/PTY terminal management
  networkInfo.ts        — this machine's own LAN-reachable IPv4 address (startup log + GET /api/config)
  sessionVisibility.ts  — which sessions a remote (non-localhost) client may see — see Key Invariants
  sessionQueueCodec.ts  — pure encode/decode for the shared prompt queue (import-free, testable without SQLite)
  remoteControlDaemon.ts — keeps a session's Claude Code Remote Control link fresh while armed
  planUsageCodec.ts / planUsageSources.ts / planUsageService.ts — each CLI's plan limits (5h/weekly %): parse, read from disk, poll + attach `session.planUsage` to every live session of that CLI
  db.ts                 — SQLite (WAL mode, 8 tables)
  authManager.ts        — password auth + tokens
  hookStats.ts          — performance metrics
  config.ts             — tool categories, timeouts
  constants.ts          — event types, statuses, WS message types
  serverConfig.ts       — data/server-config.json loader
  logger.ts             — debug-aware logging; also persists to <userData>/logs/server.log (data/logs/ outside Electron)
  resourceRouter.ts     — /api/resources (RESOURCES tab): read-only, loopback+Host-gated; resourceCatalog/Scanner/Adapters/Roots, resourceMask (pure), fsSafe

Frontend Modules

src/
  stores/               — 15 Zustand stores (session, settings, queue, queueHistory, promptSnippet, notes, label, room, camera, ui, ws, agenda, shortcut, floatingSessions, presence)
  hooks/                — useWebSocket, useTerminal, useSound, useAuth, useKeyboardShortcuts, useSessionSwitchHold, useKnownProjects, useSettingsInit, useWorkspaceAutoSave, useWorkspaceAutoLoad, useGlobalQueueScheduler, useQueueDragReorder, useClickOutside, useSelectionPopup, useDropdownFlipX, useWindowActivity, useTextClipped, useLiveBoard
  lib/                  — wsClient, db (Dexie), soundEngine, ambientEngine, alarmEngine, workspaceSnapshot, cliDetect, cyberdromeScene, fileSystemProvider, format, robot3DGeometry, robot3DModels, robotPositionPersist, robotStateMap, sceneThemes, shortcutKeys, ansi, remoteControlName, selectionExtractors, tooltips, translationLog, ttsEngine, transcript, commandMessage, queueScheduler, queueHistoryExport, queueMovePlacement, queueDragReorder, promptSnippetPool, promptSnippetInsert, pinnedRespawn, sessionSort, commandIndex, commandSuggestions, autocompleteTrigger, timePicker, rehypeSavedSelections, searchNormalize, terminalSend, filePathLink, popupResponse, mountedProjectsLru, projectEditGuard, robotPalette, robotModelMeta, roomGrid, terminalLinkHandler, terminalTransport, terminalGeometry, resumeWatchdog, textHighlight, deviceIdentity, presenceClient, fileTypeIcon, markdownHeadings, scrollWithinContainer, sessionDisplayTitle, sceneFrameloop, noteMedia, popoutTerminalWindow, aiPopup, panelResize, resourcesApi, resourceFilters, commandShortcuts, textClip, sceneStyle, groundMarkings, dioramaGeometry, dioramaLighting, robotChip, sessionRobotMemo, colorMath, dioramaProps, liveBoard, liveHint, sessionStatusStyle
  components/
    3d/                 — CyberdromeScene, CyberdromeEnvironment, SessionRobot, Robot3DModel, RobotDialogue, RobotLabel, RobotListSidebar, RoomLabels, SceneOverlay, CameraController, StatusParticles, SubagentConnections, robotPositionStore, RobotChip, GroundMarkings, SelectionMarker, AttentionPin, BlobShadow, sceneDecals, Plants
    live/               — LiveBoard, LiveEmptyState, LiveHintCallout (the 3D-off desktop LIVE page)
    session/            — StatusGlyph, DetailPanel, DetailTabs, ConversationView, ProjectTab, ProjectTabContainer, FloatingTerminalPanel, FloatingTerminalRoot, PopoutTerminalView, PopoutSessionView, PopoutProjectView, FileTree, FindInFileBar, ContentSearchModal, QueueTab, QueueItemText, QueueHistorySheet, QueueItemEditModal, QueueMovePicker, PromptSnippetPicker, LoopExcludeWindowsModal, NotesTab, NoteEditor, NoteMarkdown, SummaryTab, SummarizeModal, AiPopupHistory, SessionControlBar, SessionControlLock, SessionSwitcher, LinkifiedText, LabelPicker, KillConfirmModal, RoomKillConfirmModal, AlertModal, FileOpenChooser, PopupResponse, TexViewer, imageViewport
    terminal/           — TerminalContainer, TerminalToolbar, themes
    translate/          — SelectionPopup
    settings/           — SettingsPanel (7 tabs), ThemeSettings, SoundSettings, ShortcutSettings, HookSettings, ApiKeySettings, TranslationSettings, SummaryPromptSettings
    modals/             — NewSessionModal, QuickSessionModal, GlobalSearchModal, RestorePickerModal, SessionSwitchOverlay, ShortcutSettingsModal, ShortcutsPanel, ShortcutRow
    layout/             — NavBar, Header, HeaderAgentStrip, TitleBar, WorkdirLauncher, CliBrandIcons, DevicePresenceChip
    agenda/             — AddTaskForm, AgendaFilterBar, AgendaTaskCard
    auth/               — LoginScreen
    setup/              — SetupWizard + steps/ (Welcome, DepsCheck, Configure, Install, Done)
    resources/          — ResourceTypeRail, ResourceList, ResourceDetail, ResourceMarkdown (lazy), ConfigDetail, ResourceCompare, SourcesPanel, ChecksPanel
    ui/                 — Combobox, Modal, ResizablePanel, Select, Tabs, AutocompleteTextarea, TimePicker12, ToastContainer, SavingOverlay, WorkspaceLoadingOverlay, SearchInput, Tooltip, BrowseDirButton, DetachIcon, UnfoldIcon, FileTypeIcon
  routes/               — LiveView, HistoryView, PromptsView, ProjectBrowserView, QueueView, AgendaView, ReviewView, ResourcesView
  styles/               — CSS modules + 9 theme files
  types/                — shared TypeScript types (server + client)

Electron

electron/
  main.ts               — app lifecycle, BrowserWindow, embedded Express server
  preload.ts            — contextBridge (electronAPI)
  ptyHost.ts            — VS Code-style PTY host (node-pty)
  ptyRing.ts            — lazily-grown replay ring (dup of server/ptyRing.ts)
  popoutBounds.ts       — pure per-kind popout window bounds persistence ('terminal'/'project'/'session'/'internal')
  tray.ts               — system tray
  crashLogger.ts        — main-process crash capture (uncaughtException, render/child-process-gone, native crashReporter) -> <userData>/logs/main.log
  internalUrl.ts        — pure `isInternalAppUrl(url, port)`: is a window.open target our own origin?
  ipc/                  — setupHandlers, appHandlers, terminalHandlers

Terminals are server-owned term-* PTYs streamed over WebSocket in Electron and the browser alike. The IPC PTY host (pty-*, electron/ptyHost.ts) still exists, but nothing in the renderer creates one — see IPC Transport.

Session State Machine

SessionStart       → idle       (Idle animation)
UserPromptSubmit   → prompting  (Walking + Wave, seeks desk)
PreToolUse         → working    (Running, tool-specific animation)
PostToolUse        → working    (stays)
[timeout]          → approval   (Waiting — needs tool approval)
[timeout]          → input      (Waiting — needs user answer)
PermissionRequest  → approval   (reliable signal, overrides heuristic)
Notification(permission_prompt) → approval (backstop while a tool call is open; no timer in bypass/dontAsk)
Stop               → waiting    (ThumbsUp/Dance)
[5min waiting]     → idle       (announced; approval/input 10min + working 15min decays are silent)
SessionEnd         → ended      (Death — kept in memory)

Impact Matrix

Before modifying a feature, check what else it can break:

ChangeImpacts
Hook script / MQ formatSession Matching, Session Management, Hook Stats
Session state machine3D Robots, Sound/Alarms, Approval Detection, Auto-Idle, all frontend stores
Session MatchingTerminal/SSH, Session Resume, Team linking, External-session cards (Priority 5 + process-scan discovery), terminal adoption (Priority 4.5)
WebSocket protocolFrontend WS Client, Terminal UI, all real-time UI
API contractsALL frontend HTTP calls, Electron PTY registration
DB schemaAPI Endpoints, Client Persistence (IndexedDB mirror), Prompt Trace
prompts table / insertFullPromptSession Management, Database, Prompt Trace (GET /api/db/prompts reads it directly), Conversation View fallback
Match/highlight helpers (src/lib/textHighlight.ts)Conversation View search, Prompt Trace search — one predicate keeps every counter, row tint and <mark> in agreement
Terminal/SSHSession Matching (pending links), PTY Host registration
Zustand store shapesALL subscribing components
Theme CSS variablesALL visual components (2D + 3D), Terminal themes
Adding/removing a theme (ThemeName)THEMES + theme CSS (imported from both global.css and main.tsx), sceneThemes.ts and the ClayTone table (compile errors), light-overrides.css scanlines, optional xterm palette → settings-system.md
--font-monowindows-xp forces font-family: var(--font-mono) !important outside xterm: a component needing its own font redefines the variable on its root (see TexViewer.module.css) → settings-system.md
Electron IPC channelsPreload bridge (PRELOAD_PATH must match the build output), every electronAPI consumer
attachWindowOpenPolicy / internalUrl.tsEVERY renderer window.open — main window, both pop-outs, Project Browser, terminal link handler
Queue scheduler tick / queueHistoryStorePrompt Queue, Loops, per-session automation, Client Persistence (queueHistory), Auto-Resume Watchdog (runs first in the same tick, shares the send mutex)
presenceManager.ts (restore claim / control baton / workspace writer)Workspace Snapshot (restore + auto-save), API (clear-all, /api/presence/*), WS write gate, Queue Scheduler + Auto-Resume (canControlSession), control lock, migrateControl on re-key → multi-device-presence.md
Terminal.wsClients Set / ptySubscribers.tsTerminal/SSH, WebSocket Manager (terminal_disconnect, detachClient), Terminal UI on every device — a single-reference regression silently freezes one device's terminal
Terminal width mode (terminalGeometry.ts / terminal_geometry msg)Terminal UI (useTerminal fit wrapper, sendResize gate), Terminal/SSH (getTerminalGeometry), WS Manager (subscribe + post-resize broadcast), Presence (a phone with the baton may not resize) → terminal-ui.md
sessionVisibility.ts / remoteVisibleWS Manager (snapshot filter, broadcast skip, TERMINAL_SUBSCRIBE gate), API (/sessions/:id gate, /db/*, localhost-only toggle), Session Mgmt, Database, Detail Panel (📡) → session-visibility.md
Shared queue (session_queues / sessionQueueCodec.ts / QUEUE_UPDATE)Prompt Queue + Scheduler (every device sees one queue; firing stays baton-gated), Database, API, WS broadcast, Dexie (now a cache), Session Visibility (GET /queues filters itself) → prompt-queue.md
Plan usage (planUsage*.ts, hooks/dashboard-statusline.sh, the --settings tap in createTerminal)Session Management (handleEvent seam), Hook System (installer), Terminal/SSH (launch flag), Session Detail Panel (chip) — Plan Usage
LIVE first run (liveBoard/liveHint, wsStore.snapshotReceived, uiStore.liveHintDismissed)Views (board/empty state wait for the first snapshot), NavBar (LIVE dot, data-live-tab), WS Client — LIVE first run
Scene style (sceneStyle, dioramaGeometry/dioramaLighting/dioramaProps/colorMath, sessionRobotMemo)Cyberdrome Scene, Robot System, Particles/Effects, Settings, SceneOverlay — Scene styles
Command/file index (commandIndex)Command Autocomplete, Prompt Queue editor, Queue Tab
Agent Resources (server/resource*.ts, fsSafe.ts)RESOURCES tab; loopback+Host gate and server-side masking are its security boundary — Agent Resources
Saved prompts (promptSnippetStore / PromptSnippetPicker)Prompt Queue compose row, QueueItemEditModal MAIN + both chain sections, Client Persistence (promptSnippets, Dexie v7)
Autocomplete sigils (autocompleteTrigger/entryPrefix)Command Autocomplete, Prompt Queue editor, Queue Tab, Queue Scheduler chain steps
AutocompleteTextarea's dropdown-portalCommand Autocomplete, Prompt Queue (QueueTab/QueueItemEditModal), Floating Terminal Fork (SelectionPopup): the dropdown must stay createPortal'd to document.body → command-autocomplete.md
Transcript reconstruction (transcript.ts / commandMessage.ts)Conversation View, Review Tab (AI Popups)
Floating session spawn / forkFloating Terminal Fork, Floating Session Spawner, Review Tab, pop-out window, Session Matching
Shared UI primitives (Modal/Select/Tabs/Tooltip)ALL components that consume them (Settings, modals, panels)
Replay ring (ptyRing.ts)PTY Host + Terminal/SSH — duplicated across electron/ and server/ (tsconfig roots can't cross-import); test/ptyRing.test.ts runs one suite against both and fails on drift
Per-session text caps (sessionTrim.ts)Session Management, Session Matching, Conversation View, Database (insertFullPrompt ordering)
Eager import roots (main.tsx/App.tsx/AppLayout)Bundle size for every renderer incl. pop-out windows
Mounted-project LRU (mountedProjectsLru/projectEditGuard)Session Detail Panel, File Browser — unpersisted ProjectTab state must register with the edit guard
TTS / GCP API keySettings toggle, Terminal UI hold-to-speak, /api/tts/*: the per-user googleTtsApiKey stays client-side, sent per request. Never reintroduce ambient credentials (they leak across users) → tts-voice-output.md

Key Invariants

  • Never mutate session objects — always spread/new Map
  • One 3D scene, two looks (sceneStyle): geometry and materials are shared pools, never per robot; a SessionRobot prop missing from sessionRobotMemo is silently ignored; paint must read against its floor, judged by CIELAB deltaE in a render. → cyberdrome-scene.md
  • Never use Zustand inside R3F Canvas — causes React Error #185; all store reads in DOM layer, data flows via props
  • The 3D Canvas never runs frameloop="always" unconditionally: Electron keeps a buried window's rAF loop alive. resolveFrameloop() gates it, and demand needs the FramePump or walk cycles freeze. Keep sceneFrameloop.ts import-free. → cyberdrome-scene.md
  • Never run a process probe synchronously on the event loop: hasChildProcesses is async execFile, and after its await the approval timer must re-read the session and bail unless it is still working with a pendingTool. → approval-detection.md
  • A non-zero fitAddon.fit() reading may not be final: a remount can measure 20–30 cols, and sending that to the PTY hard-wraps scrollback for good. verifySettled (two equal readings) gates attach and reparent; four fit() sites aren't. → terminal-ui.md
  • A narrow device never resizes the PTY to its own width: mayDrivePtyGeometry(isMobile) is false on a phone even holding the baton (module-scope gate, wrapped FitAddon); it renders the PTY width in 'pan' mode. terminalGeometry.test.ts. → terminal-ui.md
  • Remote devices see only shared sessions, and the list is one of six leak paths: also the snapshot, broadcasts, /sessions/:id/*, TERMINAL_SUBSCRIBE (by terminal id) and /db/*. Hidden is 404; unknown fails closed. sessionVisibility.test.ts. → session-visibility.md
  • xterm's DOM renderer misplaces the selection on CJK lines: fixed by @xterm/addon-canvas; double-click word bounds add CJK_WORD_SEPARATORS. Curly quotes in that literal once broke the build: diff codepoints after editing it. → terminal-ui.md
  • QueueTab is not keyed by session, and DetailPanel mounts it twice: the compose draft lives in queueStore (QueueComposeDraft, per session id, re-keyed in migrateSession), never local state. QueueTab.test.tsx uses rerender(). → prompt-queue.md
  • The prompt queue is server-backed (session_queues, opaque JSON): the echo guard (originClientId + _skipServerPush) is mandatory, seed only when the server has no record, GET /api/queues filters visibility itself, Dexie is a cache. → prompt-queue.md
  • With autoEnter off the no-work fallback cannot tell a silent CLI from a human reading: resolveNoWorkFallbackMs(autoEnter) is the one place choosing 5 or 30 min, used by both gates; tested with the real constants in queueScheduler.test.ts. → queue-scheduler.md
  • Room.roomIndex is a 3D world coordinate, not a display order: it places the walls, the camera target and the room colour. List order is Room.listOrder (no 3D consumer), and reorders never write roomIndex. Grep every consumer first. → session-detail-panel.md
  • Drag gestures branch on pointerType: mouse/pen lift after 4 px of travel, touch (and unknown) keep hold-first; a gesture test that never moves the pointer proves nothing. useQueueDragReorder keeps the old shape. useRoomDragReorder.test.tsx. → session-detail-panel.md
  • Two icons that differ only in shape coordinates read as one: the room header separates collapse (filled triangle) from move (stroked arrow with a shaft) by glyph family and by divider groups. SessionSwitcher.test.tsx pins both. → session-detail-panel.md
  • "Absent is safe" picks a polarity per flag: unset remoteVisible means hidden (a new capability), unset aiPopupEnabled means on (it shipped on); the DB defaults follow. Read via isAiPopupEnabled(session): !undefined is true. → floating-terminal-fork.md
  • Deleting code can unmask lint errors you never wrote (the React Compiler rule stops bailing out on the file). Diff lint against HEAD in place (git stash, or eslint --stdin --stdin-filename), never from a scratch copy whose imports break. → terminal-ui.md
  • react-hooks/set-state-in-effect fires on new code too: to cancel on blur, add raw blur/visibilitychange listeners in the effect that owns the feature's listeners and call setState in those callbacks, instead of useWindowActivity(). → keyboard-shortcuts.md
  • The Remote Control relink can retrigger itself: its writes cause a real idle edge, so edge-triggering and the 30-min COOLDOWN_MS are both needed. Disarm is sticky; the name never sanitizes to empty (bare /remote-control disconnects). → remote-control-daemon.md
  • deriveRemoteControlName runs only in the creation modals, on an empty title, so links get <project>-<n>; remoteControlNameFor re-derives at relink. Never seed a title at creation: it suppresses the auto-title. → session-creation-modals.md
  • memo(TerminalContainer) swallows a pop-out's socket-open re-render: useTerminal watches useWsStore.connected and subscribes once per (socket, xterm). Hook-only tests miss it; PopoutTerminalView.test.tsx does not. → terminal-ui.md
  • Never block the hook script — background subshell (& disown) for all processing
  • Never hardcode port 3333 — read from config/env/CLI flag
  • Plan usage is account-wide, never "this session's" — session.planUsage is the freshest per-CLI reading on every live session of the CLI, and the Claude --settings tap REPLACES the user's status line, so it must chain to it. Plan Usage
  • Never modify ~/.claude/settings.json without atomic write — write-to-tmp + rename
  • Server imports use .js extensions — required for NodeNext module resolution with tsx
  • File browser uses resolveProjectPath() — prevents directory traversal
  • One terminal is one card: a lost SessionStart used to split a session; Priority 4.5 re-keys the sole owner of agent_terminal_id on any forward event (not CONNECTING, Stop/SessionEnd or subagent events). sessionMatcher.adoption.test.ts. → session-matching.md
  • Display names go through sessionDisplayTitle() (title || projectName || 'Unnamed'): title stays empty until the first prompt so the auto-title fires once, so never seed it. The helper stays import-free (2D and 3D use it). → session-detail-panel.md
  • Only ppid proves a discovered process is external, never cwd: resolve ppid → PTY → session with getTerminalByPtyPid (never the execSync variant); cwd may suppress a card but never bind a pid. discoveryReconcile.test.ts. → process-monitor.md
  • External sessions are traced, not dropped: an unmatched hook with a tty becomes a Priority 5 card, and the 20 s process scan adds external-<pid> cards, which are never persisted to the snapshot. The scan stays async. → session-matching.md
  • Codex skills are $name, never /name: entryPrefix() in commandIndex.ts is the one sigil rule; skills live under $CODEX_HOME/skills (incl. .system/; symlinked dirs need statSync), and $ stays Codex-only. → command-autocomplete.md
  • Spawned PTYs must not inherit the launcher's Claude env markers: CLAUDE_CODE_CHILD_SESSION=1 silently disables transcripts and breaks every --resume. stripInheritedClaudeSessionEnv runs at all three spawn sites. → terminal-ssh.md
  • A 529 ends in Stop, like a clean finish: interruptionDetector.ts reads PTY bytes edge-triggered, session.interruption clears on work hooks but never Stop, and retries are a 30-min rolling ledger with jittered backoff. Server PTYs only. → auto-resume-watchdog.md
  • A session title reaches a live shell: quoteSessionTitle escapes \, $, backtick and " (backslash first) and strips control chars; every launch path, raw startupCommand too, goes through appendSessionName. sessionNameQuoting.test.ts. → terminal-ssh.md
  • A floating AI session exists before its window: openFloatWindow returns an outcome and resolves (never throws), and every non-window branch docks the panel, or the fork is orphaned or spawned twice. popoutTerminalWindow.test.ts. → floating-terminal-fork.md
  • A search UI derives its count, highlights and filtered rows from one predicate (textHighlight.ts): matches keep .search-highlight in matches-only mode, and display caps slide to the hit (clipToMatch). → conversation-view.md
  • OUTLINE slugs and heading ids must come from equivalent text: childrenToText() walks the rendered children and stripInlineMarkdown() cleans the source, without single-underscore italics. markdownHeadings.render.test.tsx. → file-browser.md
  • About 10% of prompts rows were never typed by a human (harness tags): "the user's prompts" views exclude rows starting with <; SQLite trims need an explicit charset, and %/_ need ESCAPE '\'. → prompt-trace.md
  • The preload is preload.cjs via the one PRELOAD_PATH; a wrong name fails silently. Mar–Sep 2026 every window ran with electronAPI undefined (server.log: Mac · Chrome). Pinned by test/electronPreloadPath.test.ts → app-lifecycle.md
  • Every window's window.open goes through attachWindowOpenPolicy: our own origin (port-scoped) opens a native window, the rest shell.openExternal; an Electron renderer never falls back to window.open. internalUrl.test.ts. → app-lifecycle.md
  • A second device never rebuilds the workspace or co-drives a session: one restore claim per server process, a denied client skips restore entirely, one auto-save writer, and a per-session control baton (migrateControl on re-key). → multi-device-presence.md
  • A terminal has many subscribers: wsClients is a Set, replay goes only to the joiner, disconnect removes one socket, and ptySubscribers.ts prunes CLOSING/CLOSED (never CONNECTING) and keeps looping past a throwing send. → multi-device-presence.md
  • Remote access without a password is refused (403 / ws 4003), not warned: loopback stays password-free; decide with isLoopbackAddress, and an unknown address fails closed. authRemoteGate.test.ts. → authentication.md
  • Platform-divergent UI has one rule (platform.ts): capability → useIsDesktopApp() and unmount; visual size → CSS; size where it must not exist → useIsMobile() and unmount. window.electronAPI is never a size check. → views-routing.md
  • SSH inputs validated with Zod + shell metacharacter regex — prevents injection
  • Floating overlays stay inside the viewport: flip (Select), nudge (useDropdownFlipX) or clamp (clampToViewport); an edge-anchored menu without a guard clips itself near a window edge. Review- and render-checked; no linter sees it. → ui-primitives.md
  • An overlay in a scrolling ancestor must be portaled (or fixed): edge guards measure the window, not the clip box. Portaled menus use the 10000+ z band, re-place on capture scroll, animate opacity only. QueueMovePicker.test.tsx. → prompt-queue.md
  • An overlay under a filter/backdrop-filter/transform/will-change ancestor must be portaled too: those re-scope position: fixed. AutocompleteTextarea portals its dropdown to document.body at the source. → command-autocomplete.md
  • /api/resources is read-only and loopback-only — no writes; 404 unless socket AND Host are loopback (DNS rebinding); config values leave only via resourceMask, every served text is redacted. Agent Resources
  • Never import a Three.js-touching module from 2D code (robot3DGeometry, robot3DModels, cyberdromeScene build geometry at import): use the import-free robotPalette, robotModelMeta and roomGrid. → robot-system.md
  • One queue editor and a curated snippet library: EDIT opens QueueItemEditModal for every type (no in-row editor), and nothing writes promptSnippetStore automatically, only an explicit 🔖. ★ saves a whole item, 🔖 bare text. → saved-prompts.md
  • On touch, a tap resolves AFTER :hover reflows the row. The queue toggle sat under DEL and a tap deleted the prompt; a control in a hover-reveal row must not move, be clipped or slide down. Prompt Queue
  • Auto-idle announces only prompting → waiting and waiting → idle: the approval/input/working decays stay silent, because the queue treats idle as sendable. → process-monitor.md
  • Note media never goes in SQLite, and the Markdown stack never in the eager chunk: files on disk plus note_media rows (hourly orphan sweep), no SVG; NoteMarkdown and NotesTab are both lazy(); scope inline code as :not(pre) > code. → session-detail-panel.md
  • No static import of heavy components from main.tsx / App.tsx / AppLayout: use lazy(), then npm run build and confirm the entry chunk has zero static chunk imports. Never "fix" bundle size with manualChunks. → views-routing.md
  • db.insertFullPrompt() runs before pushPrompt() with the same timestamp: the full row wins via INSERT OR IGNORE, and reordering them makes SQLite keep the truncated text. → database.md
  • A session's ops shell is flagged isOps: true and closed on every teardown path (killSession, DELETE /api/sessions/:id, clearAllSessions), or the 130-PTY ceiling fires early with numbers nobody can reconcile. → terminal-ssh.md
  • ArchivedSession carries only what the UI reads, built solely by toArchivedSession(): a field with no consumer brings back about 46 KB per entry of write-only logs. → session-management.md
  • Never write test/debug screenshots to the repo root — Playwright/MCP captures and scratch images go to test-screenshots/ (gitignored) or /tmp; images that ship live in static/ only. .gitignore blocks committing any stray image outside static/, but root dumps still clutter the working tree, so always pass an absolute path under a scratch dir when capturing.
  • npm run typecheck only ever checked src/ — server/ had never been type-checked by any script, silently, for an unknown span of this project's history. The root tsconfig.json scopes "include": ["src"]; server/'s own tsconfig.server.json ("include": ["server", "src/types"]) exists but nothing invoked it — not typecheck, not lint (also src/-only), not the one CI workflow (build-windows.yml, which only runs electron:build:win and never typechecks at all). Found by an align-docs audit agent investigating a hook-system.md finding; running it directly surfaced 18 real errors that had been accumulating invisibly: a dead KNOWN_EVENTS entry referencing 5 nonexistent EVENT_TYPES properties (Gemini-CLI leftovers, silently undefined at runtime), two redundant-but-harmless {ok: x.ok, ...x} spreads, a real dueDate: string|null|undefined vs AgendaTask.dueDate?: string mismatch in the agenda PUT handler, FileHandle imported from the wrong module (fs instead of fs/promises), and a control-flow narrowing gap in deleteSessionFromMemory where TypeScript couldn't see that !session already implied resolvedId was non-null across a ternary. All 18 fixed; npm run typecheck:server / typecheck:all now exist as separate scripts (not merged into typecheck itself, matching lint's existing src/-only scoping) so this can't silently reopen unnoticed — but nothing runs typecheck:server automatically yet, so a regression here still won't surface on its own.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.