Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

perf: four quick wins from the performance audit

enes761164e4180b
diff --git a/src/core/commit-message.ts b/src/core/commit-message.ts
index dcc816042..45797ed74 100644
--- a/src/core/commit-message.ts
+++ b/src/core/commit-message.ts
@@ -1,8 +1,9 @@
-import { execFile, execFileSync, spawn } from 'child_process'
+import { execFile, spawn } from 'child_process'
import fs from 'fs'
import os from 'os'
import { promisify } from 'util'
import type { GitResult, Settings } from '../shared/types'
+import { findInPathString, shellPathNow } from './exec-path'
import { resolveGitRemote, runRemoteGit } from './remote-ssh/remote-git'
const run = promisify(execFile)
@@ -30,19 +31,12 @@ function resolveBinary(name: string): string | null {
// ignore
}
}
- // Resolve via PATH without a shell. `name` comes from a user setting (custom commit agent),
- // so never interpolate it into a shell string — pass it as a plain argv to `command -v`.
- // Reject anything that isn't a bare binary name to keep it well out of injection territory.
+ // Resolve via PATH without a shell OR a subprocess: walk the cached login-shell PATH from
+ // exec-path.ts (the inherited GUI PATH misses user-installed bins). `name` comes from a user
+ // setting (custom commit agent) — reject anything that isn't a bare binary name to keep it
+ // well out of injection territory.
if (!/^[A-Za-z0-9._-]+$/.test(name)) return null
- try {
- const out = execFileSync('/usr/bin/env', ['sh', '-c', 'command -v "$1"', 'sh', name], {
- encoding: 'utf-8'
- }).trim()
- if (out) return out
- } catch {
- // ignore
- }
- return null
+ return findInPathString(name, shellPathNow() ?? process.env.PATH)
}
async function git(cwd: string, args: string[]): Promise<string> {
diff --git a/src/core/context-tail.ts b/src/core/context-tail.ts
index 2b7c462ad..4262176d9 100644
--- a/src/core/context-tail.ts
+++ b/src/core/context-tail.ts
@@ -14,14 +14,30 @@ const POLL_MS = 1000
// line is dropped naturally by the JSON.parse guard.
const INITIAL_READ_CAP = 1024 * 1024 // 1 MB
-/** Scan transcript text for the LATEST assistant message's token usage + model. Pure. */
-export function parseLatestUsage(text: string): { used: number; model: string | null } | null {
+/** The scanners accept a pre-split line array so one read can split its chunk ONCE and share
+ * it — three scanners each running their own `split('\n')` tripled the allocation per tick. */
+const toLines = (text: string | string[]): string[] =>
+ Array.isArray(text) ? text : text.split('\n')
+
+/**
+ * Scan transcript text for the LATEST assistant message's token usage + model. Pure.
+ *
+ * Scans BACKWARDS and stops at the first line that settles both values: only the latest usage
+ * matters, and a forward scan JSON.parsed every line of the chunk — a single tool-result line
+ * can be 100 KB+ of JSON, fully parsed (at 1 Hz per tracked session, on the main thread) just
+ * to learn it isn't an assistant message. The includes() pre-filters skip those without a parse:
+ * a JSON-encoded assistant/usage line always contains both quoted keys.
+ */
+export function parseLatestUsage(
+ text: string | string[]
+): { used: number; model: string | null } | null {
+ const lines = toLines(text)
let found = false
let usedTokens = 0
let model: string | null = null
- for (const line of text.split('\n')) {
- const s = line.trim()
- if (!s) continue
+ for (let i = lines.length - 1; i >= 0; i--) {
+ const s = lines[i].trim()
+ if (!s || !s.includes('"usage"') || !s.includes('"assistant"')) continue
let o: { type?: string; message?: { model?: string; usage?: Record<string, number> } }
try {
o = JSON.parse(s)
@@ -33,9 +49,14 @@ export function parseLatestUsage(text: string): { used: number; model: string |
const used =
(u.input_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0)
if (used <= 0) continue
- found = true
- usedTokens = used
- model = o.message.model ?? model // carry the prior model forward when this line omits it
+ if (!found) {
+ found = true
+ usedTokens = used // the LATEST usage — earlier lines are visited only to resolve the model
+ }
+ // Same rule as the old forward scan's "carry the prior model forward": the effective model
+ // is the nearest usage line AT OR BEFORE the latest one that names it.
+ model = o.message.model ?? null
+ if (model !== null) break
}
return found ? { used: usedTokens, model } : null
}
@@ -58,9 +79,9 @@ const tag = (content: string, name: string): string | undefined => {
}
/** Scan transcript lines for queued <task-notification>s. Pure. */
-export function parseTaskNotifications(text: string): TaskNotification[] {
+export function parseTaskNotifications(text: string | string[]): TaskNotification[] {
const out: TaskNotification[] = []
- for (const line of text.split('\n')) {
+ for (const line of toLines(text)) {
const s = line.trim()
// Cheap pre-filter; the attachment echo of the same notification is skipped by the
// type check below so each completion fires exactly once.
@@ -99,8 +120,8 @@ export function parseTaskNotifications(text: string): TaskNotification[] {
* answer was. The caller only acts on it while the node is still in needs-you, so a normal turn's
* constant stream of results costs nothing.
*/
-export function hasToolResult(text: string): boolean {
- for (const line of text.split('\n')) {
+export function hasToolResult(text: string | string[]): boolean {
+ for (const line of toLines(text)) {
const s = line.trim()
// Cheap pre-filter before the parse — this runs over every transcript chunk.
if (!s || !s.includes('tool_result')) continue
@@ -212,18 +233,22 @@ export function createContextTail(
// latest value wins, so it must not wait for a newline. Notifications scan
// COMPLETE lines only, with the torn tail carried into the next read, so a torn
// <task-notification> is completed later instead of being lost.
+ // ONE split serves all three scanners: the last element is exactly the torn tail
+ // (everything past the final newline), so dropping it yields the complete lines.
const combined = t.carry?.length ? Buffer.concat([t.carry, buf]) : buf
- const { text: complete, carry } = splitCompleteLines(combined)
- t.carry = carry
- const latest = parseLatestUsage(combined.toString('utf-8'))
+ t.carry = splitCompleteLines(combined).carry
+ const lines = combined.toString('utf-8').split('\n')
+ const completeLines = lines.slice(0, -1)
+ const latest = parseLatestUsage(lines)
if (latest) {
t.used = latest.used
t.model = latest.model ?? t.model
}
if (opts?.onTaskNotification) {
- for (const n of parseTaskNotifications(complete)) opts.onTaskNotification(sessionId, n)
+ for (const n of parseTaskNotifications(completeLines))
+ opts.onTaskNotification(sessionId, n)
}
- if (opts?.onToolResult && hasToolResult(complete)) opts.onToolResult(sessionId)
+ if (opts?.onToolResult && hasToolResult(completeLines)) opts.onToolResult(sessionId)
}
}
diff --git a/src/core/exec-path.ts b/src/core/exec-path.ts
new file mode 100644
index 000000000..841cf0006
--- /dev/null
+++ b/src/core/exec-path.ts
@@ -0,0 +1,102 @@
+// Executable resolution for a GUI process, without ever spawning a login shell SYNCHRONOUSLY.
+//
+// A GUI app launched from Finder/Dock inherits only a minimal PATH (`/usr/bin:/bin:…`) — it
+// never sees Homebrew, `~/.local/bin`, nvm, etc. The historical fix was a sync
+// `execFileSync($SHELL, ['-lc', 'command -v <bin>'])` per lookup, but sourcing the user's
+// profile routinely takes 100-800ms (nvm/conda init) and a synchronous spawn of it sits on the
+// MAIN thread — freezing every window, every PTY flush and all IPC for its duration (and the
+// tmux-missing banner re-probes on a 3s poll, so it froze repeatedly).
+//
+// The replacement: resolve the login-shell PATH ONCE, asynchronously (`resolveShellPath`,
+// prewarmed at boot), and make every lookup a subprocess-free walk of that cached PATH string
+// (`findInPathString` — an accessSync per entry). Callers that run before the async probe has
+// settled fall back to the inherited PATH plus their own well-known locations, and simply
+// re-probe later (see each caller's memoization notes).
+import fs from 'fs'
+import os from 'os'
+import path from 'path'
+import { execFile } from 'child_process'
+import { promisify } from 'util'
+
+const runAsync = promisify(execFile)
+
+/**
+ * Resolve the user's REAL login-shell PATH once, and cache it.
+ *
+ * We run the user's login + interactive shell (so BOTH profile files and `.zshrc`/`.bashrc`
+ * PATH additions are seen) and read back `$PATH`, printed between sentinels to survive any
+ * dotfile noise. Bounded by a timeout; on any failure (hang, dotfile error, non-POSIX shell,
+ * Windows) we fall back to the inherited PATH.
+ */
+let cachedShellPath: string | null | undefined
+let shellPathPromise: Promise<string | null> | null = null
+export function resolveShellPath(): Promise<string | null> {
+ if (cachedShellPath !== undefined) return Promise.resolve(cachedShellPath)
+ if (shellPathPromise) return shellPathPromise
+ if (os.platform() === 'win32') {
+ cachedShellPath = null
+ return Promise.resolve(null)
+ }
+ const shell = process.env.SHELL || '/bin/bash'
+ const START = '__NT_PATH_START__'
+ const END = '__NT_PATH_END__'
+ // `-ilc` = login + interactive (matches VS Code's shell-env resolution): sources the profile
+ // files AND the interactive rc (`.zshrc`/`.bashrc`) where users commonly add nvm/bun/etc.
+ // Dotfiles routinely take hundreds of ms (nvm/conda init) and can hang, so this MUST be
+ // async — a synchronous probe here froze every window and all IPC for up to the 5s timeout.
+ // stderr is captured separately by execFile, so prompt/compinit noise can't pollute stdout.
+ shellPathPromise = runAsync(shell, ['-ilc', `command printf '${START}%s${END}' "$PATH"`], {
+ encoding: 'utf-8',
+ timeout: 5000
+ })
+ .then(({ stdout }) => {
+ const m = stdout.match(new RegExp(`${START}([\\s\\S]*?)${END}`))
+ return m?.[1]?.trim() || null
+ })
+ .catch(() => null) // login shell hung / errored / isn't POSIX — inherited-PATH fallback
+ .then((resolved) => {
+ cachedShellPath = resolved
+ return resolved
+ })
+ return shellPathPromise
+}
+
+/** The cached login-shell PATH: a string once resolved, null if the probe failed, undefined
+ * while the async probe is still in flight (callers should then fall back + re-probe later). */
+export function shellPathNow(): string | null | undefined {
+ return cachedShellPath
+}
+
+/** Walk a PATH string for an executable — sync but SUBPROCESS-FREE (one accessSync per entry),
+ * so it is safe on the main thread. Returns the first accessible match, or null. */
+export function findInPathString(bin: string, pathStr: string | null | undefined): string | null {
+ for (const dir of (pathStr ?? '').split(path.delimiter)) {
+ if (!dir) continue
+ const candidate = path.join(dir, bin)
+ try {
+ fs.accessSync(candidate, fs.constants.X_OK)
+ return candidate
+ } catch {
+ // not here — keep looking
+ }
+ }
+ return null
+}
+
+/**
+ * Resolve `bin` against the cached login-shell PATH (falling back to the inherited PATH while
+ * the probe is in flight), then against the caller's well-known locations. Never spawns.
+ */
+export function findExecutableSync(bin: string, fallbacks: string[] = []): string | null {
+ const hit = findInPathString(bin, cachedShellPath ?? process.env.PATH)
+ if (hit) return hit
+ for (const c of fallbacks) {
+ try {
+ fs.accessSync(c, fs.constants.X_OK)
+ return c
+ } catch {
+ // keep trying
+ }
+ }
+ return null
+}
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 6d0e865db..8b008fe57 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -34,6 +34,7 @@ import { effectiveSize, type PtySize } from './pty-size'
import { machOArch, archMismatch } from './macho-arch'
import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'
import { claudeConfigDirFor } from './claude-config-dir'
+import { findExecutableSync, findInPathString, resolveShellPath, shellPathNow } from './exec-path'
import { AUTH_ENV_STRIP, accountTmuxEnvArgs, remoteAccountConfigDirAbs } from './claude-accounts-core'
import { presenceHub } from './presence/hub'
@@ -99,7 +100,12 @@ bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X
`
}
-/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). */
+/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). Subprocess-free:
+ * the old fallback here was a SYNC login-shell `command -v tmux` — sourcing the profile
+ * (nvm/conda: 100-800ms) on the main thread, re-triggered every 3s by the tmux-missing
+ * banner's install poll, freezing all windows and IPC each time. Now it walks the cached
+ * login-shell PATH instead; before that async probe settles a nonstandard location can be
+ * missed, which init()'s post-probe ensureTmux() re-run and tmuxStatus()'s re-probe cover. */
function findTmux(): string | null {
for (const c of ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux', '/bin/tmux']) {
try {
@@ -108,15 +114,7 @@ function findTmux(): string | null {
// ignore
}
}
- try {
- const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', 'command -v tmux'], {
- encoding: 'utf-8'
- }).trim()
- if (out) return out
- } catch {
- // ignore
- }
- return null
+ return findInPathString('tmux', shellPathNow() ?? process.env.PATH)
}
/** Resolve an absolute ssh path (GUI apps don't inherit the shell PATH). */
@@ -156,73 +154,17 @@ function spawnHelperArchMismatch(): string | null {
function findSsh(): string | null {
if (cachedSsh !== undefined) return cachedSsh
- try {
- const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', 'command -v ssh'], {
- encoding: 'utf-8'
- }).trim()
- cachedSsh = out || null
- } catch {
- cachedSsh = null
- }
- // Common fallback locations if the login shell lookup failed.
- if (!cachedSsh) {
- for (const p of ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh']) {
- try {
- execFileSync(p, ['-V'], { stdio: 'ignore' })
- cachedSsh = p
- break
- } catch {
- // keep trying
- }
- }
- }
- return cachedSsh ?? null
+ // Subprocess-free (was a sync login-shell `command -v ssh` + an `ssh -V` spawn per fallback,
+ // all blocking the main thread). A MISS is only memoized once the async login-shell PATH
+ // probe has settled — before that a custom-location ssh would be cached away forever.
+ const found = findExecutableSync('ssh', ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh'])
+ if (found || shellPathNow() !== undefined) cachedSsh = found
+ return found
}
-/**
- * Resolve the user's REAL login-shell PATH once, and cache it.
- *
- * A GUI app launched from Finder/Dock inherits only a minimal PATH
- * (`/usr/bin:/bin:/usr/sbin:/sbin`) — it never sees `/usr/local/bin`, Homebrew
- * (`/opt/homebrew/bin`), `~/.local/bin`, nvm, bun, etc. So terminals we spawn would report
- * `command not found: claude` even though the tool is installed. We run the user's login +
- * interactive shell (so BOTH profile files and `.zshrc`/`.bashrc` PATH additions are seen) and
- * read back `$PATH`, printed between sentinels to survive any dotfile noise. Bounded by a timeout;
- * on any failure (hang, dotfile error, non-POSIX shell, Windows) we fall back to the inherited PATH.
- */
-let cachedShellPath: string | null | undefined
-let shellPathPromise: Promise<string | null> | null = null
-function resolveShellPath(): Promise<string | null> {
- if (cachedShellPath !== undefined) return Promise.resolve(cachedShellPath)
- if (shellPathPromise) return shellPathPromise
- if (os.platform() === 'win32') {
- cachedShellPath = null
- return Promise.resolve(null)
- }
- const shell = process.env.SHELL || '/bin/bash'
- const START = '__NT_PATH_START__'
- const END = '__NT_PATH_END__'
- // `-ilc` = login + interactive (matches VS Code's shell-env resolution): sources the profile
- // files AND the interactive rc (`.zshrc`/`.bashrc`) where users commonly add nvm/bun/etc.
- // Dotfiles routinely take hundreds of ms (nvm/conda init) and can hang, so this MUST be
- // async — a synchronous probe here froze every window and all IPC for up to the 5s timeout.
- // Prewarmed from init(); create() awaits it, so terminals still always get the real PATH.
- // stderr is captured separately by execFile, so prompt/compinit noise can't pollute stdout.
- shellPathPromise = runAsync(shell, ['-ilc', `command printf '${START}%s${END}' "$PATH"`], {
- encoding: 'utf-8',
- timeout: 5000
- })
- .then(({ stdout }) => {
- const m = stdout.match(new RegExp(`${START}([\\s\\S]*?)${END}`))
- return m?.[1]?.trim() || null
- })
- .catch(() => null) // login shell hung / errored / isn't POSIX — inherited-PATH fallback
- .then((resolved) => {
- cachedShellPath = resolved
- return resolved
- })
- return shellPathPromise
-}
+// resolveShellPath (the one async login-shell PATH probe) lives in exec-path.ts now, shared by
+// every module that used to spawn its own sync login shell. Prewarmed from init(); create()
+// awaits it, so terminals still always get the real PATH.
/**
* A UTF-8 locale for spawned terminals, or null to leave the inherited locale untouched.
@@ -242,22 +184,11 @@ function resolveLocaleLang(): string | null {
/**
* Resolve an executable against the user's real login-shell PATH (reusing the cached probe),
* returning its absolute path or null. GUI apps inherit only a minimal PATH, so a bare
- * `execFile('claude', …)` would fail even when the tool is installed — this walks the resolved
- * PATH entries and returns the first `bin` that exists and is accessible.
+ * `execFile('claude', …)` would fail even when the tool is installed.
*/
export async function findInLoginPath(bin: string): Promise<string | null> {
const shellPath = (await resolveShellPath()) ?? process.env.PATH ?? ''
- for (const dir of shellPath.split(path.delimiter)) {
- if (!dir) continue
- const candidate = path.join(dir, bin)
- try {
- await fs.promises.access(candidate, fs.constants.X_OK)
- return candidate
- } catch {
- // not here — keep looking
- }
- }
- return null
+ return findInPathString(bin, shellPath)
}
/** A UI client: an Electron webContents id or a ServerPlatform uiId. */
@@ -577,8 +508,10 @@ export class PtyManager {
/** Must run after app is ready (needs userData path). */
init(getSettings: () => Settings): void {
this.getSettings = getSettings
- // Prewarm the login-shell PATH probe now so the first terminal spawn doesn't wait on it.
- void resolveShellPath()
+ // Prewarm the login-shell PATH probe now so the first terminal spawn doesn't wait on it —
+ // and re-run the tmux probe once it lands: findTmux no longer spawns a login shell of its
+ // own, so a tmux living only on the user's shell PATH is invisible until this resolves.
+ void resolveShellPath().then(() => this.ensureTmux())
this.ensureTmux()
}
@@ -1104,7 +1037,7 @@ export class PtyManager {
// terminal — and any agent CLI it launches — resolves exactly what a normal terminal would.
// Reads the cache filled by the async probe: create() awaits it, and the detached/host
// paths spawn late enough that the init()-time prewarm has long since settled.
- const shellPath = cachedShellPath ?? null
+ const shellPath = shellPathNow() ?? null
if (shellPath) env.PATH = shellPath
// Same GUI-launch gap for the locale: with no LANG/LC_* the shell's `locale` is "C" (non-UTF-8),
diff --git a/src/core/remote-ssh/remote-git.ts b/src/core/remote-ssh/remote-git.ts
index 0be570470..8aeb90c0b 100644
--- a/src/core/remote-ssh/remote-git.ts
+++ b/src/core/remote-ssh/remote-git.ts
@@ -3,9 +3,10 @@
// inject into the remote shell). runRemoteGit returns the SAME { ok, out, err } shape as the local
// git() helper so callers are transport-agnostic. A module-level resolver registry lets both
// git-service.ts and commit-message.ts route the same way without threading a ref through every op.
-import { execFile, execFileSync } from 'child_process'
+import { execFile } from 'child_process'
import { promisify } from 'util'
import { childArgs } from './control-master'
+import { findExecutableSync, shellPathNow } from '../exec-path'
import { posixQuote, quoteRemotePath, type SshConnection } from '../../shared/ssh'
const run = promisify(execFile)
@@ -23,32 +24,17 @@ export function remoteGitArgs(conn: SshConnection, controlPath: string, cwd: str
let sshPath: string | null | undefined
function findSsh(): string | null {
if (sshPath !== undefined) return sshPath
- // GUI apps don't inherit the shell PATH, so probe a login shell first (mirrors
- // commit-message.ts). Kept self-contained — importing ssh-project.ts would pull in electron and
- // break this module's pure vitest tests.
- try {
- const out = execFileSync('/usr/bin/env', ['sh', '-lc', 'command -v ssh'], {
- encoding: 'utf-8'
- }).trim()
- if (out) {
- execFileSync(out, ['-V'], { stdio: 'ignore' })
- sshPath = out
- return out
- }
- } catch {
- /* fall back to the hardcoded paths */
- }
- for (const p of ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh']) {
- try {
- execFileSync(p, ['-V'], { stdio: 'ignore' })
- sshPath = p
- return p
- } catch {
- /* try next */
- }
- }
- sshPath = null
- return null
+ // GUI apps don't inherit the shell PATH. Subprocess-free (was a sync login-shell probe plus
+ // an `ssh -V` spawn per candidate, blocking the main thread): walk the cached login-shell
+ // PATH from exec-path.ts, then the hardcoded locations. A MISS is only memoized once the
+ // async PATH probe has settled, so a custom-location ssh isn't cached away forever.
+ const found = findExecutableSync('ssh', [
+ '/usr/bin/ssh',
+ '/usr/local/bin/ssh',
+ '/opt/homebrew/bin/ssh'
+ ])
+ if (found || shellPathNow() !== undefined) sshPath = found
+ return found
}
/** Run a git command on the remote over the master. Returns the same shape as the local git() helper. */
diff --git a/src/main/remote-context-tail.ts b/src/main/remote-context-tail.ts
index e6583c50b..fb094f8c8 100644
--- a/src/main/remote-context-tail.ts
+++ b/src/main/remote-context-tail.ts
@@ -61,16 +61,19 @@ export function createRemoteContextTail(
const scan = (sessionId: string, t: Tracked, read: string): void => {
const buf = Buffer.from(read)
const combined = t.carry?.length ? Buffer.concat([t.carry, buf]) : buf
- const { text: complete, carry } = splitCompleteLines(combined)
- t.carry = carry
- const latest = parseLatestUsage(combined.toString('utf-8'))
+ t.carry = splitCompleteLines(combined).carry
+ // ONE split shared by all three scanners (mirrors the local tail): the last element is the
+ // torn tail past the final newline, so dropping it yields the complete lines.
+ const lines = combined.toString('utf-8').split('\n')
+ const completeLines = lines.slice(0, -1)
+ const latest = parseLatestUsage(lines)
if (latest) {
t.used = latest.used
t.model = latest.model ?? t.model
}
- if (opts?.onToolResult && hasToolResult(complete)) opts.onToolResult(sessionId)
+ if (opts?.onToolResult && hasToolResult(completeLines)) opts.onToolResult(sessionId)
if (opts?.onTaskNotification) {
- for (const n of parseTaskNotifications(complete)) opts.onTaskNotification(sessionId, n)
+ for (const n of parseTaskNotifications(completeLines)) opts.onTaskNotification(sessionId, n)
}
}
diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.ts
index 52ba25758..c2c79ed81 100644
--- a/src/main/remote-ssh/ssh-project.ts
+++ b/src/main/remote-ssh/ssh-project.ts
@@ -1,11 +1,12 @@
import { promises as fs } from 'fs'
import path from 'path'
-import { spawn, execFile, execFileSync } from 'child_process'
+import { spawn, execFile } from 'child_process'
import { app, ipcMain, type BrowserWindow } from 'electron'
import { IPC } from '../../shared/ipc'
import { parseLsDirs, posixQuote, quoteRemotePath, remoteTmuxConf, sshHostKey, type SshConnection } from '../../shared/ssh'
import type { DownloadResult, SshProjectStatusEvent } from '../../shared/types'
import { candidateName, safeDownloadBasename } from '../../core/download-name'
+import { findExecutableSync, shellPathNow } from '../../core/exec-path'
import { mediaCachePruneList, remoteMediaCacheName } from '../../core/remote-ssh/media-cache'
import { allowMediaPath } from '../media-protocol'
import { remoteAccountConfigDir, isSupportedClaudeVersion } from '../../core/claude-accounts-core'
@@ -113,58 +114,34 @@ interface Conn {
/**
* Resolve an absolute ssh path; GUI apps don't inherit the shell PATH.
- * Mirrors findSsh() in pty-manager.ts: a cached login-shell `command -v ssh` lookup with
- * common-location fallbacks. (Do NOT use the brief's always-returns-first stub.)
+ * Mirrors findSsh() in pty-manager.ts: subprocess-free (the old sync login-shell probe + `-V`
+ * spawns blocked the main thread) — walks the cached login-shell PATH from exec-path.ts, then
+ * the common locations. A MISS is only memoized once the async PATH probe has settled.
+ * (Do NOT use the brief's always-returns-first stub.)
*/
let cachedSsh: string | null | undefined
function sshBin(): string {
if (cachedSsh !== undefined) return cachedSsh ?? 'ssh'
- try {
- const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', 'command -v ssh'], {
- encoding: 'utf-8'
- }).trim()
- cachedSsh = out || null
- } catch {
- cachedSsh = null
- }
- if (!cachedSsh) {
- for (const p of ['/usr/bin/ssh', '/usr/local/bin/ssh', '/opt/homebrew/bin/ssh']) {
- try {
- execFileSync(p, ['-V'], { stdio: 'ignore' })
- cachedSsh = p
- break
- } catch {
- // keep trying
- }
- }
- }
- return cachedSsh ?? 'ssh'
+ const found = findExecutableSync('ssh', [
+ '/usr/bin/ssh',
+ '/usr/local/bin/ssh',
+ '/opt/homebrew/bin/ssh'
+ ])
+ if (found || shellPathNow() !== undefined) cachedSsh = found
+ return found ?? 'ssh'
}
/** Resolve an absolute `scp` path the same way `sshBin()` resolves `ssh` (GUI apps lack shell PATH). */
let cachedScp: string | null | undefined
function scpBin(): string {
if (cachedScp !== undefined) return cachedScp ?? 'scp'
- try {
- const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', 'command -v scp'], {
- encoding: 'utf-8'
- }).trim()
- cachedScp = out || null
- } catch {
- cachedScp = null
- }
- if (!cachedScp) {
- for (const p of ['/usr/bin/scp', '/usr/local/bin/scp', '/opt/homebrew/bin/scp']) {
- try {
- execFileSync(p, ['-V'], { stdio: 'ignore' })
- cachedScp = p
- break
- } catch {
- // keep trying
- }
- }
- }
- return cachedScp ?? 'scp'
+ const found = findExecutableSync('scp', [
+ '/usr/bin/scp',
+ '/usr/local/bin/scp',
+ '/opt/homebrew/bin/scp'
+ ])
+ if (found || shellPathNow() !== undefined) cachedScp = found
+ return found ?? 'scp'
}
export class SshProjectManager {
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index ea7aba9fb..c5f2618ad 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useShallow } from 'zustand/react/shallow'
import { playSfx, primeSfx } from '@renderer/lib/sfx'
import {
addEdge,
@@ -875,7 +876,11 @@ export function Canvas() {
const hasProjects = useProjects((s) => s.projects.some((p) => !p.closed))
// Exclude UNAVAILABLE closed projects (folder missing): reopenProject would activate them
// unconditionally → a silent-discard empty canvas (the same case the palette guard blocks).
- const closedProjects = useProjects((s) => s.projects.filter((p) => p.closed && !p.unavailable))
+ // useShallow: the filter derives a NEW array each call — without it, every useProjects write
+ // (each kanban board commit, each debounced canvas save) re-rendered the entire Canvas.
+ const closedProjects = useProjects(
+ useShallow((s) => s.projects.filter((p) => p.closed && !p.unavailable))
+ )
// The active project's SSH server (if it's an SSH project) — drives the connection banner.
const activeSshServer = useProjects(
(s) => s.projects.find((p) => p.id === s.activeProjectId)?.ssh?.server
@@ -5070,6 +5075,12 @@ export function Canvas() {
[focusNodeById]
)
+ // Stable identity for the memoized KanbanView — an inline arrow here would re-render the
+ // whole board on every Canvas render.
+ const setKanbanModalNode = useCallback((id: string | null) => {
+ kanbanModalNodeRef.current = id
+ }, [])
+
const onPaletteQuery = useCallback((q: string) => {
transcriptQueryRef.current = q
// Reset any pending search so rapid keystrokes only fire one IPC call.
@@ -6150,6 +6161,13 @@ export function Canvas() {
[activeProjectId, setNodes, markDirty, writeDisk]
)
+ // Stable identity for the memoized KanbanView — an inline arrow would re-render the whole
+ // board on every Canvas render.
+ const renameNodeFromKanban = useCallback(
+ (nodeId: string, title: string) => renameSession(activeProjectId, nodeId, title),
+ [renameSession, activeProjectId]
+ )
+
// Write-through a sticky node's body text from the kanban card modal (the canvas sticky
// reads the same data.text path).
const editStickyText = useCallback(
@@ -7180,10 +7198,10 @@ export function Canvas() {
onChange={onKanbanChange}
onOpenNode={openNodeFromKanban}
onCreateNode={createNodeInColumn}
- onRenameNode={(nodeId, title) => renameSession(activeProjectId, nodeId, title)}
+ onRenameNode={renameNodeFromKanban}
onEditSticky={editStickyText}
onDeleteNode={deleteNodeFromKanban}
- onModalNodeChange={(id) => (kanbanModalNodeRef.current = id)}
+ onModalNodeChange={setKanbanModalNode}
onBrowserNav={browserNavFromKanban}
/>
)}
diff --git a/src/renderer/components/kanban/CardMetaBar.tsx b/src/renderer/components/kanban/CardMetaBar.tsx
index 4e540d1da..7f1dac7ff 100644
--- a/src/renderer/components/kanban/CardMetaBar.tsx
+++ b/src/renderer/components/kanban/CardMetaBar.tsx
@@ -3,7 +3,8 @@ import type { BoardLogAuthor, KanbanPriority, ProjectKanban } from '@shared/type
import { cardMeta, labelsForCard, setCardDue, setCardPriority, toggleAssignee } from '../../lib/kanban'
import { LabelChips } from './LabelChips'
import { LabelPicker } from './LabelPicker'
-import { loadIdentity, selectOthers, usePresence } from '../../state/presence'
+import { useShallow } from 'zustand/react/shallow'
+import { loadIdentity, selectFaces, usePresence } from '../../state/presence'
import { useBoardLog } from '../../state/boardLog'
import { useProjects } from '../../state/projects'
@@ -39,7 +40,10 @@ export function CardMetaBar({ nodeId, board, onChange }: CardMetaBarProps) {
const labels = labelsForCard(board, nodeId)
const projectId = useProjects((s) => s.activeProjectId)
const logEntries = useBoardLog((s) => s.entriesFor(projectId))
- const peers = usePresence(selectOthers)
+ // selectFaces + useShallow, NOT selectOthers: the pool only needs name+color, and applyDiff
+ // replaces the whole PeerState on every cursor patch (~20/s per peer) — subscribing to
+ // PeerState re-rendered the open card modal at cursor rate. Faces are cursor-immune.
+ const peers = usePresence(useShallow(selectFaces))
const pool = useMemo(() => {
const seen = new Map<string, BoardLogAuthor>()
diff --git a/src/renderer/components/kanban/KanbanColumn.tsx b/src/renderer/components/kanban/KanbanColumn.tsx
index 2efea57b4..b6b87a681 100644
--- a/src/renderer/components/kanban/KanbanColumn.tsx
+++ b/src/renderer/components/kanban/KanbanColumn.tsx
@@ -1,4 +1,4 @@
-import { useState } from 'react'
+import { memo, useCallback, useState } from 'react'
import type { KanbanColumn as KanbanColumnT } from '@shared/types'
import { NODE_COLORS } from '../../state/workspace'
import { SessionCard } from './SessionCard'
@@ -9,30 +9,34 @@ interface KanbanColumnProps {
/** null = the virtual Ungrouped column: fixed label, no rename/recolor/delete, header not draggable. */
column: KanbanColumnT | null
cards: KanbanSession[]
- onRename?: (title: string) => void
- onRecolor?: (color: string) => void
- onDelete?: () => void
+ // Column-scoped callbacks carry the column id (and card-scoped ones the node id) so KanbanView
+ // can hand every column the SAME function references — that identity stability is what lets
+ // memo() skip columns/cards untouched by a render.
+ onRename?: (columnId: string, title: string) => void
+ onRecolor?: (columnId: string, color: string) => void
+ onDelete?: (columnId: string) => void
/** Open a card's modal (↗ / double-click on the card). */
onOpenCard: (nodeId: string) => void
/** Card metadata lookup (assignees/due) for the chips on each card. */
metaOf: (nodeId: string) => KanbanCardMeta | undefined
/** Resolved board labels for a card (the colored label chips). */
labelsOf: (nodeId: string) => KanbanLabel[]
- /** "+ New" menu entries (agents, terminal, sticky) and what to do when one is picked. */
+ /** "+ New" menu entries (agents, terminal, sticky) and what to do when one is picked
+ * (columnId null = Ungrouped: no assignment). */
createOptions: KanbanCreateOption[]
- onCreate: (choice: KanbanCreateChoice) => void
+ onCreate: (choice: KanbanCreateChoice, columnId: string | null) => void
// Drag plumbing — the single drag source of truth lives in KanbanView.
onCardDragStart: (nodeId: string) => void
- onColumnDragStart?: () => void
+ onColumnDragStart?: (columnId: string) => void
onDragEnd: () => void
/** Drop on the column body: a card lands at the END of this column; a column lands BEFORE it. */
- onDropOnColumn: () => void
- onDropAtCard: (nodeId: string, side: 'before' | 'after') => void
+ onDropOnColumn: (columnId: string | null) => void
+ onDropAtCard: (columnId: string | null, nodeId: string, side: 'before' | 'after') => void
/** Right-click on a card — bubbles the cursor position + node id up to the board menu. */
onCardContext: (nodeId: string, x: number, y: number) => void
}
-export function KanbanColumn({
+export const KanbanColumn = memo(function KanbanColumn({
column, cards, metaOf, labelsOf, onRename, onRecolor, onDelete, onOpenCard, onCardContext,
createOptions, onCreate, onCardDragStart, onColumnDragStart, onDragEnd, onDropOnColumn,
onDropAtCard
@@ -44,9 +48,16 @@ export function KanbanColumn({
// Trello-style drop highlight: counted enter/leave (dragleave fires when crossing children).
const [dragOverCount, setDragOverCount] = useState(0)
+ const colId = column?.id ?? null
+ // Binds this column's id onto the shared card-drop handler; stable while the parent's is.
+ const dropAtCard = useCallback(
+ (nodeId: string, side: 'before' | 'after') => onDropAtCard(colId, nodeId, side),
+ [onDropAtCard, colId]
+ )
+
const commitTitle = () => {
const t = title.trim()
- if (column && t && t !== column.title) onRename?.(t)
+ if (column && t && t !== column.title) onRename?.(column.id, t)
setEditingTitle(false)
}
@@ -59,7 +70,7 @@ export function KanbanColumn({
onDrop={(e) => {
e.preventDefault()
setDragOverCount(0)
- onDropOnColumn()
+ onDropOnColumn(colId)
}}
>
<div
@@ -68,7 +79,7 @@ export function KanbanColumn({
onDragStart={(e) => {
if (!column) return
e.dataTransfer.effectAllowed = 'move'
- onColumnDragStart?.()
+ onColumnDragStart?.(column.id)
}}
onDragEnd={onDragEnd}
>
@@ -108,7 +119,11 @@ export function KanbanColumn({
)}
<span className="kanban-col__count">{cards.length}</span>
{column && (
- <button className="kanban-col__close" title="Delete column (cards return to Ungrouped)" onClick={onDelete}>
+ <button
+ className="kanban-col__close"
+ title="Delete column (cards return to Ungrouped)"
+ onClick={() => onDelete?.(column.id)}
+ >
✕
</button>
)}
@@ -121,7 +136,7 @@ export function KanbanColumn({
className="kanban-col__swatch"
style={{ background: c }}
onClick={() => {
- onRecolor?.(c)
+ if (column) onRecolor?.(column.id, c)
setSwatchesOpen(false)
}}
/>
@@ -135,11 +150,11 @@ export function KanbanColumn({
session={s}
meta={metaOf(s.id)}
labels={labelsOf(s.id)}
- onOpen={() => onOpenCard(s.id)}
- onContext={(x, y) => onCardContext(s.id, x, y)}
- onDragStart={() => onCardDragStart(s.id)}
+ onOpen={onOpenCard}
+ onContext={onCardContext}
+ onDragStart={onCardDragStart}
onDragEnd={onDragEnd}
- onDropAt={(side) => onDropAtCard(s.id, side)}
+ onDropAt={dropAtCard}
/>
))}
</div>
@@ -151,7 +166,7 @@ export function KanbanColumn({
key={o.key}
onClick={() => {
setNewMenuOpen(false)
- onCreate(o.choice)
+ onCreate(o.choice, colId)
}}
>
<span className="kanban-col__newicon">{o.icon}</span>
@@ -166,4 +181,4 @@ export function KanbanColumn({
</div>
</div>
)
-}
+})
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index 699974df8..ffab253e6 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -1,5 +1,5 @@
-import { useEffect, useRef, useState } from 'react'
-import type { ProjectKanban } from '@shared/types'
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import type { KanbanLabel, ProjectKanban } from '@shared/types'
import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId } from '@shared/agents/config'
import { useAgentStatus } from '../../state/agentStatus'
import { useViewMode } from '../../state/viewMode'
@@ -72,10 +72,17 @@ export interface KanbanViewProps {
type Drag = { kind: 'card' | 'column'; id: string } | null
+/** Shared empty results — stable identities so memoized cards/columns see "no change". */
+const NO_LABELS: KanbanLabel[] = []
+const NO_CARDS: KanbanSession[] = []
+
/** Full-page session board OVER the canvas. The canvas stays mounted underneath (its
* agent-status listeners must keep running, and display:none would 0×0-resize every
- * terminal into a tmux SIGWINCH) — this is an opaque overlay, nothing more. */
-export function KanbanView({
+ * terminal into a tmux SIGWINCH) — this is an opaque overlay, nothing more.
+ * memo: Canvas re-renders on plenty the board doesn't care about (agent signatures, camera
+ * banners…); with every prop stable (Canvas useCallbacks + memoized board/sessions) those
+ * renders stop at this boundary. */
+export const KanbanView = memo(function KanbanView({
board, sessions, onChange, onOpenNode, onCreateNode, onRenameNode, onEditSticky, onDeleteNode,
onModalNodeChange, onBrowserNav
}: KanbanViewProps) {
@@ -89,10 +96,11 @@ export function KanbanView({
const [labelFilter, setLabelFilter] = useState<string[]>([])
const [filterOpen, setFilterOpen] = useState(false)
// Drop ids no longer in the palette so a deleted label can't keep the board filtered to nothing.
- const paletteLabels = boardLabels(board)
- const activeFilter = labelFilter.filter((id) => paletteLabels.some((l) => l.id === id))
- const visible = (ids: string[]): string[] =>
- activeFilter.length ? ids.filter((id) => cardMatchesLabelFilter(board, id, activeFilter)) : ids
+ const paletteLabels = useMemo(() => boardLabels(board), [board])
+ const activeFilter = useMemo(
+ () => labelFilter.filter((id) => paletteLabels.some((l) => l.id === id)),
+ [labelFilter, paletteLabels]
+ )
const toggleFilter = (id: string): void =>
setLabelFilter((f) => (f.includes(id) ? f.filter((x) => x !== id) : [...f, id]))
// Opening a card = you're looking at that session: clear its unread badge, and report the open
@@ -115,30 +123,53 @@ export function KanbanView({
const projectColor = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId)?.color)
const customAgents = useSettings((s) => s.settings.customAgents)
// "+ New" menu entries: the builtin agents, the user's custom agents, then terminal + sticky
- // (same universe as the dock's add menu, minus canvas-only kinds).
- const createOptions: KanbanCreateOption[] = [
- ...BUILTIN_AGENT_IDS.map((id) => ({
- key: id,
- label: AGENT_CONFIG[id].label,
- choice: { kind: 'agent', agentId: id } as KanbanCreateChoice,
- icon: <IconAgent />
- })),
- ...customAgents.map((a) => ({
- key: a.id,
- label: a.label,
- choice: { kind: 'agent', agentId: a.id } as KanbanCreateChoice,
- icon: <IconAgent />
- })),
- { key: 'terminal', label: 'Terminal', choice: { kind: 'terminal' }, icon: <IconTerminal /> },
- { key: 'browser', label: 'Browser', choice: { kind: 'browser' }, icon: <IconWeb /> },
- { key: 'sticky', label: 'Sticky note', choice: { kind: 'sticky' }, icon: <IconNote /> }
- ]
- const byId = new Map(sessions.map((s) => [s.id, s]))
+ // (same universe as the dock's add menu, minus canvas-only kinds). Memoized — a fresh array
+ // (with fresh icon elements) per render would re-render every memoized column.
+ const createOptions: KanbanCreateOption[] = useMemo(
+ () => [
+ ...BUILTIN_AGENT_IDS.map((id) => ({
+ key: id,
+ label: AGENT_CONFIG[id].label,
+ choice: { kind: 'agent', agentId: id } as KanbanCreateChoice,
+ icon: <IconAgent />
+ })),
+ ...customAgents.map((a) => ({
+ key: a.id,
+ label: a.label,
+ choice: { kind: 'agent', agentId: a.id } as KanbanCreateChoice,
+ icon: <IconAgent />
+ })),
+ { key: 'terminal', label: 'Terminal', choice: { kind: 'terminal' }, icon: <IconTerminal /> },
+ { key: 'browser', label: 'Browser', choice: { kind: 'browser' }, icon: <IconWeb /> },
+ { key: 'sticky', label: 'Sticky note', choice: { kind: 'sticky' }, icon: <IconNote /> }
+ ],
+ [customAgents]
+ )
+ const byId = useMemo(() => new Map(sessions.map((s) => [s.id, s])), [sessions])
+ const sessionIds = useMemo(() => sessions.map((s) => s.id), [sessions])
+
+ // Stable per-card label arrays: labelsForCard allocates a fresh array per call, and that
+ // identity churn alone would defeat SessionCard's memo. Recomputed only on a board change.
+ const labelsByCard = useMemo(() => {
+ const m = new Map<string, KanbanLabel[]>()
+ if (Array.isArray(board.meta)) {
+ for (const entry of board.meta) {
+ if (!entry?.nodeId) continue
+ const l = labelsForCard(board, entry.nodeId)
+ if (l.length) m.set(entry.nodeId, l)
+ }
+ }
+ return m
+ }, [board])
+ const labelsOf = useCallback((id: string) => labelsByCard.get(id) ?? NO_LABELS, [labelsByCard])
+ const metaOf = useCallback((id: string) => cardMeta(board, id), [board])
// Prune dead nodes' assignments on every persisted change, so they never accumulate
// in the shared file.
- const commit = (next: ProjectKanban) =>
- onChange(pruneAssignments(next, sessions.map((s) => s.id)))
+ const commit = useCallback(
+ (next: ProjectKanban) => onChange(pruneAssignments(next, sessionIds)),
+ [onChange, sessionIds]
+ )
const takeDrag = (): Drag => {
const d = dragRef.current
@@ -147,33 +178,80 @@ export function KanbanView({
}
// columnId null = the virtual Ungrouped column.
- const dropOnColumn = (columnId: string | null) => {
- const drag = takeDrag()
- if (!drag) return
- if (drag.kind === 'card') commit(assignNode(board, drag.id, columnId, null))
- else if (columnId !== null) commit(moveColumn(board, drag.id, columnId))
- // a column dropped on Ungrouped is a no-op — Ungrouped is always first
- }
+ const dropOnColumn = useCallback(
+ (columnId: string | null) => {
+ const drag = takeDrag()
+ if (!drag) return
+ if (drag.kind === 'card') commit(assignNode(board, drag.id, columnId, null))
+ else if (columnId !== null) commit(moveColumn(board, drag.id, columnId))
+ // a column dropped on Ungrouped is a no-op — Ungrouped is always first
+ },
+ [board, commit]
+ )
- const dropAtCard = (columnId: string | null, targetNodeId: string, side: 'before' | 'after') => {
- const drag = takeDrag()
- if (!drag) return
- if (drag.kind === 'column') {
- if (columnId !== null) commit(moveColumn(board, drag.id, columnId))
- return
+ const dropAtCard = useCallback(
+ (columnId: string | null, targetNodeId: string, side: 'before' | 'after') => {
+ const drag = takeDrag()
+ if (!drag) return
+ if (drag.kind === 'column') {
+ if (columnId !== null) commit(moveColumn(board, drag.id, columnId))
+ return
+ }
+ // "after this card" = "before the NEXT card in the column" (null = end of column).
+ const ids = columnId === null ? unassigned(board, sessionIds) : assignedTo(board, columnId)
+ let beforeId: string | null = targetNodeId
+ if (side === 'after') {
+ const i = ids.indexOf(targetNodeId)
+ beforeId = i >= 0 && i + 1 < ids.length ? ids[i + 1] : null
+ }
+ commit(assignNode(board, drag.id, columnId, beforeId))
+ },
+ [board, commit, sessionIds]
+ )
+
+ // Per-column card lists in one pass, so a board render doesn't re-derive (and re-allocate)
+ // them per column — and their identities hold across renders that change neither the board,
+ // the sessions, nor the filter, which is what lets the memoized columns skip.
+ const columnCards = useMemo(() => {
+ const vis = (ids: string[]): string[] =>
+ activeFilter.length ? ids.filter((id) => cardMatchesLabelFilter(board, id, activeFilter)) : ids
+ const toCards = (ids: string[]): KanbanSession[] => {
+ const cards = ids.flatMap((id) => (byId.has(id) ? [byId.get(id)!] : []))
+ return cards.length ? cards : NO_CARDS
}
- // "after this card" = "before the NEXT card in the column" (null = end of column).
- const ids = columnId === null ? unassigned(board, sessions.map((s) => s.id)) : assignedTo(board, columnId)
- let beforeId: string | null = targetNodeId
- if (side === 'after') {
- const i = ids.indexOf(targetNodeId)
- beforeId = i >= 0 && i + 1 < ids.length ? ids[i + 1] : null
+ return {
+ ungrouped: toCards(vis(unassigned(board, sessionIds))),
+ byColumn: new Map(board.columns.map((c) => [c.id, toCards(vis(assignedTo(board, c.id)))]))
}
- commit(assignNode(board, drag.id, columnId, beforeId))
- }
+ }, [board, byId, sessionIds, activeFilter])
- const sessionsFor = (ids: string[]) =>
- ids.flatMap((id) => (byId.has(id) ? [byId.get(id)!] : []))
+ // Stable column/card plumbing — every handler the memoized columns receive is identity-stable
+ // across renders (the column binds its own id; cards bind theirs).
+ const handleCardDragStart = useCallback((id: string) => {
+ dragRef.current = { kind: 'card', id }
+ }, [])
+ const handleColumnDragStart = useCallback((columnId: string) => {
+ dragRef.current = { kind: 'column', id: columnId }
+ }, [])
+ const handleDragEnd = useCallback(() => {
+ dragRef.current = null
+ }, [])
+ const handleCardContext = useCallback(
+ (id: string, x: number, y: number) => setCardMenu({ nodeId: id, x, y }),
+ []
+ )
+ const handleRenameColumn = useCallback(
+ (columnId: string, t: string) => commit(renameColumn(board, columnId, t)),
+ [board, commit]
+ )
+ const handleRecolorColumn = useCallback(
+ (columnId: string, c: string) => commit(recolorColumn(board, columnId, c)),
+ [board, commit]
+ )
+ const handleDeleteColumn = useCallback(
+ (columnId: string) => commit(deleteColumn(board, columnId)),
+ [board, commit]
+ )
// Right-click menu for a card: open on canvas, move to another column, delete.
const cardMenuItems = (nodeId: string): MenuItem[] => {
@@ -246,37 +324,37 @@ export function KanbanView({
<div className="kanban-board">
<KanbanColumn
column={null}
- cards={sessionsFor(visible(unassigned(board, sessions.map((s) => s.id))))}
- metaOf={(id) => cardMeta(board, id)}
- labelsOf={(id) => labelsForCard(board, id)}
+ cards={columnCards.ungrouped}
+ metaOf={metaOf}
+ labelsOf={labelsOf}
onOpenCard={setModalNodeId}
createOptions={createOptions}
- onCreate={(choice) => onCreateNode(choice, null)}
- onCardDragStart={(id) => (dragRef.current = { kind: 'card', id })}
- onDragEnd={() => (dragRef.current = null)}
- onDropOnColumn={() => dropOnColumn(null)}
- onDropAtCard={(id, side) => dropAtCard(null, id, side)}
- onCardContext={(id, x, y) => setCardMenu({ nodeId: id, x, y })}
+ onCreate={onCreateNode}
+ onCardDragStart={handleCardDragStart}
+ onDragEnd={handleDragEnd}
+ onDropOnColumn={dropOnColumn}
+ onDropAtCard={dropAtCard}
+ onCardContext={handleCardContext}
/>
{board.columns.map((col) => (
<KanbanColumn
key={col.id}
column={col}
- cards={sessionsFor(visible(assignedTo(board, col.id)))}
- metaOf={(id) => cardMeta(board, id)}
- labelsOf={(id) => labelsForCard(board, id)}
- onRename={(t) => commit(renameColumn(board, col.id, t))}
- onRecolor={(c) => commit(recolorColumn(board, col.id, c))}
- onDelete={() => commit(deleteColumn(board, col.id))}
+ cards={columnCards.byColumn.get(col.id) ?? NO_CARDS}
+ metaOf={metaOf}
+ labelsOf={labelsOf}
+ onRename={handleRenameColumn}
+ onRecolor={handleRecolorColumn}
+ onDelete={handleDeleteColumn}
onOpenCard={setModalNodeId}
createOptions={createOptions}
- onCreate={(choice) => onCreateNode(choice, col.id)}
- onCardDragStart={(id) => (dragRef.current = { kind: 'card', id })}
- onColumnDragStart={() => (dragRef.current = { kind: 'column', id: col.id })}
- onDragEnd={() => (dragRef.current = null)}
- onDropOnColumn={() => dropOnColumn(col.id)}
- onDropAtCard={(id, side) => dropAtCard(col.id, id, side)}
- onCardContext={(id, x, y) => setCardMenu({ nodeId: id, x, y })}
+ onCreate={onCreateNode}
+ onCardDragStart={handleCardDragStart}
+ onColumnDragStart={handleColumnDragStart}
+ onDragEnd={handleDragEnd}
+ onDropOnColumn={dropOnColumn}
+ onDropAtCard={dropAtCard}
+ onCardContext={handleCardContext}
/>
))}
<button
@@ -313,4 +391,4 @@ export function KanbanView({
)}
</div>
)
-}
+})
diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsx
index f13e35ae2..fe64d5111 100644
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@ -1,26 +1,37 @@
-import { useState } from 'react'
+import { memo, useState } from 'react'
import type { KanbanCardMeta, KanbanLabel, KanbanPriority } from '@shared/types'
import { useAgentStatus } from '../../state/agentStatus'
import { ContextMeter } from '../ContextMeter'
import { LabelChips } from './LabelChips'
import type { KanbanSession } from './KanbanView'
+const PRIO_COLOR: Record<KanbanPriority, string> = {
+ low: '#8e8e93',
+ medium: '#ffd60a',
+ high: '#ff9f0a',
+ urgent: '#ff453a'
+}
+
interface SessionCardProps {
session: KanbanSession
meta?: KanbanCardMeta
/** Resolved board labels on this card (LabelChips) — resolved by the board, passed in. */
labels?: KanbanLabel[]
+ // Every callback carries the node id so the column can pass ONE stable function to all its
+ // cards — per-card arrow closures would give each card fresh props and defeat the memo.
/** Single click opens the card modal directly (the expand/collapse step was dropped). */
- onOpen: () => void
- onDragStart: () => void
+ onOpen: (nodeId: string) => void
+ onDragStart: (nodeId: string) => void
onDragEnd: () => void
/** A dragged card was dropped on this card — before it (top half) or after it (bottom half). */
- onDropAt: (side: 'before' | 'after') => void
+ onDropAt: (nodeId: string, side: 'before' | 'after') => void
/** Right-click on the card — opens the actions menu at the cursor. */
- onContext: (x: number, y: number) => void
+ onContext: (nodeId: string, x: number, y: number) => void
}
-export function SessionCard({ session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext }: SessionCardProps) {
+export const SessionCard = memo(function SessionCard({
+ session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext
+}: SessionCardProps) {
// THIS card's agent status, subscribed per card rather than threaded down from the board.
// KanbanView used to hold `useAgentStatus((s) => s.byId)` and pass the map through the column:
// that map's identity changes on every hook event of every node, so one agent's working→idle
@@ -47,12 +58,6 @@ export function SessionCard({ session, meta, labels = [], onOpen, onDragStart, o
const due = meta?.dueAt
const overdue = due !== undefined && due < Date.now()
const priority = meta?.priority
- const PRIO_COLOR: Record<KanbanPriority, string> = {
- low: '#8e8e93',
- medium: '#ffd60a',
- high: '#ff9f0a',
- urgent: '#ff453a'
- }
const hasDetail = !!status?.sessionId || !!status?.session || stickyPreview.includes('\n')
return (
<div
@@ -63,7 +68,7 @@ export function SessionCard({ session, meta, labels = [], onOpen, onDragStart, o
onDragStart={(e) => {
e.dataTransfer.effectAllowed = 'move'
setDragging(true)
- onDragStart()
+ onDragStart(session.id)
}}
onDragEnd={() => {
setDragging(false)
@@ -81,12 +86,12 @@ export function SessionCard({ session, meta, labels = [], onOpen, onDragStart, o
e.stopPropagation() // don't let the column's end-drop swallow a drop aimed at this card
const side = sideFor(e)
setDropSide(null)
- onDropAt(side)
+ onDropAt(session.id, side)
}}
- onClick={onOpen}
+ onClick={() => onOpen(session.id)}
onContextMenu={(e) => {
e.preventDefault()
- onContext(e.clientX, e.clientY)
+ onContext(session.id, e.clientX, e.clientY)
}}
title="Open card"
>
@@ -150,4 +155,4 @@ export function SessionCard({ session, meta, labels = [], onOpen, onDragStart, o
)}
</div>
)
-}
+})