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.

refactor: one definition for helpers that were copied across the tree

review3fdd4820a4f4
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 4d3135114..a71881d29 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -265,6 +265,13 @@ anything else. Board-level fields survive every transform — `pullLinks` is one
## House rules
+- **Check `src/shared` before writing a two-line helper.** A JSON-object guard (`isRecord`), an
+ error's message (`errorText`), `sleep`, the root-space parent walk (`rootPositionWith`) and the
+ credential-store temp sweep (`sweepForeignTempFiles` in `core/fs-atomic.ts`) each existed in five
+ to twenty-one hand-typed copies until #1252's follow-up, and the parent walk's copies had already
+ drifted apart on corrupt canvases. A local helper that shares a name but behaves differently
+ (zellij's `errorText`, windows-conpty's array-accepting guard) is not a copy; leave it alone.
+
- **Typing into a pane by node id goes through `PtyManager.sendPaneKeys`, and an SSH-project node
is never read or typed into on the local tmux socket.** An unmounted remote node resolves through
`remoteNodeOwner` or is refused (`not-connected`); `paneCommand` / `paneOwner` resolve unmounted
diff --git a/docs/atomic-writes.md b/docs/atomic-writes.md
index f4166ded8..688531b66 100644
--- a/docs/atomic-writes.md
+++ b/docs/atomic-writes.md
@@ -131,6 +131,15 @@ directory intentionally, including across PID namespaces where signal-0/`ESRCH`
`sweepStaleTempFiles` therefore never auto-deletes any pid-bearing temp; only the exact historical
ownerless `<file>.tmp` shape can be swept, after a conservative 24-hour grace.
+Stores whose orphaned temp would be a live credential (a GitHub token, a provider cookie, the
+phone pairing bearers in `agent.json`) make the opposite trade on purpose, through
+`sweepForeignTempFiles`. A unique name is never written twice, so such an orphan would sit on disk
+at 0600 forever; that sweep removes every temp this process does not own, with no grace, and
+accepts that a second live process's rename can then fail with `ENOENT`. The workspace store uses
+it too, for `workspace.json` and `project.json`. Both sweeps recognize temps through the same
+`atomicTempCandidate`, so a change to `tempNameFor` reaches both. The rule used to be re-typed at
+five call sites, each with its own copy of the temp-name regex.
+
## Deletes whose purpose is to stop something
`removeAtomic` retries the same transient Windows codes for `unlink`, and treats only `ENOENT` as
diff --git a/src/core/agent-launch.ts b/src/core/agent-launch.ts
index 19b63b6bd..3bdbfacc5 100644
--- a/src/core/agent-launch.ts
+++ b/src/core/agent-launch.ts
@@ -15,6 +15,7 @@ import {
import { approvalFlags } from "../shared/agents/approval-mode";
import { CODEX_NO_DAEMON_FLAG } from "../shared/agents/codex-daemon";
import { SAFE_SESSION_ID } from "../shared/session-id";
+import { isRecord } from "../shared/is-record";
/** The parser that owns a live local Windows-profile terminal. */
export type AgentLaunchDialect =
@@ -155,10 +156,6 @@ function fail(code: AgentLaunchPreparationErrorCode): never {
throw new AgentLaunchPreparationError(code);
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
function hasOnlyOwnFields(
value: Record<string, unknown>,
allowed: ReadonlySet<string>,
diff --git a/src/core/agents/hooks/antigravity.ts b/src/core/agents/hooks/antigravity.ts
index 1d8763362..54c73c4ee 100644
--- a/src/core/agents/hooks/antigravity.ts
+++ b/src/core/agents/hooks/antigravity.ts
@@ -47,6 +47,7 @@ import {
} from './antigravity-windows-wrapper'
import { readCmdAutoRun, type CmdAutoRunCheck } from './antigravity-autorun'
import { findExecutableSync, resolveShellPath } from '../../exec-path'
+import { isRecord } from '../../../shared/is-record'
/**
* Where the vendor's own installer puts `agy` (antigravity.google/docs/cli/install): `~/.local/bin`
@@ -199,9 +200,6 @@ export function isAntigravityManagedCommand(command: unknown): boolean {
)
}
-const isRecord = (v: unknown): v is Record<string, unknown> =>
- typeof v === 'object' && v !== null && !Array.isArray(v)
-
/**
* Copy a key as an OWN property. `JSON.parse` makes a `"__proto__"` key an own property, but
* `obj['__proto__'] = v` on a plain object sets its PROTOTYPE instead, and `JSON.stringify` then
diff --git a/src/core/agents/hooks/cursor.ts b/src/core/agents/hooks/cursor.ts
index e7b7fdc33..eafa141db 100644
--- a/src/core/agents/hooks/cursor.ts
+++ b/src/core/agents/hooks/cursor.ts
@@ -24,13 +24,13 @@ import { buildManagedHookCommand, normalizeHookCommand, writeManagedHookFileAtom
import { buildManagedScript } from './managed-script'
import { updateSettingsFile } from './settings-file'
import { findExecutableSync } from '../../exec-path'
+import { isRecord } from '../../../shared/is-record'
export const CURSOR_SCRIPT_FILE = 'cursor.sh'
/** Seconds Cursor waits for one handler (its default is 60). */
export const CURSOR_HOOK_TIMEOUT = 5
type Json = Record<string, unknown>
-const isRecord = (v: unknown): v is Json => typeof v === 'object' && v !== null && !Array.isArray(v)
// `os.homedir()` through the DEFAULT import so a test that spies it redirects the whole install.
export function cursorHooksJsonPath(home: string = os.homedir()): string {
diff --git a/src/core/chat-tool-body.ts b/src/core/chat-tool-body.ts
index 4f5ee2a97..27dc45456 100644
--- a/src/core/chat-tool-body.ts
+++ b/src/core/chat-tool-body.ts
@@ -1,3 +1,4 @@
+import { isRecord } from '../shared/is-record'
// The readable body of a tool call in the ⌘M chat view. Most tool calls are plumbing — a one-line
// chip (`Bash ls`) says all there is to say. Two are not: `ExitPlanMode` carries the full plan the
// user is being asked to approve, and `AskUserQuestion` carries the question and its options. The
@@ -37,7 +38,6 @@ const oneLine = (s: string): string => s.replace(/\s*[\r\n]+\s*/g, ' ').trim()
const escapeEmphasis = (s: string): string => s.replace(/[\\*_]/g, (c) => `\\${c}`)
const bold = (s: string): string => `**${escapeEmphasis(oneLine(s))}**`
-const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
const nonBlank = (v: unknown): v is string => typeof v === 'string' && v.trim() !== ''
function planBody(input: Record<string, unknown>): string | undefined {
@@ -48,14 +48,14 @@ function questionsBody(input: Record<string, unknown>): string | undefined {
if (!Array.isArray(input.questions)) return undefined
const blocks: string[] = []
for (const q of input.questions) {
- if (!isObj(q) || !nonBlank(q.question)) continue
+ if (!isRecord(q) || !nonBlank(q.question)) continue
const lines: string[] = []
if (nonBlank(q.header)) lines.push(bold(q.header), '')
// The question keeps its own paragraphs: it is a block of its own, not a one-line slot.
lines.push(q.multiSelect === true ? `${q.question} _(select all that apply)_` : q.question)
const options = Array.isArray(q.options)
? q.options
- .filter((o): o is Record<string, unknown> => isObj(o) && nonBlank(o.label))
+ .filter((o): o is Record<string, unknown> => isRecord(o) && nonBlank(o.label))
.map((o) => `- ${bold(o.label as string)}${nonBlank(o.description) ? ` — ${oneLine(o.description)}` : ''}`)
: []
if (options.length) lines.push('', ...options)
@@ -66,7 +66,7 @@ function questionsBody(input: Record<string, unknown>): string | undefined {
/** Markdown body for a tool call worth reading in full, or undefined (render the plain chip). */
export function toolBody(name: string, input: unknown): string | undefined {
- if (!isObj(input)) return undefined
+ if (!isRecord(input)) return undefined
const body =
name === 'ExitPlanMode' ? planBody(input) : name === 'AskUserQuestion' ? questionsBody(input) : undefined
return body === undefined ? undefined : capBody(body)
diff --git a/src/core/codex-chat.ts b/src/core/codex-chat.ts
index d2a8988ae..526382df2 100644
--- a/src/core/codex-chat.ts
+++ b/src/core/codex-chat.ts
@@ -37,6 +37,7 @@ import type { ChatCarriedToolResult, ChatMessage, ChatPart } from '../shared/typ
import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
import type { ChatWindowParse } from './transcript-reader'
import { codexHomeFor } from './codex-config-dir'
+import { isRecord } from '../shared/is-record'
type ToolPart = Extract<ChatPart, { kind: 'tool' }>
@@ -57,8 +58,6 @@ export const CODEX_TOOL_SEARCH = 'tool_search'
* claude's `toolArg` keys, then `query` (tool search) and `message` (the collaboration tools). */
const ARG_KEYS = ['cmd', 'command', 'file_path', 'path', 'pattern', 'query', 'description', 'prompt', 'message'] as const
-const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
-
/**
* The one-line hint for a tool call: `arguments` is a JSON string (function_call) or an object
* (tool_search_call). The first `ARG_KEYS` field holding a string (or, for `command`, an array of
@@ -74,7 +73,7 @@ export function codexToolArg(args: unknown): string {
return ''
}
}
- if (!isObj(o)) return ''
+ if (!isRecord(o)) return ''
for (const k of ARG_KEYS) {
const v = o[k]
if (typeof v === 'string') return v.slice(0, CHAT_TOOL_ARG_MAX)
@@ -91,7 +90,7 @@ function outputText(output: unknown): string {
if (typeof output === 'string') return output
if (!Array.isArray(output)) return ''
return output
- .filter((c): c is { type: string; text: string } => isObj(c) && (c.type === 'input_text' || c.type === 'output_text') && typeof c.text === 'string')
+ .filter((c): c is { type: string; text: string } => isRecord(c) && (c.type === 'input_text' || c.type === 'output_text') && typeof c.text === 'string')
.map((c) => c.text)
.join('\n')
}
@@ -132,7 +131,7 @@ function textParts(content: unknown, type: string): ChatPart[] {
if (!Array.isArray(content)) return []
const parts: ChatPart[] = []
for (const c of content) {
- if (isObj(c) && c.type === type && typeof c.text === 'string' && c.text) parts.push({ kind: 'text', text: c.text })
+ if (isRecord(c) && c.type === type && typeof c.text === 'string' && c.text) parts.push({ kind: 'text', text: c.text })
}
return parts
}
@@ -173,7 +172,7 @@ export function parseCodexChatRecords(
skipped++
continue
}
- if (!isObj(o) || !isObj(o.payload)) {
+ if (!isRecord(o) || !isRecord(o.payload)) {
skipped++
continue
}
@@ -203,7 +202,7 @@ export function parseCodexChatRecords(
// PAGINATED: the same, as a thread item. Every other item type duplicates the model stream
// (AgentMessage) or describes a tool the model stream already carries.
const item = p.item
- if (isObj(item) && item.type === 'UserMessage') {
+ if (isRecord(item) && item.type === 'UserMessage') {
const parts = textParts(item.content, 'text')
if (parts.length) {
push('user', parts)
@@ -214,7 +213,7 @@ export function parseCodexChatRecords(
// A turn that FAILED (measured: `usage_limit_exceeded`) says why only here. Without the
// note the reader sees a prompt followed by nothing.
const err = p.error
- if (isObj(err) && typeof err.message === 'string' && err.message.trim()) {
+ if (isRecord(err) && typeof err.message === 'string' && err.message.trim()) {
push('assistant', [{ kind: 'text', text: `[error] ${err.message}` }])
rendered = true
}
diff --git a/src/core/cursor-chat.ts b/src/core/cursor-chat.ts
index 1842462c5..022193927 100644
--- a/src/core/cursor-chat.ts
+++ b/src/core/cursor-chat.ts
@@ -36,10 +36,10 @@ import { metaString, summarizeResult } from './transcript-reader'
import { opencodePageMessages } from './opencode-chat'
import { isCursorBackgroundEvent, isCursorChildToolEvent } from '../shared/agents/normalize'
import { recordRawToolEvent } from './agent-status-mirror'
+import { isRecord } from '../shared/is-record'
type ToolPart = Extract<ChatPart, { kind: 'tool' }>
type Obj = Record<string, unknown>
-const isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)
// ── Pure parsing ────────────────────────────────────────────────────────────────────────────────
@@ -60,7 +60,7 @@ const ARG_KEYS = ['command', 'pattern', 'glob_pattern', 'path', 'target_director
export function cursorToolArg(args: unknown): string {
if (typeof args === 'string') return args.slice(0, CHAT_TOOL_ARG_MAX)
- if (!isObj(args)) return ''
+ if (!isRecord(args)) return ''
for (const k of ARG_KEYS) {
const v = args[k]
if (typeof v === 'string' && v) return v.slice(0, CHAT_TOOL_ARG_MAX)
@@ -72,7 +72,7 @@ export function cursorToolArg(args: unknown): string {
function resultText(p: Obj): string {
if (typeof p.result === 'string') return p.result
if (Array.isArray(p.experimental_content)) {
- return p.experimental_content.map((c) => (isObj(c) && typeof c.text === 'string' ? c.text : '')).filter(Boolean).join('\n')
+ return p.experimental_content.map((c) => (isRecord(c) && typeof c.text === 'string' ? c.text : '')).filter(Boolean).join('\n')
}
return p.result === undefined ? '' : JSON.stringify(p.result)
}
@@ -101,7 +101,7 @@ export function parseCursorChat(raw: readonly unknown[]): CursorChatParse {
let skipped = 0
let lastAssistant: Obj | undefined
for (const m of raw) {
- if (!isObj(m)) {
+ if (!isRecord(m)) {
skipped++
continue
}
@@ -113,7 +113,7 @@ export function parseCursorChat(raw: readonly unknown[]): CursorChatParse {
// A string user message is harness context, never typed. Typed text is a `<user_query>`.
const texts: ChatPart[] = []
for (const p of parts) {
- const t = isObj(p) && p.type === 'text' && typeof p.text === 'string' ? cursorUserText(p.text) : undefined
+ const t = isRecord(p) && p.type === 'text' && typeof p.text === 'string' ? cursorUserText(p.text) : undefined
if (t !== undefined) texts.push({ kind: 'text', text: t })
}
if (texts.length) messages.push({ role: 'user', parts: texts })
@@ -124,7 +124,7 @@ export function parseCursorChat(raw: readonly unknown[]): CursorChatParse {
const out: ChatPart[] = []
if (typeof m.content === 'string' && m.content.trim()) out.push({ kind: 'text', text: m.content })
for (const p of parts) {
- if (!isObj(p)) {
+ if (!isRecord(p)) {
skipped++
continue
}
@@ -143,7 +143,7 @@ export function parseCursorChat(raw: readonly unknown[]): CursorChatParse {
}
case 'tool':
for (const p of parts) {
- if (!isObj(p) || p.type !== 'tool-result') {
+ if (!isRecord(p) || p.type !== 'tool-result') {
skipped++
continue
}
@@ -160,8 +160,8 @@ export function parseCursorChat(raw: readonly unknown[]): CursorChatParse {
const out: CursorChatParse = { messages, skipped }
const modelOf = (a: Obj | undefined): string | undefined => {
for (const p of Array.isArray(a?.content) ? (a.content as unknown[]) : []) {
- const cur = isObj(p) && isObj(p.providerOptions) ? p.providerOptions.cursor : undefined
- const name = isObj(cur) ? metaString(cur.modelName) : undefined
+ const cur = isRecord(p) && isRecord(p.providerOptions) ? p.providerOptions.cursor : undefined
+ const name = isRecord(cur) ? metaString(cur.modelName) : undefined
if (name) return name
}
return undefined
@@ -349,7 +349,7 @@ export async function readCursorStore(dbPath: string, maxBytes: number = CURSOR_
db.exec('BEGIN')
const row = db.prepare("SELECT value FROM meta WHERE key = '0'").get() as { value?: string } | undefined
const meta: unknown = row?.value ? JSON.parse(Buffer.from(row.value, 'hex').toString('utf8')) : {}
- const m = isObj(meta) ? meta : {}
+ const m = isRecord(meta) ? meta : {}
const name = typeof m.name === 'string' ? m.name.trim() : ''
const store: CursorStore = { messages: [] }
if (name && name !== DEFAULT_TITLE) store.title = name.slice(0, 200)
@@ -397,13 +397,13 @@ export async function cursorTranscriptText(dbPath: string): Promise<string | nul
if (!s) return null
return s.messages
.map((m) => {
- if (!isObj(m)) return ''
+ if (!isRecord(m)) return ''
const { providerOptions: _p, ...rest } = m
if (Array.isArray(rest.content)) {
rest.content = rest.content
- .filter((c) => !(isObj(c) && (c.type === 'reasoning' || c.type === 'redacted-reasoning')))
+ .filter((c) => !(isRecord(c) && (c.type === 'reasoning' || c.type === 'redacted-reasoning')))
.map((c) => {
- if (!isObj(c)) return c
+ if (!isRecord(c)) return c
const { providerOptions: _q, experimental_content: _e, ...keep } = c
return keep
})
@@ -478,7 +478,7 @@ export function cursorContextParse(text: string | string[]): { used: number; win
for (let i = lines.length - 1; i >= 0; i--) {
try {
const o: unknown = JSON.parse(lines[i])
- if (isObj(o) && typeof o.used === 'number' && typeof o.max === 'number' && o.used > 0 && o.max > 0) {
+ if (isRecord(o) && typeof o.used === 'number' && typeof o.max === 'number' && o.used > 0 && o.max > 0) {
return { used: o.used, window: o.max, model: null }
}
} catch {
@@ -501,7 +501,7 @@ export async function trackCursorContext(
payload: unknown,
live: () => boolean = () => true
): Promise<string | undefined> {
- const p = isObj(payload) ? payload : {}
+ const p = isRecord(payload) ? payload : {}
const id = typeof p.conversation_id === 'string' ? p.conversation_id : typeof p.session_id === 'string' ? p.session_id : undefined
if (!id || tail.pathFor(id)) return id
const cwd = Array.isArray(p.workspace_roots) && typeof p.workspace_roots[0] === 'string' ? p.workspace_roots[0] : undefined
@@ -553,7 +553,7 @@ export function applyCursorRaw(
// The phone's "what it is doing now" line, remote nodes included (it needs no file). Translated to
// the claude-shaped names `recordRawToolEvent` gates on, as grok's branch does; a child's tool
// call is not the parent's activity.
- if (nodeId && isObj(payload)) {
+ if (nodeId && isRecord(payload)) {
const ev = payload.hook_event_name
if (ev === 'preToolUse' && typeof payload.tool_name === 'string' && !isCursorChildToolEvent(payload)) {
recordRawToolEvent(nodeId, { hook_event_name: 'PreToolUse', tool_name: payload.tool_name, tool_input: payload.tool_input })
diff --git a/src/core/cursor-subagents.ts b/src/core/cursor-subagents.ts
index 86c833d7a..f418a36b1 100644
--- a/src/core/cursor-subagents.ts
+++ b/src/core/cursor-subagents.ts
@@ -23,9 +23,8 @@ import { isCursorBackgroundEvent, isCursorChildToolEvent, type NormalizedAgentEv
import type { AgentId } from '../shared/agents/config'
import type { SubagentTail } from './subagent-tail'
import { CURSOR_CHAT_ID_RE, cursorConfigDir, cursorToolArg, cursorUserText } from './cursor-chat'
+import { isRecord } from '../shared/is-record'
-type Obj = Record<string, unknown>
-const isObj = (v: unknown): v is Obj => !!v && typeof v === 'object' && !Array.isArray(v)
const REDACTED = '[REDACTED]'
/** One chunk of a child's agent-transcript JSONL as card text. Stateless, fresh per card. */
@@ -39,14 +38,14 @@ export function createCursorSubagentFormatter(): (text: string) => string {
} catch {
continue
}
- if (!isObj(o)) continue
+ if (!isRecord(o)) continue
if (o.type === 'turn_ended') {
out.push(o.status === 'success' ? '✓ done' : `✗ ${typeof o.status === 'string' ? o.status : 'ended'}`)
continue
}
- const content = isObj(o.message) && Array.isArray(o.message.content) ? o.message.content : []
+ const content = isRecord(o.message) && Array.isArray(o.message.content) ? o.message.content : []
for (const c of content) {
- if (!isObj(c)) continue
+ if (!isRecord(c)) continue
if (c.type === 'text' && typeof c.text === 'string') {
const t = o.role === 'user' ? cursorUserText(c.text) : c.text.replaceAll(REDACTED, '').trim()
if (t) out.push(t)
@@ -92,7 +91,7 @@ export function createCursorSubagentTracker(deps: {
const nodes = new Map<string, NodeEntry>()
return {
onRaw(agentId, nodeId, payload) {
- if (!nodeId || !isObj(payload)) return
+ if (!nodeId || !isRecord(payload)) return
const ev = payload.hook_event_name
const conv = typeof payload.conversation_id === 'string' ? payload.conversation_id : undefined
const isTool = ev === 'preToolUse' || ev === 'postToolUse' || ev === 'postToolUseFailure'
diff --git a/src/core/fs-atomic.test.ts b/src/core/fs-atomic.test.ts
index 87ce9b4dd..1df9e5e61 100644
--- a/src/core/fs-atomic.test.ts
+++ b/src/core/fs-atomic.test.ts
@@ -14,6 +14,7 @@ import {
renameAtomic,
renameAtomicSync,
STALE_TEMP_AGE_MS,
+ sweepForeignTempFiles,
sweepStaleTempFiles,
tempNameFor,
writeFileAtomic
@@ -367,6 +368,40 @@ describe('unique temp names and abandoned-temp collection', () => {
})
})
+describe('sweepForeignTempFiles (credential stores)', () => {
+ it('removes the legacy temp and every foreign PID shape at once, with no age grace', async () => {
+ const target = join(dir, 'token.json')
+ const legacy = `${target}.tmp`
+ const priorPidShape = `${target}.1111.1.tmp`
+ const current = `${target}.2222.2.22222222-2222-4222-8222-222222222222.tmp`
+ const ours = `${target}.${process.pid}.3.33333333-3333-4333-8333-333333333333.tmp`
+ const oursPrior = `${target}.${process.pid}.4.tmp`
+ const unknown = `${target}.not-an-owner.tmp`
+ const unrelated = join(dir, 'other-fil!.tmp') // same basename length as token.json
+ const lookalike = join(dir, 'token.json.bak.1111.1.tmp')
+ await Promise.all(
+ [target, legacy, priorPidShape, current, ours, oursPrior, unknown, unrelated, lookalike].map((file) =>
+ fs.writeFile(file, file)
+ )
+ )
+
+ await sweepForeignTempFiles(target)
+
+ expect((await fs.readdir(dir)).sort()).toEqual([
+ 'other-fil!.tmp',
+ 'token.json',
+ `token.json.${process.pid}.3.33333333-3333-4333-8333-333333333333.tmp`,
+ `token.json.${process.pid}.4.tmp`,
+ 'token.json.bak.1111.1.tmp',
+ 'token.json.not-an-owner.tmp'
+ ].sort())
+ })
+
+ it('resolves quietly when the directory cannot be read', async () => {
+ await expect(sweepForeignTempFiles(join(dir, 'missing', 'token.json'))).resolves.toBeUndefined()
+ })
+})
+
describe('clearAtomicTarget', () => {
it('removes the canonical file but reports a young current temp as retained', async () => {
const target = join(dir, 'secret.json')
diff --git a/src/core/fs-atomic.ts b/src/core/fs-atomic.ts
index 5e176efce..fbb353b15 100644
--- a/src/core/fs-atomic.ts
+++ b/src/core/fs-atomic.ts
@@ -49,6 +49,7 @@
import { promises as fs, renameSync } from 'fs'
import { randomUUID } from 'crypto'
import path from 'path'
+import { sleep } from '../shared/sleep'
/**
* Errors that mean "someone else has the destination open right now", rather than "this will
@@ -69,8 +70,6 @@ function codeOf(e: unknown): string {
return typeof e === 'object' && e && 'code' in e ? String((e as { code: unknown }).code) : ''
}
-const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
-
/**
* Rename `tmp` over `target`, retrying briefly if the destination is momentarily held open.
*
@@ -173,6 +172,8 @@ function atomicTempCandidate(base: string, entry: string): AtomicTempCandidate |
* Unknown temp-name shapes are left alone. Every current writer removes its own temp on failure;
* this sweep exists only for process death and must never recreate the writer-vs-sweeper race that
* unique names fixed.
+ *
+ * A store whose orphaned temp would be a live credential uses `sweepForeignTempFiles` instead.
*/
export async function sweepStaleTempFiles(
target: string,
@@ -204,6 +205,37 @@ export async function sweepStaleTempFiles(
}
}
+/**
+ * The AGGRESSIVE sibling of `sweepStaleTempFiles`, for a target whose orphaned temp is a live
+ * credential (a token, a cookie, a device bearer). With no age grace it removes the legacy fixed
+ * `<target>.tmp` and every pid-bearing temp whose pid is not this process's. Temps bearing our own
+ * pid stay: one may be a concurrent write sitting between its `writeFile` and its `rename`.
+ *
+ * This deliberately gives up what `sweepStaleTempFiles` protects. A foreign pid can be a second
+ * LIVE process on the same directory (desktop multi-instance, two servers on one `--data-dir`, the
+ * host agent on ~/.nodeterm), and deleting its temp makes that process's rename fail with ENOENT,
+ * rethrown to its caller. The callers accept that trade because the alternative is worse for
+ * them: a unique temp name is never written twice, so an orphan holding a secret would otherwise
+ * sit on disk at 0600 forever.
+ *
+ * It recognizes exactly the shapes `atomicTempCandidate` does, so a change to `tempNameFor`
+ * reaches both sweeps. This rule used to be re-typed at five call sites, each with its own copy of
+ * the temp-name regex. Best effort: an unreadable directory never fails the caller's save.
+ */
+export async function sweepForeignTempFiles(target: string): Promise<void> {
+ try {
+ const directory = path.dirname(target)
+ const base = path.basename(target)
+ for (const entry of await fs.readdir(directory)) {
+ const candidate = atomicTempCandidate(base, entry)
+ if (!candidate || candidate.ownerPid === process.pid) continue
+ await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)
+ }
+ } catch {
+ // A directory we cannot read is not a reason to fail (or skip) the save that requested it.
+ }
+}
+
/**
* Delete `target`, retrying the same transient Windows codes, and treating "already gone" as
* success. Returns false if it is still there afterwards.
diff --git a/src/core/gemini-chat.ts b/src/core/gemini-chat.ts
index d17e5ece3..61aa5ab97 100644
--- a/src/core/gemini-chat.ts
+++ b/src/core/gemini-chat.ts
@@ -36,6 +36,7 @@ import type { ChatTranscriptPage } from '../shared/chat-page'
import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
import { locateGemini } from './handoff/locate'
import { readCappedTail } from './transcript-reader'
+import { isRecord } from '../shared/is-record'
/** Same caps as claude's reader (`summarizeResult` / `metaString` in transcript-reader.ts), in
* UTF-16 code units — kept equal so the three readers' parts look alike. */
@@ -66,7 +67,6 @@ export interface GeminiChat {
skipped: number
}
-const isObj = (v: unknown): v is Rec => !!v && typeof v === 'object' && !Array.isArray(v)
const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined)
function isHarnessText(t: string): boolean {
@@ -81,7 +81,7 @@ function visibleTexts(content: unknown): string[] {
if (typeof content === 'string') raw.push(content)
else if (Array.isArray(content)) {
for (const p of content) {
- if (!isObj(p) || p.thought === true) continue
+ if (!isRecord(p) || p.thought === true) continue
const t = str(p.text)
if (t !== undefined) raw.push(t)
}
@@ -95,14 +95,14 @@ function summarize(s: string): string {
/** What the model was given back: `functionResponse.response.output`, else its `error`. */
function responseText(part: unknown): string | undefined {
- const fr = isObj(part) && isObj(part.functionResponse) ? part.functionResponse : undefined
- const resp = fr && isObj(fr.response) ? fr.response : undefined
+ const fr = isRecord(part) && isRecord(part.functionResponse) ? part.functionResponse : undefined
+ const resp = fr && isRecord(fr.response) ? fr.response : undefined
if (!resp) return undefined
return str(resp.output) ?? str(resp.error)
}
function toolArg(args: unknown, description: unknown): string {
- if (isObj(args)) {
+ if (isRecord(args)) {
for (const k of ARG_KEYS) {
const v = str(args[k])
if (v) return v.slice(0, CHAT_TOOL_ARG_MAX)
@@ -142,7 +142,7 @@ function foldRecords(buf: string): { log: Map<string, Rec>; skipped: number } {
const log = new Map<string, Rec>()
let skipped = 0
const upsert = (m: unknown): void => {
- if (isObj(m) && typeof m.id === 'string') log.set(m.id, m)
+ if (isRecord(m) && typeof m.id === 'string') log.set(m.id, m)
}
for (const line of buf.split('\n')) {
if (!line.trim()) continue
@@ -153,7 +153,7 @@ function foldRecords(buf: string): { log: Map<string, Rec>; skipped: number } {
skipped++
continue
}
- if (!isObj(o)) {
+ if (!isRecord(o)) {
skipped++
continue
}
@@ -172,7 +172,7 @@ function foldRecords(buf: string): { log: Map<string, Rec>; skipped: number } {
}
} else if (typeof o.id === 'string') {
upsert(o)
- } else if (isObj(o.$set)) {
+ } else if (isRecord(o.$set)) {
// Metadata; `$set.messages` is the model's context, not the thread (see the file comment).
} else if (typeof o.sessionId === 'string' && typeof o.projectHash === 'string') {
if (Array.isArray(o.messages)) for (const m of o.messages) upsert(m)
@@ -213,7 +213,7 @@ export function chatFromGemini(buf: string): GeminiChat {
case 'user': {
if (Array.isArray(rec.content)) {
for (const p of rec.content) {
- if (!isObj(p) || !isObj(p.functionResponse)) continue
+ if (!isRecord(p) || !isRecord(p.functionResponse)) continue
const id = str(p.functionResponse.id)
const tool = id ? toolById.get(id) : undefined
const out = responseText(p)
@@ -233,7 +233,7 @@ export function chatFromGemini(buf: string): GeminiChat {
const calls = Array.isArray(rec.toolCalls) ? rec.toolCalls : []
if (calls.length) {
for (const c of calls) {
- if (!isObj(c)) {
+ if (!isRecord(c)) {
skipped++
continue
}
@@ -244,7 +244,7 @@ export function chatFromGemini(buf: string): GeminiChat {
}
} else if (Array.isArray(rec.content)) {
for (const p of rec.content) {
- if (!isObj(p) || !isObj(p.functionCall)) continue
+ if (!isRecord(p) || !isRecord(p.functionCall)) continue
const fc = p.functionCall
const part: ToolPart = { kind: 'tool', name: str(fc.name) || 'tool', arg: toolArg(fc.args, undefined) }
parts.push(part)
diff --git a/src/core/launch-intent-execute.ts b/src/core/launch-intent-execute.ts
index 1084a55fb..b940d390a 100644
--- a/src/core/launch-intent-execute.ts
+++ b/src/core/launch-intent-execute.ts
@@ -34,6 +34,7 @@ import {
type AgentLaunchExecutableResolution,
type PreparedAgentLaunch
} from './agent-launch'
+import { isRecord } from '../shared/is-record'
/** The Windows-native dialects this channel encodes for. POSIX shells keep their legacy line. */
export type WindowsLaunchDialect = Exclude<SessionHostShellDialect, 'posix'>
@@ -174,10 +175,6 @@ function refuse(reason: LaunchIntentFailureReason): LaunchIntentExecutionResult
return { ok: false, reason, message: MESSAGES[reason] }
}
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === 'object' && value !== null && !Array.isArray(value)
-}
-
/**
* A prompt file's text as ONE argv element. Whitespace runs collapse to a single space: the
* planner refuses control characters (a newline is a command boundary to every Windows parser),
diff --git a/src/core/opencode-chat.ts b/src/core/opencode-chat.ts
index 9698856e4..8ca1cd08f 100644
--- a/src/core/opencode-chat.ts
+++ b/src/core/opencode-chat.ts
@@ -36,6 +36,7 @@ import { CHAT_TOOL_ARG_MAX } from '../shared/chat-command'
import { CHAT_PAGE_MAX_BYTES, type ChatTranscriptPage } from '../shared/chat-page'
import { findInLoginPath } from './exec-path'
import { isSafeOpencodeSessionId, runOpencodeExportAt, type OpencodeExportOutcome } from './opencode-export'
+import { isRecord } from '../shared/is-record'
/** Same bounds as claude's reader (`summarizeResult` / `metaString`). */
const TOOL_RESULT_LINES = 3
@@ -55,8 +56,6 @@ export interface OpencodeChatParse {
effort?: string
}
-const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
-
function metaString(v: unknown): string | undefined {
return typeof v === 'string' && v.length > 0 && v.length <= CHAT_META_MAX_CHARS ? v : undefined
}
@@ -75,14 +74,14 @@ function summarize(text: string): string {
*/
export function opencodeToolArg(input: unknown, title?: unknown): string {
let v: unknown
- if (isObj(input)) {
+ if (isRecord(input)) {
for (const k of ['command', 'filePath', 'file_path', 'pattern', 'path', 'url', 'query', 'description', 'prompt', 'name']) {
if (typeof input[k] === 'string') {
v = input[k]
break
}
}
- if (v === undefined && Array.isArray(input.questions) && isObj(input.questions[0])) {
+ if (v === undefined && Array.isArray(input.questions) && isRecord(input.questions[0])) {
const q = input.questions[0].question
if (typeof q === 'string') v = q
}
@@ -94,7 +93,7 @@ export function opencodeToolArg(input: unknown, title?: unknown): string {
/** A tool part's chip. `null` = not a mappable tool part. */
function toolPart(p: Record<string, unknown>): ToolPart | null {
const state = p.state
- if (!isObj(state)) return null
+ if (!isRecord(state)) return null
const part: ToolPart = {
kind: 'tool',
name: typeof p.tool === 'string' && p.tool ? p.tool : 'tool',
@@ -114,9 +113,9 @@ function toolPart(p: Record<string, unknown>): ToolPart | null {
/** The sentence an errored assistant message ends with. `null` = malformed (counted as skipped). */
function errorText(e: unknown): string | null {
- if (!isObj(e)) return null
+ if (!isRecord(e)) return null
const name = typeof e.name === 'string' && e.name ? e.name : 'Error'
- const message = isObj(e.data) && typeof e.data.message === 'string' ? e.data.message.trim() : ''
+ const message = isRecord(e.data) && typeof e.data.message === 'string' ? e.data.message.trim() : ''
return message ? `[${name}] ${message}` : `[${name}]`
}
@@ -138,14 +137,14 @@ export function parseOpencodeExport(raw: string, sessionId: string): OpencodeCha
} catch {
return null
}
- if (!isObj(doc) || !isObj(doc.info) || doc.info.id !== sessionId) return null
+ if (!isRecord(doc) || !isRecord(doc.info) || doc.info.id !== sessionId) return null
const messages: ChatMessage[] = []
let skipped = 0
let lastAssistant: Record<string, unknown> | undefined
const entries = Array.isArray(doc.messages) ? doc.messages : []
for (const entry of entries) {
- if (!isObj(entry) || !isObj(entry.info)) {
+ if (!isRecord(entry) || !isRecord(entry.info)) {
skipped++
continue
}
@@ -160,7 +159,7 @@ export function parseOpencodeExport(raw: string, sessionId: string): OpencodeCha
skipped++
continue
}
- const created = isObj(info.time) ? info.time.created : undefined
+ const created = isRecord(info.time) ? info.time.created : undefined
const at = typeof created === 'number' && Number.isFinite(created) ? created : undefined
const stamp = (m: ChatMessage): ChatMessage => (at === undefined ? m : { ...m, at })
@@ -169,7 +168,7 @@ export function parseOpencodeExport(raw: string, sessionId: string): OpencodeCha
const own: ChatPart[] = []
const chips: ChatPart[] = []
for (const p of entry.parts) {
- if (!isObj(p) || typeof p.type !== 'string') {
+ if (!isRecord(p) || typeof p.type !== 'string') {
skipped++
continue
}
diff --git a/src/core/recent-conversations.ts b/src/core/recent-conversations.ts
index 22d856276..78449d68f 100644
--- a/src/core/recent-conversations.ts
+++ b/src/core/recent-conversations.ts
@@ -51,6 +51,7 @@ import { chatMessagesFromCopilot, COPILOT_EVENTS_FILE, copilotSessionStateRoots
import { chatFromAntigravity } from './antigravity-chat'
import { ANTIGRAVITY_SESSION_ID_RE } from './handoff/locate'
import { untrustedLine } from './github/control-read'
+import { isRecord } from '../shared/is-record'
/** Candidates opened per root (newest by mtime). A root with thousands of old transcripts costs a
* directory listing and a stat each, never a read. */
@@ -227,9 +228,6 @@ function parseJson(line: string): Record<string, unknown> | null {
}
}
-const isObj = (v: unknown): v is Record<string, unknown> =>
- !!v && typeof v === 'object' && !Array.isArray(v)
-
/** An absolute directory string, or null. A history file is input we did not write. */
export function safeCwd(v: unknown): string | null {
if (typeof v !== 'string') return null
@@ -296,13 +294,13 @@ async function parseClaude(c: Candidate): Promise<Parsed> {
async function parseCodex(c: Candidate): Promise<Parsed> {
const lines = await headLines(c)
const meta = lines.length ? parseJson(lines[0]) : null
- if (!meta || meta.type !== 'session_meta' || !isObj(meta.payload)) return null
+ if (!meta || meta.type !== 'session_meta' || !isRecord(meta.payload)) return null
const p = meta.payload
const id = p.id
if (typeof id !== 'string' || !CODEX_THREAD_ID_RE.test(id) || !validId(id)) return null
// MEASURED (codex 0.156): a spawned child rollout carries `thread_source: "subagent"` and a
// `source: {subagent: …}` object; a user's own thread says `thread_source: "user"`.
- if (p.thread_source === 'subagent' || isObj(p.source)) return null
+ if (p.thread_source === 'subagent' || isRecord(p.source)) return null
const prompt = firstPrompt(chatMessagesFromCodex(lines.join('\n')))
const t = titled(null, prompt)
if (t.titleSource === 'none') return null
@@ -336,10 +334,10 @@ async function parseGrok(c: Candidate, sessionId: string, cwd: string | null): P
async function parseCopilot(c: Candidate, dirId: string): Promise<Parsed> {
const lines = await headLines(c)
const start = lines.map(parseJson).find((o) => o?.type === 'session.start')
- const data = start && isObj(start.data) ? start.data : null
+ const data = start && isRecord(start.data) ? start.data : null
// The journal's own id must name the directory it sits in — a copied journal is not this session.
if (!data || data.sessionId !== dirId || !validId(dirId)) return null
- const cwd = isObj(data.context) ? safeCwd(data.context.cwd) : null
+ const cwd = isRecord(data.context) ? safeCwd(data.context.cwd) : null
const prompt = firstPrompt(chatMessagesFromCopilot(lines.join('\n')))
const t = titled(null, prompt)
if (t.titleSource === 'none') return null
@@ -623,7 +621,7 @@ export function listRecentConversationsReused(
/** Sanitize a request that arrived over IPC / the WS bridge. */
export function normalizeRecentRequest(raw: unknown): RecentConversationsRequest {
- if (!isObj(raw)) return {}
+ if (!isRecord(raw)) return {}
const ids = Array.isArray(raw.codexAccountIds)
? raw.codexAccountIds.filter((x): x is string => typeof x === 'string').slice(0, MAX_CODEX_ACCOUNTS)
: undefined
diff --git a/src/core/relay/hosted-scheduler.ts b/src/core/relay/hosted-scheduler.ts
index ea709776f..4764c76c3 100644
--- a/src/core/relay/hosted-scheduler.ts
+++ b/src/core/relay/hosted-scheduler.ts
@@ -29,6 +29,7 @@
// in 'running' with no listener and no timer, i.e. hosting silently dead until a restart.
import type { MintResult } from './host-token'
import { POP_REFUSED_MESSAGE, type PopRefusal } from './relay-pop'
+import { errorText } from '../../shared/error-text'
export type { MintResult } from './host-token'
const REFRESH_LEAD_MS = 30_000
@@ -85,7 +86,6 @@ interface Entry {
}
const clampDelay = (ms: number): number => Math.min(MAX_DELAY_MS, ms)
-const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
export function createHostedScheduler(deps: SchedulerDeps, now: () => number) {
if (deps.maxBridged !== undefined && !(Number.isInteger(deps.maxBridged) && deps.maxBridged >= 1)) {
diff --git a/src/core/remote-ssh/share-team-remote.ts b/src/core/remote-ssh/share-team-remote.ts
index c420b56f7..967c2b67a 100644
--- a/src/core/remote-ssh/share-team-remote.ts
+++ b/src/core/remote-ssh/share-team-remote.ts
@@ -21,6 +21,7 @@ import { isSafeNodeId } from '../../shared/safe-id'
import { RMT_TMUX_SOCKET } from './control-master'
import { sessionName } from '../tmux-naming'
import { CONTROL_RE } from '../relay/team-admin'
+import { isRecord } from '../../shared/is-record'
export const SERVER_INSTALL_URL = 'https://raw.githubusercontent.com/eneskirca/nodeterm/main/scripts/install-server.sh'
/** Where a root-installed nodeterm-server's unit lives (the installer's system mode). */
@@ -147,7 +148,6 @@ const parseJson = (text: string): unknown => {
return undefined
}
}
-const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
/** Read `shareProbeCommand`'s reply. Login noise before `##NTP 1` is skipped; a reply that never
* reaches `##END` (a dropped channel, a timeout) is an error, never a half-filled probe that
diff --git a/src/core/session-host-client.ts b/src/core/session-host-client.ts
index 8b79f809e..98659ed57 100644
--- a/src/core/session-host-client.ts
+++ b/src/core/session-host-client.ts
@@ -52,6 +52,7 @@ import { latestClaimSize, type SizeClaim } from './pty-size'
import { isTerminalReport } from './terminal-reports'
import type { PreparedAgentLaunch } from './agent-launch'
import type { HostImageStaging } from './session-host-runtime'
+import { sleep } from '../shared/sleep'
export interface SessionSubscriber {
onData(data: string): void
@@ -270,10 +271,6 @@ type ClientSessionState = {
appliedWatch?: boolean
}
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms))
-}
-
function asError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error))
}
diff --git a/src/core/usage/provider-cookie.ts b/src/core/usage/provider-cookie.ts
index 21bc960c2..90c2e895f 100644
--- a/src/core/usage/provider-cookie.ts
+++ b/src/core/usage/provider-cookie.ts
@@ -16,7 +16,7 @@
// still found.
import { promises as fs } from 'fs'
import path from 'path'
-import { renameAtomic, tempNameFor } from '../fs-atomic'
+import { renameAtomic, sweepForeignTempFiles, tempNameFor } from '../fs-atomic'
import { platform } from '../platform'
/** Owner read/write only. The whole reason these are separate files. */
@@ -45,36 +45,6 @@ export async function readProviderCookie(provider: CookieProvider): Promise<stri
}
}
-/**
- * Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by
- * builds before per-call names) and any `<file>.<pid>.<seq>[.<uuid>].tmp` whose pid is not ours.
- * Best effort — a failure here must never break a save.
- *
- * Unlike settings.json, an orphan here is a live credential at 0600 that nothing will ever
- * overwrite, so it has to be collected rather than left. Temps bearing our own pid are untouchable:
- * one may belong to a concurrent write sitting between its `writeFile` and its `rename`, and
- * deleting it would recreate the exact race the unique names fixed. A foreign pid can in theory be
- * a second LIVE process on the same data dir; that setup has no lock to begin with, and the worst
- * case is that process's rename failing cleanly (ENOENT, rethrown to its caller) instead of a
- * forgotten cookie sitting on disk forever.
- */
-async function sweepStaleTmp(target: string): Promise<void> {
- try {
- const dir = path.dirname(target)
- const base = path.basename(target)
- for (const entry of await fs.readdir(dir)) {
- if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
- const owner = /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/.exec(middle)?.[1]
- if (middle === '' || (owner && owner !== String(process.pid))) {
- await fs.rm(path.join(dir, entry), { force: true }).catch(() => undefined)
- }
- }
- } catch {
- // A dir we cannot read is not a reason to fail (or skip) the write below.
- }
-}
-
/**
* Store (or, with an empty value, clear) a provider's cookie. Written to a temp file first and
* renamed, so a crash mid-write cannot leave a half-written credential behind — and the temp
@@ -102,7 +72,7 @@ const writeChains = new Map<CookieProvider, Promise<unknown>>()
async function writeCookieNow(provider: CookieProvider, cookie: string): Promise<void> {
const target = file(provider)
// Both paths sweep: clearing a cookie that leaves an orphan temp behind has not cleared anything.
- await sweepStaleTmp(target)
+ await sweepForeignTempFiles(target)
if (!cookie.trim()) {
await fs.rm(target, { force: true })
return
diff --git a/src/core/watch-link/link-host.ts b/src/core/watch-link/link-host.ts
index 5a4d5cd55..faecb520c 100644
--- a/src/core/watch-link/link-host.ts
+++ b/src/core/watch-link/link-host.ts
@@ -174,6 +174,7 @@ import {
wrapWatcherSink
} from './watcher-policy'
import { CONTROL_WRONG_MAX, type WatchLinkRecord } from './store'
+import { errorText } from '../../shared/error-text'
export const MAX_VIEWERS_PER_LINK = 10
/** While the link is full (no idle listener, so no mint), how often the API is asked whether the link
@@ -412,7 +413,6 @@ interface CaptureSlot {
next: { result: Promise<VisibleCapture>; start(): void } | null
}
-const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
/** The same members, in any order (the typing set is a set: a new order alone is no news). */
function sameMembers(a: string[], b: string[]): boolean {
if (a.length !== b.length) return false
diff --git a/src/core/watch-link/service.ts b/src/core/watch-link/service.ts
index 017fec684..8fc941b74 100644
--- a/src/core/watch-link/service.ts
+++ b/src/core/watch-link/service.ts
@@ -98,6 +98,7 @@ import {
type WatchLinkStore
} from './store'
import type { RelayTransport } from '../relay/relay-socket'
+import { errorText } from '../../shared/error-text'
/** setTimeout's own ceiling (a longer delay fires at once). A link lives ≤ 24 h, far below it. */
const MAX_DELAY_MS = 2_147_483_647
@@ -287,7 +288,6 @@ export function sendToOwners(
for (const id of p.clientIds()) if (p.isOwnerClient?.(id) === true) p.sendTo(id, channel, ...args)
}
-const errorText = (err: unknown): string => (err instanceof Error ? err.message : String(err))
/** An error's NAME only: what failed around a password (its hash, its check) may be in the message. */
const errorName = (err: unknown): string => (err instanceof Error ? err.name : 'not an Error')
const TIMEOUT = Symbol('timeout')
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index 1c5e2af8c..2afa42daa 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -22,6 +22,7 @@ import {
type CanvasLayout,
type LayoutViewports
} from '../shared/canvas-layout'
+import { isRecord } from '../shared/is-record'
/**
* Drop a browser node's persisted `partition` unless it is exactly the jar THIS project (its
@@ -415,9 +416,6 @@ export function validKanban(k: unknown): k is ProjectKanban {
)
}
-const isRecord = (x: unknown): x is Record<string, unknown> =>
- !!x && typeof x === 'object' && !Array.isArray(x)
-
/**
* A project's `bridges` / `ropes` as they may be ADMITTED. Both come straight out of the git-shared,
* hand-editable project file, and every reader treats them as `BridgeLink[]`: the canvas restores
diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.ts
index 4aadd7751..1c86f2ce5 100644
--- a/src/core/workspace-store.ts
+++ b/src/core/workspace-store.ts
@@ -2,7 +2,7 @@ import type { SshConnection } from '../shared/ssh'
import { promises as fs } from 'fs'
import { createHash, randomUUID } from 'node:crypto'
import path from 'path'
-import { renameAtomic, writeFileAtomic } from './fs-atomic'
+import { renameAtomic, sweepForeignTempFiles, writeFileAtomic } from './fs-atomic'
import { IPC } from '../shared/ipc'
import { platform } from './platform'
import {
@@ -229,26 +229,6 @@ export async function writeAtomic(filePath: string, content: string): Promise<vo
await writeFileAtomic(filePath, content)
}
-/** Remove tmp litter next to `target` left by writers that died mid-write: the legacy fixed
- * `<file>.tmp` name and any `<file>.<pid>.<seq>[.<uuid>].tmp` from another (dead) pid. Our own
- * pid's temps are in-flight writes and stay. Same family rule as provider-cookie's sweep. */
-async function sweepStaleTmp(target: string): Promise<void> {
- try {
- const dir = path.dirname(target)
- const base = path.basename(target)
- for (const entry of await fs.readdir(dir)) {
- if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
- const owner = /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/.exec(middle)?.[1]
- if (middle === '' || (owner && owner !== String(process.pid))) {
- await fs.rm(path.join(dir, entry), { force: true }).catch(() => undefined)
- }
- }
- } catch {
- // A dir we cannot read is not a reason to fail the load.
- }
-}
-
/**
* Whether `real` (already a real path) is the filesystem root, the real home directory, or a folder
* that contains it. A shared folder is readable by every teammate, Viewers included, and a home
@@ -468,7 +448,7 @@ export class WorkspaceStore {
private async loadInner(sideline: boolean): Promise<Workspace> {
// Read-only loads (sideline: false — the relay blob path) must not mutate the disk, so the
// litter sweep rides the same flag as the corrupt-file sideline.
- if (sideline) await sweepStaleTmp(this.indexPath)
+ if (sideline) await sweepForeignTempFiles(this.indexPath)
let raw: string
try {
raw = await fs.readFile(this.indexPath, 'utf-8')
@@ -608,7 +588,7 @@ export class WorkspaceStore {
}
})
} else if (e.cwd) {
- if (sideline) await sweepStaleTmp(projectFilePath(e.cwd))
+ if (sideline) await sweepForeignTempFiles(projectFilePath(e.cwd))
const read = await this.readProjectFile(e.cwd, sideline)
if (read) {
const p = read.file
@@ -1135,7 +1115,7 @@ export class WorkspaceStore {
private async loadDataFileEntry(e: IndexEntryV3, sideline: boolean): Promise<LoadedEntry | null> {
if (!isInlineProjectFileId(e.id)) return null
const file = inlineFilePath(e.id)
- if (sideline) await sweepStaleTmp(file)
+ if (sideline) await sweepForeignTempFiles(file)
const read = await this.readDataFile(e.id, sideline)
if (!read) return null
this.revs.set(e.id, read.file.rev)
diff --git a/src/core/zellij-backend.ts b/src/core/zellij-backend.ts
index e156f81f4..f619f9448 100644
--- a/src/core/zellij-backend.ts
+++ b/src/core/zellij-backend.ts
@@ -21,6 +21,7 @@
* the session by name, the way the tmux paths use `has-session` / `capture-pane`.
*/
import type { TextDeliveryResult } from '../shared/text-delivery'
+import { sleep } from '../shared/sleep'
/** `(args) → stdout/stderr`, rejecting on a non-zero exit with `stdout`/`stderr` on the error —
* i.e. promisified `execFile`'s contract, already bound to the zellij binary and its env. */
@@ -224,8 +225,6 @@ export async function zellijSessionState(run: ZellijRun, name: string): Promise<
export const ZOMBIE_CONFIRM_READS = 5
export const ZOMBIE_CONFIRM_GAP_MS = 300
-const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))
-
/** Resolve the target pane, or null. */
async function paneOf(run: ZellijRun, name: string): Promise<string | null> {
try {
diff --git a/src/main/browser-cdp-allowlist.ts b/src/main/browser-cdp-allowlist.ts
index f9d189602..ebdd6e0d8 100644
--- a/src/main/browser-cdp-allowlist.ts
+++ b/src/main/browser-cdp-allowlist.ts
@@ -26,6 +26,7 @@
import { isNtScript } from './browser-nt-scripts'
import { normalizeAddress } from '@shared/browserUrl'
import { BROWSER_KEYS } from '../core/browser-verb'
+import { isRecord } from '../shared/is-record'
/** What the gate needs to know about the page beyond the command itself: the viewport from the last
* `Page.getLayoutMetrics`, so a mouse coordinate can be bounded to what is actually on screen. */
@@ -35,10 +36,6 @@ export interface CdpContext {
type Validator = (params: unknown, ctx: CdpContext) => boolean
-function isRecord(v: unknown): v is Record<string, unknown> {
- return typeof v === 'object' && v !== null && !Array.isArray(v)
-}
-
/** A CDP argument for the call-a-function-on-object method is safe ONLY if it carries a single scalar
* `value` — never an `objectId` (an agent-chosen live handle) and never a structured value (an
* object literal is a re-entry point for logic the NT_SCRIPTS scan never saw). */
diff --git a/src/main/github-control.ts b/src/main/github-control.ts
index 1405a5f07..98a1fa8d3 100644
--- a/src/main/github-control.ts
+++ b/src/main/github-control.ts
@@ -1,6 +1,6 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
-import { renameAtomic, tempNameFor } from '../core/fs-atomic'
+import { renameAtomic, sweepForeignTempFiles, tempNameFor } from '../core/fs-atomic'
import type { GitHubSecretStore } from '../core/github/credentials'
import type { SecretStore } from '../core/secret-store'
import type { GitHubSecretAvailability } from '../shared/github-issues'
@@ -30,41 +30,9 @@ function validToken(token: string): boolean {
return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)
}
-/**
- * Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by
- * builds before per-call names) and any `<file>.<pid>.<seq>[.<uuid>].tmp` whose pid is not ours.
- * Best effort — a failure here must never break a save.
- *
- * The token file is not config: an orphan here is a live PAT at 0600 that nothing will ever
- * overwrite, because a unique name is never written twice. So it has to be collected rather than
- * left. Temps bearing our own pid are untouchable: one may belong to a concurrent write sitting
- * between its `writeFile` and its `rename`, and deleting it would recreate the exact race the
- * unique names fixed. A foreign pid can in theory be a second LIVE process on the same dir; that
- * setup has no lock to begin with, and the worst case is that process's rename failing cleanly
- * (ENOENT, rethrown to its caller) instead of a forgotten PAT sitting on disk forever.
- */
-async function sweepStaleTmp(target: string): Promise<void> {
- try {
- const directory = path.dirname(target)
- const base = path.basename(target)
- for (const entry of await fs.readdir(directory)) {
- if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
- const owner =
- /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/
- .exec(middle)?.[1]
- if (middle === '' || (owner && owner !== String(process.pid))) {
- await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)
- }
- }
- } catch {
- // A dir we cannot read is not a reason to fail (or skip) the write below.
- }
-}
-
async function atomicWrite(file: string, document: TokenDocument): Promise<void> {
await fs.mkdir(path.dirname(file), { recursive: true })
- await sweepStaleTmp(file)
+ await sweepForeignTempFiles(file)
// The store's per-instance chain orders this write against its sibling mutations; the per-call
// temp name covers the writers the chain cannot see — a second app process on the same
// userDataDir (every process's counter starts at 0, hence the pid) and a crash between
@@ -138,7 +106,7 @@ export class ElectronSecretStore implements SecretStore {
clear(): Promise<void> {
return this.chained(async () => {
// Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.
- await sweepStaleTmp(this.filePath)
+ await sweepForeignTempFiles(this.filePath)
await fs.rm(this.filePath, { force: true })
})
}
diff --git a/src/main/handoff/render-cursor.ts b/src/main/handoff/render-cursor.ts
index a2f0f63ef..0cd6cc708 100644
--- a/src/main/handoff/render-cursor.ts
+++ b/src/main/handoff/render-cursor.ts
@@ -5,15 +5,14 @@
// (rules, skills, environment), never something the human said, so it is left out; so is reasoning.
import { cursorUserText, parseCursorNdjson } from '../../core/cursor-chat'
import { blockText, fenceJson } from './format'
-
-const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v)
+import { isRecord } from '../../shared/is-record'
export function renderCursorTranscript(raw: string): string {
const out: string[] = []
for (const m of parseCursorNdjson(raw)) {
- if (!isObj(m) || !Array.isArray(m.content)) continue
+ if (!isRecord(m) || !Array.isArray(m.content)) continue
for (const c of m.content as unknown[]) {
- if (!isObj(c)) continue
+ if (!isRecord(c)) continue
if (m.role === 'user' && c.type === 'text' && typeof c.text === 'string') {
const t = cursorUserText(c.text)
if (t !== undefined) out.push(`## User\n\n${t}`)
diff --git a/src/main/pairing-service.ts b/src/main/pairing-service.ts
index ebdf88fa3..cb6b016a0 100644
--- a/src/main/pairing-service.ts
+++ b/src/main/pairing-service.ts
@@ -40,7 +40,7 @@ import {
type RelayPairingBlock
} from './pairing-core'
import type { DeviceRevokeResult, DeviceRevokeServerOutcome, Settings } from '../shared/types'
-import { renameAtomic, tempNameFor } from '../core/fs-atomic'
+import { renameAtomic, sweepForeignTempFiles, tempNameFor } from '../core/fs-atomic'
import { publicKeyToB64, deriveSharedKey, encrypt, decrypt, type KeyPair } from './remote/e2ee'
import { hostIdFromPublicKeyB64 } from './remote/relay-id'
import { getDeviceId } from '../core/device-id'
@@ -271,39 +271,6 @@ async function readAgentJson(): Promise<Record<string, unknown>> {
}
}
-/**
- * Remove agent.json temps no writer in THIS process owns: the legacy fixed `agent.json.tmp`
- * (written by builds from before per-call names) and any `agent.json.<pid>.<seq>[.<uuid>].tmp`
- * whose pid is not ours. Best effort — a failure here must never break (or skip) the write that
- * follows.
- *
- * agent.json is not config: every device entry carries the `agentToken` bearer the phone presents
- * on the host-agent WebSocket, so an orphan is a live credential at 0600 that nothing will ever
- * overwrite — a unique name is never written twice. Temps bearing our own pid are untouchable: one
- * may belong to a concurrent write sitting between its `writeFile` and its `rename`, and deleting
- * it would recreate the exact race the unique names fixed. A foreign pid can in theory be the HOST
- * AGENT mid-write; ~/.nodeterm is shared with it and has no lock to begin with, and the worst case
- * is that process's rename failing cleanly (ENOENT, rethrown to its caller) instead of a forgotten
- * token file sitting on disk forever.
- */
-async function sweepStaleAgentTmp(): Promise<void> {
- try {
- const base = path.basename(AGENT_JSON_PATH)
- for (const entry of await fs.readdir(AGENT_DIR)) {
- if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
- const owner =
- /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/
- .exec(middle)?.[1]
- if (middle === '' || (owner && owner !== String(process.pid))) {
- await fs.rm(path.join(AGENT_DIR, entry), { force: true }).catch(() => undefined)
- }
- }
- } catch {
- // A dir we cannot read is not a reason to fail (or skip) the write below.
- }
-}
-
/** Detect the machine's display name (macOS ComputerName, else hostname). */
async function computerName(): Promise<string> {
if (process.platform === 'darwin') {
@@ -482,7 +449,9 @@ export function createPairingService(
async function writeAgentJson(obj: Record<string, unknown>): Promise<void> {
await fs.mkdir(AGENT_DIR, { recursive: true, mode: 0o700 })
await fs.chmod(AGENT_DIR, 0o700).catch(() => {})
- await sweepStaleAgentTmp()
+ // Every device entry carries the `agentToken` bearer, so an orphaned temp is a live
+ // credential; the host agent shares ~/.nodeterm and is the foreign pid this can race.
+ await sweepForeignTempFiles(AGENT_JSON_PATH)
const tmp = tempNameFor(AGENT_JSON_PATH)
try {
await fs.writeFile(tmp, JSON.stringify(obj, null, 2) + '\n', { mode: 0o600 })
diff --git a/src/main/remote-ssh/share-team.ts b/src/main/remote-ssh/share-team.ts
index 4493fcf79..8bed88a0d 100644
--- a/src/main/remote-ssh/share-team.ts
+++ b/src/main/remote-ssh/share-team.ts
@@ -52,6 +52,7 @@ import {
} from '../../shared/share-team'
import type { SshConnection } from '../../shared/ssh'
import type { RelayBookmark } from '../remote/relay-bookmarks'
+import { isRecord } from '../../shared/is-record'
/** ssh timeouts per verb. `bootstrap` and `resume` outlast the server's own admin timeouts behind
* them (45 s and 60 s) plus the CLI's start-up, so a slow but healthy server answers before ssh
@@ -116,7 +117,6 @@ const CONTROL_G = new RegExp(CONTROL_RE.source, 'gu')
const QUOTE_OR_BACKSLASH_G = /['\\]/g
const RESUME_STATUSES: ReadonlySet<string> = new Set<ResumeStatus>(['resumed', 'already-running', 'refused'])
-const isRecord = (v: unknown): v is Record<string, unknown> => typeof v === 'object' && v !== null && !Array.isArray(v)
const fail = (error: string, code?: string): ShareFail => ({ ok: false, error, ...(code ? { code } : {}) })
/** A server-sent sentence, made safe to print: controls (and text-direction overrides) blanked, bounded. */
const shown = (text: string): string => text.replace(CONTROL_G, ' ').slice(0, SHOWN_MAX)
diff --git a/src/renderer/canvas/SharedGlyphLayer.tsx b/src/renderer/canvas/SharedGlyphLayer.tsx
index b13132d88..639381eac 100644
--- a/src/renderer/canvas/SharedGlyphLayer.tsx
+++ b/src/renderer/canvas/SharedGlyphLayer.tsx
@@ -57,6 +57,7 @@ import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
import { useViewMode, viewFor } from '../state/viewMode'
import { readLocal } from '../lib/localStore'
+import { rootPositionWith } from '@shared/root-position'
/** Atlas page edge, in DEVICE pixels. 2048 (not Phase 0's 1024) because the atlas cells are
* device-sized AND the page is now keyed by COLOUR: at dpr 2 a 13px terminal font is roughly a
@@ -472,18 +473,7 @@ function absoluteRect(node: StackedNode, byId: Map<string, StackedNode>): StackR
const w = positiveSize(node.measured?.width) ?? positiveSize(node.width)
const h = positiveSize(node.measured?.height) ?? positiveSize(node.height)
if (w === null || h === null) return null
- let { x, y } = node.position
- let parentId = node.parentId
- const seen = new Set<string>([node.id])
- for (let depth = 0; parentId && depth < MAX_PARENT_DEPTH; depth++) {
- if (seen.has(parentId)) break
- seen.add(parentId)
- const parent = byId.get(parentId)
- if (!parent) break
- x += parent.position.x
- y += parent.position.y
- parentId = parent.parentId
- }
+ const { x, y } = rootPositionWith(node, (id) => byId.get(id), MAX_PARENT_DEPTH)
return { x, y, w, h }
}
diff --git a/src/renderer/components/ShareTeamDialog.tsx b/src/renderer/components/ShareTeamDialog.tsx
index 64c6652e4..3fd25dbb5 100644
--- a/src/renderer/components/ShareTeamDialog.tsx
+++ b/src/renderer/components/ShareTeamDialog.tsx
@@ -9,6 +9,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react'
import { createPortal } from 'react-dom'
import { useDialogStack } from './dialog-stack'
import type { ShareConfirmSummary, ShareNode, ShareOutcome, SharePhase } from '../lib/shareSshTeam'
+import { errorText } from '../../shared/error-text'
export type ShareDialogState =
| { phase: 'running'; step: SharePhase; log: string }
@@ -46,8 +47,6 @@ const RESTORE_FAILED_TEXT = 'The SSH project could not be restored automatically
* anyone reads, and the tail is where a failure is. */
export const SHARE_LOG_TAIL = 4000
-const errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))
-
function TitleList({ heading, items }: { heading?: string; items: string[] }): React.JSX.Element | null {
if (!items.length) return null
return (
diff --git a/src/renderer/lib/nodeFocus.ts b/src/renderer/lib/nodeFocus.ts
index 342ee2876..6e42291bf 100644
--- a/src/renderer/lib/nodeFocus.ts
+++ b/src/renderer/lib/nodeFocus.ts
@@ -1,4 +1,5 @@
import { getViewportForBounds, type Rect, type Viewport } from '@xyflow/system'
+import { rootPositionWith } from '@shared/root-position'
import { NO_INSETS, measurePinnedInsets, type RectLike, type ScreenInsets } from './pinnedInsets'
import { measureMaximizeInsets } from './maximizeInsets'
@@ -86,20 +87,7 @@ export function absolutePosition(
node: FocusableNode,
all: readonly FocusableNode[]
): { x: number; y: number } {
- let x = node.position.x
- let y = node.position.y
- let parentId = node.parentId
- const seen = new Set<string>([node.id])
- for (let depth = 0; parentId && depth < MAX_PARENT_DEPTH; depth++) {
- if (seen.has(parentId)) break
- seen.add(parentId)
- const parent = all.find((n) => n.id === parentId)
- if (!parent) break
- x += parent.position.x
- y += parent.position.y
- parentId = parent.parentId
- }
- return { x, y }
+ return rootPositionWith(node, (id) => all.find((n) => n.id === id), MAX_PARENT_DEPTH)
}
/**
diff --git a/src/renderer/lib/projectOpen.ts b/src/renderer/lib/projectOpen.ts
index 95d94ab8d..5306e6d31 100644
--- a/src/renderer/lib/projectOpen.ts
+++ b/src/renderer/lib/projectOpen.ts
@@ -3,6 +3,7 @@
// calls and the reply — so every decision that does not need React is unit-testable here, the
// same reasoning as controlRouting.ts / pendingLaunch.ts.
import { oneLine } from '@shared/one-line'
+import { rootPositionWith } from '@shared/root-position'
import { sourceIsControlCapable } from './controlRouting'
/** The little these helpers need to know about a project. */
@@ -294,27 +295,9 @@ export interface PlacedNode {
const placedW = (n: PlacedNode): number => n.size?.width ?? (n.width as number) ?? 0
const placedH = (n: PlacedNode): number => n.size?.height ?? (n.height as number) ?? 0
-/** A node's position in ROOT space: its own plus every ancestor frame's origin (a group child's
- * stored position is frame-relative). Cycle-guarded like every other parent walk. */
-function rootPosition(n: PlacedNode, byId: Map<string, PlacedNode>): { x: number; y: number } {
- let x = n.position.x
- let y = n.position.y
- const seen = new Set<string>(n.id ? [n.id] : [])
- let parentId = n.parentId
- while (parentId && !seen.has(parentId)) {
- seen.add(parentId)
- const parent = byId.get(parentId)
- if (!parent) break
- x += parent.position.x
- y += parent.position.y
- parentId = parent.parentId
- }
- return { x, y }
-}
-
/**
- * A stored node's ROOT-space position — the public face of `rootPosition`, so the cold-open
- * planner does not need a third copy of a parent walk this repo already carries two of.
+ * A stored node's ROOT-space position (a group child's stored position is frame-relative), over
+ * the shared parent walk in `@shared/root-position`.
*/
export function rootPositionIn(
nodes: readonly PlacedNode[],
@@ -322,7 +305,7 @@ export function rootPositionIn(
): { x: number; y: number } {
const byId = new Map<string, PlacedNode>()
for (const n of nodes) if (n.id) byId.set(n.id, n)
- return rootPosition(node, byId)
+ return rootPositionWith(node, (id) => byId.get(id))
}
/**
@@ -342,7 +325,7 @@ export function nextFreePosition(
let left = Infinity
let bottom = -Infinity
for (const n of nodes) {
- const at = rootPosition(n, byId)
+ const at = rootPositionWith(n, (id) => byId.get(id))
if (Number.isFinite(at.x)) left = Math.min(left, at.x)
const b = at.y + placedH(n)
if (Number.isFinite(b)) bottom = Math.max(bottom, b)
diff --git a/src/renderer/lib/shareSshTeam.ts b/src/renderer/lib/shareSshTeam.ts
index 1e2575ea4..d4166be5e 100644
--- a/src/renderer/lib/shareSshTeam.ts
+++ b/src/renderer/lib/shareSshTeam.ts
@@ -30,6 +30,7 @@ import {
type ShareReply,
type ShareTeamApi
} from '@shared/share-team'
+import { errorText } from '@shared/error-text'
/** One terminal node of the project being shared, with what the renderer knows about its agent. */
export interface ShareNode {
@@ -133,8 +134,6 @@ const BUSY_STATES = new Set<AgentState>(['working', 'blocked', 'waiting'])
const isAgentResumable = (id: string | undefined): boolean =>
!!id && (RESUMABLE_AGENTS as readonly string[]).includes(id)
-const errorText = (e: unknown): string => (e instanceof Error ? e.message : String(e))
-
export const BUSY_REFUSAL = 'Wait for these agents to finish (or stop them), then share again.'
export const CANVAS_CHANGED = 'The canvas changed while preparing the share. Nothing was changed; share again.'
export const otherHostRefusal = (titles: string[]): string =>
diff --git a/src/renderer/nodes/RunBar.tsx b/src/renderer/nodes/RunBar.tsx
index 2fbf89bb0..f1bb16591 100644
--- a/src/renderer/nodes/RunBar.tsx
+++ b/src/renderer/nodes/RunBar.tsx
@@ -32,6 +32,7 @@ import { useSession } from '../session/session'
import { useProjects } from '../state/projects'
import { createBrowserNode, createSimulatorNode, terminalNodeSize, type CanvasNode } from '../state/workspace'
import { IconPlay, IconReload } from '../components/icons'
+import { sleep } from '@shared/sleep'
/**
* The run node's toolbar: VS Code's "Run Without Debugging" for any `.vscode/launch.json`
@@ -101,8 +102,6 @@ function parseSig(sig: string): Array<{ id: string; title: string; runConfig: {
})
}
-const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
-
export function RunBar({ nodeId, config, autoStart, simulator, browser: browserPanel }: Props) {
const session = useSession()
const { api } = session
diff --git a/src/renderer/state/kanbanDisplay.ts b/src/renderer/state/kanbanDisplay.ts
index 2184bc51f..118c92833 100644
--- a/src/renderer/state/kanbanDisplay.ts
+++ b/src/renderer/state/kanbanDisplay.ts
@@ -1,5 +1,6 @@
import { create } from 'zustand'
import { readLocal, writeLocal } from '../lib/localStore'
+import { isRecord } from '../../shared/is-record'
// How ONE person looks at a project's board — PERSONAL, per machine: localStorage, never the
// git-shared .nodeterm/project.json (same rule as the view mode and the card panel). What the board
@@ -22,9 +23,6 @@ export interface ProjectBoardDisplay {
export type KanbanDisplayMap = Record<string, ProjectBoardDisplay>
-const isRecord = (x: unknown): x is Record<string, unknown> =>
- !!x && typeof x === 'object' && !Array.isArray(x)
-
/** Parses the persisted map. Anything unreadable is "every default"; only literal booleans are
* kept, so a hand-edited value can never flip a default it did not spell exactly. */
export function parseKanbanDisplay(raw: string | null): KanbanDisplayMap {
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index 71637e819..29afbafc1 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -31,6 +31,7 @@ import { groupsFirst } from '@shared/node-order'
import { applyOwnCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
import { registerCodexRelayProjectCheck } from './codexCli'
import { markWorkspaceDirty } from './workspaceDirty'
+import { rootPositionWith } from '@shared/root-position'
import { folderName } from '../lib/projectOpen'
// One order-independent key for an edge's endpoints — the SAME rule `hiddenLinkIds` uses, so a
// rope and the bridge it covers are recognized as one relationship here too.
@@ -328,19 +329,7 @@ function rootStatePosition(
nodes: CanvasNodeState[]
): { x: number; y: number } {
const byId = new Map(nodes.map((candidate) => [candidate.id, candidate]))
- const seen = new Set<string>([node.id])
- let x = node.position.x
- let y = node.position.y
- let parentId = node.parentId
- while (parentId && !seen.has(parentId)) {
- seen.add(parentId)
- const parent = byId.get(parentId)
- if (!parent) break
- x += parent.position.x
- y += parent.position.y
- parentId = parent.parentId
- }
- return { x, y }
+ return rootPositionWith(node, (id) => byId.get(id))
}
function stateIsDescendant(
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index 870cb9f97..1d72d678b 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -53,6 +53,7 @@ export { accountNodeColor, agentAccountColor } from '@shared/agents/account-colo
import { mutationTrustsLaunch, sanitizeInboundNode } from '@shared/node-exec'
import { SYSTEM_NODE_COLORS } from '@shared/node-colors'
import { groupsFirstBy } from '@shared/node-order'
+import { rootPositionWith } from '@shared/root-position'
// Preserve the renderer's long-standing import surface; validation and the palette now live in
// shared so Server Edition and canvas-control accept exactly what these pickers display.
@@ -2036,19 +2037,7 @@ function groupsFirst(nodes: CanvasNode[]): CanvasNode[] {
/** A node's position in ROOT space: its own position plus every ancestor frame's origin. */
export function rootPosition(node: CanvasNode, nodes: CanvasNode[]): { x: number; y: number } {
const byId = new Map(nodes.map((candidate) => [candidate.id, candidate]))
- const seen = new Set<string>([node.id])
- let x = node.position.x
- let y = node.position.y
- let parentId = node.parentId
- while (parentId && !seen.has(parentId)) {
- seen.add(parentId)
- const parent = byId.get(parentId)
- if (!parent) break
- x += parent.position.x
- y += parent.position.y
- parentId = parent.parentId
- }
- return { x, y }
+ return rootPositionWith(node, (id) => byId.get(id))
}
/**
diff --git a/src/server/github-control.ts b/src/server/github-control.ts
index e96ded0a2..8a1f9e828 100644
--- a/src/server/github-control.ts
+++ b/src/server/github-control.ts
@@ -1,6 +1,6 @@
import { promises as fs } from 'node:fs'
import path from 'node:path'
-import { renameAtomic, tempNameFor } from '../core/fs-atomic'
+import { renameAtomic, sweepForeignTempFiles, tempNameFor } from '../core/fs-atomic'
import type { GitHubSecretStore } from '../core/github/credentials'
import type { SecretStore } from '../core/secret-store'
import type { CorePlatform } from '../core/platform'
@@ -19,38 +19,6 @@ function validToken(token: string): boolean {
return token.trim() === token && token.length > 0 && token.length <= 4096 && !/[\r\n\0]/.test(token)
}
-/**
- * Remove temp files no writer in THIS process owns: the legacy fixed `<file>.tmp` (written by
- * builds before per-call names) and any `<file>.<pid>.<seq>[.<uuid>].tmp` whose pid is not ours.
- * Best effort — a failure here must never break a save.
- *
- * The token file is not config: an orphan here is a live PAT at 0600 that nothing will ever
- * overwrite, because a unique name is never written twice. So it has to be collected rather than
- * left. Temps bearing our own pid are untouchable: one may belong to a concurrent write sitting
- * between its `writeFile` and its `rename`, and deleting it would recreate the exact race the
- * unique names fixed. A foreign pid can be a second LIVE server on the same data dir; that setup
- * has no lock to begin with, and the worst case is that process's rename failing cleanly (ENOENT,
- * rethrown to its caller) instead of a forgotten PAT sitting on disk forever.
- */
-async function sweepStaleTmp(target: string): Promise<void> {
- try {
- const directory = path.dirname(target)
- const base = path.basename(target)
- for (const entry of await fs.readdir(directory)) {
- if (!entry.startsWith(base) || !entry.endsWith('.tmp')) continue
- const middle = entry.slice(base.length, -'.tmp'.length) // '' or '.<pid>.<seq>[.<uuid>]'
- const owner =
- /^\.(\d+)\.\d+(?:\.[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12})?$/
- .exec(middle)?.[1]
- if (middle === '' || (owner && owner !== String(process.pid))) {
- await fs.rm(path.join(directory, entry), { force: true }).catch(() => undefined)
- }
- }
- } catch {
- // A dir we cannot read is not a reason to fail (or skip) the write below.
- }
-}
-
/** Generic headless secret store. Server Edition has no OS keyring, so callers receive the same
* owner-only atomic file semantics instead of copying the GitHub token implementation. */
export class ServerSecretStore implements SecretStore {
@@ -83,7 +51,7 @@ export class ServerSecretStore implements SecretStore {
private async saveNow(token: string): Promise<void> {
if (!validToken(token)) throw new ServerSecretStoreError('invalid-token')
await fs.mkdir(this.userDataDir, { recursive: true })
- await sweepStaleTmp(this.filePath)
+ await sweepForeignTempFiles(this.filePath)
// The store's per-instance chain orders this write against its sibling mutations; the per-call
// temp name covers the writers the chain cannot see — a second `nodeterm-server --data-dir X`
// process on the same dir (every process's counter starts at 0, hence the pid) and a crash
@@ -110,7 +78,7 @@ export class ServerSecretStore implements SecretStore {
clear(): Promise<void> {
return this.chained(async () => {
// Sweep here too: clearing a token that leaves an orphan temp behind has not cleared anything.
- await sweepStaleTmp(this.filePath)
+ await sweepForeignTempFiles(this.filePath)
await fs.rm(this.filePath, { force: true })
})
}
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index 99f1eb222..975f86403 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -38,6 +38,7 @@ import {
import { assembleLaunchCommand } from '../shared/agents/launch'
import type { AgentState, NormalizedAgentEvent } from '../shared/agents/normalize'
import { oneLine } from '../shared/one-line'
+import { rootPositionWith } from '../shared/root-position'
import { RUN_NOW_AFTER_REFUSAL, runNowRequested } from '../shared/control-verbs'
import {
RUN_NOW_AFTER_SUCCESS_REFUSAL,
@@ -301,32 +302,16 @@ function sourceCanControl(
return !!agentId && canControlCanvas(agentId)
}
-function absolutePosition(project: Project, node: CanvasNodeState): { x: number; y: number } {
- let x = node.position.x
- let y = node.position.y
- let parent = node.parentId
- const seen = new Set<string>()
- while (parent && !seen.has(parent)) {
- seen.add(parent)
- const p = project.nodes.find((candidate) => candidate.id === parent)
- if (!p) break
- x += p.position.x
- y += p.position.y
- parent = p.parentId
- }
- return { x, y }
-}
-
function placeRight(
project: Project,
source: CanvasNodeState,
size: { width: number; height: number },
reserved: readonly CanvasNodeState[] = []
): { x: number; y: number } {
- const origin = absolutePosition(project, source)
+ const origin = rootPosition(project.nodes, source)
const sourceWidth = source.size?.width || TERMINAL_SIZE.width
const occupied = [...project.nodes, ...reserved].map((node) => {
- const position = absolutePosition(project, node)
+ const position = rootPosition(project.nodes, node)
return {
x: position.x,
y: position.y,
@@ -584,19 +569,7 @@ function rootPosition(
node: CanvasNodeState
): { x: number; y: number } {
const byId = new Map(nodes.map((candidate) => [candidate.id, candidate]))
- const seen = new Set<string>([node.id])
- let x = node.position.x
- let y = node.position.y
- let parentId = node.parentId
- while (parentId && !seen.has(parentId)) {
- seen.add(parentId)
- const parent = byId.get(parentId)
- if (!parent) break
- x += parent.position.x
- y += parent.position.y
- parentId = parent.parentId
- }
- return { x, y }
+ return rootPositionWith(node, (id) => byId.get(id))
}
/** Desktop `ungroupNodes` semantics over persisted nodes: direct children move up one level. */
diff --git a/src/session-host/host.ts b/src/session-host/host.ts
index 23ad0bf94..a6203114d 100644
--- a/src/session-host/host.ts
+++ b/src/session-host/host.ts
@@ -62,6 +62,7 @@ import { SessionHostSocketRequestQueue } from './socket-request-queue'
import { trySessionHostHello } from './hello-probe'
import { killHostSession } from './kill-session'
import { clampEmulatorScrollback } from '../shared/scrollback'
+import { sleep } from '../shared/sleep'
/** How long a session-less host lingers before exiting — mirrors tmux's own server lifetime rule
* ("the server exits when its last session dies"), plus a grace window so an app restart that
@@ -114,10 +115,6 @@ function log(line: string): void {
}
}
-function sleep(ms: number): Promise<void> {
- return new Promise((resolve) => setTimeout(resolve, ms))
-}
-
/** Poll for a WINNER of the startup race to finish writing its state file and come up — the state
* file can legitimately exist-but-be-incomplete for a brief window between this process losing
* the exclusive-create race and the winner actually binding + writing token + state. */
diff --git a/src/shared/agents/permission-answer.ts b/src/shared/agents/permission-answer.ts
index 133295e74..435a80bc8 100644
--- a/src/shared/agents/permission-answer.ts
+++ b/src/shared/agents/permission-answer.ts
@@ -1,3 +1,4 @@
+import { isRecord } from '../is-record'
// Structured answers to a HELD Claude PermissionRequest (docs/hook-reply-approvals.md).
//
// The managed hook holds a PermissionRequest open and polls an answer file. The legacy answer is
@@ -95,8 +96,6 @@ export const QUESTIONS_MAX = 16
export const QUESTION_OPTIONS_MAX = 32
export const QUESTION_TEXT_MAX_CHARS = 4000
-const isRecord = (v: unknown): v is Record<string, unknown> =>
- typeof v === 'object' && v !== null && !Array.isArray(v)
const keyText = (v: unknown): v is string =>
typeof v === 'string' && v !== '' && v.length <= QUESTION_TEXT_MAX_CHARS
/** A display-only string (header, description): kept when readable, dropped (never refused) when not. */
diff --git a/src/shared/error-text.test.ts b/src/shared/error-text.test.ts
new file mode 100644
index 000000000..90bea0ebd
--- /dev/null
+++ b/src/shared/error-text.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { errorText } from './error-text'
+
+describe('errorText', () => {
+ it("returns an Error's message", () => {
+ expect(errorText(new Error('boom'))).toBe('boom')
+ expect(errorText(new TypeError('bad type'))).toBe('bad type')
+ })
+
+ it('stringifies anything else', () => {
+ expect(errorText('plain')).toBe('plain')
+ expect(errorText(42)).toBe('42')
+ expect(errorText(undefined)).toBe('undefined')
+ expect(errorText({ message: 'not an Error' })).toBe('[object Object]')
+ })
+})
diff --git a/src/shared/error-text.ts b/src/shared/error-text.ts
new file mode 100644
index 000000000..20c79564b
--- /dev/null
+++ b/src/shared/error-text.ts
@@ -0,0 +1,10 @@
+/**
+ * The message of a caught value: an `Error`'s `message`, else the value stringified.
+ *
+ * Several modules declare a local helper with this NAME that does something else (zellij's joins
+ * stdout and stderr, opencode's formats an SDK error object, the simulator's strips an Xcode
+ * prefix). Those are separate functions, not copies of this one, and stay where they are.
+ */
+export function errorText(error: unknown): string {
+ return error instanceof Error ? error.message : String(error)
+}
diff --git a/src/shared/is-record.test.ts b/src/shared/is-record.test.ts
new file mode 100644
index 000000000..e4c0cb4ff
--- /dev/null
+++ b/src/shared/is-record.test.ts
@@ -0,0 +1,16 @@
+import { describe, expect, it } from 'vitest'
+import { isRecord } from './is-record'
+
+describe('isRecord', () => {
+ it('accepts plain objects, including empty and null-prototype ones', () => {
+ expect(isRecord({})).toBe(true)
+ expect(isRecord({ a: 1 })).toBe(true)
+ expect(isRecord(Object.create(null))).toBe(true)
+ })
+
+ it('rejects null, arrays and primitives', () => {
+ for (const value of [null, undefined, [], [1], 0, 1, '', 'x', true, false, Symbol('s'), 1n]) {
+ expect(isRecord(value), String(value)).toBe(false)
+ }
+ })
+})
diff --git a/src/shared/is-record.ts b/src/shared/is-record.ts
new file mode 100644
index 000000000..ed9062a75
--- /dev/null
+++ b/src/shared/is-record.ts
@@ -0,0 +1,14 @@
+/**
+ * True for a plain JSON-style object: not null, not an array. The guard every reader of untrusted
+ * JSON (hook payloads, transcripts, git-shared project files, CDP messages) runs before it touches
+ * a field.
+ *
+ * One definition, imported everywhere. It used to be re-typed per file under two names
+ * (`isRecord` / `isObj`), with the null check spelled two different ways.
+ *
+ * Arrays are rejected on purpose. `session-host/windows-conpty.ts` keeps its own guard because it
+ * accepts arrays, and folding it in here would change what that reader accepts.
+ */
+export function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
+}
diff --git a/src/shared/kanban-ops.ts b/src/shared/kanban-ops.ts
index 6db66772b..74e5c7602 100644
--- a/src/shared/kanban-ops.ts
+++ b/src/shared/kanban-ops.ts
@@ -15,6 +15,7 @@ import type {
KanbanAssignment, KanbanCardMeta, KanbanColumn, KanbanColumnCategory, KanbanLabel,
KanbanLabelColor, KanbanOp, KanbanPriority, KanbanSavedView, ProjectKanban
} from './types'
+import { isRecord } from './is-record'
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/
/** What a display name must never carry: C0/C1 controls (they break a name out of its one-line chip),
@@ -35,7 +36,6 @@ const CATEGORIES: readonly KanbanColumnCategory[] = ['unstarted', 'started', 'do
const DUE_MIN = 0
const DUE_MAX = 32_503_680_000_000
-const isObj = (x: unknown): x is Record<string, unknown> => !!x && typeof x === 'object' && !Array.isArray(x)
const text = (x: unknown, max: number): string | null =>
typeof x === 'string' && x.length <= max && !CONTROL.test(x) ? x : null
/**
@@ -59,7 +59,7 @@ const idList = (x: unknown): string[] | null => {
}
function column(x: unknown): KanbanColumn | null {
- if (!isObj(x) || !isRefId(x.id)) return null
+ if (!isRecord(x) || !isRefId(x.id)) return null
const title = displayText(x.title, TITLE_MAX)
if (title === null) return null
const out: KanbanColumn = { id: x.id, title, color: text(x.color, COLOR_MAX) ?? DEFAULT_COLUMN_COLOR }
@@ -68,18 +68,18 @@ function column(x: unknown): KanbanColumn | null {
}
function assignment(x: unknown): KanbanAssignment | null {
- if (!isObj(x) || !isRefId(x.nodeId) || !isRefId(x.columnId)) return null
+ if (!isRecord(x) || !isRefId(x.nodeId) || !isRefId(x.columnId)) return null
const out: KanbanAssignment = { nodeId: x.nodeId, columnId: x.columnId }
if (isValidRank(x.rank)) out.rank = x.rank
return out
}
function meta(x: unknown): KanbanCardMeta | null {
- if (!isObj(x) || !isRefId(x.nodeId)) return null
+ if (!isRecord(x) || !isRefId(x.nodeId)) return null
const out: KanbanCardMeta = { nodeId: x.nodeId }
if (Array.isArray(x.assignees)) {
const a = x.assignees
- .filter(isObj)
+ .filter(isRecord)
.map((p) => ({ name: displayText(p.name, NAME_MAX), color: text(p.color, COLOR_MAX) }))
.filter((p): p is { name: string; color: string } => !!p.name && p.color !== null)
.slice(0, 50)
@@ -94,7 +94,7 @@ function meta(x: unknown): KanbanCardMeta | null {
}
function label(x: unknown): KanbanLabel | null {
- if (!isObj(x) || !isRefId(x.id)) return null
+ if (!isRecord(x) || !isRefId(x.id)) return null
const name = displayText(x.name, LABEL_NAME_MAX)
if (name === null) return null
const color: KanbanLabelColor = KANBAN_LABEL_COLORS.includes(x.color as KanbanLabelColor)
@@ -118,7 +118,7 @@ export function isKanbanOp(m: { op?: unknown }): boolean {
* label's to `default`), rank, priority, dueAt, category, and the display text (label name, column
* title, assignee name: see `displayText`). */
export function sanitizeKanbanOp(m: unknown): KanbanOp | null {
- if (!isObj(m)) return null
+ if (!isRecord(m)) return null
switch (m.op) {
case 'kb-column': { const c = column(m.column); return c && { op: 'kb-column', column: c } }
case 'kb-column-remove': return isRefId(m.id) ? { op: 'kb-column-remove', id: m.id } : null
@@ -175,7 +175,7 @@ export function isKanbanDeletion(m: KanbanOp): boolean {
// edit. Malformed entries are invisible to both: the diff never casts them, and the one op that
// writes a list back writes it clean.
const isEntry = <K extends string>(key: K) => (x: unknown): x is Record<K, string> =>
- isObj(x) && typeof x[key] === 'string'
+ isRecord(x) && typeof x[key] === 'string'
const columnsOf = (b: ProjectKanban): KanbanColumn[] =>
Array.isArray(b.columns) ? b.columns.filter(isEntry('id')) as KanbanColumn[] : []
const assignmentsOf = (b: ProjectKanban): KanbanAssignment[] =>
@@ -282,7 +282,7 @@ export function applyKanbanOp(board: ProjectKanban | undefined, m: KanbanOp, pro
function stable(v: unknown): string {
return JSON.stringify(v, (_k, val) =>
- isObj(val) ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, val[k]])) : val)
+ isRecord(val) ? Object.fromEntries(Object.keys(val).sort().map((k) => [k, val[k]])) : val)
}
const same = (a: unknown, b: unknown): boolean => stable(a) === stable(b)
diff --git a/src/shared/kanban-views.ts b/src/shared/kanban-views.ts
index faddbfec9..b7607b744 100644
--- a/src/shared/kanban-views.ts
+++ b/src/shared/kanban-views.ts
@@ -15,6 +15,7 @@
* IDENTITY so a well-formed file is never rewritten.
*/
import type { KanbanSavedView, KanbanViewQuery, ProjectKanban } from './types'
+import { isRecord } from './is-record'
export const KANBAN_VIEW_SOURCES: ReadonlyArray<NonNullable<KanbanViewQuery['source']>> = [
'all',
@@ -31,9 +32,6 @@ const LIST_MAX = 200
// eslint-disable-next-line no-control-regex
const CONTROL = /[\u0000-\u001f\u007f-\u009f]/g
-const isRecord = (x: unknown): x is Record<string, unknown> =>
- !!x && typeof x === 'object' && !Array.isArray(x)
-
/** A shown name: control characters out, trimmed, bounded. '' = no usable name. */
function cleanName(name: string): string {
return name.replace(CONTROL, ' ').trim().slice(0, VIEW_NAME_MAX).trim()
diff --git a/src/shared/root-position.test.ts b/src/shared/root-position.test.ts
new file mode 100644
index 000000000..79fd2b523
--- /dev/null
+++ b/src/shared/root-position.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest'
+import { rootPositionWith, type ParentedNode } from './root-position'
+
+type TestNode = ParentedNode & { id: string }
+
+const byIdLookup = (nodes: TestNode[]) => {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ return (id: string) => byId.get(id)
+}
+
+describe('rootPositionWith', () => {
+ it('returns a top-level node position unchanged', () => {
+ const node = { id: 'a', position: { x: 3, y: 4 } }
+ expect(rootPositionWith(node, byIdLookup([node]))).toEqual({ x: 3, y: 4 })
+ })
+
+ it('adds every ancestor frame origin through nested groups', () => {
+ const outer = { id: 'outer', position: { x: 100, y: 200 } }
+ const inner = { id: 'inner', position: { x: 10, y: 20 }, parentId: 'outer' }
+ const leaf = { id: 'leaf', position: { x: 1, y: 2 }, parentId: 'inner' }
+ expect(rootPositionWith(leaf, byIdLookup([outer, inner, leaf]))).toEqual({ x: 111, y: 222 })
+ })
+
+ it('stops at a missing parent with what it has accumulated', () => {
+ const inner = { id: 'inner', position: { x: 10, y: 20 }, parentId: 'gone' }
+ const leaf = { id: 'leaf', position: { x: 1, y: 2 }, parentId: 'inner' }
+ expect(rootPositionWith(leaf, byIdLookup([inner, leaf]))).toEqual({ x: 11, y: 22 })
+ })
+
+ it('terminates on a parent cycle, visiting each frame once', () => {
+ const a = { id: 'a', position: { x: 1, y: 1 }, parentId: 'b' }
+ const b = { id: 'b', position: { x: 10, y: 10 }, parentId: 'a' }
+ expect(rootPositionWith(a, byIdLookup([a, b]))).toEqual({ x: 11, y: 11 })
+ })
+
+ it('does not offset a node that names itself as its parent', () => {
+ const self = { id: 'self', position: { x: 5, y: 7 }, parentId: 'self' }
+ expect(rootPositionWith(self, byIdLookup([self]))).toEqual({ x: 5, y: 7 })
+ })
+
+ it('walks an id-less node (a not-yet-created placement) like any other', () => {
+ const frame = { id: 'frame', position: { x: 50, y: 60 } }
+ expect(rootPositionWith({ position: { x: 1, y: 2 }, parentId: 'frame' }, byIdLookup([frame]))).toEqual({
+ x: 51,
+ y: 62
+ })
+ })
+
+ it('honors maxDepth', () => {
+ const g1 = { id: 'g1', position: { x: 1000, y: 0 } }
+ const g2 = { id: 'g2', position: { x: 100, y: 0 }, parentId: 'g1' }
+ const leaf = { id: 'leaf', position: { x: 1, y: 0 }, parentId: 'g2' }
+ const lookup = byIdLookup([g1, g2, leaf])
+ expect(rootPositionWith(leaf, lookup, 1)).toEqual({ x: 101, y: 0 })
+ expect(rootPositionWith(leaf, lookup, 0)).toEqual({ x: 1, y: 0 })
+ })
+
+ it("uses the caller's lookup, so first-match and last-match callers keep their answer", () => {
+ const first = { id: 'dup', position: { x: 10, y: 0 } }
+ const last = { id: 'dup', position: { x: 20, y: 0 } }
+ const leaf = { id: 'leaf', position: { x: 1, y: 0 }, parentId: 'dup' }
+ const all = [first, last, leaf]
+ expect(rootPositionWith(leaf, (id) => all.find((node) => node.id === id))).toEqual({ x: 11, y: 0 })
+ expect(rootPositionWith(leaf, byIdLookup(all))).toEqual({ x: 21, y: 0 })
+ })
+})
diff --git a/src/shared/root-position.ts b/src/shared/root-position.ts
new file mode 100644
index 000000000..60fd7fb80
--- /dev/null
+++ b/src/shared/root-position.ts
@@ -0,0 +1,39 @@
+/**
+ * A node's position in ROOT (canvas) space: its own `position` plus the origin of every ancestor
+ * frame, because a grouped node's `position` is relative to its parent.
+ *
+ * This is the ONE parent walk. Seven copies used to exist (renderer workspace, cold-open planner,
+ * project store, focus, glyph layer and two in the headless node factory). They agreed on a valid
+ * canvas and drifted on a corrupt one: one did not count the node itself as visited, so a node
+ * that names itself as its parent was offset by its own position once.
+ *
+ * The walk always stops: every id is visited at most once (`seen` starts with the node's own id),
+ * and it stops at a missing parent. `lookup` is the caller's own, so a caller that resolves a
+ * duplicated id to the first match (`Array.find`) or the last one (a `Map` built from the array)
+ * keeps doing so. `maxDepth` keeps the cap two callers already had; a parent chain that long is a
+ * data bug.
+ */
+export interface ParentedNode {
+ position: { x: number; y: number }
+ parentId?: string
+}
+
+export function rootPositionWith<T extends ParentedNode>(
+ node: ParentedNode & { id?: string },
+ lookup: (id: string) => T | undefined,
+ maxDepth: number = Number.POSITIVE_INFINITY
+): { x: number; y: number } {
+ let x = node.position.x
+ let y = node.position.y
+ let parentId = node.parentId
+ const seen = new Set<string>(node.id ? [node.id] : [])
+ for (let depth = 0; parentId && depth < maxDepth && !seen.has(parentId); depth++) {
+ seen.add(parentId)
+ const parent = lookup(parentId)
+ if (!parent) break
+ x += parent.position.x
+ y += parent.position.y
+ parentId = parent.parentId
+ }
+ return { x, y }
+}
diff --git a/src/shared/run-config.ts b/src/shared/run-config.ts
index 740754d7b..b946f0c25 100644
--- a/src/shared/run-config.ts
+++ b/src/shared/run-config.ts
@@ -28,6 +28,7 @@
* `envFile`'s secrets) therefore never land in the user's shell history or scrollback.
*/
import { shellSingleQuote, shellSplit } from './shell-quote'
+import { isRecord } from './is-record'
// ─── The node's persisted choice ─────────────────────────────────────────────────────────────
@@ -198,10 +199,6 @@ export interface LaunchFile {
compounds: LaunchCompound[]
}
-function isRecord(v: unknown): v is Record<string, unknown> {
- return !!v && typeof v === 'object' && !Array.isArray(v)
-}
-
function withOsOverride(raw: Record<string, unknown>, os: OsKey): Record<string, unknown> {
const o = raw[os]
return isRecord(o) ? { ...raw, ...o } : raw
diff --git a/src/shared/sleep.ts b/src/shared/sleep.ts
new file mode 100644
index 000000000..621edd186
--- /dev/null
+++ b/src/shared/sleep.ts
@@ -0,0 +1,4 @@
+/** Resolve after `ms` milliseconds. A plain `setTimeout`, so fake timers in tests control it. */
+export function sleep(ms: number): Promise<void> {
+ return new Promise((resolve) => setTimeout(resolve, ms))
+}