Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Generate session titles from the first exchange (OpenCode parity)
rcourtman70a20f6ac7d8
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 003258fd58..7e5ee62db9 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -1522,6 +1522,18 @@ deriving an older display status from `workflowStatusHistory`.return the updated `ChatSession`, update the visible row without closing thepicker, and leave messages, handoff context, approvals, and tool evidenceunchanged.+ Session titles follow OpenCode's generated-title model: after a session's+ first exchange completes, the chat runtime upgrades the auto-truncated+ first-prompt placeholder to a short model-generated title+ (`chat.Service.generateSessionTitle`, `internal/ai/chat/session_title.go`).+ The upgrade runs after the done event reaches the client (no turn+ latency), only on the first exchange, and never overwrites a title the+ user set: any title that differs from the placeholder is left alone, with+ a re-check before persisting to lose races against a concurrent rename.+ Title requests pass the same model-boundary sanitizer as normal turns,+ record usage as `assistant_session_title`, and a failed or timed-out+ title call leaves the placeholder in place rather than failing anything+ user-visible.Assistant turn undo/redo is also a source-backed session repair workflow,not a transcript-local delete button. The referenced OpenCode source in`packages/opencode/src/cli/cmd/tui/routes/session/index.tsx` registers@@ -2376,6 +2388,15 @@ deriving an older display status from `workflowStatusHistory`.## Current State+Session titles are model-generated after the first exchange+(`internal/ai/chat/session_title.go`): the chat runtime upgrades the+auto-truncated first-prompt placeholder once the done event has reached the+client, never overwrites a user-set title (placeholder comparison plus a+pre-persist re-check), passes the model-boundary sanitizer, records usage as+`assistant_session_title`, and leaves the placeholder on failure or timeout.+The long-form contract lives with the session rename clause in Extension+Points.+Finding identity is the LLM-assigned key (resource+category+key hash → ID),and key collisions are surfaced, not forked: when a same-ID re-detection'stitle shares essentially no keywords with the existing finding's titlediff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.goindex e6c5ba5745..cd61682eff 100644--- a/internal/ai/chat/service.go+++ b/internal/ai/chat/service.go@@ -964,6 +964,12 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac})streamCallback(StreamEvent{Type: "done", Data: doneData})+ // Upgrade the placeholder title (truncated first prompt) to a+ // model-generated one after the first exchange. The client has already+ // received done; this bounded call only delays handler teardown and+ // skips itself on any later turn or user rename.+ s.upgradeSessionTitleAfterFirstExchange(session.ID)+return nil}diff --git a/internal/ai/chat/service_test.go b/internal/ai/chat/service_test.goindex 1e64e3fdf6..fc5553fb46 100644--- a/internal/ai/chat/service_test.go+++ b/internal/ai/chat/service_test.go@@ -672,6 +672,10 @@ func TestService_Execute_NonStreaming(t *testing.T) {callback(providers.StreamEvent{Type: "done", Data: providers.DoneEvent{}})}).Once()+ // First-exchange completion triggers background session-title generation.+ mockProvider.On("Chat", mock.Anything, mock.Anything).+ Return(&providers.ChatResponse{Content: "Greeting check"}, nil)+ mockProvider.On("Name").Return("mock").Maybe()executor := tools.NewPulseToolExecutor(tools.ExecutorConfig{})service := &Service{diff --git a/internal/ai/chat/session_title.go b/internal/ai/chat/session_title.gonew file mode 100644index 0000000000..245b460dba--- /dev/null+++ b/internal/ai/chat/session_title.go@@ -0,0 +1,217 @@+package chat++import (+ "context"+ "fmt"+ "strings"+ "time"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/modelboundary"+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"+ "github.com/rs/zerolog/log"+)++const (+ // Slow chat routes (reasoning models via aggregators) routinely take+ // ~10s for even tiny completions; the call runs after the client already+ // received done, so the budget only delays handler teardown.+ sessionTitleTimeout = 20 * time.Second+ sessionTitleSourceMaxChars = 2000+)++const sessionTitleSystemPrompt = `You title Pulse Assistant chat sessions.++Given the first user message and the assistant's reply, produce a short descriptive title for the session list.++Rules:+- At most 50 characters.+- Plain text only: no quotes, no markdown, no trailing punctuation.+- Name the concrete subject (host, VM, container, service, alert) when one exists.+- Do not invent details that are not in the exchange.++Respond with the title only.`++// upgradeSessionTitleAfterFirstExchange upgrades a fresh session's+// placeholder title (the truncated first prompt) to a model-generated one.+// Called after the done event has already reached the client, so the bounded+// provider call adds no user-visible turn latency. Best-effort: never fails+// the turn. Uses a background context because the client may have stopped+// reading the stream by now.+func (s *Service) upgradeSessionTitleAfterFirstExchange(sessionID string) {+ ctx, cancel := context.WithTimeout(context.Background(), sessionTitleTimeout)+ defer cancel()+ if err := s.generateSessionTitle(ctx, sessionID); err != nil {+ if ctx.Err() != nil {+ // A provider too slow to title within budget is worth surfacing.+ log.Warn().Err(err).Str("session_id", sessionID).Msg("[ChatService] Session title generation timed out")+ return+ }+ log.Debug().Err(err).Str("session_id", sessionID).Msg("[ChatService] Session title generation skipped")+ }+}++// generateSessionTitle generates and persists a model-produced session title.+// It only acts on a session's first exchange while the title still carries the+// auto-truncated placeholder, so a user rename is never overwritten.+func (s *Service) generateSessionTitle(ctx context.Context, sessionID string) error {+ normalizedSessionID := strings.TrimSpace(sessionID)+ if normalizedSessionID == "" {+ return fmt.Errorf("session id required")+ }++ s.mu.RLock()+ started := s.started+ sessions := s.sessions+ provider := s.provider+ costStore := s.costStore+ cfgSnapshot := s.cfg+ unifiedResourceProvider := s.unifiedResourceProvider+ s.mu.RUnlock()++ if !started || sessions == nil {+ return fmt.Errorf("service not started")+ }+ if provider == nil {+ return fmt.Errorf("provider not available")+ }++ session, err := sessions.Get(normalizedSessionID)+ if err != nil {+ return err+ }+ messages, err := sessions.GetMessages(normalizedSessionID)+ if err != nil {+ return err+ }++ firstUser, firstAssistant, userCount := firstSessionExchange(messages)+ if userCount != 1 {+ return fmt.Errorf("not the first exchange")+ }+ if firstUser == "" {+ return fmt.Errorf("no user prompt to title")+ }+ // Only replace the auto-truncated placeholder. Anything else means the+ // user renamed the session (or a title was already generated).+ if session.Title != "" && session.Title != generateTitle(firstUser) {+ return fmt.Errorf("title already customized")+ }++ requestModel := ""+ if cfgSnapshot != nil {+ requestModel = strings.TrimSpace(cfgSnapshot.GetChatModel())+ }++ titleRequest := providers.ChatRequest{+ System: sessionTitleSystemPrompt,+ ExecutionID: "session-title:" + normalizedSessionID,+ MaxTokens: 60,+ Temperature: 0.2,+ Messages: []providers.Message{{+ Role: "user",+ Content: "Title this Pulse Assistant session.\n\nUser message:\n" ++ truncateForSessionTitle(firstUser) ++ "\n\nAssistant reply:\n" ++ truncateForSessionTitle(firstAssistant),+ }},+ }++ // Persisted prompts carry raw resource identifiers; run the same+ // model-boundary sanitizer as a normal turn (local providers unaffected).+ if sanitizer := modelboundary.RequestSanitizerForModel(requestModel, unifiedResourceProvider); sanitizer != nil {+ titleRequest = sanitizer(titleRequest)+ }++ response, err := provider.Chat(ctx, titleRequest)+ if err != nil {+ return fmt.Errorf("generate session title: %w", err)+ }+ if costStore != nil && response != nil && (response.InputTokens != 0 || response.OutputTokens != 0) {+ costStore.Record(cost.UsageEvent{+ Timestamp: time.Now(),+ Provider: provider.Name(),+ RequestModel: requestModel,+ ResponseModel: strings.TrimSpace(response.Model),+ UseCase: "chat",+ InputTokens: response.InputTokens,+ OutputTokens: response.OutputTokens,+ TargetType: "assistant_session_title",+ TargetID: normalizedSessionID,+ })+ }++ title := normalizeGeneratedSessionTitle(response.Content)+ if title == "" {+ return fmt.Errorf("model returned an empty title")+ }++ // Re-check for a concurrent user rename before persisting.+ current, err := sessions.Get(normalizedSessionID)+ if err != nil {+ return err+ }+ if current.Title != "" && current.Title != generateTitle(firstUser) {+ return fmt.Errorf("title customized while generating")+ }++ if _, err := sessions.Rename(normalizedSessionID, title); err != nil {+ return err+ }+ log.Debug().Str("session_id", normalizedSessionID).Str("title", title).Msg("[ChatService] Session title generated")+ return nil+}++// firstSessionExchange returns the first user prompt, the first assistant+// answer that follows it, and the total count of real user prompts (tool+// results excluded).+func firstSessionExchange(messages []Message) (string, string, int) {+ firstUser := ""+ firstAssistant := ""+ userCount := 0+ for _, msg := range messages {+ switch msg.Role {+ case "user":+ if msg.ToolResult != nil {+ continue+ }+ userCount+++ if firstUser == "" {+ firstUser = strings.TrimSpace(msg.Content)+ }+ case "assistant":+ if firstUser != "" && firstAssistant == "" && strings.TrimSpace(msg.Content) != "" {+ firstAssistant = strings.TrimSpace(msg.Content)+ }+ }+ }+ return firstUser, firstAssistant, userCount+}++func truncateForSessionTitle(text string) string {+ text = strings.TrimSpace(text)+ if text == "" {+ return "(empty)"+ }+ runes := []rune(text)+ if len(runes) <= sessionTitleSourceMaxChars {+ return text+ }+ return string(runes[:sessionTitleSourceMaxChars]) + "…"+}++// normalizeGeneratedSessionTitle shapes raw model output into a session title:+// first line only, stripped of wrapping quotes and trailing punctuation, then+// run through the same word-boundary truncation as placeholder titles.+func normalizeGeneratedSessionTitle(raw string) string {+ line := strings.TrimSpace(raw)+ if idx := strings.IndexAny(line, "\r\n"); idx >= 0 {+ line = line[:idx]+ }+ line = strings.Trim(line, "\"'`*# ")+ line = strings.TrimRight(line, ".!,;: ")+ if line == "" {+ return ""+ }+ return generateTitle(line)+}diff --git a/internal/ai/chat/session_title_test.go b/internal/ai/chat/session_title_test.gonew file mode 100644index 0000000000..5117387a5c--- /dev/null+++ b/internal/ai/chat/session_title_test.go@@ -0,0 +1,95 @@+package chat++import (+ "context"+ "testing"++ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++type titleStubProvider struct {+ title string+ calls int+}++func (p *titleStubProvider) Chat(ctx context.Context, req providers.ChatRequest) (*providers.ChatResponse, error) {+ p.calls+++ return &providers.ChatResponse{Content: p.title, Model: req.Model, InputTokens: 10, OutputTokens: 5}, nil+}++func (p *titleStubProvider) TestConnection(ctx context.Context) error { return nil }+func (p *titleStubProvider) Name() string { return "stub" }+func (p *titleStubProvider) ListModels(ctx context.Context) ([]providers.ModelInfo, error) {+ return nil, nil+}+func (p *titleStubProvider) ChatStream(ctx context.Context, req providers.ChatRequest, callback providers.StreamCallback) error {+ return nil+}+func (p *titleStubProvider) SupportsThinking(model string) bool { return false }++func newTitleTestService(t *testing.T, provider providers.StreamingProvider) (*Service, *SessionStore) {+ t.Helper()+ store, err := NewSessionStore(t.TempDir())+ require.NoError(t, err)+ return &Service{sessions: store, provider: provider, started: true}, store+}++func seedFirstExchange(t *testing.T, store *SessionStore, prompt, answer string) *Session {+ t.Helper()+ session, err := store.Create()+ require.NoError(t, err)+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "user", Content: prompt}))+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "assistant", Content: answer}))+ return session+}++func TestGenerateSessionTitleUpgradesPlaceholderAfterFirstExchange(t *testing.T) {+ provider := &titleStubProvider{title: "\"Frigate memory check on delly.\"\nExtra line ignored"}+ svc, store := newTitleTestService(t, provider)+ session := seedFirstExchange(t, store, "how much memory is frigate using on delly right now?", "Frigate uses 1.2 GiB.")++ require.NoError(t, svc.generateSessionTitle(context.Background(), session.ID))++ updated, err := store.Get(session.ID)+ require.NoError(t, err)+ assert.Equal(t, "Frigate memory check on delly", updated.Title)+ assert.Equal(t, 1, provider.calls)+}++func TestGenerateSessionTitleSkipsUserRenamedSessions(t *testing.T) {+ provider := &titleStubProvider{title: "Generated title"}+ svc, store := newTitleTestService(t, provider)+ session := seedFirstExchange(t, store, "check pbs backups", "All PBS jobs succeeded.")+ _, err := store.Rename(session.ID, "My backup investigation")+ require.NoError(t, err)++ err = svc.generateSessionTitle(context.Background(), session.ID)+ require.Error(t, err)+ assert.Equal(t, 0, provider.calls)++ updated, err := store.Get(session.ID)+ require.NoError(t, err)+ assert.Equal(t, "My backup investigation", updated.Title)+}++func TestGenerateSessionTitleSkipsLaterTurns(t *testing.T) {+ provider := &titleStubProvider{title: "Generated title"}+ svc, store := newTitleTestService(t, provider)+ session := seedFirstExchange(t, store, "first prompt", "first answer")+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "user", Content: "second prompt"}))+ require.NoError(t, store.AddMessage(session.ID, Message{Role: "assistant", Content: "second answer"}))++ err := svc.generateSessionTitle(context.Background(), session.ID)+ require.Error(t, err)+ assert.Equal(t, 0, provider.calls)+}++func TestNormalizeGeneratedSessionTitle(t *testing.T) {+ assert.Equal(t, "Disk pressure on minipc", normalizeGeneratedSessionTitle(" \"Disk pressure on minipc.\" "))+ assert.Equal(t, "", normalizeGeneratedSessionTitle(" \n"))+ long := normalizeGeneratedSessionTitle("An extremely verbose session title that keeps going well past the fifty character budget")+ assert.LessOrEqual(t, len([]rune(long)), 53, "should truncate near the 50-char budget (plus ellipsis)")+ assert.Contains(t, long, "...")+}