diff --git a/internal/claude/chat.go b/internal/claude/chat.go index 7a03f892..ff03b1bc 100644 --- a/internal/claude/chat.go +++ b/internal/claude/chat.go @@ -37,6 +37,7 @@ func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.Ch return protocol.ChatSession{}, err } title = strings.TrimSpace(title) + c.SetTitle(ctx, id, title) s := c.sessionFor(id, absolute) s.mu.Lock() s.title = title diff --git a/internal/claude/claude.go b/internal/claude/claude.go index 0cb98ce8..9d269d5d 100644 --- a/internal/claude/claude.go +++ b/internal/claude/claude.go @@ -102,6 +102,9 @@ type Chat struct { mu sync.Mutex sessions map[string]*session closed bool + // titles holds the operator's chat titles by session id (see SetTitle), so a + // session rebuilt after an idle release keeps its name. + titles map[string]string // quotas is the latest rate_limit_event quota per account (see quota.go). quotaMu sync.Mutex @@ -177,10 +180,34 @@ func (c *Chat) sessionFor(id, directory string) *session { streamClaimed: map[int]bool{}, lastUsed: time.Now(), } + s.title = c.titles[id] c.sessions[id] = s return s } +// SetTitle records the chat's current title. The server calls it on a rename +// and when it first routes a session after a restart. A running CLI keeps the +// name it started with; the next spawn passes the new one as --name. The server +// never writes into Claude Code's transcript itself. +func (c *Chat) SetTitle(_ context.Context, id, title string) { + title = strings.TrimSpace(title) + if id == "" || title == "" { + return + } + c.mu.Lock() + if c.titles == nil { + c.titles = map[string]string{} + } + c.titles[id] = title + s := c.sessions[id] + c.mu.Unlock() + if s != nil { + s.mu.Lock() + s.title = title + s.mu.Unlock() + } +} + func (c *Chat) forget(id string) { c.mu.Lock() delete(c.sessions, id) diff --git a/internal/claude/name_test.go b/internal/claude/name_test.go new file mode 100644 index 00000000..c6c135bf --- /dev/null +++ b/internal/claude/name_test.go @@ -0,0 +1,87 @@ +package claude + +import ( + "context" + "os" + "slices" + "testing" +) + +func TestCLIArgsNameTheSessionWithItsTitle(t *testing.T) { + chat := &Chat{sessions: map[string]*session{}} + s := chat.sessionFor("id-1", "/fixture") + + args, _ := s.cliArgs(false) + if slices.Contains(args, "--name") { + t.Fatalf("an untitled session must not pass --name: %q", args) + } + + s.title = " Fix the\nlogin page " + args, _ = s.cliArgs(false) + if got := argValue(args, "--name"); got != "Fix the login page" { + t.Fatalf("--name = %q, want the title on one line: %q", got, args) + } + if argValue(args, "--session-id") != "id-1" { + t.Fatalf("a new session must pin its id: %q", args) + } + args, _ = s.cliArgs(true) + if argValue(args, "--resume") != "id-1" || argValue(args, "--name") != "Fix the login page" { + t.Fatalf("a resumed session must keep its id and name: %q", args) + } +} + +func TestSetTitleReachesExistingAndRebuiltSessions(t *testing.T) { + ctx := context.Background() + chat := &Chat{sessions: map[string]*session{}} + + // A title recorded before the session is rebuilt (a server restart) is + // applied when sessionFor creates it. + chat.SetTitle(ctx, "id-1", "From the registry") + if got := chat.sessionFor("id-1", "/fixture").title; got != "From the registry" { + t.Fatalf("rebuilt session title = %q", got) + } + + // A rename updates a live session, and survives an idle release. + chat.SetTitle(ctx, "id-1", "Renamed") + if got := chat.session("id-1").title; got != "Renamed" { + t.Fatalf("live session title = %q", got) + } + chat.forget("id-1") + if got := chat.sessionFor("id-1", "/fixture").title; got != "Renamed" { + t.Fatalf("title after release = %q", got) + } + + // A blank title never erases the name. + chat.SetTitle(ctx, "id-1", " ") + if got := chat.session("id-1").title; got != "Renamed" { + t.Fatalf("blank rename changed the title to %q", got) + } +} + +func TestSpawnPassesTheTitleAndARenameReachesTheNextSpawn(t *testing.T) { + ctx := context.Background() + chat := testChat(t) + session := newCreatedChat(t, chat) + frames := subscribe(t, chat, session.ID) + if err := chat.Prompt(ctx, session.ID, "hello"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + logPath := os.Getenv("FAKE_CLAUDE_LOG") + entries := readArgs(t, logPath) + if got := argValue(entries[len(entries)-1].Args, "--name"); got != "Fixture" { + t.Fatalf("first spawn --name = %q: %+v", got, entries) + } + + chat.SetTitle(ctx, session.ID, "Renamed chat") + chat.session(session.ID).closeProcess() + if err := chat.Prompt(ctx, session.ID, "hello again"); err != nil { + t.Fatal(err) + } + waitStepEnded(t, frames) + entries = readArgs(t, logPath) + last := entries[len(entries)-1].Args + if argValue(last, "--resume") != session.ID || argValue(last, "--name") != "Renamed chat" { + t.Fatalf("respawn after rename = %q", last) + } +} diff --git a/internal/claude/process.go b/internal/claude/process.go index bcf540e7..907b86c3 100644 --- a/internal/claude/process.go +++ b/internal/claude/process.go @@ -55,6 +55,46 @@ type controlReply struct { err string } +// cliArgs builds the CLI arguments for one spawn and returns the permission +// mode it applied. resume continues an existing transcript; otherwise the CLI +// pins the id recorded at create time. A known chat title is passed as --name, +// which Claude Code records as the session's display name, so `claude --resume` +// in a terminal lists the chat by its title. +func (s *session) cliArgs(resume bool) ([]string, string) { + args := []string{ + "-p", + "--input-format", "stream-json", + "--output-format", "stream-json", + "--verbose", + "--include-partial-messages", + "--permission-prompt-tool=stdio", + "--permission-prompts", "host", + } + if resume { + args = append(args, "--resume", s.id) + } else { + args = append(args, "--session-id", s.id) + } + s.mu.Lock() + model, mode, title := s.model, s.mode, s.title + s.mu.Unlock() + if model != "" { + args = append(args, "--model", model) + } + if mode != "" && mode != defaultMode { + args = append(args, "--permission-mode", mode) + } + if name := sessionDisplayName(title); name != "" { + args = append(args, "--name", name) + } + return args, mode +} + +// sessionDisplayName folds a chat title onto one line for the CLI's session name. +func sessionDisplayName(title string) string { + return strings.Join(strings.Fields(title), " ") +} + // spawn starts the CLI in the session directory. A session whose transcript // already exists resumes it; a new one pins the id we recorded at create time. func (s *session) spawn(ctx context.Context) (*process, error) { @@ -67,29 +107,7 @@ func (s *session) spawn(ctx context.Context) (*process, error) { if info, err := os.Stat(s.directory); err != nil || !info.IsDir() { return nil, fmt.Errorf("Claude session directory is not available: %s", s.directory) } - args := []string{ - "-p", - "--input-format", "stream-json", - "--output-format", "stream-json", - "--verbose", - "--include-partial-messages", - "--permission-prompt-tool=stdio", - "--permission-prompts", "host", - } - if findTranscriptFile(s.id) != "" { - args = append(args, "--resume", s.id) - } else { - args = append(args, "--session-id", s.id) - } - if s.model != "" { - args = append(args, "--model", s.model) - } - s.mu.Lock() - mode := s.mode - s.mu.Unlock() - if mode != "" && mode != defaultMode { - args = append(args, "--permission-mode", mode) - } + args, mode := s.cliArgs(findTranscriptFile(s.id) != "") cmd := exec.CommandContext(s.chat.ctx, s.chat.binary, args...) cmd.Dir = s.directory env, notices := s.chat.processEnv(ctx, s.directory) diff --git a/internal/server/chat.go b/internal/server/chat.go index fa11989b..d3b7ef9c 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -208,7 +208,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker handleChatColor(ctx, request, registry, hub.changes(), clientID, write) return true case protocol.ChatRename: - handleChatRename(ctx, request, registry, hub.changes(), clientID, write) + handleChatRename(ctx, request, broker, registry, hub.changes(), clientID, write) return true case protocol.ChatExport: handleChatExport(ctx, request, broker, registry, write) diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 0ee5263e..eacd6a76 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -273,13 +273,22 @@ func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBrok if adapter == nil { return nil, errors.New("chat backend " + backend + " is not available") } - if hinter, ok := adapter.(chatDirectoryHinter); ok && m.registry != nil { + hinter, hintsDirectory := adapter.(chatDirectoryHinter) + titler, takesTitle := adapter.(chatTitleSetter) + if (hintsDirectory || takesTitle) && m.registry != nil { m.mu.Lock() done := m.hinted[sessionID] m.mu.Unlock() if !done { if row, found, err := m.registry.OperatorSession(ctx, sessionID); err == nil && found { - hinter.HintDirectory(ctx, sessionID, row.Directory) + if hintsDirectory { + hinter.HintDirectory(ctx, sessionID, row.Directory) + } + // The registry holds the operator's title, renames included, so + // a session rebuilt after a restart keeps its name. + if takesTitle && row.Title != "" { + titler.SetTitle(ctx, sessionID, row.Title) + } m.mu.Lock() if m.hinted == nil { m.hinted = map[string]bool{} @@ -292,6 +301,26 @@ func (m *chatManager) brokerFor(ctx context.Context, sessionID string) (chatBrok return adapter, nil } +// chatTitleSetter is a harness that names its own sessions from the operator's +// chat title (Claude Code passes it as --name on the next spawn). SetTitle +// records the title in memory only and does no I/O. +type chatTitleSetter interface { + SetTitle(ctx context.Context, sessionID, title string) +} + +// SetTitle hands a renamed chat's title to its harness when the harness keeps +// one. The registry stays the source of truth; this only refreshes the name the +// harness shows outside the app. +func (m *chatManager) SetTitle(ctx context.Context, sessionID, title string) { + adapter, err := m.brokerFor(ctx, sessionID) + if err != nil { + return + } + if titler, ok := adapter.(chatTitleSetter); ok { + titler.SetTitle(ctx, sessionID, title) + } +} + // chatDirectoryHinter is a harness that needs a session's recorded directory // to find it after a restart (Claude Code keeps a transcript in the // directory's own CLAUDE_CONFIG_DIR). HintDirectory is cheap after the first diff --git a/internal/server/chat_rename.go b/internal/server/chat_rename.go index 4fa5fc78..98ae5777 100644 --- a/internal/server/chat_rename.go +++ b/internal/server/chat_rename.go @@ -18,7 +18,7 @@ const chatTitleLimit = 200 // browser and device lists the same name. The OpenCode session, its transcript // and its generated title are untouched, and a session that is not an operator // chat is refused before anything is written. -func handleChatRename(ctx context.Context, request protocol.Message, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { +func handleChatRename(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry, changes *chatSessionChanges, clientID string, write func(protocol.Message) error) { if registry == nil { _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "operator session registry is not configured on this server"}) return @@ -48,5 +48,10 @@ func handleChatRename(ctx context.Context, request protocol.Message, registry op _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()}) return } + // A harness that names its own sessions (Claude Code's --name) takes the + // new title for its next start; the registry row above stays authoritative. + if titler, ok := broker.(chatTitleSetter); ok { + titler.SetTitle(ctx, rename.SessionID, title) + } echoOperatorSession(ctx, request, rename.SessionID, protocol.ChatRename, registry, changes, clientID, write) } diff --git a/internal/server/chat_rename_test.go b/internal/server/chat_rename_test.go new file mode 100644 index 00000000..1d2655d2 --- /dev/null +++ b/internal/server/chat_rename_test.go @@ -0,0 +1,85 @@ +package server + +import ( + "context" + "path/filepath" + "sync" + "testing" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// titledChat records the titles the server hands to a harness that names its +// own sessions (Claude Code's --name). +type titledChat struct { + *fakeChat + titleMu sync.Mutex + titles []string +} + +func (c *titledChat) SetTitle(_ context.Context, _, title string) { + c.titleMu.Lock() + c.titles = append(c.titles, title) + c.titleMu.Unlock() +} + +func (c *titledChat) lastTitle() string { + c.titleMu.Lock() + defer c.titleMu.Unlock() + if len(c.titles) == 0 { + return "" + } + return c.titles[len(c.titles)-1] +} + +func TestChatRenameReachesTheHarnessAndARestartLearnsTheRegistryTitle(t *testing.T) { + ctx := context.Background() + store, err := pipeline.Open(filepath.Join(t.TempDir(), "chat.db")) + if err != nil { + t.Fatal(err) + } + id := "01900000-0000-7000-8000-000000000003" + if err := store.RecordOperatorSession(ctx, id, "/fixture", "Original", protocol.ChatSessionTagOperator); err != nil { + t.Fatal(err) + } + if err := store.SetOperatorSessionBackend(ctx, id, "claude"); err != nil { + t.Fatal(err) + } + + // First routing after a restart hands the registry title to the harness. + fake := &titledChat{fakeChat: scriptedChat()} + manager := &chatManager{claude: fake, registry: store, cache: map[string]string{}} + if _, err := manager.brokerFor(ctx, id); err != nil { + t.Fatal(err) + } + if got := fake.lastTitle(); got != "Original" { + t.Fatalf("routed session title = %q, want the registry title", got) + } + + var reply protocol.Message + capture := func(msg protocol.Message) error { reply = msg; return nil } + handleChatRename(ctx, protocol.Message{ID: "rename", ChatRename: &protocol.ChatRenameRequest{SessionID: id, Title: " Renamed "}}, manager, store, nil, "client", capture) + if reply.Type != protocol.ChatRename || reply.ChatSession == nil || reply.ChatSession.Title != "Renamed" { + t.Fatalf("rename reply = %+v", reply) + } + if got := fake.lastTitle(); got != "Renamed" { + t.Fatalf("harness title after rename = %q", got) + } + + // A restarted server learns the renamed title from the registry. + restarted := &titledChat{fakeChat: scriptedChat()} + manager = &chatManager{claude: restarted, registry: store, cache: map[string]string{}} + if _, err := manager.brokerFor(ctx, id); err != nil { + t.Fatal(err) + } + if got := restarted.lastTitle(); got != "Renamed" { + t.Fatalf("title after restart = %q", got) + } + + // A refused rename never reaches the harness. + handleChatRename(ctx, protocol.Message{ID: "blank", ChatRename: &protocol.ChatRenameRequest{SessionID: id, Title: " "}}, manager, store, nil, "client", capture) + if reply.Type != protocol.Error || restarted.lastTitle() != "Renamed" { + t.Fatalf("blank rename = %+v, harness title %q", reply, restarted.lastTitle()) + } +}