Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat: sync desktop terminal themes to remote daemon tmux windows

0xken154c7af5e03184
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index 5e2e7621e..1a3904ef1 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -280,6 +280,40 @@ describe('BackendSocket outbound queue', () => {
await socket.stop()
})
+ it('hands theme_set to the host-theme sink and acknowledges it to the requester', async () => {
+ const socket = new BackendSocket('token')
+ const received: unknown[] = []
+ socket.hostThemeSink = (theme) => received.push(theme)
+ socket.connect()
+ const ws = wsMock.instances[0]
+ ws.open()
+ const unwrap = vi.spyOn(socket.e2ee, 'unwrapDown')
+ vi.spyOn(socket.e2ee, 'hasSession').mockReturnValue(true)
+ const wrapReply = vi.spyOn(socket.e2ee, 'wrapRpcReply').mockReturnValue({
+ type: 'theme_set_result', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } },
+ })
+ const envelope = { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } }
+
+ unwrap.mockReturnValueOnce({
+ type: 'theme_set', payload: { requestId: 't-1', background: '#171B29', foreground: '#f5f5f5' },
+ })
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'theme_set', payload: envelope } })
+ await vi.waitFor(() => {
+ expect(wrapReply).toHaveBeenCalledWith('web-1', 'theme_set_result', 't-1', { applied: true })
+ })
+ // Normalised to lowercase, and a full pair — never half a style.
+ expect(received).toEqual([{ background: '#171b29', foreground: '#f5f5f5' }])
+
+ // A malformed colour is refused, not half-applied.
+ unwrap.mockReturnValueOnce({ type: 'theme_set', payload: { requestId: 't-2', background: 'dark' } })
+ ws.message({ t: 'down', connId: 'web-1', frame: { type: 'theme_set', payload: envelope } })
+ await vi.waitFor(() => {
+ expect(wrapReply).toHaveBeenCalledWith('web-1', 'theme_set_result', 't-2', { error: 'BAD_THEME' })
+ })
+ expect(received).toHaveLength(1)
+ await socket.stop()
+ })
+
it('answers usage_read with this machine\'s own readings, wrapped for the requester', async () => {
// What goes back names what the person spends and on whose account, so it must leave encrypted.
// The reader is the socket's own field: this never touches a real home, Keychain or network.
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 6510ff46b..92a5d5b22 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -41,6 +41,7 @@ import { listFileTree, readProjectFile } from './lib/files.js'
import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'
import { codexMessagesToEvents, windowCodexLines } from './engines/codex/normalizer.js'
import { codexSubagentResolverFor } from './engines/codex/subagent.js'
+import { parseHostTheme, type HostTheme } from './lib/hostTheme.js'
import { cursorMessagesToEvents, windowCursorLines } from './engines/cursor/normalizer.js'
import { loadCursorReplayTaskLinks } from './engines/cursor/subagent.js'
import { opencodeMessagesToEvents, windowOpencodeMessages } from './engines/opencode/normalizer.js'
@@ -382,6 +383,9 @@ export class BackendSocket {
/** Answers `usage_read` — this machine's own agent-account usage (lib/accountUsage.ts). A field
* rather than a direct call so a spec answers it without a real home, Keychain or network. */
accountUsageReader: () => Promise<AccountUsageReading[]> = readAccountUsage
+ /** Receives `theme_set` — the desktop's pane colours, to become this machine's tmux
+ * `window-style` (lib/hostTheme.ts). Wired by cli.ts; null answers with UNSUPPORTED. */
+ hostThemeSink: ((theme: HostTheme) => void) | null = null
runtimeProfileProvider: ((session: RegisteredSession) => string | null) | null = null
onRuntimeProfileUpdate: ((sessionId: string, selectedModel: string) => Promise<void>) | null = null
/** Web↔adapter E2EE: group-encrypts user events, runs the CPace pairing, holds per-conn sessions. */
@@ -1817,6 +1821,17 @@ export class BackendSocket {
return
}
+ // The colours the desktop paints its panes with, so tmux answers a TUI's OSC 10/11 with
+ // them instead of with whatever terminal happened to attach first (lib/hostTheme.ts).
+ case 'theme_set': {
+ if (!this.hostThemeSink) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }
+ const theme = parseHostTheme(payload)
+ if (!theme) { reply(type, requestId, { error: 'BAD_THEME' }); return }
+ this.hostThemeSink(theme)
+ reply(type, requestId, { applied: true })
+ return
+ }
+
// v1 no-ops: no programmatic session control over an interactive tmux claude.
case 'new_chat':
case 'compact':
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index d4164231a..c35f1989f 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -66,6 +66,7 @@ import { terminateDeletedAgent, checkPidRuntime } from './lib/deleteAgentFallbac
import { restartAgent, type RestartAgentDeps } from './lib/restartAgent.js'
import { claudeContinuation, findLiveSession } from './lib/sessionRepair.js'
import { TmuxBackend } from './lib/tmuxBackend.js'
+import { DEFAULT_HOST_THEME, loadHostTheme, saveHostTheme, type HostTheme } from './lib/hostTheme.js'
import { createAndRegisterPane } from './lib/createAgentPane.js'
import { restoreAgents } from './lib/restoreAgents.js'
import { buildLaunchOverrides, validateLaunchOverrides, type LaunchOverridesDeps, type LaunchOverridesResult, type LaunchSource } from './lib/launchOverrides.js'
@@ -1030,7 +1031,11 @@ async function runForeground(session: AuthSession): Promise<void> {
console.log(`[tmux] not on the daemon PATH · adopted ${tmuxPath.from} from the user's login shell`)
}
}
- const tmuxBackend = terminalConfig.backends.includes('tmux') ? new TmuxBackend() : null
+ // The desktop's pane colours, for tmux's `window-style` (lib/hostTheme.ts): the last ones the app
+ // sent, or its stock dark palette until it says otherwise. Read through a closure so a change
+ // reaches sessions created after it without rebuilding the backend.
+ let hostTheme: HostTheme = loadHostTheme() ?? DEFAULT_HOST_THEME
+ const tmuxBackend = terminalConfig.backends.includes('tmux') ? new TmuxBackend(() => hostTheme) : null
const herdrTargets = await resolveHerdrTargets()
activeHerdrSessions = herdrTargets.map((target) => target.sessionName)
const resolvedHerdrPaths = herdrTargets.flatMap((target) => target.state === 'available' ? [target.endpoint.socketPath] : [])
@@ -1370,6 +1375,17 @@ async function runForeground(session: AuthSession): Promise<void> {
diagnostic: (event, fields) => console.log(`[terminal-stream] ${event}`, fields),
})
backend.setTerminalStreamManager(terminalStreams)
+ // `agentReconciler` is declared further down; this closure only ever runs for a frame, and no
+ // socket is connected until well after that declaration (backend.connect() is the last thing
+ // this function does).
+ backend.hostThemeSink = (theme) => {
+ if (theme.background === hostTheme.background && theme.foreground === hostTheme.foreground) return
+ hostTheme = theme
+ saveHostTheme(theme)
+ console.log(`[theme] panes now bg=${theme.background} fg=${theme.foreground}`)
+ // Existing sessions pick it up on the next scan (TmuxBackend.inventory restyles); nudge one now.
+ void agentReconciler.trigger()
+ }
// Per-session web turn-lifecycle state; the device mirror keeps its own state + recap.
const turnStates = new Map<string, TurnState>()
diff --git a/cli/src/lib/e2ee/core.test.ts b/cli/src/lib/e2ee/core.test.ts
index ec4b30003..2e53a2808 100644
--- a/cli/src/lib/e2ee/core.test.ts
+++ b/cli/src/lib/e2ee/core.test.ts
@@ -138,6 +138,9 @@ describe('e2ee core — codes + fingerprint + classification', () => {
// either list the request would not fail — it would time out, which is harder to find.
expect(C.isEncryptedDownType('usage_read')).toBe(true)
expect(C.isEncryptedRpcResultType('usage_read_result')).toBe(true)
+ // The desktop's pane colours ride the same path; a miss here is the same silent timeout.
+ expect(C.isEncryptedDownType('theme_set')).toBe(true)
+ expect(C.isEncryptedRpcResultType('theme_set_result')).toBe(true)
expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('session_get_result')).toBe(true)
expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agents_list_result')).toBe(true)
expect(C.ENCRYPTED_RPC_RESULT_TYPES.has('agent_update_result')).toBe(true)
@@ -203,6 +206,6 @@ describe('e2ee core — interop keystone', () => {
it('core.ts still hashes to the pinned value shared with the other implementations', () => {
const here = dirname(fileURLToPath(import.meta.url))
const actual = createHash('sha256').update(readFileSync(join(here, 'core.ts'))).digest('hex')
- expect(actual).toBe('f4bc05b2ee97b2a6b014bbf38728b4e4c76e4156d48180ff3bf63eb6a2d96d4d')
+ expect(actual).toBe('84cb86ec25470ed2a573f13381f077f2b27a56f4396eccf5a0408d1a2266d476')
})
})
diff --git a/cli/src/lib/e2ee/core.ts b/cli/src/lib/e2ee/core.ts
index 67a2baffa..148df488e 100644
--- a/cli/src/lib/e2ee/core.ts
+++ b/cli/src/lib/e2ee/core.ts
@@ -357,6 +357,10 @@ export const ENCRYPTED_RPC_RESULT_TYPES = new Set<string>([
// This machine's Claude/Codex rate limits and a key naming the account — what the person is
// spending, and on whose subscription. The relay has no business reading either.
'usage_read_result',
+ // Acknowledges the desktop's pane colours (`theme_set`, lib/hostTheme.ts). Listed so the reply is
+ // targeted at the requester rather than broadcast — and so a daemon that predates the type is
+ // told apart by silence, exactly like `usage_read`.
+ 'theme_set_result',
])
/** Client→adapter frames that carry or can trigger adapter-local user data. */
export const ENCRYPTED_DOWN_TYPES = new Set<string>([
@@ -374,6 +378,9 @@ export const ENCRYPTED_DOWN_TYPES = new Set<string>([
// an {__e2e} envelope, requestId would read back undefined, and the requester would wait out its
// timeout on a reply that was never going to be sent.
'usage_read',
+ // The desktop's pane colours for this machine's tmux sessions (lib/hostTheme.ts). Same trap as
+ // above if missing: the envelope would never be opened and the app would wait out its timeout.
+ 'theme_set',
'device_e2ee_pair', 'e2ee_pairings_list', 'e2ee_pairing_unpair',
'e2ee_pairings_unpair_all', 'e2ee_browser_link_create',
// Remote terminal control is always pairwise E2EE. The relay may route by outer type/connId but must
diff --git a/cli/src/lib/hostTheme.spec.ts b/cli/src/lib/hostTheme.spec.ts
new file mode 100644
index 000000000..f19508542
--- /dev/null
+++ b/cli/src/lib/hostTheme.spec.ts
@@ -0,0 +1,40 @@
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+// The module reads env.ADAPTER_DATA_DIR at import, so each test gets a fresh module over a scratch dir.
+let dataDir: string
+async function load() {
+ vi.resetModules()
+ process.env.ADAPTER_DATA_DIR = dataDir
+ return await import('./hostTheme.js')
+}
+beforeEach(() => { dataDir = mkdtempSync(join(tmpdir(), 'host-theme-')) })
+afterEach(() => { rmSync(dataDir, { recursive: true, force: true }); delete process.env.ADAPTER_DATA_DIR })
+
+describe('hostTheme', () => {
+ it('accepts only a full pair of #rrggbb colours, lowercased', async () => {
+ const { parseHostTheme } = await load()
+ expect(parseHostTheme({ background: '#171B29', foreground: '#F5F5F5' })).toEqual({ background: '#171b29', foreground: '#f5f5f5' })
+ expect(parseHostTheme({ background: '#171b29' })).toBeNull()
+ expect(parseHostTheme({ background: 'black', foreground: '#ffffff' })).toBeNull()
+ expect(parseHostTheme({ background: '#fff', foreground: '#ffffff' })).toBeNull()
+ expect(parseHostTheme(null)).toBeNull()
+ })
+
+ it('spells the tmux window-style value', async () => {
+ const { windowStyleOf, DEFAULT_HOST_THEME } = await load()
+ expect(windowStyleOf(DEFAULT_HOST_THEME)).toBe('bg=#181818,fg=#f5f5f5')
+ })
+
+ it('round-trips through the data dir and ignores a corrupt file', async () => {
+ const { loadHostTheme, saveHostTheme } = await load()
+ expect(loadHostTheme()).toBeNull()
+ saveHostTheme({ background: '#300a24', foreground: '#ffffff' })
+ expect(JSON.parse(readFileSync(join(dataDir, 'host-theme.json'), 'utf8'))).toEqual({ background: '#300a24', foreground: '#ffffff' })
+ expect(loadHostTheme()).toEqual({ background: '#300a24', foreground: '#ffffff' })
+ writeFileSync(join(dataDir, 'host-theme.json'), '{not json')
+ expect(loadHostTheme()).toBeNull()
+ })
+})
diff --git a/cli/src/lib/hostTheme.ts b/cli/src/lib/hostTheme.ts
new file mode 100644
index 000000000..a46c4b04c
--- /dev/null
+++ b/cli/src/lib/hostTheme.ts
@@ -0,0 +1,62 @@
+/**
+ * The colours the desktop app paints its terminal panes with, as tmux needs to hear them.
+ *
+ * A TUI inside a pane (Codex) asks its terminal `OSC 10;?` / `OSC 11;?` once at startup and picks
+ * a light or dark palette from the answer. The terminal is tmux, and tmux answers from the FIRST
+ * client attached to the session — the daemon's control-mode client normally, which yields black
+ * and a dark palette; but a person who `tmux attach`es a light-themed terminal first makes tmux
+ * answer white, and Codex then draws pale-green/pink diff rows with dark text inside the app's
+ * dark pane. Measured on tmux 3.7c: the `window-style` option wins over every client's colours in
+ * that reply, and it changes nothing a control-mode client receives (the style is painted only for
+ * tty clients). So the app tells the daemon its colours, and the daemon sets `window-style` on the
+ * sessions it owns.
+ *
+ * Persisted, because Codex asks once: a daemon restarted before the app reconnects must already
+ * know the last colours when it creates the next session.
+ */
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { env } from '../config/env.js'
+
+export interface HostTheme {
+ background: string
+ foreground: string
+}
+
+/** The desktop's stock palette (`graphite` in desktop/lib/shared/theme/color_palette.dart). */
+export const DEFAULT_HOST_THEME: HostTheme = { background: '#181818', foreground: '#f5f5f5' }
+
+const HEX = /^#[0-9a-f]{6}$/i
+
+/** A well-formed theme or null — never a partial one, so `window-style` is always a full pair. */
+export function parseHostTheme(value: unknown): HostTheme | null {
+ if (!value || typeof value !== 'object') return null
+ const { background, foreground } = value as Record<string, unknown>
+ if (typeof background !== 'string' || typeof foreground !== 'string') return null
+ if (!HEX.test(background) || !HEX.test(foreground)) return null
+ return { background: background.toLowerCase(), foreground: foreground.toLowerCase() }
+}
+
+/** The `window-style` value for a theme: what `set-option -w window-style` takes. */
+export function windowStyleOf(theme: HostTheme): string {
+ return `bg=${theme.background},fg=${theme.foreground}`
+}
+
+const fileOf = () => join(env.ADAPTER_DATA_DIR, 'host-theme.json')
+
+export function loadHostTheme(): HostTheme | null {
+ try {
+ return parseHostTheme(JSON.parse(readFileSync(fileOf(), 'utf8')))
+ } catch {
+ return null
+ }
+}
+
+export function saveHostTheme(theme: HostTheme): void {
+ try {
+ mkdirSync(env.ADAPTER_DATA_DIR, { recursive: true, mode: 0o700 })
+ writeFileSync(fileOf(), JSON.stringify(theme, null, 2) + '\n', { mode: 0o600 })
+ } catch (error) {
+ console.warn(`[theme] could not persist host theme: ${error instanceof Error ? error.message : error}`)
+ }
+}
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 623e2feb4..02ab226e6 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -792,6 +792,18 @@ export function setPaneMouseOn(pane: string): Promise<void> {
})
}
+/**
+ * The colours tmux reports to a program in the pane that asks (`OSC 10;?`/`OSC 11;?`) — see
+ * `hostTheme.ts` for why a TUI's palette depends on it. Window-scoped, never `-g`: the daemon
+ * shares the user's default tmux server and must not restyle sessions it did not create.
+ * Best-effort and idempotent, like [setPaneMouseOn].
+ */
+export function setPaneWindowStyle(pane: string, style: string): Promise<boolean> {
+ return new Promise((resolve) => {
+ execFile('tmux', ['set-option', '-w', '-t', pane, 'window-style', style], { timeout: 2_000 }, (error) => resolve(!error))
+ })
+}
+
/** What tmux knows about a pane right now. See `agentCreateDiagnosis.ts` for why this is read. */
export interface TmuxPaneState {
dead: boolean
diff --git a/cli/src/lib/tmuxBackend.spec.ts b/cli/src/lib/tmuxBackend.spec.ts
index 687bf27ba..50684e3dc 100644
--- a/cli/src/lib/tmuxBackend.spec.ts
+++ b/cli/src/lib/tmuxBackend.spec.ts
@@ -41,13 +41,52 @@ esac
// `remain-on-exit` is chained into the SAME invocation, not sent after it: an engine that
// exits immediately would otherwise take its session down before a follow-up call landed,
// and its error text with it.
- 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on',
+ // `window-style` rides the same invocation for the same reason: the engine asks its
+ // terminal for its colours (OSC 10/11) once, at startup, and never again.
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test ; set-option -w remain-on-exit on ; set-option -w window-style bg=#181818,fg=#f5f5f5',
'set-option -t %42 mouse on',
'display-message -p -t %42 #{session_id}',
'kill-session -t $7',
])
})
+ it('styles panes with the theme the app last sent, and re-styles existing ones on a scan', async () => {
+ const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-theme-'))
+ dirs.push(dir)
+ const calls = join(dir, 'calls')
+ const tmux = join(dir, 'tmux')
+ writeFileSync(tmux, `#!/bin/sh
+printf '%s\\n' "$*" >> "$TMUX_BACKEND_CALLS"
+case "$1" in
+ new-session) printf '%%7\\n' ;;
+ list-panes) printf '%%7|100|harness-codex-1|/tmp/work\\n%%9|101|harness-claude-2|/tmp/other\\n' ;;
+esac
+`)
+ chmodSync(tmux, 0o700)
+ process.env.PATH = `${dir}${delimiter}${originalPath ?? ''}`
+ process.env.TMUX_BACKEND_CALLS = calls
+ let theme = { background: '#171b29', foreground: '#f5f5f5' }
+ const backend = new TmuxBackend(() => theme)
+
+ await backend.create({ cwd: '/tmp/work', label: 'harness-codex-1' })
+ await backend.inventory()
+ // Nothing changed: the scan touches only the pane it has not styled yet.
+ await backend.inventory()
+ theme = { background: '#300a24', foreground: '#ffffff' }
+ await backend.inventory()
+ await new Promise((resolve) => setTimeout(resolve, 50))
+
+ const styleCalls = readFileSync(calls, 'utf8').trim().split('\n').filter((line) => line.includes('window-style'))
+ expect(styleCalls).toEqual([
+ 'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-codex-1 ; set-option -w remain-on-exit on ; set-option -w window-style bg=#171b29,fg=#f5f5f5',
+ // The pane this daemon did not create is styled on the first scan; %7 already was.
+ 'set-option -w -t %9 window-style bg=#171b29,fg=#f5f5f5',
+ // The app changed its palette: every live pane, once.
+ 'set-option -w -t %7 window-style bg=#300a24,fg=#ffffff',
+ 'set-option -w -t %9 window-style bg=#300a24,fg=#ffffff',
+ ])
+ })
+
it('carries tmux\'s own refusal into the failure reason', async () => {
const dir = mkdtempSync(join(tmpdir(), 'tmux-backend-refusal-'))
dirs.push(dir)
@@ -202,7 +241,8 @@ printf '%%42\\n'
expect(readFileSync(calls, 'utf8').trim().split('\n')[0]).toBe(
'new-session -d -P -F #{pane_id} -c /tmp/work -s harness-test'
+ ' -e ANTHROPIC_BASE_URL=https://relay.example/relay -e ANTHROPIC_AUTH_TOKEN=gridkey-abc123'
- + ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on',
+ + ' /bin/zsh -lic exec "$@" harness-engine claude ; set-option -w remain-on-exit on'
+ + ' ; set-option -w window-style bg=#181818,fg=#f5f5f5',
)
})
it('respawns a pane in place with a new environment, keeping the pane id', async () => {
diff --git a/cli/src/lib/tmuxBackend.ts b/cli/src/lib/tmuxBackend.ts
index 4fcb742bf..d99c74b75 100644
--- a/cli/src/lib/tmuxBackend.ts
+++ b/cli/src/lib/tmuxBackend.ts
@@ -28,7 +28,9 @@ import {
sendLiteralToTmux,
sendToTmux,
setPaneMouseOn,
+ setPaneWindowStyle,
} from './tmux.js'
+import { DEFAULT_HOST_THEME, windowStyleOf, type HostTheme } from './hostTheme.js'
import { listTmuxPanes } from './tmuxAgentDiscovery.js'
import { terminalRouteKey } from './terminalRuntime.js'
@@ -89,6 +91,15 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
readonly name = 'tmux' as const
readonly instanceId = 'tmux:default'
+ /** What each Harness pane's `window-style` was last set to, so a scan re-applies only changes. */
+ private readonly styledPanes = new Map<string, string>()
+
+ /**
+ * [hostTheme] answers with the desktop's current pane colours (see `hostTheme.ts`); read at every
+ * use rather than captured, so a theme the app sends later reaches sessions created after it.
+ */
+ constructor(private readonly hostTheme: () => HostTheme = () => DEFAULT_HOST_THEME) {}
+
async create(request: TerminalCreateRequest): Promise<TerminalCreateResult<TmuxRuntimeRef>> {
const args = ['new-session', '-d', '-P', '-F', '#{pane_id}']
if (request.cwd) args.push('-c', request.cwd)
@@ -107,6 +118,10 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
// already gone before the follow-up command could reach the server.
// Whoever created the pane owns turning this back off; see `clearPaneRemainOnExit`.
args.push(';', 'set-option', '-w', 'remain-on-exit', 'on')
+ // Same invocation, same reason: an engine asks its terminal for its colours (OSC 10/11) in its
+ // first milliseconds and never again, so the style has to be there before the engine is.
+ const style = windowStyleOf(this.hostTheme())
+ args.push(';', 'set-option', '-w', 'window-style', style)
// `killed`/`signal` come from execFile's own error shape, which ErrnoException alone does not declare.
type ExecError = NodeJS.ErrnoException & { killed?: boolean; signal?: NodeJS.Signals | null }
const result = await new Promise<{ error: ExecError | null; stdout: string; stderr: string }>((resolve) => {
@@ -133,6 +148,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
return terminalActionPossiblyExecuted('tmux created a session without returning its root pane')
}
await setPaneMouseOn(paneId)
+ this.styledPanes.set(paneId, style)
return { state: 'succeeded', dispatch: 'executed', runtime: { backend: 'tmux', paneId } }
}
@@ -227,6 +243,7 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
async inventory(): Promise<TerminalInventoryResult> {
const result = await listTmuxPanes()
if (!result.ok) return { state: 'unavailable', reason: result.error }
+ this.restyle(result.panes.map((pane) => pane.tmuxPane))
return {
state: 'available',
roots: result.panes.map((pane) => ({
@@ -237,6 +254,28 @@ export class TmuxBackend implements TerminalBackend<TmuxRuntimeRef> {
}
}
+ /**
+ * Retroactive, on every scan: a pane from before this build, one that outlived a daemon restart,
+ * or every pane after the app changed its palette. Fire-and-forget — a scan that misses one
+ * because tmux was briefly slow catches it on the next pass. Panes that are gone are forgotten
+ * so a reused pane id is styled afresh.
+ */
+ private restyle(panes: readonly string[]): void {
+ const style = windowStyleOf(this.hostTheme())
+ const live = new Set(panes)
+ for (const pane of panes) {
+ if (this.styledPanes.get(pane) === style) continue
+ // Recorded only once tmux has taken it: a pane recorded on the attempt would never be
+ // retried after a timeout, until the theme happened to change again.
+ void setPaneWindowStyle(pane, style).then((applied) => {
+ if (applied && live.has(pane)) this.styledPanes.set(pane, style)
+ })
+ }
+ for (const pane of [...this.styledPanes.keys()]) {
+ if (!live.has(pane)) this.styledPanes.delete(pane)
+ }
+ }
+
async validate(runtime: TmuxRuntimeRef, expected: TerminalProcessExpectation): Promise<RuntimeValidation> {
try {
const live = await resolvePaneEngineProcess(runtime.paneId, expected.engine)
diff --git a/cli/src/scripts/install.spec.ts b/cli/src/scripts/install.spec.ts
index bb29bf903..ffb7c428b 100644
--- a/cli/src/scripts/install.spec.ts
+++ b/cli/src/scripts/install.spec.ts
@@ -273,7 +273,7 @@ describe("scripts/install.sh command contract", () => {
} finally {
rmSync(scratch, { recursive: true, force: true });
}
- });
+ }, 20_000);
it("refuses a managed tmux whose checksum does not match, and links nothing", () => {
const source = readFileSync(installer, "utf8");
@@ -301,7 +301,7 @@ describe("scripts/install.sh command contract", () => {
} finally {
rmSync(scratch, { recursive: true, force: true });
}
- });
+ }, 20_000);
it("falls back to the managed build when Homebrew cannot install tmux", () => {
const source = readFileSync(installer, "utf8");
@@ -329,7 +329,7 @@ describe("scripts/install.sh command contract", () => {
} finally {
rmSync(scratch, { recursive: true, force: true });
}
- });
+ }, 20_000);
it("host mode puts ~/.local/bin on PATH for new shells", () => {
const source = readFileSync(installer, "utf8");
@@ -357,7 +357,7 @@ describe("scripts/install.sh command contract", () => {
} finally {
rmSync(scratch, { recursive: true, force: true });
}
- });
+ }, 20_000);
it("host mode stops after the host requirements", () => {
const source = readFileSync(installer, "utf8");
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.md
index 82620c05c..814212625 100644
--- a/desktop/CLAUDE.md
+++ b/desktop/CLAUDE.md
@@ -168,6 +168,17 @@ from `node_status` pushes — distinct from our own socket status, pending offli
sessions get `handleFrame` first (a session returns true for any terminal frame, even one not
addressed to it), then the app-level switch handles `node_status`, `agent_*`, `turn_*`, and the
hardware-dial events `dial_scroll`/`dial_focus`.
+- **A pane's colours are told to the daemon** (`theme_set`, `AppNotifier._announceTerminalTheme`, on
+ every connect and whenever `grid.AppTheme.palette` or `terminalThemeStore` changes; CLI side
+ `lib/hostTheme.ts`). tmux answers a TUI's `OSC 10;?`/`OSC 11;?` — which is how Codex picks a light
+ or dark diff palette, once, at startup — from whichever client attached to the session FIRST, so a
+ person who `tmux attach`ed a light terminal before the daemon's control client made Codex draw
+ pale-green diff rows with dark text inside a dark pane. tmux's `window-style` wins over every
+ client in that reply and changes nothing a control-mode client receives, so the daemon sets it,
+ window-scoped, on the sessions it created (`TmuxBackend.create` chains it into `new-session`;
+ `inventory()` restyles existing panes on each scan). ⚠️ `theme_set`/`theme_set_result` are in the
+ E2EE type sets in `cli/src/lib/e2ee/core.ts`, which re-pinned the interop keystone; a daemon
+ that predates the type goes silent, which the app treats as "not supported" — never an error.
- `third_party/xterm` is a **vendored, patched** xterm 4.0.0 (atomic `replaceRange` fix for scroll
regions — see its `README.autonomous.md`). Do not replace it with the pub package; the regression
lives in `test/terminal_session_test.dart`.
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 9bb275eba..3b18dada1 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -3,6 +3,9 @@ import 'dart:io' show exit, pid;
import 'dart:math' show Random;
import 'package:dio/dio.dart';
+
+import 'dart:ui' show Color;
+
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:url_launcher/url_launcher.dart';
@@ -26,6 +29,10 @@ import '../core/retry.dart';
import '../settings/config_store.dart';
import '../stats/harness_stats.dart';
import '../terminal/terminal_session.dart';
+import '../terminal/terminal_theme.dart';
+import '../terminal/terminal_theme_store.dart';
+import '../logging/app_log.dart';
+import '../shared/theme/app_theme.dart' as grid;
import '../terminal/remote_media_download.dart';
import '../widgets/engine_identity.dart' show allEngines;
import 'dial_status.dart';
@@ -1077,6 +1084,11 @@ class AppNotifier extends ChangeNotifier {
config = configStore?.config ?? config {
_autonomousEnv = this.config.autonomousEnv;
api = ApiClient(config: this.config, session: session);
+ // `grid.AppTheme.palette`, not the prefs store: main.dart copies the saved
+ // choice into the palette notifier while rebuilding, so the store fires
+ // before the colours the panes actually use have moved.
+ grid.AppTheme.palette.addListener(_announceTerminalThemeEverywhere);
+ terminalThemeStore.addListener(_announceTerminalThemeEverywhere);
}
String? get lastError => _lastError;
@@ -1345,6 +1357,101 @@ class AppNotifier extends ChangeNotifier {
/// Publish the selected pane to the existing local CLI connection. The CLI
/// shares this focus with paired devices and the dial; terminal attachments
/// and operating-system window activation do not define the selected agent.
+ /// The colours the panes are actually painted with — the terminal theme in
+ /// force, not the app palette by assumption (Tango is its own scheme).
+ static Map<String, String> terminalThemeColours() {
+ final theme = terminalThemeFor(
+ grid.AppTheme.palette.value,
+ terminalThemeStore.value,
+ );
+ String hex(Color color) =>
+ '#${(color.toARGB32() & 0xFFFFFF).toRadixString(16).padLeft(6, '0')}';
+ return {
+ 'background': hex(theme.background),
+ 'foreground': hex(theme.foreground),
+ };
+ }
+
+ /// Tells one machine's daemon the pane colours (`theme_set`, answered by
+ /// the CLI's lib/hostTheme.ts). Fire-and-forget: a daemon that predates the
+ /// type cannot open the envelope and goes silent, and that is nothing to
+ /// put on the error strip — the pane still opens, only a TUI's palette may
+ /// guess wrong there.
+ void _announceTerminalTheme(String machineId) {
+ if (_disposed) return;
+ final connection = _pool != null || connectionForTest != null
+ ? _conn(machineId)
+ : null;
+ if (connection == null) return;
+ unawaited(
+ connection
+ .request(
+ 'theme_set',
+ payload: terminalThemeColours(),
+ timeout: const Duration(seconds: 5),
+ )
+ .catchError((Object error) {
+ appLog.debug('ws', 'theme_set not applied on $machineId: $error');
+ return <String, dynamic>{};
+ }),
+ );
+ }
+
+ /// The palette or terminal theme changed: every connected machine hears it,
+ /// so a session created after this on any of them starts with the new
+ /// colours and existing ones are restyled on the daemon's next scan.
+ void _announceTerminalThemeEverywhere() {
+ for (final entry in machineStates.entries) {
+ if (entry.value.connectionStatus != ConnectionStatus.connected) continue;
+ _announceTerminalTheme(entry.key);
+ }
+ }
+
+ /// What a machine hears the moment its socket is up — first connect, or a
+ /// reconnect after its daemon restarted, which has forgotten all of it.
+ void _onMachineConnected(String machineId, MachineState machine) {
+ machine.needsLink = false;
+ _stopLinkRetry(machineId);
+ // A daemon that just came up — first connect, or a reconnect after it
+ // restarted — has never been told what is on the grid. Without this
+ // the dial goes back to beeping about tiles in plain sight until the
+ // next time a pane happens to change.
+ _announceOpenPanesToDial();
+ // ...nor which tile this window is looking at. The daemon repeats that to the dial after every
+ // list push, which is what keeps the two screens from drifting apart — but it can only repeat
+ // something it has been told, and until now the first telling waited for the focus to CHANGE.
+ // A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto
+ // the wrong tile stayed there.
+ _announceAppFocus();
+ // ...nor what colour its panes are. tmux answers a TUI's "what is my background?"
+ // (OSC 10/11 — Codex picks its light or dark diff palette from it) with whichever
+ // terminal attached first, unless told; this tells it, for the sessions it owns.
+ _announceTerminalTheme(machineId);
+ // The local CLI never hands back `connected` until it has terminated E2EE (or confirmed
+ // none is needed, for its own machine) — every machine's data is ready to load right away,
+ // with no separate app-side readiness gate to wait on anymore.
+ if (machine.isLocalMachine) {
+ machine.transportMode = MachineTransportMode.localPlaintext;
+ } else {
+ machine.transportMode = MachineTransportMode.cloudE2ee;
+ }
+ // Route through _applyNodeStatus (not just `machine.nodeOnline = true`) for every machine,
+ // not only the local one — a successful select IS the machine being reachable again, and
+ // this is what lets a pending agent (captured below on disconnect) reattach automatically
+ // instead of leaving the user stuck on the empty "select a machine" placeholder.
+ unawaited(_applyNodeStatus(machine, true));
+ unawaited(_loadMachineData(machine, force: true));
+ _startAgentSyncTimer(machineId);
+ }
+
+ @visibleForTesting
+ void onMachineConnectedForTest(String machineId) {
+ final machine = machineStates[machineId];
+ if (machine == null) return;
+ machine.connectionStatus = ConnectionStatus.connected;
+ _onMachineConnected(machineId, machine);
+ }
+
void _announceAppFocus() {
final pane = focusedPane;
final machineId = pane?.agentId == null ? null : pane?.machineId;
@@ -2497,34 +2604,7 @@ class AppNotifier extends ChangeNotifier {
if (machine == null) return;
machine.connectionStatus = nextStatus;
if (nextStatus == ConnectionStatus.connected) {
- machine.needsLink = false;
- _stopLinkRetry(machineId);
- // A daemon that just came up — first connect, or a reconnect after it
- // restarted — has never been told what is on the grid. Without this
- // the dial goes back to beeping about tiles in plain sight until the
- // next time a pane happens to change.
- _announceOpenPanesToDial();
- // ...nor which tile this window is looking at. The daemon repeats that to the dial after every
- // list push, which is what keeps the two screens from drifting apart — but it can only repeat
- // something it has been told, and until now the first telling waited for the focus to CHANGE.
- // A daemon restarted mid-session therefore had nothing to say, and a dial that re-anchored onto
- // the wrong tile stayed there.
- _announceAppFocus();
- // The local CLI never hands back `connected` until it has terminated E2EE (or confirmed
- // none is needed, for its own machine) — every machine's data is ready to load right away,
- // with no separate app-side readiness gate to wait on anymore.
- if (machine.isLocalMachine) {
- machine.transportMode = MachineTransportMode.localPlaintext;
- } else {
- machine.transportMode = MachineTransportMode.cloudE2ee;
- }
- // Route through _applyNodeStatus (not just `machine.nodeOnline = true`) for every machine,
- // not only the local one — a successful select IS the machine being reachable again, and
- // this is what lets a pending agent (captured below on disconnect) reattach automatically
- // instead of leaving the user stuck on the empty "select a machine" placeholder.
- unawaited(_applyNodeStatus(machine, true));
- unawaited(_loadMachineData(machine, force: true));
- _startAgentSyncTimer(machineId);
+ _onMachineConnected(machineId, machine);
} else if (nextStatus == ConnectionStatus.reconnecting ||
nextStatus == ConnectionStatus.disconnected) {
_stopAgentSyncTimer(machineId);
@@ -5658,6 +5738,8 @@ class AppNotifier extends ChangeNotifier {
@override
void dispose() {
+ grid.AppTheme.palette.removeListener(_announceTerminalThemeEverywhere);
+ terminalThemeStore.removeListener(_announceTerminalThemeEverywhere);
_localGitProjects.dispose();
sessionPreviews.dispose();
_disposed = true;
diff --git a/desktop/test/machine_loading_test.dart b/desktop/test/machine_loading_test.dart
index 15be02e9e..545107adf 100644
--- a/desktop/test/machine_loading_test.dart
+++ b/desktop/test/machine_loading_test.dart
@@ -4,8 +4,11 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/models.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/terminal_pane.dart';
+import 'package:harness/terminal/terminal_theme_store.dart';
import 'package:harness/ws/ws_conn.dart';
const _machine = Machine(
@@ -50,6 +53,8 @@ class _Connection extends WsConn {
final calls = <String>[];
final agents = <Completer<Map<String, dynamic>>>[];
final capabilities = <Completer<Map<String, dynamic>>>[];
+ final themes = <Map<String, dynamic>>[];
+ bool refuseTheme = false;
final timeouts = <String, Duration>{};
final sent = <String>[];
Completer<void>? readiness;
@@ -73,6 +78,13 @@ class _Connection extends WsConn {
agents.add(response);
case 'terminal_capabilities':
capabilities.add(response);
+ case 'theme_set':
+ themes.add(payload);
+ if (refuseTheme) {
+ response.completeError(StateError('daemon predates theme_set'));
+ } else {
+ response.complete({'applied': true});
+ }
default:
throw StateError('Unexpected request: $type');
}
@@ -258,4 +270,51 @@ void main() {
expect(connection.calls, isEmpty);
expect(app.panes, isEmpty);
});
+
+ group('pane colours reach the daemon', () {
+ tearDown(() {
+ grid.AppTheme.palette.value = HarnessPalette.graphite;
+ terminalThemeStore.value = TerminalThemeChoice.matchApp;
+ });
+
+ test('are announced when a machine connects, as the colours the panes are painted with', () async {
+ grid.AppTheme.palette.value = HarnessPalette.midnight;
+ app.onMachineConnectedForTest('m');
+ await _tick();
+ connection.agents.single.complete(_agents);
+ await _tick();
+ connection.capabilities.single.complete(_capabilities);
+ await _tick();
+
+ expect(connection.themes, [
+ {'background': '#171b29', 'foreground': '#f5f5f5'},
+ ]);
+ expect(connection.timeouts['theme_set'], const Duration(seconds: 5));
+ });
+
+ test('are re-announced to connected machines when the palette or terminal theme changes', () async {
+ machine.connectionStatus = ConnectionStatus.connected;
+ grid.AppTheme.palette.value = HarnessPalette.forest;
+ await _tick();
+ // Tango is its own scheme: what goes out is what the pane draws, not the app palette.
+ terminalThemeStore.value = TerminalThemeChoice.tango;
+ await _tick();
+
+ expect(connection.themes, [
+ {'background': '#18231e', 'foreground': '#f5f5f5'},
+ {'background': '#300a24', 'foreground': '#ffffff'},
+ ]);
+ });
+
+ test('a daemon that cannot take the colours is not an error', () async {
+ connection.refuseTheme = true;
+ machine.connectionStatus = ConnectionStatus.connected;
+ grid.AppTheme.palette.value = HarnessPalette.slate;
+ await _tick();
+ await _tick();
+
+ expect(connection.themes, hasLength(1));
+ expect(app.lastError, isNull);
+ });
+ });
}
diff --git a/desktop/test/terminal_theme_test.dart b/desktop/test/terminal_theme_test.dart
index b986e58c8..df8fb74a5 100644
--- a/desktop/test/terminal_theme_test.dart
+++ b/desktop/test/terminal_theme_test.dart
@@ -1,10 +1,27 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/shared/theme/app_theme.dart' as grid;
+import 'package:harness/shared/theme/color_palette.dart';
+import 'package:harness/state/app_state.dart';
import 'package:harness/terminal/terminal_theme.dart';
+import 'package:harness/terminal/terminal_theme_store.dart';
void main() {
test('the terminal default follows the app\'s dark background', () {
expect(darkTerminalTheme.background, const Color(0xff181818));
expect(darkTerminalTheme.foreground, const Color(0xffffffff));
});
+
+ test('the colours sent to a daemon are the pane\'s own, as #rrggbb', () {
+ addTearDown(() {
+ grid.AppTheme.palette.value = HarnessPalette.graphite;
+ terminalThemeStore.value = TerminalThemeChoice.matchApp;
+ });
+ expect(AppNotifier.terminalThemeColours(), {
+ 'background': '#181818',
+ 'foreground': '#f5f5f5',
+ });
+ terminalThemeStore.value = TerminalThemeChoice.tango;
+ expect(AppNotifier.terminalThemeColours()['background'], '#300a24');
+ });
}