You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Add optional dynamic conversation titles via a model rename capability #14044
Codex should optionally expose a model-usable tool/capability for dynamically renaming the current conversation as the work evolves.
Problem
Static or one-time titles are often insufficient once a session changes direction. Even with manual rename support, the title can drift out of sync with the actual work unless the user keeps updating it themselves.
Requested behavior
add an optional capability/tool that allows the model to rename the current conversation/thread
expose it as a user-controlled feature, for example "Dynamic Conversation Title"
allow prompting/guidance that encourages the model to keep the title aligned with the current work as the task evolves
keep manual rename available and let the user override the dynamic title at any time
Why this is useful
long sessions often change scope or become more specific over time
dynamic titles would improve resume/search/navigation across many threads
it reduces the need for the user to manually keep titles synchronized with the actual work
Suggested UX / policy direction
off by default or clearly opt-in
model updates title only when the conversation meaningfully changes
avoid noisy micro-renames on every tiny turn
title changes should be visible/auditable in the UI
Success criteria
a session can keep a useful current title without manual renaming every time the scope shifts
the feature is controllable by the user
manual rename and dynamic rename coexist cleanly
title changes improve session navigation rather than creating churn
I’d like to add a concrete CLI/TUI use case for this.
I use long-running Codex CLI sessions where the actual task often becomes clearer only after several turns. A helper can infer a better title from the conversation and persist it to local session metadata, but without a first-class current-thread rename capability it still cannot reliably update the active TUI state. In practice, the workaround is to copy /rename <title> to the clipboard and ask the user to paste it, or wait until the session is exited and resumed before the title is visible everywhere.
An opt-in dynamic title capability would solve this cleanly if it provides:
a current-thread-scoped rename action/tool that the model can invoke only when enabled
immediate TUI refresh, including the statusline and resume/history surfaces
clear user control: off by default, manual rename always wins, and title changes are visible/auditable
rate limiting or semantic-change gating so the model does not rename on every small turn
consistent persistence across the existing title stores, so session_index, SQLite-backed metadata, resume picker, and app/CLI surfaces do not drift
This is closely related to #15444, but the dynamic-title version is useful when the user does not want to keep manually issuing /rename after the session scope evolves. The key requirement from the CLI side is not only persistence, but a supported way for the current TUI session to be notified and refreshed.
I now have a working, zero-model-cost workaround for the CLI/TUI version of this problem.
This does not replace the requested native capability: it changes the terminal window/tab title, not the persisted Codex thread name used by /resume, search, or other surfaces. Still, it may be useful both as an immediate workaround and as implementation evidence for separating a stable task label from live activity state.
UserPromptSubmit: derive a short deterministic task label, persist it per session, and write ● <task>
Stop: reuse the same label and write ○ <task>
SessionStart: restore the label after resume and write the idle state
The solid/hollow dot already communicates the live state, so the title does not repeat Working or Idle in text.
The hook writes an OSC 0 sequence directly to /dev/tty, because hook stdout is captured by Codex. It does not call a model or the network, so it adds no token cost or model latency.
Other behavior:
low-information prompts such as continue, go, or 好的 do not replace the task label
an explicit thread name (/rename) takes priority when it is available in local metadata
child-agent hook input is ignored so a subagent cannot overwrite the parent terminal title
labels are truncated by terminal display width, including double-width CJK characters
state is written atomically under ~/.codex/terminal-title-state/
Otty already honors OSC titles directly. Hook trust should be reviewed and approved on the target machine; persisted trust hashes should not be copied between machines.
Verification
Tested locally with:
Codex CLI 0.146.0-alpha.9.2
Node.js 22.22.0
macOS + Otty
Verified:
working → idle transition
stable title after a short continue prompt
title restoration on SessionStart
explicit-name priority
child-agent isolation
strict Codex config parsing
all merged hooks trusted and enabled
The remaining reason for a native feature is important: this workaround cannot update the persisted thread name or notify every Codex surface. A first-class current-thread rename capability would still be the clean solution for /resume, history/search, IDE, desktop, and web. A smaller native TUI improvement could also expose something like a turn-summary terminal-title item alongside the existing activity/run-state items.
The current package is v0.4.0. It remains an opt-in Codex Desktop plugin workaround rather than a replacement for the native capability requested here.
It deliberately avoids renaming on every turn:
prompt 2 establishes a useful project-aware title;
prompt 4 refines it only when the task is clearer;
prompt 10 refreshes it only after a material change in project, work type, object, or purpose;
color blocks are the default, with semantic icons and project-defined custom markers also supported;
an explicit skill action can normalize older Codex tasks in bounded batches of at most 10.
The title format keeps the project or repository visible:
Marker Domain|Project/repository key|Work type|Concrete object: purpose or symptom
Example output in Codex Desktop (default color-block style):
For private projects without Jira or Gerrit, it uses the project name, repository name, or cwd basename rather than inventing a placeholder ID.
Privacy and safety boundaries remain narrow:
the Hook stores only hashed session/turn identifiers, prompt counts, and fired checkpoints;
it does not persist prompt text, generated titles, transcripts, rollout data, database content, full paths, or project taxonomy;
it uses supported Codex task-title tools and does not edit Codex databases, session indexes, or rollout files;
configuration is bounded, fail-open, and does not replay checkpoints when the schedule changes.
Then restart Codex or start a new task and review/trust the command Hook before enabling it.
Screenshots, configuration, limitations, and the full installation guide are in the repository README. The package is tested through Windows and Linux CI.
This still does not cover runtimes that lack a supported current-thread title tool. A native implementation would remain better for cross-surface behavior, auditability, and first-class manual/dynamic-title precedence.
I built RecentlyDivorced because long-running Codex sessions change purpose. A useful resume list should identify the current work.
I would like to contribute this behavior as activity-aware session titles, implemented in the Codex CLI binary for Linux, macOS, and Windows. The reference plugin supplies implementation evidence. The native feature should use Codex's existing title and storage services.
What current Codex already provides
At inspected commit 459a79eb85400af759e9220c7bafb4429ae07516, the CLI already generates an initial title for an unnamed thread. It also generates a manual rename suggestion from recent conversation. The title service has a 36-character display limit, a 960-byte request budget, and asynchronous structured generation. See thread_title.rs, the initial trigger, and the result handler.
The added behavior is automatic refresh after a meaningful change in activity, with a cached, local fast path and durable manual-name priority.
Reference implementation and evidence
The pinned reference is 97cecc852247f01a39b54d9242832382ef629123. Its runtime contains three useful mechanisms.
Immediate local label. A prompt hook derives a provisional label from the latest substantive request. Short continuation prompts keep the existing label. This path requires no model call.
Reuse before generation. Cached activity and rollout fingerprints determine whether a label can be reused. Unchanged activity avoids a new labeling request. Initial labeling and later refinement use bounded batches.
Bounded context. The reader starts with a 64 KiB tail window and produces a capsule of at most 480 characters. Current user activity takes precedence over older background. It can read ordinary history, a plaintext compaction summary, or a CompactVeteran handoff. The native feature should work independently with ordinary Codex histories.
During this review, the Rust unit suite was run on Linux:
cargo test --locked --manifest-path plugins/recentlydivorced/runtime/Cargo.toml
Result: 8 passed, 0 failed, 1 ignored. The ignored case uses live Codex model usage.
The passing tests cover current-request priority, trivial prompts, bounded capsules, label normalization, cache decisions, partial-tail recovery, handoff extraction, and legacy/paginated thread eligibility. The full refinement path can consume model usage; the local provisional and cache-hit paths do not.
Proposed native implementation
User control. Add an explicit activity-title mode alongside initial-title and manual-title behavior. Preserve existing behavior on upgrade. A user rename pins that name until the user enables automation again. Treat pre-existing names with unknown origin conservatively.
Event-driven refresh. Use typed, eligible user-input events to advance an activity revision. Keep provisional labels local and quick. Coalesce changes and refine within a configured request budget. Reopening /resume should use stored metadata. Backfill older sessions in bounded, resumable batches.
Race-safe persistence. Store title origin and revision through the canonical thread store. Apply a generated result only when its source activity revision is current and the title remains automatic. Perform this check with the write. A delayed result must preserve a later manual rename or newer automatic label.
One native writer. Extend the existing metadata path so saved names, the compatibility index, and TUI notifications agree. Keep the transcript preview's meaning separate from the title. Use thread revisions in place of Unix inode/device checks and platform-neutral paths in place of fixed database filenames.
Bounded generation. Reuse the native title service and provider selection. Preserve the 36-character title and whole-request byte limits. The reference's 480-character cap is not a substitute for a UTF-8 byte budget. Treat source conversation text as data; label generation should have no tool authority. Keep the last valid title when refinement fails, and expose an opt-out and usage controls.
Independent scope. Apply the same eligibility checks to prompt events, resume, and backfill. Keep subagent and internal generation threads isolated. Shared runtime changes should retain other clients' current behavior.
Acceptance criteria
Case
Required result
A session moves from implementation to a different task
The automatic title follows the new activity.
The user sends “continue” or the rollout adds only tool output
The title remains useful; no redundant refinement is scheduled.
A manual rename occurs while generation is running
The manual name wins durably, including after restart.
Two generated results finish out of order
Only the current activity revision can write.
/resume reopens with unchanged activity
Stored labels are shown without new model calls.
Unicode, image-heavy, or large histories
Whole-request budgets and display limits hold.
A labeling request fails or is cancelled
Navigation stays responsive and the last valid name remains.
Native Windows, macOS, and Linux
The same persistence and refresh behavior passes integration tests.
Relation to this issue
This adds tested CLI reference code to #14044's existing request for dynamic titles. It also supports the explicit control requested in #41537. Earlier comments correctly identify live TUI refresh and consistent persistence as core requirements.
Requested maintainer decision: extend the existing title service with an activity revision, manual-title ownership, and bounded refresh scheduling. These changes can be developed and reviewed independently of checkpointed continuation.
Adding a concrete use case to this request: sessions that start with the same command or boilerplate become indistinguishable when their titles only reflect that opening.
The command can remain in the title, but a short description of the project and the actual task should follow, using the working directory/project and relevant conversation context. A folder name alone may not explain what the project does.
These examples show the desired information, rather than fitting the current CLI's 36-character limit. A compact primary title plus a visible subtitle could preserve this context when space is tight.
The third case matters: adding the directory alone does not distinguish different tasks in the same project. Likewise, a path can identify the project without establishing what the user wants done.
Suggested behavior
Treat a generic opening as provisional. Once a substantive request or the task discovered during normal work makes the purpose clear, refine the automatic title.
Prefer the explicit task; use the repository name or a short distinguishing path component plus a brief, grounded description of what the project does. Reuse known project metadata or context already read during the task; omit unknown descriptions instead of guessing. If the task is still unknown, defer refinement instead of inventing it.
Keep the command prefix optional/short so it does not crowd out the useful description.
Preserve manual names and keep the resulting title consistent across history/resume and active UI surfaces.
Codex already has relevant machinery
At upstream commit 67a7096, the CLI has an asynchronous structured title generator, a 36-character title limit, a 960-byte constructed-prompt budget, and a rename-suggestion path using recent conversation. The automatic trigger uses a user message for an unnamed thread. So this is about selecting sufficient context and refining an uninformative initial title, building on existing generation.
For efficiency, reuse an existing suitable generated title or task summary where available; otherwise pass a bounded task/context excerpt to the existing service after the main turn. Avoid a repository scan or full-transcript model call just for naming. Skip redundant refinement when the task has not changed.
The recommendations and implementation evidence already in this discussion cover much of this, so no separate benchmark was run. This is an additional acceptance case: identical opening commands, including within the same project, should become distinguishable once their actual tasks are known.
Related: #24289 (initial automatic naming), #29681 (project context), and #40223 (excess context in title-generation requests).
Complete local prototype and suggested default
Here are the full scripts. Save block 1 as title_hook.py; save block 2 as ~/.codex/hooks.json after replacing the absolute script path; save block 3 as backfill_old_threads.py beside title_hook.py. This is a Linux/Python 3 prototype using the installed, signed-in codex CLI. Review the hook in /hooks if Codex requests trust.
The live hook reuses the active agent’s task understanding, with no separate model request. It records a grounded project description and task once, preserves preexisting manual names, stops after five user turns, and appends and more locally for an explicitly marked new task. Unmarked task changes cannot reliably be detected by a simple hook.
1. Ongoing hook script:
#!/usr/bin/env python3"""Self-contained, project-aware Codex title hook. Python standard library only."""importargparseimportcontextlibimportfcntlimporthashlibimportjsonimportosfrompathlibimportPathimportreimportselectimportshleximportsubprocessimportsysimporttempfileimporttimeimportunicodedataclassCodexRPC:
def__init__(self, timeout=15):
self.timeout=timeoutself.buffer=b''self.sequence=0home=Path(os.environ.get('CODEX_HOME', str(Path.home() /'.codex')))
sock=home/'app-server-control'/'app-server-control.sock'command= ['codex', 'app-server', 'proxy'] ifsock.exists() else ['codex', 'app-server', '--stdio']
self.process=subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
try:
self.call('initialize', {'clientInfo': {'name': 'local-title-hook', 'version': '0.2'}, 'capabilities': {'experimentalApi': True}})
self.send({'method': 'initialized'})
exceptException:
self.close()
raisedefsend(self, payload):
self.process.stdin.write((json.dumps(payload) +'\n').encode())
self.process.stdin.flush()
defcall(self, method, params):
self.sequence+=1request_id=self.sequenceself.send({'id': request_id, 'method': method, 'params': params})
end=time.monotonic() +self.timeoutwhileTrue:
iftime.monotonic() >=end:
raiseTimeoutError('Codex metadata request timed out: '+method)
ifb'\n'inself.buffer:
line, self.buffer=self.buffer.split(b'\n', 1)
response=json.loads(line)
ifresponse.get('id') !=request_id:
continueif'error'inresponse:
raiseRuntimeError(json.dumps(response['error']))
returnresponse['result']
ifnotselect.select([self.process.stdout], [], [], max(0, end-time.monotonic()))[0]:
raiseTimeoutError('Codex metadata request timed out: '+method)
chunk=os.read(self.process.stdout.fileno(), 65536)
ifnotchunk:
raiseRuntimeError('Codex metadata connection closed')
self.buffer+=chunkdefclose(self):
ifself.process.poll() isNone:
self.process.terminate()
try:
self.process.wait(timeout=3)
exceptsubprocess.TimeoutExpired:
self.process.kill()
self.process.wait()
forpipein (self.process.stdin, self.process.stdout):
pipe.close()
def__enter__(self):
returnselfdef__exit__(self, *args):
self.close()
definspect_thread(session):
withCodexRPC() asrpc:
returnrpc.call('thread/read', {'threadId': session, 'includeTurns': False})['thread']
defpublish(session, state, candidate, directory):
withCodexRPC() asrpc:
thread=rpc.call('thread/read', {'threadId': session, 'includeTurns': False})['thread']
current=thread.get('name')
if'applied_name'instateandcurrent!=state['applied_name']:
state.update(disabled=True, record_allowed=False, skip_reason='name_changed_outside_hook')
returnFalseifstate.get('initial_name'):
state.update(disabled=True, record_allowed=False, skip_reason='preexisting_name')
returnFalse# Codex exposes no name-origin or conditional-name-write field. On a# newly unnamed thread this can replace its automatic initial name.# A concurrent manual rename cannot be distinguished from that name.backup_dir=Path(directory) /'renames'backup_dir.mkdir(parents=True, exist_ok=True, mode=0o700)
withtempfile.NamedTemporaryFile(mode='w', prefix='rename-', suffix='.json', dir=backup_dir, delete=False) asstream:
backup= {'thread_id': session, 'old_name': current, 'new_name': candidate['title'], 'status': 'pending'}
json.dump(backup, stream, ensure_ascii=False, indent=2)
backup_path=Path(stream.name)
rpc.call('thread/name/set', {'threadId': session, 'name': candidate['title']})
actual=rpc.call('thread/read', {'threadId': session, 'includeTurns': False})['thread'].get('name')
ifactual!=candidate['title']:
raiseRuntimeError('Thread name changed before rename verification')
backup['status'] ='verified'backup_path.write_text(json.dumps(backup, ensure_ascii=False, indent=2))
state['applied_name'] =actualreturnTrueROOT=Path(__file__).resolve().parentTASK_SWITCH=re.compile(r'^\s*(?:new|separate|unrelated|different) task\s*:', re.IGNORECASE)
GENERIC= {'continue', 'go', 'go on', 'resume', 'proceed', 'carry on', 'yes', 'ok'}
defnormalized(text):
return' '.join(text.lower().strip().strip('.!?').split())
defclean(value, field, limit, required=False):
ifnotisinstance(value, str):
raiseValueError(f'{field} must be text')
ifany(unicodedata.category(c).startswith('C') forcinvalue):
raiseValueError(f'{field} contains control characters')
value=' '.join(value.split())
ifrequiredandnotvalue:
raiseValueError(f'{field} is required')
iflen(value) >limit:
raiseValueError(f'{field} exceeds {limit} characters; summarize it')
returnvaluedefload_json(path):
returnjson.loads(path.read_text()) ifpath.exists() else {}
defsave_json(path, value):
fd, name=tempfile.mkstemp(prefix='.write-', dir=path.parent)
try:
withos.fdopen(fd, 'w') asstream:
json.dump(value, stream, ensure_ascii=False, indent=2)
stream.write('\n')
os.replace(name, path)
finally:
ifos.path.exists(name):
os.unlink(name)
@contextlib.contextmanagerdefstate_for(directory, session):
ifnotisinstance(session, str) ornotsessionorlen(session) >256:
raiseValueError('invalid session_id')
directory.mkdir(parents=True, exist_ok=True, mode=0o700)
key=hashlib.sha256(session.encode()).hexdigest()
with (directory/ (key+'.lock')).open('a') aslock:
fcntl.flock(lock, fcntl.LOCK_EX)
path=directory/ (key+'.json')
state=load_json(path)
yieldstatesave_json(path, state)
deftitle_parts(candidate, prefix):
project=candidate['project']
ifcandidate['description']:
project+=f" ({candidate['description']})"task=candidate['task']
full=f'{project} — {task}'ifprefix:
full=f'{prefix}: {full}'compact=taskiflen(task) <=36elsetask[:35].rstrip() +'…'return {'title': full, 'compact_title': compact, 'subtitle': project}
defhook(event, directory, max_turns=5, apply=False):
# Subagent events can carry the parent's session id. Never share their state.ifevent.get('agent_id') orevent.get('agent_type') orevent.get('hook_event_name') notin {'UserPromptSubmit', 'Stop'}:
return {}
session=event.get('session_id')
turn=event.get('turn_id')
ifnotisinstance(turn, str) ornotturnorlen(turn) >256:
return {}
withstate_for(directory, session) asstate:
ifstate.get('disabled'):
return {}
ifapplyandnotstate.get('live_initialized'):
thread=inspect_thread(session)
state.update(live_initialized=True, live=True, initial_name=thread.get('name'))
ifthread.get('name') orthread.get('ephemeral') orisinstance(thread.get('source'), dict):
state.update(disabled=True, record_allowed=False, skip_reason='preexisting_name_or_internal_thread')
return {}
ifevent['hook_event_name'] =='Stop':
ifevent.get('stop_hook_active'):
return {}
candidate=state.get('candidate')
ifturn==state.get('pending_turn') andstate.get('turn_count', 0) >=max_turns:
state['disabled'] =Truestate['record_allowed'] =Falseifcandidateandcandidate['turn_id'] ==turnandstate.get('shown_title') !=candidate['title']:
state['shown_title'] =candidate['title']
ifstate.get('live'):
return {}
return {'systemMessage': 'Title preview: '+candidate['title']}
return {}
cwd=event.get('cwd')
prompt=event.get('prompt')
ifnotisinstance(cwd, str) ornotisinstance(prompt, str):
return {}
ifmax_turns<1:
raiseValueError('max_turns must be positive')
seen=state.setdefault('seen_turns', [])
ifturninseen:
return {}
# The limit belongs to the session, never to its directory or title.ifstate.get('turn_count', 0) >=max_turns:
state.update(disabled=True, record_allowed=False)
return {}
seen.append(turn)
state['turn_count'] =state.get('turn_count', 0) +1state.update(cwd=cwd, pending_turn=turn, record_allowed=False)
previous=state.get('candidate')
ifprevious:
ifTASK_SWITCH.match(prompt) andnotprevious.get('and_more'):
previous['and_more'] =Trueprevious['title'] +=' and more'base=previous['task']
iflen(base) >27:
base=base[:26].rstrip() +'…'previous['compact_title'] =base+' and more'# This local suffix must not emit additional model context or# ask the agent to record anything. Inspect it with `show`.ifstate.get('live'):
publish(session, state, previous, directory)
state.update(disabled=True, shown_title=previous['title'])
return {}
generic=normalized(prompt) inGENERICif'prefix'notinstate:
state['prefix'] =prompt.strip().strip('.!?').capitalize() ifgenericelse''state['record_allowed'] =Truecommand=f'python3 {shlex.quote(str(Path(__file__).resolve()))} --state-dir {shlex.quote(str(directory))} record'template= {'session_id': session, 'turn_id': turn, 'project': '<short project name>',
'description': '<what this project does, or empty if unknown>',
'task': '<specific current task>', 'evidence': '<brief sources already observed>'}
destination= ('This applies the initial thread name through the Codex API. 'ifstate.get('live') else'This only saves a local preview; it does not rename the session. ')
instructions= (
'Local project-aware session title. Use your understanding from the normal task; do not start ''another model, scan the repository, or read extra files just for naming. Once the task is ''clear, write one small JSON record by running the command below with JSON on stdin ''(a quoted heredoc is fine). '+destination+'Use the actual target project, not a generic working-directory basename. Include a brief ''grounded description of what the project does. Omit unknown descriptions. The task must ''describe intent, not claim success. Do not invent a task from “continue” alone. ''Record the initial useful title only once per thread. Keep project <=32, description <=48, task <=72 ''characters. Do this before your final answer when tools are already allowed; otherwise skip.\n'+command+'\nJSON fields (placeholders are explanatory):\n'+json.dumps(template, ensure_ascii=False)
)
return {'hookSpecificOutput': {'hookEventName': 'UserPromptSubmit', 'additionalContext': instructions}}
defrecord(data, directory):
withstate_for(directory, data.get('session_id')) asstate:
ifnotstateordata.get('turn_id') !=state.get('pending_turn'):
raiseValueError('stale or unknown turn; run UserPromptSubmit first')
ifstate.get('disabled') ornotstate.get('record_allowed') orstate.get('candidate'):
raiseValueError('title already recorded or per-thread cutoff reached')
candidate= {
'project': clean(data.get('project'), 'project', 32, True),
'description': clean(data.get('description', ''), 'description', 48),
'task': clean(data.get('task'), 'task', 72, True),
'evidence': clean(data.get('evidence'), 'evidence', 500, True),
'turn_id': data['turn_id'],
}
ifnormalized(candidate['task']) inGENERIC:
raiseValueError('task is still unknown')
candidate.update(title_parts(candidate, state.get('prefix', '')))
ifstate.get('live'):
ifnotpublish(data['session_id'], state, candidate, directory):
return {'skipped': state.get('skip_reason')}
state['candidate'] =candidatestate['record_allowed'] =Falsereturncandidatedefmain():
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--state-dir', type=Path, default=ROOT/'.state')
parser.add_argument('action', choices=['hook', 'record', 'show'])
parser.add_argument('--session-id')
parser.add_argument('--apply', action='store_true', help='Apply titles through the Codex metadata API')
parser.add_argument('--max-turns', type=int, default=5, help='Per-thread user-turn limit (default: 5)')
args=parser.parse_args()
try:
ifargs.action=='show':
withstate_for(args.state_dir, args.session_id) asstate:
result=state.get('candidate', {})
else:
raw=sys.stdin.read(65537)
iflen(raw) >65536:
raiseValueError('input exceeds 64 KiB character limit')
data=json.loads(raw)
ifnotisinstance(data, dict):
raiseValueError('input must be an object')
result=hook(data, args.state_dir, args.max_turns, args.apply) ifargs.action=='hook'elserecord(data, args.state_dir)
print(json.dumps(result, ensure_ascii=False))
except (ValueError, TypeError, OSError, RuntimeError, TimeoutError) asexc:
ifargs.action=='hook':
print('{}') # Naming must never block the primary task.print('title preview skipped: '+str(exc), file=sys.stderr)
else:
print(str(exc), file=sys.stderr)
return1return0if__name__=='__main__':
raiseSystemExit(main())
For old threads, run python3 backfill_old_threads.py plan --output old-thread-titles-plan.json, review the JSON, then run python3 backfill_old_threads.py apply old-thread-titles-plan.json. This separate command uses GPT-6 Luna at low effort, sends bounded title/project/task snippets, deduplicates listing rows by thread ID, skips uncertain proposals, and saves a receipt after each verified rename. The reusable backfill has not been rerun against already-renamed threads.
The local suite passes 22 tests, including a mocked app-server rename and duplicate-ID listing. An earlier refined historical batch renamed 99 of 101 distinct remaining threads using 9,865 model tokens. Suggested default: derive the initial title during normal task work, defer while the task is unclear, preserve manual names, and make historical backfill reviewable and optional.
Thanks @a3mentia for adding the same-opening, same-project case. That makes the acceptance criterion much clearer: once the tasks are known, their titles should distinguish them.
Your prototype's note about concurrent manual renames also identifies a key native requirement. The RecentlyDivorced proposal above requests stored title origin and a revision check performed atomically with the write. That would let Codex reject stale generated names and preserve user changes. A plugin-side read before an unconditional rename cannot provide the same guarantee.
Together, these give us a concrete navigation test and a persistence requirement for extending the existing title service.
Repository follow-up: RecentlyDivorced v0.3.13, commit 1b8c294, adds generic-opening deferral, stored project context, protected external/unknown names, explicit per-thread --auto/--pin, and stale-result rejection. The isolated lifecycle proof exercises the same-project case and renames/new input during generation. All nine scenarios pass in CI and against the release binary, using temporary stores and a deterministic model-process stub—not a live-model benchmark.
The plugin's conditional SQLite write protects the local name row; it does not supply native title-origin metadata, detect an identical-text manual rename, or synchronize every active UI and compatibility store. Unknown existing names are preserved unless the user explicitly enables automation. These limits are documented in the release and remain reasons for the native origin/revision/notification contract proposed here.
Activity
github-actions commentedon Mar 9, 2026
Potential duplicates detected. Please review them and close your issue if it is a duplicate.
Powered by Codex Action
zxfxpower commentedon Jun 4, 2026
I’d like to add a concrete CLI/TUI use case for this.
I use long-running Codex CLI sessions where the actual task often becomes clearer only after several turns. A helper can infer a better title from the conversation and persist it to local session metadata, but without a first-class current-thread rename capability it still cannot reliably update the active TUI state. In practice, the workaround is to copy
/rename <title>to the clipboard and ask the user to paste it, or wait until the session is exited and resumed before the title is visible everywhere.An opt-in dynamic title capability would solve this cleanly if it provides:
session_index, SQLite-backed metadata, resume picker, and app/CLI surfaces do not driftThis is closely related to #15444, but the dynamic-title version is useful when the user does not want to keep manually issuing
/renameafter the session scope evolves. The key requirement from the CLI side is not only persistence, but a supported way for the current TUI session to be notified and refreshed.sunnykaibai commentedon Jul 30, 2026
I now have a working, zero-model-cost workaround for the CLI/TUI version of this problem.
This does not replace the requested native capability: it changes the terminal window/tab title, not the persisted Codex thread name used by
/resume, search, or other surfaces. Still, it may be useful both as an immediate workaround and as implementation evidence for separating a stable task label from live activity state.The result looks like:
How it works
It uses the existing Codex lifecycle hooks:
UserPromptSubmit: derive a short deterministic task label, persist it per session, and write● <task>Stop: reuse the same label and write○ <task>SessionStart: restore the label after resume and write the idle stateThe solid/hollow dot already communicates the live state, so the title does not repeat
WorkingorIdlein text.The hook writes an OSC 0 sequence directly to
/dev/tty, because hook stdout is captured by Codex. It does not call a model or the network, so it adds no token cost or model latency.Other behavior:
continue,go, or好的do not replace the task label/rename) takes priority when it is available in local metadata~/.codex/terminal-title-state/The reusable hook script is here:
https://gist.github.com/sunnykaibai/f9a4c5450ee68f71c7b3c76adbe98f86
Minimal configuration
Merge these handlers into the existing
~/.codex/hooks.jsonrather than replacing other hooks:{ "hooks": { "SessionStart": [{ "hooks": [{ "type": "command", "command": "node --no-warnings /ABSOLUTE/PATH/codex-terminal-title-hook.mjs", "timeout": 5 }] }], "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "node --no-warnings /ABSOLUTE/PATH/codex-terminal-title-hook.mjs", "timeout": 5 }] }], "Stop": [{ "hooks": [{ "type": "command", "command": "node --no-warnings /ABSOLUTE/PATH/codex-terminal-title-hook.mjs", "timeout": 5 }] }] } }Disable the native title writer so it does not overwrite the hook:
For VS Code integrated terminals, the tab title setting must accept the program-provided sequence:
{ "terminal.integrated.tabs.title": "${sequence}" }Otty already honors OSC titles directly. Hook trust should be reviewed and approved on the target machine; persisted trust hashes should not be copied between machines.
Verification
Tested locally with:
0.146.0-alpha.9.222.22.0Verified:
continuepromptSessionStartThe remaining reason for a native feature is important: this workaround cannot update the persisted thread name or notify every Codex surface. A first-class current-thread rename capability would still be the clean solution for
/resume, history/search, IDE, desktop, and web. A smaller native TUI improvement could also expose something like aturn-summaryterminal-title item alongside the existing activity/run-state items.znbsf commentedon Aug 17, 2026
Update (2026-09-01): this workaround now lives in a standalone repository:
https://github.com/znbsf/codex-task-title-organizer
The current package is v0.4.0. It remains an opt-in Codex Desktop plugin workaround rather than a replacement for the native capability requested here.
It deliberately avoids renaming on every turn:
The title format keeps the project or repository visible:
Marker Domain|Project/repository key|Work type|Concrete object: purpose or symptomExample output in Codex Desktop (default color-block style):
For private projects without Jira or Gerrit, it uses the project name, repository name, or
cwdbasename rather than inventing a placeholder ID.Privacy and safety boundaries remain narrow:
Install from GitHub:
Then restart Codex or start a new task and review/trust the command Hook before enabling it.
Screenshots, configuration, limitations, and the full installation guide are in the repository README. The package is tested through Windows and Linux CI.
This still does not cover runtimes that lack a supported current-thread title tool. A native implementation would remain better for cross-surface behavior, auditability, and first-class manual/dynamic-title precedence.
lmtlssss commentedon Sep 5, 2026
CLI implementation evidence: activity-aware session titles
I built RecentlyDivorced because long-running Codex sessions change purpose. A useful resume list should identify the current work.
I would like to contribute this behavior as activity-aware session titles, implemented in the Codex CLI binary for Linux, macOS, and Windows. The reference plugin supplies implementation evidence. The native feature should use Codex's existing title and storage services.
What current Codex already provides
At inspected commit
459a79eb85400af759e9220c7bafb4429ae07516, the CLI already generates an initial title for an unnamed thread. It also generates a manual rename suggestion from recent conversation. The title service has a 36-character display limit, a 960-byte request budget, and asynchronous structured generation. See thread_title.rs, the initial trigger, and the result handler.The added behavior is automatic refresh after a meaningful change in activity, with a cached, local fast path and durable manual-name priority.
Reference implementation and evidence
The pinned reference is
97cecc852247f01a39b54d9242832382ef629123. Its runtime contains three useful mechanisms.Immediate local label. A prompt hook derives a provisional label from the latest substantive request. Short continuation prompts keep the existing label. This path requires no model call.
Reuse before generation. Cached activity and rollout fingerprints determine whether a label can be reused. Unchanged activity avoids a new labeling request. Initial labeling and later refinement use bounded batches.
Bounded context. The reader starts with a 64 KiB tail window and produces a capsule of at most 480 characters. Current user activity takes precedence over older background. It can read ordinary history, a plaintext compaction summary, or a CompactVeteran handoff. The native feature should work independently with ordinary Codex histories.
During this review, the Rust unit suite was run on Linux:
cargo test --locked --manifest-path plugins/recentlydivorced/runtime/Cargo.tomlResult: 8 passed, 0 failed, 1 ignored. The ignored case uses live Codex model usage.
The passing tests cover current-request priority, trivial prompts, bounded capsules, label normalization, cache decisions, partial-tail recovery, handoff extraction, and legacy/paginated thread eligibility. The full refinement path can consume model usage; the local provisional and cache-hit paths do not.
Proposed native implementation
User control. Add an explicit activity-title mode alongside initial-title and manual-title behavior. Preserve existing behavior on upgrade. A user rename pins that name until the user enables automation again. Treat pre-existing names with unknown origin conservatively.
Event-driven refresh. Use typed, eligible user-input events to advance an activity revision. Keep provisional labels local and quick. Coalesce changes and refine within a configured request budget. Reopening
/resumeshould use stored metadata. Backfill older sessions in bounded, resumable batches.Race-safe persistence. Store title origin and revision through the canonical thread store. Apply a generated result only when its source activity revision is current and the title remains automatic. Perform this check with the write. A delayed result must preserve a later manual rename or newer automatic label.
One native writer. Extend the existing metadata path so saved names, the compatibility index, and TUI notifications agree. Keep the transcript preview's meaning separate from the title. Use thread revisions in place of Unix inode/device checks and platform-neutral paths in place of fixed database filenames.
Bounded generation. Reuse the native title service and provider selection. Preserve the 36-character title and whole-request byte limits. The reference's 480-character cap is not a substitute for a UTF-8 byte budget. Treat source conversation text as data; label generation should have no tool authority. Keep the last valid title when refinement fails, and expose an opt-out and usage controls.
Independent scope. Apply the same eligibility checks to prompt events, resume, and backfill. Keep subagent and internal generation threads isolated. Shared runtime changes should retain other clients' current behavior.
Acceptance criteria
/resumereopens with unchanged activityRelation to this issue
This adds tested CLI reference code to #14044's existing request for dynamic titles. It also supports the explicit control requested in #41537. Earlier comments correctly identify live TUI refresh and consistent persistence as core requirements.
Requested maintainer decision: extend the existing title service with an activity revision, manual-title ownership, and bounded refresh scheduling. These changes can be developed and reviewed independently of checkpointed continuation.
a3mentia commentedon Sep 27, 2026
Adding a concrete use case to this request: sessions that start with the same command or boilerplate become indistinguishable when their titles only reflect that opening.
The command can remain in the title, but a short description of the project and the actual task should follow, using the working directory/project and relevant conversation context. A folder name alone may not explain what the project does.
Illustrative examples (not captured session titles):
continueshop, an online store: repair checkout retry handlingContinue: shop (online store) — fix checkout retriescontinuedocs, an API reference site: fix broken API linksContinue: docs (API reference) — fix broken linkscontinueshop, an online store: investigate login expiryContinue: shop (online store) — investigate login expiryThese examples show the desired information, rather than fitting the current CLI's 36-character limit. A compact primary title plus a visible subtitle could preserve this context when space is tight.
The third case matters: adding the directory alone does not distinguish different tasks in the same project. Likewise, a path can identify the project without establishing what the user wants done.
Suggested behavior
Codex already has relevant machinery
At upstream commit
67a7096, the CLI has an asynchronous structured title generator, a 36-character title limit, a 960-byte constructed-prompt budget, and a rename-suggestion path using recent conversation. The automatic trigger uses a user message for an unnamed thread. So this is about selecting sufficient context and refining an uninformative initial title, building on existing generation.For efficiency, reuse an existing suitable generated title or task summary where available; otherwise pass a bounded task/context excerpt to the existing service after the main turn. Avoid a repository scan or full-transcript model call just for naming. Skip redundant refinement when the task has not changed.
The recommendations and implementation evidence already in this discussion cover much of this, so no separate benchmark was run. This is an additional acceptance case: identical opening commands, including within the same project, should become distinguishable once their actual tasks are known.
Related: #24289 (initial automatic naming), #29681 (project context), and #40223 (excess context in title-generation requests).
Complete local prototype and suggested default
Here are the full scripts. Save block 1 as
title_hook.py; save block 2 as~/.codex/hooks.jsonafter replacing the absolute script path; save block 3 asbackfill_old_threads.pybesidetitle_hook.py. This is a Linux/Python 3 prototype using the installed, signed-incodexCLI. Review the hook in/hooksif Codex requests trust.The live hook reuses the active agent’s task understanding, with no separate model request. It records a grounded project description and task once, preserves preexisting manual names, stops after five user turns, and appends
and morelocally for an explicitly marked new task. Unmarked task changes cannot reliably be detected by a simple hook.1. Ongoing hook script:
2. Global hook configuration:
{ "hooks": { "UserPromptSubmit": [{"hooks": [{"type": "command", "command": "python3 /absolute/path/to/title_hook.py --max-turns 5 --apply hook", "timeout": 60}]}], "Stop": [{"hooks": [{"type": "command", "command": "python3 /absolute/path/to/title_hook.py --max-turns 5 --apply hook", "timeout": 60}]}] } }3. Optional one-time backfill script:
For old threads, run
python3 backfill_old_threads.py plan --output old-thread-titles-plan.json, review the JSON, then runpython3 backfill_old_threads.py apply old-thread-titles-plan.json. This separate command uses GPT-6 Luna at low effort, sends bounded title/project/task snippets, deduplicates listing rows by thread ID, skips uncertain proposals, and saves a receipt after each verified rename. The reusable backfill has not been rerun against already-renamed threads.The local suite passes 22 tests, including a mocked app-server rename and duplicate-ID listing. An earlier refined historical batch renamed 99 of 101 distinct remaining threads using 9,865 model tokens. Suggested default: derive the initial title during normal task work, defer while the task is unclear, preserve manual names, and make historical backfill reviewable and optional.
lmtlssss commentedon Sep 28, 2026
Thanks @a3mentia for adding the same-opening, same-project case. That makes the acceptance criterion much clearer: once the tasks are known, their titles should distinguish them.
Your prototype's note about concurrent manual renames also identifies a key native requirement. The RecentlyDivorced proposal above requests stored title origin and a revision check performed atomically with the write. That would let Codex reject stale generated names and preserve user changes. A plugin-side read before an unconditional rename cannot provide the same guarantee.
Together, these give us a concrete navigation test and a persistence requirement for extending the existing title service.
Repository follow-up: RecentlyDivorced v0.3.13, commit
1b8c294, adds generic-opening deferral, stored project context, protected external/unknown names, explicit per-thread--auto/--pin, and stale-result rejection. The isolated lifecycle proof exercises the same-project case and renames/new input during generation. All nine scenarios pass in CI and against the release binary, using temporary stores and a deterministic model-process stub—not a live-model benchmark.The plugin's conditional SQLite write protects the local name row; it does not supply native title-origin metadata, detect an identical-text manual rename, or synchronize every active UI and compatibility store. Unknown existing names are preserved unless the user explicitly enables automation. These limits are documented in the release and remain reasons for the native origin/revision/notification contract proposed here.
etraut-openai commentedon Oct 12, 2026
This now exists. You can ask your agent to rename its session.