Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(codex): set semantic thread names (#3887)
Bohan Jiang3808049361cf
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex e3e48eaa84..d38c14dc37 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -2919,6 +2919,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iexecOpts := agent.ExecOptions{Cwd: env.WorkDir,Model: model,+ ThreadName: deriveTaskThreadName(task),Timeout: d.cfg.AgentTimeout,SemanticInactivityTimeout: d.cfg.CodexSemanticInactivityTimeout,ResumeSessionID: task.PriorSessionID,diff --git a/server/internal/daemon/thread_name.go b/server/internal/daemon/thread_name.gonew file mode 100644index 0000000000..82e3f0a069--- /dev/null+++ b/server/internal/daemon/thread_name.go@@ -0,0 +1,40 @@+package daemon++import "strings"++const codexThreadNameMaxRunes = 120++func deriveTaskThreadName(task Task) string {+ candidates := []string{+ task.ThreadName,+ task.AutopilotTitle,+ task.QuickCreatePrompt,+ task.ChatMessage,+ task.TriggerCommentContent,+ }+ for _, candidate := range candidates {+ if name := normalizeThreadName(candidate, codexThreadNameMaxRunes); name != "" {+ return name+ }+ }+ return ""+}++func normalizeThreadName(s string, maxRunes int) string {+ fields := strings.Fields(s)+ if len(fields) == 0 {+ return ""+ }+ normalized := strings.Join(fields, " ")+ if maxRunes <= 0 {+ return normalized+ }+ rs := []rune(normalized)+ if len(rs) <= maxRunes {+ return normalized+ }+ if maxRunes <= 3 {+ return string(rs[:maxRunes])+ }+ return string(rs[:maxRunes-3]) + "..."+}diff --git a/server/internal/daemon/thread_name_test.go b/server/internal/daemon/thread_name_test.gonew file mode 100644index 0000000000..74fd72ed06--- /dev/null+++ b/server/internal/daemon/thread_name_test.go@@ -0,0 +1,44 @@+package daemon++import (+ "strings"+ "testing"+)++func TestDeriveTaskThreadNamePrefersClaimedThreadName(t *testing.T) {+ t.Parallel()++ got := deriveTaskThreadName(Task{+ ThreadName: " Fix login redirect ",+ TriggerCommentContent: "please look at this comment",+ ChatMessage: "chat fallback",+ })+ if got != "Fix login redirect" {+ t.Fatalf("thread name = %q, want %q", got, "Fix login redirect")+ }+}++func TestDeriveTaskThreadNameFallsBackToTaskContext(t *testing.T) {+ t.Parallel()++ got := deriveTaskThreadName(Task{QuickCreatePrompt: "create issue for billing sync"})+ if got != "create issue for billing sync" {+ t.Fatalf("thread name = %q, want quick-create prompt", got)+ }+}++func TestNormalizeThreadNameCollapsesWhitespaceAndTruncates(t *testing.T) {+ t.Parallel()++ input := "first line\n\t" + strings.Repeat("x", codexThreadNameMaxRunes+20)+ got := normalizeThreadName(input, codexThreadNameMaxRunes)+ if strings.ContainsAny(got, "\n\t") {+ t.Fatalf("thread name still contains raw whitespace: %q", got)+ }+ if len([]rune(got)) != codexThreadNameMaxRunes {+ t.Fatalf("thread name rune length = %d, want %d", len([]rune(got)), codexThreadNameMaxRunes)+ }+ if !strings.HasSuffix(got, "...") {+ t.Fatalf("thread name should end with ellipsis marker, got %q", got)+ }+}diff --git a/server/internal/daemon/types.go b/server/internal/daemon/types.goindex e14d310f3a..2117d69943 100644--- a/server/internal/daemon/types.go+++ b/server/internal/daemon/types.go@@ -44,6 +44,7 @@ type Task struct {// regardless of task kind so the daemon can inject `## Workspace Context`// into the brief. Empty when the owner hasn't set one.WorkspaceContext string `json:"workspace_context,omitempty"`+ ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread historyAgent *AgentData `json:"agent,omitempty"`Repos []RepoData `json:"repos,omitempty"`ProjectID string `json:"project_id,omitempty"` // issue's project, when presentdiff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 2601e9d60b..941af5f7fd 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -168,6 +168,7 @@ type AgentTaskResponse struct {// regardless of issue / chat / autopilot / quick-create — sees the same// shared context. Empty when the workspace owner hasn't set it.WorkspaceContext string `json:"workspace_context,omitempty"`+ ThreadName string `json:"thread_name,omitempty"` // semantic title for provider-native session/thread historyStatus string `json:"status"`Priority int32 `json:"priority"`DispatchedAt *string `json:"dispatched_at"`diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex fb1da948dd..4ef0de213f 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1172,6 +1172,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if task.IssueID.Valid {if issue, err := h.Queries.GetIssue(r.Context(), task.IssueID); err == nil {resp.WorkspaceID = uuidToString(issue.WorkspaceID)+ resp.ThreadName = issue.Title// Squad-leader briefing injection: when the issue is assigned// to a squad and the claiming agent is that squad's current@@ -1338,6 +1339,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if cs, err := h.Queries.GetChatSession(r.Context(), task.ChatSessionID); err == nil {resp.WorkspaceID = uuidToString(cs.WorkspaceID)resp.ChatSessionID = uuidToString(cs.ID)+ resp.ThreadName = cs.Titleif ws, err := h.Queries.GetWorkspace(r.Context(), cs.WorkspaceID); err == nil && ws.Repos != nil {var repos []RepoDataif json.Unmarshal(ws.Repos, &repos) == nil && len(repos) > 0 {@@ -1402,6 +1404,9 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {}}resp.ChatMessage = strings.Join(parts, "\n\n")+ if strings.TrimSpace(resp.ThreadName) == "" {+ resp.ThreadName = resp.ChatMessage+ }}}}@@ -1418,6 +1423,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {}if ap, err := h.Queries.GetAutopilot(r.Context(), run.AutopilotID); err == nil {resp.AutopilotTitle = ap.Title+ resp.ThreadName = ap.Titleif ap.Description.Valid {resp.AutopilotDescription = ap.Description.String}@@ -1445,6 +1451,7 @@ func (h *Handler) ClaimTaskByRuntime(w http.ResponseWriter, r *http.Request) {if json.Unmarshal(task.Context, &qc) == nil && qc.Type == service.QuickCreateContextType {hasQuickCreate = trueresp.QuickCreatePrompt = qc.Prompt+ resp.ThreadName = qc.Promptresp.WorkspaceID = qc.WorkspaceID// When the user picked a project in the modal, surface its titlediff --git a/server/internal/handler/daemon_test.go b/server/internal/handler/daemon_test.goindex 0fd3636492..c1a87a9fe2 100644--- a/server/internal/handler/daemon_test.go+++ b/server/internal/handler/daemon_test.go@@ -1962,6 +1962,7 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {var resp struct {Task *struct {WorkspaceID string `json:"workspace_id"`+ ThreadName string `json:"thread_name"`} `json:"task"`}if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {@@ -1976,6 +1977,9 @@ func TestClaimTask_AutopilotRunOnly_PopulatesWorkspaceID(t *testing.T) {if resp.Task.WorkspaceID != testWorkspaceID {t.Fatalf("expected workspace_id %q, got %q", testWorkspaceID, resp.Task.WorkspaceID)}+ if resp.Task.ThreadName != "claim workspace fixture" {+ t.Fatalf("autopilot task thread_name = %q, want autopilot title", resp.Task.ThreadName)+ }}// TestClaimTaskByRuntime_TaskWorkspaceMismatch_CancelsAndRejects verifies@@ -2387,6 +2391,7 @@ type claimRuntimeGuardTask struct {PriorSessionID string `json:"prior_session_id"`PriorWorkDir string `json:"prior_work_dir"`ChatMessage string `json:"chat_message"`+ ThreadName string `json:"thread_name"`}func claimTaskForRuntimeGuard(t *testing.T, runtimeID, daemonID string) *claimRuntimeGuardTask {@@ -2634,6 +2639,9 @@ func TestClaimTask_IssuePriorSessionRuntimeGuard(t *testing.T) {if task.PriorWorkDir != "/tmp/old-runtime-workdir" {t.Fatalf("runtime mismatch: expected PriorWorkDir='/tmp/old-runtime-workdir', got %q", task.PriorWorkDir)}+ if task.ThreadName != "runtime-session-skip fixture" {+ t.Fatalf("issue task thread_name = %q, want issue title", task.ThreadName)+ }if _, err := testPool.Exec(ctx, `UPDATE agent_task_queueSET status = 'completed', completed_at = now()@@ -2906,6 +2914,9 @@ func TestClaimTask_ChatDeliversAllUnansweredUserMessages(t *testing.T) {if task.ChatMessage != "看上海天气\n\n还有青岛" {t.Fatalf("chat prompt must include every unanswered user message in order; got %q", task.ChatMessage)}+ if task.ThreadName != "debounce delivery chat" {+ t.Fatalf("chat task thread_name = %q, want chat session title", task.ThreadName)+ }// Complete the run and record the agent's assistant reply, then send a// fresh user message — only the new one should be delivered next.@@ -2940,6 +2951,35 @@ func TestClaimTask_ChatDeliversAllUnansweredUserMessages(t *testing.T) {}}+func TestClaimTask_QuickCreatePopulatesThreadName(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ agentID, runtimeID, daemonID := createRuntimeGuardAgent(t, ctx)++ quickPrompt := "create a follow-up issue for Codex session titles"+ quickContext, _ := json.Marshal(map[string]any{+ "type": "quick_create",+ "prompt": quickPrompt,+ "requester_id": testUserID,+ "workspace_id": testWorkspaceID,+ })++ if _, err := testPool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, status, priority, context)+ VALUES ($1, $2, 'queued', 2, $3)+ `, agentID, runtimeID, quickContext); err != nil {+ t.Fatalf("setup: create quick-create task: %v", err)+ }++ task := claimTaskForRuntimeGuard(t, runtimeID, daemonID)+ if task.ThreadName != quickPrompt {+ t.Fatalf("quick-create task thread_name = %q, want prompt", task.ThreadName)+ }+}+func TestClaimTask_ChatForceFreshSessionSkipsPriorSession(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex 1f34c5812d..57e80f97e0 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -28,6 +28,7 @@ type ExecOptions struct {// developer/system instructions. Hermes ACP intentionally ignores it and// relies on cwd-scoped context files such as AGENTS.md instead.SystemPrompt string+ ThreadName stringMaxTurns intTimeout time.DurationSemanticInactivityTimeout time.Durationdiff --git a/server/pkg/agent/codex.go b/server/pkg/agent/codex.goindex 4443ea732a..893dc7b50a 100644--- a/server/pkg/agent/codex.go+++ b/server/pkg/agent/codex.go@@ -922,9 +922,29 @@ func (c *codexClient) startOrResumeThread(ctx context.Context, opts ExecOptions,if threadID == "" {return "", false, fmt.Errorf("codex thread/start returned no thread ID")}+ c.trySetThreadName(ctx, threadID, opts.ThreadName, logger)return threadID, false, nil}+func (c *codexClient) trySetThreadName(ctx context.Context, threadID, name string, logger *slog.Logger) {+ name = strings.TrimSpace(name)+ if name == "" {+ return+ }+ if err := c.setThreadName(ctx, threadID, name); err != nil {+ logger.Warn("codex thread/name/set failed; continuing without provider-native thread title",+ "thread_id", threadID, "error", err)+ }+}++func (c *codexClient) setThreadName(ctx context.Context, threadID, name string) error {+ _, err := c.request(ctx, "thread/name/set", map[string]any{+ "threadId": threadID,+ "name": name,+ })+ return err+}+// applyCodexReasoningEffort writes the per-agent thinking_level into a// Codex app-server request. The three points — thread/start.config,// thread/resume.config, turn/start.effort — all flow through this helperdiff --git a/server/pkg/agent/codex_test.go b/server/pkg/agent/codex_test.goindex a2056e79d1..d73e49e482 100644--- a/server/pkg/agent/codex_test.go+++ b/server/pkg/agent/codex_test.go@@ -881,6 +881,81 @@ func TestCodexStartOrResumeThreadStartsFresh(t *testing.T) {}}+func TestCodexStartOrResumeThreadSetsNameOnFreshThread(t *testing.T) {+ t.Parallel()++ c, fs, _ := newTestCodexClient(t)++ wait := drainRPCScript(t, c, fs, []rpcResponse{+ {+ method: "thread/start",+ result: json.RawMessage(`{"thread":{"id":"thr_named"}}`),+ },+ {+ method: "thread/name/set",+ result: json.RawMessage(`{}`),+ assertFn: func(t *testing.T, params map[string]any) {+ if params["threadId"] != "thr_named" {+ t.Errorf("threadId = %v, want thr_named", params["threadId"])+ }+ if params["name"] != "Review GitHub issue #3843" {+ t.Errorf("name = %v, want semantic title", params["name"])+ }+ },+ },+ })+ defer wait()++ threadID, resumed, err := c.startOrResumeThread(+ context.Background(),+ ExecOptions{ThreadName: "Review GitHub issue #3843"},+ slog.Default(),+ )+ if err != nil {+ t.Fatalf("startOrResumeThread: %v", err)+ }+ if threadID != "thr_named" {+ t.Errorf("threadID = %q, want thr_named", threadID)+ }+ if resumed {+ t.Error("resumed should be false when no prior session is provided")+ }+}++func TestCodexStartOrResumeThreadNameFailureDoesNotBlock(t *testing.T) {+ t.Parallel()++ c, fs, _ := newTestCodexClient(t)++ wait := drainRPCScript(t, c, fs, []rpcResponse{+ {+ method: "thread/start",+ result: json.RawMessage(`{"thread":{"id":"thr_named"}}`),+ },+ {+ method: "thread/name/set",+ errMsg: "unsupported method",+ errCode: -32601,+ },+ })+ defer wait()++ threadID, resumed, err := c.startOrResumeThread(+ context.Background(),+ ExecOptions{ThreadName: "Semantic task title"},+ slog.Default(),+ )+ if err != nil {+ t.Fatalf("startOrResumeThread should continue after name failure: %v", err)+ }+ if threadID != "thr_named" {+ t.Errorf("threadID = %q, want thr_named", threadID)+ }+ if resumed {+ t.Error("resumed should be false when no prior session is provided")+ }+}+func TestCodexStartOrResumeThreadResumesPriorThread(t *testing.T) {t.Parallel()