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(session): editor/diff/explorer + source-control read fs/git from the session

enes9ac40e45c8dd
diff --git a/src/renderer/components/CloneRepoDialog.tsx b/src/renderer/components/CloneRepoDialog.tsx
index 3b993f54f..f3fadc781 100644
--- a/src/renderer/components/CloneRepoDialog.tsx
+++ b/src/renderer/components/CloneRepoDialog.tsx
@@ -1,5 +1,6 @@
import { useEffect, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
+import { useSession } from '../session/session'
import {
expandCloneUrl,
isValidCloneUrl,
@@ -23,6 +24,11 @@ interface CloneRepoDialogProps {
* half-cloned directory it claimed.
*/
export function CloneRepoDialog({ open, onClose, onCloned }: CloneRepoDialogProps) {
+ // This dialog's core api (a stable context read): the clone runs on the session's core. The
+ // effects below capture it in their CLOSURES and keep their `[open]` dep arrays — one of them
+ // subscribes (onCloneProgress), and re-keying a resource effect on `api` is the 4c bomb the
+ // sub-stage rules forbid. (The native folder picker stays on the app-global `dialog`.)
+ const { api } = useSession()
const [url, setUrl] = useState('')
const [parent, setParent] = useState('')
const [cloning, setCloning] = useState(false)
@@ -43,13 +49,13 @@ export function CloneRepoDialog({ open, onClose, onCloned }: CloneRepoDialogProp
urlRef.current?.focus()
const remembered = localStorage.getItem(PARENT_KEY)
if (remembered) setParent(remembered)
- else void window.nodeTerminal.git.cloneDefaultParent().then((p) => setParent((cur) => cur || p))
+ else void api.git.cloneDefaultParent().then((p) => setParent((cur) => cur || p))
}, [open])
// Progress stream — subscribed only while the dialog is open.
useEffect(() => {
if (!open) return
- return window.nodeTerminal.git.onCloneProgress(setProgress)
+ return api.git.onCloneProgress(setProgress)
}, [open])
// Closing the dialog (open → false) while a clone is in flight aborts it (main
@@ -60,7 +66,7 @@ export function CloneRepoDialog({ open, onClose, onCloned }: CloneRepoDialogProp
}, [cloning])
useEffect(() => {
if (open) return
- if (cloningRef.current) void window.nodeTerminal.git.cloneAbort()
+ if (cloningRef.current) void api.git.cloneAbort()
}, [open])
if (!open) return null
@@ -70,9 +76,9 @@ export function CloneRepoDialog({ open, onClose, onCloned }: CloneRepoDialogProp
setCloning(true)
setError('')
setProgress(null)
- let r: Awaited<ReturnType<typeof window.nodeTerminal.git.clone>>
+ let r: Awaited<ReturnType<typeof api.git.clone>>
try {
- r = await window.nodeTerminal.git.clone(parent.trim(), expanded)
+ r = await api.git.clone(parent.trim(), expanded)
} catch (err) {
setError(String(err))
return
@@ -92,7 +98,7 @@ export function CloneRepoDialog({ open, onClose, onCloned }: CloneRepoDialogProp
}
const cancel = (): void => {
- if (cloning) void window.nodeTerminal.git.cloneAbort()
+ if (cloning) void api.git.cloneAbort()
onClose()
}
diff --git a/src/renderer/components/ExplorerPanel.tsx b/src/renderer/components/ExplorerPanel.tsx
index 4bfeefd42..481f1c8e4 100644
--- a/src/renderer/components/ExplorerPanel.tsx
+++ b/src/renderer/components/ExplorerPanel.tsx
@@ -4,6 +4,7 @@ import type { DirEntry, FsApi } from '@shared/types'
import { useProjects } from '../state/projects'
import { useExplorer } from '../state/explorer'
import { sshFs } from '../terminal/ssh-fs'
+import { useSession } from '../session/session'
import { promptDialog } from './promptDialog'
import { ancestorDirs, createTargetDir, newEntryPath, parentDir } from '../lib/explorerCreate'
@@ -166,9 +167,14 @@ export function ExplorerPanel({ onClose, onOpenFile, reveal }: ExplorerPanelProp
// ControlMaster via `sshFs`. Local (and relay) projects keep the local fs rooted at `cwd`.
const ssh = project?.ssh
const cwd = ssh ? ssh.remoteCwd : project?.cwd
+ // This panel's core api (a stable context read — the local session's api IS window.nodeTerminal).
+ // `api` IS a dep here: the memo is a pure pick (no resource), and the list effect below should
+ // re-fetch off a new core's fs when 4c makes a session's api replaceable.
+ const { api } = useSession()
const fs = useMemo<FsApi>(
- () => (ssh && project ? sshFs(project.id) : window.nodeTerminal.fs),
- [project?.id, ssh]
+ () => (ssh && project ? sshFs(project.id) : api.fs),
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [project?.id, ssh, api]
)
// Files opened from an SSH project's Explorer are genuinely remote — stamp `sshFs` so the editor
// node routes its read/write over the project's ControlMaster fs (local/relay projects pass false).
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index ef45282d4..d4ea26cfc 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -10,6 +10,7 @@ import { IconBellFilled, IconCircleCheck, IconPin } from './icons'
import { useProjects } from '../state/projects'
import { useAgentStatus } from '../state/agentStatus'
import { useSessionNaming } from '../state/sessionNaming'
+import { useSession } from '../session/session'
export interface SessionsSidebarProps {
open: boolean
@@ -43,6 +44,8 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
const activeProjectId = useProjects((s) => s.activeProjectId)
const statusById = useAgentStatus((s) => s.byId)
const namingById = useSessionNaming((s) => s.byId)
+ // This sidebar's core api (a stable context read — the branch lookups run on the session's git).
+ const { api } = useSession()
const [filter, setFilter] = useState('')
// Explicit per-project collapse choices (true = collapsed, false = expanded). Absent =
@@ -72,7 +75,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
let cancelled = false
projects.forEach((p) => {
if (!p.cwd || branches[p.id] !== undefined) return
- window.nodeTerminal.git
+ api.git
.status(p.cwd)
.then((st) => {
if (cancelled) return
@@ -86,7 +89,9 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
return () => {
cancelled = true
}
- }, [open, projects, branches])
+ // `api` is a safe dep: this effect only fetches (cancellation flag, no resource), and the
+ // local session's api is referentially stable, so adding it changes nothing today.
+ }, [open, projects, branches, api])
// Gated on `open`: this component stays mounted while the sidebar is closed (the common
// case), and the O(projects × nodes) rebuild re-ran on every agent hook event otherwise.
diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsx
index 262811a28..262c52c44 100644
--- a/src/renderer/components/SourceControlPanel.tsx
+++ b/src/renderer/components/SourceControlPanel.tsx
@@ -7,6 +7,7 @@ import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
import { useSshConn } from '../state/sshConn'
import { useScmDraft } from '../state/scmDraft'
+import { useSession } from '../session/session'
import { GitHistoryPanel } from './git-history/GitHistoryPanel'
import { buildCommitMenuItems } from './git-history/git-history-menu'
import { ContextMenu, type MenuItem } from './ContextMenu'
@@ -113,7 +114,9 @@ export function SourceControlPanel({
action: 'merge' | 'rebase' | 'delete'
} | null>(null)
- const git = window.nodeTerminal.git
+ // This panel's core api (a stable context read — the local session's api IS window.nodeTerminal,
+ // so `git` keeps its identity and every hook dep array it sits in behaves exactly as before).
+ const git = useSession().api.git
const refresh = useCallback(async () => {
setStatus(cwd ? await git.status(cwd) : null)
diff --git a/src/renderer/nodes/DiffNode.tsx b/src/renderer/nodes/DiffNode.tsx
index 16ca20029..346a9654f 100644
--- a/src/renderer/nodes/DiffNode.tsx
+++ b/src/renderer/nodes/DiffNode.tsx
@@ -4,6 +4,7 @@ import { monaco } from '../editor/monaco-setup'
import { useSettings } from '../state/settings'
import { useProjects } from '../state/projects'
import { sshFs } from '../terminal/ssh-fs'
+import { useSession } from '../session/session'
import type { CanvasNode } from '../state/workspace'
import { tooLargeSize, formatBytes } from '@shared/fsLimits'
@@ -13,6 +14,11 @@ import { tooLargeSize, formatBytes } from '@shared/fsLimits'
*/
export function DiffNode({ id, data, selected }: NodeProps<CanvasNode>) {
const { deleteElements } = useReactFlow()
+ // This node's core api (a stable context read). Captured by the mount effect's CLOSURE below —
+ // deliberately NOT in its dep array: that effect creates/tears down Monaco models, and the
+ // local api is referentially stable, so re-keying the effect on it would be a silent lifecycle
+ // change armed for 4c. Task 6 precedent.
+ const { api } = useSession()
const bodyRef = useRef<HTMLDivElement>(null)
const editorRef = useRef<monaco.editor.IStandaloneDiffEditor | null>(null)
const originalRef = useRef<monaco.editor.ITextModel | null>(null)
@@ -48,7 +54,7 @@ export function DiffNode({ id, data, selected }: NodeProps<CanvasNode>) {
let original: monaco.editor.ITextModel | null = null
let modified: monaco.editor.ITextModel | null = null
- const git = window.nodeTerminal.git
+ const git = api.git
const abs = `${cwd}/${rel}`
// SSH project: `git.showFile` already routes remotely (Task 2 chokepoint), but the working-tree
// side is a raw fs read — for an SSH project (active project has `ssh`) read it over the master
@@ -57,7 +63,7 @@ export function DiffNode({ id, data, selected }: NodeProps<CanvasNode>) {
const sshProjectId = projState.getProject(projState.activeProjectId)?.ssh
? projState.activeProjectId
: null
- const workingFs = sshProjectId ? sshFs(sshProjectId) : window.nodeTerminal.fs
+ const workingFs = sshProjectId ? sshFs(sshProjectId) : api.fs
// commit mode: parent (<oid>^) vs commit (<oid>). staged: HEAD vs index. unstaged: index vs working.
const origP = commitOid
? git.showFile(cwd, `${commitOid}^`, rel)
diff --git a/src/renderer/nodes/EditorNode.tsx b/src/renderer/nodes/EditorNode.tsx
index c0839b6ab..feee45275 100644
--- a/src/renderer/nodes/EditorNode.tsx
+++ b/src/renderer/nodes/EditorNode.tsx
@@ -6,6 +6,7 @@ import { useSettings } from '../state/settings'
import { remoteFs } from '../terminal/remote-fs'
import { sshFs } from '../terminal/ssh-fs'
import { useProjects } from '../state/projects'
+import { useSession } from '../session/session'
import type { CanvasNode } from '../state/workspace'
import { tooLargeSize, formatBytes } from '@shared/fsLimits'
@@ -45,16 +46,19 @@ export function EditorNode({ id, data, selected }: NodeProps<CanvasNode>) {
// Set by a worktree removal sweep (`displacedByWorktree` / `resetDisplacedCwd` in Canvas.tsx):
// this file no longer exists, and unlike a terminal's cwd there is nothing to re-point it at.
const fileMissing = !!data.fileMissing
+ // This node's core api (a stable context read — the local session's api IS window.nodeTerminal).
+ const { api } = useSession()
// Backend pick (the `FsApi` shape is identical across all three, so the rest of the component is
// unchanged): a relay session operates on the HOST's filesystem via the relay; an SSH-project
- // editor (`data.sshFs`) on the project's remote fs over the ControlMaster; otherwise the local fs.
+ // editor (`data.sshFs`) on the project's remote fs over the ControlMaster; otherwise the
+ // session's fs.
const activeProjectId = useProjects((s) => s.activeProjectId)
const connectionId = data.remote?.connectionId
const fs = connectionId
? remoteFs(connectionId)
: data.sshFs && activeProjectId
? sshFs(activeProjectId)
- : window.nodeTerminal.fs
+ : api.fs
const fileName = filePath.split('/').pop() || 'untitled'
const ext = fileName.includes('.') ? fileName.split('.').pop()!.toLowerCase() : ''
const isImage = ext in IMAGE_MIME
diff --git a/src/renderer/state/scmDraft.ts b/src/renderer/state/scmDraft.ts
index efbaf1bd6..38a78b1a6 100644
--- a/src/renderer/state/scmDraft.ts
+++ b/src/renderer/state/scmDraft.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { activeSessionApi } from '../session/session'
/**
* Per-repo Source Control draft state — the commit message and the in-flight "generate"
@@ -31,7 +32,9 @@ export const useScmDraft = create<ScmDraftState>((set, get) => ({
errors: { ...s.errors, [cwd]: '' }
}))
try {
- const r = await window.nodeTerminal.git.generateMessage(cwd)
+ // Non-component consumer: git comes from the ACTIVE session's core (the local session's
+ // api is `window.nodeTerminal` by identity — same function reference as before Stage 4).
+ const r = await activeSessionApi().git.generateMessage(cwd)
set((s) => ({
generating: { ...s.generating, [cwd]: false },
...(r.ok
diff --git a/src/renderer/state/worktrees.test.ts b/src/renderer/state/worktrees.test.ts
index b0b02832e..db6d3c676 100644
--- a/src/renderer/state/worktrees.test.ts
+++ b/src/renderer/state/worktrees.test.ts
@@ -1,5 +1,7 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
import { useWorktrees, WORKTREE_STATUS_THROTTLE_MS } from './worktrees'
+import { createSession, resetSessionsForTest, setActiveSession } from '../session/session'
+import type { NodeTerminalApi } from '@shared/types'
/** A `git status` on a healthy worktree, with only the fields the store reads spelled out. */
const okStatus = (over: Partial<Record<string, unknown>> = {}): unknown => ({
@@ -32,6 +34,12 @@ beforeEach(() => {
gitMock.status.mockReset()
// Test double for the preload/bridge API (the vitest env is `node`, so there is no real window).
;(globalThis as { window?: unknown }).window = { nodeTerminal: { git: gitMock } }
+ // The store reads git through the ACTIVE SESSION's api (Stage 4), so register a session whose
+ // api carries the same git mock. Store construction touches no wire, so this is free.
+ resetSessionsForTest()
+ setActiveSession(
+ createSession('local', { git: gitMock } as unknown as NodeTerminalApi, 'test').id
+ )
useWorktrees.getState().reset()
})
@@ -696,3 +704,29 @@ describe('useWorktrees.refresh interleaving without reset', () => {
])
})
})
+
+describe('session routing (Stage 4)', () => {
+ // The store is a NON-COMPONENT consumer: it must reach git through the active session's api
+ // (`activeSessionApi().git`), never through the `window.nodeTerminal` global — a remote tab's
+ // worktree facts must come from the remote core. The window stub here carries DIFFERENT spies
+ // than the session api, so the two paths are distinguishable.
+ it('reads git through the active session api, not the window global', async () => {
+ const windowGit = {
+ repoRoot: vi.fn(async () => '/repo'),
+ worktreeList: vi.fn(async () => listed([])),
+ status: vi.fn(async () => okStatus())
+ }
+ ;(globalThis as { window?: unknown }).window = { nodeTerminal: { git: windowGit } }
+ gitMock.status.mockResolvedValue(okStatus())
+ gitMock.repoRoot.mockResolvedValue('/repo')
+ gitMock.worktreeList.mockResolvedValue(listed([]))
+
+ await useWorktrees.getState().refreshStatus('/wt/feat', 'g1')
+ await useWorktrees.getState().refresh('/repo', [])
+
+ expect(gitMock.status).toHaveBeenCalledWith('/wt/feat')
+ expect(gitMock.repoRoot).toHaveBeenCalledWith('/repo')
+ expect(windowGit.status).not.toHaveBeenCalled()
+ expect(windowGit.repoRoot).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/renderer/state/worktrees.ts b/src/renderer/state/worktrees.ts
index c73e1ed8c..be54f6a11 100644
--- a/src/renderer/state/worktrees.ts
+++ b/src/renderer/state/worktrees.ts
@@ -1,4 +1,5 @@
import { create } from 'zustand'
+import { activeSessionApi } from '../session/session'
import {
normWorktreePath,
reconcileWorktrees,
@@ -121,7 +122,10 @@ export const useWorktrees = create<WorktreesState>((set) => ({
// After bumping, capture the new epoch so this refresh knows if it was superseded.
epoch++
const mineEpoch = epoch
- const git = window.nodeTerminal.git
+ // Non-component consumer: git comes from the ACTIVE session's core (resolved per call, not at
+ // module load — the local session's api is `window.nodeTerminal` by identity, so this is the
+ // same function reference as before Stage 4).
+ const git = activeSessionApi().git
try {
const root = await git.repoRoot(projectCwd)
if (mineEpoch !== epoch) return
@@ -200,9 +204,10 @@ export const useWorktrees = create<WorktreesState>((set) => ({
const prev = lastStatusAt.get(path) ?? 0
if (now - prev < WORKTREE_STATUS_THROTTLE_MS) return
lastStatusAt.set(path, now)
- let status: Awaited<ReturnType<typeof window.nodeTerminal.git.status>>
+ const git = activeSessionApi().git
+ let status: Awaited<ReturnType<typeof git.status>>
try {
- status = await window.nodeTerminal.git.status(path)
+ status = await git.status(path)
} catch {
// Un-stamp, or a transient failure would lock the chip out of retrying for the whole window.
if (lastStatusAt.get(path) === now) lastStatusAt.delete(path)