Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(codex): the session-name relay fallback and thread/account readers (S6 PR 4)

Claude Code3df787f7e5a1
diff --git a/src/core/codex-session-name.test.ts b/src/core/codex-session-name.test.ts
index 804aac4c6..4e097b34c 100644
--- a/src/core/codex-session-name.test.ts
+++ b/src/core/codex-session-name.test.ts
@@ -10,10 +10,17 @@ import os from 'node:os'
import http from 'node:http'
import path from 'node:path'
import { WebSocketServer, type WebSocket } from 'ws'
+import { createHash } from 'node:crypto'
import {
codexThreadExistsAt,
codexUnixWebSocketUrl,
+ forgetCodexSessionNames,
+ readCodexAccountAt,
+ readCodexSessionName,
readCodexSessionNameAt,
+ readCodexThreadAt,
+ relayedCodexSessionName,
+ rememberCodexSessionName,
waitForCodexAppServer
} from './codex-session-name'
@@ -160,3 +167,131 @@ describe('codexUnixWebSocketUrl', () => {
expect(() => codexUnixWebSocketUrl('/tmp/a?b/app.sock')).toThrow()
})
})
+
+describe('relayedCodexSessionName (the on-disk relay fallback)', () => {
+ it('reads, trims and caps the name the relay stored under the socket-scoped path', () => {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-relay-name-'))
+ const socketPath = '/home/x/.codex/app-server-control/app-server-control.sock'
+ const scope = createHash('sha256').update(socketPath).digest('hex').slice(0, 16)
+ const nameDir = path.join(home, '.nodeterm', 'codex-thread-names', scope)
+ fs.mkdirSync(nameDir, { recursive: true })
+ fs.writeFileSync(path.join(nameDir, 'thread-1'), ` ${'z'.repeat(600)} `)
+ const value = relayedCodexSessionName(socketPath, 'thread-1', home)
+ expect(value).toBe('z'.repeat(500))
+ expect(relayedCodexSessionName(socketPath, 'thread-missing', home)).toBeNull()
+ expect(relayedCodexSessionName(socketPath, '../escape', home)).toBeNull()
+ fs.rmSync(home, { recursive: true, force: true })
+ })
+})
+
+describe('readCodexSessionName relay fallback wiring', () => {
+ it('falls back to the relayed name when the app-server reports none, and a real name wins', async () => {
+ const savedHome = process.env.HOME
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-name-wire-'))
+ process.env.HOME = home
+ forgetCodexSessionNames()
+ try {
+ const scope = createHash('sha256').update(sock).digest('hex').slice(0, 16)
+ const nameDir = path.join(home, '.nodeterm', 'codex-thread-names', scope)
+ fs.mkdirSync(nameDir, { recursive: true })
+ fs.writeFileSync(path.join(nameDir, 'thread-nameless'), 'Relayed title')
+ // The server has this thread but with a null name → the relay copy fills in.
+ expect(await readCodexSessionName('thread-nameless', sock)).toBe('Relayed title')
+ forgetCodexSessionNames()
+ // A real server name always wins over the relay copy.
+ fs.writeFileSync(path.join(nameDir, 'thread-known'), 'Stale relayed title')
+ expect(await readCodexSessionName('thread-known', sock)).toBe('Named by codex')
+ } finally {
+ forgetCodexSessionNames()
+ if (savedHome === undefined) delete process.env.HOME
+ else process.env.HOME = savedHome
+ fs.rmSync(home, { recursive: true, force: true })
+ }
+ })
+})
+
+describe('rememberCodexSessionName', () => {
+ it('seeds the cache so the next read serves it without a socket, and rejects a bad id', async () => {
+ forgetCodexSessionNames()
+ try {
+ // A dead socket would answer null; the seeded value is served instead.
+ const dead = path.join(dir, 'dead-remember.sock')
+ rememberCodexSessionName('thread-seeded', 'Seeded title', dead)
+ expect(await readCodexSessionName('thread-seeded', dead)).toBe('Seeded title')
+ rememberCodexSessionName('../bad', 'ignored', dead)
+ expect(relayedCodexSessionName(dead, '../bad')).toBeNull()
+ } finally {
+ forgetCodexSessionNames()
+ }
+ })
+})
+
+describe('readCodexThreadAt / readCodexAccountAt', () => {
+ let d = ''
+ let s = ''
+ let srv: http.Server
+ let w: WebSocketServer
+
+ beforeAll(async () => {
+ d = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-cx2-'))
+ s = path.join(d, 'as.sock')
+ srv = http.createServer()
+ w = new WebSocketServer({ server: srv })
+ w.on('connection', (ws) => {
+ ws.on('message', (raw) => {
+ const msg = JSON.parse(raw.toString()) as Record<string, any>
+ if (msg.method === 'initialize') return ws.send(JSON.stringify({ id: msg.id, result: {} }))
+ if (msg.method === 'thread/read') {
+ const id = msg.params?.threadId as string
+ if (id === 'thread-a')
+ return ws.send(
+ JSON.stringify({
+ id: msg.id,
+ result: { thread: { id, name: 'A', path: '/abs/rollout-thread-a.jsonl' } }
+ })
+ )
+ if (id === 'thread-b')
+ return ws.send(
+ JSON.stringify({ id: msg.id, result: { thread: { id, name: null, path: 'relative' } } })
+ )
+ if (id === 'thread-forked')
+ // The server answers with a DIFFERENT id — must be refused.
+ return ws.send(
+ JSON.stringify({ id: msg.id, result: { thread: { id: 'other', path: '/abs/x.jsonl' } } })
+ )
+ return ws.send(JSON.stringify({ id: msg.id, error: { message: 'no rollout found' } }))
+ }
+ if (msg.method === 'account/read')
+ return ws.send(
+ JSON.stringify({ id: msg.id, result: { account: { email: ' [email protected] ' } } })
+ )
+ })
+ })
+ await new Promise<void>((resolve) => srv.listen(s, resolve))
+ })
+
+ afterAll(async () => {
+ await new Promise<void>((resolve) => w.close(() => resolve()))
+ await new Promise<void>((resolve) => srv.close(() => resolve()))
+ fs.rmSync(d, { recursive: true, force: true })
+ })
+
+ it('reads id, name and absolute path; drops a non-absolute path to null', async () => {
+ expect(await readCodexThreadAt(s, 'thread-a')).toEqual({
+ id: 'thread-a',
+ name: 'A',
+ path: '/abs/rollout-thread-a.jsonl'
+ })
+ expect(await readCodexThreadAt(s, 'thread-b')).toEqual({ id: 'thread-b', name: null, path: null })
+ })
+
+ it('refuses a response whose thread id does not match the one asked for', async () => {
+ expect(await readCodexThreadAt(s, 'thread-forked')).toBeNull()
+ expect(await readCodexThreadAt(s, 'thread-unknown')).toBeNull()
+ expect(await readCodexThreadAt(s, '../../etc/passwd')).toBeNull()
+ })
+
+ it('reads and trims the account email', async () => {
+ expect(await readCodexAccountAt(s)).toEqual({ email: '[email protected]' })
+ })
+})
diff --git a/src/core/codex-session-name.ts b/src/core/codex-session-name.ts
index de65584f8..4503c7a01 100644
--- a/src/core/codex-session-name.ts
+++ b/src/core/codex-session-name.ts
@@ -13,6 +13,8 @@
* cannot read means the node keeps its own title, and a thread we cannot start means the launcher
* falls back to plain codex.
*/
+import { createHash } from 'crypto'
+import { readFileSync } from 'fs'
import { homedir } from 'os'
import path from 'path'
import { WebSocket } from 'ws'
@@ -479,9 +481,193 @@ export function startCodexThread(cwd: string): Promise<string> {
return startCodexThreadAt(defaultCodexAppServerSocket(), cwd)
}
+/**
+ * The relay's on-disk fallback for a session name the shared app-server no longer reports.
+ *
+ * A native in-TUI `/resume` can fork a cloud conversation into a local app-server thread whose
+ * `Thread.name` is `null`; the persistent relay observed the source id at bind time and copied its
+ * `session_index` title to `~/.nodeterm/codex-thread-names/<sha256(socket)[..16]>/<threadId>` (the
+ * exact path the relay daemon's `nameFile` writes — one definition, kept in step). Read as DATA and
+ * capped; a later real `Thread.name` from the server always wins. Fails to `null`.
+ */
+export function relayedCodexSessionName(
+ socketPath: string,
+ threadId: string,
+ home = homedir()
+): string | null {
+ if (!isSafeThreadId(threadId)) return null
+ try {
+ const scope = createHash('sha256').update(socketPath).digest('hex').slice(0, 16)
+ const value = readFileSync(
+ path.join(home, '.nodeterm', 'codex-thread-names', scope, threadId),
+ 'utf8'
+ ).trim()
+ return value ? value.slice(0, 500) : null
+ } catch {
+ return null
+ }
+}
+
+/** Seed the in-process name cache from a name observed elsewhere (e.g. a relay bind), so the next
+ * sweep serves it without a socket round-trip. A blank name caches an explicit `null`. */
+export function rememberCodexSessionName(
+ threadId: string,
+ name: unknown,
+ socketPath = defaultCodexAppServerSocket()
+): void {
+ if (!isSafeThreadId(threadId)) return
+ const value = typeof name === 'string' && name.trim() ? name.trim() : null
+ names.set(`${socketPath}\0${threadId}`, { name: value, at: Date.now() })
+}
+
+/** Read a thread's full identity from an app-server socket: its id (must come back UNCHANGED), name,
+ * and absolute rollout path. Used by the cross-account switch to locate a foreign rollout. Fails to
+ * `null` rather than throwing into a poll loop. */
+export function readCodexThreadAt(
+ socketPath: string,
+ threadId: string,
+ timeoutMs = REQUEST_TIMEOUT_MS
+): Promise<{ id: string; name: string | null; path: string | null } | null> {
+ if (!isSafeThreadId(threadId)) return Promise.resolve(null)
+ return new Promise((resolve) => {
+ let settled = false
+ let ws: WebSocket
+ const finish = (value: { id: string; name: string | null; path: string | null } | null): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ try {
+ ws.close()
+ } catch {
+ /* the connection may never have opened */
+ }
+ resolve(value)
+ }
+ const timer = setTimeout(() => finish(null), timeoutMs)
+ timer.unref?.()
+ try {
+ ws = connectCodexAppServer(socketPath)
+ } catch {
+ clearTimeout(timer)
+ resolve(null)
+ return
+ }
+ ws.once('open', () => {
+ ws.send(
+ JSON.stringify({
+ id: 1,
+ method: 'initialize',
+ params: { clientInfo: { name: 'nodeterm', version: '1' } }
+ })
+ )
+ })
+ ws.on('message', (raw) => {
+ let message: Record<string, any>
+ try {
+ message = JSON.parse(raw.toString())
+ } catch {
+ return
+ }
+ if (message.id === 1) {
+ if (message.error) return finish(null)
+ ws.send(JSON.stringify({ method: 'initialized' }))
+ ws.send(
+ JSON.stringify({ id: 2, method: 'thread/read', params: { threadId, includeTurns: false } })
+ )
+ } else if (message.id === 2) {
+ const thread = message.result?.thread
+ if (message.error || typeof thread?.id !== 'string' || thread.id !== threadId) {
+ finish(null)
+ return
+ }
+ finish({
+ id: thread.id,
+ name: typeof thread.name === 'string' && thread.name.trim() ? thread.name.trim() : null,
+ path: typeof thread.path === 'string' && path.isAbsolute(thread.path) ? thread.path : null
+ })
+ }
+ })
+ ws.once('error', () => finish(null))
+ ws.once('close', () => finish(null))
+ })
+}
+
+/** Read the logged-in account's email from an app-server socket (`account/read`). Fails to `null`. */
+export function readCodexAccountAt(
+ socketPath: string,
+ timeoutMs = REQUEST_TIMEOUT_MS
+): Promise<{ email: string | null } | null> {
+ return new Promise((resolve) => {
+ let settled = false
+ let ws: WebSocket
+ const finish = (value: { email: string | null } | null): void => {
+ if (settled) return
+ settled = true
+ clearTimeout(timer)
+ try {
+ ws.close()
+ } catch {
+ /* the connection may never have opened */
+ }
+ resolve(value)
+ }
+ const timer = setTimeout(() => finish(null), timeoutMs)
+ timer.unref?.()
+ try {
+ ws = connectCodexAppServer(socketPath)
+ } catch {
+ clearTimeout(timer)
+ resolve(null)
+ return
+ }
+ ws.once('open', () => {
+ ws.send(
+ JSON.stringify({
+ id: 1,
+ method: 'initialize',
+ params: { clientInfo: { name: 'nodeterm', version: '1' } }
+ })
+ )
+ })
+ ws.on('message', (raw) => {
+ let message: Record<string, any>
+ try {
+ message = JSON.parse(raw.toString())
+ } catch {
+ return
+ }
+ if (message.id === 1) {
+ if (message.error) return finish(null)
+ ws.send(JSON.stringify({ method: 'initialized' }))
+ ws.send(JSON.stringify({ id: 2, method: 'account/read', params: {} }))
+ } else if (message.id === 2) {
+ const account = message.result?.account
+ const email =
+ typeof account?.email === 'string' && account.email.trim()
+ ? account.email.trim()
+ : typeof message.result?.email === 'string' && message.result.email.trim()
+ ? message.result.email.trim()
+ : null
+ finish(message.error ? null : { email })
+ }
+ })
+ ws.once('error', () => finish(null))
+ ws.once('close', () => finish(null))
+ })
+}
+
+/** Drop the memoized/coalesced name state — for tests and for a relay/account-set change. */
+export function forgetCodexSessionNames(): void {
+ names.clear()
+ inflight.clear()
+}
+
/**
* The READ leg for `TITLE_READ_CAPABLE`. Memoized for `CACHE_MS` and coalesced, because the
* session-name sweep asks once a minute PER NODE and every ask is a socket connect.
+ *
+ * When the shared app-server reports no name, fall back to the relay's on-disk copy
+ * (`relayedCodexSessionName`) so a conversation forked in the TUI still shows its title.
*/
export function readCodexSessionName(
threadId: string,
@@ -494,7 +680,8 @@ export function readCodexSessionName(
const running = inflight.get(key)
if (running) return running
const request = readCodexSessionNameAt(socketPath, threadId).then(
- (name) => {
+ (serverName) => {
+ const name = serverName ?? relayedCodexSessionName(socketPath, threadId)
names.set(key, { name, at: Date.now() })
inflight.delete(key)
return name