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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Window auto rename: the daemon names a window for its repo and work; hn 0.1.15 asks for it (#992)
lingrdc59f1a31f011
diff --git a/cli/e2e/services.e2e.ts b/cli/e2e/services.e2e.tsindex b6acf463b..81b4c7842 100644--- a/cli/e2e/services.e2e.ts+++ b/cli/e2e/services.e2e.ts@@ -54,7 +54,7 @@ const QUICK_TO_PARK = { HARNESSD_SERVICE_PARK_CRASHES: '3', HARNESSD_SERVICE_INI/** The processes the services run in by default, and what makes every one of them fail as it starts. The* experiments' (the teams', the orchestrator's) start only once they are on: e2e/experiments.e2e.ts. */const SERVICE_PROCESSES = ['search', 'viewers', 'edge', 'models'] as const-const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,handoff,recaps,models'+const EVERY_PROCESS_FAILING = 'search,viewers,store,workspaces,usage,monitor,projects,handoff,recaps,windowNames,models'describe('a failing service never takes the core down', () => {let daemon: IsolatedDaemon | undefined@@ -78,6 +78,7 @@ describe('a failing service never takes the core down', () => {expect(await client.request('session_search', { query: 'first' })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'search' })expect(await client.request('dsh_list', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'store', retryable: true })expect(await client.request('fs_list_dir', { path: d.projectsDir })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: true })+ expect(await client.request('window_name', { agentIds: [agentId] })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'windowNames', retryable: true })expect(await client.request('machine_resources', {})).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'monitor', retryable: true })// Models is on demand and never came up: its request waits no longer than a start (core/serviceLinks.ts// `ON_DEMAND_START_MS`), and every one after it is answered at once.@@ -140,10 +141,10 @@ describe('a failing service never takes the core down', () => {})it('with every service in the core failing to start, the core starts, runs an agent through turns and a restart, and says each service is off', async () => {- daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store,usage,monitor,projects,recaps', ...IN_THE_CORE } })+ daemon = await IsolatedDaemon.create({ env: { HARNESSD_TEST_FAULTS: 'search,viewers,models,workspaces,store,usage,monitor,projects,recaps,windowNames', ...IN_THE_CORE } })onTestFailed(() => { console.log(`---- daemon log\n${daemon?.log().split('\n').slice(-80).join('\n')}`) })await daemon.start()- for (const service of ['search', 'viewers', 'models', 'workspaces', 'store', 'usage', 'monitor', 'projects', 'recaps']) {+ for (const service of ['search', 'viewers', 'models', 'workspaces', 'store', 'usage', 'monitor', 'projects', 'recaps', 'windowNames']) {expect(daemon.log()).toContain(`[services] ${service} did not start · injected fault: ${service} · the core runs without it`)}const client = await LocalClient.connect(daemon)@@ -168,6 +169,8 @@ describe('a failing service never takes the core down', () => {for (const type of ['git_pull_request', 'git_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file']) {expect(await client.request(type, { agentId, path: daemon.projectsDir }), type).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'projects', retryable: false })}+ // A window's name off: the apps keep the names they have.+ expect(await client.request('window_name', { agentIds: [agentId] })).toMatchObject({ error: 'SERVICE_UNAVAILABLE', service: 'windowNames', retryable: false })// With the monitor off, the Monitor's list is still the list: its rows, without readings.const monitored = (await client.request('agents_list', { monitor: true })).agents.find((agent: Record<string, any>) => agent.id === agentId)expect(monitored.monitor).toMatchObject({ rssBytes: null, cpu: null, processes: [] })diff --git a/cli/src/core/api.ts b/cli/src/core/api.tsindex 2643c0137..e55f819b5 100644--- a/cli/src/core/api.ts+++ b/cli/src/core/api.ts@@ -454,6 +454,8 @@ export const MONITOR_REQUESTS = ['machine_resources'] as constexport const COMMAND_BAR_REQUESTS = ['command_bar', 'command_bar_http'] as const/** The project and folder readers (services/projects.ts). */export const PROJECTS_REQUESTS = ['git_pull_request', 'git_project_info', 'scm_project_info', 'project_preview', 'fs_list_dir', 'agent_read_file'] as const+/** A window's name for its repo and its work, by a small model in the background (services/windowNames.ts). */+export const WINDOW_NAMES_REQUESTS = ['window_name'] as const/** Change agent's handoff file, prepared in the edge host (services/handoff.ts). */export const HANDOFF_REQUESTS = ['agent_handoff_prepare'] as const/**diff --git a/cli/src/core/main.ts b/cli/src/core/main.tsindex c3d8ab969..0b9839333 100644--- a/cli/src/core/main.ts+++ b/cli/src/core/main.ts@@ -118,7 +118,7 @@ import { createAgentUpdate } from './agents/update.js'import { createEngineHooks, installEngineHooks } from './engines/hooks.js'import { createCursorTaskHooks } from './engines/cursorTasks.js'import { databaseHistory } from './transcripts/databaseHistory.js'-import { COMMAND_BAR_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'+import { COMMAND_BAR_REQUESTS, createCoreApi, DEVICES_FALLBACKS, DEVICES_REQUESTS, emptyPorts, HANDOFF_REQUESTS, EXPERIMENTS, LONG_ANSWERS, MODELS_FALLBACKS, MODELS_OFF, MODELS_REQUESTS, MONITOR_FALLBACKS, MONITOR_OFF, MONITOR_REQUESTS, ORCHESTRATOR_FALLBACKS, ORCHESTRATOR_REQUESTS, SHARE_REQUESTS, SHARING_FALLBACKS, PROJECTS_REQUESTS, SEARCH_FALLBACKS, SEARCH_REQUESTS, STORE_REQUESTS, TEAMS_FALLBACKS, TEAMS_REQUESTS, USAGE_REQUESTS, VIEWERS_FALLBACKS, WIFI_FALLBACKS, WINDOW_NAMES_REQUESTS, WORKSPACES_FALLBACKS, type GatewayAccount, type GatewayOps, type GatewayStatus, type RouteAnswer, type TeamsPort, type WindowFocus } from './api.js'import { createServiceHost, testFaults } from './serviceHost.js'import { startStalls } from './stall.js'import { createServiceLinks, type ServiceLinks } from './serviceLinks.js'@@ -1091,7 +1091,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {// The requests each service that can run in its own process answers, as core/api.ts declares them.const requestsOf: Record<string, readonly string[]> = {search: SEARCH_REQUESTS, store: STORE_REQUESTS, usage: USAGE_REQUESTS, monitor: MONITOR_REQUESTS, projects: PROJECTS_REQUESTS, models: MODELS_REQUESTS, handoff: HANDOFF_REQUESTS,- devices: DEVICES_REQUESTS,+ devices: DEVICES_REQUESTS, windowNames: WINDOW_NAMES_REQUESTS,...Object.fromEntries(Object.entries(EXPERIMENTS).map(([name, experiment]) => [name, experiment.requests])),}// The experiments (core/api.ts `EXPERIMENTS`): each may act on the core through the hooks an experiment has.@@ -1229,8 +1229,10 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (outOfProcess.has('monitor')) ports.monitor = createMonitorLink((type, payload) => serviceLinks.call('monitor', type, payload))else serviceHost.start('monitor', inline!.startMonitor, coreApi, MONITOR_FALLBACKS, MONITOR_REQUESTS)// An agent's branch and pull request, a project's repository and preview, a folder's subfolders and a- // media file from an agent's project (services/projects.ts): in this process, or in the edge host.+ // media file from an agent's project (services/projects.ts), and a window's name (services/windowNames.ts):+ // in this process, or in the edge host.if (!outOfProcess.has('projects')) serviceHost.serve('projects', inline!.startProjects, coreApi, PROJECTS_REQUESTS)+ if (!outOfProcess.has('windowNames')) serviceHost.serve('windowNames', inline!.startWindowNames, coreApi, WINDOW_NAMES_REQUESTS)if (!outOfProcess.has('commandBar')) serviceHost.serve('commandBar', inline!.startCommandBar, coreApi, COMMAND_BAR_REQUESTS)if (!outOfProcess.has('handoff')) serviceHost.serve('handoff', inline!.startHandoff, coreApi, HANDOFF_REQUESTS)// The recaps: in this process, or in the edge host (services/recapsProcess.ts), told each turn's lifecycle.diff --git a/cli/src/harnessd/services.spec.ts b/cli/src/harnessd/services.spec.tsindex 01a39c344..1ce6c0bef 100644--- a/cli/src/harnessd/services.spec.ts+++ b/cli/src/harnessd/services.spec.ts@@ -451,7 +451,7 @@ describe('ServiceSupervisor', () => {const hosted = Object.values(SERVICE_HOSTS).flatMap((host) => host.services)expect(KNOWN_SERVICES).toEqual(hosted)expect(new Set(hosted).size).toBe(hosted.length)- expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps'])+ expect(SERVICE_HOSTS.edge.services).toEqual(['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames'])})})@@ -467,7 +467,7 @@ describe('which services the core leaves to its master', () => {expect(serviceProcessesEnv(serviceSpecs({ HARNESSD_SERVICES: 'store' }, SERVICE_HOSTS))).toMatchObject({ [SERVICE_PROCESSES_ENV]: 'store' })// By service, not by process: a core from before the edge host routes the services it knows of it.const hosted = serviceSpecs({ HARNESSD_SERVICES: 'edge' }, SERVICE_HOSTS)- expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps' })+ expect(serviceProcessesEnv(hosted)).toEqual({ [SERVICE_PROCESSES_ENV]: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames', HARNESSD_SERVICES: 'workspaces,usage,monitor,projects,handoff,recaps,windowNames' })expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(hosted) }, known)]).toEqual(['workspaces'])expect(serviceProcessesEnv([])).toEqual({ [SERVICE_PROCESSES_ENV]: '', HARNESSD_SERVICES: 'none' })expect([...servicesTheMasterRuns({ ...supervised, ...serviceProcessesEnv(specs) }, known)]).toEqual(['search', 'workspaces'])diff --git a/cli/src/harnessd/services.ts b/cli/src/harnessd/services.tsindex 58cb672ca..2d7bf819a 100644--- a/cli/src/harnessd/services.ts+++ b/cli/src/harnessd/services.ts@@ -374,8 +374,9 @@ export const SERVICE_HOSTS: Readonly<Record<string, ServiceHostSpec>> = {// samples in ps's and ioreg's; what it holds is the agents the core sent it and one parsed sample.// The monitor parses up to 8 MB of ioreg output per Monitor poll on a Mac with a GPU, hence more// than workspaces alone had. The recaps hold each session's last three recaps, answers (8 KiB each at- // most) and asks, as the core did while they ran in it, and a few timers per open turn.- edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps'], heapLimitMiB: 384, rssLimitMiB: 768 },+ // most) and asks, as the core did while they ran in it, and a few timers per open turn. The window+ // names hold at most 400 short names; their model runs in its own process (lib/oneshot.ts).+ edge: { services: ['workspaces', 'usage', 'monitor', 'projects', 'handoff', 'recaps', 'windowNames'], heapLimitMiB: 384, rssLimitMiB: 768 },// The orchestrator (services/orchestratorProcess.ts), an experiment: started only once it is on, for a// saved project or a request (core/api.ts `EXPERIMENTS`). Its projects' files and the frames of their// Directors; the agents it runs are the core's.diff --git a/cli/src/serviceProcess.ts b/cli/src/serviceProcess.tsindex 66955e61e..56005a8a7 100644--- a/cli/src/serviceProcess.ts+++ b/cli/src/serviceProcess.ts@@ -34,6 +34,7 @@ export const SERVICE_RUNNERS: ReadonlyMap<string, () => Promise<Runner>> = new M['usage', async () => (await import('./services/usageProcess.js')).runUsageService],['monitor', async () => (await import('./services/monitorProcess.js')).runMonitorService],['projects', async () => (await import('./services/projectsProcess.js')).runProjectsService],+ ['windowNames', async () => (await import('./services/windowNamesProcess.js')).runWindowNamesService],['handoff', async () => (await import('./services/handoffProcess.js')).runHandoffService],['recaps', async () => (await import('./services/recapsProcess.js')).runRecapsService],['store', async () => (await import('./services/storeProcess.js')).runStoreService],diff --git a/cli/src/services/inline.spec.ts b/cli/src/services/inline.spec.tsindex 19bd5c1e5..fc670f7d1 100644--- a/cli/src/services/inline.spec.ts+++ b/cli/src/services/inline.spec.ts@@ -16,10 +16,11 @@ import { startStore } from './store.js'import { startUsage } from './usage.js'import { startViewers } from './viewers.js'import { startWifi } from './wifi.js'+import { startWindowNames } from './windowNames.js'import { startWorkspaces } from './workspaces.js'describe('the services the core runs in its own process only when they do not run in theirs', () => {it('are their own starts, unchanged: the same services either way', () => {- expect({ ...inline }).toEqual({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWorkspaces })+ expect({ ...inline }).toEqual({ startCommandBar, startDevices, startHandoff, startGateway, startModels, startMonitor, startOrchestrator, startProjects, startRecaps, startSearch, startSharing, startStore, startTeamsInCore, startUsage, startViewers, startWifi, startWindowNames, startWorkspaces })})})diff --git a/cli/src/services/inline.ts b/cli/src/services/inline.tsindex 1e0a5d668..4c29a5862 100644--- a/cli/src/services/inline.ts+++ b/cli/src/services/inline.ts@@ -28,4 +28,5 @@ export { startStore } from './store.js'export { startUsage } from './usage.js'export { startViewers } from './viewers.js'export { startWifi } from './wifi.js'+export { startWindowNames } from './windowNames.js'export { startWorkspaces } from './workspaces.js'diff --git a/cli/src/services/windowNames.spec.ts b/cli/src/services/windowNames.spec.tsnew file mode 100644index 000000000..8589d58d5--- /dev/null+++ b/cli/src/services/windowNames.spec.ts@@ -0,0 +1,224 @@+import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { afterEach, describe, expect, it, vi } from 'vitest'+import { runRouterOneShot } from '../lib/oneshot.js'+import type { RegisteredSession } from '../lib/registry.js'+import { fakeCore } from '../testing/fakeCore.js'+import { BUDGET_MS, cleanName, defaultNamers, KEEP, PROMPT, RETRY_MS, startWindowNames, WINDOW_NAMES_REQUESTS, windowAsk, type Namer } from './windowNames.js'++vi.mock('../lib/oneshot.js', () => ({ runRouterOneShot: vi.fn(async () => ({ text: 'Harness TUI\n', sessionId: null })) }))+// The real `opencode models` path, run with a command that lists nothing.+vi.mock('../lib/engineBin.js', () => ({ opencodeBin: () => '/bin/echo' }))++const ASKER = { local: true, owner: true }+type Repo = { kind: string; name: string; root: string | null; remote: string | null; branch: string | null }+const agent = (agentId: string, engine: string, cwd: string) => ({ agentId, sessionId: `s-${agentId}`, engine, cwd }) as RegisteredSession++/** The user's window (2026-10-07): two harnesses in autonomous-harness, one in aptis-notes (no git), a shell. */+const AGENTS: Record<string, [string, string, string]> = {+ tui: ['TUI layout spacing consistency', 'claude', '/work/harness'],+ lm: ['Lm studio respawn on quit', 'claude', '/work/harness-lm'],+ pi: ['pi:c', 'pi', '/work/aptis'],+ sh: ['Terminal harness 10-6 11:25', 'terminal', '/work/harness'],+ grid: ['Grid relay respawn prod', 'codex', '/work/grid'],+ mob: ['Mobile login screen', 'pi', '/work/mobile-test'],+ // Pi's own title before it has one: the folder alone.+ pidefault: ['π - mobile-test', 'pi', '/work/mobile-test'],+ loose: ['Fix the build', 'claude', '/work/loose'],+ // Harnesses with no title yet, as the user's xiaozhi-esp32 window had (2026-10-07).+ untitled: ['OpenCode harness 10-7 16:45', 'opencode', '/work/harness'],+ numbered: ['harness-3', 'claude', '/work/harness'],+ blank: ['', 'claude', '/work/harness'],+}+const HARNESS = 'github.com/autonomous-ai/autonomous-harness'+// As describeScmProject reads them on the user's machine (2026-10-07).+const REPOS: Record<string, Repo> = {+ '/work/harness': { kind: 'git', name: 'autonomous-harness', root: '/work/harness', remote: HARNESS, branch: 'main' },+ // A linked worktree of the same repo: a root of its own, the same remote, its own branch.+ '/work/harness-lm': { kind: 'git', name: 'autonomous-harness', root: '/worktrees/gentle-walrus', remote: HARNESS, branch: 'lm-studio-stays-closed' },+ '/work/aptis': { kind: 'none', name: 'aptis-notes', root: null, remote: null, branch: null },+ '/work/grid': { kind: 'git', name: 'autonomous-grid-cli', root: '/work/grid', remote: 'github.com/autonomous-ai/autonomous-grid-cli', branch: 'main' },+ '/work/mobile-test': { kind: 'git', name: 'mobile-test', root: '/work/mobile-test', remote: null, branch: 'main' },+ // A repo with no remote and no root git said: known by its name.+ '/work/loose': { kind: 'git', name: 'loose', root: null, remote: null, branch: 'main' },+}+const describeRepo = async (cwd: string | null | undefined): Promise<Repo | null> => {+ if (cwd === '/work/broken') throw new Error('git failed')+ return REPOS[cwd ?? ''] ?? null+}++function setup(over: { dataDir?: string; ask?: (namer: Namer, prompt: string) => Promise<string>; namers?: (engines: string[]) => Promise<Namer[]>; now?: () => number; defaults?: boolean } = {}) {+ const sessions = Object.entries(AGENTS).map(([id, [, engine, cwd]]) => agent(id, engine, cwd))+ sessions.push(agent('broken', 'claude', '/work/broken'), agent('nobranch', 'claude', '/work/nobranch'))+ REPOS['/work/nobranch'] = { kind: 'git', name: 'detached', root: '/work/nobranch', remote: null, branch: null }+ const core = fakeCore({+ dataDir: over.dataDir ?? mkdtempSync(join(tmpdir(), 'window-names-')),+ agents: { byAgent: vi.fn((id: string) => sessions.find((s) => s.agentId === id)), displayName: vi.fn((s: RegisteredSession) => AGENTS[s.agentId]?.[0] ?? s.agentId) },+ })+ const ask = vi.fn(over.ask ?? (async () => 'Harness TUI LMStudio'))+ const namers = vi.fn(over.namers ?? (async () => [{ engine: 'opencode', model: 'opencode/exo-free' } as Namer]))+ const requests = over.defaults ? startWindowNames(core) : startWindowNames(core, { describe: describeRepo, ask, namers, now: over.now })+ const name = (agentIds: unknown) => requests.window_name!({ agentIds }, ASKER) as Promise<Record<string, unknown>>+ return { core, requests, name, ask, namers }+}++describe('window names', () => {+ afterEach(() => { vi.clearAllMocks() })++ it('answer exactly the requests they declare', () => {+ expect(Object.keys(setup().requests)).toEqual([...WINDOW_NAMES_REQUESTS])+ })++ it('show the model the headings of the harnesses in the repo most of them are in — not a shell, not a folder without git', async () => {+ const { core } = setup()+ const ask = await windowAsk(core, ['tui', 'lm', 'pi', 'sh'], describeRepo)+ expect(ask?.prompt).toBe(`${PROMPT}\n- TUI layout spacing consistency autonomous-harness ⎇ main\n- Lm studio respawn on quit autonomous-harness ⎇ lm-studio-stays-closed`)+ expect(ask?.engines).toEqual(['claude'])+ // The same harnesses in another order, or one twice: the same window, the same key.+ expect((await windowAsk(core, ['lm', 'tui', 'tui'], describeRepo))?.key).toBe(ask?.key)+ expect(ask?.key.split('\n')[0]).toBe('autonomous-harness')+ // A repo with fewer harnesses is left out; a tie goes to the first in pane order.+ expect((await windowAsk(core, ['grid', 'tui', 'lm'], describeRepo))?.prompt).not.toContain('Grid relay')+ expect((await windowAsk(core, ['grid', 'mob'], describeRepo))?.engines).toEqual(['codex'])+ expect((await windowAsk(core, ['loose'], describeRepo))?.key).toBe('loose\nFix the build loose ⎇ main')+ // A harness with no title of its own says nothing of its work: left out, and alone, no name asked.+ expect((await windowAsk(core, ['untitled', 'numbered', 'blank', 'tui'], describeRepo))?.prompt).toBe(`${PROMPT}\n- TUI layout spacing consistency autonomous-harness ⎇ main`)+ expect(await windowAsk(core, ['untitled', 'numbered', 'blank', 'pidefault'], describeRepo)).toBeNull()+ // No harness in a repo (a shell, a folder without git, no branch, a git that fails, an unknown agent): none.+ expect(await windowAsk(core, ['pi', 'sh', 'nobranch', 'broken', 'gone'], describeRepo)).toBeNull()+ })++ it('take only a short plain answer as a name', () => {+ expect(cleanName('Harness TUI LMStudio\n')).toBe('Harness TUI LMStudio')+ expect(cleanName('\x1b[0m> build · exo-free\n\n"Harness TUI LMStudio."\n')).toBe('Harness TUI LMStudio')+ expect(cleanName('Mobile Test')).toBe('Mobile Test')+ for (const wrong of ['', '\n> build\n', 'Autonomous harness TUI spacing and LM Studio', 'Harness + LMStudio', 'Harness · TUI', 'Harness, TUI', 'A name: Harness', 'x'.repeat(41)]) {+ expect(cleanName(wrong), wrong).toBeNull()+ }+ })++ it('pick OpenCode\'s free models as it lists them now, then the window\'s engines with their small model — never one named here', async () => {+ const listing = 'opencode/exo-free\nopencode/big-pickle\nzai/glm-5\nopencode/mimo-flash-free\nopencode/a-free\nopencode/b-free\n'+ expect(await defaultNamers(['claude', 'codex', 'pi', 'terminal', 'grok'], async () => listing)).toEqual([+ { engine: 'opencode', model: 'opencode/exo-free' }, { engine: 'opencode', model: 'opencode/mimo-flash-free' }, { engine: 'opencode', model: 'opencode/a-free' },+ { engine: 'claude', model: 'haiku', effort: 'low' }, { engine: 'codex', effort: 'low' }, { engine: 'pi' },+ ])+ // No OpenCode: the window's own engines alone.+ expect(await defaultNamers(['opencode'], async () => { throw new Error('ENOENT') })).toEqual([{ engine: 'opencode' }])+ // The real listing, run (a command that lists nothing here).+ expect(await defaultNamers(['claude'])).toEqual([{ engine: 'claude', model: 'haiku', effort: 'low' }])+ })++ it('answer pending at once, name the window behind the request, then answer its name — kept across a restart', async () => {+ const dataDir = mkdtempSync(join(tmpdir(), 'window-names-'))+ const first = setup({ dataDir })+ expect(await first.name(['tui', 'lm', 'pi'])).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await first.name(['tui', 'lm', 'pi'])).toEqual({ name: 'Harness TUI LMStudio' }))+ expect(first.ask).toHaveBeenCalledTimes(1)+ expect(first.namers).toHaveBeenCalledWith(['claude'])+ expect(JSON.parse(readFileSync(join(dataDir, 'window-names.json'), 'utf8'))[0][1]).toBe('Harness TUI LMStudio')+ // A restart: the name is read back, no model asked.+ const again = setup({ dataDir })+ expect(await again.name(['lm', 'tui'])).toEqual({ name: 'Harness TUI LMStudio' })+ expect(again.ask).not.toHaveBeenCalled()+ })++ it('name one window at a time, and keep the name a window has when it has no repo or no ids', async () => {+ let release!: (text: string) => void+ const { name } = setup({ ask: () => new Promise((resolve) => { release = resolve }) })+ expect(await name(['tui'])).toEqual({ name: null, pending: true })+ expect(await name(['mob'])).toEqual({ name: null, pending: true })+ release('Harness TUI')+ await vi.waitFor(async () => expect(await name(['tui'])).toEqual({ name: 'Harness TUI' }))+ for (const ids of [['pi', 'sh'], [], 'tui', [7, null]]) expect(await name(ids)).toEqual({ name: null })+ })++ it('try the next model when one fails or answers badly; with none, keep the name and ask again only after a while', async () => {+ let now = 1_000+ const tries: string[] = []+ const { name } = setup({+ now: () => now,+ namers: async () => [{ engine: 'opencode', model: 'a' }, { engine: 'opencode', model: 'b' }, { engine: 'claude', model: 'haiku' }],+ ask: async (namer) => {+ tries.push(namer.model!)+ if (namer.model === 'a') throw new Error('gone')+ return namer.model === 'b' ? 'Autonomous harness TUI spacing and LM Studio' : 'Harness TUI'+ },+ })+ expect(await name(['tui'])).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await name(['tui'])).toEqual({ name: 'Harness TUI' }))+ expect(tries).toEqual(['a', 'b', 'haiku'])++ const none = setup({ now: () => now, namers: async () => [] })+ expect(await none.name(['mob'])).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await none.name(['mob'])).toEqual({ name: null }))+ now += RETRY_MS+ expect(await none.name(['mob'])).toEqual({ name: null, pending: true })+ })++ it('give a model that never answers its time and ask the next — a window is never left pending', async () => {+ vi.useFakeTimers()+ try {+ const tries: string[] = []+ const { name } = setup({+ namers: async () => [{ engine: 'opencode', model: 'stuck' }, { engine: 'claude', model: 'haiku' }],+ ask: (namer) => { tries.push(namer.model!); return namer.model === 'stuck' ? new Promise<string>(() => {}) : Promise.resolve('Harness TUI') },+ })+ expect(await name(['tui'])).toEqual({ name: null, pending: true })+ await vi.advanceTimersByTimeAsync(BUDGET_MS - 1)+ expect(tries).toEqual(['stuck'])+ expect(await name(['tui'])).toEqual({ name: null, pending: true })+ await vi.advanceTimersByTimeAsync(1)+ expect(tries).toEqual(['stuck', 'haiku'])+ expect(await name(['tui'])).toEqual({ name: 'Harness TUI' })+ } finally { vi.useRealTimers() }+ })++ it('keep the newest names, read back only well-formed ones, and never fail a request over the disk', async () => {+ const dataDir = mkdtempSync(join(tmpdir(), 'window-names-'))+ writeFileSync(join(dataDir, 'window-names.json'), JSON.stringify([['k0', 'Old'], ['bad'], 7, ...Array.from({ length: KEEP }, (_, i) => [`k${i + 1}`, `N${i + 1}`])]))+ const { name } = setup({ dataDir, ask: async () => 'Mobile Test' })+ expect(await name(['mob'])).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await name(['mob'])).toEqual({ name: 'Mobile Test' }))+ const kept: Array<[string, string]> = JSON.parse(readFileSync(join(dataDir, 'window-names.json'), 'utf8'))+ expect(kept).toHaveLength(KEEP)+ expect(kept.some(([key]) => key === 'k0' || key === 'k1')).toBe(false)+ expect(kept.at(-1)?.[1]).toBe('Mobile Test')+ // A folder that cannot be written (the scratch folder, the names file): the window keeps its name.+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const unwritable = setup({ dataDir: '/dev/null/window-names' })+ expect(await unwritable.name(['tui'])).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await unwritable.name(['tui'])).toEqual({ name: null }))+ error.mockRestore()+ })++ it('a name it cannot write is still answered, and the error said', async () => {+ const dataDir = mkdtempSync(join(tmpdir(), 'window-names-'))+ // The names file is a folder: the scratch folder can be made, the file cannot be written.+ const { mkdirSync } = await import('node:fs')+ mkdirSync(join(dataDir, 'window-names.json.tmp'))+ const error = vi.spyOn(console, 'error').mockImplementation(() => {})+ const { name } = setup({ dataDir })+ expect(await name(['tui'])).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await name(['tui'])).toEqual({ name: 'Harness TUI LMStudio' }))+ expect(error).toHaveBeenCalledWith('[window-names] could not keep the names:', expect.any(String))+ error.mockRestore()+ })++ it('by default ask the small models through one cold one-shot each', async () => {+ const { name } = setup({ defaults: true })+ // (The default reads the repo too: this window's folders are not real repos, so nothing to name.)+ expect(await name(['tui'])).toEqual({ name: null })+ expect(runRouterOneShot).not.toHaveBeenCalled()+ const core = fakeCore({ dataDir: mkdtempSync(join(tmpdir(), 'window-names-')), agents: { byAgent: vi.fn(() => agent('tui', 'claude', '/work/harness')), displayName: vi.fn(() => 'TUI layout spacing consistency') } })+ const requests = startWindowNames(core, { describe: describeRepo, namers: async () => [{ engine: 'claude', model: 'haiku', effort: 'low' }] })+ expect(await requests.window_name!({ agentIds: ['tui'] }, ASKER)).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await requests.window_name!({ agentIds: ['tui'] }, ASKER)).toEqual({ name: 'Harness TUI' }))+ expect(runRouterOneShot).toHaveBeenCalledWith('claude', expect.objectContaining({ model: 'haiku', effort: 'low', timeoutMs: BUDGET_MS, prompt: expect.stringContaining('TUI layout spacing consistency') }))+ // With no namers given, the default ones (no OpenCode here, the window's claude with haiku).+ const plain = startWindowNames(fakeCore({ dataDir: mkdtempSync(join(tmpdir(), 'window-names-')), agents: { byAgent: vi.fn(() => agent('tui', 'claude', '/work/harness')), displayName: vi.fn(() => 'T') } }), { describe: describeRepo })+ expect(await plain.window_name!({ agentIds: ['tui'] }, ASKER)).toEqual({ name: null, pending: true })+ await vi.waitFor(async () => expect(await plain.window_name!({ agentIds: ['tui'] }, ASKER)).toEqual({ name: 'Harness TUI' }))+ })+})diff --git a/cli/src/services/windowNames.ts b/cli/src/services/windowNames.tsnew file mode 100644index 000000000..3d28d9636--- /dev/null+++ b/cli/src/services/windowNames.ts@@ -0,0 +1,195 @@+/**+ * Window names (`window_name`): a window of the apps named for the repo its harnesses work in and the+ * work they do — `Harness TUI LMStudio` — by a small model, in the background+ * (docs/plans/2026-10-07-002-window-auto-rename-daemon-plan.md). The pane names stay as they are; this is+ * the window's name alone, and an app asks for it only while its own Auto rename switch is on.+ *+ * An app sends the agent ids of one window's panes on this machine, in pane order. Only harnesses inside a+ * git repo with a title of their own count (not a shell, not a folder without git, not one still called+ * `Claude harness 10-7 14:02`), those of the repo most of them are in. A window+ * with none, or no model to ask, is answered `{ name: null }`: the app keeps the name it has. A name not+ * known yet is answered `pending` at once and asked of the model behind the request, one window at a time+ * — never in the request's line. Names are kept in `window-names.json` by the window's headings, so every+ * app asking for the same window gets the same name, and a window's titles changing asks again.+ *+ * The model is never named here: OpenCode's free models as `opencode models` lists them now, else the+ * window's own engines with their small model (Claude's `haiku`, Codex at low effort).+ */+import { execFile } from 'node:child_process'+import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'+import { basename, join } from 'node:path'+import { promisify } from 'node:util'+import type { CoreApi, ServiceRequests } from '../core/api.js'+import { parseOpencodeModelsOutput } from '../engines/opencode/runtimeProfile.js'+import { isTerminalEngine } from '../engines/types.js'+import { isAutomaticName } from '../lib/agentNames.js'+import type { OneShotEngine } from '../lib/disposableOneShotPool.js'+import { opencodeBin } from '../lib/engineBin.js'+import { runRouterOneShot } from '../lib/oneshot.js'+import { describeScmProject } from '../scm/scmProjects.js'+import { internalOnThrow } from './requestErrors.js'++/** The requests the window names answer for the apps, declared in core/api.ts for the core to route. */+export { WINDOW_NAMES_REQUESTS } from '../core/api.js'++/** What the model is asked, the window's panes' headings after it (`title repo ⎇ branch`). */+export const PROMPT = 'Name a terminal window in AT MOST 4 plain words so that someone reading it knows the work going on in it. '+ + 'Word 1: the repo name as one short word (autonomous-harness -> Harness). Then ONE keyword per piece of work (the product or part it '+ + 'touches, like TUI or LMStudio). No symbols, no punctuation, no "and", no quotes. Reply with ONLY the name.\n\n'+ + 'The window\'s panes, as their headings show them (title, then repo and branch):'++/** A window's key not named (no model answered a name) is asked again after this long. */+export const RETRY_MS = 10 * 60_000+/** What a model has to answer in; past it the next one is asked, whatever the model's own process does+ * (a one-shot whose process has already exited waits out its own timeout: lib/oneshot.ts). */+export const BUDGET_MS = 45_000+/** The names kept (the oldest go first). */+export const KEEP = 400+/** The agents of one window read, at most (a window holds nine panes). */+const MAX_AGENTS = 16+/** OpenCode's free models tried for one window, at most. */+const MAX_FREE = 3++/** What a window's name is asked from: [key], its repo's harnesses' headings, and the engines they run. */+export interface WindowAsk { key: string; prompt: string; engines: string[] }+/** A small model to ask: an engine, and a model and effort where the engine needs one named. */+export interface Namer { engine: OneShotEngine; model?: string; effort?: 'low' }++type Project = { kind: string; name: string; root: string | null; remote: string | null; branch: string | null }++export interface WindowNamesDeps {+ /** What repo a folder is in (scm/scmProjects.ts). */+ describe?: (cwd: string | null | undefined) => Promise<Project | null>+ /** The small models to try for a window whose harnesses run [engines], in order. */+ namers?: (engines: string[]) => Promise<Namer[]>+ /** One model's answer to [prompt], in a scratch folder [cwd]; throws when it fails. */+ ask?: (namer: Namer, prompt: string, cwd: string) => Promise<string>+ now?: () => number+}++/**+ * The ask for a window whose panes run agents [ids] (pane order): its harnesses inside a git repo (not a+ * shell), each once, of the repo most of them are in (a tie: the first in pane order). Null when none is.+ * A repo is known by its remote, else its name — never its folder: a linked worktree has a root of its own+ * (`gentle-walrus` for an autonomous-harness branch), and is the same repo.+ */+export async function windowAsk(core: Pick<CoreApi, 'agents'>, ids: readonly string[], describe: NonNullable<WindowNamesDeps['describe']>): Promise<WindowAsk | null> {+ const panes: Array<{ repo: string; name: string; line: string; engine: string }> = []+ for (const id of new Set(ids)) {+ const session = core.agents.byAgent(id)+ if (!session || isTerminalEngine(session.engine)) continue+ // A harness with no title yet (`OpenCode harness 10-7 16:45`, `harness-3`) says nothing of its work:+ // shown one, a model named an xiaozhi-esp32 window "Harness TUI Autoname" from the prompt's example.+ // Pi's own title before it has one, `π - autonomous-harness`, is the folder alone: no title either.+ const title = core.agents.displayName(session).trim()+ if (!title || isAutomaticName(title) || (session.cwd && title === `π - ${basename(session.cwd)}`)) continue+ const project = await describe(session.cwd).catch(() => null)+ if (!project || project.kind !== 'git' || !project.branch) continue+ panes.push({ repo: project.remote ?? project.name, name: project.name, line: `${title} ${project.name} ⎇ ${project.branch}`, engine: session.engine })+ }+ const counts = new Map<string, number>()+ for (const pane of panes) counts.set(pane.repo, (counts.get(pane.repo) ?? 0) + 1)+ let repo: string | null = null+ for (const [candidate, n] of counts) if (repo === null || n > counts.get(repo)!) repo = candidate+ if (repo === null) return null+ const mine = panes.filter((pane) => pane.repo === repo)+ const key = [mine[0].name, ...mine.map((pane) => pane.line).sort()].join('\n')+ const prompt = `${PROMPT}\n${mine.map((pane) => `- ${pane.line}`).join('\n')}`+ return { key, prompt, engines: [...new Set(mine.map((pane) => pane.engine))] }+}++/**+ * A model's answer as a window name: its last line (a banner and blank lines left out), one to four words+ * of letters and digits. Null for anything else, and the window keeps its name.+ */+export function cleanName(text: string): string | null {+ // eslint-disable-next-line no-control-regex+ const lines = text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, '').split('\n').map((line) => line.trim()).filter((line) => line && !line.startsWith('>'))+ const line = lines.at(-1)+ if (!line) return null+ const name = line.replace(/^["'`.*]+|["'`.*]+$/g, '').trim()+ const words = name.split(/\s+/).filter(Boolean)+ if (words.length === 0 || words.length > 4 || [...name].length > 40) return null+ if (!/^[\p{L}\p{N}\s]+$/u.test(name)) return null+ return words.join(' ')+}++const run = promisify(execFile)++/**+ * The small models for a window whose harnesses run [engines]: OpenCode's free models as it lists them now+ * (none named here; OpenCode not installed, none), then each of the window's engines that can answer once,+ * with its small model — Claude's `haiku`, Codex at low effort, the others as they are set.+ */+export async function defaultNamers(engines: readonly string[], list: () => Promise<string> = async () => (await run(opencodeBin(), ['models'], { timeout: 10_000, maxBuffer: 1024 * 1024 })).stdout): Promise<Namer[]> {+ const free = await list().then((out) => parseOpencodeModelsOutput(out).map((m) => m.id).filter((id) => /-free$/.test(id)), () => [])+ const own: Namer[] = engines.flatMap((engine): Namer[] => engine === 'claude' ? [{ engine: 'claude', model: 'haiku', effort: 'low' }]+ : engine === 'codex' ? [{ engine: 'codex', effort: 'low' }]+ : engine === 'opencode' || engine === 'pi' || engine === 'cursor' || engine === 'commandcode' || engine === 'kilo' ? [{ engine }]+ : [])+ return [...free.slice(0, MAX_FREE).map((model): Namer => ({ engine: 'opencode', model })), ...own]+}++/** One model's answer, cold: a window is named once, so no worker is kept warm for it. */+async function askOnce(namer: Namer, prompt: string, cwd: string): Promise<string> {+ const { text } = await runRouterOneShot(namer.engine, { prompt, cwd, model: namer.model, effort: namer.effort, timeoutMs: BUDGET_MS })+ return text+}++export function startWindowNames(core: CoreApi, deps: WindowNamesDeps = {}): ServiceRequests {+ const describe = deps.describe ?? describeScmProject+ const namers = deps.namers ?? ((engines: string[]) => defaultNamers(engines))+ const ask = deps.ask ?? askOnce+ const now = deps.now ?? Date.now+ const file = join(core.dataDir, 'window-names.json')+ const scratch = join(core.dataDir, 'window-names-scratch')+ const names = new Map<string, string>()+ const failed = new Map<string, number>()+ let naming: string | null = null++ try {+ const rows: unknown = JSON.parse(readFileSync(file, 'utf8'))+ if (Array.isArray(rows)) for (const row of rows) if (Array.isArray(row) && typeof row[0] === 'string' && typeof row[1] === 'string') names.set(row[0], row[1])+ } catch { /* none kept yet */ }++ const keep = (key: string, name: string): void => {+ names.delete(key)+ names.set(key, name)+ for (const old of names.keys()) { if (names.size <= KEEP) break; names.delete(old) }+ try {+ writeFileSync(`${file}.tmp`, JSON.stringify([...names]))+ renameSync(`${file}.tmp`, file)+ } catch (error) { console.error('[window-names] could not keep the names:', String(error)) }+ }++ /** The first valid name a small model gives the window; null when none does. */+ const nameOf = async (window: WindowAsk): Promise<string | null> => {+ mkdirSync(scratch, { recursive: true, mode: 0o700 })+ for (const namer of await namers(window.engines)) {+ let timer: NodeJS.Timeout | undefined+ const late = new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new Error('no answer in time')), BUDGET_MS) })+ const name = await Promise.race([ask(namer, window.prompt, scratch), late]).then(cleanName, () => null).finally(() => clearTimeout(timer))+ if (name) return name+ }+ return null+ }++ return {+ window_name: internalOnThrow('window_name', async (payload) => {+ const ids = Array.isArray(payload.agentIds) ? payload.agentIds.filter((id): id is string => typeof id === 'string').slice(0, MAX_AGENTS) : []+ const window = await windowAsk(core, ids, describe)+ if (!window) return { name: null }+ const known = names.get(window.key)+ if (known) return { name: known }+ if (naming !== null) return { name: null, pending: true }+ const at = failed.get(window.key)+ if (at !== undefined && now() - at < RETRY_MS) return { name: null }+ naming = window.key+ void nameOf(window).then((name) => {+ if (name) keep(window.key, name)+ else failed.set(window.key, now())+ }, () => { failed.set(window.key, now()) }).finally(() => { naming = null })+ return { name: null, pending: true }+ }),+ }+}diff --git a/cli/src/services/windowNamesProcess.spec.ts b/cli/src/services/windowNamesProcess.spec.tsnew file mode 100644index 000000000..4ffc00fa5--- /dev/null+++ b/cli/src/services/windowNamesProcess.spec.ts@@ -0,0 +1,58 @@+import { afterEach, describe, expect, it, vi } from 'vitest'+import type { CoreApi } from '../core/api.js'+import { WINDOW_NAMES_REQUESTS } from '../core/api.js'+import type { RegisteredSession } from '../lib/registry.js'+import { runServiceProcess, type CoreConnection, type ServiceProcessOptions } from './process.js'+import { runWindowNamesService } from './windowNamesProcess.js'++// The real default reaches a real socket: never in a test.+vi.mock('./process.js', () => ({ runServiceProcess: vi.fn(() => ({ stop: vi.fn() })) }))++const agent = (agentId: string, displayName: string) => ({ agentId, sessionId: `s-${agentId}`, engine: 'claude', cwd: `/work/${agentId}`, displayName }) as RegisteredSession & { displayName: string }+const ASKER = { local: true, owner: true }++describe('the window names in their own process', () => {+ afterEach(() => vi.clearAllMocks())++ const setup = () => {+ let options: ServiceProcessOptions | null = null+ let api: CoreApi | null = null+ /** The names the window names saw for the agents when they were asked. */+ const seen: string[][] = []+ runWindowNamesService({+ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't',+ run: (given) => { options = given; return { stop: vi.fn() } },+ start: (core) => {+ api = core+ return { window_name: (payload, asker) => { seen.push(core.agents.live().map((session) => core.agents.displayName(session))); return { ids: payload.agentIds, owner: asker.owner } } }+ },+ })+ return { options: options!, api: api!, seen }+ }++ it('reads the agents and the names the apps show from the core as each request starts', async () => {+ const { options, api, seen } = setup()+ expect(options).toMatchObject({ name: 'windowNames', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ // Before a core has connected: the agents it last said, which is none.+ expect(await options.requests.window_name!({ agentIds: ['a1'] }, ASKER)).toEqual({ ids: ['a1'], owner: true })+ let answer: Record<string, unknown> = { agents: [agent('a1', 'TUI layout spacing consistency')] }+ const query = vi.fn(async (_name: string) => answer)+ options.onConnected!({ query } satisfies CoreConnection)+ await options.requests.window_name!({}, ASKER)+ // `agents`, not `live`: it carries the name each agent is shown by, which a window is named from.+ expect(query).toHaveBeenLastCalledWith('agents')+ answer = { error: 'UNKNOWN_QUERY' }+ await options.requests.window_name!({}, ASKER)+ query.mockRejectedValueOnce(new Error('the core went away'))+ await options.requests.window_name!({}, ASKER)+ expect(seen).toEqual([[], ['TUI layout spacing consistency'], ['TUI layout spacing consistency'], ['TUI layout spacing consistency']])+ expect(api.agents.byAgent('a1')?.agentId).toBe('a1')+ })++ it('runs as a real service by default, answering every request the core routes to it', () => {+ runWindowNamesService({ dataDir: '/data', socketPath: '/data/daemon-1.sock', machineId: 'm', token: 't' })+ const options = vi.mocked(runServiceProcess).mock.calls.at(-1)![0]+ expect(options.name).toBe('windowNames')+ expect(Object.keys(options.requests)).toEqual([...WINDOW_NAMES_REQUESTS])+ })+})diff --git a/cli/src/services/windowNamesProcess.ts b/cli/src/services/windowNamesProcess.tsnew file mode 100644index 000000000..af681001c--- /dev/null+++ b/cli/src/services/windowNamesProcess.ts@@ -0,0 +1,42 @@+/**+ * The window names in their own process (`harness __service windowNames`, in the edge host): the same+ * handler as in the core's process (services/windowNames.ts), on the agents the core names as each request+ * starts (`service_query agents`, which carries the name the apps show for each). The model runs and their+ * time are this process's alone.+ */+import type { ServiceRequests } from '../core/api.js'+import type { RegisteredSession } from '../lib/registry.js'+import { runServiceProcess, type CoreConnection, type ServiceProcess } from './process.js'+import { agentsIn, processCoreApi } from './processCoreApi.js'+import { startWindowNames } from './windowNames.js'++export interface WindowNamesServiceOptions {+ dataDir: string+ socketPath: string+ machineId: string+ token: string+ /** Swapped in tests for one that does not touch the real socket or process. */+ run?: typeof runServiceProcess+ /** Swapped in tests for one that runs no model and reads no disk. */+ start?: typeof startWindowNames+}++export function runWindowNamesService(options: WindowNamesServiceOptions): ServiceProcess {+ let agents: RegisteredSession[] = []+ let core: CoreConnection | null = null+ /** The agents now, with their shown names. A core that cannot say leaves the last ones it said. */+ const refresh = async (): Promise<void> => {+ agents = agentsIn(await core?.query('agents').catch(() => null)) ?? agents+ }+ const answers = (options.start ?? startWindowNames)(processCoreApi(options.dataDir, 'windowNames', { live: () => agents }))+ const requests: ServiceRequests = Object.fromEntries(Object.entries(answers).map(([type, handle]) =>+ [type, async (payload: Record<string, unknown>, asker: Parameters<typeof handle>[1]) => { await refresh(); return handle(payload, asker) }]))+ return (options.run ?? runServiceProcess)({+ name: 'windowNames',+ socketPath: options.socketPath,+ machineId: options.machineId,+ token: options.token,+ requests,+ onConnected: (connection) => { core = connection },+ })+}diff --git a/docs/plans/2026-10-07-002-window-auto-rename-daemon-plan.md b/docs/plans/2026-10-07-002-window-auto-rename-daemon-plan.mdnew file mode 100644index 000000000..f85110d26--- /dev/null+++ b/docs/plans/2026-10-07-002-window-auto-rename-daemon-plan.md@@ -0,0 +1,82 @@+# Window auto rename: one daemon request, the TUI first++Status: built (daemon, TUI, desktop). Date 2026-10-07. Replaces a TUI-only model call that+was tried first in `tui/src/autoname.rs`.++## What the user decided++- Pane names stay exactly as they are. Only a WINDOW (tab) gets a new name, and only when its+ harness panes are inside a git repo.+- Name = one short phrase, at most 4 words, no symbols: a one-word form of the repo, then one keyword+ per piece of work — `Harness TUI LMStudio`, `Mobile Test`, `Xiaozhi Muse Gadgets`.+- Written by a small model in the background. Never a hard-coded model: an OpenCode free model picked+ at run time; else the engine the panes use, with its small model (Claude `haiku`, Codex at low+ effort). No model: the window keeps the name it has.+- The daemon does the naming, as it already does for pane names (`projectDisplayName`, sent to every+ app). Apps that want it call one request; each app has its own **Auto rename** switch, **off by+ default** — off, an app behaves exactly as today.+- The TUI first, then release (CLI + TUI). Desktop and mobile come later and reuse the same request.+- Appearance: the **Tab name** section goes away; the tab shows the selected pane's title (`pane`)+ by default, and a window auto rename named shows that name instead. (`Tab` — how the current tab+ is marked — stays.)++## The request (the part every app reuses)++```+→ window_name { agentIds: ["…", "…"] } this machine's agents of one window, in pane order+← { name: "Harness TUI LMStudio" } named+← { name: null, pending: true } being named in the background; ask again later+← { name: null } no harness pane in a repo, or no model: keep the name+← { error: "SERVICE_UNAVAILABLE" | "UNSUPPORTED" } an older or failing daemon: keep the name+```++The app sends agent ids only; the daemon knows each agent's title, repo, branch and engine, so every+rule lives in one place.++## Daemon (`cli/`)++| File | Change |+|---|---|+| `src/core/api.ts` | `export const WINDOW_NAMES_REQUESTS = ['window_name'] as const` beside the other `*_REQUESTS`. |+| `src/services/windowNames.ts` (new) | `startWindowNames(core, ports)` → `{ window_name }`. Reads agents only through `core.agents` (`byAgent`, `displayName`) — a service process has no machine name; repo and branch through `describeScmProject` (`kind === 'git'`). Rules moved from `tui/src/autoname.rs`: skip shells (`terminal` engine), agents not in a repo, and agents with no title of their own yet (`OpenCode harness 10-7 16:45`, `harness-3`: `isAutomaticName`; shown one, a model copied the prompt's example and named an xiaozhi-esp32 window "Harness TUI Autoname"); the repo most of them are in, known by its remote (a linked worktree has its own root and is the same repo; a tie: the first in pane order); each agent once; headings `title repo ⎇ branch`; key = repo + sorted headings; the same prompt; the same answer check (1–4 words, letters and digits only). Names kept in `<dataDir>/window-names.json` (400 newest, written atomically). A name missing: answer `pending` at once and name it in the background — never awaited in the request (core rule 4); one at a time; a failed key not retried for 10 minutes. |+| same file: the model | `pickNamer(engines)`: OpenCode on PATH → `opencode models`, the ids ending in `-free`, tried in order until one answers a valid name (at most 3); else the first engine among the window's harnesses that can run a one-shot — Claude with model `haiku`, Codex with its default model at effort `low`, others with their default. Run through `lib/oneshot.ts` (`runRouterOneShot`, cold), cwd a scratch folder in the data dir, 45 s budget per model, raced in the service (a one-shot whose process already exited waits out its own timeout). Known: OpenCode 2's `run` no longer takes `--pure`, so its one-shot fails today and Claude `haiku` names the window; `lib/oneshot.ts` is fixed separately. |+| `src/services/windowNamesProcess.ts` (new) | Its runner in its own process, as `projectsProcess.ts`. |+| `src/services/inline.ts` | `export { startWindowNames } from './windowNames.js'`. |+| `src/serviceProcess.ts` | `SERVICE_RUNNERS`: `['windowNames', …runWindowNamesService]`. |+| `src/harnessd/services.ts` | `SERVICE_HOSTS.edge.services`: add `'windowNames'` (light pure JS beside workspaces, projects). |+| `src/core/main.ts` | Requests map: `windowNames: WINDOW_NAMES_REQUESTS`; in-process fallback: `serviceHost.serve('windowNames', inline!.startWindowNames, coreApi, WINDOW_NAMES_REQUESTS)`. |+| `src/lib/e2ee/core.ts` | Not changed here: its lists are hash-pinned with the web client and the device firmware in other repos. Until they move together, only an app on the same machine asks (the TUI's local link, the desktop's local daemon). |+| Tests | `services/windowNames.spec.ts` (100% coverage with `fakeCore()`: rules, key, prompt, answer check, cache, pending, retry, model choice, no model), `windowNamesProcess.spec.ts`, `e2e/services.e2e.ts` (the service in `EVERY_PROCESS_FAILING`, a `windowNames.window_name` fault answers `SERVICE_FAILED`, the service off answers `SERVICE_UNAVAILABLE`). |++## TUI (`tui/`)++| File | Change |+|---|---|+| `src/autoname.rs` | Keep: the switch, the call from `sync_titles`, `#{window_auto_named}`. Replace the local model run and `window-names.json` with the request: per window, the machine most of its repo panes are on (the TUI knows project and branch), its agent ids in pane order. Answers kept in memory by (machine, agent ids, their names) so a title change asks again; `pending` → ask again in 5 s; an error or `null` → keep the name. |+| `src/modal.rs` | Remove the `Tab name` section and its options (and its tests' rows). `Auto rename` stays. |+| `src/options/mod.rs`, `src/config.rs`, `src/app.rs` (`sync_window_status`), `src/settings.rs` | Default tab name source `pane` (was `tmux`); `@hn-window-name tmux` from a tmux.conf or an old tui.toml still works. |+| kept from today | `agent_renamed` by `agentId`; `set` re-derives the tab format; an empty rename returns to automatic; a name cleared on the desk; an older server's derived formats re-derived on join. |+| Tests | Rust unit tests for the request flow (named / pending / null / error), machine choice, the removed section, the `pane` default; `e2e.sh`, `new-harness.py`, `keybinds.py`, `native-terminal.py`. |++## Real end-to-end check (before any release)++An isolated daemon (the `e2e/` `IsolatedDaemon` helper, its own data folder) on this machine with real+OpenCode; new harnesses in a repo; an isolated hn against it with Auto rename on:+a window gets a name within a minute; the same window again is answered from `window-names.json`+without a model run; a title change renames it; a window without a repo keeps its name; Auto rename+off changes nothing; with no engine on PATH the window keeps its name; an older daemon (no request)+leaves the TUI as today. Every harness made is deleted afterwards.++## Release++1. CLI: `npx vitest run` + `tsc --noEmit` on the branch, `make release-cli ARGS=--dry-run`, then the+ CLI release; verify the published version.+2. TUI: bump to 0.1.15, `cargo test --locked`, `e2e.sh`, `native-terminal.py`, release-tui.yml;+ verify the four binaries' checksums.+3. Auto rename stays off by default in both; nothing changes for anyone until they turn it on.++## Later (not in this change)++Desktop is built in this change and released only after the user tests it. Mobile, and remote machines+for any app: `window_name` / `window_name_result` added to the e2ee lists together with the web client and+firmware repos. OpenCode 2's one-shot in `lib/oneshot.ts`.diff --git a/tui/Cargo.lock b/tui/Cargo.lockindex 2af8e6708..2a2614599 100644--- a/tui/Cargo.lock+++ b/tui/Cargo.lock@@ -654,7 +654,7 @@ dependencies = [[[package]]name = "harness-tui"-version = "0.1.14"+version = "0.1.15"dependencies = ["alacritty_terminal","base64",diff --git a/tui/Cargo.toml b/tui/Cargo.tomlindex ac5d45a5f..82ad646e7 100644--- a/tui/Cargo.toml+++ b/tui/Cargo.toml@@ -1,6 +1,6 @@[package]name = "harness-tui"-version = "0.1.14"+version = "0.1.15"edition = "2024"[dependencies]diff --git a/tui/src/app.rs b/tui/src/app.rsindex 1bd152d8d..cadad6924 100644--- a/tui/src/app.rs+++ b/tui/src/app.rs@@ -547,6 +547,8 @@ pub struct App {/// Sessions' latest turns (session_tail), by session id: read once each time C-b s opens.pub tails: HashMap<String, Value>,pub tails_asked: HashSet<String>,+ /// Auto rename's names and its one ask at a time (`autoname.rs`).+ pub autoname: crate::autoname::Namer,pub desk_mode: DeskMode,/// The daemon on this computer is signed in (its `/api/status`): with DeskMode::Account, the/// desk is in front, with this computer's windows joined to it.@@ -1029,6 +1031,7 @@ impl App {said: Vec::new(),tails: HashMap::new(),tails_asked: HashSet::new(),+ autoname: Default::default(),desk_mode,signed_in: false,desk_revision: -1,@@ -1509,9 +1512,12 @@ impl App {match ty {"agent_synced" | "agent_created" | "agent_renamed" => {let row = payload.get("agent").cloned().unwrap_or(payload.clone());- let Some(id) = row.get("id").and_then(Value::as_str).map(str::to_string) else { return };+ // (The daemon's `agent_renamed` is `{agentId, name, engine}`: a name, not a row.)+ let Some(id) = row.get("id").or_else(|| row.get("agentId")).and_then(Value::as_str).map(str::to_string) else { return };let key = (machine_id.to_string(), id);- if ty == "agent_renamed" && row.get("engine").is_none() {+ if ty == "agent_renamed" && payload.get("agent").is_none() {+ // Its name only (a rename, or its engine's new title: `projectDisplayName`) —+ // never an agent rebuilt from a partial row.if let (Some(agent), Some(name)) = (self.fleet.agents.get_mut(&key), row.get("name").and_then(Value::as_str)) { agent.name = name.to_string() }} else {let previous = self.fleet.agents.get(&key);@@ -4643,8 +4649,18 @@ impl App {pub fn sync_titles(&mut self) {// Harness OS signed in: a desk tab is called what the desktop app calls it.let desk_names = if self.desk_mode == DeskMode::Account && self.session_desk { self.desk_tab_names() } else { HashMap::new() };+ let auto_rename = self.options.auto_rename();for index in 0..self.tabs.len() {if self.tabs[index].named || self.tabs[index].home { continue }+ // Auto rename: a window with a repo, for the repo and its work (autoname.rs); until its+ // name comes, and without a repo, as before.+ if auto_rename { if let Some(name) = self.auto_name(index) { self.tabs[index].name = name; continue } }+ // Auto rename off, a window still called what it named it: named again as before — also+ // where automatic-rename is off, which would otherwise keep the name it found.+ else if crate::autoname::given(self, index).is_some_and(|name| name == self.tabs[index].name) {+ self.tabs[index].first_named = false;+ self.name_tab_after_first_at(index);+ }if let Some(name) = desk_names.get(&self.tabs[index].id) { self.tabs[index].name = name.clone(); continue }// tmux's automatic-rename (unless it is off): an unnamed window is called after its// active pane — a shell by what runs in it (automatic-rename-format: `zsh`, `vim`,@@ -5135,8 +5151,19 @@ impl App {pub fn rename_tab(&mut self, name: &str) { let i = self.active; self.rename_tab_at(i, name) }- /// rename-window -t: that window.+ /// rename-window -t: that window. An empty name gives the window back to automatic naming:+ /// it is called what it would be had nobody named it.pub fn rename_tab_at(&mut self, index: usize, name: &str) {+ if name.trim().is_empty() {+ let Some(tab) = self.tabs.get_mut(index) else { return };+ tab.named = false;+ tab.first_named = false;+ let (id, on_desk) = (tab.id.clone(), tab.on_desk);+ if let Some(options) = self.options.windows.get_mut(&id) { options.remove("automatic-rename"); }+ self.sync_titles();+ if on_desk { let name = self.tabs[index].name.clone(); self.desk_op(json!({ "op": "tab.rename", "id": id, "name": name, "nameIsCustom": false })) }+ return;+ }let Some(tab) = self.tabs.get_mut(index) else { return };tab.name = name.to_string();tab.named = true;@@ -5484,6 +5511,7 @@ impl App {}"border_style" => ("@hn-border", format!("border style: {value}")),"dim" => ("@hn-dim", format!("dim other panes: {value}")),+ "auto_rename" => ("@hn-auto-rename", format!("auto rename: {value}")),// ── status bar tabs ──// The two tab options decide the window-status-* format and current-tab style; set the// remembered choice now, then reconcile those derived options the way `[look]` would@@ -5501,6 +5529,7 @@ impl App {// (The bar and the frames change the panes' room: every program is told its size.)if matches!(knob, "status_bar" | "border_style" | "window_active" | "window_name") { self.redraw_all = true }if matches!(knob, "status_bar" | "border_style") { self.fit_panes() }+ if knob == "auto_rename" { self.sync_titles(); self.redraw_all = true }let i = self.active;self.view_layout_changed(i);self.persist_look();@@ -5509,8 +5538,8 @@ impl App {/// Recompute the status bar's `window-status-*` overrides from `@hn-window-name` and/// `@hn-window-active` (which together decide them), the same pair `[look]` emits at boot.- fn sync_window_status(&mut self) {- let name = self.options.get("@hn-window-name", "", None).unwrap_or_else(|| "tmux".into());+ pub(crate) fn sync_window_status(&mut self) {+ let name = self.options.get("@hn-window-name", "", None).unwrap_or_else(|| crate::options::DEFAULT_TAB_NAME.into());let active = self.options.get("@hn-window-active", "", None).unwrap_or_else(|| "star".into());let overrides = crate::options::window_status_overrides(&name, &active);let global = crate::options::SetFlags { global: true, ..Default::default() };@@ -5527,6 +5556,17 @@ impl App {}}+ /// The status bar's `window-status-*` formats derived again by this build, when they are hn's own+ /// (`status_window_format`'s, whatever build derived them) and not as this build derives them —+ /// never a format somebody wrote. Whether they changed.+ pub fn rederive_window_status(&mut self) -> bool {+ let names = ["window-status-format", "window-status-current-format"];+ let now: Vec<Option<String>> = names.iter().map(|n| self.options.get(n, "", None)).collect();+ if !now.iter().flatten().all(|v| crate::options::derived_window_status(v)) { return false }+ self.sync_window_status();+ names.iter().map(|n| self.options.get(n, "", None)).collect::<Vec<_>>() != now+ }+/// Write the current look (as the options hold it) to tui.toml's `[look]`, best-effort.pub fn persist_look(&mut self) {let mut look = crate::config::Look::default();@@ -5545,6 +5585,7 @@ impl App {look.dim = self.options.get("@hn-dim", "", None);look.window_active = self.options.get("@hn-window-active", "", None);look.window_name = self.options.get("@hn-window-name", "", None);+ look.auto_rename = self.options.get("@hn-auto-rename", "", None);if let Err(e) = crate::config::write_look(&look) { self.say(format!("could not write tui.toml: {e}"), crate::theme::DANGER) }}@@ -5732,6 +5773,12 @@ impl App {let layout_doc = row.get("layout").cloned().unwrap_or(json!({}));match self.tabs.iter().position(|t| t.id == id) {Some(index) => {+ // A name given elsewhere and cleared there (an empty rename): automatic naming is+ // back here too — as `rename_tab_at` leaves it — or the old name would stay.+ if !named && self.tabs[index].named {+ self.tabs[index].first_named = false;+ if let Some(options) = self.options.windows.get_mut(&id) { options.remove("automatic-rename"); }+ }let tab = &mut self.tabs[index];// A name given (rename-window) is every terminal's; one automatic-rename gave// stays as automatic-rename gives it here, from what the window runs.@@ -6683,6 +6730,49 @@ mod recovery_tests {assert_eq!(app.tabs[0].name, "discussion");}+ /// The daemon's `agent_renamed` as it really is (`cli/src/core/agents/events.ts`: `{agentId,+ /// name, engine}`): the harness is called that at once, and the rest known about it stays.+ #[tokio::test]+ async fn a_real_agent_renamed_renames_the_harness_and_keeps_the_rest() {+ let mut app = fixture();+ app.fleet.merge_roster("test-peer", &[json!({"id": "agent-1", "name": "Claude harness 10-7 14:04", "engine": "claude", "project": {"name": "webapp", "branch": "main"}})]);+ app.on_frame("test-peer", "agent_renamed", json!({"agentId": "agent-1", "name": "Deploy checklist", "engine": "claude"}));+ let agent = app.fleet.agent("test-peer", "agent-1").unwrap();+ assert_eq!((agent.name.as_str(), agent.engine.as_str(), agent.project.as_str(), agent.branch.as_str()), ("Deploy checklist", "claude", "webapp", "main"));+ }++ /// `set -g @hn-window-name …` by hand (or from a config file) changes the tab as Appearance does.+ #[tokio::test]+ async fn setting_the_tab_name_source_by_hand_changes_the_tab_at_once() {+ let mut app = fixture();+ let format = |app: &App| app.options.get("window-status-format", "", None).unwrap_or_default();+ crate::commands::execute(&mut app, "set -g @hn-window-name pane");+ assert!(format(&app).contains("#{pane_title}"), "{}", format(&app));+ crate::commands::execute(&mut app, "set -g @hn-window-name tmux");+ assert!(format(&app).contains("#{window_short_name}") && !format(&app).contains("#{pane_title}"), "{}", format(&app));+ }++ /// Renaming a window to nothing gives it back to automatic naming; a name stays its own.+ #[tokio::test]+ async fn an_empty_rename_gives_the_window_back_to_automatic_naming() {+ let mut app = fixture();+ app.fleet.merge_roster("test-peer", &[json!({"id": "agent-1", "name": "Fix flaky login test", "engine": "claude", "project": {"name": "webapp"}})]);+ let mut tab = Tab::with_wid("w", 1);+ tab.root = Some(Node::new(1, 80, 23));+ tab.focus = Some(1);+ app.tabs = vec![tab];+ app.active = 0;+ app.rename_tab_at(0, "release");+ app.sync_titles();+ assert!(app.tabs[0].named && app.tabs[0].name == "release", "a name you set is never overwritten");+ let id = app.tabs[0].id.clone();+ assert_eq!(app.options.windows.get(&id).and_then(|o| o.get("automatic-rename")).map(String::as_str), Some("off"));+ app.rename_tab_at(0, " ");+ assert!(!app.tabs[0].named);+ assert_eq!(app.tabs[0].name, "Fix flaky login test");+ assert!(app.options.windows.get(&id).is_none_or(|o| !o.contains_key("automatic-rename")), "tmux's automatic-rename is back on");+ }+#[tokio::test]async fn the_os_joins_its_windows_to_the_account_and_keeps_its_own_harnesses_after() {let mut app = fixture();@@ -6993,6 +7083,27 @@ mod desk_layout_tests {assert_eq!(desk_pane_ids(app.tabs[0].root.as_ref().unwrap()), vec![3, 2, 1]);}+ /// A name given on the desktop is every terminal's; cleared there (an empty rename), the window+ /// is named automatically here again — not left with the old name.+ #[test]+ fn a_name_cleared_on_the_desk_is_automatic_here_again() {+ let mut app = fixture();+ app.fleet.merge_roster("layout-peer", &[json!({"id": "agent-1", "name": "Task 1", "engine": "claude", "project": {"name": "webapp"}})]);+ app.tabs[0].focus = Some(1);+ let mut named = desk(2, app.tabs[0].layout.clone());+ named["tabs"][0]["name"] = json!("release");+ named["tabs"][0]["nameIsCustom"] = json!(true);+ app.apply_desk(&named);+ app.sync_titles();+ assert!(app.tabs[0].named && app.tabs[0].name == "release");+ let mut cleared = desk(3, app.tabs[0].layout.clone());+ cleared["tabs"][0]["name"] = json!("New Swarm");+ app.apply_desk(&cleared);+ app.sync_titles();+ assert!(!app.tabs[0].named);+ assert_eq!(app.tabs[0].name, "Task 1");+ }+#[test]fn shared_pane_sequence_is_spatial_not_tree_or_tmux_number_order() {let mut root = layout::arrange(layout::Named::MainVerticalMirrored, &[1, 2, 3], 120, 35,diff --git a/tui/src/autoname.rs b/tui/src/autoname.rsnew file mode 100644index 000000000..41c81abf1--- /dev/null+++ b/tui/src/autoname.rs@@ -0,0 +1,283 @@+//! Auto rename (`@hn-auto-rename on`, tui.toml `auto_rename`): a window with a repo is named for the+//! repo and the work its panes do — `Harness TUI LMStudio` — by the daemon (`window_name`,+//! cli/src/services/windowNames.ts; docs/plans/2026-10-07-002-window-auto-rename-daemon-plan.md). The+//! daemon holds the rules, picks a small model and keeps the names, so every app asking for the same+//! window gets the same name. Off (the default), no window is asked for and every name is as before.+//!+//! A window is asked of the machine most of its harness panes in a git repo are on, with that machine's+//! agents in pane order. Until its name comes — and with no repo, an older daemon or no model — the+//! window keeps the name it has. A name you set always wins.++use std::collections::HashMap;+use std::time::{Duration, Instant};++use serde_json::{json, Value};++use crate::app::App;++/// What a window's name is asked from: the machine, its agents in pane order, and [key] — those agents+/// with the names they are shown by now, so a title changing asks again.+#[derive(Debug, PartialEq)]+pub struct Ask { pub machine: String, pub agents: Vec<String>, pub key: String }++/// What the daemon said of a window.+enum Answer { Name(String), None(Instant) }++/// The daemon's answers, by [Ask::key]; the windows asked now; the machines that could not answer.+#[derive(Default)]+pub struct Namer {+ answers: HashMap<String, Answer>,+ asking: HashMap<String, Instant>,+ quiet: HashMap<String, Instant>,+}++/// A window with no name (no repo, no model) or a machine that could not answer is asked again after this.+const RETRY: Duration = Duration::from_secs(600);+/// A window being named is asked again after this.+const AGAIN: Duration = Duration::from_secs(5);+/// What the daemon has to answer in (it answers at once: `pending` while it names the window).+const BUDGET: Duration = Duration::from_secs(15);++/// The ask for window [index]: the machine most of its harness panes in a git repo (a branch) are on —+/// a tie, the first in pane order — and that machine's agents in the window, in pane order, each once+/// (the daemon picks among them). None when no harness pane is in a repo.+pub fn ask(app: &App, index: usize) -> Option<Ask> {+ let tab = app.tabs.get(index)?;+ let mut agents: Vec<(String, String, String)> = Vec::new();+ let mut repo: Vec<(String, usize)> = Vec::new();+ for id in tab.panes() {+ let Some(pane) = app.panes.get(&id) else { continue };+ if agents.iter().any(|(m, a, _)| *m == pane.machine_id && *a == pane.agent_id) { continue }+ let Some(agent) = app.fleet.agent(&pane.machine_id, &pane.agent_id) else { continue };+ agents.push((pane.machine_id.clone(), pane.agent_id.clone(), agent.name.clone()));+ if agent.engine == "terminal" || agent.project.is_empty() || agent.branch.is_empty() { continue }+ match repo.iter_mut().find(|(m, _)| *m == pane.machine_id) { Some((_, n)) => *n += 1, None => repo.push((pane.machine_id.clone(), 1)) }+ }+ let machine = repo.iter().fold(None::<&(String, usize)>, |best, r| match best { Some(b) if b.1 >= r.1 => best, _ => Some(r) })?.0.clone();+ let mine: Vec<&(String, String, String)> = agents.iter().filter(|(m, _, _)| *m == machine).collect();+ let key = format!("{machine}\n{}", mine.iter().map(|(_, a, n)| format!("{a}\t{n}")).collect::<Vec<_>>().join("\n"));+ Some(Ask { machine, agents: mine.iter().map(|(_, a, _)| a.clone()).collect(), key })+}++/// Whether window [index] has auto rename's name now — `#{window_auto_named}`, so a status bar that+/// shows the selected pane's title shows this name instead.+pub fn named(app: &App, index: usize) -> bool {+ app.options.auto_rename() && app.tabs.get(index).is_some_and(|t| !t.named && !t.home)+ && ask(app, index).is_some_and(|a| matches!(app.autoname.answers.get(&a.key), Some(Answer::Name(_))))+}++/// The name auto rename has for window [index], the switch on or off — to tell its name from another.+pub fn given(app: &App, index: usize) -> Option<String> {+ if app.autoname.answers.is_empty() { return None }+ let ask = ask(app, index)?;+ match app.autoname.answers.get(&ask.key) { Some(Answer::Name(name)) => Some(name.clone()), _ => None }+}++impl App {+ /// Window [index]'s name by auto rename: the daemon's, else None — asked once (again while the+ /// daemon names it), the window keeping its name meanwhile.+ pub fn auto_name(&mut self, index: usize) -> Option<String> {+ let ask = ask(self, index)?;+ match self.autoname.answers.get(&ask.key) {+ Some(Answer::Name(name)) => return Some(name.clone()),+ Some(Answer::None(at)) if at.elapsed() < RETRY => return None,+ _ => {}+ }+ if self.autoname.quiet.get(&ask.machine).is_some_and(|at| at.elapsed() < RETRY) { return None }+ if self.autoname.asking.get(&ask.key).is_some_and(|at| at.elapsed() < BUDGET + AGAIN) { return None }+ let Some(link) = self.link(&ask.machine) else { return None };+ self.autoname.asking.insert(ask.key.clone(), Instant::now());+ let Ask { machine, agents, key } = ask;+ self.spawn(async move { link.rpc("window_name", json!({ "agentIds": agents }), BUDGET).await.ok() }, move |app: &mut App, answer: Option<Value>| {+ app.window_name_answer(&machine, key, answer);+ });+ None+ }++ /// The daemon's answer for the window [key] (on [machine]): its name; `pending` — asked again in a+ /// moment; none (no repo, no model) — asked again in a while; no answer or an error (an older+ /// daemon, the service off) — that machine is not asked for a while.+ pub fn window_name_answer(&mut self, machine: &str, key: String, answer: Option<Value>) {+ match answer {+ Some(a) if a.get("error").is_none() => match a.get("name").and_then(Value::as_str) {+ Some(name) => { self.autoname.asking.remove(&key); self.autoname.answers.insert(key, Answer::Name(name.to_string())); }+ None if a.get("pending").and_then(Value::as_bool) == Some(true) => {+ // Asked again once it has had a moment: until then the window is not asked.+ self.autoname.asking.insert(key, Instant::now() - BUDGET);+ self.spawn(tokio::time::sleep(AGAIN), |app: &mut App, _| { app.sync_titles(); app.redraw_all = true });+ return;+ }+ None => { self.autoname.asking.remove(&key); self.autoname.answers.insert(key, Answer::None(Instant::now())); }+ },+ _ => { self.autoname.asking.remove(&key); self.autoname.quiet.insert(machine.to_string(), Instant::now()); }+ }+ self.sync_titles();+ self.redraw_all = true;+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::app::Tab;+ use crate::fleet::{Machine, Reach};+ use crate::layout::{Dir, Node};+ use crate::pane::{Pane, Phase};++ /// The user's window: two harnesses in autonomous-harness, one in aptis-notes (no git), a shell —+ /// and, on another machine, a harness in a repo.+ fn app() -> App {+ let (sink, _) = tokio::sync::mpsc::unbounded_channel();+ let mut app = App::new(19791, sink, (120, 36));+ for (id, name) in [("m", "Mac Auto"), ("b", "Box")] {+ app.fleet.machines.push(Machine { id: id.into(), name: name.into(), local: id == "m", shared: false, status: "running".into(), reach: Reach::Ready });+ }+ app.fleet.merge_roster("m", &[+ json!({"id": "a1", "name": "TUI layout spacing consistency", "engine": "claude", "project": {"name": "autonomous-harness", "branch": "main"}}),+ json!({"id": "a2", "name": "Lm studio respawn on quit", "engine": "claude", "project": {"name": "autonomous-harness", "branch": "lm-studio-stays-closed"}}),+ json!({"id": "a3", "name": "pi:c", "engine": "pi", "project": {"name": "aptis-notes"}}),+ json!({"id": "a4", "name": "Terminal harness 10-6 11:25", "engine": "terminal", "project": {"name": "autonomous-harness", "branch": "main"}}),+ ]);+ app.fleet.merge_roster("b", &[json!({"id": "b1", "name": "Grid relay respawn prod", "engine": "codex", "project": {"name": "autonomous-grid-cli", "branch": "main"}})]);+ for (i, (machine, agent)) in [("m", "a1"), ("m", "a2"), ("m", "a3"), ("m", "a4"), ("b", "b1")].into_iter().enumerate() {+ let mut pane = Pane::new(i as u64 + 1, machine, agent, 80, 24);+ pane.phase = Phase::Live;+ app.panes.insert(i as u64 + 1, pane);+ }+ app+ }++ fn window(app: &mut App, panes: &[u64]) {+ let mut tab = Tab::with_wid("before", 1);+ let mut root = Node::new(panes[0], 80, 23);+ for p in &panes[1..] { root.split(panes[0], *p, Dir::Horizontal); }+ tab.root = Some(root);+ tab.order = panes.to_vec();+ tab.focus = panes.last().copied();+ app.tabs = vec![tab];+ app.active = 0;+ }++ #[test]+ fn a_window_is_asked_of_the_machine_most_of_its_repo_harnesses_are_on() {+ let mut app = app();+ window(&mut app, &[1, 2, 3, 4, 5]);+ let first = ask(&app, 0).unwrap();+ // This machine's agents in pane order (the daemon picks among them); not the other machine's.+ assert_eq!((first.machine.as_str(), first.agents.clone()), ("m", vec!["a1".to_string(), "a2".into(), "a3".into(), "a4".into()]));+ // A title changing is another question.+ app.fleet.merge_roster("b", &[json!({"id": "b1", "name": "Grid relay respawn prod", "engine": "codex", "project": {"name": "autonomous-grid-cli", "branch": "main"}})]);+ app.fleet.agents.get_mut(&("m".to_string(), "a2".to_string())).unwrap().name = "Ship the release notes".into();+ assert_ne!(ask(&app, 0).unwrap().key, first.key);+ // The other machine's one repo harness against this one's none: that machine is asked.+ window(&mut app, &[3, 4, 5]);+ assert_eq!(ask(&app, 0).unwrap().machine, "b");+ // No harness in a repo (a folder without git, a shell): nothing to ask.+ window(&mut app, &[3, 4]);+ assert_eq!(ask(&app, 0), None);+ }++ #[tokio::test]+ async fn the_daemons_name_names_the_window_while_auto_rename_is_on() {+ let mut app = app();+ window(&mut app, &[1, 2, 3]);+ let key = ask(&app, 0).unwrap().key;+ app.window_name_answer("m", key.clone(), Some(json!({"name": "Harness TUI LMStudio"})));+ // Off (the default): as before.+ app.sync_titles();+ assert_ne!(app.tabs[0].name, "Harness TUI LMStudio");+ crate::commands::execute(&mut app, "set -g @hn-auto-rename on");+ assert_eq!(app.tabs[0].name, "Harness TUI LMStudio", "on: at once");+ // A name you set wins; given back, the window is the daemon's again.+ app.rename_tab_at(0, "release");+ app.sync_titles();+ assert_eq!(app.tabs[0].name, "release");+ app.rename_tab_at(0, "");+ assert_eq!(app.tabs[0].name, "Harness TUI LMStudio");+ crate::commands::execute(&mut app, "set -g @hn-auto-rename off");+ assert_ne!(app.tabs[0].name, "Harness TUI LMStudio", "off: as before");+ // automatic-rename off keeps the name a window found: auto rename's is not one to keep.+ crate::commands::execute(&mut app, "set -g automatic-rename off");+ crate::commands::execute(&mut app, "set -g @hn-auto-rename on");+ assert_eq!(app.tabs[0].name, "Harness TUI LMStudio");+ crate::commands::execute(&mut app, "set -g @hn-auto-rename off");+ assert_eq!(app.tabs[0].name, "TUI layout spacing consistency", "its first harness's name, as before");+ }++ /// `@hn-window-name` / `@hn-window-active` set by hand derive the tab's format again — never over+ /// one the user wrote.+ #[tokio::test]+ async fn the_tab_options_set_by_hand_keep_a_format_the_user_wrote() {+ let mut app = app();+ window(&mut app, &[1, 2]);+ crate::commands::execute(&mut app, "set -g window-status-format '#I #W'");+ crate::commands::execute(&mut app, "set -g @hn-window-active star");+ crate::commands::execute(&mut app, "set -g @hn-window-name tmux");+ assert_eq!(app.options.get("window-status-format", "", None).as_deref(), Some("#I #W"));+ crate::commands::execute(&mut app, "set -gu window-status-format");+ crate::commands::execute(&mut app, "set -g @hn-window-name pane");+ assert!(app.options.get("window-status-format", "", None).is_some_and(|f| crate::options::derived_window_status(&f)));+ }++ #[tokio::test]+ async fn pending_none_and_errors_keep_the_name_the_window_has() {+ let mut app = app();+ crate::commands::execute(&mut app, "set -g @hn-auto-rename on");+ window(&mut app, &[1, 2]);+ app.tabs[0].name = "kept".into();+ let key = ask(&app, 0).unwrap().key;+ for answer in [Some(json!({"name": null, "pending": true})), Some(json!({"name": null})), Some(json!({"error": "UNSUPPORTED"})), None] {+ app.window_name_answer("m", key.clone(), answer.clone());+ assert!(app.auto_name(0).is_none(), "{answer:?}");+ assert!(!named(&app, 0), "{answer:?}");+ }+ // No link to the machine here: nothing is asked, nothing breaks.+ window(&mut app, &[5]);+ assert_eq!(app.auto_name(0), None);+ }++ /// The status bar shows the daemon's name, whole — also where it shows the selected pane's title+ /// (`@hn-window-name pane`, the default); without one, as before.+ #[tokio::test]+ async fn the_status_bar_shows_the_name_whole_in_either_tab_name_mode() {+ let mut app = app();+ window(&mut app, &[1, 2]);+ let key = ask(&app, 0).unwrap().key;+ app.window_name_answer("m", key, Some(json!({"name": "Harness Deploy Release"})));+ let tab = |app: &App| crate::format::expand(app, &app.options.get("window-status-format", "", None).unwrap_or_default(), 0, app.tabs[0].focus, false);+ for mode in ["pane", "tmux"] {+ crate::commands::execute(&mut app, &format!("set -g @hn-window-name {mode}"));+ crate::commands::execute(&mut app, "set -g @hn-auto-rename on");+ assert!(tab(&app).contains("Harness Deploy Release"), "{mode}: {}", tab(&app));+ crate::commands::execute(&mut app, "set -g @hn-auto-rename off");+ assert!(!tab(&app).contains("Harness Deploy Release"), "{mode}, off: {}", tab(&app));+ }+ crate::commands::execute(&mut app, "set -g @hn-window-name pane");+ assert!(tab(&app).contains("Lm studio respawn on quit"), "the selected pane's title: {}", tab(&app));+ }++ /// A client of a server an older build started takes that build's status bar formats; it derives+ /// them again, or auto rename's name never shows. (The format is the one the user's own server held,+ /// read from it on 2026-10-07: the old `pane` one, a closing brace short.)+ #[tokio::test]+ async fn an_older_servers_status_bar_formats_are_derived_again_but_never_a_written_one() {+ let mut app = app();+ window(&mut app, &[1, 2]);+ let key = ask(&app, 0).unwrap().key;+ app.window_name_answer("m", key, Some(json!({"name": "Harness TUI LMStudio"})));+ let g = crate::options::SetFlags { global: true, ..Default::default() };+ let old = "#I:#{pane_title}#{?window_active,*,#{?window_last_flag,-,}}#{s/[*-]//:window_flags}#{?#{==:#{window_agent_state},idle},,#{?window_agent_icon, #{window_agent_icon},}";+ for (name, value) in [("@hn-window-name", "pane"), ("@hn-auto-rename", "on"), ("window-status-format", old), ("window-status-current-format", old)] {+ let _ = app.options.set(name, Some(value), &g, "", 0);+ }+ app.sync_titles();+ let tab = |app: &App| crate::format::expand(app, &app.options.get("window-status-format", "", None).unwrap_or_default(), 0, app.tabs[0].focus, false);+ assert!(!tab(&app).contains("Harness TUI LMStudio"), "the old format shows the pane's title: {}", tab(&app));+ assert!(app.rederive_window_status());+ assert!(tab(&app).contains("Harness TUI LMStudio"), "{}", tab(&app));+ assert!(!app.rederive_window_status(), "derived already: nothing to do");+ let _ = app.options.set("window-status-format", Some("#I #W"), &g, "", 0);+ assert!(!app.rederive_window_status());+ assert_eq!(app.options.get("window-status-format", "", None).as_deref(), Some("#I #W"));+ }+}diff --git a/tui/src/commands.rs b/tui/src/commands.rsindex 2ff8eb04a..e99ac9c1b 100644--- a/tui/src/commands.rs+++ b/tui/src/commands.rs@@ -1266,6 +1266,10 @@ fn after_set(app: &mut App, name: &str, now: Option<String>, global: bool, tab:// (The bar down a side and the pane frames change the panes' room.)if matches!(name.as_str(), "@hn-status-bar" | "@hn-border" | "@hn-focus") { app.redraw_all = true; app.fit_panes(); }if name == "@hn-dim" { app.redraw_all = true }+ // (Set by hand too: the tab's format and every window's name follow, as from Appearance — the+ // format only while it is hn's own, never one the user wrote: `set -g window-status-format '#I #W'`.)+ if matches!(name.as_str(), "@hn-window-name" | "@hn-window-active") { app.rederive_window_status(); app.sync_titles(); app.redraw_all = true }+ if name == "@hn-auto-rename" { app.sync_titles(); app.redraw_all = true }// alerts_reset_all: every window's silence timer starts again.if name == "monitor-silence" { for t in app.tabs.iter_mut() { t.last_output = std::time::Instant::now() } }if name.starts_with('@') && now.is_none() { app.opts.user.remove(&name); return }diff --git a/tui/src/config.rs b/tui/src/config.rsindex b57eea650..7ea9c52b0 100644--- a/tui/src/config.rs+++ b/tui/src/config.rs@@ -148,6 +148,8 @@ pub struct Look {/// How a tab's name is shown in the status bar: `tmux` (default: the window's short name) |/// `pane` (the window's full name).pub window_name: Option<String>,+ /// `on`: a window with a repo is named for it and its work, in the background (`off` unless chosen).+ pub auto_rename: Option<String>,}pub struct Config {@@ -215,6 +217,7 @@ impl Look {if let Some(b) = &self.border_style { out.push(("@hn-border".into(), b.clone())) }if let Some(w) = &self.status_bar_width { out.push(("@hn-status-bar-width".into(), w.clone())) }if let Some(d) = &self.dim { out.push(("@hn-dim".into(), d.clone())) }+ if let Some(a) = &self.auto_rename { out.push(("@hn-auto-rename".into(), a.clone())) }// ── status bar tabs ──// Two options shape the window list in the status bar: how the current tab is marked and// how a tab's name is shown. `@hn-window-active`/`@hn-window-name` carry the choice for the@@ -222,7 +225,7 @@ impl Look {if let Some(a) = &self.window_active { out.push(("@hn-window-active".into(), a.clone())) }if let Some(n) = &self.window_name { out.push(("@hn-window-name".into(), n.clone())) }// The window-status-* overrides these two options need (empty for the tmux + star defaults).- let name = self.window_name.as_deref().unwrap_or("tmux");+ let name = self.window_name.as_deref().unwrap_or(crate::options::DEFAULT_TAB_NAME);let active = self.window_active.as_deref().unwrap_or("star");for (o, v) in crate::options::window_status_overrides(name, active) { out.push((o, v)) }out@@ -396,6 +399,7 @@ fn look_of(look: &toml::Table, problems: &mut Vec<String>) -> Look {field(look, "dim", &mut l.dim);field(look, "window_active", &mut l.window_active);field(look, "window_name", &mut l.window_name);+ field(look, "auto_rename", &mut l.auto_rename);// (An older file's `tabs` is left alone: the tabs over the panes are gone, the bar lists the windows.)l}@@ -434,6 +438,7 @@ fn format_look(look: &Look) -> String {push(&look.dim, "dim", &mut s);push(&look.window_active, "window_active", &mut s);push(&look.window_name, "window_name", &mut s);+ push(&look.auto_rename, "auto_rename", &mut s);s}@@ -586,21 +591,24 @@ mod tests {#[test]fn window_status_options_emit_format_and_style_overrides() {let get = |a: &[(String, String)], n: &str| a.iter().find(|(k, _)| k == n).map(|(_, v)| v.clone());- // The defaults (tmux + star) put just the two @hn markers; no format/style overrides, so- // the tmux defaults draw the bar.- let star = Look { window_active: Some("star".into()), window_name: Some("tmux".into()), ..Default::default() }.assignments();- assert_eq!(get(&star, "@hn-window-active").as_deref(), Some("star"));- assert_eq!(get(&star, "@hn-window-name").as_deref(), Some("tmux"));- assert!(get(&star, "window-status-format").is_none(), "default keeps tmux's format");- assert!(get(&star, "window-status-current-format").is_none());- assert!(get(&star, "window-status-current-style").is_none());- // `pane` names the window with its active pane's title; `filled` drops the `*` and the tab- // takes the status line's own colours swapped (a solid block, as the preview draws it).+ // The defaults (pane + star) put just the two @hn markers; no format/style overrides, so+ // the defaults draw the bar: the selected pane's title, or auto rename's name.+ for star in [Look { window_active: Some("star".into()), window_name: Some("pane".into()), ..Default::default() }.assignments(), Look::default().assignments()] {+ assert!(get(&star, "window-status-format").is_none(), "the default format");+ assert!(get(&star, "window-status-current-format").is_none());+ assert!(get(&star, "window-status-current-style").is_none());+ }+ // `tmux` (from an older tui.toml) shows the window's name instead.+ let tmux = Look { window_active: Some("star".into()), window_name: Some("tmux".into()), ..Default::default() }.assignments();+ assert_eq!(get(&tmux, "@hn-window-name").as_deref(), Some("tmux"));+ let normal = get(&tmux, "window-status-format").unwrap();+ assert!(normal.contains("#{window_short_name}") && !normal.contains("#{pane_title}"), "{normal}");+ // `filled` drops the `*` and the tab takes the status line's own colours swapped (a solid+ // block, as the preview draws it).let filled = Look { window_active: Some("filled".into()), window_name: Some("pane".into()), ..Default::default() }.assignments();- let normal = get(&filled, "window-status-format").unwrap();+ assert!(get(&filled, "window-status-format").is_none(), "the other tabs: the default");let current = get(&filled, "window-status-current-format").unwrap();- assert!(normal.contains("#{pane_title}"), "pane uses the active pane's title: {normal}");- assert!(current.contains("#{pane_title}"));+ assert!(current.contains("#{pane_title}"), "pane uses the active pane's title: {current}");assert!(!current.contains("#{window_active,*"), "filled leaves no `*`: {current}");let style = get(&filled, "window-status-current-style").unwrap();assert!(style.contains("bold"), "{style}");diff --git a/tui/src/format.rs b/tui/src/format.rsindex 9ff7f6909..180adfe2c 100644--- a/tui/src/format.rs+++ b/tui/src/format.rs@@ -1279,6 +1279,8 @@ fn table(app: &App, name: &str, window: usize, pane_id: Option<u64>) -> Option<V// The name in whole words within 20 columns, … after what is cut: a harness is named for its// task, and the window list has room for a few words of each."window_short_name" => tab.map(|t| short_name(&t.name, 20)).unwrap_or_default(),+ // Named by auto rename now (autoname.rs): its repo and its work.+ "window_auto_named" => (tab.is_some() && crate::autoname::named(app, window)).then_some("1").unwrap_or("0").into(),"window_flags" => flags(app, window).replacen('#', "##", 1),"window_raw_flags" => flags(app, window),"window_active" => (window == app.active).then_some("1").unwrap_or("0").into(),diff --git a/tui/src/main.rs b/tui/src/main.rsindex df58d44a7..c44ac11c9 100644--- a/tui/src/main.rs+++ b/tui/src/main.rs@@ -71,6 +71,7 @@ mod bar_more;// ── models: the Models view (step 6) ──mod models;mod runtime_model;+mod autoname;use std::io::{self, BufWriter, Write};use std::time::{Duration, Instant};diff --git a/tui/src/modal.rs b/tui/src/modal.rsindex fca388e68..4854d9a4e 100644--- a/tui/src/modal.rs+++ b/tui/src/modal.rs@@ -704,7 +704,9 @@ pub fn theme_sections(app: &App) -> Vec<Row> {sec("section:boxes", "Borders", "every pane its own box", if border_style_of(app) == "box" { "on" } else { "off" }),// ── status bar tabs ──sec("section:tab", "Tab", "how the current tab is marked", tab_active_of(app)),- sec("section:tabname", "Tab name", "how a tab's name is shown", tab_name_of(app)),+ // (No "Tab name": a tab shows the selected pane's title, or auto rename's name. `@hn-window-name+ // tmux` in a tmux.conf or tui.toml still shows the window's name instead.)+ sec("section:autorename", "Auto rename", "a window named for its repo and its work", if app.options.auto_rename() { "on" } else { "off" }),// (Keys are Keybinds', a panel of their own in Commands.)]}@@ -720,9 +722,6 @@ fn border_style_of(app: &App) -> &'static str { app.options.border_style() }/// How the current tab is marked: `star` (default) | `filled` (`@hn-window-active`).fn tab_active_of(app: &App) -> &'static str { if app.options.get("@hn-window-active", "", None).as_deref() == Some("filled") { "filled" } else { "star" } }-/// A tab's name source: `tmux` (default) | `pane` (`@hn-window-name`).-fn tab_name_of(app: &App) -> &'static str { if app.options.get("@hn-window-name", "", None).as_deref() == Some("pane") { "pane" } else { "tmux" } }-/// The look/theme picker, level two: the options of one section. Enter on one applies it (and the/// ▼ moves to it); Left/Esc returns to the section list.pub fn theme_options(app: &App, section: &str) -> Vec<Row> {@@ -767,9 +766,10 @@ pub fn theme_options(app: &App, section: &str) -> Vec<Row> {"tab" => { let cur = tab_active_of(app);[("star", "star", "the current tab is marked *"), ("filled", "filled", "the current tab is filled (inverted)")].iter().map(|(v, label, hint)| opt(format!("window_active:{v}"), label, cur == *v, hint)).collect() }- "tabname" => { let cur = tab_name_of(app);- [("tmux", "tmux", "the window's short name"), ("pane", "pane", "the window's full name")]- .iter().map(|(v, label, hint)| opt(format!("window_name:{v}"), label, cur == *v, hint)).collect() }+ "autorename" => { let cur = if o.auto_rename() { "on" } else { "off" };+ [("on", "a window with a repo is named for it and its work, by a small model, in the background (Harness TUI LMStudio)"),+ ("off", "windows keep the names they have")]+ .iter().map(|(v, hint)| opt(format!("auto_rename:{v}"), v, cur == *v, hint)).collect() }_ => vec![],}}@@ -859,7 +859,7 @@ mod theme_row_tests {let ids: Vec<&str> = rows.iter().map(|r| r.id.as_str()).collect();assert_eq!(ids, vec!["section:theme", "section:status", "section:focus",// ── status bar ──- "section:bar", "section:boxes", "section:tab", "section:tabname"]);+ "section:bar", "section:boxes", "section:tab", "section:autorename"]);// Each section shows its current value and opens onto a non-empty option list.assert!(rows.iter().all(|r| !r.right.is_empty()), "each section shows a value");for r in &rows {@@ -905,14 +905,11 @@ mod theme_row_tests {}#[test]- fn the_tab_and_tab_name_sections_list_their_choices() {+ fn the_tab_section_lists_its_choices_and_there_is_no_tab_name_section() {let a0 = app();let tab_rows = theme_options(&a0, "tab");let tab_ids: Vec<&str> = tab_rows.iter().map(|r| r.id.as_str()).collect();assert_eq!(tab_ids, vec!["window_active:star", "window_active:filled"]);- let name_rows = theme_options(&a0, "tabname");- let name_ids: Vec<&str> = name_rows.iter().map(|r| r.id.as_str()).collect();- assert_eq!(name_ids, vec!["window_name:tmux", "window_name:pane"]);// The mark follows the option in use.let mut a1 = app();let global = crate::options::SetFlags { global: true, ..Default::default() };@@ -920,10 +917,23 @@ mod theme_row_tests {let filled = theme_options(&a1, "tab");let idx = filled.iter().position(|r| r.id == "window_active:filled").unwrap();assert!(filled[idx].lead.iter().any(|s| s.content.as_ref() == "✓ "));- let _ = a1.options.set("@hn-window-name", Some("pane"), &global, "", 0);- let pane = theme_options(&a1, "tabname");- let idx = pane.iter().position(|r| r.id == "window_name:pane").unwrap();- assert!(pane[idx].lead.iter().any(|s| s.content.as_ref() == "✓ "));+ // No Tab name: a tab shows the selected pane's title, or auto rename's name.+ assert!(theme_options(&a0, "tabname").is_empty());+ assert!(!theme_sections(&a0).iter().any(|r| r.id == "section:tabname"));+ }++ /// Auto rename is a switch of its own in Appearance, off until turned on, and saved to tui.toml.+ #[test]+ fn auto_rename_is_a_switch_off_until_turned_on() {+ let mut app = app();+ let section = |app: &App| theme_sections(app).into_iter().find(|r| r.id == "section:autorename").map(|r| r.right).unwrap();+ assert_eq!(section(&app), "off");+ assert_eq!(theme_options(&app, "autorename").iter().map(|r| r.id.as_str()).collect::<Vec<_>>(), vec!["auto_rename:on", "auto_rename:off"]);+ assert_eq!(app.set_look("auto_rename", "on"), "auto rename: on");+ assert!(app.options.auto_rename());+ assert_eq!(section(&app), "on");+ let look = crate::config::Look { auto_rename: Some("on".into()), ..Default::default() };+ assert!(look.assignments().contains(&("@hn-auto-rename".into(), "on".into())), "tui.toml's auto_rename turns it on at start");}// ── keys ──diff --git a/tui/src/options/mod.rs b/tui/src/options/mod.rsindex 62775e850..1a558539d 100644--- a/tui/src/options/mod.rs+++ b/tui/src/options/mod.rs@@ -111,7 +111,7 @@ pub fn defaults() -> &'static BTreeMap<String, String> {// Keep tmux's familiar current/previous markers beside the name, then any other// flags, then the harness state. The selected tab needs no filled badge.for name in ["window-status-format", "window-status-current-format"] {- m.insert(name.into(), status_window_format("tmux", true));+ m.insert(name.into(), status_window_format(DEFAULT_TAB_NAME, true));}// Unread activity and bells already carry #/! markers. Keep a continuous status// background and emphasize text instead of introducing inverted tab badges.@@ -142,23 +142,36 @@ pub fn defaults() -> &'static BTreeMap<String, String> {})}+/// What a tab shows unless `@hn-window-name` says otherwise: the selected pane's title (`pane`), or+/// auto rename's name for the window. (No longer a choice in Appearance; `tmux` from a tmux.conf or+/// an older tui.toml still shows the window's name.)+pub const DEFAULT_TAB_NAME: &str = "pane";+/// The status bar's per-window text. [name] is the tab name source (`tmux` = the window's short/// name, `pane` = the window's full name); [star] is whether the window you are on is marked `*`/// (`false` for a filled tab, which needs no `*` beside its name).pub fn status_window_format(name: &str, star: bool) -> String {// `tmux` keeps hn's window name, `pane` the active pane's own title (a harness's task, not the- // window's auto-renamed name) — the two can differ, which is the point of the option.- let name_part = if name == "pane" { "#{pane_title}" } else { "#{window_short_name}" };+ // window's auto-renamed name) — the two can differ, which is the point of the option. A window+ // auto rename has named (its repo and its work) shows that name either way, whole: it is four+ // words at most already.+ let name_part = if name == "pane" { "#{?window_auto_named,#{window_name},#{pane_title}}" } else { "#{?window_auto_named,#{window_name},#{window_short_name}}" };let mark = if star { "#{?window_active,*,#{?window_last_flag,-,}}" } else { "#{?window_last_flag,-,}" };// (Two closing braces: the idle test's and the icon's. With one, the icon never showed.)format!("#I:{name_part}{mark}#{{s/[*-]//:window_flags}}#{{?#{{==:#{{window_agent_state}},idle}},,#{{?window_agent_icon, #{{window_agent_icon}},}}}}")}+/// Whether [format] is one [status_window_format] derived, by this build or an older one (whose+/// name part or closing braces may differ), as opposed to one somebody wrote in tmux.conf.+pub fn derived_window_status(format: &str) -> bool {+ format.starts_with("#I:") && format.contains("#{s/[*-]//:window_flags}#{?#{==:#{window_agent_state},idle},,#{?window_agent_icon, #{window_agent_icon},}")+}+/// The status bar's `window-status-*` overrides for a tab name source [name] (`tmux`|`pane`) and a-/// current-tab [active] (`star`|`filled`). Empty when they match the defaults (tmux + star), so a-/// caller can leave the tmux defaults in place. Shared by boot (from `[look]`) and a live pick.+/// current-tab [active] (`star`|`filled`). Empty when they match the defaults ([DEFAULT_TAB_NAME] ++/// star), so a caller can leave the defaults in place. Shared by boot (from `[look]`) and a live pick.pub fn window_status_overrides(name: &str, active: &str) -> Vec<(String, String)> {- let default_win = status_window_format("tmux", true);+ let default_win = status_window_format(DEFAULT_TAB_NAME, true);let mut out = Vec::new();let normal = status_window_format(name, true);let current = status_window_format(name, active == "star");@@ -322,6 +335,10 @@ impl Store {/// blurred surfaces alike. Off unless chosen.pub fn dim_others(&self) -> bool { self.get("@hn-dim", "", None).as_deref() == Some("on") }+ /// `@hn-auto-rename on` (tui.toml `auto_rename`): a window with a repo is named for it and its+ /// work (`autoname.rs`). Off unless chosen.+ pub fn auto_rename(&self) -> bool { self.get("@hn-auto-rename", "", None).as_deref() == Some("on") }+/// `@hn-border` as chosen — `box` unless it says `line`. (`@hn-look classic` is not a choice/// of lines: hn wrote it into every `[look]` it saved, a theme picked or a status bar moved.)pub fn border_style(&self) -> &'static str {diff --git a/tui/src/server.rs b/tui/src/server.rsindex ca058895b..f7506a220 100644--- a/tui/src/server.rs+++ b/tui/src/server.rs@@ -265,6 +265,9 @@ pub fn join(app: &mut App) {app.server_synced = Some(mine);} else {take(app);+ // A server started by an older build keeps the status bar's formats as that build derived+ // them; this one derives its own (tmux.conf's own formats are left alone).+ if app.rederive_window_status() { app.server_dirty = true; publish(app) }}}diff --git a/tui/src/settings.rs b/tui/src/settings.rsindex f581cec10..fcf131bd6 100644--- a/tui/src/settings.rs+++ b/tui/src/settings.rs@@ -737,7 +737,7 @@ impl Look {boxes: o.border_style() == "box",dim: o.dim_others(),window_active: get("@hn-window-active", "star"),- window_name: get("@hn-window-name", "tmux"),+ window_name: get("@hn-window-name", crate::options::DEFAULT_TAB_NAME),}}