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.

Add projects, tmux session continuity, settings, and source control

enese1c895142b92
diff --git a/package-lock.json b/package-lock.json
index 71683424e..870511d09 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,16 +1,17 @@
{
- "name": "nodebasedterminal",
+ "name": "node-terminal",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
- "name": "nodebasedterminal",
+ "name": "node-terminal",
"version": "0.1.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
- "node-pty": "^1.0.0"
+ "node-pty": "^1.0.0",
+ "zustand": "^4.5.7"
},
"devDependencies": {
"@electron/rebuild": "^3.6.0",
@@ -1511,14 +1512,14 @@
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.31",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.31.tgz",
"integrity": "sha512-vfEqpXTvwT91yhmwdfouStN2hSKwTvyRs8qpLfADyrq/kxDw0hZM7Wk9Ug1FELj8hIby+S/+kQCSRFF32nv2Qw==",
- "dev": true,
+ "devOptional": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
@@ -2113,7 +2114,7 @@
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
- "dev": true,
+ "devOptional": true,
"license": "MIT"
},
"node_modules/d3-color": {
@@ -3005,7 +3006,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
- "dev": true,
"license": "MIT"
},
"node_modules/jsesc": {
@@ -3093,7 +3093,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
- "dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
@@ -3674,7 +3673,6 @@
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
@@ -4301,7 +4299,6 @@
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
"integrity": "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w==",
- "dev": true,
"license": "MIT",
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
@@ -4486,7 +4483,6 @@
"version": "4.5.7",
"resolved": "https://registry.npmjs.org/zustand/-/zustand-4.5.7.tgz",
"integrity": "sha512-CHOUy7mu3lbD6o6LJLfllpjkzhHXSBlX8B9+qPddUsIfeF5S/UZ5q0kmCsnRqT1UHFQZchNFDDzMbQsuesHWlw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"use-sync-external-store": "^1.2.2"
diff --git a/package.json b/package.json
index 0fc848574..c185757fa 100644
--- a/package.json
+++ b/package.json
@@ -15,7 +15,8 @@
"postinstall": "electron-rebuild -f -w node-pty"
},
"dependencies": {
- "node-pty": "^1.0.0"
+ "node-pty": "^1.0.0",
+ "zustand": "^4.5.7"
},
"devDependencies": {
"@electron/rebuild": "^3.6.0",
diff --git a/src/main/commit-message.ts b/src/main/commit-message.ts
new file mode 100644
index 000000000..48233f6ad
--- /dev/null
+++ b/src/main/commit-message.ts
@@ -0,0 +1,234 @@
+import { execFile, execFileSync, spawn } from 'child_process'
+import fs from 'fs'
+import os from 'os'
+import { promisify } from 'util'
+import type { GitResult, Settings } from '../shared/types'
+
+const run = promisify(execFile)
+
+const STAGED_DIFF_BYTE_BUDGET = 200_000
+const OUTPUT_LIMIT = 64_000
+const TIMEOUT_MS = 120_000
+
+const bytes = (s: string) => Buffer.byteLength(s, 'utf-8')
+
+/** Resolve a CLI binary to an absolute path (GUI apps don't inherit the shell PATH). */
+function resolveBinary(name: string): string | null {
+ if (name.startsWith('/')) return fs.existsSync(name) ? name : null
+ const candidates = [
+ `${os.homedir()}/.local/bin/${name}`,
+ `${os.homedir()}/.claude/local/${name}`,
+ `/opt/homebrew/bin/${name}`,
+ `/usr/local/bin/${name}`,
+ `/usr/bin/${name}`
+ ]
+ for (const c of candidates) {
+ try {
+ if (fs.existsSync(c)) return c
+ } catch {
+ // ignore
+ }
+ }
+ try {
+ const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', `command -v ${name}`], {
+ encoding: 'utf-8'
+ }).trim()
+ if (out) return out
+ } catch {
+ // ignore
+ }
+ return null
+}
+
+async function git(cwd: string, args: string[]): Promise<string> {
+ try {
+ const { stdout } = await run('git', args, { cwd, maxBuffer: 50 * 1024 * 1024 })
+ return stdout
+ } catch {
+ return ''
+ }
+}
+
+/**
+ * Split a unified diff into per-file chunks (each starting at a `diff --git` header) and
+ * fairly distribute a byte budget across them ("water-filling"), so one giant generated
+ * file (lockfile etc.) can't starve the human-written changes. Each cut is on a line
+ * boundary with a marker; the agent never sees a half line.
+ */
+function truncateDiffForPrompt(diff: string, budget: number): string {
+ if (bytes(diff) <= budget) return diff
+
+ const chunks: string[] = []
+ const re = /(^|\n)(diff --git )/g
+ let lastIndex = 0
+ let m: RegExpExecArray | null
+ const starts: number[] = []
+ while ((m = re.exec(diff))) starts.push(m.index + (m[1] ? 1 : 0))
+ if (starts.length === 0) return capAtLine(diff, budget)
+ for (let i = 0; i < starts.length; i++) {
+ chunks.push(diff.slice(starts[i], i + 1 < starts.length ? starts[i + 1] : diff.length))
+ }
+ lastIndex = starts[0]
+ const preamble = diff.slice(0, lastIndex)
+
+ // Water-fill: smallest files first take their full size; the rest share what remains.
+ let remaining = budget - bytes(preamble)
+ let left = chunks.length
+ const caps = new Array<number>(chunks.length)
+ chunks
+ .map((c, i) => ({ i, size: bytes(c) }))
+ .sort((a, b) => a.size - b.size)
+ .forEach(({ i, size }) => {
+ const share = Math.max(0, Math.floor(remaining / Math.max(1, left)))
+ const take = Math.min(size, share)
+ caps[i] = take
+ remaining -= take
+ left--
+ })
+
+ return preamble + chunks.map((c, i) => capAtLine(c, caps[i])).join('')
+}
+
+function capAtLine(text: string, cap: number): string {
+ if (bytes(text) <= cap) return text
+ let cut = Buffer.from(text, 'utf-8').slice(0, Math.max(0, cap)).toString('utf-8')
+ const nl = cut.lastIndexOf('\n')
+ if (nl > 0) cut = cut.slice(0, nl)
+ const omitted = bytes(text) - bytes(cut)
+ return `${cut}\n...(diff truncated, ${omitted} bytes omitted)\n`
+}
+
+function buildPrompt(diff: string, files: string, extra: string): string {
+ const base = `Write a git commit message for the staged changes below.
+Output ONLY the commit message - no preamble, no code fences, no quotes.
+Use a concise subject line of at most 72 characters; if useful, add a blank line then a short body.
+Do not include "Co-authored-by" trailers.`
+ const body = diff
+ ? `\n\nStaged diff:\n\`\`\`diff\n${diff}\n\`\`\``
+ : `\n\nStaged files (diff omitted due to size):\n${files}`
+ const suffix = extra.trim() ? `\n\nAdditional user prompt:\n${extra.trim()}` : ''
+ return base + body + suffix
+}
+
+/** Split a command template into tokens (quote-aware, NO shell expansion). */
+function tokenize(cmd: string): string[] {
+ const out: string[] = []
+ const re = /"([^"]*)"|'([^']*)'|(\S+)/g
+ let m: RegExpExecArray | null
+ while ((m = re.exec(cmd))) out.push(m[1] ?? m[2] ?? m[3])
+ return out
+}
+
+interface Plan {
+ bin: string
+ args: string[]
+ stdin: string | null
+}
+
+function planAgent(settings: Settings, prompt: string): Plan | { error: string } {
+ if (settings.commitAgent === 'custom') {
+ const tokens = tokenize(settings.commitAgentCommand)
+ if (tokens.length === 0) return { error: 'No custom commit command set (Settings → Commit messages).' }
+ const bin = resolveBinary(tokens[0])
+ if (!bin) return { error: `Command "${tokens[0]}" not found.` }
+ const rest = tokens.slice(1)
+ if (rest.includes('{prompt}')) {
+ return { bin, args: rest.map((t) => (t === '{prompt}' ? prompt : t)), stdin: null }
+ }
+ return { bin, args: rest, stdin: prompt }
+ }
+ if (settings.commitAgent === 'codex') {
+ const bin = resolveBinary('codex')
+ if (!bin) return { error: 'codex CLI not found.' }
+ return { bin, args: ['exec', '--sandbox', 'read-only'], stdin: prompt }
+ }
+ const bin = resolveBinary('claude')
+ if (!bin) return { error: 'claude CLI not found. Install Claude Code or pick another agent in Settings.' }
+ return { bin, args: ['-p', '--permission-mode', 'plan'], stdin: prompt }
+}
+
+function spawnAgent(
+ bin: string,
+ args: string[],
+ cwd: string,
+ stdin: string | null
+): Promise<{ code: number; stdout: string; stderr: string }> {
+ return new Promise((resolve) => {
+ const child = spawn(bin, args, {
+ cwd,
+ env: process.env,
+ stdio: ['pipe', 'pipe', 'pipe'],
+ windowsHide: true
+ })
+ let stdout = ''
+ let stderr = ''
+ const timer = setTimeout(() => child.kill('SIGKILL'), TIMEOUT_MS)
+ child.stdout.on('data', (d) => {
+ if (stdout.length < OUTPUT_LIMIT) stdout += d.toString()
+ })
+ child.stderr.on('data', (d) => {
+ if (stderr.length < OUTPUT_LIMIT) stderr += d.toString()
+ })
+ child.on('error', (e) => {
+ clearTimeout(timer)
+ resolve({ code: 1, stdout, stderr: stderr || String(e) })
+ })
+ child.on('close', (code) => {
+ clearTimeout(timer)
+ resolve({ code: code ?? 1, stdout, stderr })
+ })
+ if (stdin !== null) {
+ child.stdin.write(stdin)
+ child.stdin.end()
+ }
+ })
+}
+
+// eslint-disable-next-line no-control-regex
+const ANSI = /\[[0-9;]*m/g
+
+/** Strip CLI noise (ANSI, status lines, wrapping fence, quotes) to leave the message. */
+function cleanMessage(raw: string): string {
+ let s = raw.replace(ANSI, '').trim()
+ const fence = s.match(/^```[a-zA-Z]*\n([\s\S]*?)\n```$/)
+ if (fence) s = fence[1].trim()
+ const noise = /^(generating|thinking|loading|analyzing|working|reading|here'?s|sure[,.!]?|okay|certainly|i'?ll|let me)\b/i
+ const lines = s.split('\n')
+ while (lines.length && noise.test(lines[0].trim())) lines.shift()
+ s = lines.join('\n').trim()
+ s = s.replace(/^["'`]+/, '').replace(/["'`]+$/, '').trim()
+ return s
+}
+
+function extractError(text: string): string {
+ const lines = text
+ .replace(ANSI, '')
+ .split('\n')
+ .map((l) => l.trim())
+ .filter(Boolean)
+ const meaningful = lines.reverse().find((l) => /error|fail|denied|not found|429|unauthor/i.test(l))
+ return meaningful || lines[0] || 'Agent produced no output.'
+}
+
+/** Orchestrates: staged diff -> budget -> prompt -> read-only agent spawn -> clean message. */
+export async function generateCommitMessage(cwd: string, settings: Settings): Promise<GitResult> {
+ if (!cwd) return { ok: false, message: 'No project folder set.' }
+
+ const names = (await git(cwd, ['diff', '--cached', '--name-status'])).trim()
+ if (!names) return { ok: false, message: 'No staged changes. Stage files first.' }
+
+ const rawDiff = await git(cwd, ['diff', '--cached', '--patch', '--minimal'])
+ const diff = rawDiff ? truncateDiffForPrompt(rawDiff, STAGED_DIFF_BYTE_BUDGET) : ''
+ const prompt = buildPrompt(diff, names, settings.commitExtraPrompt)
+
+ const plan = planAgent(settings, prompt)
+ if ('error' in plan) return { ok: false, message: plan.error }
+
+ const res = await spawnAgent(plan.bin, plan.args, cwd, plan.stdin)
+ const message = cleanMessage(res.stdout)
+ if (res.code !== 0 && !message) {
+ return { ok: false, message: extractError(res.stderr || res.stdout) }
+ }
+ if (!message) return { ok: false, message: 'Agent produced no commit message.' }
+ return { ok: true, message }
+}
diff --git a/src/main/git-service.ts b/src/main/git-service.ts
new file mode 100644
index 000000000..e081f3ef8
Binary files /dev/null and b/src/main/git-service.ts differ
diff --git a/src/main/index.ts b/src/main/index.ts
index c911bddd5..8c16a48da 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -1,18 +1,27 @@
import { join } from 'path'
-import { app, BrowserWindow, shell } from 'electron'
+import { app, BrowserWindow, dialog, ipcMain, shell } from 'electron'
+import { IPC } from '../shared/ipc'
import { PtyManager } from './pty-manager'
import { WorkspaceStore } from './workspace-store'
+import { SettingsStore } from './settings-store'
+import { GitService } from './git-service'
+import { generateCommitMessage } from './commit-message'
+const settingsStore = new SettingsStore()
const ptyManager = new PtyManager()
const workspaceStore = new WorkspaceStore()
+const gitService = new GitService()
function createWindow(): void {
const win = new BrowserWindow({
width: 1400,
height: 900,
show: false,
- backgroundColor: '#11131a',
+ backgroundColor: '#1e1e1e',
title: 'node-terminal',
+ // Integrate the macOS traffic lights into our top bar (modern Mac app look).
+ titleBarStyle: 'hiddenInset',
+ trafficLightPosition: { x: 16, y: 15 },
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
contextIsolation: true,
@@ -38,8 +47,22 @@ function createWindow(): void {
}
app.whenReady().then(() => {
+ settingsStore.init()
+ settingsStore.registerIpc()
+ ptyManager.init(() => settingsStore.get())
ptyManager.registerIpc()
workspaceStore.registerIpc()
+ gitService.registerIpc()
+
+ ipcMain.handle(IPC.commitGenerate, (_e, cwd: string) =>
+ generateCommitMessage(cwd, settingsStore.get())
+ )
+
+ ipcMain.handle(IPC.dialogSelectFolder, async () => {
+ const result = await dialog.showOpenDialog({ properties: ['openDirectory', 'createDirectory'] })
+ return result.canceled || result.filePaths.length === 0 ? null : result.filePaths[0]
+ })
+
createWindow()
app.on('activate', () => {
diff --git a/src/main/pty-manager.ts b/src/main/pty-manager.ts
index de2951013..79d29a546 100644
--- a/src/main/pty-manager.ts
+++ b/src/main/pty-manager.ts
@@ -1,22 +1,89 @@
import os from 'os'
-import { ipcMain, webContents } from 'electron'
+import fs from 'fs'
+import path from 'path'
+import { execFileSync } from 'child_process'
+import { app, ipcMain, webContents } from 'electron'
import * as pty from 'node-pty'
import { IPC } from '../shared/ipc'
-import type { PtyCreateOptions } from '../shared/types'
+import { DEFAULT_SETTINGS, type PtyCreateOptions, type Settings } from '../shared/types'
+
+// A dedicated tmux socket isolates our sessions from the user's own tmux server.
+const TMUX_SOCKET = 'node-terminal'
+
+// Minimal tmux config so the user's ~/.tmux.conf never interferes. The tmux server
+// (under our socket) keeps sessions alive while no client is attached, which is what
+// gives us continuity across node remounts and full app restarts.
+function tmuxConf(scrollback: number): string {
+ return `# auto-generated by node-terminal — do not edit
+set -g status off
+set -g mouse on
+set -g history-limit ${Math.max(1000, scrollback)}
+set -g default-terminal "xterm-256color"
+set -sg escape-time 10
+set -g destroy-unattached off
+setw -g aggressive-resize on
+`
+}
+
+/** Resolve an absolute tmux path (GUI apps don't inherit the shell PATH). */
+function findTmux(): string | null {
+ for (const c of ['/opt/homebrew/bin/tmux', '/usr/local/bin/tmux', '/usr/bin/tmux', '/bin/tmux']) {
+ try {
+ if (fs.existsSync(c)) return c
+ } catch {
+ // ignore
+ }
+ }
+ try {
+ const out = execFileSync(process.env.SHELL || '/bin/bash', ['-lc', 'command -v tmux'], {
+ encoding: 'utf-8'
+ }).trim()
+ if (out) return out
+ } catch {
+ // ignore
+ }
+ return null
+}
+
+/** tmux session names may not contain '.', ':' or whitespace. */
+function sessionName(persistKey: string): string {
+ return `nt-${persistKey.replace(/[^a-zA-Z0-9_-]/g, '_')}`
+}
interface Session {
proc: pty.IPty
- /** The renderer we send output back to. */
webContentsId: number
}
/**
* Manages all live PTY processes and bridges them to the renderer over IPC.
- * The renderer never touches node-pty directly; everything goes through this class.
+ *
+ * On macOS/Linux with tmux available, each terminal node attaches to a persistent
+ * tmux session named after its node id (`tmux new-session -A`). Closing a node's
+ * window only detaches the client — the tmux session (and everything running in it)
+ * survives, so reopening the node or restarting the app reattaches and continues
+ * where it left off. Without tmux, it falls back to a plain shell (no persistence).
*/
export class PtyManager {
private sessions = new Map<string, Session>()
private counter = 0
+ private tmuxPath: string | null = null
+ private confPath = ''
+ private getSettings: () => Settings = () => DEFAULT_SETTINGS
+
+ /** Must run after app is ready (needs userData path). */
+ init(getSettings: () => Settings): void {
+ this.getSettings = getSettings
+ this.tmuxPath = findTmux()
+ if (!this.tmuxPath) return
+ this.confPath = path.join(app.getPath('userData'), 'tmux.conf')
+ try {
+ fs.writeFileSync(this.confPath, tmuxConf(getSettings().tmuxScrollback))
+ } catch {
+ // If we can't write the config, disable tmux and fall back to a plain shell.
+ this.tmuxPath = null
+ }
+ }
registerIpc(): void {
ipcMain.handle(IPC.ptyCreate, (event, options: PtyCreateOptions) =>
@@ -29,19 +96,57 @@ export class PtyManager {
this.resize(sessionId, cols, rows)
)
ipcMain.on(IPC.ptyKill, (_event, sessionId: string) => this.kill(sessionId))
+ ipcMain.on(IPC.ptyDestroy, (_event, persistKey: string) => this.destroySession(persistKey))
}
private create(webContentsId: number, options: PtyCreateOptions): string {
const sessionId = `pty-${++this.counter}`
- const shell =
- options.shell || process.env.SHELL || (os.platform() === 'win32' ? 'powershell.exe' : 'bash')
+ const cwd = options.cwd || os.homedir()
+
+ // Strip TMUX so tmux doesn't refuse to nest if the app itself was launched
+ // from inside a tmux session.
+ const env = { ...process.env, TERM: 'xterm-256color' } as Record<string, string>
+ delete env.TMUX
+ delete env.TMUX_PANE
- const proc = pty.spawn(shell, [], {
- name: 'xterm-color',
+ const settings = this.getSettings()
+ let file: string
+ let args: string[]
+
+ if (this.tmuxPath && settings.tmuxEnabled && options.persistKey) {
+ // attach-or-create the persistent session for this node; -D detaches any stale client.
+ file = this.tmuxPath
+ args = [
+ '-L',
+ TMUX_SOCKET,
+ '-f',
+ this.confPath,
+ 'new-session',
+ '-A',
+ '-D',
+ '-c',
+ cwd,
+ '-s',
+ sessionName(options.persistKey)
+ ]
+ // Honor a custom default shell at session creation (ignored on reattach).
+ const shell = options.shell || settings.defaultShell
+ if (shell) args.push(shell)
+ } else {
+ file =
+ options.shell ||
+ settings.defaultShell ||
+ process.env.SHELL ||
+ (os.platform() === 'win32' ? 'powershell.exe' : 'bash')
+ args = []
+ }
+
+ const proc = pty.spawn(file, args, {
+ name: 'xterm-256color',
cols: options.cols,
rows: options.rows,
- cwd: options.cwd || os.homedir(),
- env: process.env as Record<string, string>
+ cwd,
+ env
})
proc.onData((data) => {
@@ -68,6 +173,10 @@ export class PtyManager {
session.proc.resize(Math.max(1, cols), Math.max(1, rows))
}
+ /**
+ * Detach the client. With tmux this only kills our client process; the tmux
+ * session keeps running so it can be reattached later.
+ */
kill(sessionId: string): void {
const session = this.sessions.get(sessionId)
if (!session) return
@@ -75,7 +184,22 @@ export class PtyManager {
this.sessions.delete(sessionId)
}
- /** Terminate all processes when the app quits. */
+ /** Permanently end a node's persistent tmux session (called when the user closes it). */
+ destroySession(persistKey: string): void {
+ if (!this.tmuxPath) return
+ try {
+ execFileSync(this.tmuxPath, ['-L', TMUX_SOCKET, 'kill-session', '-t', sessionName(persistKey)], {
+ stdio: 'ignore'
+ })
+ } catch {
+ // session may not exist; ignore
+ }
+ }
+
+ /**
+ * On quit, detach all clients (do NOT kill tmux sessions — that's the whole point
+ * of persistence). The tmux server keeps the sessions alive for next launch.
+ */
killAll(): void {
for (const { proc } of this.sessions.values()) proc.kill()
this.sessions.clear()
diff --git a/src/main/settings-store.ts b/src/main/settings-store.ts
new file mode 100644
index 000000000..e403aa740
--- /dev/null
+++ b/src/main/settings-store.ts
@@ -0,0 +1,39 @@
+import { promises as fs, readFileSync } from 'fs'
+import path from 'path'
+import { app, ipcMain } from 'electron'
+import { IPC } from '../shared/ipc'
+import { DEFAULT_SETTINGS, type Settings } from '../shared/types'
+
+/**
+ * Stores user settings in settings.json. Keeps a synchronous cache so the PtyManager
+ * can read shell/tmux preferences immediately at terminal creation.
+ */
+export class SettingsStore {
+ private cache: Settings = DEFAULT_SETTINGS
+
+ private get filePath(): string {
+ return path.join(app.getPath('userData'), 'settings.json')
+ }
+
+ /** Load synchronously into cache (call after app is ready). */
+ init(): void {
+ try {
+ const raw = readFileSync(this.filePath, 'utf-8')
+ this.cache = { ...DEFAULT_SETTINGS, ...JSON.parse(raw) }
+ } catch {
+ this.cache = DEFAULT_SETTINGS
+ }
+ }
+
+ get(): Settings {
+ return this.cache
+ }
+
+ registerIpc(): void {
+ ipcMain.handle(IPC.settingsLoad, () => this.cache)
+ ipcMain.handle(IPC.settingsSave, async (_e, settings: Settings) => {
+ this.cache = { ...DEFAULT_SETTINGS, ...settings }
+ await fs.writeFile(this.filePath, JSON.stringify(this.cache, null, 2), 'utf-8')
+ })
+ }
+}
diff --git a/src/main/workspace-store.ts b/src/main/workspace-store.ts
index 7cca43072..df13a36b1 100644
--- a/src/main/workspace-store.ts
+++ b/src/main/workspace-store.ts
@@ -2,11 +2,16 @@ import { promises as fs } from 'fs'
import path from 'path'
import { app, ipcMain } from 'electron'
import { IPC } from '../shared/ipc'
-import { EMPTY_WORKSPACE, type Workspace } from '../shared/types'
+import {
+ DEFAULT_PROJECT_ID,
+ EMPTY_WORKSPACE,
+ type Workspace,
+ type WorkspaceV1
+} from '../shared/types'
/**
* Stores the workspace JSON in the user's userData directory.
- * MVP keeps a single workspace file: workspace.json
+ * A single file (workspace.json) holds all projects.
*/
export class WorkspaceStore {
private get filePath(): string {
@@ -21,9 +26,7 @@ export class WorkspaceStore {
async load(): Promise<Workspace> {
try {
const raw = await fs.readFile(this.filePath, 'utf-8')
- const parsed = JSON.parse(raw) as Workspace
- if (parsed?.version === 1 && Array.isArray(parsed.nodes)) return parsed
- return EMPTY_WORKSPACE
+ return migrate(JSON.parse(raw))
} catch {
// Missing or corrupt file -> return an empty workspace.
return EMPTY_WORKSPACE
@@ -34,3 +37,34 @@ export class WorkspaceStore {
await fs.writeFile(this.filePath, JSON.stringify(workspace, null, 2), 'utf-8')
}
}
+
+/** Normalize any on-disk shape (v1 single canvas, v2 projects) into a valid v2 workspace. */
+function migrate(parsed: unknown): Workspace {
+ const ws = parsed as Partial<Workspace> & Partial<WorkspaceV1>
+
+ if (ws?.version === 2 && Array.isArray(ws.projects) && ws.projects.length > 0) {
+ const active = ws.projects.some((p) => p.id === ws.activeProjectId)
+ ? (ws.activeProjectId as string)
+ : ws.projects[0].id
+ return { version: 2, activeProjectId: active, projects: ws.projects }
+ }
+
+ // v1: a single canvas -> wrap it in one default project.
+ if (ws?.version === 1 && Array.isArray(ws.nodes)) {
+ return {
+ version: 2,
+ activeProjectId: DEFAULT_PROJECT_ID,
+ projects: [
+ {
+ id: DEFAULT_PROJECT_ID,
+ name: 'Project 1',
+ color: '#7aa2f7',
+ viewport: ws.viewport ?? { x: 0, y: 0, zoom: 1 },
+ nodes: ws.nodes
+ }
+ ]
+ }
+ }
+
+ return EMPTY_WORKSPACE
+}
diff --git a/src/preload/index.ts b/src/preload/index.ts
index ed4d0b3ee..28a7efff4 100644
--- a/src/preload/index.ts
+++ b/src/preload/index.ts
@@ -12,6 +12,7 @@ const api: NodeTerminalApi = {
write: (sessionId, data) => ipcRenderer.send(IPC.ptyWrite, sessionId, data),
resize: (sessionId, cols, rows) => ipcRenderer.send(IPC.ptyResize, sessionId, cols, rows),
kill: (sessionId) => ipcRenderer.send(IPC.ptyKill, sessionId),
+ destroy: (persistKey) => ipcRenderer.send(IPC.ptyDestroy, persistKey),
onData: (sessionId, listener) => {
const channel = IPC.ptyData(sessionId)
const handler = (_e: unknown, data: string) => listener(data)
@@ -28,6 +29,32 @@ const api: NodeTerminalApi = {
workspace: {
load: () => ipcRenderer.invoke(IPC.workspaceLoad),
save: (workspace: Workspace) => ipcRenderer.invoke(IPC.workspaceSave, workspace)
+ },
+ dialog: {
+ selectFolder: () => ipcRenderer.invoke(IPC.dialogSelectFolder)
+ },
+ settings: {
+ load: () => ipcRenderer.invoke(IPC.settingsLoad),
+ save: (settings) => ipcRenderer.invoke(IPC.settingsSave, settings)
+ },
+ git: {
+ status: (cwd) => ipcRenderer.invoke(IPC.gitStatus, cwd),
+ init: (cwd) => ipcRenderer.invoke(IPC.gitInit, cwd),
+ commit: (cwd, message) => ipcRenderer.invoke(IPC.gitCommit, cwd, message),
+ push: (cwd) => ipcRenderer.invoke(IPC.gitPush, cwd),
+ pull: (cwd) => ipcRenderer.invoke(IPC.gitPull, cwd),
+ sync: (cwd) => ipcRenderer.invoke(IPC.gitSync, cwd),
+ publish: (cwd, name, isPrivate) => ipcRenderer.invoke(IPC.gitPublish, cwd, name, isPrivate),
+ stage: (cwd, paths) => ipcRenderer.invoke(IPC.gitStage, cwd, paths),
+ unstage: (cwd, paths) => ipcRenderer.invoke(IPC.gitUnstage, cwd, paths),
+ stageAll: (cwd) => ipcRenderer.invoke(IPC.gitStageAll, cwd),
+ unstageAll: (cwd) => ipcRenderer.invoke(IPC.gitUnstageAll, cwd),
+ diff: (cwd, path, staged, untracked) =>
+ ipcRenderer.invoke(IPC.gitDiff, cwd, path, staged, untracked),
+ discard: (cwd, path, untracked) => ipcRenderer.invoke(IPC.gitDiscard, cwd, path, untracked),
+ switchBranch: (cwd, name) => ipcRenderer.invoke(IPC.gitSwitchBranch, cwd, name),
+ createBranch: (cwd, name) => ipcRenderer.invoke(IPC.gitCreateBranch, cwd, name),
+ generateMessage: (cwd) => ipcRenderer.invoke(IPC.commitGenerate, cwd)
}
}
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 64495c586..937452af7 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -3,100 +3,574 @@ import {
Background,
BackgroundVariant,
Controls,
+ MiniMap,
ReactFlow,
useNodesState,
useReactFlow,
type Viewport
} from '@xyflow/react'
+import type { Node } from '@xyflow/react'
import { TerminalNode } from '../nodes/TerminalNode'
+import { StickyNode } from '../nodes/StickyNode'
+import { GroupNode } from '../nodes/GroupNode'
+import { Dock } from '../components/Dock'
+import { TabBar } from '../components/TabBar'
+import { ContextMenu, type MenuItem } from '../components/ContextMenu'
+import { CommandPalette, type Command } from '../components/CommandPalette'
+import { SettingsPanel } from '../components/SettingsPanel'
+import { SourceControlPanel } from '../components/SourceControlPanel'
+import { transport } from '../terminal/local-transport'
+import { useProjects } from '../state/projects'
+import { useSettings } from '../state/settings'
import {
+ COLLAPSED_HEIGHT,
+ createStickyNode,
createTerminalNode,
- nodesToWorkspace,
- workspaceToNodes,
- type TermNode
+ flowToNodeStates,
+ groupSelectedNodes,
+ nodeStatesToFlow,
+ ungroupNodes,
+ type CanvasNode
} from '../state/workspace'
+const GRID = 24
+
export function Canvas() {
- const [nodes, setNodes, onNodesChange] = useNodesState<TermNode>([])
+ const [nodes, setNodes, onNodesChange] = useNodesState<CanvasNode>([])
const [dirty, setDirty] = useState(false)
- const [ready, setReady] = useState(false)
+ const [zoomPct, setZoomPct] = useState(100)
+ const [menu, setMenu] = useState<{ x: number; y: number; items: MenuItem[] } | null>(null)
+ const [paletteOpen, setPaletteOpen] = useState(false)
+ const [settingsOpen, setSettingsOpen] = useState(false)
+ const [scOpen, setScOpen] = useState(false)
+ const settings = useSettings((s) => s.settings)
const viewportRef = useRef<Viewport>({ x: 0, y: 0, zoom: 1 })
- const { setViewport } = useReactFlow()
+ const nodesRef = useRef<CanvasNode[]>(nodes)
+ const loadingRef = useRef(false)
+ const flowWrapRef = useRef<HTMLDivElement>(null)
+ const { setViewport, fitView, zoomIn, zoomOut, screenToFlowPosition, setCenter, getZoom } =
+ useReactFlow()
+
+ const activeProjectId = useProjects((s) => s.activeProjectId)
+ nodesRef.current = nodes
- const nodeTypes = useMemo(() => ({ terminal: TerminalNode }), [])
+ const nodeTypes = useMemo(
+ () => ({ terminal: TerminalNode, sticky: StickyNode, group: GroupNode }),
+ []
+ )
- // Load from disk on startup.
+ // 1) Load the whole workspace once and hydrate the projects store.
useEffect(() => {
let cancelled = false
+ void useSettings.getState().hydrate()
window.nodeTerminal.workspace.load().then((ws) => {
if (cancelled) return
- setNodes(workspaceToNodes(ws))
- viewportRef.current = ws.viewport
- setViewport(ws.viewport)
- setReady(true)
+ useProjects.getState().hydrate(ws)
+ // Upgrade the on-disk format (e.g. v1 -> v2 migration) right away.
+ void window.nodeTerminal.workspace.save(useProjects.getState().toWorkspace())
})
return () => {
cancelled = true
}
- }, [setNodes, setViewport])
+ }, [])
+
+ // 2) Whenever the active project changes, load its canvas into React Flow.
+ useEffect(() => {
+ if (!activeProjectId) return
+ const project = useProjects.getState().getProject(activeProjectId)
+ if (!project) return
+ loadingRef.current = true
+ setNodes(nodeStatesToFlow(project.nodes))
+ viewportRef.current = project.viewport
+ setViewport(project.viewport)
+ setZoomPct(Math.round(project.viewport.zoom * 100))
+ // Let load-induced changes settle before we start tracking edits as dirty.
+ const t = setTimeout(() => {
+ loadingRef.current = false
+ }, 0)
+ return () => clearTimeout(t)
+ }, [activeProjectId, setNodes, setViewport])
+
+ const markDirty = useCallback(() => {
+ if (!loadingRef.current) setDirty(true)
+ }, [])
- const markDirty = useCallback(() => setDirty(true), [])
+ // ---- persistence helpers ----
+ const commitActiveToStore = useCallback(() => {
+ const id = useProjects.getState().activeProjectId
+ if (id) useProjects.getState().commitCanvas(id, flowToNodeStates(nodesRef.current), viewportRef.current)
+ }, [])
+ const writeDisk = useCallback(async () => {
+ await window.nodeTerminal.workspace.save(useProjects.getState().toWorkspace())
+ setDirty(false)
+ }, [])
+
+ const persist = useCallback(async () => {
+ commitActiveToStore()
+ await writeDisk()
+ }, [commitActiveToStore, writeDisk])
+
+ // Debounced auto-save for canvas edits.
+ useEffect(() => {
+ if (!dirty) return
+ const t = setTimeout(() => void persist(), 800)
+ return () => clearTimeout(t)
+ }, [dirty, persist])
+
+ // ---- canvas interactions ----
const handleNodesChange: typeof onNodesChange = useCallback(
(changes) => {
onNodesChange(changes)
- // Position/size/removal changes count as unsaved (dirty) changes.
if (changes.some((c) => c.type !== 'select')) markDirty()
},
[onNodesChange, markDirty]
)
- const addTerminal = useCallback(() => {
- setNodes((ns) => [...ns, createTerminalNode(ns.length)])
- markDirty()
- }, [setNodes, markDirty])
+ /** Flow-space point at the center of the visible canvas (for dock-added nodes). */
+ const viewCenter = useCallback(() => {
+ const rect = flowWrapRef.current?.getBoundingClientRect()
+ if (!rect) return undefined
+ return screenToFlowPosition({ x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 })
+ }, [screenToFlowPosition])
- const save = useCallback(async () => {
- const ws = nodesToWorkspace(nodes, viewportRef.current)
- await window.nodeTerminal.workspace.save(ws)
- setDirty(false)
- }, [nodes])
+ const addTerminal = useCallback(
+ (center?: { x: number; y: number }) => {
+ const cwd = useProjects.getState().getProject(activeProjectId)?.cwd
+ setNodes((ns) => [...ns, createTerminalNode(ns.length, cwd, center ?? viewCenter())])
+ markDirty()
+ },
+ [setNodes, markDirty, activeProjectId, viewCenter]
+ )
+
+ const addSticky = useCallback(
+ (center?: { x: number; y: number }) => {
+ setNodes((ns) => [...ns, createStickyNode(ns.length, center ?? viewCenter())])
+ markDirty()
+ },
+ [setNodes, markDirty, viewCenter]
+ )
- // Color/title edits are written to nodes via updateNodeData; watch the node data
- // and mark dirty when it changes so those edits are persisted too.
+ // ---- multi-node actions (context menu) ----
+ const deleteNodes = useCallback(
+ (ids: string[]) => {
+ const set = new Set(ids)
+ nodesRef.current.forEach((n) => {
+ if (set.has(n.id) && n.type === 'terminal') transport.destroy(n.id)
+ })
+ setNodes((ns) => {
+ // Free children of any deleted group back to absolute positions.
+ const groupPos = new Map(
+ ns.filter((n) => set.has(n.id) && n.type === 'group').map((g) => [g.id, g.position])
+ )
+ return ns
+ .filter((n) => !set.has(n.id))
+ .map((n) =>
+ n.parentId && groupPos.has(n.parentId)
+ ? {
+ ...n,
+ parentId: undefined,
+ extent: undefined,
+ position: {
+ x: n.position.x + groupPos.get(n.parentId)!.x,
+ y: n.position.y + groupPos.get(n.parentId)!.y
+ }
+ }
+ : n
+ )
+ })
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
+ const groupSelection = useCallback(
+ (ids: string[]) => {
+ const groupCount = nodesRef.current.filter((n) => n.type === 'group').length
+ setNodes((ns) => groupSelectedNodes(ns as CanvasNode[], ids, groupCount))
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
+ const ungroup = useCallback(
+ (groupId: string) => {
+ setNodes((ns) => ungroupNodes(ns as CanvasNode[], groupId))
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
+ const setNodesColor = useCallback(
+ (ids: string[], color: string) => {
+ const set = new Set(ids)
+ setNodes((ns) => ns.map((n) => (set.has(n.id) ? { ...n, data: { ...n.data, color } } : n)))
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
+ const alignToGrid = useCallback(
+ (ids: string[]) => {
+ const g = useSettings.getState().settings.gridSize || GRID
+ const set = new Set(ids)
+ setNodes((ns) =>
+ ns.map((n) =>
+ set.has(n.id)
+ ? {
+ ...n,
+ position: {
+ x: Math.round(n.position.x / g) * g,
+ y: Math.round(n.position.y / g) * g
+ }
+ }
+ : n
+ )
+ )
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
+ const selectAll = useCallback(() => {
+ setNodes((ns) => ns.map((n) => ({ ...n, selected: true })))
+ }, [setNodes])
+
+ const toggleCollapseNodes = useCallback(
+ (ids: string[]) => {
+ const set = new Set(ids)
+ setNodes((ns) =>
+ ns.map((n) => {
+ if (!set.has(n.id)) return n
+ const next = !n.data.collapsed
+ const expandedHeight =
+ (n.data.expandedHeight as number) ?? n.measured?.height ?? (n.height as number) ?? 300
+ const height = next ? COLLAPSED_HEIGHT : expandedHeight
+ return {
+ ...n,
+ height,
+ style: { ...n.style, height },
+ data: { ...n.data, collapsed: next, expandedHeight }
+ }
+ })
+ )
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
+ const goToNode = useCallback(
+ (node: Node) => {
+ const w = node.measured?.width ?? (node.width as number) ?? 0
+ const h = node.measured?.height ?? (node.height as number) ?? 0
+ setCenter(node.position.x + w / 2, node.position.y + h / 2, {
+ zoom: Math.max(getZoom(), 1),
+ duration: 300
+ })
+ },
+ [setCenter, getZoom]
+ )
+
+ const onNodeDoubleClick = useCallback(
+ (_e: React.MouseEvent, node: Node) => {
+ if (useSettings.getState().settings.doubleClickFocus) goToNode(node)
+ },
+ [goToNode]
+ )
+
+ // Cmd/Ctrl+K toggles the command palette; Cmd/Ctrl+, opens settings.
useEffect(() => {
- if (ready) markDirty()
- // only when data references change
+ const onKey = (e: KeyboardEvent) => {
+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'k') {
+ e.preventDefault()
+ setPaletteOpen((v) => !v)
+ } else if ((e.metaKey || e.ctrlKey) && e.key === ',') {
+ e.preventDefault()
+ setSettingsOpen(true)
+ }
+ }
+ window.addEventListener('keydown', onKey)
+ return () => window.removeEventListener('keydown', onKey)
+ }, [])
+
+ // Apply the accent color as a CSS variable.
+ useEffect(() => {
+ document.documentElement.style.setProperty('--accent', settings.accent)
+ }, [settings.accent])
+
+
+ /** ids to act on for a node menu: the whole selection if the node is part of it, else just it. */
+ const targetIds = useCallback((node: Node): string[] => {
+ const selected = nodesRef.current.filter((n) => n.selected).map((n) => n.id)
+ return node.selected && selected.length > 0 ? selected : [node.id]
+ }, [])
+
+ const selectionItems = useCallback(
+ (ids: string[]): MenuItem[] => [
+ { type: 'label', label: ids.length > 1 ? `${ids.length} nodes` : '1 node' },
+ ...(ids.length > 1
+ ? ([
+ { label: 'Group selection', onClick: () => groupSelection(ids) },
+ { type: 'separator' }
+ ] as MenuItem[])
+ : []),
+ { type: 'colors', onPick: (c) => setNodesColor(ids, c) },
+ { type: 'separator' },
+ { label: 'Align to grid', onClick: () => alignToGrid(ids) },
+ { label: 'Collapse / Expand', onClick: () => toggleCollapseNodes(ids) },
+ { type: 'separator' },
+ { label: 'Delete', danger: true, onClick: () => deleteNodes(ids) }
+ ],
+ [groupSelection, setNodesColor, alignToGrid, toggleCollapseNodes, deleteNodes]
+ )
+
+ const groupItems = useCallback(
+ (groupId: string): MenuItem[] => [
+ { type: 'label', label: 'Group' },
+ { type: 'colors', onPick: (c) => setNodesColor([groupId], c) },
+ { type: 'separator' },
+ { label: 'Ungroup', onClick: () => ungroup(groupId) },
+ { label: 'Delete (keeps nodes)', danger: true, onClick: () => ungroup(groupId) }
+ ],
+ [setNodesColor, ungroup]
+ )
+
+ const onPaneContextMenu = useCallback(
+ (e: MouseEvent | React.MouseEvent) => {
+ e.preventDefault()
+ const at = screenToFlowPosition({ x: e.clientX, y: e.clientY })
+ setMenu({
+ x: e.clientX,
+ y: e.clientY,
+ items: [
+ { label: 'New terminal here', onClick: () => addTerminal(at) },
+ { label: 'New sticky note here', onClick: () => addSticky(at) },
+ { type: 'separator' },
+ { label: 'Select all', onClick: selectAll },
+ { label: 'Fit view', onClick: () => fitView({ padding: 0.2, duration: 300 }) }
+ ]
+ })
+ },
+ [screenToFlowPosition, addTerminal, addSticky, selectAll, fitView]
+ )
+
+ const onNodeContextMenu = useCallback(
+ (e: React.MouseEvent, node: Node) => {
+ e.preventDefault()
+ const items = node.type === 'group' ? groupItems(node.id) : selectionItems(targetIds(node))
+ setMenu({ x: e.clientX, y: e.clientY, items })
+ },
+ [groupItems, selectionItems, targetIds]
+ )
+
+ const onSelectionContextMenu = useCallback(
+ (e: React.MouseEvent, selected: Node[]) => {
+ e.preventDefault()
+ setMenu({ x: e.clientX, y: e.clientY, items: selectionItems(selected.map((n) => n.id)) })
+ },
+ [selectionItems]
+ )
+
+ // Title/color/text edits go through updateNodeData; watch them so they persist too.
+ useEffect(() => {
+ markDirty()
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [nodes.map((n) => `${n.id}:${n.data.title}:${n.data.color}`).join('|')])
+ }, [
+ nodes
+ .map(
+ (n) =>
+ `${n.id}:${n.data.title}:${n.data.color}:${n.data.text ?? ''}:${
+ n.data.collapsed ? 1 : 0
+ }:${((n.data.tags as string[]) ?? []).join(',')}`
+ )
+ .join('|')
+ ])
+
+ const onMove = useCallback(
+ (_e: unknown, vp: Viewport) => {
+ viewportRef.current = vp
+ setZoomPct(Math.round(vp.zoom * 100))
+ markDirty()
+ },
+ [markDirty]
+ )
+
+ // ---- project (tab) actions ----
+ const switchProject = useCallback(
+ (id: string) => {
+ if (id === useProjects.getState().activeProjectId) return
+ commitActiveToStore()
+ useProjects.getState().setActive(id)
+ void writeDisk()
+ },
+ [commitActiveToStore, writeDisk]
+ )
+
+ const addProject = useCallback(() => {
+ commitActiveToStore()
+ const project = useProjects.getState().addProject()
+ useProjects.getState().setActive(project.id)
+ void writeDisk()
+ }, [commitActiveToStore, writeDisk])
+
+ const addProjectFromFolder = useCallback(async () => {
+ const folder = await window.nodeTerminal.dialog.selectFolder()
+ if (!folder) return
+ const name = folder.split('/').filter(Boolean).pop() || 'Project'
+ commitActiveToStore()
+ const project = useProjects.getState().addProject(name, folder)
+ useProjects.getState().setActive(project.id)
+ void writeDisk()
+ }, [commitActiveToStore, writeDisk])
+
+ const renameProject = useCallback(
+ (id: string, name: string) => {
+ useProjects.getState().renameProject(id, name)
+ void persist()
+ },
+ [persist]
+ )
+
+ const setProjectFolder = useCallback(
+ async (id: string) => {
+ const folder = await window.nodeTerminal.dialog.selectFolder()
+ if (!folder) return
+ useProjects.getState().setProjectCwd(id, folder)
+ void persist()
+ },
+ [persist]
+ )
+
+ const deleteProject = useCallback(
+ (id: string) => {
+ const store = useProjects.getState()
+ if (store.projects.length <= 1) return
+ if (id === store.activeProjectId) commitActiveToStore()
+ // End the tmux sessions of every terminal in the deleted project.
+ store.getProject(id)?.nodes.forEach((n) => {
+ if ((n.kind ?? 'terminal') === 'terminal') transport.destroy(n.id)
+ })
+ store.deleteProject(id)
+ void writeDisk()
+ },
+ [commitActiveToStore, writeDisk]
+ )
+
+ const buildCommands = useCallback((): Command[] => {
+ const cmds: Command[] = [
+ { id: 'new-term', label: 'New terminal', section: 'Create', run: () => addTerminal() },
+ { id: 'new-sticky', label: 'New sticky note', run: () => addSticky() },
+ { id: 'new-project', label: 'New project', run: () => addProject() },
+ { id: 'fit', label: 'Fit view', run: () => fitView({ padding: 0.2, duration: 300 }) },
+ { id: 'save', label: 'Save', run: () => void persist() }
+ ]
+ const store = useProjects.getState()
+ store.projects
+ .filter((p) => p.id !== store.activeProjectId)
+ .forEach((p) =>
+ cmds.push({
+ id: `proj-${p.id}`,
+ label: `Switch to ${p.name}`,
+ hint: 'project',
+ run: () => switchProject(p.id)
+ })
+ )
+ nodesRef.current
+ .filter((n) => n.type !== 'group')
+ .forEach((n) =>
+ cmds.push({
+ id: `node-${n.id}`,
+ label: `Go to ${n.data.title}`,
+ hint: ((n.data.tags as string[]) ?? []).join(' '),
+ run: () => goToNode(n)
+ })
+ )
+ return cmds
+ }, [addTerminal, addSticky, addProject, fitView, persist, switchProject, goToNode])
return (
- <div style={{ width: '100%', height: '100%' }}>
- <div className="toolbar">
- <button onClick={addTerminal}>+ New terminal</button>
- <button onClick={save}>Save</button>
- <span className={`dirty-dot${dirty ? ' dirty' : ''}`} title={dirty ? 'Unsaved changes' : 'Saved'} />
- <span className="hint">Drag · pan · Ctrl/⌘+wheel to zoom</span>
+ <div className="canvas-root">
+ <TabBar
+ onSwitch={switchProject}
+ onAdd={addProject}
+ onAddFromFolder={addProjectFromFolder}
+ onRename={renameProject}
+ onSetFolder={setProjectFolder}
+ onDelete={deleteProject}
+ />
+
+ <div className="controls-cluster">
+ <button title="Command palette (⌘K)" onClick={() => setPaletteOpen(true)}>
+ ⌕
+ </button>
+ <button title="Source Control" onClick={() => setScOpen(true)}>
+ ⎇
+ </button>
+ <button title="Settings (⌘,)" onClick={() => setSettingsOpen(true)}>
+ ⚙
+ </button>
</div>
- <ReactFlow
- nodes={nodes}
- nodeTypes={nodeTypes}
- onNodesChange={handleNodesChange}
- onMoveEnd={(_e, vp) => {
- viewportRef.current = vp
- if (ready) markDirty()
- }}
- minZoom={0.2}
- maxZoom={2}
- proOptions={{ hideAttribution: true }}
- deleteKeyCode={null}
- selectionOnDrag
- panOnDrag={[1, 2]}
- >
- <Background variant={BackgroundVariant.Dots} gap={24} size={1} color="#2c3142" />
- <Controls />
- </ReactFlow>
+ <div className="flow-wrap" ref={flowWrapRef}>
+ <ReactFlow
+ nodes={nodes}
+ nodeTypes={nodeTypes}
+ onNodesChange={handleNodesChange}
+ onMove={onMove}
+ onPaneContextMenu={onPaneContextMenu}
+ onNodeContextMenu={onNodeContextMenu}
+ onSelectionContextMenu={onSelectionContextMenu}
+ onNodeDoubleClick={onNodeDoubleClick}
+ minZoom={0.2}
+ maxZoom={2}
+ proOptions={{ hideAttribution: true }}
+ deleteKeyCode={null}
+ selectionOnDrag
+ panOnDrag={[1, 2]}
+ snapToGrid={settings.snapToGrid}
+ snapGrid={[settings.gridSize, settings.gridSize]}
+ >
+ <Background
+ variant={BackgroundVariant.Dots}
+ gap={settings.gridSize || GRID}
+ size={1}
+ color="#3a3a3a"
+ />
+ <Controls showInteractive={false} position="bottom-left" />
+ <MiniMap
+ className="minimap"
+ position="bottom-right"
+ pannable
+ zoomable
+ maskColor="rgba(10,12,18,0.6)"
+ nodeColor={(n) => (n.data as { color?: string })?.color ?? '#0a84ff'}
+ nodeStrokeColor={(n) => (n.data as { color?: string })?.color ?? '#0a84ff'}
+ />
+ </ReactFlow>
+ </div>
+
+ {menu && (
+ <ContextMenu x={menu.x} y={menu.y} items={menu.items} onClose={() => setMenu(null)} />
+ )}
+
+ {paletteOpen && (
+ <CommandPalette commands={buildCommands()} onClose={() => setPaletteOpen(false)} />
+ )}
+
+ {settingsOpen && <SettingsPanel onClose={() => setSettingsOpen(false)} />}
+
+ {scOpen && <SourceControlPanel onClose={() => setScOpen(false)} />}
+
+ <Dock
+ dirty={dirty}
+ zoomPct={zoomPct}
+ onAddTerminal={addTerminal}
+ onAddSticky={addSticky}
+ onSave={persist}
+ onFitView={() => fitView({ padding: 0.2, duration: 300 })}
+ onZoomIn={() => zoomIn({ duration: 150 })}
+ onZoomOut={() => zoomOut({ duration: 150 })}
+ />
</div>
)
}
diff --git a/src/renderer/components/CommandPalette.tsx b/src/renderer/components/CommandPalette.tsx
new file mode 100644
index 000000000..d133f1c9a
--- /dev/null
+++ b/src/renderer/components/CommandPalette.tsx
@@ -0,0 +1,92 @@
+import { useMemo, useState } from 'react'
+import { createPortal } from 'react-dom'
+
+export interface Command {
+ id: string
+ label: string
+ hint?: string
+ section?: string
+ run: () => void
+}
+
+interface CommandPaletteProps {
+ commands: Command[]
+ onClose: () => void
+}
+
+/** Case-insensitive subsequence match — "ntr" matches "New TeRminal". */
+function matches(label: string, q: string): boolean {
+ if (!q) return true
+ const s = label.toLowerCase()
+ let i = 0
+ for (const ch of q.toLowerCase()) {
+ i = s.indexOf(ch, i)
+ if (i === -1) return false
+ i++
+ }
+ return true
+}
+
+/** Cmd/Ctrl+K command palette: fuzzy-filter actions and jump targets, Enter to run. */
+export function CommandPalette({ commands, onClose }: CommandPaletteProps) {
+ const [query, setQuery] = useState('')
+ const [active, setActive] = useState(0)
+
+ const filtered = useMemo(
+ () => commands.filter((c) => matches(`${c.label} ${c.hint ?? ''}`, query)).slice(0, 50),
+ [commands, query]
+ )
+
+ const run = (cmd?: Command) => {
+ if (!cmd) return
+ cmd.run()
+ onClose()
+ }
+
+ return createPortal(
+ <div className="palette-overlay" onClick={onClose}>
+ <div className="palette" onClick={(e) => e.stopPropagation()}>
+ <input
+ className="palette__input"
+ autoFocus
+ spellCheck={false}
+ placeholder="Type a command or name…"
+ value={query}
+ onChange={(e) => {
+ setQuery(e.target.value)
+ setActive(0)
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown') {
+ e.preventDefault()
+ setActive((a) => Math.min(a + 1, filtered.length - 1))
+ } else if (e.key === 'ArrowUp') {
+ e.preventDefault()
+ setActive((a) => Math.max(a - 1, 0))
+ } else if (e.key === 'Enter') {
+ e.preventDefault()
+ run(filtered[active])
+ } else if (e.key === 'Escape') {
+ onClose()
+ }
+ }}
+ />
+ <div className="palette__list">
+ {filtered.length === 0 && <div className="palette__empty">No matches</div>}
+ {filtered.map((c, i) => (
+ <button
+ key={c.id}
+ className={`palette__item${i === active ? ' active' : ''}`}
+ onMouseEnter={() => setActive(i)}
+ onClick={() => run(c)}
+ >
+ <span className="palette__label">{c.label}</span>
+ {c.hint && <span className="palette__hint">{c.hint}</span>}
+ </button>
+ ))}
+ </div>
+ </div>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/ContextMenu.tsx b/src/renderer/components/ContextMenu.tsx
new file mode 100644
index 000000000..e5e2ae962
--- /dev/null
+++ b/src/renderer/components/ContextMenu.tsx
@@ -0,0 +1,63 @@
+import { createPortal } from 'react-dom'
+import { NODE_COLORS } from '../state/workspace'
+
+export type MenuItem =
+ | { type?: 'item'; label: string; onClick: () => void; danger?: boolean; disabled?: boolean }
+ | { type: 'separator' }
+ | { type: 'label'; label: string }
+ | { type: 'colors'; onPick: (color: string) => void }
+
+interface ContextMenuProps {
+ x: number
+ y: number
+ items: MenuItem[]
+ onClose: () => void
+}
+
+/**
+ * A right-click menu rendered in a body portal at fixed coordinates, so it is never
+ * clipped or hidden behind the canvas. Closes on backdrop click.
+ */
+export function ContextMenu({ x, y, items, onClose }: ContextMenuProps) {
+ return createPortal(
+ <>
+ <div className="ctx-backdrop" onContextMenu={(e) => e.preventDefault()} onClick={onClose} />
+ <div className="ctx-menu" style={{ top: y, left: x }} onClick={(e) => e.stopPropagation()}>
+ {items.map((item, i) => {
+ if (item.type === 'separator') return <div key={i} className="ctx-sep" />
+ if (item.type === 'label') return <div key={i} className="ctx-label">{item.label}</div>
+ if (item.type === 'colors') {
+ return (
+ <div key={i} className="ctx-colors">
+ {NODE_COLORS.map((c) => (
+ <button
+ key={c}
+ style={{ background: c }}
+ onClick={() => {
+ item.onPick(c)
+ onClose()
+ }}
+ />
+ ))}
+ </div>
+ )
+ }
+ return (
+ <button
+ key={i}
+ className={`ctx-item${item.danger ? ' danger' : ''}`}
+ disabled={item.disabled}
+ onClick={() => {
+ item.onClick()
+ onClose()
+ }}
+ >
+ {item.label}
+ </button>
+ )
+ })}
+ </div>
+ </>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/Dock.tsx b/src/renderer/components/Dock.tsx
new file mode 100644
index 000000000..4cae00b99
--- /dev/null
+++ b/src/renderer/components/Dock.tsx
@@ -0,0 +1,139 @@
+import { useState } from 'react'
+
+interface DockProps {
+ dirty: boolean
+ zoomPct: number
+ onAddTerminal: () => void
+ onAddSticky: () => void
+ onSave: () => void
+ onFitView: () => void
+ onZoomIn: () => void
+ onZoomOut: () => void
+}
+
+/**
+ * Bottom-center floating dock. The "+" opens a node-type menu above it.
+ * All canvas actions live here so the canvas itself stays clean.
+ */
+export function Dock({
+ dirty,
+ zoomPct,
+ onAddTerminal,
+ onAddSticky,
+ onSave,
+ onFitView,
+ onZoomIn,
+ onZoomOut
+}: DockProps) {
+ const [menuOpen, setMenuOpen] = useState(false)
+
+ const pick = (fn: () => void) => () => {
+ fn()
+ setMenuOpen(false)
+ }
+
+ return (
+ <>
+ {menuOpen && <div className="dock-backdrop" onClick={() => setMenuOpen(false)} />}
+
+ <div className="dock">
+ {menuOpen && (
+ <div className="dock-menu">
+ <button onClick={pick(onAddTerminal)}>
+ <TerminalIcon />
+ <span>Terminal</span>
+ </button>
+ <button onClick={pick(onAddSticky)}>
+ <NoteIcon />
+ <span>Sticky Note</span>
+ </button>
+ </div>
+ )}
+
+ <button
+ className={`dock-btn dock-add${menuOpen ? ' active' : ''}`}
+ title="Add node"
+ onClick={() => setMenuOpen((v) => !v)}
+ >
+ <PlusIcon />
+ </button>
+
+ <span className="dock-sep" />
+
+ <button className="dock-btn" title="Save" onClick={onSave}>
+ <SaveIcon />
+ <span className={`dock-dirty${dirty ? ' dirty' : ''}`} />
+ </button>
+ <button className="dock-btn" title="Fit view" onClick={onFitView}>
+ <FrameIcon />
+ </button>
+
+ <span className="dock-sep" />
+
+ <button className="dock-btn dock-zoom-btn" title="Zoom out" onClick={onZoomOut}>
+ <MinusIcon />
+ </button>
+ <span className="dock-zoom">{zoomPct}%</span>
+ <button className="dock-btn dock-zoom-btn" title="Zoom in" onClick={onZoomIn}>
+ <PlusSmallIcon />
+ </button>
+ </div>
+ </>
+ )
+}
+
+/* ---- inline icons (stroke = currentColor) ---- */
+const S = { width: 18, height: 18, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.8, strokeLinecap: 'round' as const, strokeLinejoin: 'round' as const }
+
+function PlusIcon() {
+ return (
+ <svg {...S} width={20} height={20}>
+ <path d="M12 5v14M5 12h14" />
+ </svg>
+ )
+}
+function PlusSmallIcon() {
+ return (
+ <svg {...S} width={15} height={15}>
+ <path d="M12 5v14M5 12h14" />
+ </svg>
+ )
+}
+function MinusIcon() {
+ return (
+ <svg {...S} width={15} height={15}>
+ <path d="M5 12h14" />
+ </svg>
+ )
+}
+function SaveIcon() {
+ return (
+ <svg {...S}>
+ <path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z" />
+ <path d="M17 21v-8H7v8M7 3v5h8" />
+ </svg>
+ )
+}
+function FrameIcon() {
+ return (
+ <svg {...S}>
+ <path d="M4 8V5a1 1 0 0 1 1-1h3M16 4h3a1 1 0 0 1 1 1v3M20 16v3a1 1 0 0 1-1 1h-3M8 20H5a1 1 0 0 1-1-1v-3" />
+ </svg>
+ )
+}
+function TerminalIcon() {
+ return (
+ <svg {...S}>
+ <rect x="3" y="4" width="18" height="16" rx="2" />
+ <path d="M7 9l3 3-3 3M13 15h4" />
+ </svg>
+ )
+}
+function NoteIcon() {
+ return (
+ <svg {...S}>
+ <path d="M4 4h16v11l-5 5H4z" />
+ <path d="M20 15h-5v5" />
+ </svg>
+ )
+}
diff --git a/src/renderer/components/NodeTags.tsx b/src/renderer/components/NodeTags.tsx
new file mode 100644
index 000000000..810645f6e
--- /dev/null
+++ b/src/renderer/components/NodeTags.tsx
@@ -0,0 +1,54 @@
+import { useState } from 'react'
+
+interface NodeTagsProps {
+ tags: string[]
+ onChange: (tags: string[]) => void
+}
+
+/** Inline tag chips with add/remove, used inside nodes. */
+export function NodeTags({ tags, onChange }: NodeTagsProps) {
+ const [adding, setAdding] = useState(false)
+ const [draft, setDraft] = useState('')
+
+ const commit = () => {
+ const t = draft.trim()
+ if (t && !tags.includes(t)) onChange([...tags, t])
+ setDraft('')
+ setAdding(false)
+ }
+
+ return (
+ <div className="node-tags nodrag">
+ {tags.map((t) => (
+ <span key={t} className="node-tag">
+ {t}
+ <button title="Remove tag" onClick={() => onChange(tags.filter((x) => x !== t))}>
+ ×
+ </button>
+ </span>
+ ))}
+ {adding ? (
+ <input
+ className="node-tag-input"
+ value={draft}
+ autoFocus
+ spellCheck={false}
+ placeholder="tag"
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') commit()
+ if (e.key === 'Escape') {
+ setDraft('')
+ setAdding(false)
+ }
+ }}
+ onBlur={commit}
+ />
+ ) : (
+ <button className="node-tag-add" title="Add tag" onClick={() => setAdding(true)}>
+ + tag
+ </button>
+ )}
+ </div>
+ )
+}
diff --git a/src/renderer/components/SettingsPanel.tsx b/src/renderer/components/SettingsPanel.tsx
new file mode 100644
index 000000000..7e9db6d70
--- /dev/null
+++ b/src/renderer/components/SettingsPanel.tsx
@@ -0,0 +1,194 @@
+import { createPortal } from 'react-dom'
+import { useSettings } from '../state/settings'
+import { NODE_COLORS } from '../state/workspace'
+
+interface SettingsPanelProps {
+ onClose: () => void
+}
+
+/** Right-side settings drawer. Changes are saved immediately. */
+export function SettingsPanel({ onClose }: SettingsPanelProps) {
+ const settings = useSettings((s) => s.settings)
+ const update = useSettings((s) => s.update)
+
+ return createPortal(
+ <div className="drawer-overlay" onClick={onClose}>
+ <aside className="drawer" onClick={(e) => e.stopPropagation()}>
+ <div className="drawer__head">
+ <h2>Settings</h2>
+ <button className="drawer__close" onClick={onClose}>
+ ×
+ </button>
+ </div>
+
+ <div className="drawer__body">
+ <section>
+ <h3>Terminal</h3>
+ <label className="set-row">
+ <span>Font size</span>
+ <input
+ type="number"
+ min={8}
+ max={28}
+ value={settings.fontSize}
+ onChange={(e) => update({ fontSize: Number(e.target.value) || 13 })}
+ />
+ </label>
+ <label className="set-row">
+ <span>Font family</span>
+ <input
+ type="text"
+ value={settings.fontFamily}
+ onChange={(e) => update({ fontFamily: e.target.value })}
+ />
+ </label>
+ <label className="set-row">
+ <span>Cursor blink</span>
+ <input
+ type="checkbox"
+ checked={settings.cursorBlink}
+ onChange={(e) => update({ cursorBlink: e.target.checked })}
+ />
+ </label>
+ </section>
+
+ <section>
+ <h3>Shell</h3>
+ <label className="set-row">
+ <span>Default shell</span>
+ <input
+ type="text"
+ placeholder="system default"
+ value={settings.defaultShell}
+ onChange={(e) => update({ defaultShell: e.target.value })}
+ />
+ </label>
+ </section>
+
+ <section>
+ <h3>Behavior</h3>
+ <label className="set-row">
+ <span>Grid size</span>
+ <input
+ type="number"
+ min={8}
+ max={96}
+ value={settings.gridSize}
+ onChange={(e) => update({ gridSize: Number(e.target.value) || 24 })}
+ />
+ </label>
+ <label className="set-row">
+ <span>Snap to grid</span>
+ <input
+ type="checkbox"
+ checked={settings.snapToGrid}
+ onChange={(e) => update({ snapToGrid: e.target.checked })}
+ />
+ </label>
+ <label className="set-row">
+ <span>Pan-hover delay (ms)</span>
+ <input
+ type="number"
+ min={0}
+ max={2000}
+ step={50}
+ value={settings.panHoverDelay}
+ onChange={(e) => update({ panHoverDelay: Number(e.target.value) || 0 })}
+ />
+ </label>
+ <label className="set-row">
+ <span>Double-click to focus</span>
+ <input
+ type="checkbox"
+ checked={settings.doubleClickFocus}
+ onChange={(e) => update({ doubleClickFocus: e.target.checked })}
+ />
+ </label>
+ </section>
+
+ <section>
+ <h3>Appearance</h3>
+ <div className="set-row">
+ <span>Accent</span>
+ <div className="set-swatches">
+ {NODE_COLORS.map((c) => (
+ <button
+ key={c}
+ className={settings.accent === c ? 'active' : ''}
+ style={{ background: c }}
+ onClick={() => update({ accent: c })}
+ />
+ ))}
+ </div>
+ </div>
+ </section>
+
+ <section>
+ <h3>Commit messages (AI)</h3>
+ <p className="set-note">
+ Runs a local coding-agent CLI read-only on your staged diff (no built-in model).
+ </p>
+ <label className="set-row">
+ <span>Agent</span>
+ <select
+ value={settings.commitAgent}
+ onChange={(e) =>
+ update({ commitAgent: e.target.value as 'claude' | 'codex' | 'custom' })
+ }
+ >
+ <option value="claude">Claude Code</option>
+ <option value="codex">Codex</option>
+ <option value="custom">Custom command…</option>
+ </select>
+ </label>
+ {settings.commitAgent === 'custom' && (
+ <label className="set-row">
+ <span>Command</span>
+ <input
+ type="text"
+ placeholder="mycli --flag {prompt}"
+ value={settings.commitAgentCommand}
+ onChange={(e) => update({ commitAgentCommand: e.target.value })}
+ />
+ </label>
+ )}
+ <label className="set-col">
+ <span>Extra prompt (optional)</span>
+ <textarea
+ className="set-textarea"
+ placeholder="e.g. Use Conventional Commits with gitmoji"
+ value={settings.commitExtraPrompt}
+ onChange={(e) => update({ commitExtraPrompt: e.target.value })}
+ />
+ </label>
+ </section>
+
+ <section>
+ <h3>tmux</h3>
+ <p className="set-note">Applies to new terminals / next launch.</p>
+ <label className="set-row">
+ <span>Persistent sessions (tmux)</span>
+ <input
+ type="checkbox"
+ checked={settings.tmuxEnabled}
+ onChange={(e) => update({ tmuxEnabled: e.target.checked })}
+ />
+ </label>
+ <label className="set-row">
+ <span>Scrollback lines</span>
+ <input
+ type="number"
+ min={1000}
+ max={200000}
+ step={1000}
+ value={settings.tmuxScrollback}
+ onChange={(e) => update({ tmuxScrollback: Number(e.target.value) || 50000 })}
+ />
+ </label>
+ </section>
+ </div>
+ </aside>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/SourceControlPanel.tsx b/src/renderer/components/SourceControlPanel.tsx
new file mode 100644
index 000000000..dfcb745ef
--- /dev/null
+++ b/src/renderer/components/SourceControlPanel.tsx
@@ -0,0 +1,339 @@
+import { Fragment, useCallback, useEffect, useState } from 'react'
+import { createPortal } from 'react-dom'
+import type { GitFileChange, GitResult, GitStatus } from '@shared/types'
+import { useProjects } from '../state/projects'
+
+interface SourceControlPanelProps {
+ onClose: () => void
+}
+
+const STATUS_COLOR: Record<string, string> = {
+ M: '#ffd60a',
+ A: '#32d74b',
+ D: '#ff453a',
+ R: '#bf5af2',
+ U: '#6ac4dc'
+}
+
+function DiffStat({ added, deleted }: { added: number; deleted: number }) {
+ if (!added && !deleted) return null
+ return (
+ <span className="scm-stat">
+ {added > 0 && <span className="scm-add">+{added}</span>}
+ {deleted > 0 && <span className="scm-del">-{deleted}</span>}
+ </span>
+ )
+}
+
+/** Renders a unified diff with colored add/remove/hunk lines. */
+function DiffBlock({ text }: { text: string }) {
+ const lines = text.split('\n')
+ return (
+ <pre className="scm-diff">
+ {lines.map((ln, i) => {
+ let cls = 'd-ctx'
+ if (ln.startsWith('@@')) cls = 'd-hunk'
+ else if (ln.startsWith('+') && !ln.startsWith('+++')) cls = 'd-add'
+ else if (ln.startsWith('-') && !ln.startsWith('---')) cls = 'd-del'
+ else if (ln.startsWith('diff ') || ln.startsWith('index ') || ln.startsWith('+++') || ln.startsWith('---'))
+ cls = 'd-meta'
+ return (
+ <div key={i} className={cls}>
+ {ln || ' '}
+ </div>
+ )
+ })}
+ </pre>
+ )
+}
+
+/** Visual Studio-style Source Control: file-level stage/diff/discard + branch switcher. */
+export function SourceControlPanel({ onClose }: SourceControlPanelProps) {
+ const project = useProjects((s) => s.projects.find((p) => p.id === s.activeProjectId))
+ const cwd = project?.cwd
+ const [status, setStatus] = useState<GitStatus | null>(null)
+ const [message, setMessage] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [error, setError] = useState('')
+ const [openKey, setOpenKey] = useState<string | null>(null)
+ const [diffText, setDiffText] = useState('')
+ const [branchMenu, setBranchMenu] = useState<{ top: number; left: number } | null>(null)
+ const [newBranch, setNewBranch] = useState('')
+ const [generating, setGenerating] = useState(false)
+
+ const git = window.nodeTerminal.git
+
+ const refresh = useCallback(async () => {
+ setStatus(cwd ? await git.status(cwd) : null)
+ }, [cwd, git])
+
+ useEffect(() => {
+ void refresh()
+ }, [refresh])
+
+ const act = async (fn: () => Promise<GitResult>) => {
+ setBusy(true)
+ const r = await fn()
+ setError(r.ok ? '' : r.message)
+ setBusy(false)
+ setOpenKey(null)
+ await refresh()
+ }
+
+ const toggleDiff = async (f: GitFileChange, staged: boolean) => {
+ const key = `${staged ? 's' : 'c'}:${f.path}`
+ if (openKey === key) {
+ setOpenKey(null)
+ return
+ }
+ setOpenKey(key)
+ setDiffText('Loading…')
+ const d = await git.diff(cwd!, f.path, staged, f.status === 'U')
+ setDiffText(d || '(no textual diff)')
+ }
+
+ const discard = (f: GitFileChange) => {
+ if (!window.confirm(`Discard changes to ${f.path}? This cannot be undone.`)) return
+ void act(() => git.discard(cwd!, f.path, f.status === 'U'))
+ }
+
+ const generate = async () => {
+ setGenerating(true)
+ setError('')
+ const r = await git.generateMessage(cwd!)
+ setGenerating(false)
+ if (r.ok) setMessage(r.message)
+ else setError(r.message)
+ }
+
+ const commitAndPush = () =>
+ act(async () => {
+ const c = await git.commit(cwd!, message)
+ if (!c.ok) return c
+ setMessage('')
+ return status?.hasRemote ? git.push(cwd!) : c
+ })
+
+ const renderFiles = (list: GitFileChange[], staged: boolean) =>
+ list.map((f) => {
+ const key = `${staged ? 's' : 'c'}:${f.path}`
+ return (
+ <Fragment key={key}>
+ <div className={`scm-file${openKey === key ? ' open' : ''}`}>
+ <span className="scm-letter" style={{ color: STATUS_COLOR[f.status] ?? 'rgba(255,255,255,0.85)' }}>
+ {f.status}
+ </span>
+ <button className="scm-path" title={f.path} onClick={() => toggleDiff(f, staged)}>
+ {f.path}
+ </button>
+ <DiffStat added={f.added} deleted={f.deleted} />
+ <span className="scm-row-actions">
+ {!staged && (
+ <button className="scm-iconbtn" title="Discard changes" onClick={() => discard(f)}>
+ ↩
+ </button>
+ )}
+ <button
+ className="scm-iconbtn"
+ title={staged ? 'Unstage' : 'Stage'}
+ onClick={() =>
+ act(() => (staged ? git.unstage(cwd!, [f.path]) : git.stage(cwd!, [f.path])))
+ }
+ >
+ {staged ? '−' : '+'}
+ </button>
+ </span>
+ </div>
+ {openKey === key && <DiffBlock text={diffText} />}
+ </Fragment>
+ )
+ })
+
+ const stagedCount = status?.staged.length ?? 0
+
+ return createPortal(
+ <div className="drawer-overlay" onClick={onClose}>
+ <aside className="drawer scm" onClick={(e) => e.stopPropagation()}>
+ <div className="drawer__head">
+ <h2>Source control</h2>
+ <button className="drawer__close" onClick={onClose}>
+ ×
+ </button>
+ </div>
+
+ {!cwd && (
+ <div className="drawer__body">
+ <p className="set-note">Set a folder for this project first (tab ⌄ → “Set folder…”).</p>
+ </div>
+ )}
+
+ {cwd && status && !status.hasRepo && (
+ <div className="drawer__body">
+ <p className="set-note">No git repository in this folder.</p>
+ <button className="sc-btn" disabled={busy} onClick={() => act(() => git.init(cwd))}>
+ Initialize repository
+ </button>
+ </div>
+ )}
+
+ {cwd && status && status.hasRepo && (
+ <>
+ <div className="scm-bar">
+ <span className="scm-repo">⌥ {status.repoName}</span>
+ <button
+ className="scm-branch"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect()
+ setBranchMenu({ top: r.bottom + 4, left: r.left })
+ }}
+ >
+ ⎇ {status.branch} ⌄
+ </button>
+ <span className="scm-spacer" />
+ {status.hasRemote ? (
+ <>
+ <span className="scm-ahead">↑{status.ahead}</span>
+ <span className="scm-behind">↓{status.behind}</span>
+ <button className="scm-sync" disabled={busy} onClick={() => act(() => git.sync(cwd))}>
+ Sync
+ </button>
+ </>
+ ) : (
+ <button
+ className="scm-sync"
+ disabled={busy || !status.ghAvailable}
+ title={status.ghAvailable ? '' : 'GitHub CLI (gh) not found'}
+ onClick={() => act(() => git.publish(cwd, project?.name || 'repo', true))}
+ >
+ Publish
+ </button>
+ )}
+ </div>
+
+ <div className="drawer__body scm-body">
+ {status.staged.length > 0 && (
+ <section className="scm-section">
+ <div className="scm-section-head">
+ <span>
+ STAGED · <b>{status.staged.length}</b>
+ </span>
+ <button onClick={() => act(() => git.unstageAll(cwd))}>unstage all</button>
+ </div>
+ {renderFiles(status.staged, true)}
+ </section>
+ )}
+
+ <section className="scm-section">
+ <div className="scm-section-head">
+ <span>
+ CHANGES · <b>{status.changes.length}</b>
+ </span>
+ {status.changes.length > 0 && (
+ <button onClick={() => act(() => git.stageAll(cwd))}>+ stage all</button>
+ )}
+ </div>
+ {status.changes.length === 0 && status.staged.length === 0 && (
+ <p className="set-note">No changes — working tree clean.</p>
+ )}
+ {renderFiles(status.changes, false)}
+ </section>
+
+ <section className="scm-commit">
+ <div className="scm-commit-head">
+ <span>Commit message</span>
+ <button
+ className="scm-gen"
+ disabled={generating || stagedCount === 0}
+ title="Generate from staged diff with your AI agent"
+ onClick={generate}
+ >
+ {generating ? '✦ Generating…' : '✦ Generate'}
+ </button>
+ </div>
+ <textarea
+ className="scm-message"
+ placeholder="Message (⌘↵ to commit)"
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ onKeyDown={(e) => {
+ if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') commitAndPush()
+ }}
+ />
+ <div className="scm-commit-foot">
+ <span>{stagedCount} files staged</span>
+ <span>⌘↵ to commit</span>
+ </div>
+ <button
+ className="scm-commit-btn"
+ disabled={busy || !message.trim() || stagedCount === 0}
+ onClick={commitAndPush}
+ >
+ {status.hasRemote ? 'Commit & Push' : 'Commit'} → {status.branch}
+ </button>
+ </section>
+
+ {status.recent.length > 0 && (
+ <section className="scm-section">
+ <div className="scm-section-head">
+ <span>RECENT COMMITS</span>
+ </div>
+ {status.recent.map((c) => (
+ <div key={c.hash} className="scm-commit-row">
+ <span className="scm-hash">{c.hash}</span>
+ <span className="scm-subject" title={c.subject}>
+ {c.subject}
+ </span>
+ <span className="scm-rel">{c.relative}</span>
+ </div>
+ ))}
+ </section>
+ )}
+
+ {error && <pre className="sc-log">{error}</pre>}
+ </div>
+ </>
+ )}
+
+ {branchMenu &&
+ status &&
+ createPortal(
+ <>
+ <div className="tab-backdrop" onClick={() => setBranchMenu(null)} />
+ <div className="tab-menu" style={{ top: branchMenu.top, left: branchMenu.left }}>
+ {status.branches.map((b) => (
+ <button
+ key={b}
+ onClick={() => {
+ setBranchMenu(null)
+ if (b !== status.branch) void act(() => git.switchBranch(cwd!, b))
+ }}
+ >
+ {b === status.branch ? '● ' : ' '}
+ {b}
+ </button>
+ ))}
+ <div className="ctx-sep" />
+ <input
+ className="tab__edit"
+ placeholder="new branch name"
+ value={newBranch}
+ spellCheck={false}
+ onChange={(e) => setNewBranch(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter' && newBranch.trim()) {
+ const name = newBranch.trim()
+ setNewBranch('')
+ setBranchMenu(null)
+ void act(() => git.createBranch(cwd!, name))
+ }
+ }}
+ />
+ </div>
+ </>,
+ document.body
+ )}
+ </aside>
+ </div>,
+ document.body
+ )
+}
diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsx
new file mode 100644
index 000000000..e5424f78a
--- /dev/null
+++ b/src/renderer/components/TabBar.tsx
@@ -0,0 +1,201 @@
+import { useState } from 'react'
+import { createPortal } from 'react-dom'
+import { useProjects } from '../state/projects'
+
+interface TabBarProps {
+ onSwitch: (id: string) => void
+ onAdd: () => void
+ onAddFromFolder: () => void
+ onRename: (id: string, name: string) => void
+ onSetFolder: (id: string) => void
+ onDelete: (id: string) => void
+}
+
+/**
+ * Top tab bar — one tab per project. Click to switch, "+" to add. The active tab
+ * exposes a caret menu (Rename / Set folder / Delete). The menu is rendered in a body
+ * portal with fixed positioning so it is never clipped by the tab strip's overflow nor
+ * hidden behind the canvas.
+ */
+export function TabBar({
+ onSwitch,
+ onAdd,
+ onAddFromFolder,
+ onRename,
+ onSetFolder,
+ onDelete
+}: TabBarProps) {
+ const projects = useProjects((s) => s.projects)
+ const activeId = useProjects((s) => s.activeProjectId)
+ const [menuId, setMenuId] = useState<string | null>(null)
+ const [menuPos, setMenuPos] = useState<{ top: number; left: number } | null>(null)
+ const [addPos, setAddPos] = useState<{ top: number; left: number } | null>(null)
+ const [editingId, setEditingId] = useState<string | null>(null)
+ const [draft, setDraft] = useState('')
+
+ const menuProject = projects.find((p) => p.id === menuId)
+
+ const closeMenu = () => {
+ setMenuId(null)
+ setMenuPos(null)
+ }
+
+ const openMenu = (id: string, anchor: HTMLElement) => {
+ const r = anchor.getBoundingClientRect()
+ setMenuId(id)
+ setMenuPos({ top: r.bottom + 4, left: r.left })
+ }
+
+ const startRename = (id: string, current: string) => {
+ setEditingId(id)
+ setDraft(current)
+ closeMenu()
+ }
+
+ const commitRename = () => {
+ if (editingId) {
+ const name = draft.trim()
+ if (name) onRename(editingId, name)
+ }
+ setEditingId(null)
+ }
+
+ return (
+ <>
+ {(menuId || editingId) && (
+ <div
+ className="tab-backdrop"
+ onClick={() => {
+ closeMenu()
+ commitRename()
+ }}
+ />
+ )}
+
+ <div className="tabbar">
+ <span className="tabbar__brand">node-terminal</span>
+
+ <div className="tabbar__tabs">
+ {projects.map((p) => {
+ const active = p.id === activeId
+ return (
+ <div
+ key={p.id}
+ className={`tab${active ? ' active' : ''}`}
+ style={active ? { borderBottomColor: p.color } : undefined}
+ onClick={() => !editingId && onSwitch(p.id)}
+ title={p.cwd || undefined}
+ >
+ <span className="tab__dot" style={{ background: p.color }} />
+ {editingId === p.id ? (
+ <input
+ className="tab__edit"
+ value={draft}
+ autoFocus
+ spellCheck={false}
+ onChange={(e) => setDraft(e.target.value)}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') commitRename()
+ if (e.key === 'Escape') setEditingId(null)
+ }}
+ onBlur={commitRename}
+ onClick={(e) => e.stopPropagation()}
+ />
+ ) : (
+ <span className="tab__name">{p.name}</span>
+ )}
+
+ {active && editingId !== p.id && (
+ <button
+ className="tab__caret"
+ title="Project options"
+ onClick={(e) => {
+ e.stopPropagation()
+ if (menuId === p.id) closeMenu()
+ else openMenu(p.id, e.currentTarget)
+ }}
+ >
+ ⌄
+ </button>
+ )}
+ </div>
+ )
+ })}
+
+ <button
+ className="tab__add"
+ title="New project"
+ onClick={(e) => {
+ const r = e.currentTarget.getBoundingClientRect()
+ setAddPos({ top: r.bottom + 4, left: r.left })
+ }}
+ >
+ +
+ </button>
+ </div>
+ </div>
+
+ {addPos &&
+ createPortal(
+ <>
+ <div className="tab-backdrop" onClick={() => setAddPos(null)} />
+ <div
+ className="tab-menu"
+ style={{ top: addPos.top, left: addPos.left }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <button
+ onClick={() => {
+ onAdd()
+ setAddPos(null)
+ }}
+ >
+ Empty project
+ </button>
+ <button
+ onClick={() => {
+ onAddFromFolder()
+ setAddPos(null)
+ }}
+ >
+ From folder…
+ </button>
+ </div>
+ </>,
+ document.body
+ )}
+
+ {menuId &&
+ menuPos &&
+ menuProject &&
+ createPortal(
+ <div
+ className="tab-menu"
+ style={{ top: menuPos.top, left: menuPos.left }}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <button onClick={() => startRename(menuProject.id, menuProject.name)}>Rename</button>
+ <button
+ onClick={() => {
+ onSetFolder(menuProject.id)
+ closeMenu()
+ }}
+ >
+ Set folder…
+ </button>
+ <button
+ className="danger"
+ disabled={projects.length <= 1}
+ onClick={() => {
+ onDelete(menuProject.id)
+ closeMenu()
+ }}
+ >
+ Delete project
+ </button>
+ </div>,
+ document.body
+ )}
+ </>
+ )
+}
diff --git a/src/renderer/nodes/GroupNode.tsx b/src/renderer/nodes/GroupNode.tsx
new file mode 100644
index 000000000..5f4f1e99d
--- /dev/null
+++ b/src/renderer/nodes/GroupNode.tsx
@@ -0,0 +1,56 @@
+import { useState } from 'react'
+import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'
+import { NODE_COLORS, ungroupNodes, type CanvasNode } from '../state/workspace'
+
+/**
+ * A group frame: a labeled, resizable, translucent box that contains child nodes.
+ * Children are real React Flow nodes parented to this one, so dragging the frame moves
+ * them together. The frame renders behind its children (it appears first in the array).
+ */
+export function GroupNode({ id, data, selected }: NodeProps<CanvasNode>) {
+ const { updateNodeData, setNodes } = useReactFlow()
+ const [showColors, setShowColors] = useState(false)
+
+ const ungroup = () => setNodes((ns) => ungroupNodes(ns as CanvasNode[], id))
+
+ return (
+ <div className="group-node" style={{ borderColor: data.color, background: `${data.color}12` }}>
+ <NodeResizer minWidth={200} minHeight={140} isVisible={selected} color={data.color} />
+
+ <div className="group-node__header">
+ <button
+ className="term-node__color"
+ style={{ background: data.color }}
+ title="Color"
+ onClick={() => setShowColors((v) => !v)}
+ />
+ {showColors && (
+ <div className="color-popover">
+ {NODE_COLORS.map((c) => (
+ <button
+ key={c}
+ style={{ background: c }}
+ onClick={() => {
+ updateNodeData(id, { color: c })
+ setShowColors(false)
+ }}
+ />
+ ))}
+ </div>
+ )}
+ <input
+ className="term-node__title nodrag"
+ value={data.title}
+ spellCheck={false}
+ onChange={(e) => updateNodeData(id, { title: e.target.value })}
+ />
+ <button className="group-node__ungroup nodrag" title="Ungroup" onClick={ungroup}>
+ ungroup
+ </button>
+ <button className="term-node__close" title="Remove group (keeps nodes)" onClick={ungroup}>
+ ×
+ </button>
+ </div>
+ </div>
+ )
+}
diff --git a/src/renderer/nodes/StickyNode.tsx b/src/renderer/nodes/StickyNode.tsx
new file mode 100644
index 000000000..fd392b08b
--- /dev/null
+++ b/src/renderer/nodes/StickyNode.tsx
@@ -0,0 +1,86 @@
+import { useState } from 'react'
+import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'
+import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
+
+/**
+ * A sticky note node: a colored, resizable card with free-text content.
+ * No PTY — purely a visual note for organizing the canvas (handy for ADHD users).
+ */
+export function StickyNode({ id, data, selected }: NodeProps<CanvasNode>) {
+ const { updateNodeData, deleteElements, setNodes } = useReactFlow()
+ const [showColors, setShowColors] = useState(false)
+ const collapsed = !!data.collapsed
+
+ const toggleCollapse = () =>
+ setNodes((ns) =>
+ ns.map((n) => {
+ if (n.id !== id) return n
+ const next = !n.data.collapsed
+ const expandedHeight =
+ (n.data.expandedHeight as number) ?? n.measured?.height ?? (n.height as number) ?? 200
+ const height = next ? COLLAPSED_HEIGHT : expandedHeight
+ return {
+ ...n,
+ height,
+ style: { ...n.style, height },
+ data: { ...n.data, collapsed: next, expandedHeight }
+ }
+ })
+ )
+
+ return (
+ <div
+ className={`sticky-node${selected ? ' selected' : ''}${collapsed ? ' collapsed' : ''}`}
+ style={{ background: `${data.color}22`, borderColor: data.color }}
+ >
+ <NodeResizer minWidth={160} minHeight={120} isVisible={selected && !collapsed} color={data.color} />
+
+ <div className="sticky-node__header" style={{ background: `${data.color}33` }}>
+ <button className="term-node__collapse" title={collapsed ? 'Expand' : 'Collapse'} onClick={toggleCollapse}>
+ {collapsed ? '▸' : '▾'}
+ </button>
+ <button
+ className="term-node__color"
+ style={{ background: data.color }}
+ title="Color"
+ onClick={() => setShowColors((v) => !v)}
+ />
+ {showColors && (
+ <div className="color-popover">
+ {NODE_COLORS.map((c) => (
+ <button
+ key={c}
+ style={{ background: c }}
+ onClick={() => {
+ updateNodeData(id, { color: c })
+ setShowColors(false)
+ }}
+ />
+ ))}
+ </div>
+ )}
+ <input
+ className="term-node__title nodrag"
+ value={data.title}
+ spellCheck={false}
+ onChange={(e) => updateNodeData(id, { title: e.target.value })}
+ />
+ <button
+ className="term-node__close"
+ title="Close"
+ onClick={() => deleteElements({ nodes: [{ id }] })}
+ >
+ ×
+ </button>
+ </div>
+
+ <textarea
+ className="sticky-node__body nodrag nowheel"
+ value={data.text ?? ''}
+ placeholder="Write a note…"
+ spellCheck={false}
+ onChange={(e) => updateNodeData(id, { text: e.target.value })}
+ />
+ </div>
+ )
+}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 8f90db1b7..fda1c584d 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -3,41 +3,55 @@ import { NodeResizer, useReactFlow, type NodeProps } from '@xyflow/react'
import { Terminal } from '@xterm/xterm'
import { FitAddon } from '@xterm/addon-fit'
import { transport } from '../terminal/local-transport'
-import { NODE_COLORS, type TermNode } from '../state/workspace'
+import { patchTerminalScale } from '../terminal/scale-fix'
+import { NodeTags } from '../components/NodeTags'
+import { useSettings } from '../state/settings'
+import { COLLAPSED_HEIGHT, NODE_COLORS, type CanvasNode } from '../state/workspace'
/**
- * A single terminal node: a header (title + color + close) with a real xterm.js
- * terminal inside. The terminal session (PTY) is opened through the transport when
- * the component mounts and closed when it unmounts.
+ * A single terminal node: header (collapse + color + title + close), optional tag chips,
+ * and a real xterm.js terminal. A hover guard delays entering the terminal so the canvas
+ * can be panned across terminals without grabbing focus.
*/
-export function TerminalNode({ id, data, selected }: NodeProps<TermNode>) {
- const { updateNodeData, deleteElements } = useReactFlow()
+export function TerminalNode({ id, data, selected }: NodeProps<CanvasNode>) {
+ const { updateNodeData, deleteElements, getZoom, setNodes } = useReactFlow()
+ const settings = useSettings((s) => s.settings)
const bodyRef = useRef<HTMLDivElement>(null)
+ const termRef = useRef<Terminal | null>(null)
+ const fitRef = useRef<FitAddon | null>(null)
+ const dwellRef = useRef<ReturnType<typeof setTimeout> | null>(null)
const [showColors, setShowColors] = useState(false)
+ const [armed, setArmed] = useState(true)
+ const collapsed = !!data.collapsed
+ const tags = (data.tags as string[]) ?? []
// Terminal lifecycle — set up exactly once.
useEffect(() => {
const container = bodyRef.current
if (!container) return
+ const s = useSettings.getState().settings
const term = new Terminal({
- fontFamily: 'Menlo, Monaco, "Courier New", monospace',
- fontSize: 13,
- cursorBlink: true,
- theme: { background: '#11131a', foreground: '#c0caf5' },
+ fontFamily: s.fontFamily,
+ fontSize: s.fontSize,
+ cursorBlink: s.cursorBlink,
+ theme: { background: '#1e1e1e', foreground: '#e6e6e6' },
allowProposedApi: true
})
+ termRef.current = term
const fit = new FitAddon()
+ fitRef.current = fit
term.loadAddon(fit)
term.open(container)
fit.fit()
+ patchTerminalScale(term, getZoom)
let sessionId: string | null = null
let disposed = false
const cleanups: Array<() => void> = []
transport
- .create({ cols: term.cols, rows: term.rows, shell: data.shell, cwd: data.cwd })
+ .create({ cols: term.cols, rows: term.rows, shell: data.shell, cwd: data.cwd, persistKey: id })
.then((sid) => {
if (disposed) {
transport.kill(sid)
@@ -50,17 +64,15 @@ export function TerminalNode({ id, data, selected }: NodeProps<TermNode>) {
term.write(`\r\n\x1b[90m[process exited with code ${code}]\x1b[0m\r\n`)
})
)
- // Forward user input to the PTY.
cleanups.push(term.onData((input) => transport.write(sid, input)).dispose)
})
- // Re-fit the terminal whenever the container size changes (resize/zoom layout).
const resize = () => {
try {
fit.fit()
if (sessionId) transport.resize(sessionId, term.cols, term.rows)
} catch {
- // fit can throw when the size is 0; ignore.
+ // fit can throw when the size is 0 (e.g. collapsed); ignore.
}
}
const observer = new ResizeObserver(resize)
@@ -69,19 +81,77 @@ export function TerminalNode({ id, data, selected }: NodeProps<TermNode>) {
return () => {
disposed = true
observer.disconnect()
+ if (dwellRef.current) clearTimeout(dwellRef.current)
cleanups.forEach((fn) => fn())
if (sessionId) transport.kill(sessionId)
term.dispose()
+ termRef.current = null
+ fitRef.current = null
}
- // shell/cwd are only used at creation time; the empty dependency array is intentional.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
+ // Live-apply font/cursor settings to the running terminal.
+ useEffect(() => {
+ const term = termRef.current
+ if (!term) return
+ term.options.fontSize = settings.fontSize
+ term.options.fontFamily = settings.fontFamily
+ term.options.cursorBlink = settings.cursorBlink
+ try {
+ fitRef.current?.fit()
+ } catch {
+ // ignore
+ }
+ }, [settings.fontSize, settings.fontFamily, settings.cursorBlink])
+
+ const toggleCollapse = () =>
+ setNodes((ns) =>
+ ns.map((n) => {
+ if (n.id !== id) return n
+ const next = !n.data.collapsed
+ const expandedHeight =
+ (n.data.expandedHeight as number) ?? n.measured?.height ?? (n.height as number) ?? 300
+ const height = next ? COLLAPSED_HEIGHT : expandedHeight
+ return {
+ ...n,
+ height,
+ style: { ...n.style, height },
+ data: { ...n.data, collapsed: next, expandedHeight }
+ }
+ })
+ )
+
+ // ---- hover guard: dwell before entering the terminal ----
+ const onBodyEnter = () => {
+ if (dwellRef.current) clearTimeout(dwellRef.current)
+ dwellRef.current = setTimeout(() => {
+ setArmed(false)
+ termRef.current?.focus()
+ }, settings.panHoverDelay)
+ }
+ const onBodyLeave = () => {
+ if (dwellRef.current) clearTimeout(dwellRef.current)
+ setArmed(true)
+ termRef.current?.blur()
+ }
+ const enterNow = () => {
+ if (dwellRef.current) clearTimeout(dwellRef.current)
+ setArmed(false)
+ termRef.current?.focus()
+ }
+
return (
- <div className={`term-node${selected ? ' selected' : ''}`} style={{ borderTopColor: data.color }}>
- <NodeResizer minWidth={260} minHeight={160} isVisible={selected} color="#7aa2f7" />
+ <div
+ className={`term-node${selected ? ' selected' : ''}${collapsed ? ' collapsed' : ''}`}
+ style={{ borderTopColor: data.color }}
+ >
+ <NodeResizer minWidth={260} minHeight={160} isVisible={selected && !collapsed} color="#0a84ff" />
<div className="term-node__header">
+ <button className="term-node__collapse" title={collapsed ? 'Expand' : 'Collapse'} onClick={toggleCollapse}>
+ {collapsed ? '▸' : '▾'}
+ </button>
<button
className="term-node__color"
style={{ background: data.color }}
@@ -110,15 +180,27 @@ export function TerminalNode({ id, data, selected }: NodeProps<TermNode>) {
/>
<button
className="term-node__close"
- title="Close"
- onClick={() => deleteElements({ nodes: [{ id }] })}
+ title="Close (ends the session)"
+ onClick={() => {
+ transport.destroy(id)
+ deleteElements({ nodes: [{ id }] })
+ }}
>
×
</button>
</div>
- {/* nodrag: clicking the terminal must not drag the node. nowheel: for scrollback. */}
- <div className="term-node__body nodrag nowheel" ref={bodyRef} />
+ {!collapsed && (
+ <NodeTags tags={tags} onChange={(t) => updateNodeData(id, { tags: t })} />
+ )}
+
+ {/* Body always mounted (keeps xterm alive); hidden via CSS when collapsed. */}
+ <div className="term-node__body" onMouseEnter={onBodyEnter} onMouseLeave={onBodyLeave}>
+ <div className="term-node__xterm nodrag nowheel" ref={bodyRef} />
+ {armed && (
+ <div className="term-hover-guard nodrag nowheel" onMouseDown={enterNow} title="Click to focus" />
+ )}
+ </div>
</div>
)
}
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
new file mode 100644
index 000000000..0077b4f08
--- /dev/null
+++ b/src/renderer/state/projects.ts
@@ -0,0 +1,84 @@
+import { create } from 'zustand'
+import type { CanvasNodeState, Project, Viewport, Workspace } from '@shared/types'
+import { createProject } from './workspace'
+
+interface ProjectsState {
+ projects: Project[]
+ activeProjectId: string
+
+ hydrate(ws: Workspace): void
+ getProject(id: string): Project | undefined
+
+ setActive(id: string): void
+ /** Adds a new project and returns it (caller commits the current canvas first). */
+ addProject(name?: string, cwd?: string): Project
+ renameProject(id: string, name: string): void
+ setProjectCwd(id: string, cwd: string): void
+ /** Writes the serialized canvas (nodes + viewport) back into a project. */
+ commitCanvas(id: string, nodes: CanvasNodeState[], viewport: Viewport): void
+ /** Removes a project; returns the id that should become active (never deletes the last one). */
+ deleteProject(id: string): string
+
+ toWorkspace(): Workspace
+}
+
+export const useProjects = create<ProjectsState>((set, get) => ({
+ projects: [],
+ activeProjectId: '',
+
+ hydrate(ws) {
+ set({ projects: ws.projects, activeProjectId: ws.activeProjectId })
+ },
+
+ getProject(id) {
+ return get().projects.find((p) => p.id === id)
+ },
+
+ setActive(id) {
+ set({ activeProjectId: id })
+ },
+
+ addProject(name, cwd) {
+ const project = createProject(get().projects.length, name, cwd)
+ set((s) => ({ projects: [...s.projects, project] }))
+ return project
+ },
+
+ renameProject(id, name) {
+ set((s) => ({
+ projects: s.projects.map((p) => (p.id === id ? { ...p, name } : p))
+ }))
+ },
+
+ setProjectCwd(id, cwd) {
+ set((s) => ({
+ projects: s.projects.map((p) => (p.id === id ? { ...p, cwd } : p))
+ }))
+ },
+
+ commitCanvas(id, nodes, viewport) {
+ set((s) => ({
+ projects: s.projects.map((p) => (p.id === id ? { ...p, nodes, viewport } : p))
+ }))
+ },
+
+ deleteProject(id) {
+ const { projects, activeProjectId } = get()
+ if (projects.length <= 1) return activeProjectId // never delete the last project
+
+ const index = projects.findIndex((p) => p.id === id)
+ const remaining = projects.filter((p) => p.id !== id)
+ let nextActive = activeProjectId
+ if (activeProjectId === id) {
+ // pick the neighbor that takes this slot (or the new last one)
+ nextActive = remaining[Math.min(index, remaining.length - 1)].id
+ }
+ set({ projects: remaining, activeProjectId: nextActive })
+ return nextActive
+ },
+
+ toWorkspace() {
+ const { projects, activeProjectId } = get()
+ return { version: 2, activeProjectId, projects }
+ }
+}))
diff --git a/src/renderer/state/settings.ts b/src/renderer/state/settings.ts
new file mode 100644
index 000000000..1070dfd6e
--- /dev/null
+++ b/src/renderer/state/settings.ts
@@ -0,0 +1,23 @@
+import { create } from 'zustand'
+import { DEFAULT_SETTINGS, type Settings } from '@shared/types'
+
+interface SettingsState {
+ settings: Settings
+ hydrate(): Promise<void>
+ update(patch: Partial<Settings>): void
+}
+
+export const useSettings = create<SettingsState>((set, get) => ({
+ settings: DEFAULT_SETTINGS,
+
+ async hydrate() {
+ const s = await window.nodeTerminal.settings.load()
+ set({ settings: { ...DEFAULT_SETTINGS, ...s } })
+ },
+
+ update(patch) {
+ const next = { ...get().settings, ...patch }
+ set({ settings: next })
+ void window.nodeTerminal.settings.save(next)
+ }
+}))
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index bc11dedf5..c17879a10 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -1,87 +1,257 @@
import type { Node } from '@xyflow/react'
-import type { TerminalNodeState, Viewport, Workspace } from '@shared/types'
+import type { CanvasNodeState, NodeKind, Project } from '@shared/types'
-/** Preset color palette assigned to new terminals in order (for grouping/focus). */
+/** Preset color palette — macOS system colors (dark mode). */
export const NODE_COLORS = [
- '#7aa2f7', // blue
- '#9ece6a', // green
- '#e0af68', // yellow
- '#f7768e', // red
- '#bb9af7', // purple
- '#7dcfff', // cyan
- '#ff9e64' // orange
+ '#0a84ff', // systemBlue
+ '#32d74b', // systemGreen
+ '#ffd60a', // systemYellow
+ '#ff453a', // systemRed
+ '#bf5af2', // systemPurple
+ '#6ac4dc', // systemTeal
+ '#ff9f0a' // systemOrange
]
-const DEFAULT_SIZE = { width: 440, height: 300 }
+const TERMINAL_SIZE = { width: 440, height: 300 }
+const STICKY_SIZE = { width: 240, height: 200 }
+const GROUP_SIZE = { width: 520, height: 360 }
+
+/** Height of a node when collapsed (header only). */
+export const COLLAPSED_HEIGHT = 40
/** User data carried in the React Flow node's data field. */
-export interface TermNodeData {
+export interface NodeData {
title: string
color: string
group: string | null
+ tags?: string[]
+ collapsed?: boolean
+ /** Expanded height to restore when un-collapsing (kept out of the persisted size). */
+ expandedHeight?: number
shell?: string
cwd?: string
+ text?: string
[key: string]: unknown
}
-export type TermNode = Node<TermNodeData, 'terminal'>
+/** React Flow node type string mirrors the persisted NodeKind. */
+export type CanvasNode = Node<NodeData, NodeKind>
let idCounter = 0
-function nextId(): string {
- return `term-${Date.now().toString(36)}-${++idCounter}`
+function nextId(prefix: string): string {
+ return `${prefix}-${Date.now().toString(36)}-${++idCounter}`
+}
+
+/** Stagger placement so new nodes don't overlap. */
+function staggeredPosition(index: number) {
+ return { x: 80 + (index % 4) * 360, y: 120 + Math.floor(index / 4) * 320 }
+}
+
+/** Top-left position so a node of the given size is centered on `center`. */
+function placeAt(center: { x: number; y: number } | undefined, index: number, w: number, h: number) {
+ return center ? { x: center.x - w / 2, y: center.y - h / 2 } : staggeredPosition(index)
}
-/** Creates a new node for the toolbar's "New terminal" action. */
-export function createTerminalNode(index: number): TermNode {
+/** Creates a new terminal node. `cwd` comes from the active project's default folder. */
+export function createTerminalNode(
+ index: number,
+ cwd?: string,
+ center?: { x: number; y: number }
+): CanvasNode {
return {
- id: nextId(),
+ id: nextId('term'),
type: 'terminal',
- // Stagger placement so they don't overlap.
- position: { x: 80 + (index % 4) * 360, y: 80 + Math.floor(index / 4) * 320 },
- width: DEFAULT_SIZE.width,
- height: DEFAULT_SIZE.height,
- style: { width: DEFAULT_SIZE.width, height: DEFAULT_SIZE.height },
+ position: placeAt(center, index, TERMINAL_SIZE.width, TERMINAL_SIZE.height),
+ width: TERMINAL_SIZE.width,
+ height: TERMINAL_SIZE.height,
+ style: { width: TERMINAL_SIZE.width, height: TERMINAL_SIZE.height },
data: {
title: `Terminal ${index + 1}`,
color: NODE_COLORS[index % NODE_COLORS.length],
- group: null
+ group: null,
+ tags: [],
+ cwd
}
}
}
-/** Converts a workspace read from disk into React Flow nodes. */
-export function workspaceToNodes(ws: Workspace): TermNode[] {
- return ws.nodes.map((n) => ({
- id: n.id,
- type: 'terminal',
- position: n.position,
- width: n.size.width,
- height: n.size.height,
- style: { width: n.size.width, height: n.size.height },
+/** Creates a new sticky note. */
+export function createStickyNode(index: number, center?: { x: number; y: number }): CanvasNode {
+ return {
+ id: nextId('sticky'),
+ type: 'sticky',
+ position: placeAt(center, index, STICKY_SIZE.width, STICKY_SIZE.height),
+ width: STICKY_SIZE.width,
+ height: STICKY_SIZE.height,
+ style: { width: STICKY_SIZE.width, height: STICKY_SIZE.height },
data: {
- title: n.title,
- color: n.color,
- group: n.group,
- shell: n.shell,
- cwd: n.cwd
+ title: 'Note',
+ color: '#ffd60a',
+ group: null,
+ text: ''
+ }
+ }
+}
+
+/** Creates a group frame node at a given position/size (children get parentId = its id). */
+export function createGroupNode(
+ position: { x: number; y: number },
+ size: { width: number; height: number } = GROUP_SIZE,
+ index = 0
+): CanvasNode {
+ return {
+ id: nextId('group'),
+ type: 'group',
+ position,
+ width: size.width,
+ height: size.height,
+ style: { width: size.width, height: size.height },
+ data: {
+ title: `Group ${index + 1}`,
+ color: NODE_COLORS[index % NODE_COLORS.length],
+ group: null
+ }
+ }
+}
+
+/** Creates a new project. */
+export function createProject(index: number, name?: string, cwd?: string): Project {
+ return {
+ id: nextId('project'),
+ name: name ?? `Project ${index + 1}`,
+ color: NODE_COLORS[index % NODE_COLORS.length],
+ cwd,
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: []
+ }
+}
+
+const GROUP_PAD = 28
+const GROUP_HEADER = 34
+
+const nodeW = (n: CanvasNode) => n.measured?.width ?? (n.width as number) ?? 0
+const nodeH = (n: CanvasNode) => n.measured?.height ?? (n.height as number) ?? 0
+
+/**
+ * Wraps the given top-level node ids in a new group frame: creates the group sized to
+ * enclose them and reparents the children (positions become relative to the group).
+ * Returns a new nodes array with the group placed first (React Flow needs parents first).
+ */
+export function groupSelectedNodes(
+ nodes: CanvasNode[],
+ ids: string[],
+ groupIndex: number
+): CanvasNode[] {
+ const set = new Set(ids)
+ const members = nodes.filter((n) => set.has(n.id) && !n.parentId && n.type !== 'group')
+ if (members.length === 0) return nodes
+
+ const minX = Math.min(...members.map((n) => n.position.x))
+ const minY = Math.min(...members.map((n) => n.position.y))
+ const maxX = Math.max(...members.map((n) => n.position.x + nodeW(n)))
+ const maxY = Math.max(...members.map((n) => n.position.y + nodeH(n)))
+
+ const gx = minX - GROUP_PAD
+ const gy = minY - GROUP_PAD - GROUP_HEADER
+ const group = createGroupNode(
+ { x: gx, y: gy },
+ { width: maxX - minX + GROUP_PAD * 2, height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER },
+ groupIndex
+ )
+
+ const updated = nodes.map((n) =>
+ set.has(n.id) && !n.parentId && n.type !== 'group'
+ ? {
+ ...n,
+ parentId: group.id,
+ extent: 'parent' as const,
+ position: { x: n.position.x - gx, y: n.position.y - gy },
+ selected: false
+ }
+ : n
+ )
+ return [group, ...updated]
+}
+
+/** Removes a group frame and restores its children to absolute positions. */
+export function ungroupNodes(nodes: CanvasNode[], groupId: string): CanvasNode[] {
+ const group = nodes.find((n) => n.id === groupId)
+ if (!group) return nodes
+ return nodes
+ .filter((n) => n.id !== groupId)
+ .map((n) =>
+ n.parentId === groupId
+ ? {
+ ...n,
+ parentId: undefined,
+ extent: undefined,
+ position: { x: n.position.x + group.position.x, y: n.position.y + group.position.y }
+ }
+ : n
+ )
+}
+
+/** Converts persisted node states into live React Flow nodes (parents first). */
+export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
+ // React Flow requires a parent node to appear before its children in the array.
+ const ordered = [...states].sort((a, b) => {
+ if ((a.kind === 'group') === (b.kind === 'group')) return 0
+ return a.kind === 'group' ? -1 : 1
+ })
+ return ordered.map((n) => {
+ const collapsed = !!n.collapsed
+ const height = collapsed ? COLLAPSED_HEIGHT : n.size.height
+ return {
+ id: n.id,
+ // Default to 'terminal' for nodes saved before the kind field existed.
+ type: n.kind ?? 'terminal',
+ position: n.position,
+ width: n.size.width,
+ height,
+ style: { width: n.size.width, height },
+ ...(n.parentId ? { parentId: n.parentId, extent: 'parent' as const } : {}),
+ data: {
+ title: n.title,
+ color: n.color,
+ group: n.group,
+ tags: n.tags,
+ collapsed,
+ expandedHeight: n.size.height,
+ shell: n.shell,
+ cwd: n.cwd,
+ text: n.text
+ }
}
- }))
+ })
}
-/** Converts live React Flow nodes into a workspace to write to disk. */
-export function nodesToWorkspace(nodes: TermNode[], viewport: Viewport): Workspace {
- const serialized: TerminalNodeState[] = nodes.map((n) => ({
- id: n.id,
- position: n.position,
- size: {
- width: n.measured?.width ?? n.width ?? DEFAULT_SIZE.width,
- height: n.measured?.height ?? n.height ?? DEFAULT_SIZE.height
- },
- title: n.data.title,
- color: n.data.color,
- group: n.data.group,
- shell: n.data.shell,
- cwd: n.data.cwd
- }))
- return { version: 1, viewport, nodes: serialized }
+/** Serializes live React Flow nodes back into persisted node states. */
+export function flowToNodeStates(nodes: CanvasNode[]): CanvasNodeState[] {
+ const sizeFor = (kind: NodeKind) =>
+ kind === 'sticky' ? STICKY_SIZE : kind === 'group' ? GROUP_SIZE : TERMINAL_SIZE
+ return nodes.map((n) => {
+ const kind: NodeKind = (n.type as NodeKind) ?? 'terminal'
+ const collapsed = !!n.data.collapsed
+ return {
+ id: n.id,
+ kind,
+ position: n.position,
+ size: {
+ width: n.measured?.width ?? n.width ?? sizeFor(kind).width,
+ // While collapsed, persist the expanded height, not the shrunk one.
+ height: collapsed
+ ? n.data.expandedHeight ?? sizeFor(kind).height
+ : n.measured?.height ?? n.height ?? sizeFor(kind).height
+ },
+ title: n.data.title,
+ color: n.data.color,
+ group: n.data.group,
+ tags: n.data.tags,
+ collapsed: n.data.collapsed,
+ parentId: n.parentId,
+ shell: n.data.shell,
+ cwd: n.data.cwd,
+ text: n.data.text
+ }
+ })
}
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index f78142a37..1c4846b15 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -2,13 +2,24 @@
@import '@xyflow/react/dist/style.css';
:root {
- --bg: #11131a;
- --panel: #1a1d29;
- --panel-header: #232735;
- --border: #2c3142;
- --text: #c0caf5;
- --muted: #565f89;
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ /* macOS dark-mode palette (NSColor / HIG) */
+ --bg: #1e1e1e; /* content / canvas / terminal (controlBackground) */
+ --panel: #282828; /* bars, panels, node chrome (underPage) */
+ --panel-header: #323232; /* elevated / hover (windowBackground) */
+ --panel-2: #323232;
+ --border: rgba(255, 255, 255, 0.1); /* separator */
+ --text: rgba(255, 255, 255, 0.85); /* label */
+ --muted: rgba(255, 255, 255, 0.55); /* secondaryLabel */
+ --muted-2: rgba(255, 255, 255, 0.25); /* tertiaryLabel */
+ --accent: #0a84ff; /* systemBlue */
+ --accent-hover: #3a9bff;
+ --radius: 8px;
+ --radius-sm: 6px;
+ --radius-lg: 12px;
+ font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'SF Pro', 'Helvetica Neue',
+ sans-serif;
+ font-size: 13px;
+ -webkit-font-smoothing: antialiased;
}
* {
@@ -26,51 +37,318 @@ body,
overflow: hidden;
}
-/* ---- Top toolbar ---- */
-.toolbar {
- position: absolute;
- top: 12px;
- left: 12px;
- z-index: 10;
+.canvas-root {
+ width: 100%;
+ height: 100%;
+ position: relative;
+ display: flex;
+ flex-direction: column;
+}
+
+/* ---- Top project tab bar ---- */
+.tabbar {
+ position: relative;
display: flex;
- gap: 8px;
align-items: center;
+ gap: 14px;
+ height: 44px;
+ /* Leave room for the macOS traffic lights on the left. */
+ padding: 0 12px 0 86px;
background: var(--panel);
- border: 1px solid var(--border);
- border-radius: 10px;
- padding: 8px 10px;
- box-shadow: 0 6px 24px rgba(0, 0, 0, 0.35);
+ border-bottom: 1px solid var(--border);
+ /* Above the canvas and the menu backdrop so tabs/inputs stay interactive. */
+ z-index: 30;
+ flex-shrink: 0;
+ /* The bar itself is the window drag region. */
+ -webkit-app-region: drag;
+}
+
+/* Interactive elements inside the bar must not drag the window. */
+.tabbar button,
+.tabbar input,
+.tab,
+.tabbar__tabs {
+ -webkit-app-region: no-drag;
+}
+
+.tabbar__brand {
+ font-size: 13px;
+ font-weight: 700;
+ color: var(--muted);
+ letter-spacing: 0.2px;
+ white-space: nowrap;
+}
+
+.tabbar__tabs {
+ display: flex;
+ align-items: stretch;
+ gap: 2px;
+ height: 100%;
+ overflow-x: auto;
+}
+
+.tab {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 7px;
+ padding: 0 10px;
+ height: 100%;
+ border-bottom: 2px solid transparent;
+ color: var(--muted);
+ font-size: 13px;
+ cursor: pointer;
+ white-space: nowrap;
}
-.toolbar button {
+.tab:hover {
background: var(--panel-header);
+}
+
+.tab.active {
+ color: var(--text);
+ background: var(--panel-header);
+}
+
+.tab__dot {
+ width: 9px;
+ height: 9px;
+ border-radius: 50%;
+ flex-shrink: 0;
+}
+
+.tab__name {
+ max-width: 160px;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.tab__edit {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 5px;
+ color: var(--text);
+ font-size: 13px;
+ padding: 2px 6px;
+ width: 120px;
+ outline: none;
+}
+
+.tab__caret {
+ background: transparent;
+ border: none;
+ color: var(--muted);
+ cursor: pointer;
+ font-size: 13px;
+ line-height: 1;
+ padding: 2px 3px;
+ border-radius: 4px;
+}
+
+.tab__caret:hover {
+ background: var(--border);
+ color: var(--text);
+}
+
+.tab__add {
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ align-self: center;
+ width: 26px;
+ height: 26px;
+ margin-left: 4px;
+ background: transparent;
+ border: 1px solid var(--border);
+ border-radius: 7px;
color: var(--text);
+ font-size: 16px;
+ cursor: pointer;
+}
+
+.tab__add:hover {
+ background: var(--panel-header);
+}
+
+.tab-backdrop {
+ position: fixed;
+ inset: 0;
+ /* Below the tab bar (so tabs stay clickable) but above the canvas. */
+ z-index: 25;
+}
+
+.tab-menu {
+ position: fixed;
+ z-index: 40;
+ min-width: 150px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 6px;
+ background: rgba(40, 40, 42, 0.98);
border: 1px solid var(--border);
+ border-radius: 10px;
+ box-shadow: 0 12px 36px rgba(0, 0, 0, 0.55);
+}
+
+.tab-menu button {
+ display: flex;
+ align-items: center;
+ padding: 8px 10px;
+ background: transparent;
+ border: none;
border-radius: 7px;
- padding: 6px 12px;
+ color: var(--text);
font-size: 13px;
+ text-align: left;
cursor: pointer;
}
-.toolbar button:hover {
- background: #2c3142;
+.tab-menu button:hover {
+ background: var(--panel-header);
}
-.toolbar .dirty-dot {
- width: 8px;
- height: 8px;
- border-radius: 50%;
- background: var(--muted);
+.tab-menu button.danger {
+ color: #ff453a;
+}
+
+.tab-menu button:disabled {
+ color: var(--muted);
+ cursor: not-allowed;
+}
+
+.tab-menu button.danger:hover:not(:disabled) {
+ background: rgba(247, 118, 142, 0.15);
+}
+
+/* ---- Bottom-center dock ---- */
+.dock-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 19;
+}
+
+.dock {
+ position: absolute;
+ bottom: 22px;
+ left: 50%;
+ transform: translateX(-50%);
+ z-index: 20;
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ padding: 7px 10px;
+ background: rgba(40, 40, 42, 0.92);
+ backdrop-filter: blur(10px);
+ border: 1px solid var(--border);
+ border-radius: 16px;
+ box-shadow: 0 10px 32px rgba(0, 0, 0, 0.5);
+}
+
+.dock-btn {
+ position: relative;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ width: 38px;
+ height: 38px;
+ background: transparent;
+ color: var(--text);
+ border: none;
+ border-radius: 10px;
+ cursor: pointer;
+}
+
+.dock-btn:hover {
+ background: var(--panel-header);
+}
+
+.dock-add {
+ background: var(--accent);
+ color: #fff;
+}
+
+.dock-add:hover {
+ background: var(--accent-hover);
}
-.toolbar .dirty-dot.dirty {
- background: var(--e0af68, #e0af68);
+.dock-add.active {
+ background: #0060df;
+ color: #fff;
}
-.toolbar .hint {
+.dock-sep {
+ width: 1px;
+ height: 22px;
+ background: var(--border);
+ margin: 0 4px;
+}
+
+.dock-zoom-btn {
+ width: 30px;
+ height: 30px;
+}
+
+.dock-zoom {
+ min-width: 46px;
+ text-align: center;
font-size: 12px;
color: var(--muted);
- margin-left: 4px;
+ user-select: none;
+}
+
+.dock-dirty {
+ position: absolute;
+ top: 7px;
+ right: 7px;
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: transparent;
+}
+
+.dock-dirty.dirty {
+ background: #ffd60a;
+}
+
+/* Add-node menu above the dock */
+.dock-menu {
+ position: absolute;
+ bottom: calc(100% + 10px);
+ left: 0;
+ min-width: 190px;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: 6px;
+ background: rgba(40, 40, 42, 0.98);
+ backdrop-filter: blur(10px);
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ box-shadow: 0 12px 36px rgba(0, 0, 0, 0.55);
+}
+
+.dock-menu button {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 9px 12px;
+ background: transparent;
+ color: var(--text);
+ border: none;
+ border-radius: 8px;
+ font-size: 14px;
+ text-align: left;
+ cursor: pointer;
+}
+
+.dock-menu button:hover {
+ background: var(--panel-header);
+}
+
+.dock-menu svg {
+ color: var(--muted);
+ flex-shrink: 0;
}
/* ---- Terminal node ---- */
@@ -88,7 +366,7 @@ body,
}
.term-node.selected {
- border-color: #7aa2f7;
+ border-color: var(--accent);
}
.term-node__header {
@@ -140,20 +418,123 @@ body,
.term-node__close:hover {
background: rgba(247, 118, 142, 0.2);
- color: #f7768e;
+ color: #ff453a;
}
.term-node__body {
+ position: relative;
flex: 1;
min-height: 0;
+ background: var(--bg);
+}
+
+.term-node__xterm {
+ position: absolute;
+ inset: 0;
padding: 4px 2px 2px 6px;
- background: #11131a;
}
-.term-node__body .xterm {
+.term-node__xterm .xterm {
height: 100%;
}
+/* Transparent overlay that lets you pan across a terminal until you dwell/click. */
+.term-hover-guard {
+ position: absolute;
+ inset: 0;
+ z-index: 2;
+ cursor: default;
+}
+
+.term-node.collapsed {
+ border-bottom-width: 1px;
+}
+
+.term-node.collapsed .term-node__body,
+.term-node.collapsed .node-tags {
+ display: none;
+}
+
+.term-node__collapse {
+ background: transparent;
+ border: none;
+ color: var(--muted);
+ cursor: pointer;
+ font-size: 11px;
+ line-height: 1;
+ padding: 2px 4px;
+ border-radius: 4px;
+ flex-shrink: 0;
+}
+
+.term-node__collapse:hover {
+ background: rgba(255, 255, 255, 0.08);
+ color: var(--text);
+}
+
+/* ---- Node tags ---- */
+.node-tags {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 4px;
+ padding: 4px 8px;
+ background: var(--panel);
+ border-top: 1px solid var(--border);
+}
+
+.node-tag {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ padding: 1px 4px 1px 7px;
+ font-size: 11px;
+ color: var(--text);
+ background: var(--panel-header);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+}
+
+.node-tag button {
+ background: transparent;
+ border: none;
+ color: var(--muted);
+ cursor: pointer;
+ font-size: 12px;
+ line-height: 1;
+ padding: 0 1px;
+}
+
+.node-tag button:hover {
+ color: #ff453a;
+}
+
+.node-tag-add {
+ background: transparent;
+ border: 1px dashed var(--border);
+ color: var(--muted);
+ border-radius: 10px;
+ font-size: 11px;
+ padding: 1px 7px;
+ cursor: pointer;
+}
+
+.node-tag-add:hover {
+ color: var(--text);
+ border-color: var(--muted);
+}
+
+.node-tag-input {
+ width: 70px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ color: var(--text);
+ font-size: 11px;
+ padding: 1px 7px;
+ outline: none;
+}
+
/* Color picker popover */
.color-popover {
position: absolute;
@@ -180,3 +561,883 @@ body,
.react-flow {
background: var(--bg);
}
+
+.flow-wrap {
+ flex: 1;
+ min-height: 0;
+ position: relative;
+}
+
+/* ---- Right-click context menu ---- */
+.ctx-backdrop {
+ position: fixed;
+ inset: 0;
+ z-index: 45;
+}
+
+.ctx-menu {
+ position: fixed;
+ z-index: 46;
+ min-width: 180px;
+ display: flex;
+ flex-direction: column;
+ gap: 1px;
+ padding: 6px;
+ background: rgba(40, 40, 42, 0.98);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ box-shadow: 0 12px 36px rgba(0, 0, 0, 0.55);
+}
+
+.ctx-item {
+ display: flex;
+ align-items: center;
+ padding: 8px 10px;
+ background: transparent;
+ border: none;
+ border-radius: 7px;
+ color: var(--text);
+ font-size: 13px;
+ text-align: left;
+ cursor: pointer;
+}
+
+.ctx-item:hover:not(:disabled) {
+ background: var(--panel-header);
+}
+
+.ctx-item:disabled {
+ color: var(--muted);
+ cursor: not-allowed;
+}
+
+.ctx-item.danger {
+ color: #ff453a;
+}
+
+.ctx-item.danger:hover:not(:disabled) {
+ background: rgba(247, 118, 142, 0.15);
+}
+
+.ctx-sep {
+ height: 1px;
+ background: var(--border);
+ margin: 4px 2px;
+}
+
+.ctx-label {
+ padding: 4px 10px;
+ font-size: 11px;
+ color: var(--muted);
+ text-transform: uppercase;
+ letter-spacing: 0.4px;
+}
+
+.ctx-colors {
+ display: grid;
+ grid-template-columns: repeat(7, 1fr);
+ gap: 5px;
+ padding: 6px 8px;
+}
+
+.ctx-colors button {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ cursor: pointer;
+}
+
+/* ---- Sticky note node ---- */
+.sticky-node {
+ width: 100%;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ border: 1px solid;
+ border-radius: 10px;
+ overflow: hidden;
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.35);
+}
+
+.sticky-node.selected {
+ box-shadow: 0 0 0 1px var(--accent), 0 8px 28px rgba(0, 0, 0, 0.4);
+}
+
+.sticky-node__header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 8px;
+ cursor: grab;
+ user-select: none;
+}
+
+.sticky-node__body {
+ flex: 1;
+ min-height: 0;
+ resize: none;
+ background: transparent;
+ border: none;
+ outline: none;
+ color: var(--text);
+ font-family: inherit;
+ font-size: 13px;
+ line-height: 1.45;
+ padding: 8px 10px;
+}
+
+.sticky-node__body::placeholder {
+ color: rgba(192, 202, 245, 0.4);
+}
+
+.sticky-node.collapsed .sticky-node__body {
+ display: none;
+}
+
+/* ---- Top-right controls cluster ---- */
+.controls-cluster {
+ position: absolute;
+ top: 54px;
+ right: 14px;
+ z-index: 11;
+ display: flex;
+ gap: 6px;
+}
+
+.controls-cluster button {
+ width: 34px;
+ height: 34px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: rgba(40, 40, 42, 0.92);
+ border: 1px solid var(--border);
+ border-radius: 9px;
+ color: var(--text);
+ font-size: 15px;
+ cursor: pointer;
+ box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
+}
+
+.controls-cluster button:hover {
+ background: var(--panel-header);
+}
+
+/* ---- Right-side drawer (settings / source control) ---- */
+.drawer-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 55;
+ background: rgba(10, 12, 18, 0.4);
+ display: flex;
+ justify-content: flex-end;
+}
+
+.drawer {
+ width: 360px;
+ max-width: 92vw;
+ height: 100%;
+ background: var(--panel);
+ border-left: 1px solid var(--border);
+ box-shadow: -16px 0 48px rgba(0, 0, 0, 0.5);
+ display: flex;
+ flex-direction: column;
+}
+
+.drawer.scm {
+ width: 460px;
+}
+
+.drawer__head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 14px 16px;
+ border-bottom: 1px solid var(--border);
+}
+
+.drawer__head h2 {
+ margin: 0;
+ font-size: 15px;
+}
+
+.drawer__close {
+ background: transparent;
+ border: none;
+ color: var(--muted);
+ font-size: 20px;
+ line-height: 1;
+ cursor: pointer;
+}
+
+.drawer__close:hover {
+ color: var(--text);
+}
+
+.drawer__body {
+ flex: 1;
+ overflow-y: auto;
+ padding: 8px 16px 24px;
+}
+
+.drawer__body section {
+ padding: 12px 0;
+ border-bottom: 1px solid var(--border);
+}
+
+.drawer__body h3 {
+ margin: 0 0 8px;
+ font-size: 12px;
+ text-transform: uppercase;
+ letter-spacing: 0.4px;
+ color: var(--muted);
+}
+
+.set-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 5px 0;
+ font-size: 13px;
+}
+
+.set-row input[type='text'],
+.set-row input[type='number'] {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--text);
+ padding: 5px 8px;
+ font-size: 12px;
+ width: 160px;
+ outline: none;
+}
+
+.set-row input[type='number'] {
+ width: 80px;
+}
+
+.set-row select {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--text);
+ padding: 5px 8px;
+ font-size: 12px;
+ outline: none;
+}
+
+.set-col {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ padding: 6px 0;
+ font-size: 13px;
+}
+
+.set-textarea {
+ width: 100%;
+ min-height: 54px;
+ resize: vertical;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--text);
+ font-family: inherit;
+ font-size: 12px;
+ padding: 7px 9px;
+ outline: none;
+}
+
+.set-swatches {
+ display: flex;
+ gap: 5px;
+}
+
+.set-swatches button {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+ border: 1px solid rgba(255, 255, 255, 0.15);
+ cursor: pointer;
+}
+
+.set-swatches button.active {
+ outline: 2px solid var(--text);
+ outline-offset: 1px;
+}
+
+.set-note {
+ margin: 0 0 8px;
+ font-size: 11px;
+ color: var(--muted);
+}
+
+/* ---- Source control ---- */
+.sc-meta {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 12px;
+ font-size: 12px;
+ color: var(--muted);
+}
+
+.sc-branch {
+ color: var(--text);
+ font-weight: 600;
+}
+
+.sc-message {
+ width: 100%;
+ min-height: 60px;
+ resize: vertical;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ color: var(--text);
+ font-family: inherit;
+ font-size: 13px;
+ padding: 8px 10px;
+ outline: none;
+ margin-bottom: 8px;
+}
+
+.sc-actions {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px;
+ margin-bottom: 8px;
+}
+
+.sc-btn {
+ background: var(--panel-header);
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ color: var(--text);
+ font-size: 12px;
+ padding: 7px 11px;
+ cursor: pointer;
+}
+
+.sc-btn:hover:not(:disabled) {
+ background: var(--panel-2);
+}
+
+.sc-btn.primary {
+ background: var(--accent, var(--accent));
+ color: #fff;
+ border-color: transparent;
+ font-weight: 600;
+}
+
+.sc-btn:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.sc-log {
+ white-space: pre-wrap;
+ word-break: break-word;
+ font-size: 11px;
+ color: var(--muted);
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 8px 10px;
+ max-height: 160px;
+ overflow-y: auto;
+}
+
+.sc-graph {
+ margin: 0;
+ font-family: Menlo, Monaco, 'Courier New', monospace;
+ font-size: 11px;
+ line-height: 1.5;
+ color: var(--text);
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 8px 10px;
+ max-height: 260px;
+ overflow: auto;
+ white-space: pre;
+}
+
+/* ---- Source control (VS Code style) ---- */
+.scm-bar {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 16px;
+ border-bottom: 1px solid var(--border);
+ font-family: Menlo, Monaco, monospace;
+ font-size: 13px;
+}
+
+.scm-repo {
+ color: var(--text);
+}
+
+.scm-branch {
+ background: rgba(122, 162, 247, 0.15);
+ color: #a9c0ff;
+ border: 1px solid rgba(122, 162, 247, 0.3);
+ border-radius: 7px;
+ padding: 3px 9px;
+ font-family: inherit;
+ font-size: 12px;
+ cursor: pointer;
+}
+
+.scm-branch:hover {
+ background: rgba(122, 162, 247, 0.25);
+}
+
+.scm-spacer {
+ flex: 1;
+}
+
+.scm-ahead {
+ color: #32d74b;
+}
+
+.scm-behind {
+ color: var(--muted);
+}
+
+.scm-sync {
+ background: var(--panel-header);
+ border: 1px solid var(--border);
+ border-radius: 7px;
+ color: var(--text);
+ font-size: 12px;
+ padding: 4px 11px;
+ cursor: pointer;
+}
+
+.scm-sync:hover:not(:disabled) {
+ background: var(--panel-2);
+}
+
+.scm-sync:disabled {
+ opacity: 0.5;
+ cursor: not-allowed;
+}
+
+.scm-body {
+ font-family: Menlo, Monaco, monospace;
+}
+
+.scm-section {
+ padding: 14px 0 6px;
+}
+
+.scm-section-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0 2px 8px;
+ font-size: 11px;
+ letter-spacing: 0.5px;
+ color: var(--muted);
+}
+
+.scm-section-head b {
+ color: var(--text);
+ background: var(--panel-header);
+ border-radius: 8px;
+ padding: 0 7px;
+ margin-left: 2px;
+}
+
+.scm-section-head button {
+ background: transparent;
+ border: none;
+ color: #a9c0ff;
+ font-size: 12px;
+ cursor: pointer;
+ font-family: inherit;
+}
+
+.scm-section-head button:hover {
+ text-decoration: underline;
+}
+
+.scm-file {
+ display: flex;
+ align-items: center;
+ gap: 9px;
+ padding: 5px 2px;
+ font-size: 13px;
+}
+
+.scm-row-actions {
+ display: flex;
+ gap: 2px;
+ flex-shrink: 0;
+ opacity: 0;
+}
+
+.scm-file:hover .scm-row-actions,
+.scm-file.open .scm-row-actions {
+ opacity: 1;
+}
+
+.scm-iconbtn {
+ width: 20px;
+ height: 20px;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ background: transparent;
+ border: none;
+ border-radius: 5px;
+ color: var(--muted);
+ font-size: 15px;
+ line-height: 1;
+ cursor: pointer;
+}
+
+.scm-iconbtn:hover {
+ background: var(--panel-header);
+ color: var(--text);
+}
+
+.scm-letter {
+ width: 12px;
+ text-align: center;
+ font-weight: 700;
+ flex-shrink: 0;
+}
+
+.scm-path {
+ flex: 1;
+ min-width: 0;
+ background: transparent;
+ border: none;
+ color: var(--text);
+ font-family: inherit;
+ font-size: 13px;
+ text-align: left;
+ cursor: pointer;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+}
+
+.scm-path:hover {
+ color: #a9c0ff;
+ text-decoration: underline;
+}
+
+.scm-file.open .scm-path {
+ color: #a9c0ff;
+}
+
+.scm-discard {
+ background: transparent;
+ border: none;
+ color: var(--muted);
+ cursor: pointer;
+ font-size: 13px;
+ padding: 0 4px;
+ flex-shrink: 0;
+}
+
+.scm-discard:hover {
+ color: #ff453a;
+}
+
+.scm-diff {
+ margin: 2px 0 8px 26px;
+ padding: 8px 10px;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ font-family: Menlo, Monaco, monospace;
+ font-size: 11px;
+ line-height: 1.5;
+ max-height: 280px;
+ overflow: auto;
+ white-space: pre;
+}
+
+.scm-diff > div {
+ min-height: 1em;
+}
+
+.scm-diff .d-add {
+ color: #32d74b;
+ background: rgba(158, 206, 106, 0.08);
+}
+
+.scm-diff .d-del {
+ color: #ff453a;
+ background: rgba(247, 118, 142, 0.08);
+}
+
+.scm-diff .d-hunk {
+ color: #6ac4dc;
+}
+
+.scm-diff .d-meta {
+ color: var(--muted);
+}
+
+.scm-diff .d-ctx {
+ color: var(--text);
+}
+
+.scm-stat {
+ flex-shrink: 0;
+ display: flex;
+ gap: 6px;
+}
+
+.scm-add {
+ color: #32d74b;
+}
+
+.scm-del {
+ color: #ff453a;
+}
+
+.scm-commit {
+ padding: 14px 0;
+}
+
+.scm-commit-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0 2px 8px;
+ font-size: 11px;
+ letter-spacing: 0.5px;
+ color: var(--muted);
+ text-transform: uppercase;
+}
+
+.scm-gen {
+ background: rgba(10, 132, 255, 0.15);
+ border: 1px solid rgba(10, 132, 255, 0.4);
+ color: #6cb0ff;
+ border-radius: 7px;
+ font-size: 11px;
+ letter-spacing: 0.2px;
+ text-transform: none;
+ padding: 3px 10px;
+ cursor: pointer;
+}
+
+.scm-gen:hover:not(:disabled) {
+ background: rgba(10, 132, 255, 0.28);
+}
+
+.scm-gen:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+}
+
+.scm-message {
+ width: 100%;
+ min-height: 64px;
+ resize: vertical;
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ color: var(--text);
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+ font-size: 14px;
+ padding: 10px 12px;
+ outline: none;
+}
+
+.scm-commit-foot {
+ display: flex;
+ justify-content: space-between;
+ padding: 8px 2px 12px;
+ font-size: 11px;
+ color: var(--muted);
+}
+
+.scm-commit-btn {
+ width: 100%;
+ background: var(--accent, var(--accent));
+ color: #fff;
+ border: none;
+ border-radius: 10px;
+ padding: 12px;
+ font-size: 14px;
+ font-weight: 700;
+ cursor: pointer;
+ box-shadow: 0 6px 20px rgba(122, 162, 247, 0.35);
+}
+
+.scm-commit-btn:disabled {
+ opacity: 0.45;
+ cursor: not-allowed;
+ box-shadow: none;
+}
+
+.scm-commit-row {
+ display: flex;
+ align-items: baseline;
+ gap: 10px;
+ padding: 7px 2px;
+ font-size: 13px;
+ border-top: 1px solid var(--border);
+}
+
+.scm-hash {
+ color: #a9c0ff;
+ flex-shrink: 0;
+}
+
+.scm-subject {
+ flex: 1;
+ color: var(--text);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
+}
+
+.scm-rel {
+ color: var(--muted);
+ flex-shrink: 0;
+ font-size: 11px;
+}
+
+/* ---- Command palette ---- */
+.palette-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 60;
+ display: flex;
+ justify-content: center;
+ align-items: flex-start;
+ padding-top: 12vh;
+ background: rgba(10, 12, 18, 0.45);
+}
+
+.palette {
+ width: 560px;
+ max-width: 90vw;
+ max-height: 60vh;
+ display: flex;
+ flex-direction: column;
+ background: rgba(40, 40, 42, 0.99);
+ border: 1px solid var(--border);
+ border-radius: 14px;
+ box-shadow: 0 24px 64px rgba(0, 0, 0, 0.6);
+ overflow: hidden;
+}
+
+.palette__input {
+ background: transparent;
+ border: none;
+ border-bottom: 1px solid var(--border);
+ color: var(--text);
+ font-size: 15px;
+ padding: 14px 16px;
+ outline: none;
+}
+
+.palette__list {
+ overflow-y: auto;
+ padding: 6px;
+}
+
+.palette__item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ width: 100%;
+ padding: 9px 12px;
+ background: transparent;
+ border: none;
+ border-radius: 8px;
+ color: var(--text);
+ font-size: 13px;
+ text-align: left;
+ cursor: pointer;
+}
+
+.palette__item.active {
+ background: var(--panel-header);
+}
+
+.palette__hint {
+ color: var(--muted);
+ font-size: 11px;
+}
+
+.palette__empty {
+ padding: 16px;
+ color: var(--muted);
+ font-size: 13px;
+ text-align: center;
+}
+
+/* ---- Group frame node ---- */
+.group-node {
+ width: 100%;
+ height: 100%;
+ border: 1.5px dashed;
+ border-radius: 12px;
+ display: flex;
+ flex-direction: column;
+}
+
+.group-node__header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 5px 8px;
+ cursor: grab;
+ user-select: none;
+}
+
+.group-node__ungroup {
+ background: transparent;
+ border: 1px solid var(--border);
+ color: var(--muted);
+ border-radius: 6px;
+ font-size: 11px;
+ padding: 2px 7px;
+ cursor: pointer;
+}
+
+.group-node__ungroup:hover {
+ background: var(--panel-header);
+ color: var(--text);
+}
+
+/* ---- Minimap ---- */
+.minimap {
+ background: rgba(40, 40, 42, 0.85) !important;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ overflow: hidden;
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4);
+}
+
+/* React Flow controls dark theme */
+.react-flow__controls {
+ border-radius: 10px;
+ overflow: hidden;
+ box-shadow: 0 8px 28px rgba(0, 0, 0, 0.4);
+}
+
+.react-flow__controls-button {
+ background: var(--panel);
+ border-bottom: 1px solid var(--border);
+ color: var(--text);
+ fill: var(--text);
+}
+
+.react-flow__controls-button:hover {
+ background: var(--panel-header);
+}
diff --git a/src/renderer/terminal/local-transport.ts b/src/renderer/terminal/local-transport.ts
index 726ea1d0b..4e568abf7 100644
--- a/src/renderer/terminal/local-transport.ts
+++ b/src/renderer/terminal/local-transport.ts
@@ -27,6 +27,10 @@ export class LocalTransport implements TerminalTransport {
this.pty.kill(sessionId)
}
+ destroy(persistKey: string): void {
+ this.pty.destroy(persistKey)
+ }
+
onData(sessionId: string, listener: (data: string) => void): () => void {
return this.pty.onData(sessionId, listener)
}
diff --git a/src/renderer/terminal/scale-fix.ts b/src/renderer/terminal/scale-fix.ts
new file mode 100644
index 000000000..44ca80544
--- /dev/null
+++ b/src/renderer/terminal/scale-fix.ts
@@ -0,0 +1,56 @@
+import type { Terminal } from '@xterm/xterm'
+
+/**
+ * Fixes mouse selection drift when a terminal lives under a CSS `transform: scale()`
+ * (React Flow zoom).
+ *
+ * xterm computes cell coordinates as `(clientX - rect.left) / cssCellWidth`. `rect.left`
+ * comes from `getBoundingClientRect()` which IS scale-aware, so `clientX - rect.left` is in
+ * scaled screen pixels — but `cssCellWidth` is the UNSCALED cell size. The result is off by
+ * the zoom factor, so the selection lands away from the cursor at any zoom != 1.
+ *
+ * We wrap the internal MouseService and convert the event's client coords back into the
+ * terminal's own (unscaled) pixel space before xterm runs its math:
+ * fakeClientX = rect.left + (clientX - rect.left) / scale
+ * which makes `fakeClientX - rect.left = (clientX - rect.left) / scale` — the correct
+ * unscaled offset. No-ops at scale 1.
+ */
+export function patchTerminalScale(term: Terminal, getScale: () => number): void {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const ms: any = (term as unknown as { _core?: { _mouseService?: unknown } })._core?._mouseService
+ if (!ms || ms.__scalePatched) return
+ ms.__scalePatched = true
+
+ const adjust = (event: MouseEvent, element: HTMLElement): MouseEvent => {
+ const s = getScale() || 1
+ if (Math.abs(s - 1) < 0.001) return event
+ const rect = element.getBoundingClientRect()
+ return new Proxy(event, {
+ get(target, prop) {
+ if (prop === 'clientX') return rect.left + (event.clientX - rect.left) / s
+ if (prop === 'clientY') return rect.top + (event.clientY - rect.top) / s
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ const value = (target as any)[prop]
+ return typeof value === 'function' ? value.bind(target) : value
+ }
+ }) as MouseEvent
+ }
+
+ const origGetCoords = typeof ms.getCoords === 'function' ? ms.getCoords.bind(ms) : null
+ if (origGetCoords) {
+ ms.getCoords = (
+ event: MouseEvent,
+ element: HTMLElement,
+ cols: number,
+ rows: number,
+ isSelection?: boolean
+ ) => origGetCoords(adjust(event, element), element, cols, rows, isSelection)
+ }
+
+ const origReport =
+ typeof ms.getMouseReportCoords === 'function' ? ms.getMouseReportCoords.bind(ms) : null
+ if (origReport) {
+ ms.getMouseReportCoords = (event: MouseEvent, element: HTMLElement) =>
+ origReport(adjust(event, element), element)
+ }
+}
diff --git a/src/renderer/terminal/transport.ts b/src/renderer/terminal/transport.ts
index 655f43ef4..3be43a485 100644
--- a/src/renderer/terminal/transport.ts
+++ b/src/renderer/terminal/transport.ts
@@ -12,7 +12,10 @@ export interface TerminalTransport {
create(options: PtyCreateOptions): Promise<string>
write(sessionId: string, data: string): void
resize(sessionId: string, cols: number, rows: number): void
+ /** Detaches the client; with tmux the underlying session survives. */
kill(sessionId: string): void
+ /** Permanently ends a node's persistent session. */
+ destroy(persistKey: string): void
/** Listens for output; returns an unsubscribe function. */
onData(sessionId: string, listener: (data: string) => void): () => void
/** Fires when the session closes; returns an unsubscribe function. */
diff --git a/src/shared/ipc.ts b/src/shared/ipc.ts
index d5231c989..4b84641ca 100644
--- a/src/shared/ipc.ts
+++ b/src/shared/ipc.ts
@@ -5,9 +5,29 @@ export const IPC = {
ptyWrite: 'pty:write',
ptyResize: 'pty:resize',
ptyKill: 'pty:kill',
+ ptyDestroy: 'pty:destroy',
// Events broadcast from main to the renderer (sessionId is appended to the channel name).
ptyData: (sessionId: string) => `pty:data:${sessionId}`,
ptyExit: (sessionId: string) => `pty:exit:${sessionId}`,
workspaceLoad: 'workspace:load',
- workspaceSave: 'workspace:save'
+ workspaceSave: 'workspace:save',
+ dialogSelectFolder: 'dialog:select-folder',
+ settingsLoad: 'settings:load',
+ settingsSave: 'settings:save',
+ gitStatus: 'git:status',
+ gitInit: 'git:init',
+ gitCommit: 'git:commit',
+ gitPush: 'git:push',
+ gitPull: 'git:pull',
+ gitSync: 'git:sync',
+ gitPublish: 'git:publish',
+ gitStage: 'git:stage',
+ gitUnstage: 'git:unstage',
+ gitStageAll: 'git:stage-all',
+ gitUnstageAll: 'git:unstage-all',
+ gitDiff: 'git:diff',
+ gitDiscard: 'git:discard',
+ gitSwitchBranch: 'git:switch-branch',
+ gitCreateBranch: 'git:create-branch',
+ commitGenerate: 'commit:generate'
} as const
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 9e33206d0..bbcfc464f 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -5,18 +5,35 @@ export interface PtyCreateOptions {
cwd?: string
cols: number
rows: number
+ /**
+ * Stable key (the node id) used to derive a persistent tmux session name so the
+ * terminal reattaches to the same session across remounts and app restarts.
+ */
+ persistKey?: string
}
-/** Persisted state of a single terminal node. */
-export interface TerminalNodeState {
+export type NodeKind = 'terminal' | 'sticky' | 'group'
+
+/** Persisted state of a single canvas node (terminal, sticky note, or group frame). */
+export interface CanvasNodeState {
id: string
+ kind: NodeKind
position: { x: number; y: number }
size: { width: number; height: number }
title: string
color: string
group: string | null
+ /** Labels for organizing/filtering terminals. */
+ tags?: string[]
+ /** When true the node body is hidden (header-only). */
+ collapsed?: boolean
+ /** Parent group node id, if this node belongs to a group frame. */
+ parentId?: string
+ // terminal-only
shell?: string
cwd?: string
+ // sticky-only
+ text?: string
}
/** Canvas pan/zoom state. */
@@ -26,17 +43,45 @@ export interface Viewport {
zoom: number
}
+/** A project is one canvas/page: its own nodes, viewport, and default working dir. */
+export interface Project {
+ id: string
+ name: string
+ color: string
+ /** Default working directory for new terminals created in this project. */
+ cwd?: string
+ viewport: Viewport
+ nodes: CanvasNodeState[]
+}
+
/** The full workspace written to / read from disk. */
export interface Workspace {
+ version: 2
+ activeProjectId: string
+ projects: Project[]
+}
+
+/** Old single-canvas format (v1), kept only for migration on load. */
+export interface WorkspaceV1 {
version: 1
viewport: Viewport
- nodes: TerminalNodeState[]
+ nodes: CanvasNodeState[]
}
+export const DEFAULT_PROJECT_ID = 'project-1'
+
export const EMPTY_WORKSPACE: Workspace = {
- version: 1,
- viewport: { x: 0, y: 0, zoom: 1 },
- nodes: []
+ version: 2,
+ activeProjectId: DEFAULT_PROJECT_ID,
+ projects: [
+ {
+ id: DEFAULT_PROJECT_ID,
+ name: 'Project 1',
+ color: '#7aa2f7',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: []
+ }
+ ]
}
// ---- Contract for the API exposed to the renderer via preload ----
@@ -48,8 +93,10 @@ export interface PtyApi {
write(sessionId: string, data: string): void
/** Updates the PTY when the terminal is resized. */
resize(sessionId: string, cols: number, rows: number): void
- /** Terminates the session. */
+ /** Detaches/terminates the PTY client (the underlying tmux session survives). */
kill(sessionId: string): void
+ /** Permanently ends the persistent session for a node (kills its tmux session). */
+ destroy(persistKey: string): void
/** Listens for PTY output. Returns an unsubscribe function. */
onData(sessionId: string, listener: (data: string) => void): () => void
/** Fires when the PTY process exits. Returns an unsubscribe function. */
@@ -61,7 +108,119 @@ export interface WorkspaceApi {
save(workspace: Workspace): Promise<void>
}
+export interface DialogApi {
+ /** Opens a native folder picker; returns the chosen path or null if cancelled. */
+ selectFolder(): Promise<string | null>
+}
+
+/** User-configurable application settings (settings.json). */
+export interface Settings {
+ fontSize: number
+ fontFamily: string
+ cursorBlink: boolean
+ /** Empty string = use the system default shell. */
+ defaultShell: string
+ gridSize: number
+ snapToGrid: boolean
+ /** ms to dwell over a terminal before it takes pointer focus (pan-across guard). */
+ panHoverDelay: number
+ doubleClickFocus: boolean
+ accent: string
+ tmuxEnabled: boolean
+ tmuxScrollback: number
+ /** AI commit message agent: a local coding-agent CLI run read-only. */
+ commitAgent: 'claude' | 'codex' | 'custom'
+ /** For commitAgent='custom': command template; {prompt} placeholder optional (else stdin). */
+ commitAgentCommand: string
+ /** Extra instructions appended to the commit prompt (e.g. Conventional Commits). */
+ commitExtraPrompt: string
+}
+
+export const DEFAULT_SETTINGS: Settings = {
+ fontSize: 13,
+ fontFamily: 'Menlo, Monaco, "Courier New", monospace',
+ cursorBlink: true,
+ defaultShell: '',
+ gridSize: 24,
+ snapToGrid: false,
+ panHoverDelay: 300,
+ doubleClickFocus: true,
+ accent: '#0a84ff',
+ tmuxEnabled: true,
+ tmuxScrollback: 50000,
+ commitAgent: 'claude',
+ commitAgentCommand: '',
+ commitExtraPrompt: ''
+}
+
+export interface SettingsApi {
+ load(): Promise<Settings>
+ save(settings: Settings): Promise<void>
+}
+
+export interface GitFileChange {
+ path: string
+ /** Single-letter status: M (modified), A (added), D (deleted), R (renamed), U (untracked). */
+ status: string
+ added: number
+ deleted: number
+}
+
+export interface GitCommit {
+ hash: string
+ subject: string
+ relative: string
+}
+
+export interface GitStatus {
+ hasRepo: boolean
+ /** "owner/repo" from the origin remote, else the folder name. */
+ repoName: string
+ branch: string
+ /** Local branch names (for the branch switcher). */
+ branches: string[]
+ ahead: number
+ behind: number
+ hasRemote: boolean
+ ghAvailable: boolean
+ staged: GitFileChange[]
+ changes: GitFileChange[]
+ recent: GitCommit[]
+}
+
+export interface GitResult {
+ ok: boolean
+ message: string
+}
+
+export interface GitApi {
+ status(cwd: string): Promise<GitStatus>
+ init(cwd: string): Promise<GitResult>
+ /** Commits the staged changes (no implicit add). */
+ commit(cwd: string, message: string): Promise<GitResult>
+ push(cwd: string): Promise<GitResult>
+ pull(cwd: string): Promise<GitResult>
+ /** Pull then push. */
+ sync(cwd: string): Promise<GitResult>
+ publish(cwd: string, name: string, isPrivate: boolean): Promise<GitResult>
+ stage(cwd: string, paths: string[]): Promise<GitResult>
+ unstage(cwd: string, paths: string[]): Promise<GitResult>
+ stageAll(cwd: string): Promise<GitResult>
+ unstageAll(cwd: string): Promise<GitResult>
+ /** Unified diff for a file. `staged` selects index vs worktree; untracked shows full file. */
+ diff(cwd: string, path: string, staged: boolean, untracked: boolean): Promise<string>
+ /** Discard a file's changes (or delete it if untracked). */
+ discard(cwd: string, path: string, untracked: boolean): Promise<GitResult>
+ switchBranch(cwd: string, name: string): Promise<GitResult>
+ createBranch(cwd: string, name: string): Promise<GitResult>
+ /** Generate a commit message from the staged diff via a local AI agent CLI. */
+ generateMessage(cwd: string): Promise<GitResult>
+}
+
export interface NodeTerminalApi {
pty: PtyApi
workspace: WorkspaceApi
+ dialog: DialogApi
+ settings: SettingsApi
+ git: GitApi
}