feat: restore Quick Chat tabs and expose agent goals (#3645)

This commit is contained in:
Carlos Florêncio
2026-09-14 11:32:21 +01:00
committed by GitHub
parent c092acac8b
commit bb784a1d90
68 changed files with 5090 additions and 171 deletions
+14
View File
@@ -73,6 +73,20 @@ func (e *emitter) plan(entries []acp.PlanEntry) {
})
}
// sessionInfo sends the ACP session metadata extension used by goal-aware
// providers. The caller supplies only the provider metadata under _meta.
func (e *emitter) sessionInfo(meta map[string]any) {
_ = e.conn.SessionUpdate(e.ctx, acp.SessionNotification{
SessionId: e.sid,
Update: acp.SessionUpdate{
SessionInfoUpdate: &acp.SessionSessionInfoUpdate{
SessionUpdate: "session_info_update",
Meta: meta,
},
},
})
}
// monitorClaudeMeta builds the `_meta.claudeCode.toolName=Monitor` payload
// claude-agent-acp tags Monitor tool_call notifications with. Used by
// e2e:monitor_* directives to reproduce the wire format exactly so the
+68
View File
@@ -0,0 +1,68 @@
package main
import (
"strings"
"time"
)
const goalObjective = "Coordinate contributor PR reviews and keep the review queue current. " +
"Review the outstanding changes, record the relevant decisions, and continue with the next " +
"review when the current one is complete."
func goalSnapshot(status string, createdAt, updatedAt int64) map[string]any {
return map[string]any{
"objective": goalObjective,
"status": status,
"createdAt": createdAt,
"updatedAt": updatedAt,
"tokenBudget": nil,
"tokensUsed": 42,
"timeUsedSeconds": 3,
"controlMethod": "_session/goal",
}
}
func emitGoalActive(e *emitter, createdAt, updatedAt int64) {
e.sessionInfo(map[string]any{"goal": goalSnapshot("active", createdAt, updatedAt)})
waitForDelay(e.ctx, 250)
e.sessionInfo(map[string]any{
"codex": map[string]any{"threadStatus": "idle"},
})
}
func scenarioGoalActive(e *emitter) {
now := time.Now().UnixMilli()
emitGoalActive(e, now, now)
e.text("The provider goal remains active after the thread becomes idle.")
}
func scenarioGoalComplete(e *emitter) {
now := time.Now().UnixMilli()
emitGoalActive(e, now, now)
waitForDelay(e.ctx, 400)
e.sessionInfo(map[string]any{"goal": goalSnapshot("complete", now, now+1)})
e.text("The provider goal is complete.")
}
func scenarioGoalClear(e *emitter) {
now := time.Now().UnixMilli()
emitGoalActive(e, now, now)
waitForDelay(e.ctx, 400)
e.sessionInfo(map[string]any{"goal": nil})
e.text("The provider goal was cleared.")
}
func scenarioGoalLong(e *emitter) {
now := time.Now().UnixMilli()
longObjective := goalObjective + " " + strings.Repeat("Keep the review context available. ", 80)
e.sessionInfo(map[string]any{
"goal": map[string]any{
"objective": longObjective,
"status": "active",
"createdAt": now,
"updatedAt": now,
"controlMethod": "_session/goal",
},
})
e.text("The provider reported a long active goal.")
}
+63
View File
@@ -0,0 +1,63 @@
package main
import (
"testing"
)
func TestGoalScenariosEmitGoalLifecycleFrames(t *testing.T) {
tests := []struct {
name string
wantGoalUpdates int
wantActive bool
wantFinalStatus string
wantFinalCleared bool
}{
{name: "goal-active", wantGoalUpdates: 1, wantActive: true},
{name: "goal-complete", wantGoalUpdates: 2, wantActive: true, wantFinalStatus: "complete"},
{name: "goal-clear", wantGoalUpdates: 2, wantActive: true, wantFinalCleared: true},
{name: "goal-long", wantGoalUpdates: 1, wantActive: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
emit, updates := newTestEmitter()
scenarioRegistry[tt.name](emit)
goalUpdates := make([]map[string]any, 0)
for _, update := range updates.getUpdates() {
info := update.notification.Update.SessionInfoUpdate
if info == nil {
continue
}
if value, ok := info.Meta["goal"]; ok {
if value == nil {
goalUpdates = append(goalUpdates, nil)
continue
}
goal, ok := value.(map[string]any)
if !ok {
t.Fatalf("goal metadata has type %T", value)
}
goalUpdates = append(goalUpdates, goal)
}
}
if len(goalUpdates) != tt.wantGoalUpdates {
t.Fatalf("goal update count = %d, want %d", len(goalUpdates), tt.wantGoalUpdates)
}
if tt.wantActive {
if goalUpdates[0]["status"] != "active" {
t.Fatalf("first goal status = %v, want active", goalUpdates[0]["status"])
}
}
if tt.wantFinalCleared {
if goalUpdates[len(goalUpdates)-1] != nil {
t.Fatalf("final goal = %v, want clear", goalUpdates[len(goalUpdates)-1])
}
}
if tt.wantFinalStatus != "" && goalUpdates[len(goalUpdates)-1]["status"] != tt.wantFinalStatus {
t.Fatalf("final goal status = %v, want %s", goalUpdates[len(goalUpdates)-1]["status"], tt.wantFinalStatus)
}
})
}
}
+4
View File
@@ -54,6 +54,10 @@ var scenarioRegistry = map[string]func(e *emitter){
"steer-fold-setup": scenarioSteerFoldSetup,
"steer-defer-setup": scenarioSteerDeferSetup,
"saved-prompt-delivery": scenarioSavedPromptDelivery,
"goal-active": scenarioGoalActive,
"goal-complete": scenarioGoalComplete,
"goal-clear": scenarioGoalClear,
"goal-long": scenarioGoalLong,
}
// steerSetupHoldMillis is how long steer-fold-setup and steer-defer-setup
@@ -1209,6 +1209,31 @@ func TestConvertNotification_SessionInfoUpdateFixture(t *testing.T) {
}
}
func TestConvertNotification_SessionInfoUpdateGoalFixture(t *testing.T) {
a := newTestAdapter()
t.Cleanup(func() { _ = a.Close() })
raw := []byte(`{"sessionId":"s1","update":{"sessionUpdate":"session_info_update","_meta":{"goal":{"objective":"Coordinate contributor PR reviews","status":"active","createdAt":1789079689000,"updatedAt":1789287777000,"tokenBudget":null,"tokensUsed":9547009,"timeUsedSeconds":47312,"controlMethod":"_session/goal"}}}}`)
var notification acp.SessionNotification
if err := json.Unmarshal(raw, &notification); err != nil {
t.Fatalf("unmarshal goal fixture: %v", err)
}
if notification.Update.SessionInfoUpdate == nil {
t.Fatal("generated SDK did not decode goal session_info_update")
}
result := a.convertNotification(notification)
if result == nil {
t.Fatal("expected non-nil result for goal session_info_update")
}
goal, ok := result.SessionMeta["goal"].(map[string]any)
if !ok {
t.Fatalf("goal metadata type = %T, want map[string]any", result.SessionMeta["goal"])
}
if goal["status"] != "active" || goal["objective"] != "Coordinate contributor PR reviews" {
t.Fatalf("goal metadata = %#v", goal)
}
}
func TestConvertUsageUpdate_ZeroUsed(t *testing.T) {
a := newTestAdapter()
@@ -787,7 +787,7 @@ func (m *Manager) GetWorkspaceTrackerFor(subpath string) (*WorkspaceTracker, err
}
t := NewWorkspaceTrackerForRepo(full, cleaned, m.logger)
m.configureTracker(t, cleaned, m.currentWorkspaceSourceRoots())
m.prepareTrackerComparisonTarget(t)
m.prepareTrackerComparisonTarget(t, false)
m.workspaceTrackersBySubpath[cleaned] = t
return t, nil
}
@@ -44,10 +44,10 @@ func (m *Manager) getComparisonTargets() map[string]models.ComparisonTarget {
func (m *Manager) PrepareComparisonTargets(_ context.Context) {
root, trackers := m.snapshotTrackers()
if root != nil {
m.prepareTrackerComparisonTarget(root)
m.prepareTrackerComparisonTarget(root, false)
}
for _, tracker := range trackers {
m.prepareTrackerComparisonTarget(tracker)
m.prepareTrackerComparisonTarget(tracker, false)
}
}
@@ -84,7 +84,7 @@ func (m *Manager) RetryUnavailableComparisonTargets() {
resolution.ErrorCode == comparisonTargetErrorInvalid {
continue
}
m.prepareTrackerComparisonTarget(tracker)
m.prepareTrackerComparisonTarget(tracker, true)
}
}
@@ -112,7 +112,7 @@ func (m *Manager) UpdateComparisonTargets(_ context.Context, targets map[string]
if tracker == nil || comparisonTargetMapsEqual(previous, current, tracker.RepositoryName()) {
continue
}
m.prepareTrackerComparisonTarget(tracker)
m.prepareTrackerComparisonTarget(tracker, false)
}
}
@@ -122,7 +122,7 @@ func comparisonTargetMapsEqual(previous, current map[string]models.ComparisonTar
return leftOK == rightOK && (!leftOK || left.Equal(right))
}
func (m *Manager) prepareTrackerComparisonTarget(tracker *WorkspaceTracker) {
func (m *Manager) prepareTrackerComparisonTarget(tracker *WorkspaceTracker, forceRetry bool) {
if tracker == nil {
return
}
@@ -147,13 +147,14 @@ func (m *Manager) prepareTrackerComparisonTarget(tracker *WorkspaceTracker) {
return
}
m.scheduleComparisonTargetOperation(repositoryName, tracker, *target)
m.scheduleComparisonTargetOperation(repositoryName, tracker, *target, forceRetry)
}
func (m *Manager) scheduleComparisonTargetOperation(
repositoryName string,
tracker *WorkspaceTracker,
target models.ComparisonTarget,
forceRetry bool,
) {
m.comparisonTargetOpsMu.Lock()
if m.comparisonTargetOpsStopping {
@@ -175,7 +176,7 @@ func (m *Manager) scheduleComparisonTargetOperation(
return
}
if existing := m.comparisonTargetOps[repositoryName]; existing != nil {
if existing.tracker == tracker && existing.target.Equal(target) {
if existing.tracker == tracker && existing.target.Equal(target) && !forceRetry {
m.comparisonTargetOpsMu.Unlock()
cancel()
release()
@@ -132,6 +132,52 @@ func TestRetryUnavailableComparisonTargetsRecoversOnFreshRequest(t *testing.T) {
}
}
func TestRetryUnavailableComparisonTargetsReplacesStaleMatchingOperation(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
target := comparisonTargetProcessTestTarget()
mgr, markers := newComparisonTargetTestManager(t, repoDir, target, nil)
tracker := mgr.GetWorkspaceTracker()
tracker.SetComparisonTargetUnavailable(&target, comparisonTargetErrorFetch)
tracker.SetGitEnvironment([]string{
comparisonTargetGitShimModeEnv + "=comparison",
"KANDEV_TEST_GIT_LOG=" + markers.commandLog,
"KANDEV_TEST_FETCH_STARTED=" + markers.fetchStarted,
"KANDEV_TEST_STATUS_STARTED=" + markers.statusStarted,
})
// A failed operation publishes unavailable before its deferred cleanup
// removes the operation from the manager. A fresh request in that window
// must replace the stale same-target entry instead of leaving the tracker
// pending forever.
oldCanceled := make(chan struct{})
oldOperation := &comparisonTargetOperation{
target: target,
tracker: tracker,
cancel: func() {
select {
case <-oldCanceled:
default:
close(oldCanceled)
}
},
}
mgr.comparisonTargetOpsMu.Lock()
mgr.comparisonTargetOps = map[string]*comparisonTargetOperation{"": oldOperation}
mgr.comparisonTargetOpsMu.Unlock()
mgr.RetryUnavailableComparisonTargets()
resolution := waitForComparisonResolution(t, tracker, comparisonTargetStatusReady, "")
if resolution.Ref != target.ComparisonRef() {
t.Fatalf("recovered comparison ref = %q, want %q", resolution.Ref, target.ComparisonRef())
}
select {
case <-oldCanceled:
default:
t.Fatal("stale comparison operation was not canceled")
}
}
func TestComparisonTargetPublicationRequiresActiveOperation(t *testing.T) {
repoDir, cleanup := setupTestRepo(t)
t.Cleanup(cleanup)
@@ -190,7 +190,7 @@ func (m *Manager) transitionToMultiRepoMode(ctx context.Context, workDir string,
bareRoot := m.newTrackerForRepo(workDir, "")
m.configureTracker(bareRoot, "", roots)
m.prepareTrackerComparisonTarget(bareRoot)
m.prepareTrackerComparisonTarget(bareRoot, false)
bareRoot.Start(ctx)
for _, sub := range subs {
bareRoot.AttachWorkspaceStreamSubscriber(sub)
@@ -200,7 +200,7 @@ func (m *Manager) transitionToMultiRepoMode(ctx context.Context, workDir string,
for _, child := range children {
tracker := m.newTrackerForRepo(child.path, child.name)
m.configureTracker(tracker, child.name, roots)
m.prepareTrackerComparisonTarget(tracker)
m.prepareTrackerComparisonTarget(tracker, false)
tracker.Start(ctx)
for _, sub := range subs {
tracker.AttachWorkspaceStreamSubscriber(sub)
@@ -247,7 +247,7 @@ func (m *Manager) appendNewRepoTrackers(ctx context.Context, workDir string, chi
zap.String("path", child.path))
tracker := m.newTrackerForRepo(child.path, child.name)
m.configureTracker(tracker, child.name, roots)
m.prepareTrackerComparisonTarget(tracker)
m.prepareTrackerComparisonTarget(tracker, false)
tracker.Start(ctx)
for _, sub := range subs {
tracker.AttachWorkspaceStreamSubscriber(sub)
@@ -312,7 +312,7 @@ func (m *Manager) reconcileRepoTrackers(ctx context.Context, workDir string, chi
}
tracker := m.newTrackerForRepo(child.path, child.name)
m.configureTracker(tracker, child.name, roots)
m.prepareTrackerComparisonTarget(tracker)
m.prepareTrackerComparisonTarget(tracker, false)
tracker.Start(ctx)
for _, sub := range subs {
tracker.AttachWorkspaceStreamSubscriber(sub)
@@ -127,7 +127,7 @@ func (m *Manager) reconcileWorkspaceTrackerGraph(
root = oldRoot
rootReused = true
syncTrackerConfiguration(root, desiredRoot, roots)
m.prepareTrackerComparisonTarget(root)
m.prepareTrackerComparisonTarget(root, false)
desiredRoot.Stop()
}
if !rootReused {
@@ -141,7 +141,7 @@ func (m *Manager) reconcileWorkspaceTrackerGraph(
identity := repositoryTrackerIdentity(desired.RepositoryName(), desired.workDir)
if existing := oldByIdentity[identity]; existing != nil {
syncTrackerConfiguration(existing, desired, roots)
m.prepareTrackerComparisonTarget(existing)
m.prepareTrackerComparisonTarget(existing, false)
desired.Stop()
retained = append(retained, existing)
used[existing] = struct{}{}
@@ -0,0 +1,251 @@
package orchestrator
import (
"encoding/json"
"math"
)
const (
goalKey = "goal"
goalObjectiveMaxSize = 16 * 1024
goalClearWatermarkInfoKey = "_kandev_goal_clear_watermark"
)
func mergeACPGoalMetaWithClearWatermark(
existing, incoming map[string]any,
attachmentChanged bool,
existingClearWatermark any,
) (map[string]any, map[string]any) {
merged := mergeACPGoalMeta(existing, incoming, attachmentChanged)
if attachmentChanged {
return merged, nil
}
watermark := parseACPGoalWatermark(existingClearWatermark)
incomingGoal, incomingHasGoal := incoming[goalKey]
if !incomingHasGoal {
return merged, watermark
}
if incomingGoal == nil {
if existingGoal, ok := parseACPGoal(existing[goalKey]); ok {
return merged, goalWatermark(existingGoal)
}
return merged, watermark
}
parsed, ok := parseACPGoal(incomingGoal)
if !ok {
if existingGoal, existingOK := parseACPGoal(existing[goalKey]); existingOK {
return merged, goalWatermark(existingGoal)
}
return merged, watermark
}
if watermark != nil && !goalIsAtLeastAsFresh(parsed, watermark) {
merged[goalKey] = nil
return merged, watermark
}
return merged, nil
}
func goalWatermark(goal map[string]any) map[string]any {
return map[string]any{
"createdAt": goal["createdAt"],
"updatedAt": goal["updatedAt"],
}
}
func parseACPGoalWatermark(value any) map[string]any {
record, ok := value.(map[string]any)
if !ok {
return nil
}
createdAt, createdOK := goalNumber(record["createdAt"])
updatedAt, updatedOK := goalNumber(record["updatedAt"])
if !createdOK || !updatedOK {
return nil
}
return map[string]any{"createdAt": createdAt, "updatedAt": updatedAt}
}
var supportedGoalStatuses = map[string]struct{}{
"active": {},
"paused": {},
"blocked": {},
"limited": {},
"complete": {},
}
// mergeACPGoalMeta retains the typed goal extension while preserving the
// existing replacement semantics for every other provider metadata key.
func mergeACPGoalMeta(
existing, incoming map[string]any,
attachmentChanged bool,
) map[string]any {
merged := cloneACPMetadata(incoming)
existingGoal, existingHasGoal := existing[goalKey]
incomingGoal, incomingHasGoal := incoming[goalKey]
if attachmentChanged {
if parsed, ok := parseACPGoal(incomingGoal); incomingHasGoal && ok {
merged[goalKey] = parsed
} else {
merged[goalKey] = nil
}
return merged
}
if !incomingHasGoal {
if existingHasGoal {
merged[goalKey] = existingGoal
}
return merged
}
if incomingGoal == nil {
merged[goalKey] = nil
return merged
}
parsed, ok := parseACPGoal(incomingGoal)
if !ok {
// A present but malformed replacement is an explicit non-active
// projection. Retaining an older active goal would misrepresent the
// provider after it has changed or invalidated the goal payload.
merged[goalKey] = nil
return merged
}
if existingParsed, existingOK := parseACPGoal(existingGoal); existingOK && !goalIsAtLeastAsFresh(parsed, existingParsed) {
merged[goalKey] = existingParsed
return merged
}
merged[goalKey] = parsed
return merged
}
func cloneACPMetadata(values map[string]any) map[string]any {
if values == nil {
return map[string]any{}
}
cloned := make(map[string]any, len(values))
for key, value := range values {
cloned[key] = value
}
return cloned
}
func parseACPGoal(value any) (map[string]any, bool) {
record, ok := goalRecord(value)
if !ok {
return nil, false
}
objective, status, createdAt, updatedAt, ok := requiredGoalFields(record)
if !ok {
return nil, false
}
parsed := map[string]any{
"objective": objective,
"status": status,
"createdAt": createdAt,
"updatedAt": updatedAt,
}
if !optionalGoalNumbers(record, parsed) {
return nil, false
}
if !optionalGoalControlMethod(record, parsed) {
return nil, false
}
return parsed, true
}
func goalRecord(value any) (map[string]any, bool) {
if value == nil {
return nil, false
}
record, ok := value.(map[string]any)
return record, ok && record != nil
}
func requiredGoalFields(record map[string]any) (string, string, float64, float64, bool) {
objective, objectiveOK := record["objective"].(string)
if !objectiveOK || objective == "" || len(objective) > goalObjectiveMaxSize {
return "", "", 0, 0, false
}
status, statusOK := record["status"].(string)
if !statusOK {
return "", "", 0, 0, false
}
if _, supported := supportedGoalStatuses[status]; !supported {
return "", "", 0, 0, false
}
createdAt, createdOK := goalNumber(record["createdAt"])
updatedAt, updatedOK := goalNumber(record["updatedAt"])
if !createdOK || !updatedOK {
return "", "", 0, 0, false
}
return objective, status, createdAt, updatedAt, true
}
func optionalGoalNumbers(record, parsed map[string]any) bool {
for _, key := range []string{"tokenBudget", "tokensUsed", "timeUsedSeconds"} {
raw, present := record[key]
if !present || raw == nil {
continue
}
number, valid := goalNumber(raw)
if !valid {
return false
}
parsed[key] = number
}
return true
}
func optionalGoalControlMethod(record, parsed map[string]any) bool {
controlMethod, present := record["controlMethod"]
if !present || controlMethod == nil {
return true
}
method, valid := controlMethod.(string)
if !valid {
return false
}
parsed["controlMethod"] = method
return true
}
func goalNumber(value any) (float64, bool) {
var number float64
switch typed := value.(type) {
case float64:
number = typed
case float32:
number = float64(typed)
case int:
number = float64(typed)
case int64:
number = float64(typed)
case json.Number:
parsed, err := typed.Float64()
if err != nil {
return 0, false
}
number = parsed
default:
return 0, false
}
return number, number >= 0 && !math.IsNaN(number) && !math.IsInf(number, 0)
}
func goalIsAtLeastAsFresh(incoming, existing map[string]any) bool {
incomingCreated, incomingCreatedOK := goalNumber(incoming["createdAt"])
existingCreated, existingCreatedOK := goalNumber(existing["createdAt"])
incomingUpdated, incomingUpdatedOK := goalNumber(incoming["updatedAt"])
existingUpdated, existingUpdatedOK := goalNumber(existing["updatedAt"])
if !incomingCreatedOK || !existingCreatedOK || !incomingUpdatedOK || !existingUpdatedOK {
return false
}
if incomingCreated != existingCreated {
return incomingCreated > existingCreated
}
return incomingUpdated >= existingUpdated
}
@@ -0,0 +1,202 @@
package orchestrator
import (
"context"
"testing"
"github.com/stretchr/testify/require"
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
"github.com/kandev/kandev/internal/events"
)
func testACPGoal(status string, createdAt, updatedAt float64) map[string]any {
return map[string]any{
"objective": "Coordinate contributor PR reviews",
"status": status,
"createdAt": createdAt,
"updatedAt": updatedAt,
}
}
func TestParseACPGoalAcceptsEverySupportedStatus(t *testing.T) {
for _, status := range []string{"active", "paused", "blocked", "limited", "complete"} {
t.Run(status, func(t *testing.T) {
parsed, ok := parseACPGoal(testACPGoal(status, 10, 20))
require.True(t, ok)
require.Equal(t, status, parsed["status"])
})
}
}
func TestParseACPGoalRejectsMalformedSnapshots(t *testing.T) {
cases := []map[string]any{
{"objective": "missing status", "createdAt": float64(10), "updatedAt": float64(20)},
{"objective": "unknown status", "status": "running", "createdAt": float64(10), "updatedAt": float64(20)},
{"objective": "missing created", "status": "active", "updatedAt": float64(20)},
{"objective": "bad updated", "status": "active", "createdAt": float64(10), "updatedAt": "20"},
{"objective": "bad optional", "status": "active", "createdAt": float64(10), "updatedAt": float64(20), "tokensUsed": "many"},
}
for index, value := range cases {
t.Run("case", func(t *testing.T) {
_, ok := parseACPGoal(value)
require.False(t, ok, "case %d must be rejected", index)
})
}
}
func TestMergeACPGoalMetaRejectsOlderSnapshotsAndAllowsNewGoals(t *testing.T) {
existing := map[string]any{"goal": testACPGoal("complete", 100, 200), "keep": true}
older := map[string]any{"goal": testACPGoal("active", 100, 199)}
equal := map[string]any{"goal": testACPGoal("complete", 100, 200)}
newer := map[string]any{"goal": testACPGoal("active", 100, 201)}
require.Equal(t, "complete", mergeACPGoalMeta(existing, older, false)[goalKey].(map[string]any)["status"])
require.Equal(t, "complete", mergeACPGoalMeta(existing, equal, false)[goalKey].(map[string]any)["status"])
require.Equal(t, "active", mergeACPGoalMeta(existing, newer, false)[goalKey].(map[string]any)["status"])
newGoal := testACPGoal("active", 101, 1)
merged := mergeACPGoalMeta(existing, map[string]any{"goal": newGoal}, false)
require.Equal(t, newGoal, merged[goalKey])
}
func TestMergeACPGoalMetaPreservesOrderedClear(t *testing.T) {
active := map[string]any{"goal": testACPGoal("active", 100, 200)}
cleared := mergeACPGoalMeta(active, map[string]any{"goal": nil}, false)
require.Contains(t, cleared, goalKey)
require.Nil(t, cleared[goalKey])
retained := mergeACPGoalMeta(cleared, map[string]any{"codex": map[string]any{"threadStatus": "idle"}}, false)
require.Contains(t, retained, goalKey)
require.Nil(t, retained[goalKey])
}
func TestMergeACPGoalMetaTreatsMalformedReplacementAsInactive(t *testing.T) {
active := map[string]any{"goal": testACPGoal("active", 100, 200)}
malformed := map[string]any{"goal": testACPGoal("running", 100, 201)}
merged := mergeACPGoalMeta(active, malformed, false)
require.Contains(t, merged, goalKey)
require.Nil(t, merged[goalKey])
}
func TestMergeACPGoalMetaKeepsOlderGoalCleared(t *testing.T) {
active := map[string]any{"goal": testACPGoal("active", 100, 200)}
cleared, watermark := mergeACPGoalMetaWithClearWatermark(
active,
map[string]any{"goal": nil},
false,
nil,
)
require.Nil(t, cleared[goalKey])
require.Equal(t, map[string]any{"createdAt": float64(100), "updatedAt": float64(200)}, watermark)
older, retainedWatermark := mergeACPGoalMetaWithClearWatermark(
cleared,
map[string]any{"goal": testACPGoal("active", 100, 199)},
false,
watermark,
)
require.Nil(t, older[goalKey])
require.Equal(t, watermark, retainedWatermark)
newer, noWatermark := mergeACPGoalMetaWithClearWatermark(
cleared,
map[string]any{"goal": testACPGoal("active", 100, 201)},
false,
watermark,
)
require.Equal(t, "active", newer[goalKey].(map[string]any)["status"])
require.Nil(t, noWatermark)
}
func TestMergeACPGoalMetaResetsOnAttachmentChange(t *testing.T) {
active := map[string]any{"goal": testACPGoal("active", 100, 200)}
cleared := mergeACPGoalMeta(active, map[string]any{"codex": "new-attachment"}, true)
require.Nil(t, cleared[goalKey])
newGoal := testACPGoal("active", 1, 2)
attached := mergeACPGoalMeta(active, map[string]any{"goal": newGoal}, true)
require.Equal(t, newGoal, attached[goalKey])
}
func TestHandleSessionInfoEvent_GoalSurvivesUnrelatedMetadata(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "t1", "s1", "step1")
eb := &recordingEventBus{}
svc := createTestService(repo, newMockStepGetter(), newMockTaskRepo())
svc.eventBus = eb
goal := map[string]any{
"objective": "Coordinate contributor PR reviews",
"status": "active",
"createdAt": float64(1789079689000),
"updatedAt": float64(1789287777000),
}
svc.handleSessionInfoEvent(ctx, &lifecycle.AgentStreamEventPayload{
TaskID: "t1",
SessionID: "s1",
Data: &lifecycle.AgentStreamEventData{
ACPSessionID: "acp-1",
SessionMeta: map[string]any{
"goal": goal,
},
},
})
svc.handleSessionInfoEvent(ctx, &lifecycle.AgentStreamEventPayload{
TaskID: "t1",
SessionID: "s1",
Data: &lifecycle.AgentStreamEventData{
SessionMeta: map[string]any{
"codex": map[string]any{"threadStatus": "idle"},
},
},
})
updated, err := repo.GetTaskSession(ctx, "s1")
require.NoError(t, err)
acp, ok := updated.Metadata["acp"].(map[string]interface{})
require.True(t, ok)
meta, ok := acp["meta"].(map[string]interface{})
require.True(t, ok)
require.Equal(t, goal, meta["goal"])
require.Len(t, eb.events, 2)
require.Equal(t, events.BuildSessionInfoSubject("s1"), eb.events[1].subject)
payload, ok := eb.events[1].event.Data.(lifecycle.SessionInfoEventPayload)
require.True(t, ok)
require.Equal(t, goal, payload.SessionMeta["goal"])
}
func TestHandleSessionInfoEvent_DropsObsoleteACPAttachment(t *testing.T) {
ctx := context.Background()
repo := setupTestRepo(t)
seedSession(t, repo, "t1", "s1", "step1")
eb := &recordingEventBus{}
agentManager := &mockAgentManager{
getACPSessionIDForSessionFunc: func(string) (string, bool) {
return "acp-current", true
},
}
svc := createTestServiceWithAgent(repo, newMockStepGetter(), newMockTaskRepo(), agentManager)
svc.eventBus = eb
svc.handleSessionInfoEvent(ctx, &lifecycle.AgentStreamEventPayload{
TaskID: "t1",
SessionID: "s1",
Data: &lifecycle.AgentStreamEventData{
ACPSessionID: "acp-old",
SessionMeta: map[string]any{
"goal": testACPGoal("active", 10, 20),
},
},
})
updated, err := repo.GetTaskSession(ctx, "s1")
require.NoError(t, err)
_, hasACP := updated.Metadata["acp"]
require.False(t, hasACP)
require.Empty(t, eb.events)
}
@@ -3316,6 +3316,14 @@ func (s *Service) handleSessionInfoEvent(ctx context.Context, payload *lifecycle
if !s.resumeAttemptAllowsExecution(payload.SessionID, payload.ExecutionID, payload.AttemptID) {
return
}
if currentACPSessionID := s.currentACPSessionID(payload.SessionID); currentACPSessionID != "" &&
payload.Data.ACPSessionID != "" && payload.Data.ACPSessionID != currentACPSessionID {
s.logger.Info("dropping session info from stale ACP session generation",
zap.String("session_id", payload.SessionID),
zap.String("acp_session_id", payload.Data.ACPSessionID),
zap.String("current_acp_session_id", currentACPSessionID))
return
}
info, err := s.mergedACPSessionInfo(ctx, payload.SessionID, payload.Data)
if err != nil {
s.logger.Warn("failed to read existing ACP session info",
@@ -3375,6 +3383,7 @@ func (s *Service) mergedACPSessionInfo(
}
}
}
existingACPSessionID := stringFromMap(info, "session_id")
if data.ACPSessionID != "" {
info["session_id"] = data.ACPSessionID
}
@@ -3384,8 +3393,27 @@ func (s *Service) mergedACPSessionInfo(
if data.SessionUpdatedAt != "" {
info["updated_at"] = data.SessionUpdatedAt
}
if data.SessionMeta != nil {
info["meta"] = data.SessionMeta
attachmentChanged := data.ACPSessionID != "" &&
existingACPSessionID != "" &&
data.ACPSessionID != existingACPSessionID
if data.SessionMeta != nil || attachmentChanged {
existingMeta, _ := info["meta"].(map[string]any)
incomingMeta := data.SessionMeta
if incomingMeta == nil {
incomingMeta = map[string]any{}
}
mergedMeta, clearWatermark := mergeACPGoalMetaWithClearWatermark(
existingMeta,
incomingMeta,
attachmentChanged,
info[goalClearWatermarkInfoKey],
)
info["meta"] = mergedMeta
if clearWatermark == nil {
delete(info, goalClearWatermarkInfoKey)
} else {
info[goalClearWatermarkInfoKey] = clearWatermark
}
}
return info, nil
}
@@ -277,6 +277,19 @@ describe("QuickChatModal mixed tabs", () => {
expect(tabs[1].querySelector('[role="status"]')).toBeNull();
});
it("does not leave the previous tab content interactive during a pending selection", () => {
useQuickChatModalMock.mockReturnValue({
...defaultQuickChatModalState,
pendingQuickChatOpen: true,
});
render(<QuickChatModal workspaceId={WORKSPACE_ID} />);
expect(screen.getByTestId("quick-chat-selection-loading")).toBeTruthy();
expect(screen.queryByTestId("mock-quick-terminal-view")).toBeNull();
expect(screen.queryByTestId("quick-chat-session-view")).toBeNull();
});
it("uses the same persisted order callback for coarse-pointer moves", () => {
responsiveMock.isFinePointer = false;
render(<QuickChatModal workspaceId={WORKSPACE_ID} />);
@@ -46,14 +46,6 @@ function QuickChatContent({
quickChat,
setQuickChatInitialPrompt,
}: QuickChatContentProps) {
const canCreateConfigurationChat = !quickChat.sessions.some(
(session) => session.kind === "config",
);
const setupKind =
quickChat.activeSession && isQuickChatSetupSessionId(quickChat.activeSession.sessionId)
? quickChat.activeSession.kind
: null;
return (
<>
<QuickChatTabs
@@ -74,59 +66,130 @@ function QuickChatContent({
tabOrder={quickChat.tabOrder}
onTabOrderChange={quickChat.persistTabOrder}
/>
{quickChat.activeKind === "terminal" && quickChat.activeTerminalTab && (
<QuickTerminalTabView
key={quickChat.activeTerminalTab.tabId}
tab={quickChat.activeTerminalTab}
onStateChange={(state) =>
quickChat.handleTerminalStateChange(quickChat.activeTerminalTab!.tabId, state)
}
onDescriptorReady={(descriptor) =>
quickChat.handleTerminalDescriptorReady(quickChat.activeTerminalTab!.tabId, descriptor)
}
/>
)}
{quickChat.activeKind === "conversation" &&
quickChat.activeSessionId &&
quickChat.activeSession &&
!quickChat.activeSessionNeedsAgent && (
<QuickChatSessionView
session={quickChat.activeSession}
onInitialPromptAttempted={() =>
setQuickChatInitialPrompt(quickChat.activeSessionId!, undefined)
}
/>
)}
{quickChat.activeKind === "conversation" &&
quickChat.activeSessionNeedsAgent &&
setupKind === "chat" && (
<QuickChatSetup
key={`${workspaceId}:${quickChat.setupKey}`}
workspaceId={workspaceId}
canCreateConfigurationChat={canCreateConfigurationChat}
pendingAgentId={quickChat.pendingAgentId}
onStart={quickChat.handleSelectAgent}
onCancel={() => quickChat.handleOpenChange(false)}
onKindChange={quickChat.handleSetupKindChange}
/>
)}
{quickChat.activeKind === "conversation" &&
quickChat.activeSessionNeedsAgent &&
setupKind === "config" && (
<ConfigChatSetup
key={`${workspaceId}:config:${quickChat.setupKey}`}
defaultProfileId={configChat.defaultProfileId}
isStarting={configChat.isStarting}
error={configChat.error}
onStart={(profileId, prompt) => configChat.startSession(profileId, prompt)}
onCancel={() => quickChat.handleOpenChange(false)}
onKindChange={quickChat.handleSetupKindChange}
/>
)}
<QuickChatActiveContent
workspaceId={workspaceId}
configChat={configChat}
quickChat={quickChat}
setQuickChatInitialPrompt={setQuickChatInitialPrompt}
/>
</>
);
}
function QuickChatActiveContent({
workspaceId,
configChat,
quickChat,
setQuickChatInitialPrompt,
}: QuickChatContentProps) {
const canCreateConfigurationChat = !quickChat.sessions.some(
(session) => session.kind === "config",
);
if (quickChat.pendingQuickChatOpen) return <QuickChatSelectionLoading />;
return (
<>
<QuickChatTerminalContent quickChat={quickChat} />
<QuickChatConversationContent
workspaceId={workspaceId}
configChat={configChat}
quickChat={quickChat}
setQuickChatInitialPrompt={setQuickChatInitialPrompt}
canCreateConfigurationChat={canCreateConfigurationChat}
/>
</>
);
}
function QuickChatSelectionLoading() {
const { t } = useTranslation();
return (
<div
aria-live="polite"
className="flex min-h-0 flex-1 items-center justify-center text-sm text-muted-foreground"
data-testid="quick-chat-selection-loading"
>
{t("common:loading")}
</div>
);
}
function QuickChatTerminalContent({
quickChat,
}: {
quickChat: QuickChatContentProps["quickChat"];
}) {
if (quickChat.activeKind !== "terminal" || !quickChat.activeTerminalTab) return null;
const tab = quickChat.activeTerminalTab;
return (
<QuickTerminalTabView
key={tab.tabId}
tab={tab}
onStateChange={(state) => quickChat.handleTerminalStateChange(tab.tabId, state)}
onDescriptorReady={(descriptor) =>
quickChat.handleTerminalDescriptorReady(tab.tabId, descriptor)
}
/>
);
}
function QuickChatConversationContent({
workspaceId,
configChat,
quickChat,
setQuickChatInitialPrompt,
canCreateConfigurationChat,
}: QuickChatContentProps & { canCreateConfigurationChat: boolean }) {
if (
quickChat.activeKind !== "conversation" ||
!quickChat.activeSessionId ||
!quickChat.activeSession
) {
return null;
}
const setupKind = isQuickChatSetupSessionId(quickChat.activeSession.sessionId)
? quickChat.activeSession.kind
: null;
if (!quickChat.activeSessionNeedsAgent) {
return (
<QuickChatSessionView
session={quickChat.activeSession}
onInitialPromptAttempted={() =>
setQuickChatInitialPrompt(quickChat.activeSessionId!, undefined)
}
/>
);
}
if (setupKind === "chat") {
return (
<QuickChatSetup
key={`${workspaceId}:${quickChat.setupKey}`}
workspaceId={workspaceId}
canCreateConfigurationChat={canCreateConfigurationChat}
pendingAgentId={quickChat.pendingAgentId}
onStart={quickChat.handleSelectAgent}
onCancel={() => quickChat.handleOpenChange(false)}
onKindChange={quickChat.handleSetupKindChange}
/>
);
}
if (setupKind === "config") {
return (
<ConfigChatSetup
key={`${workspaceId}:config:${quickChat.setupKey}`}
defaultProfileId={configChat.defaultProfileId}
isStarting={configChat.isStarting}
error={configChat.error}
onStart={(profileId, prompt) => configChat.startSession(profileId, prompt)}
onCancel={() => quickChat.handleOpenChange(false)}
onKindChange={quickChat.handleSetupKindChange}
/>
);
}
return null;
}
function QuickChatResizeHandle({
edge,
onMouseDown,
@@ -65,6 +65,7 @@ function makeAppState() {
}>,
activeSessionId: "",
activeKind: "conversation" as const,
pendingQuickChatOpen: null,
activeTerminalTabId: null,
terminalTabs: [] as QuickTerminalTab[],
tabOrderByWorkspace: {} as Record<string, string[]>,
@@ -98,6 +99,7 @@ function makeStore(overrides: Partial<MockStore> = {}): MockStore {
terminalTabs: [],
activeSessionId: "",
activeKind: "conversation",
pendingQuickChatOpen: null,
activeTerminalTabId: null,
closeQuickChat: vi.fn(),
closeQuickChatSession: vi.fn(),
@@ -32,6 +32,7 @@ function useQuickChatStore(workspaceId: string) {
activeSessionId: s.quickChat.activeSessionId,
activeKind: s.quickChat.activeKind,
activeTerminalTabId: s.quickChat.activeTerminalTabId,
pendingQuickChatOpen: s.quickChat.pendingOpen,
terminalTabs: s.quickChat.terminalTabs,
closeQuickChat: s.closeQuickChat,
closeQuickChatSession: s.closeQuickChatSession,
@@ -434,6 +435,7 @@ export function useQuickChatModal(workspaceId: string, onSupersedeConfigStart =
terminalTabs,
activeKind: store.activeKind,
activeTerminalTabId: activeTerminalTab?.tabId ?? null,
pendingQuickChatOpen: store.pendingQuickChatOpen,
activeTerminalTab,
activeSessionId: activeSession?.sessionId ?? null,
activeSession,
@@ -0,0 +1,77 @@
import { act, cleanup, render, screen } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { AgentGoal } from "@/lib/agent-goal";
import { AgentGoalChip } from "./agent-goal-chip";
type Listener = () => void;
const listeners = new Set<Listener>();
let pointer: "fine" | "coarse" = "fine";
function installViewport(): void {
Object.defineProperty(window, "innerWidth", {
configurable: true,
writable: true,
value: 1024,
});
window.matchMedia = vi.fn((query: string) => {
let matches = false;
if (query.includes("pointer: fine")) matches = pointer === "fine";
else if (query.includes("min-width")) matches = true;
return {
media: query,
matches,
onchange: null,
addEventListener: vi.fn((_event: string, listener: Listener) => listeners.add(listener)),
removeEventListener: vi.fn((_event: string, listener: Listener) =>
listeners.delete(listener),
),
addListener: vi.fn(),
removeListener: vi.fn(),
dispatchEvent: vi.fn(),
} as unknown as MediaQueryList;
});
}
function setPointer(next: "fine" | "coarse"): void {
pointer = next;
installViewport();
act(() => {
for (const listener of listeners) listener();
});
}
function activeGoal(): AgentGoal {
return {
objective: "Coordinate contributor PR reviews",
status: "active",
createdAt: 10,
updatedAt: 20,
};
}
beforeEach(() => {
listeners.clear();
pointer = "fine";
installViewport();
});
afterEach(() => {
cleanup();
listeners.clear();
vi.restoreAllMocks();
});
describe("AgentGoalChip responsive subscription", () => {
it("changes disclosure surface when pointer mode changes while mounted", () => {
render(<AgentGoalChip goal={activeGoal()} />);
expect(screen.getByTestId("agent-goal-chip").className).toContain("h-6");
setPointer("coarse");
expect(screen.getByTestId("agent-goal-chip").className).toContain("min-h-11");
setPointer("fine");
expect(screen.getByTestId("agent-goal-chip").className).toContain("h-6");
});
});
@@ -0,0 +1,133 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
import type { AgentGoal } from "@/lib/agent-goal";
import { AgentGoalChip } from "./agent-goal-chip";
const responsiveMock = vi.hoisted(() => ({
isMobile: false,
isFinePointer: true,
}));
const GOAL_CHIP_TEST_ID = "agent-goal-chip";
const GOAL_POPOVER_TEST_ID = "agent-goal-popover";
const GOAL_OBJECTIVE = "Coordinate contributor PR reviews";
const GOAL_CONTINUATION = "The agent may continue automatically between replies.";
vi.mock("@/hooks/use-compact-task-chrome", () => ({
useTouchDrawer: () => !responsiveMock.isFinePointer,
}));
vi.mock("@/hooks/use-responsive-breakpoint", () => ({
useResponsiveBreakpoint: () => ({
breakpoint: responsiveMock.isMobile ? "mobile" : "desktop",
isMobile: responsiveMock.isMobile,
isTablet: false,
isDesktop: !responsiveMock.isMobile,
isCompactDesktop: false,
isFullDesktop: !responsiveMock.isMobile,
isFinePointer: responsiveMock.isFinePointer,
usesDesktopWorkbench: !responsiveMock.isMobile,
}),
}));
function activeGoal(overrides: Partial<AgentGoal> = {}): AgentGoal {
return {
objective: GOAL_OBJECTIVE,
status: "active",
createdAt: 10,
updatedAt: 20,
...overrides,
};
}
beforeEach(() => {
responsiveMock.isMobile = false;
responsiveMock.isFinePointer = true;
});
afterEach(() => {
cleanup();
});
describe("AgentGoalChip", () => {
it("opens the goal details on desktop hover", async () => {
render(<AgentGoalChip goal={activeGoal()} />);
const trigger = screen.getByTestId(GOAL_CHIP_TEST_ID);
expect(trigger.className).toContain("h-6");
fireEvent.mouseEnter(trigger);
const details = await screen.findByTestId(GOAL_POPOVER_TEST_ID);
expect(details.textContent).toContain(GOAL_OBJECTIVE);
expect(details.textContent).toContain(GOAL_CONTINUATION);
});
it("uses a phone drawer with a large touch target", async () => {
responsiveMock.isMobile = true;
responsiveMock.isFinePointer = true;
render(<AgentGoalChip goal={activeGoal()} />);
const trigger = screen.getByTestId(GOAL_CHIP_TEST_ID);
expect(trigger.className).toContain("min-h-11");
expect(trigger.className).toContain("min-w-11");
fireEvent.click(trigger);
const details = await screen.findByTestId("agent-goal-drawer-content");
expect(details.textContent).toContain(GOAL_OBJECTIVE);
expect(screen.getByRole("button", { name: "Close goal details" }).className).toContain(
"[@media(pointer:coarse)]:min-h-11",
);
});
it("does not close the touch drawer when the trigger loses hover state", () => {
vi.useFakeTimers();
try {
responsiveMock.isFinePointer = false;
render(<AgentGoalChip goal={activeGoal()} />);
const trigger = screen.getByTestId(GOAL_CHIP_TEST_ID);
fireEvent.click(trigger);
expect(screen.getByTestId("agent-goal-drawer-content")).toBeTruthy();
fireEvent.mouseLeave(trigger);
act(() => vi.advanceTimersByTime(150));
expect(screen.getByTestId("agent-goal-drawer-content")).toBeTruthy();
} finally {
vi.useRealTimers();
}
});
it("keeps hover details open while crossing into the popover", () => {
vi.useFakeTimers();
try {
render(<AgentGoalChip goal={activeGoal()} />);
const trigger = screen.getByTestId(GOAL_CHIP_TEST_ID);
fireEvent.mouseEnter(trigger);
const details = screen.getByTestId(GOAL_POPOVER_TEST_ID);
fireEvent.mouseLeave(trigger);
fireEvent.mouseEnter(details);
act(() => vi.advanceTimersByTime(150));
expect(screen.getByTestId(GOAL_POPOVER_TEST_ID)).toBe(details);
fireEvent.mouseLeave(details);
act(() => vi.advanceTimersByTime(150));
expect(screen.queryByTestId(GOAL_POPOVER_TEST_ID)).toBeNull();
} finally {
vi.useRealTimers();
}
});
it("uses the drawer for coarse pointers and hides non-active goals", () => {
responsiveMock.isFinePointer = false;
const { rerender } = render(<AgentGoalChip goal={activeGoal()} />);
expect(screen.getByTestId(GOAL_CHIP_TEST_ID).className).toContain("min-h-11");
rerender(<AgentGoalChip goal={activeGoal({ status: "paused" })} />);
expect(screen.queryByTestId(GOAL_CHIP_TEST_ID)).toBeNull();
});
});
@@ -0,0 +1,327 @@
"use client";
import {
forwardRef,
useEffect,
useId,
useRef,
useState,
type ComponentPropsWithoutRef,
type ForwardedRef,
type ReactNode,
} from "react";
import { IconTarget, IconX } from "@tabler/icons-react";
import { Button } from "@kandev/ui/button";
import {
Drawer,
DrawerClose,
DrawerContent,
DrawerDescription,
DrawerHeader,
DrawerTitle,
DrawerTrigger,
} from "@kandev/ui/drawer";
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
import { useTranslation } from "react-i18next";
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
import type { AgentGoal } from "@/lib/agent-goal";
import { cn } from "@/lib/utils";
type AgentGoalDetailsProps = {
goal: AgentGoal;
drawer?: boolean;
};
function AgentGoalDetails({ goal, drawer = false }: AgentGoalDetailsProps) {
const { t } = useTranslation();
return (
<div
data-testid="agent-goal-details"
className={cn("space-y-2", drawer && "min-h-0 overflow-y-auto p-4")}
data-vaul-no-drag={drawer ? true : undefined}
>
<div className="flex items-center justify-between gap-2">
<span className="font-medium text-foreground">{t("task:goalDetailsTitle")}</span>
<span className="shrink-0 text-[11px] text-primary">{t("task:goalStatusActive")}</span>
</div>
<p
data-testid="agent-goal-objective"
className="max-h-48 overflow-y-auto whitespace-pre-wrap text-foreground [overflow-wrap:anywhere]"
>
{goal.objective}
</p>
<p className="text-muted-foreground">{t("task:goalContinuationExplanation")}</p>
</div>
);
}
export type AgentGoalChipProps = {
goal: AgentGoal | null;
};
type AgentGoalTriggerProps = {
detailsId: string;
open: boolean;
restoringFocusRef: { current: boolean };
setOpen: (open: boolean) => void;
suppressHoverRef: { current: boolean };
triggerRef: { current: HTMLButtonElement | null };
triggerWasFocusedRef: { current: boolean };
onHoverChange: (hovered: boolean) => void;
usesDrawer: boolean;
} & Omit<ComponentPropsWithoutRef<"button">, "ref">;
const AgentGoalTrigger = forwardRef<HTMLButtonElement, AgentGoalTriggerProps>(
function AgentGoalTrigger(
{
detailsId,
open,
restoringFocusRef,
setOpen,
suppressHoverRef,
triggerRef,
triggerWasFocusedRef,
onHoverChange,
usesDrawer,
...buttonProps
},
forwardedRef: ForwardedRef<HTMLButtonElement>,
) {
const { t } = useTranslation();
return (
<button
{...buttonProps}
type="button"
ref={(node) => {
triggerRef.current = node;
if (typeof forwardedRef === "function") forwardedRef(node);
else if (forwardedRef) forwardedRef.current = node;
}}
data-testid="agent-goal-chip"
aria-label={t("task:goalActive")}
aria-haspopup="dialog"
aria-expanded={open}
aria-controls={detailsId}
onMouseEnter={() => {
if (usesDrawer) return;
onHoverChange(true);
if (!suppressHoverRef.current) setOpen(true);
}}
onMouseLeave={() => {
if (usesDrawer) return;
onHoverChange(false);
suppressHoverRef.current = false;
}}
onFocus={() => {
if (!usesDrawer) {
if (restoringFocusRef.current) {
restoringFocusRef.current = false;
return;
}
triggerWasFocusedRef.current = true;
setOpen(true);
}
}}
onKeyDown={(event) => {
if (!usesDrawer && event.key === "Escape") {
event.preventDefault();
event.stopPropagation();
suppressHoverRef.current = true;
setOpen(false);
}
}}
className={cn(
buttonProps.className,
"inline-flex items-center justify-center gap-1 rounded-full border border-primary/40 bg-primary/10 text-[11px] font-medium text-primary transition-colors hover:bg-primary/15 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50",
usesDrawer ? "min-h-11 min-w-11 px-3" : "h-6 px-2",
)}
>
<IconTarget className="h-3.5 w-3.5" aria-hidden="true" />
<span>{t("task:goalActive")}</span>
</button>
);
},
);
type AgentGoalPopoverProps = {
children: ReactNode;
detailsId: string;
goal: AgentGoal;
open: boolean;
setOpen: (open: boolean) => void;
suppressHoverRef: { current: boolean };
triggerRef: { current: HTMLButtonElement | null };
triggerWasFocusedRef: { current: boolean };
restoringFocusRef: { current: boolean };
onHoverChange: (hovered: boolean) => void;
};
function AgentGoalPopover({
children,
detailsId,
goal,
open,
setOpen,
suppressHoverRef,
triggerRef,
triggerWasFocusedRef,
restoringFocusRef,
onHoverChange,
}: AgentGoalPopoverProps) {
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>{children}</PopoverTrigger>
<PopoverContent
id={detailsId}
data-testid="agent-goal-popover"
side="top"
align="start"
className="w-80 max-w-[calc(100vw-1rem)] p-3"
onCloseAutoFocus={(event) => {
event.preventDefault();
suppressHoverRef.current = true;
if (triggerWasFocusedRef.current) {
restoringFocusRef.current = true;
triggerRef.current?.focus();
}
triggerWasFocusedRef.current = false;
}}
onEscapeKeyDown={(event) => {
event.preventDefault();
event.stopPropagation();
suppressHoverRef.current = true;
setOpen(false);
}}
onMouseEnter={() => onHoverChange(true)}
onMouseLeave={() => onHoverChange(false)}
>
<AgentGoalDetails goal={goal} />
</PopoverContent>
</Popover>
);
}
type AgentGoalDrawerProps = {
children: ReactNode;
detailsId: string;
goal: AgentGoal;
open: boolean;
setOpen: (open: boolean) => void;
};
function AgentGoalDrawer({ children, detailsId, goal, open, setOpen }: AgentGoalDrawerProps) {
const { t } = useTranslation();
return (
<Drawer open={open} onOpenChange={setOpen}>
<DrawerTrigger asChild>{children}</DrawerTrigger>
<DrawerContent
id={detailsId}
data-testid="agent-goal-drawer-content"
className="max-h-[min(80dvh,calc(100dvh-env(safe-area-inset-bottom)))]"
>
<DrawerHeader className="shrink-0 flex-row items-center justify-between gap-3 text-left">
<div className="min-w-0">
<DrawerTitle>{t("task:goalDetailsTitle")}</DrawerTitle>
<DrawerDescription>{t("task:goalDetailsDescription")}</DrawerDescription>
</div>
<DrawerClose asChild>
<Button
type="button"
variant="ghost"
size="icon-sm"
aria-label={t("task:goalCloseDetails")}
className="[@media(pointer:coarse)]:min-h-11 [@media(pointer:coarse)]:min-w-11"
>
<IconX aria-hidden="true" />
</Button>
</DrawerClose>
</DrawerHeader>
<AgentGoalDetails goal={goal} drawer />
</DrawerContent>
</Drawer>
);
}
export function AgentGoalChip({ goal }: AgentGoalChipProps) {
const { isFinePointer, isMobile } = useResponsiveBreakpoint();
const usesDrawer = !isFinePointer || isMobile;
const [open, setOpen] = useState(false);
const suppressHoverRef = useRef(false);
const triggerRef = useRef<HTMLButtonElement>(null);
const triggerWasFocusedRef = useRef(false);
const restoringFocusRef = useRef(false);
const triggerHoveredRef = useRef(false);
const contentHoveredRef = useRef(false);
const hoverCloseTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const detailsId = `agent-goal-details-${useId()}`;
const isActive = goal?.status === "active";
useEffect(() => {
if (!isActive) setOpen(false);
}, [isActive]);
useEffect(
() => () => {
if (hoverCloseTimerRef.current !== null) clearTimeout(hoverCloseTimerRef.current);
},
[],
);
if (!isActive || !goal) return null;
const setHoverPresence = (region: "trigger" | "content", hovered: boolean) => {
if (region === "trigger") triggerHoveredRef.current = hovered;
else contentHoveredRef.current = hovered;
if (hovered) {
if (hoverCloseTimerRef.current !== null) {
clearTimeout(hoverCloseTimerRef.current);
hoverCloseTimerRef.current = null;
}
return;
}
if (triggerHoveredRef.current || contentHoveredRef.current) return;
if (hoverCloseTimerRef.current !== null) clearTimeout(hoverCloseTimerRef.current);
hoverCloseTimerRef.current = setTimeout(() => {
hoverCloseTimerRef.current = null;
if (!triggerHoveredRef.current && !contentHoveredRef.current) setOpen(false);
}, 100);
};
const trigger = (
<AgentGoalTrigger
detailsId={detailsId}
open={open}
restoringFocusRef={restoringFocusRef}
setOpen={setOpen}
suppressHoverRef={suppressHoverRef}
triggerRef={triggerRef}
triggerWasFocusedRef={triggerWasFocusedRef}
onHoverChange={(hovered) => setHoverPresence("trigger", hovered)}
usesDrawer={usesDrawer}
/>
);
if (usesDrawer) {
return (
<AgentGoalDrawer detailsId={detailsId} goal={goal} open={open} setOpen={setOpen}>
{trigger}
</AgentGoalDrawer>
);
}
return (
<AgentGoalPopover
detailsId={detailsId}
goal={goal}
open={open}
setOpen={setOpen}
suppressHoverRef={suppressHoverRef}
triggerRef={triggerRef}
triggerWasFocusedRef={triggerWasFocusedRef}
restoringFocusRef={restoringFocusRef}
onHoverChange={(hovered) => setHoverPresence("content", hovered)}
>
{trigger}
</AgentGoalPopover>
);
}
@@ -0,0 +1,140 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { cleanup, render, screen } from "@testing-library/react";
import { useSyncExternalStore, type ComponentProps } from "react";
import { ChatStatusBar, shouldRenderChatStatusBar } from "./chat-status-bar";
const statusStore = vi.hoisted(() => {
const state = {
userSettings: { showTranscriptAutoScrollControl: false },
taskSessions: {
items: {
"session-1": {
id: "session-1",
task_id: "",
state: "IDLE",
metadata: {
acp: {
meta: {
goal: {
objective: "Coordinate contributor PR reviews",
status: "active",
createdAt: 10,
updatedAt: 20,
},
},
},
},
},
},
},
};
const listeners = new Set<() => void>();
return {
state,
subscribe(listener: () => void) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
});
vi.mock("@/components/state-provider", () => ({
useAppStore: <T,>(selector: (state: typeof statusStore.state) => T) =>
useSyncExternalStore(
statusStore.subscribe,
() => selector(statusStore.state),
() => selector(statusStore.state),
),
}));
vi.mock("@/components/task/workflow-move-proceed-button", () => ({
WorkflowMoveProceedButton: () => null,
}));
vi.mock("@/components/github/pr-status-chip", () => ({ PRStatusChip: () => null }));
vi.mock("@/components/gitlab/mr-status-chip", () => ({ MRStatusChip: () => null }));
vi.mock("@/components/task/task-dependency-chip", () => ({ TaskDependencyChip: () => null }));
vi.mock("@/components/azure-devops/azure-devops-task-pull-request-chip", () => ({
AzureDevOpsTaskPullRequestChip: () => null,
}));
vi.mock("@/components/integrations/registered-change-request-status", () => ({
RegisteredChangeRequestStatus: () => <span data-testid="registered-review-status" />,
}));
vi.mock("@/components/task/share/share-button", () => ({
shareableSessionStateClient: () => false,
}));
vi.mock("@/components/task/chat/transcript-nav-group", () => ({
TranscriptNavGroup: () => null,
}));
vi.mock("@/components/threads/open-in-threads-button", () => ({
OpenInThreadsButton: () => null,
}));
vi.mock("@/hooks/domains/threads/use-deck-thread", () => ({ useIsDeckThread: () => false }));
vi.mock("./todo-indicator", () => ({ TodoIndicator: () => null }));
vi.mock("./auto-scroll-toggle-button", () => ({ AutoScrollToggleButton: () => null }));
vi.mock("./pr-archive-banners", () => ({
PRMergedBanner: () => null,
PRClosedBanner: () => null,
}));
vi.mock("./task-autopilot-chat-chip", () => ({
AutopilotChatChip: () => null,
useTaskAutopilot: () => false,
}));
vi.mock("./agent-goal-chip", () => ({
AgentGoalChip: ({ goal }: { goal: { objective: string } | null }) =>
goal ? <span data-testid="agent-goal-chip">{goal.objective}</span> : null,
}));
afterEach(cleanup);
function renderStatus(overrides: Partial<ComponentProps<typeof ChatStatusBar>> = {}) {
return render(
<ChatStatusBar
todoItems={[]}
taskId={null}
sessionId="session-1"
sessionState="IDLE"
nextStepName={null}
onProceed={vi.fn()}
isAgentBusy={false}
hasPendingClarification={false}
isMoving={false}
{...overrides}
/>,
);
}
describe("chat status bar goal visibility", () => {
it("renders when the active goal is the only status item", () => {
renderStatus();
expect(screen.getByTestId("chat-status-bar")).toBeTruthy();
expect(screen.getByTestId("agent-goal-chip").textContent).toContain(
"Coordinate contributor PR reviews",
);
});
it("places the goal after review status and before the queue chip", () => {
renderStatus({ queueChip: <span data-testid="queue-chip" /> });
const row = screen.getByTestId("chat-status-bar");
const order = Array.from(row.children).map((child) => child.getAttribute("data-testid"));
expect(order.indexOf("registered-review-status")).toBeLessThan(
order.indexOf("agent-goal-chip"),
);
expect(order.indexOf("agent-goal-chip")).toBeLessThan(order.indexOf("queue-chip"));
});
it("counts an active goal when deciding whether the row is needed", () => {
expect(
shouldRenderChatStatusBar({
hasTask: false,
hasTodos: false,
hasQueueChip: false,
showRightControls: false,
showProceed: false,
hasGoal: true,
}),
).toBe(true);
});
});
@@ -10,7 +10,7 @@
* indicators, so nothing here participates in composing or sending a message.
*/
import type { ReactNode } from "react";
import { useMemo, type ReactNode } from "react";
import { useAppStore } from "@/components/state-provider";
import { WorkflowMoveProceedButton } from "@/components/task/workflow-move-proceed-button";
import type { WorkflowMoveEntryOptions } from "@/lib/api/domains/kanban-api";
@@ -27,7 +27,9 @@ import { TodoIndicator } from "./todo-indicator";
import { AutoScrollToggleButton } from "./auto-scroll-toggle-button";
import { PRMergedBanner, PRClosedBanner } from "./pr-archive-banners";
import { AutopilotChatChip, useTaskAutopilot } from "./task-autopilot-chat-chip";
import { AgentGoalChip } from "./agent-goal-chip";
import { shouldShowProceed } from "./types";
import { getAgentGoal } from "@/lib/agent-goal";
import { useComposerDisclosureContext } from "./composer-disclosure";
import { cn } from "@/lib/utils";
@@ -60,14 +62,22 @@ export function shouldRenderChatStatusBar({
hasQueueChip,
showRightControls,
showProceed,
hasGoal,
}: {
hasTask: boolean;
hasTodos: boolean;
hasQueueChip: boolean;
showRightControls: boolean;
showProceed: boolean;
hasGoal?: boolean;
}): boolean {
return hasTask || hasTodos || hasQueueChip || showRightControls || showProceed;
return hasTask || hasTodos || hasQueueChip || showRightControls || showProceed || !!hasGoal;
}
function readACPMetadata(metadata: Record<string, unknown> | null | undefined): unknown {
const acp = metadata?.acp;
if (!acp || typeof acp !== "object" || Array.isArray(acp)) return undefined;
return (acp as Record<string, unknown>).meta;
}
function getRightControlVisibility({
@@ -168,6 +178,13 @@ export function ChatStatusBar({
// Asked here rather than inside the button so the cluster still renders when
// the Threads jump is the only right-hand control this session qualifies for.
const showThreadsLink = useIsDeckThread(taskId, sessionId);
const activeGoalMetadata = useAppStore((state) =>
sessionId ? readACPMetadata(state.taskSessions.items[sessionId]?.metadata) : undefined,
);
const activeGoal = useMemo(() => {
const goal = getAgentGoal(activeGoalMetadata);
return goal?.status === "active" ? goal : null;
}, [activeGoalMetadata]);
const { canShare, showRightControls } = getRightControlVisibility({
taskId,
sessionId,
@@ -184,6 +201,7 @@ export function ChatStatusBar({
hasQueueChip: !!queueChip,
showRightControls,
showProceed,
hasGoal: !!activeGoal,
})
) {
return null;
@@ -198,6 +216,7 @@ export function ChatStatusBar({
{autopilot && <AutopilotChatChip />}
<TaskDependencyChip taskId={taskId} />
{!separateCI && <ComposerCIStatus taskId={taskId} sessionId={sessionId} />}
{activeGoal && <AgentGoalChip key={sessionId ?? "none"} goal={activeGoal} />}
{queueChip}
{/* Distinct per-banner keys: the key remounts the banner on task switch
so its dismissed state re-initialises, and keeping the two suffixes
+114
View File
@@ -0,0 +1,114 @@
import { expect, test } from "../../fixtures/test-base";
import { openTaskSession } from "../../helpers/session";
import { openQuickChatWithAgent, sendQuickChatMessage } from "./quick-chat-helpers";
const GOAL_OBJECTIVE_FRAGMENT = "Coordinate contributor PR reviews";
const GOAL_CONTINUATION_COPY = "The agent may continue automatically between replies.";
test.describe("agent goal visibility", () => {
test("keeps an active goal visible in task chat across idle and reload", async ({
testPage,
apiClient,
seedData,
}) => {
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
`Agent goal task ${Date.now()}`,
seedData.agentProfileId,
{
description: "/e2e:goal-active",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
if (!task.session_id) throw new Error("goal task did not return a session id");
let session = await openTaskSession(testPage, task.id);
const chip = () => session.activeChat().getByTestId("agent-goal-chip");
await expect(chip()).toBeVisible({ timeout: 30_000 });
await chip().hover();
const popover = testPage.getByTestId("agent-goal-popover");
await expect(popover).toBeVisible();
await expect(popover).toContainText(GOAL_OBJECTIVE_FRAGMENT);
await expect(popover).toContainText(GOAL_CONTINUATION_COPY);
await testPage.keyboard.press("Escape");
await expect(popover).toBeHidden();
await chip().focus();
await expect(popover).toBeVisible();
await testPage.keyboard.press("Escape");
await expect(popover).toBeHidden();
await testPage.reload();
session = await openTaskSession(testPage, task.id);
await expect(session.activeChat().getByTestId("agent-goal-chip")).toBeVisible({
timeout: 30_000,
});
await session.sendMessageViaButton("/e2e:goal-complete");
await session.expectChatResponseVisible("The provider goal is complete.", 0, {
timeout: 30_000,
});
await expect(session.activeChat().getByTestId("agent-goal-chip")).toBeHidden({
timeout: 15_000,
});
await session.sendMessageViaButton("/e2e:goal-active");
await expect(session.activeChat().getByTestId("agent-goal-chip")).toBeVisible({
timeout: 30_000,
});
await session.sendMessageViaButton("/e2e:goal-clear");
await session.expectChatResponseVisible("The provider goal was cleared.", 0, {
timeout: 30_000,
});
await expect(session.activeChat().getByTestId("agent-goal-chip")).toBeHidden({
timeout: 15_000,
});
});
test("contains a long objective in the desktop disclosure", async ({
testPage,
apiClient,
seedData,
}) => {
const task = await apiClient.createTaskWithAgent(
seedData.workspaceId,
`Long agent goal ${Date.now()}`,
seedData.agentProfileId,
{
description: "/e2e:goal-long",
workflow_id: seedData.workflowId,
workflow_step_id: seedData.startStepId,
repository_ids: [seedData.repositoryId],
},
);
await openTaskSession(testPage, task.id);
const chip = testPage.getByTestId("agent-goal-chip");
await expect(chip).toBeVisible({ timeout: 30_000 });
await chip.hover();
const objective = testPage.getByTestId("agent-goal-objective");
await expect(objective).toBeVisible();
await expect(objective).toContainText(GOAL_OBJECTIVE_FRAGMENT);
await expect
.poll(() => objective.evaluate((element) => element.scrollHeight > element.clientHeight))
.toBe(true);
const bounds = await objective.boundingBox();
expect(bounds).not.toBeNull();
if (!bounds) throw new Error("goal objective bounds unavailable");
expect(bounds.width).toBeLessThanOrEqual(testPage.viewportSize()?.width ?? bounds.width);
});
test("uses the same goal disclosure in Quick Chat", async ({ testPage }) => {
const dialog = await openQuickChatWithAgent(testPage);
await sendQuickChatMessage(dialog, testPage, "/e2e:goal-active");
const chip = dialog.getByTestId("agent-goal-chip");
await expect(chip).toBeVisible({ timeout: 30_000 });
await chip.click();
await expect(testPage.getByTestId("agent-goal-popover")).toBeVisible();
await expect(testPage.getByTestId("agent-goal-popover")).toContainText(GOAL_CONTINUATION_COPY);
});
});
@@ -0,0 +1,79 @@
import { type Locator, type Page } from "@playwright/test";
import { expect, test } from "../../fixtures/test-base";
import { assertNoDocumentHorizontalOverflow } from "../../helpers/layout-assertions";
import {
startQuickChatFromSetup,
sendQuickChatMessage,
waitForQuickChatDirectInput,
} from "./quick-chat-helpers";
async function openMobileQuickChat(page: Page): Promise<Locator> {
await page.goto("/");
await page.waitForLoadState("networkidle");
await page.getByTestId("mobile-topbar-menu").tap();
await page.getByTestId("mobile-quick-chat-button").tap();
const dialog = page.getByRole("dialog", { name: "Quick Chat" });
await expect(dialog).toBeVisible({ timeout: 10_000 });
return dialog;
}
test.describe("mobile agent goal visibility", () => {
test("opens the active goal in a touch drawer and clears it", async ({ testPage }) => {
const dialog = await openMobileQuickChat(testPage);
await startQuickChatFromSetup(dialog, testPage);
await sendQuickChatMessage(dialog, testPage, "/e2e:goal-active");
const chip = dialog.getByTestId("agent-goal-chip");
await expect(chip).toBeVisible({ timeout: 30_000 });
await expect(
dialog.getByText("The provider goal remains active after the thread becomes idle.", {
exact: false,
}),
).toBeVisible({ timeout: 30_000 });
const bounds = await chip.boundingBox();
expect(bounds).not.toBeNull();
if (!bounds) throw new Error("goal trigger bounds unavailable");
expect(bounds.width).toBeGreaterThanOrEqual(44);
expect(bounds.height).toBeGreaterThanOrEqual(44);
await chip.tap();
const drawer = testPage.getByTestId("agent-goal-drawer-content");
await expect(drawer).toBeVisible();
await expect(drawer).toContainText("Coordinate contributor PR reviews");
await expect(drawer).toContainText("The agent may continue automatically between replies.");
await assertNoDocumentHorizontalOverflow(testPage, "mobile agent goal drawer");
const close = testPage.getByRole("button", { name: "Close goal details" });
const closeBounds = await close.boundingBox();
expect(closeBounds).not.toBeNull();
if (!closeBounds) throw new Error("goal close bounds unavailable");
expect(closeBounds.width).toBeGreaterThanOrEqual(44);
expect(closeBounds.height).toBeGreaterThanOrEqual(44);
await close.tap();
await expect(drawer).toBeHidden();
await waitForQuickChatDirectInput(dialog);
await sendQuickChatMessage(dialog, testPage, "/e2e:goal-complete");
await expect(dialog.getByText("The provider goal is complete.", { exact: false })).toBeVisible({
timeout: 30_000,
});
await expect(dialog.getByTestId("agent-goal-chip")).toBeHidden({ timeout: 15_000 });
await waitForQuickChatDirectInput(dialog);
await sendQuickChatMessage(dialog, testPage, "/e2e:goal-active");
await expect(dialog.getByTestId("agent-goal-chip")).toBeVisible({ timeout: 30_000 });
await expect(
dialog.getByText("The provider goal remains active after the thread becomes idle.", {
exact: false,
}),
).toBeVisible({ timeout: 30_000 });
await waitForQuickChatDirectInput(dialog);
await sendQuickChatMessage(dialog, testPage, "/e2e:goal-clear");
await expect(dialog.getByText("The provider goal was cleared.", { exact: false })).toBeVisible({
timeout: 30_000,
});
await expect(dialog.getByTestId("agent-goal-chip")).toBeHidden({ timeout: 15_000 });
});
});
@@ -122,6 +122,22 @@ export async function waitForQuickChatComposerReady(dialog: Locator): Promise<Lo
return editor;
}
/**
* Wait for Quick Chat to accept a direct prompt instead of queueing it behind
* the active turn. The composer remains editable while the agent is running,
* so checking editability alone can submit a message too early.
*/
export async function waitForQuickChatDirectInput(dialog: Locator): Promise<void> {
const idlePlaceholder = dialog
.locator(
'[data-placeholder="Continue working on the task..."]:visible, [data-placeholder="Continue working on the plan..."]:visible, [data-placeholder="Continue working on the file..."]:visible',
)
.first();
const editor = dialog.locator('.tiptap.ProseMirror[contenteditable="true"]:visible').first();
await expect(idlePlaceholder).toBeVisible({ timeout: 15_000 });
await expect(editor).toBeEditable({ timeout: 15_000 });
}
export async function startQuickChatFromSetup(dialog: Locator, page: Page) {
await selectAgentIfNeeded(dialog, page);
await expect(dialog.getByTestId("quick-chat-start")).toBeEnabled({ timeout: 10_000 });
@@ -981,6 +981,14 @@ test.describe("Quick Chat", () => {
const secondTab = dialog.locator(
`[data-tab-reference="${secondReference}"] [data-testid="quick-chat-tab"]`,
);
// Explicitly select the non-first conversation so reload coverage proves
// the remembered selection wins over the deterministic first-tab fallback.
await secondTab.click();
await expect
.poll(() =>
testPage.evaluate("window.__KANDEV_E2E_STORE__?.getState().quickChat.activeSessionId"),
)
.toBe(second.session_id);
await secondTab.locator('button[title="Double-click to rename"]').click({ button: "right" });
await testPage.getByRole("menuitem", { name: "Rename", exact: true }).click();
const renameInput = secondTab.getByRole("textbox", { name: "Rename chat" });
@@ -1057,6 +1065,11 @@ test.describe("Quick Chat", () => {
await expect
.poll(() => quickChatTabReferences(restoredDialog), { timeout: 15_000 })
.toEqual([terminalReference, firstReference, secondReference]);
await expect
.poll(() =>
testPage.evaluate("window.__KANDEV_E2E_STORE__?.getState().quickChat.activeSessionId"),
)
.toBe(second.session_id);
await expect(
restoredDialog.locator(
`[data-tab-reference="${firstReference}"] [data-testid="quick-chat-tab-name"]`,
@@ -42,8 +42,25 @@ export async function expectBoundedMountedCards(column: Locator): Promise<void>
}
export async function scrollColumnToBottom(scrollOwner: Locator): Promise<void> {
await scrollOwner.evaluate((element) => {
element.scrollTop = element.scrollHeight;
element.dispatchEvent(new Event("scroll", { bubbles: true }));
});
let stableBottomSamples = 0;
await expect
.poll(
async () => {
const atBottom = await scrollOwner.evaluate((element) => {
const maxScrollTop = Math.max(0, element.scrollHeight - element.clientHeight);
if (maxScrollTop === 0) return false;
element.scrollTop = maxScrollTop;
element.dispatchEvent(new Event("scroll", { bubbles: true }));
return element.scrollTop >= maxScrollTop - 1;
});
stableBottomSamples = atBottom ? stableBottomSamples + 1 : 0;
return stableBottomSamples >= 2;
},
{
timeout: 10_000,
intervals: [50, 100, 250],
message: "virtualized column did not settle at the bottom",
},
)
.toBe(true);
}
+118 -1
View File
@@ -1,5 +1,10 @@
import { act, renderHook } from "@testing-library/react";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { produce } from "immer";
import type { Draft } from "immer";
import { defaultUIState } from "@/lib/state/slices/ui/ui-slice";
import { hydrateUI } from "@/lib/state/hydration/hydrator";
import type { AppState } from "@/lib/state/store";
const requestQuickChatClose = vi.hoisted(() => vi.fn());
@@ -10,10 +15,16 @@ vi.mock("@/components/quick-chat/quick-chat-focus", () => ({
const openQuickChat = vi.fn();
const closeQuickChat = vi.fn();
const requestQuickChatOpen = vi.fn();
const WORKSPACE_ID = "workspace-1";
const ACTIVE_CONFIG_ID = "config-active";
const REMEMBERED_CHAT_ID = "chat-remembered";
let activeSessionId: string | null = null;
let isOpen = false;
let rememberedSelectionByWorkspace: Record<string, { chat?: string; config?: string }> = {};
let selectionReadyByWorkspace: Record<string, boolean> = { [WORKSPACE_ID]: true };
let selectionRevisionByWorkspace: Record<string, number> = {};
let quickChatTabOrderByWorkspace: Record<string, string[]> = {};
let sessions: Array<{
sessionId: string;
workspaceId: string;
@@ -22,7 +33,21 @@ let sessions: Array<{
vi.mock("@/components/state-provider", () => ({
useAppStore: (selector: (state: unknown) => unknown) =>
selector({ openQuickChat, closeQuickChat, quickChat: { isOpen, sessions, activeSessionId } }),
selector({
openQuickChat,
closeQuickChat,
requestQuickChatOpen,
quickChat: {
isOpen,
sessions,
activeSessionId,
rememberedSelectionByWorkspace,
selectionReadyByWorkspace,
selectionRevisionByWorkspace,
tabOrderByWorkspace: {},
},
userSettings: { quickChatTabOrderByWorkspace },
}),
}));
import { useQuickChatLauncher } from "./use-quick-chat-launcher";
@@ -31,8 +56,13 @@ beforeEach(() => {
sessions = [];
activeSessionId = null;
isOpen = false;
rememberedSelectionByWorkspace = {};
selectionReadyByWorkspace = { [WORKSPACE_ID]: true };
selectionRevisionByWorkspace = {};
quickChatTabOrderByWorkspace = {};
openQuickChat.mockReset();
closeQuickChat.mockReset();
requestQuickChatOpen.mockReset();
requestQuickChatClose.mockReset();
requestQuickChatClose.mockReturnValue(false);
});
@@ -106,10 +136,97 @@ describe("useQuickChatLauncher typed sessions", () => {
{ sessionId: ACTIVE_CONFIG_ID, workspaceId: WORKSPACE_ID, kind: "config" },
];
activeSessionId = ACTIVE_CONFIG_ID;
selectionRevisionByWorkspace = { [WORKSPACE_ID]: 1 };
const { result } = renderHook(() => useQuickChatLauncher(WORKSPACE_ID, "config"));
act(() => result.current());
expect(openQuickChat).toHaveBeenCalledWith(ACTIVE_CONFIG_ID, WORKSPACE_ID, undefined, "config");
});
it("restores the remembered conversation after visiting another workspace", () => {
sessions = [
{ sessionId: "chat-a-first", workspaceId: WORKSPACE_ID, kind: "chat" },
{ sessionId: "chat-a-remembered", workspaceId: WORKSPACE_ID, kind: "chat" },
{ sessionId: "chat-b-active", workspaceId: "workspace-2", kind: "chat" },
];
activeSessionId = "chat-b-active";
rememberedSelectionByWorkspace = { [WORKSPACE_ID]: { chat: "chat-a-remembered" } };
const { result } = renderHook(() => useQuickChatLauncher(WORKSPACE_ID));
act(() => result.current());
expect(openQuickChat).toHaveBeenCalledWith(
"chat-a-remembered",
WORKSPACE_ID,
undefined,
"chat",
);
});
});
describe("useQuickChatLauncher delayed selection", () => {
it("launches the tab that hydration restored from browser selection", () => {
const hydrated = produce(
structuredClone(defaultUIState) as unknown as AppState,
(draft: Draft<AppState>) => {
draft.quickChat.rememberedSelectionByWorkspace = {
[WORKSPACE_ID]: { chat: REMEMBERED_CHAT_ID },
};
draft.quickChat.rememberedSelectionOrder = [WORKSPACE_ID];
hydrateUI(draft, {
quickChat: {
isOpen: false,
activeSessionId: null,
sessions: [
{ sessionId: "chat-first", workspaceId: WORKSPACE_ID, kind: "chat" },
{ sessionId: REMEMBERED_CHAT_ID, workspaceId: WORKSPACE_ID, kind: "chat" },
],
},
});
},
);
sessions = hydrated.quickChat.sessions;
activeSessionId = hydrated.quickChat.activeSessionId;
rememberedSelectionByWorkspace = hydrated.quickChat.rememberedSelectionByWorkspace;
selectionReadyByWorkspace = hydrated.quickChat.selectionReadyByWorkspace;
selectionRevisionByWorkspace = hydrated.quickChat.selectionRevisionByWorkspace;
const { result } = renderHook(() => useQuickChatLauncher(WORKSPACE_ID));
act(() => result.current());
expect(activeSessionId).toBe(REMEMBERED_CHAT_ID);
expect(openQuickChat).toHaveBeenCalledWith(REMEMBERED_CHAT_ID, WORKSPACE_ID, undefined, "chat");
});
it("waits for the authoritative workspace list before choosing a fallback", () => {
sessions = [{ sessionId: "chat-other", workspaceId: "workspace-2", kind: "chat" }];
selectionReadyByWorkspace = {};
const { result } = renderHook(() => useQuickChatLauncher(WORKSPACE_ID));
act(() => result.current());
expect(requestQuickChatOpen).toHaveBeenCalledWith(WORKSPACE_ID, "chat");
expect(openQuickChat).not.toHaveBeenCalled();
});
it("passes the persisted tab order through a delayed open", () => {
sessions = [{ sessionId: "chat-other", workspaceId: "workspace-2", kind: "chat" }];
selectionReadyByWorkspace = {};
quickChatTabOrderByWorkspace = {
[WORKSPACE_ID]: ["conversation:chat-second", "conversation:chat-first"],
};
const { result } = renderHook(() => useQuickChatLauncher(WORKSPACE_ID));
act(() => result.current());
expect(requestQuickChatOpen).toHaveBeenCalledWith(WORKSPACE_ID, "chat", [
"conversation:chat-second",
"conversation:chat-first",
]);
});
});
+33 -2
View File
@@ -5,6 +5,7 @@ import {
requestQuickChatClose,
type QuickChatLauncherFocusOptions,
} from "@/components/quick-chat/quick-chat-focus";
import { orderQuickChatTabs } from "@/lib/state/slices/ui/quick-chat-tab-order";
import type { QuickChatSessionKind } from "@/lib/state/slices/ui/types";
type QuickChatLauncherOptions = Pick<QuickChatLauncherFocusOptions, "returnFocusRef"> & {
@@ -29,6 +30,23 @@ export function useQuickChatLauncher(
const isQuickChatOpen = useAppStore((state) => state.quickChat.isOpen);
const quickChatSessions = useAppStore((state) => state.quickChat.sessions);
const activeSessionId = useAppStore((state) => state.quickChat.activeSessionId);
const selectionRevision = useAppStore(
(state) => state.quickChat.selectionRevisionByWorkspace[workspaceId ?? ""] ?? 0,
);
const rememberedSelection = useAppStore(
(state) => state.quickChat.rememberedSelectionByWorkspace[workspaceId ?? ""],
);
const selectionReady = useAppStore(
(state) => state.quickChat.selectionReadyByWorkspace[workspaceId ?? ""] ?? false,
);
const tabOrder = useAppStore((state) => {
const workspace = workspaceId ?? "";
return (
state.quickChat.tabOrderByWorkspace[workspace] ??
state.userSettings.quickChatTabOrderByWorkspace[workspace]
);
});
const requestQuickChatOpen = useAppStore((state) => state.requestQuickChatOpen);
const handleOpenQuickChat = useCallback(() => {
if (!workspaceId) return;
@@ -43,8 +61,16 @@ export function useQuickChatLauncher(
(session) => session.workspaceId === workspaceId && (session.kind ?? "chat") === kind,
);
const existingSession =
matchingSessions.find((session) => session.sessionId === activeSessionId) ??
matchingSessions[0];
(selectionRevision > 0
? matchingSessions.find((session) => session.sessionId === activeSessionId)
: undefined) ??
matchingSessions.find((session) => session.sessionId === rememberedSelection?.[kind]) ??
(selectionReady ? orderQuickChatTabs(matchingSessions, [], tabOrder).sessions[0] : undefined);
if (!selectionReady && !existingSession) {
if (tabOrder) requestQuickChatOpen(workspaceId, kind, tabOrder);
else requestQuickChatOpen(workspaceId, kind);
return;
}
if (existingSession) {
openQuickChat(
existingSession.sessionId,
@@ -66,6 +92,11 @@ export function useQuickChatLauncher(
quickChatSessions,
kind,
activeSessionId,
selectionRevision,
rememberedSelection,
selectionReady,
tabOrder,
requestQuickChatOpen,
openQuickChat,
]);
@@ -112,4 +112,18 @@ describe("useResponsiveBreakpoint", () => {
expect(result.current.breakpoint).toBe("compactDesktop");
expect(result.current.usesDesktopWorkbench).toBe(true);
});
it("updates pointer mode while the subscription remains mounted", () => {
const { result } = renderHook(() => useResponsiveBreakpoint());
expect(result.current.isFinePointer).toBe(true);
notifyResize(1024, "coarse");
expect(result.current.isFinePointer).toBe(false);
expect(result.current.breakpoint).toBe("desktop");
notifyResize(1024, "fine");
expect(result.current.isFinePointer).toBe(true);
});
});
+53
View File
@@ -0,0 +1,53 @@
import { describe, expect, it } from "vitest";
import {
isAgentGoalSnapshotNewer,
mergeAgentGoalMetadata,
parseAgentGoal,
type AgentGoal,
} from "./agent-goal";
function goal(status: AgentGoal["status"], createdAt = 10, updatedAt = 20): AgentGoal {
return { objective: "Coordinate contributor PR reviews", status, createdAt, updatedAt };
}
describe("agent goal projection", () => {
it("accepts each supported provider status", () => {
for (const status of ["active", "paused", "blocked", "limited", "complete"] as const) {
expect(parseAgentGoal(goal(status))?.status).toBe(status);
}
});
it("retains an accepted goal across sparse metadata and explicit clear", () => {
const active = { goal: goal("active"), provider: "codex" };
expect(mergeAgentGoalMetadata(active, { codex: { threadStatus: "idle" } })).toEqual({
codex: { threadStatus: "idle" },
goal: goal("active"),
});
expect(mergeAgentGoalMetadata(active, { goal: null })).toEqual({ goal: null });
});
it("rejects malformed and older snapshots without making them active", () => {
const active = { goal: goal("active", 10, 20) };
expect(parseAgentGoal({ ...goal("active"), status: "running" })).toBeNull();
expect(mergeAgentGoalMetadata(active, { goal: goal("active", 10, 19) })).toEqual(active);
expect(
mergeAgentGoalMetadata(active, { goal: { ...goal("active"), status: "running" } }),
).toEqual({
goal: null,
});
});
it("uses strict RFC3339 freshness for reconnect snapshots", () => {
const reconciliation = {
revision: 1,
cleared: false,
watermark: goal("active", 10, 20),
sourceUpdatedAt: "2026-06-11T00:01:00.000Z",
};
expect(isAgentGoalSnapshotNewer("2026-06-11T00:02:00.000Z", reconciliation)).toBe(true);
expect(isAgentGoalSnapshotNewer("2026-02-30T00:02:00.000Z", reconciliation)).toBe(false);
});
});
+238
View File
@@ -0,0 +1,238 @@
import { parseTurnTimestamp } from "@/lib/state/slices/session/turn-actions";
export type AgentGoalStatus = "active" | "paused" | "blocked" | "limited" | "complete";
export type AgentGoal = {
objective: string;
status: AgentGoalStatus;
createdAt: number;
updatedAt: number;
tokenBudget?: number | null;
tokensUsed?: number;
timeUsedSeconds?: number;
controlMethod?: string;
};
export type AgentGoalReconciliation = {
revision: number;
cleared: boolean;
watermark: { createdAt: number; updatedAt: number } | null;
/** ACP session-info timestamp of the accepted live snapshot. */
sourceUpdatedAt?: string;
};
const GOAL_OBJECTIVE_MAX_LENGTH = 16 * 1024;
const GOAL_STATUSES = new Set<AgentGoalStatus>([
"active",
"paused",
"blocked",
"limited",
"complete",
]);
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isNonNegativeFiniteNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value) && value >= 0;
}
function hasOwn(value: Record<string, unknown>, key: string): boolean {
return Object.prototype.hasOwnProperty.call(value, key);
}
function parseOptionalGoalFields(value: Record<string, unknown>, goal: AgentGoal): boolean {
if (hasOwn(value, "tokenBudget")) {
if (value.tokenBudget !== null && !isNonNegativeFiniteNumber(value.tokenBudget)) return false;
goal.tokenBudget = value.tokenBudget as number | null;
}
for (const key of ["tokensUsed", "timeUsedSeconds"] as const) {
if (!hasOwn(value, key)) continue;
if (!isNonNegativeFiniteNumber(value[key])) return false;
goal[key] = value[key];
}
if (hasOwn(value, "controlMethod")) {
if (typeof value.controlMethod !== "string") return false;
goal.controlMethod = value.controlMethod;
}
return true;
}
/** Parses the narrow ACP goal extension into the fields the UI is allowed to read. */
export function parseAgentGoal(value: unknown): AgentGoal | null {
if (!isRecord(value)) return null;
const { objective, status, createdAt, updatedAt } = value;
if (
typeof objective !== "string" ||
objective.length === 0 ||
objective.length > GOAL_OBJECTIVE_MAX_LENGTH ||
typeof status !== "string" ||
!GOAL_STATUSES.has(status as AgentGoalStatus) ||
!isNonNegativeFiniteNumber(createdAt) ||
!isNonNegativeFiniteNumber(updatedAt)
) {
return null;
}
const goal: AgentGoal = {
objective,
status: status as AgentGoalStatus,
createdAt,
updatedAt,
};
return parseOptionalGoalFields(value, goal) ? goal : null;
}
/** Compares provider goal snapshots by goal identity and update time. */
export function isAgentGoalAtLeastAsFresh(incoming: AgentGoal, existing: AgentGoal): boolean {
if (incoming.createdAt !== existing.createdAt) return incoming.createdAt > existing.createdAt;
return incoming.updatedAt >= existing.updatedAt;
}
function isAgentGoalStrictlyNewer(
incoming: AgentGoal,
watermark: { createdAt: number; updatedAt: number },
): boolean {
return (
incoming.createdAt > watermark.createdAt ||
(incoming.createdAt === watermark.createdAt && incoming.updatedAt > watermark.updatedAt)
);
}
/** Returns whether an incoming session snapshot is newer than the accepted live goal snapshot. */
export function isAgentGoalSnapshotNewer(
snapshotUpdatedAt: string | undefined,
reconciliation: AgentGoalReconciliation | undefined,
): boolean {
if (!snapshotUpdatedAt || !reconciliation?.sourceUpdatedAt) return false;
const snapshotTime = parseTurnTimestamp(snapshotUpdatedAt);
const sourceTime = parseTurnTimestamp(reconciliation.sourceUpdatedAt);
return snapshotTime !== null && sourceTime !== null && snapshotTime > sourceTime;
}
/** Returns the accepted goal from ACP metadata, or null for absent/invalid values. */
export function getAgentGoal(metadata: unknown): AgentGoal | null {
if (!isRecord(metadata)) return null;
return parseAgentGoal(metadata.goal);
}
/**
* Merges only the goal field into a sparse provider metadata replacement.
* Other ACP metadata keeps the existing shallow replacement behavior.
*/
export function mergeAgentGoalMetadata(
existing: Record<string, unknown> | undefined,
incoming: Record<string, unknown> | undefined,
options: {
attachmentChanged?: boolean;
source?: "live" | "hydration";
reconciliation?: AgentGoalReconciliation;
snapshotUpdatedAt?: string;
} = {},
): Record<string, unknown> {
const current = existing ?? {};
const next = { ...(incoming ?? {}) };
const existingHasGoal = hasOwn(current, "goal");
const incomingHasGoal = hasOwn(incoming ?? {}, "goal");
if (options.attachmentChanged) {
return mergeAttachedGoal(next, incoming, incomingHasGoal);
}
if (!incomingHasGoal) {
return preserveExistingGoal(next, current, existingHasGoal);
}
if (incoming?.goal === null) {
return mergeClearedGoal(next, current.goal, options);
}
return mergeLiveGoal(next, current, incoming ?? {}, options);
}
function mergeAttachedGoal(
next: Record<string, unknown>,
incoming: Record<string, unknown> | undefined,
incomingHasGoal: boolean,
): Record<string, unknown> {
next.goal = incomingHasGoal ? parseAgentGoal(incoming?.goal) : null;
return next;
}
function preserveExistingGoal(
next: Record<string, unknown>,
current: Record<string, unknown>,
existingHasGoal: boolean,
): Record<string, unknown> {
if (existingHasGoal) next.goal = current.goal;
return next;
}
function mergeClearedGoal(
next: Record<string, unknown>,
currentGoal: unknown,
options: {
attachmentChanged?: boolean;
source?: "live" | "hydration";
reconciliation?: AgentGoalReconciliation;
snapshotUpdatedAt?: string;
},
): Record<string, unknown> {
next.goal = shouldRetainHydrationGoal(currentGoal, options) ? currentGoal : null;
return next;
}
function mergeLiveGoal(
next: Record<string, unknown>,
current: Record<string, unknown>,
incoming: Record<string, unknown>,
options: {
attachmentChanged?: boolean;
source?: "live" | "hydration";
reconciliation?: AgentGoalReconciliation;
snapshotUpdatedAt?: string;
},
): Record<string, unknown> {
const parsed = parseAgentGoal(incoming.goal);
if (!parsed) {
next.goal = null;
return next;
}
const existingGoal = parseAgentGoal(current.goal);
if (shouldRetainClearedGoal(parsed, options)) {
next.goal = current.goal;
return next;
}
next.goal =
existingGoal && !isAgentGoalAtLeastAsFresh(parsed, existingGoal) ? existingGoal : parsed;
return next;
}
function shouldRetainHydrationGoal(
currentGoal: unknown,
options: {
source?: "live" | "hydration";
reconciliation?: AgentGoalReconciliation;
snapshotUpdatedAt?: string;
},
): boolean {
return (
options.source === "hydration" &&
options.reconciliation !== undefined &&
!options.reconciliation.cleared &&
parseAgentGoal(currentGoal) !== null &&
!isAgentGoalSnapshotNewer(options.snapshotUpdatedAt, options.reconciliation)
);
}
function shouldRetainClearedGoal(
parsed: AgentGoal,
options: { source?: "live" | "hydration"; reconciliation?: AgentGoalReconciliation },
): boolean {
if (!options.reconciliation?.cleared) return false;
const watermark = options.reconciliation.watermark;
return (
(!watermark && options.source !== "live") ||
(watermark !== null && !isAgentGoalStrictlyNewer(parsed, watermark))
);
}
@@ -0,0 +1,63 @@
import { beforeEach, describe, expect, it } from "vitest";
import {
ANONYMOUS_QUICK_CHAT_SELECTION_IDENTITY,
loadQuickChatSelection,
persistQuickChatSelection,
} from "./selection-storage";
describe("Quick Chat selection storage", () => {
beforeEach(() => window.localStorage.clear());
it("keeps remembered selections separate for each identity", () => {
persistQuickChatSelection("user-a", { "workspace-a": { chat: "chat-a" } }, ["workspace-a"]);
expect(loadQuickChatSelection("user-a").selections).toEqual({
"workspace-a": { chat: "chat-a" },
});
expect(loadQuickChatSelection("user-b").selections).toEqual({});
});
it("retains valid entries and ignores malformed stored values", () => {
window.localStorage.setItem(
"kandev.quick-chat.selection.v1.user-a",
JSON.stringify({
version: 1,
entries: [
{ workspaceId: "workspace-a", chat: "chat-a", lastSelectedAt: 2 },
{ workspaceId: "", chat: "invalid", lastSelectedAt: 1 },
{ workspaceId: "workspace-b", config: 42, lastSelectedAt: 0 },
],
}),
);
expect(loadQuickChatSelection("user-a").selections).toEqual({
"workspace-a": { chat: "chat-a" },
});
});
it("uses an anonymous identity for authentication-disabled deployments", () => {
persistQuickChatSelection(
ANONYMOUS_QUICK_CHAT_SELECTION_IDENTITY,
{ "workspace-a": { chat: "chat-a" } },
["workspace-a"],
);
expect(loadQuickChatSelection(ANONYMOUS_QUICK_CHAT_SELECTION_IDENTITY).selections).toEqual({
"workspace-a": { chat: "chat-a" },
});
});
it("bounds stored workspaces to the most recently selected entries", () => {
const selections = Object.fromEntries(
Array.from({ length: 205 }, (_, index) => [`workspace-${index}`, { chat: `chat-${index}` }]),
);
const order = Object.keys(selections).reverse();
persistQuickChatSelection("user-a", selections, order);
const loaded = loadQuickChatSelection("user-a");
expect(Object.keys(loaded.selections)).toHaveLength(200);
expect(loaded.order[0]).toBe("workspace-204");
expect(loaded.selections["workspace-0"]).toBeUndefined();
});
});
@@ -0,0 +1,152 @@
import type {
QuickChatSelection,
QuickChatSelectionByWorkspace,
QuickChatSelectionOrder,
QuickChatSessionKind,
} from "@/lib/state/slices/ui/types";
export const ANONYMOUS_QUICK_CHAT_SELECTION_IDENTITY = "anonymous";
const STORAGE_PREFIX = "kandev.quick-chat.selection.v1.";
const STORAGE_VERSION = 1;
const MAX_WORKSPACES = 200;
export type QuickChatSelectionIdentity = string | null;
export type QuickChatSelectionStorageResult = {
selections: QuickChatSelectionByWorkspace;
order: QuickChatSelectionOrder;
};
type StoredSelectionEntry = {
workspaceId: string;
chat?: string;
config?: string;
lastSelectedAt?: number;
};
type StoredSelectionDocument = {
version: number;
entries: StoredSelectionEntry[];
};
type AuthIdentityState = {
mode: "disabled" | "setup" | "enabled";
authenticated: boolean;
user: { id: string } | null;
};
function storageKey(identity: QuickChatSelectionIdentity): string | null {
return identity === null ? null : `${STORAGE_PREFIX}${encodeURIComponent(identity)}`;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function isSessionId(value: unknown): value is string {
return typeof value === "string" && value.length > 0;
}
function readEntry(value: unknown): StoredSelectionEntry | null {
if (!isRecord(value) || typeof value.workspaceId !== "string" || !value.workspaceId) {
return null;
}
const entry: StoredSelectionEntry = { workspaceId: value.workspaceId };
for (const kind of ["chat", "config"] as const) {
if (isSessionId(value[kind])) entry[kind] = value[kind];
}
if (typeof value.lastSelectedAt === "number" && Number.isFinite(value.lastSelectedAt)) {
entry.lastSelectedAt = value.lastSelectedAt;
}
return entry.chat || entry.config ? entry : null;
}
function emptySelection(): QuickChatSelectionStorageResult {
return { selections: {}, order: [] };
}
/** Returns the browser-storage identity for the current authentication mode. */
export function getQuickChatSelectionIdentity(auth: AuthIdentityState): QuickChatSelectionIdentity {
if (auth.mode === "disabled") return ANONYMOUS_QUICK_CHAT_SELECTION_IDENTITY;
if (auth.mode !== "enabled" || !auth.authenticated || !auth.user?.id) return null;
return auth.user.id;
}
/** Reads and validates remembered Quick Chat selections for one identity. */
export function loadQuickChatSelection(
identity: QuickChatSelectionIdentity,
): QuickChatSelectionStorageResult {
const key = storageKey(identity);
if (!key || typeof window === "undefined") return emptySelection();
try {
const raw = window.localStorage.getItem(key);
if (!raw) return emptySelection();
const parsed: unknown = JSON.parse(raw);
if (!isRecord(parsed) || parsed.version !== STORAGE_VERSION || !Array.isArray(parsed.entries)) {
return emptySelection();
}
const entries = parsed.entries
.map(readEntry)
.filter((entry): entry is StoredSelectionEntry => entry !== null)
.map((entry, index) => ({ entry, index }))
.sort(
(left, right) =>
(right.entry.lastSelectedAt ?? 0) - (left.entry.lastSelectedAt ?? 0) ||
left.index - right.index,
);
const selections: QuickChatSelectionByWorkspace = {};
const order: QuickChatSelectionOrder = [];
for (const { entry } of entries) {
if (order.length >= MAX_WORKSPACES || selections[entry.workspaceId]) continue;
const selection: QuickChatSelection = {};
if (entry.chat) selection.chat = entry.chat;
if (entry.config) selection.config = entry.config;
selections[entry.workspaceId] = selection;
order.push(entry.workspaceId);
}
return { selections, order };
} catch {
return emptySelection();
}
}
/** Writes the bounded remembered-selection map. Storage failures are harmless. */
export function persistQuickChatSelection(
identity: QuickChatSelectionIdentity,
selections: QuickChatSelectionByWorkspace,
order: QuickChatSelectionOrder,
): void {
const key = storageKey(identity);
if (!key || typeof window === "undefined") return;
const orderedWorkspaceIds = [
...order,
...Object.keys(selections).filter((workspaceId) => !order.includes(workspaceId)),
].filter((workspaceId, index, all) => all.indexOf(workspaceId) === index);
const entries: StoredSelectionEntry[] = orderedWorkspaceIds
.filter((workspaceId) => selections[workspaceId])
.slice(0, MAX_WORKSPACES)
.map((workspaceId, index) => {
const selection = selections[workspaceId];
return {
workspaceId,
...(selection.chat ? { chat: selection.chat } : {}),
...(selection.config ? { config: selection.config } : {}),
lastSelectedAt: Date.now() - index,
};
});
try {
window.localStorage.setItem(
key,
JSON.stringify({ version: STORAGE_VERSION, entries } satisfies StoredSelectionDocument),
);
} catch {
// Browser storage can be disabled or full. The in-memory selection remains valid.
}
}
export const QUICK_CHAT_SELECTION_MAX_WORKSPACES = MAX_WORKSPACES;
export type { QuickChatSessionKind };
+3 -2
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-lines -- AppState keeps the explicit cross-slice store contract in one type. */
import type { HydrationOptions } from "./hydration/hydrator";
import type {
Repository,
@@ -392,7 +393,6 @@ export type AppState = KanbanSlice & {
closeQuickChatSession: (sessionId: string) => void;
setActiveQuickChatSession: (sessionId: string, workspaceId: string) => void;
renameQuickChatSession: (sessionId: string, name: string) => void;
setQuickChatInitialPrompt: UIA["setQuickChatInitialPrompt"];
setSessionFailureNotification: (n: UISliceTypes.SessionFailureNotification | null) => void;
setTaskDeletedNotification: (n: UISliceTypes.TaskDeletedNotification | null) => void;
setUpdateAvailableNotification: (n: UISliceTypes.UpdateAvailableNotification | null) => void;
@@ -630,7 +630,8 @@ export type AppState = KanbanSlice & {
restoreRichOutputAnimations: UIA["restoreRichOutputAnimations"];
acknowledgeAgentErrors: UIA["acknowledgeAgentErrors"];
dismissAgentError: UIA["dismissAgentError"];
} & AppStateExtraActions;
} & AppStateExtraActions &
Pick<UIA, "setQuickChatInitialPrompt" | "requestQuickChatOpen" | "setQuickChatSelectionIdentity">;
// Most callers hydrate a fully-shaped slice per top-level key (see
// mergeInitialState / hydrateState), but `system` is a grab-bag of many
+11
View File
@@ -16,3 +16,14 @@ describe("turn hydration state", () => {
expect(state.turns.loadedBySession).toEqual({ "session-1": true });
});
});
describe("quick chat hydration state", () => {
it("marks an empty boot snapshot ready for the active workspace", () => {
const state = mergeInitialState({
workspaces: { items: [], activeId: "workspace-1" },
quickChat: { sessions: [] },
} as unknown as HydrationState);
expect(state.quickChat.selectionReadyByWorkspace).toEqual({ "workspace-1": true });
});
});
+15 -2
View File
@@ -183,7 +183,7 @@ function mergeCodeHostFields(
/** Merge quick-chat state from hydration over defaults, applying locally stored chat names to the SSR-provided sessions. */
function mergeQuickChatState(initialState: HydrationState): DefaultState["quickChat"] {
const { sessions, ...hydratedQuickChat } = initialState.quickChat ?? {};
const quickChat = {
const quickChat: DefaultState["quickChat"] = {
...defaultState.quickChat,
...hydratedQuickChat,
unseenIdleByWorkspace: {},
@@ -191,8 +191,21 @@ function mergeQuickChatState(initialState: HydrationState): DefaultState["quickC
sessionOwnership: {},
syncRevisionByWorkspace: {},
tombstonedSessions: {},
rememberedSelectionByWorkspace: {},
rememberedSelectionOrder: [],
selectionStorageIdentity: null,
selectionReadyByWorkspace: {},
selectionRevisionByWorkspace: {},
pendingOpen: null,
};
return sessions ? mergeHydratedQuickChatSessions(quickChat, sessions) : quickChat;
const merged = sessions ? mergeHydratedQuickChatSessions(quickChat, sessions) : quickChat;
for (const session of sessions ?? []) {
merged.selectionReadyByWorkspace[session.workspaceId] = true;
}
if (sessions?.length === 0 && initialState.workspaces?.activeId) {
merged.selectionReadyByWorkspace[initialState.workspaces.activeId] = true;
}
return merged;
}
/** Merge sidebar view state, preferring the server-provided views, active view, and draft from user settings when present. */
@@ -138,7 +138,53 @@ describe("hydrateUI — typed quick chat sessions", () => {
});
});
// eslint-disable-next-line max-lines-per-function -- This covers the full hydration-to-launcher sequence in one fixture.
describe("hydrateUI — quick chat lifecycle", () => {
it("restores the remembered tab before a passive hydrated active session", () => {
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
draft.quickChat.sessions = [{ sessionId: "chat-first", workspaceId: "ws-1", kind: "chat" }];
draft.quickChat.activeSessionId = "chat-first";
draft.quickChat.rememberedSelectionByWorkspace = {
"ws-1": { chat: "chat-remembered" },
};
draft.quickChat.rememberedSelectionOrder = ["ws-1"];
hydrateUI(draft, {
quickChat: {
isOpen: false,
activeSessionId: null,
sessions: [
{ sessionId: "chat-first", workspaceId: "ws-1", kind: "chat" },
{ sessionId: "chat-remembered", workspaceId: "ws-1", kind: "chat" },
],
},
});
});
expect(result.quickChat.activeSessionId).toBe("chat-remembered");
});
it("resolves an empty boot snapshot for the active workspace", () => {
const result = produce(makeAppDraft(), (draft: Draft<AppState>) => {
draft.workspaces.activeId = "ws-1";
draft.quickChat.pendingOpen = {
workspaceId: "ws-1",
kind: "chat",
selectionRevision: 0,
};
hydrateUI(draft, {
quickChat: {
isOpen: true,
activeSessionId: null,
sessions: [],
},
});
});
expect(result.quickChat.selectionReadyByWorkspace).toMatchObject({ "ws-1": true });
expect(result.quickChat.pendingOpen).toBeNull();
expect(result.quickChat.activeSessionId).toBe("quick-chat-setup:ws-1:chat");
});
it("restores server-owned terminal tabs during a fresh hydration", () => {
const result = produce(makeDraft(), (draft: Draft<AppState>) => {
hydrateUI(draft, {
+171 -41
View File
@@ -1,3 +1,4 @@
/* eslint-disable max-lines -- Hydration owns the cross-slice merge boundary. */
import type { Draft } from "immer";
import type { AppState, HydrationState } from "../store";
import type { KanbanState } from "../slices/kanban/types";
@@ -7,6 +8,11 @@ import {
mergeHydratedQuickChatSessions,
reconcileQuickTerminalTabs,
} from "@/lib/state/slices/ui/quick-chat-sync";
import {
findRememberedQuickChatSession,
restoreQuickChatSession,
} from "@/lib/state/slices/ui/quick-chat-selection";
import { getQuickChatSetupSessionId } from "@/lib/state/slices/ui/quick-chat-session";
import { compareUserSettingsRevisions } from "@/lib/settings/user-settings-revision";
import { mergeAgentProfileRecentUseState } from "@/lib/agent-profile-recent-use";
import {
@@ -547,15 +553,7 @@ export function hydrateUI(draft: Draft<AppState>, state: HydrationState): void {
if (state.previewPanel) deepMerge(draft.previewPanel, state.previewPanel);
if (state.rightPanel) deepMerge(draft.rightPanel, state.rightPanel);
if (state.diffs) deepMerge(draft.diffs, state.diffs);
if (state.quickChat) {
// SSR snapshots may arrive after live WebSocket updates. Hydration only
// adopts previously unseen sessions and never removes or regresses tabs.
if (state.quickChat.sessions) {
draft.quickChat = mergeHydratedQuickChatSessions(draft.quickChat, state.quickChat.sessions);
restoreQuickChatSelection(draft, draft.quickChat.sessions, draft.quickChat.activeSessionId);
}
if (state.quickChat.terminalTabs) hydrateQuickTerminalState(draft, state.quickChat);
}
if (state.quickChat) hydrateQuickChatState(draft, state.quickChat);
if (state.connection) {
const { status: _status, ...rest } = state.connection || {};
if (Object.keys(rest).length > 0) {
@@ -564,6 +562,29 @@ export function hydrateUI(draft: Draft<AppState>, state: HydrationState): void {
}
}
function hydrateQuickChatState(
draft: Draft<AppState>,
quickChat: NonNullable<HydrationState["quickChat"]>,
): void {
// SSR snapshots may arrive after live WebSocket updates. Hydration only
// adopts previously unseen sessions and never removes or regresses tabs.
if (quickChat.sessions) {
draft.quickChat = mergeHydratedQuickChatSessions(draft.quickChat, quickChat.sessions);
const readyWorkspaceIds = new Set(quickChat.sessions.map((session) => session.workspaceId));
if (quickChat.sessions.length === 0 && draft.workspaces?.activeId) {
readyWorkspaceIds.add(draft.workspaces.activeId);
}
for (const workspaceId of readyWorkspaceIds) {
draft.quickChat.selectionReadyByWorkspace[workspaceId] = true;
}
restoreQuickChatSelection(draft, draft.quickChat.sessions, draft.quickChat.activeSessionId);
for (const workspaceId of readyWorkspaceIds) {
resolveHydratedPendingOpen(draft, workspaceId, quickChat.sessions);
}
}
if (quickChat.terminalTabs) hydrateQuickTerminalState(draft, quickChat);
}
/** Merge SSR quick-chat terminal tabs per workspace, restoring the active and last-used terminal tab when they still exist. */
function hydrateQuickTerminalState(
draft: Draft<AppState>,
@@ -605,44 +626,153 @@ function restoreQuickChatSelection(
draft.quickChat.activeKind ??= "conversation";
draft.quickChat.activeTerminalTabId ??= null;
draft.quickChat.lastTerminalTabIdByWorkspace ??= {};
if (draft.quickChat.activeKind === "terminal") {
if (
draft.quickChat.activeTerminalTabId &&
draft.quickChat.terminalTabs.some((tab) => tab.tabId === draft.quickChat.activeTerminalTabId)
) {
return;
}
draft.quickChat.activeKind = "conversation";
}
if (preserveHydratedTerminalSelection(draft)) return;
const workspaceId = previousWorkspaceId(previousSessions, previousActiveSessionId);
if (preserveExplicitHydratedConversationSelection(draft, workspaceId)) return;
if (restoreRememberedHydrationSelection(draft, workspaceId)) return;
if (restoreHydratedConversationFallback(draft, workspaceId)) return;
if (restoreHydratedTerminalFallback(draft, workspaceId)) return;
draft.quickChat.activeSessionId = null;
if (draft.quickChat.terminalTabs.length === 0) draft.quickChat.isOpen = false;
}
function preserveHydratedTerminalSelection(draft: Draft<AppState>): boolean {
if (draft.quickChat.activeKind !== "terminal") return false;
const activeTerminalTabId = draft.quickChat.activeTerminalTabId;
if (
draft.quickChat.activeSessionId &&
draft.quickChat.sessions.some(
(session) => session.sessionId === draft.quickChat.activeSessionId,
)
activeTerminalTabId &&
draft.quickChat.terminalTabs.some((tab) => tab.tabId === activeTerminalTabId)
) {
return true;
}
draft.quickChat.activeKind = "conversation";
return false;
}
function preserveExplicitHydratedConversationSelection(
draft: Draft<AppState>,
workspaceId: string | undefined,
): boolean {
if (!workspaceId || (draft.quickChat.selectionRevisionByWorkspace[workspaceId] ?? 0) <= 0) {
return false;
}
const activeSessionId = draft.quickChat.activeSessionId;
return Boolean(
activeSessionId &&
draft.quickChat.sessions.some((session) => session.sessionId === activeSessionId),
);
}
function restoreRememberedHydrationSelection(
draft: Draft<AppState>,
workspaceId: string | undefined,
): boolean {
const rememberedSession = findRememberedHydrationSession(draft, workspaceId);
if (!rememberedSession) return false;
draft.quickChat.activeSessionId = rememberedSession.sessionId;
draft.quickChat.activeKind = "conversation";
return true;
}
function restoreHydratedConversationFallback(
draft: Draft<AppState>,
workspaceId: string | undefined,
): boolean {
const fallbackSession =
draft.quickChat.sessions.find((session) => session.workspaceId === workspaceId) ??
draft.quickChat.sessions[0];
if (!fallbackSession) return false;
draft.quickChat.activeSessionId = fallbackSession.sessionId;
draft.quickChat.activeKind = "conversation";
return true;
}
function restoreHydratedTerminalFallback(
draft: Draft<AppState>,
workspaceId: string | undefined,
): boolean {
const fallbackTerminal = draft.quickChat.terminalTabs.find(
(tab) => tab.workspaceId === workspaceId,
);
if (!fallbackTerminal) return false;
draft.quickChat.activeKind = "terminal";
draft.quickChat.activeTerminalTabId = fallbackTerminal.tabId;
return true;
}
function resolveHydratedPendingOpen(
draft: Draft<AppState>,
workspaceId: string,
hydratedSessions: AppState["quickChat"]["sessions"],
): void {
const pending = draft.quickChat.pendingOpen;
if (
!pending ||
pending.workspaceId !== workspaceId ||
pending.selectionRevision !== (draft.quickChat.selectionRevisionByWorkspace[workspaceId] ?? 0)
) {
return;
}
const previousWorkspaceId = previousSessions.find(
(session) => session.sessionId === previousActiveSessionId,
)?.workspaceId;
const fallbackSession =
draft.quickChat.sessions.find((session) => session.workspaceId === previousWorkspaceId) ??
draft.quickChat.sessions[0];
if (fallbackSession) {
draft.quickChat.activeSessionId = fallbackSession.sessionId;
draft.quickChat.activeKind = "conversation";
return;
}
const fallbackTerminal = draft.quickChat.terminalTabs.find(
(tab) => tab.workspaceId === previousWorkspaceId,
const tabOrder =
pending.tabOrder ??
draft.quickChat.tabOrderByWorkspace[workspaceId] ??
draft.userSettings.quickChatTabOrderByWorkspace[workspaceId];
const sessionId = restoreQuickChatSession(
hydratedSessions,
draft.quickChat.rememberedSelectionByWorkspace,
workspaceId,
pending.kind,
tabOrder,
);
if (fallbackTerminal) {
draft.quickChat.activeKind = "terminal";
draft.quickChat.activeTerminalTabId = fallbackTerminal.tabId;
return;
if (sessionId) {
draft.quickChat.activeSessionId = sessionId;
} else {
const setupSessionId = getQuickChatSetupSessionId(workspaceId, pending.kind);
if (!draft.quickChat.sessions.some((session) => session.sessionId === setupSessionId)) {
draft.quickChat.sessions.push({
sessionId: setupSessionId,
workspaceId,
kind: pending.kind,
});
}
draft.quickChat.activeSessionId = setupSessionId;
}
draft.quickChat.activeSessionId = null;
if (draft.quickChat.terminalTabs.length === 0) draft.quickChat.isOpen = false;
draft.quickChat.activeKind = "conversation";
draft.quickChat.isOpen = true;
draft.quickChat.pendingOpen = null;
}
function previousWorkspaceId(
sessions: AppState["quickChat"]["sessions"],
activeSessionId: string | null,
): string | undefined {
return sessions.find((session) => session.sessionId === activeSessionId)?.workspaceId;
}
function findRememberedHydrationSession(
draft: Draft<AppState>,
preferredWorkspaceId: string | undefined,
): AppState["quickChat"]["sessions"][number] | undefined {
const workspaceIds = [
preferredWorkspaceId,
...draft.quickChat.rememberedSelectionOrder,
...Object.keys(draft.quickChat.rememberedSelectionByWorkspace),
];
const seen = new Set<string>();
for (const workspaceId of workspaceIds) {
if (!workspaceId || seen.has(workspaceId)) continue;
seen.add(workspaceId);
for (const kind of ["chat", "config"] as const) {
const remembered = findRememberedQuickChatSession(
draft.quickChat.sessions,
draft.quickChat.rememberedSelectionByWorkspace,
workspaceId,
kind,
);
if (remembered) return remembered;
}
}
return undefined;
}
/**
@@ -0,0 +1,218 @@
import { describe, expect, it } from "vitest";
import { mergeTaskSession } from "./session-merge";
import type { TaskSession } from "@/lib/types/http";
const ACTIVE_GOAL = {
objective: "Coordinate contributor PR reviews",
status: "active",
createdAt: 10,
updatedAt: 20,
};
const LIVE_GOAL_SNAPSHOT_AT = "2026-06-11T00:02:00.000Z";
const STALE_GOAL_SNAPSHOT_AT = "2026-06-11T00:01:30.000Z";
const FRESH_GOAL_SNAPSHOT_AT = "2026-06-11T00:03:00.000Z";
function session(
metadata: Record<string, unknown>,
extras: Partial<TaskSession> = {},
): TaskSession {
return {
id: "session-1",
task_id: "task-1",
state: "WAITING_FOR_INPUT",
started_at: "2026-06-11T00:00:00.000Z",
updated_at: "2026-06-11T00:01:00.000Z",
metadata,
...extras,
} as TaskSession;
}
describe("TaskSession goal hydration reconciliation", () => {
it("does not resurrect a goal cleared by a live event", () => {
const existing = session(
{ acp: { session_id: "acp-1", meta: { goal: null } } },
{
goal_reconciliation: {
revision: 2,
cleared: true,
watermark: { createdAt: 10, updatedAt: 20 },
},
},
);
const staleHydration = session({
acp: { session_id: "acp-1", meta: { goal: ACTIVE_GOAL } },
});
const merged = mergeTaskSession(existing, staleHydration);
expect(merged.metadata?.acp).toMatchObject({ meta: { goal: null } });
expect(merged.goal_reconciliation).toEqual(existing.goal_reconciliation);
});
it("does not let stale hydration clear a newer live goal", () => {
const existing = session(
{
acp: {
session_id: "acp-1",
updated_at: LIVE_GOAL_SNAPSHOT_AT,
meta: { goal: ACTIVE_GOAL },
},
},
{
goal_reconciliation: {
revision: 1,
cleared: false,
watermark: { createdAt: 10, updatedAt: 20 },
sourceUpdatedAt: LIVE_GOAL_SNAPSHOT_AT,
},
},
);
const merged = mergeTaskSession(
existing,
session({
acp: {
session_id: "acp-1",
updated_at: STALE_GOAL_SNAPSHOT_AT,
meta: { goal: null },
},
}),
);
expect(merged.metadata?.acp).toMatchObject({ meta: { goal: ACTIVE_GOAL } });
});
it("accepts a newer goal after a clear", () => {
const existing = session(
{ acp: { session_id: "acp-1", meta: { goal: null } } },
{
goal_reconciliation: {
revision: 2,
cleared: true,
watermark: { createdAt: 10, updatedAt: 20 },
},
},
);
const newerGoal = { ...ACTIVE_GOAL, createdAt: 11, updatedAt: 1 };
const merged = mergeTaskSession(
existing,
session({
acp: { session_id: "acp-1", meta: { goal: newerGoal } },
}),
);
expect(merged.metadata?.acp).toMatchObject({ meta: { goal: newerGoal } });
});
it("invalidates the old goal when the ACP attachment changes", () => {
const existing = session(
{ acp: { session_id: "acp-1", meta: { goal: ACTIVE_GOAL } } },
{
goal_reconciliation: {
revision: 1,
cleared: false,
watermark: { createdAt: 10, updatedAt: 20 },
},
},
);
const attached = mergeTaskSession(
existing,
session({ acp: { session_id: "acp-2", meta: {} } }),
);
expect(attached.metadata?.acp).toMatchObject({ session_id: "acp-2", meta: { goal: null } });
expect(attached.goal_reconciliation).toMatchObject({
cleared: true,
watermark: null,
});
const staleHydration = mergeTaskSession(
attached,
session({ acp: { session_id: "acp-2", meta: { goal: ACTIVE_GOAL } } }),
);
expect(staleHydration.metadata?.acp).toMatchObject({ meta: { goal: null } });
});
});
describe("TaskSession reconnect goal hydration", () => {
it("accepts a fresh reconnect snapshot that clears a live goal", () => {
const existing = session(
{
acp: {
session_id: "acp-1",
updated_at: LIVE_GOAL_SNAPSHOT_AT,
meta: { goal: ACTIVE_GOAL },
},
},
{
goal_reconciliation: {
revision: 1,
cleared: false,
watermark: { createdAt: 10, updatedAt: 20 },
sourceUpdatedAt: LIVE_GOAL_SNAPSHOT_AT,
},
},
);
const merged = mergeTaskSession(
existing,
session({
acp: {
session_id: "acp-1",
updated_at: FRESH_GOAL_SNAPSHOT_AT,
meta: { goal: null },
},
}),
);
expect(merged.metadata?.acp).toMatchObject({ meta: { goal: null } });
expect(merged.goal_reconciliation).toMatchObject({
revision: 2,
cleared: true,
sourceUpdatedAt: FRESH_GOAL_SNAPSHOT_AT,
});
});
it("uses the fresh task snapshot revision when ACP metadata time is unchanged", () => {
const existing = session(
{
acp: {
session_id: "acp-1",
updated_at: LIVE_GOAL_SNAPSHOT_AT,
meta: { goal: ACTIVE_GOAL },
},
},
{
updated_at: LIVE_GOAL_SNAPSHOT_AT,
goal_reconciliation: {
revision: 1,
cleared: false,
watermark: { createdAt: 10, updatedAt: 20 },
sourceUpdatedAt: LIVE_GOAL_SNAPSHOT_AT,
},
},
);
const merged = mergeTaskSession(
existing,
session(
{
acp: {
session_id: "acp-1",
updated_at: LIVE_GOAL_SNAPSHOT_AT,
meta: { goal: null },
},
},
{ updated_at: FRESH_GOAL_SNAPSHOT_AT },
),
);
expect(merged.metadata?.acp).toMatchObject({ meta: { goal: null } });
expect(merged.goal_reconciliation).toMatchObject({
cleared: true,
sourceUpdatedAt: FRESH_GOAL_SNAPSHOT_AT,
});
});
});
@@ -1,5 +1,127 @@
import type { TaskSession } from "@/lib/types/http";
import { mergePendingActionProjection } from "./task-session-projection-actions";
import { getAgentGoal, isAgentGoalSnapshotNewer, mergeAgentGoalMetadata } from "@/lib/agent-goal";
import { parseTurnTimestamp } from "./turn-actions";
function asMetadataRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function hasACPAttachmentChanged(existing: TaskSession, incoming: TaskSession): boolean {
const currentACP = asMetadataRecord(existing.metadata?.acp);
const incomingACP = asMetadataRecord(incoming.metadata?.acp);
const currentSessionID = typeof currentACP?.session_id === "string" ? currentACP.session_id : "";
const incomingSessionID =
typeof incomingACP?.session_id === "string" ? incomingACP.session_id : "";
return (
currentSessionID !== "" && incomingSessionID !== "" && currentSessionID !== incomingSessionID
);
}
function goalReconciliationForAttachment(
metadata: Record<string, unknown> | undefined,
revision: number,
) {
const goal = getAgentGoal(metadata);
return {
revision,
cleared: goal === null,
watermark: goal ? { createdAt: goal.createdAt, updatedAt: goal.updatedAt } : null,
};
}
function mergeGoalReconciliation(
existing: TaskSession,
incoming: TaskSession,
mergedMetadata: TaskSession["metadata"],
attachmentChanged: boolean,
) {
if (incoming.goal_reconciliation) return incoming.goal_reconciliation;
if (!attachmentChanged) {
const reconciliation = existing.goal_reconciliation;
const incomingUpdatedAt = readGoalSnapshotUpdatedAt(incoming);
if (
reconciliation &&
!reconciliation.cleared &&
hasIncomingGoalClear(incoming) &&
incomingUpdatedAt &&
isAgentGoalSnapshotNewer(incomingUpdatedAt, reconciliation)
) {
return {
...reconciliation,
revision: reconciliation.revision + 1,
cleared: true,
sourceUpdatedAt: incomingUpdatedAt,
};
}
return reconciliation;
}
const mergedACP = asMetadataRecord(mergedMetadata?.acp);
const mergedMeta = asMetadataRecord(mergedACP?.meta);
return goalReconciliationForAttachment(
mergedMeta,
(existing.goal_reconciliation?.revision ?? 0) + 1,
);
}
function readACPUpdatedAt(value: unknown): string | undefined {
const record = asMetadataRecord(value);
return typeof record?.updated_at === "string" ? record.updated_at : undefined;
}
function readGoalSnapshotUpdatedAt(session: TaskSession): string | undefined {
const candidates = [readACPUpdatedAt(session.metadata?.acp), session.updated_at];
let newest: string | undefined;
let newestTime: bigint | null = null;
for (const candidate of candidates) {
const candidateTime = parseTurnTimestamp(candidate);
if (candidateTime === null || (newestTime !== null && candidateTime <= newestTime)) continue;
newest = candidate;
newestTime = candidateTime;
}
return newest;
}
function hasIncomingGoalClear(session: TaskSession): boolean {
const acp = asMetadataRecord(session.metadata?.acp);
const meta = asMetadataRecord(acp?.meta);
return meta?.goal === null && Object.prototype.hasOwnProperty.call(meta ?? {}, "goal");
}
function mergeSessionMetadata(
existing: TaskSession,
incoming: TaskSession,
): TaskSession["metadata"] {
if (incoming.metadata == null) return existing.metadata;
const current = existing.metadata ?? {};
const next = { ...current, ...incoming.metadata };
const currentACP = asMetadataRecord(current.acp);
const incomingACP = asMetadataRecord(incoming.metadata.acp);
if (!currentACP && !incomingACP) return next;
const currentACPRecord = currentACP ?? {};
const incomingACPRecord = incomingACP ?? {};
const attachmentChanged = hasACPAttachmentChanged(existing, incoming);
const mergedACP = { ...currentACPRecord, ...incomingACPRecord };
if (incoming.goal_reconciliation) {
mergedACP.meta = incomingACPRecord.meta;
} else if (incomingACPRecord.meta !== undefined || attachmentChanged) {
const currentMeta = asMetadataRecord(currentACPRecord.meta);
const incomingMeta = asMetadataRecord(incomingACPRecord.meta);
mergedACP.meta = mergeAgentGoalMetadata(currentMeta, incomingMeta, {
attachmentChanged,
source: "hydration",
reconciliation: existing.goal_reconciliation,
snapshotUpdatedAt: readGoalSnapshotUpdatedAt(incoming),
});
} else if (currentACPRecord.meta !== undefined) {
mergedACP.meta = currentACPRecord.meta;
}
next.acp = mergedACP;
return next;
}
/** Merge the runtime cancellation projection using its process-local revision. */
function mergeCancellationProjection(
@@ -97,7 +219,16 @@ export function mergeTaskSession(existing: TaskSession, incoming: TaskSession):
existingRouteGeneration !== undefined &&
(incomingRouteGeneration === undefined || incomingRouteGeneration < existingRouteGeneration);
const pendingAction = mergePendingActionProjection(existing, incoming);
const attachmentChanged = hasACPAttachmentChanged(existing, incoming);
const merged = { ...existing, ...incoming };
merged.metadata = mergeSessionMetadata(existing, incoming);
const goalReconciliation = mergeGoalReconciliation(
existing,
incoming,
merged.metadata,
attachmentChanged,
);
if (goalReconciliation) merged.goal_reconciliation = goalReconciliation;
// A backend session update never carries the frontend-only projection owner.
// Its absence is the revocation signal for an optimistic resume rollback.
if (incoming.resume_projection_id === undefined) delete merged.resume_projection_id;
@@ -1,5 +1,4 @@
import type { Draft } from "immer";
import { getQuickChatSetupSessionId } from "./quick-chat-session";
import {
clearMarker,
closeQuickChatSession,
@@ -10,9 +9,25 @@ import {
removeQuickChatSessionsForTask,
upsertQuickChatSession,
} from "./quick-chat-sync";
import type { QuickChatSession, UISlice } from "./types";
import {
clearRememberedQuickChatSelection,
clearRememberedQuickChatSession,
clearSelectionOrderIfEmpty,
rememberQuickChatSelection,
restoreQuickChatSession,
touchQuickChatSelectionOrder,
} from "./quick-chat-selection";
import {
loadQuickChatSelection,
persistQuickChatSelection,
} from "@/lib/quick-chat/selection-storage";
import { getQuickChatSetupSessionId, isQuickChatSetupSessionId } from "./quick-chat-session";
import type { QuickChatSession, QuickChatSessionKind, QuickChatState, UISlice } from "./types";
type ImmerSet = (recipe: (draft: Draft<UISlice>) => void) => void;
type ImmerGet = () => Pick<UISlice, "quickChat"> & {
userSettings?: { quickChatTabOrderByWorkspace?: Record<string, string[]> };
};
function findWorkspaceConfigSession(
sessions: UISlice["quickChat"]["sessions"],
@@ -43,15 +58,139 @@ function upsertQuickChatSessionDraft(
return true;
}
function openQuickChat(set: ImmerSet) {
function persistRememberedSelection(get: ImmerGet): void {
const quickChat = get().quickChat;
persistQuickChatSelection(
quickChat.selectionStorageIdentity,
quickChat.rememberedSelectionByWorkspace,
quickChat.rememberedSelectionOrder,
);
}
function bumpSelectionRevision(quickChat: Draft<QuickChatState>, workspaceId: string): void {
quickChat.selectionRevisionByWorkspace[workspaceId] =
(quickChat.selectionRevisionByWorkspace[workspaceId] ?? 0) + 1;
if (quickChat.pendingOpen?.workspaceId === workspaceId) quickChat.pendingOpen = null;
}
function rememberSelectedSession(
quickChat: Draft<QuickChatState>,
session: QuickChatSession,
): void {
const kind = session.kind ?? "chat";
bumpSelectionRevision(quickChat, session.workspaceId);
if (isQuickChatSetupSessionId(session.sessionId)) return;
quickChat.rememberedSelectionByWorkspace = rememberQuickChatSelection(
quickChat.rememberedSelectionByWorkspace,
session.workspaceId,
kind,
session.sessionId,
);
quickChat.rememberedSelectionOrder = touchQuickChatSelectionOrder(
quickChat.rememberedSelectionOrder,
session.workspaceId,
);
}
function clearRememberedSession(
quickChat: Draft<QuickChatState>,
sessions: QuickChatSession[],
sessionId: string,
): void {
const session = sessions.find((item) => item.sessionId === sessionId);
if (!session) return;
const next = clearRememberedQuickChatSession(
quickChat.rememberedSelectionByWorkspace,
sessions,
sessionId,
);
if (next === quickChat.rememberedSelectionByWorkspace) return;
quickChat.rememberedSelectionByWorkspace = next;
quickChat.rememberedSelectionOrder = clearSelectionOrderIfEmpty(
quickChat.rememberedSelectionOrder,
next,
);
bumpSelectionRevision(quickChat, session.workspaceId);
}
function clearMissingRememberedSelections(
quickChat: Draft<QuickChatState>,
workspaceId: string,
serverSessions: QuickChatSession[],
): void {
const serverIdsByKind = new Map<QuickChatSessionKind, Set<string>>();
for (const kind of ["chat", "config"] as const) {
serverIdsByKind.set(
kind,
new Set(
serverSessions
.filter((session) => (session.kind ?? "chat") === kind)
.map((session) => session.sessionId),
),
);
}
for (const kind of ["chat", "config"] as const) {
const selected = quickChat.rememberedSelectionByWorkspace[workspaceId]?.[kind];
if (!selected || serverIdsByKind.get(kind)?.has(selected)) continue;
const next = clearRememberedQuickChatSelection(
quickChat.rememberedSelectionByWorkspace,
workspaceId,
kind,
);
quickChat.rememberedSelectionByWorkspace = next;
quickChat.rememberedSelectionOrder = clearSelectionOrderIfEmpty(
quickChat.rememberedSelectionOrder,
next,
);
}
}
function resolvePendingOpen(
quickChat: Draft<QuickChatState>,
workspaceId: string,
sessions: QuickChatSession[],
persistedTabOrder?: string[],
): void {
const pending = quickChat.pendingOpen;
if (
!pending ||
pending.workspaceId !== workspaceId ||
pending.selectionRevision !== (quickChat.selectionRevisionByWorkspace[workspaceId] ?? 0)
)
return;
const sessionId = restoreQuickChatSession(
sessions,
quickChat.rememberedSelectionByWorkspace,
workspaceId,
pending.kind,
pending.tabOrder ?? quickChat.tabOrderByWorkspace[workspaceId] ?? persistedTabOrder,
);
if (sessionId) {
quickChat.activeSessionId = sessionId;
quickChat.activeKind = "conversation";
} else {
const setupSessionId = getQuickChatSetupSessionId(workspaceId, pending.kind);
if (!quickChat.sessions.some((session) => session.sessionId === setupSessionId)) {
quickChat.sessions.push({ sessionId: setupSessionId, workspaceId, kind: pending.kind });
}
quickChat.activeSessionId = setupSessionId;
quickChat.activeKind = "conversation";
}
quickChat.isOpen = true;
quickChat.pendingOpen = null;
}
function openQuickChat(set: ImmerSet, get: ImmerGet) {
return (
sessionId: string,
workspaceId: string,
agentProfileId?: string,
kind: "chat" | "config" = "chat",
taskId?: string,
) =>
) => {
set((draft) => {
draft.quickChat.pendingOpen = null;
if (!sessionId) {
const existing =
kind === "config"
@@ -67,6 +206,7 @@ function openQuickChat(set: ImmerSet) {
draft.quickChat.isOpen = true;
draft.quickChat.activeSessionId = existing?.sessionId ?? setupSessionId;
draft.quickChat.activeKind = "conversation";
bumpSelectionRevision(draft.quickChat, workspaceId);
// The dialog is open now, so every workspace's dots are obsolete.
draft.quickChat.unseenIdleByWorkspace = {};
return;
@@ -84,21 +224,26 @@ function openQuickChat(set: ImmerSet) {
draft.quickChat.isOpen = true;
draft.quickChat.activeSessionId = sessionId;
draft.quickChat.activeKind = "conversation";
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
if (session) rememberSelectedSession(draft.quickChat, session);
// Only a successful open clears the dots; a rejected cross-workspace open
// must not erase markers the user never saw.
draft.quickChat.unseenIdleByWorkspace = {};
});
persistRememberedSelection(get);
};
}
function addQuickChatSession(set: ImmerSet) {
function addQuickChatSession(set: ImmerSet, get: ImmerGet) {
return (
sessionId: string,
workspaceId: string,
agentProfileId?: string,
kind: "chat" | "config" = "chat",
taskId?: string,
) =>
) => {
set((draft) => {
draft.quickChat.pendingOpen = null;
const activeWorkspaceId = draft.quickChat.sessions.find(
(session) => session.sessionId === draft.quickChat.activeSessionId,
)?.workspaceId;
@@ -115,8 +260,12 @@ function addQuickChatSession(set: ImmerSet) {
if (!draft.quickChat.isOpen || !activeWorkspaceId || activeWorkspaceId === workspaceId) {
draft.quickChat.activeSessionId = sessionId;
draft.quickChat.activeKind = "conversation";
const active = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
if (active) rememberSelectedSession(draft.quickChat, active);
}
});
persistRememberedSelection(get);
};
}
function buildQuickChatOrderActions(set: ImmerSet) {
@@ -148,20 +297,71 @@ function buildQuickChatOrderActions(set: ImmerSet) {
};
}
export function buildQuickChatActions(set: ImmerSet) {
function closeQuickChatAction(set: ImmerSet) {
return () =>
set((draft) => {
draft.quickChat.isOpen = false;
if (draft.quickChat.pendingOpen) {
bumpSelectionRevision(draft.quickChat, draft.quickChat.pendingOpen.workspaceId);
draft.quickChat.pendingOpen = null;
}
});
}
function closeQuickChatSessionAction(set: ImmerSet, get: ImmerGet) {
return (sessionId: string) => {
const sessions = get().quickChat.sessions;
set((draft) => {
const closing = sessions.find((session) => session.sessionId === sessionId);
const wasActiveConversation =
draft.quickChat.activeKind === "conversation" &&
draft.quickChat.activeSessionId === sessionId;
draft.quickChat = closeQuickChatSession(draft.quickChat, sessionId);
clearRememberedSession(draft.quickChat, sessions, sessionId);
if (!closing || !wasActiveConversation) return;
const replacement = draft.quickChat.sessions.find(
(session) => session.sessionId === draft.quickChat.activeSessionId,
);
if (
replacement &&
replacement.workspaceId === closing.workspaceId &&
(replacement.kind ?? "chat") === (closing.kind ?? "chat")
) {
rememberSelectedSession(draft.quickChat, replacement);
}
});
persistRememberedSelection(get);
};
}
function syncQuickChatSessionsAction(set: ImmerSet, get: ImmerGet) {
return (workspaceId: string, sessions: QuickChatSession[]) => {
set((draft) => {
if (draft.quickChat.pendingOpen?.workspaceId !== workspaceId) {
draft.quickChat.pendingOpen = null;
}
draft.quickChat = reconcileQuickChatSessions(draft.quickChat, workspaceId, sessions);
clearMissingRememberedSelections(draft.quickChat, workspaceId, sessions);
draft.quickChat.selectionReadyByWorkspace[workspaceId] = true;
resolvePendingOpen(
draft.quickChat,
workspaceId,
sessions,
get().userSettings?.quickChatTabOrderByWorkspace?.[workspaceId],
);
});
persistRememberedSelection(get);
};
}
function buildQuickChatSessionActions(set: ImmerSet, get: ImmerGet) {
return {
...buildQuickChatOrderActions(set),
addQuickChatSession: addQuickChatSession(set),
openQuickChat: openQuickChat(set),
closeQuickChat: () =>
set((draft) => {
draft.quickChat.isOpen = false;
}),
closeQuickChatSession: (sessionId: string) =>
set((draft) => {
draft.quickChat = closeQuickChatSession(draft.quickChat, sessionId);
}),
setActiveQuickChatSession: (sessionId: string, workspaceId: string) =>
addQuickChatSession: addQuickChatSession(set, get),
openQuickChat: openQuickChat(set, get),
closeQuickChat: closeQuickChatAction(set),
closeQuickChatSession: closeQuickChatSessionAction(set, get),
setActiveQuickChatSession: (sessionId: string, workspaceId: string) => {
let selected = false;
set((draft) => {
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
if (!session || session.workspaceId !== workspaceId) return;
@@ -170,9 +370,14 @@ export function buildQuickChatActions(set: ImmerSet) {
workspaceId,
sessionId,
);
draft.quickChat.pendingOpen = null;
draft.quickChat.activeSessionId = sessionId;
draft.quickChat.activeKind = "conversation";
}),
rememberSelectedSession(draft.quickChat, session);
selected = true;
});
if (selected) persistRememberedSelection(get);
},
renameQuickChatSession: (sessionId: string, name: string) =>
set((draft) => {
const session = draft.quickChat.sessions.find((item) => item.sessionId === sessionId);
@@ -181,10 +386,7 @@ export function buildQuickChatActions(set: ImmerSet) {
draft.quickChat.syncRevisionByWorkspace[session.workspaceId] =
(draft.quickChat.syncRevisionByWorkspace[session.workspaceId] ?? 0) + 1;
}),
syncQuickChatSessions: (workspaceId: string, sessions: QuickChatSession[]) =>
set((draft) => {
draft.quickChat = reconcileQuickChatSessions(draft.quickChat, workspaceId, sessions);
}),
syncQuickChatSessions: syncQuickChatSessionsAction(set, get),
syncQuickTerminalTabs: (workspaceId: string, tabs: UISlice["quickChat"]["terminalTabs"]) =>
set((draft) => {
draft.quickChat = reconcileQuickTerminalTabs(draft.quickChat, workspaceId, tabs);
@@ -193,14 +395,28 @@ export function buildQuickChatActions(set: ImmerSet) {
set((draft) => {
draft.quickChat = upsertQuickChatSession(draft.quickChat, session);
}),
removeQuickChatSessionsForTask: (taskId: string) =>
removeQuickChatSessionsForTask: (taskId: string) => {
const sessions = get().quickChat.sessions.filter((session) => session.taskId === taskId);
set((draft) => {
draft.quickChat = removeQuickChatSessionsForTask(draft.quickChat, taskId);
}),
removeQuickChatSession: (sessionId: string) =>
for (const session of sessions)
clearRememberedSession(draft.quickChat, sessions, session.sessionId);
});
persistRememberedSelection(get);
},
removeQuickChatSession: (sessionId: string) => {
const sessions = get().quickChat.sessions;
set((draft) => {
draft.quickChat = removeQuickChatSession(draft.quickChat, sessionId);
}),
clearRememberedSession(draft.quickChat, sessions, sessionId);
});
persistRememberedSelection(get);
},
};
}
function buildQuickChatActivityActions(set: ImmerSet) {
return {
markQuickChatUnseenIdle: (sessionId: string, workspaceId: string) =>
set((draft) => {
draft.quickChat.unseenIdleByWorkspace[workspaceId] = {
@@ -248,3 +464,48 @@ export function buildQuickChatActions(set: ImmerSet) {
}),
};
}
function buildQuickChatSelectionActions(set: ImmerSet) {
return {
requestQuickChatOpen: (
workspaceId: string,
kind: QuickChatSessionKind = "chat",
tabOrder?: string[],
) =>
set((draft) => {
const selectionRevision = draft.quickChat.selectionRevisionByWorkspace[workspaceId] ?? 0;
draft.quickChat.pendingOpen = {
workspaceId,
kind,
selectionRevision,
...(tabOrder ? { tabOrder: [...tabOrder] } : {}),
};
draft.quickChat.isOpen = true;
draft.quickChat.activeKind = "conversation";
draft.quickChat.activeSessionId = null;
draft.quickChat.activeTerminalTabId = null;
draft.quickChat.unseenIdleByWorkspace = {};
}),
setQuickChatSelectionIdentity: (identity: string | null) =>
set((draft) => {
if (draft.quickChat.selectionStorageIdentity === identity) return;
const hadSelectionIdentity = draft.quickChat.selectionStorageIdentity !== null;
const loaded = loadQuickChatSelection(identity);
draft.quickChat.selectionStorageIdentity = identity;
draft.quickChat.rememberedSelectionByWorkspace = loaded.selections;
draft.quickChat.rememberedSelectionOrder = loaded.order;
if (hadSelectionIdentity) draft.quickChat.selectionReadyByWorkspace = {};
draft.quickChat.selectionRevisionByWorkspace = {};
draft.quickChat.pendingOpen = null;
}),
};
}
export function buildQuickChatActions(set: ImmerSet, get: ImmerGet) {
return {
...buildQuickChatOrderActions(set),
...buildQuickChatSessionActions(set, get),
...buildQuickChatActivityActions(set),
...buildQuickChatSelectionActions(set),
};
}
@@ -0,0 +1,204 @@
import { describe, expect, it, beforeEach } from "vitest";
import { create } from "zustand";
import { immer } from "zustand/middleware/immer";
import { createUISlice } from "./ui-slice";
import type { UISlice } from "./types";
import { createAppStore } from "@/lib/state/store";
const WORKSPACE_A = "workspace-a";
const WORKSPACE_B = "workspace-b";
const CHAT_FIRST_ID = "chat-first";
const CHAT_SECOND_ID = "chat-second";
const SESSION_A = "session-a";
const SESSION_B = "session-b";
function makeStore() {
return create<UISlice>()(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
immer((...args) => ({ ...(createUISlice as any)(...args) })),
);
}
beforeEach(() => {
window.localStorage.clear();
});
describe("Quick Chat remembered selection actions", () => {
it("persists chat and config selections separately for each workspace", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("chat-a", WORKSPACE_A, undefined, "chat");
store.getState().openQuickChat("config-a", WORKSPACE_A, undefined, "config");
store.getState().openQuickChat("chat-b", WORKSPACE_B, undefined, "chat");
expect(store.getState().quickChat.rememberedSelectionByWorkspace).toEqual({
[WORKSPACE_A]: { chat: "chat-a", config: "config-a" },
[WORKSPACE_B]: { chat: "chat-b" },
});
const reloaded = makeStore();
reloaded.getState().setQuickChatSelectionIdentity("user-a");
expect(reloaded.getState().quickChat.rememberedSelectionByWorkspace).toEqual(
store.getState().quickChat.rememberedSelectionByWorkspace,
);
});
it("does not let terminal activation change the remembered conversation", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("chat-a", WORKSPACE_A);
const before = store.getState().quickChat.rememberedSelectionByWorkspace;
store.getState().createQuickTerminal(WORKSPACE_A);
expect(store.getState().quickChat.rememberedSelectionByWorkspace).toEqual(before);
});
it("does not persist a temporary setup tab as a remembered conversation", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("", WORKSPACE_A);
expect(store.getState().quickChat.rememberedSelectionByWorkspace).toEqual({});
expect(window.localStorage.getItem("kandev.quick-chat.selection.v1.user-a")).toBe(
'{"version":1,"entries":[]}',
);
});
it("resolves a pending open to the remembered tab after the workspace list arrives", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("chat-remembered", WORKSPACE_A);
store.getState().closeQuickChat();
store.getState().requestQuickChatOpen(WORKSPACE_A);
store.getState().syncQuickChatSessions(WORKSPACE_A, [
{ sessionId: CHAT_FIRST_ID, workspaceId: WORKSPACE_A, kind: "chat" },
{ sessionId: "chat-remembered", workspaceId: WORKSPACE_A, kind: "chat" },
]);
expect(store.getState().quickChat).toMatchObject({
activeSessionId: "chat-remembered",
pendingOpen: null,
isOpen: true,
selectionReadyByWorkspace: { [WORKSPACE_A]: true },
});
});
it("falls back and clears a missing remembered tab when the list arrives", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("chat-removed", WORKSPACE_A);
store.getState().closeQuickChat();
store.getState().requestQuickChatOpen(WORKSPACE_A);
store
.getState()
.syncQuickChatSessions(WORKSPACE_A, [
{ sessionId: "chat-first", workspaceId: WORKSPACE_A, kind: "chat" },
]);
expect(store.getState().quickChat).toMatchObject({
activeSessionId: CHAT_FIRST_ID,
pendingOpen: null,
isOpen: true,
});
expect(store.getState().quickChat.rememberedSelectionByWorkspace).toEqual({});
});
});
describe("Quick Chat selection races", () => {
it("uses the captured persisted order after a remembered tab is removed", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("chat-removed", WORKSPACE_A);
store.getState().closeQuickChat();
store
.getState()
.requestQuickChatOpen(WORKSPACE_A, "chat", [
`conversation:${CHAT_SECOND_ID}`,
`conversation:${CHAT_FIRST_ID}`,
]);
store.getState().syncQuickChatSessions(WORKSPACE_A, [
{ sessionId: CHAT_FIRST_ID, workspaceId: WORKSPACE_A, kind: "chat" },
{ sessionId: CHAT_SECOND_ID, workspaceId: WORKSPACE_A, kind: "chat" },
]);
expect(store.getState().quickChat.activeSessionId).toBe(CHAT_SECOND_ID);
expect(store.getState().quickChat.rememberedSelectionByWorkspace).toEqual({});
});
it("uses user settings order when a delayed open has no optimistic order", () => {
const store = createAppStore();
store.getState().setUserSettings({
...store.getState().userSettings,
quickChatTabOrderByWorkspace: {
[WORKSPACE_A]: [`conversation:${CHAT_SECOND_ID}`, `conversation:${CHAT_FIRST_ID}`],
},
});
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat("chat-removed", WORKSPACE_A);
store.getState().closeQuickChat();
store.getState().requestQuickChatOpen(WORKSPACE_A);
store.getState().syncQuickChatSessions(WORKSPACE_A, [
{ sessionId: CHAT_FIRST_ID, workspaceId: WORKSPACE_A, kind: "chat" },
{ sessionId: CHAT_SECOND_ID, workspaceId: WORKSPACE_A, kind: "chat" },
]);
expect(store.getState().quickChat.activeSessionId).toBe(CHAT_SECOND_ID);
});
it("preserves accepted boot readiness while loading the selection identity", () => {
const store = createAppStore({
workspaces: { items: [], activeId: WORKSPACE_A },
quickChat: { sessions: [] },
});
expect(store.getState().quickChat.selectionReadyByWorkspace).toEqual({
[WORKSPACE_A]: true,
});
});
it("remembers the replacement when the selected tab is closed", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat(SESSION_A, WORKSPACE_A);
store.getState().openQuickChat(SESSION_B, WORKSPACE_A);
store.getState().setActiveQuickChatSession(SESSION_A, WORKSPACE_A);
store.getState().closeQuickChatSession(SESSION_A);
expect(store.getState().quickChat).toMatchObject({
activeSessionId: SESSION_B,
rememberedSelectionByWorkspace: { [WORKSPACE_A]: { chat: SESSION_B } },
});
});
it("invalidates a pending open when its remembered tab is removed", () => {
const store = makeStore();
store.getState().setQuickChatSelectionIdentity("user-a");
store.getState().openQuickChat(SESSION_A, WORKSPACE_A);
store.getState().closeQuickChat();
store.getState().requestQuickChatOpen(WORKSPACE_A);
store.getState().closeQuickChatSession(SESSION_A);
expect(store.getState().quickChat.pendingOpen).toBeNull();
});
it("cancels a pending open when another workspace finishes syncing", () => {
const store = makeStore();
store.getState().requestQuickChatOpen(WORKSPACE_A);
store
.getState()
.syncQuickChatSessions(WORKSPACE_B, [
{ sessionId: SESSION_B, workspaceId: WORKSPACE_B, kind: "chat" },
]);
expect(store.getState().quickChat.pendingOpen).toBeNull();
});
});
@@ -0,0 +1,55 @@
import { describe, expect, it } from "vitest";
import type { QuickChatSession } from "./types";
import {
clearRememberedQuickChatSelection,
findRememberedQuickChatSession,
rememberQuickChatSelection,
restoreQuickChatSession,
} from "./quick-chat-selection";
const WORKSPACE_A = "workspace-a";
const WORKSPACE_B = "workspace-b";
const sessions: QuickChatSession[] = [
{ sessionId: "chat-first", workspaceId: WORKSPACE_A, kind: "chat" },
{ sessionId: "chat-second", workspaceId: WORKSPACE_A, kind: "chat" },
{ sessionId: "config-a", workspaceId: WORKSPACE_A, kind: "config" },
{ sessionId: "chat-other", workspaceId: WORKSPACE_B, kind: "chat" },
];
describe("Quick Chat remembered selection", () => {
it("restores the remembered session only for its workspace and kind", () => {
const remembered = { [WORKSPACE_A]: { chat: "chat-second", config: "config-a" } };
expect(findRememberedQuickChatSession(sessions, remembered, WORKSPACE_A, "chat")).toEqual(
sessions[1],
);
expect(findRememberedQuickChatSession(sessions, remembered, WORKSPACE_B, "chat")).toBe(
undefined,
);
expect(findRememberedQuickChatSession(sessions, remembered, WORKSPACE_A, "config")).toEqual(
sessions[2],
);
});
it("falls back in displayed order when the remembered session is unavailable", () => {
const remembered = { [WORKSPACE_A]: { chat: "deleted" } };
expect(
restoreQuickChatSession(sessions, remembered, WORKSPACE_A, "chat", [
"conversation:chat-second",
"conversation:chat-first",
]),
).toBe("chat-second");
});
it("updates and clears one workspace-kind preference without touching siblings", () => {
const initial = { [WORKSPACE_A]: { chat: "chat-first", config: "config-a" } };
const remembered = rememberQuickChatSelection(initial, WORKSPACE_B, "chat", "chat-other");
const cleared = clearRememberedQuickChatSelection(remembered, WORKSPACE_A, "chat");
expect(cleared).toEqual({
[WORKSPACE_A]: { config: "config-a" },
[WORKSPACE_B]: { chat: "chat-other" },
});
});
});
@@ -0,0 +1,98 @@
import { orderQuickChatTabs } from "./quick-chat-tab-order";
import { isQuickChatSetupSessionId } from "./quick-chat-session";
import type {
QuickChatSelection,
QuickChatSelectionByWorkspace,
QuickChatSelectionOrder,
QuickChatSession,
QuickChatSessionKind,
} from "./types";
export function rememberQuickChatSelection(
selections: QuickChatSelectionByWorkspace,
workspaceId: string,
kind: QuickChatSessionKind,
sessionId: string,
): QuickChatSelectionByWorkspace {
return {
...selections,
[workspaceId]: {
...selections[workspaceId],
[kind]: sessionId,
},
};
}
export function clearRememberedQuickChatSelection(
selections: QuickChatSelectionByWorkspace,
workspaceId: string,
kind: QuickChatSessionKind,
): QuickChatSelectionByWorkspace {
const current = selections[workspaceId];
if (!current || !current[kind]) return selections;
const next: QuickChatSelection = { ...current };
delete next[kind];
if (Object.keys(next).length === 0) {
const { [workspaceId]: _removed, ...remaining } = selections;
return remaining;
}
return { ...selections, [workspaceId]: next };
}
export function clearRememberedQuickChatSession(
selections: QuickChatSelectionByWorkspace,
sessions: QuickChatSession[],
sessionId: string,
): QuickChatSelectionByWorkspace {
const session = sessions.find((item) => item.sessionId === sessionId);
if (!session) return selections;
const kind = session.kind ?? "chat";
if (selections[session.workspaceId]?.[kind] !== sessionId) return selections;
return clearRememberedQuickChatSelection(selections, session.workspaceId, kind);
}
export function findRememberedQuickChatSession(
sessions: QuickChatSession[],
selections: QuickChatSelectionByWorkspace,
workspaceId: string,
kind: QuickChatSessionKind,
): QuickChatSession | undefined {
const sessionId = selections[workspaceId]?.[kind];
if (!sessionId || isQuickChatSetupSessionId(sessionId)) return undefined;
return sessions.find(
(session) =>
session.sessionId === sessionId &&
session.workspaceId === workspaceId &&
(session.kind ?? "chat") === kind,
);
}
export function restoreQuickChatSession(
sessions: QuickChatSession[],
selections: QuickChatSelectionByWorkspace,
workspaceId: string,
kind: QuickChatSessionKind,
savedOrder: QuickChatSelectionOrder = [],
): string | undefined {
const remembered = findRememberedQuickChatSession(sessions, selections, workspaceId, kind);
if (remembered) return remembered.sessionId;
const matching = sessions.filter(
(session) => session.workspaceId === workspaceId && (session.kind ?? "chat") === kind,
);
return orderQuickChatTabs(matching, [], savedOrder).sessions[0]?.sessionId;
}
export function touchQuickChatSelectionOrder(
order: QuickChatSelectionOrder,
workspaceId: string,
): QuickChatSelectionOrder {
return [workspaceId, ...order.filter((item) => item !== workspaceId)];
}
export function clearSelectionOrderIfEmpty(
order: QuickChatSelectionOrder,
selections: QuickChatSelectionByWorkspace,
): QuickChatSelectionOrder {
return order.filter((workspaceId) => Boolean(selections[workspaceId]));
}
@@ -48,6 +48,12 @@ function state(sessions: QuickChatSession[], overrides: Partial<QuickChatState>
tabOrderByWorkspace: {},
tabOrderSyncErrorByWorkspace: {},
tabOrderSyncPendingByWorkspace: {},
rememberedSelectionByWorkspace: {},
rememberedSelectionOrder: [],
selectionStorageIdentity: null,
selectionReadyByWorkspace: {},
selectionRevisionByWorkspace: {},
pendingOpen: null,
...overrides,
};
}
@@ -62,6 +62,14 @@ function findTerminalFallback(
);
}
function cancelPendingConversationOpen(quickChat: QuickChatState): void {
const pending = quickChat.pendingOpen;
if (!pending) return;
quickChat.selectionRevisionByWorkspace[pending.workspaceId] =
(quickChat.selectionRevisionByWorkspace[pending.workspaceId] ?? 0) + 1;
quickChat.pendingOpen = null;
}
export function activateWorkspaceFallback(quickChat: QuickChatState, workspaceId?: string): void {
if (!workspaceId) {
quickChat.activeSessionId = null;
@@ -107,6 +115,7 @@ export function buildQuickTerminalActions(set: ImmerSet) {
reuseOrCreateQuickTerminal: (workspaceId: string) => {
let tabId = "";
set((draft) => {
cancelPendingConversationOpen(draft.quickChat);
const lastId = draft.quickChat.lastTerminalTabIdByWorkspace[workspaceId];
const existing = findWorkspaceTerminal(draft.quickChat.terminalTabs, workspaceId, lastId);
const fallback =
@@ -119,6 +128,7 @@ export function buildQuickTerminalActions(set: ImmerSet) {
createQuickTerminal: (workspaceId: string) => {
let tabId = "";
set((draft) => {
cancelPendingConversationOpen(draft.quickChat);
tabId = createQuickTerminalDraft(draft.quickChat, workspaceId);
});
return tabId;
@@ -143,6 +153,7 @@ export function buildQuickTerminalActions(set: ImmerSet) {
set((draft) => {
const tab = draft.quickChat.terminalTabs.find((item) => item.tabId === tabId);
if (!tab || tab.workspaceId !== workspaceId) return;
cancelPendingConversationOpen(draft.quickChat);
activateTerminalDraft(draft.quickChat, tab);
}),
removeQuickTerminal: (tabId: string) =>
+34
View File
@@ -118,6 +118,20 @@ export type SystemHealthState = {
export type QuickChatSessionKind = "chat" | "config";
export type QuickChatSelection = Partial<Record<QuickChatSessionKind, string>>;
export type QuickChatSelectionByWorkspace = Record<string, QuickChatSelection>;
export type QuickChatSelectionOrder = string[];
export type QuickChatPendingOpen = {
workspaceId: string;
kind: QuickChatSessionKind;
selectionRevision: number;
/** Effective order captured by the launcher while the authoritative list is pending. */
tabOrder?: QuickChatSelectionOrder;
};
export type QuickTerminalStatus = "connecting" | "running" | "exited" | "error";
export type QuickTerminalTab = {
@@ -178,6 +192,18 @@ export type QuickChatState = {
tabOrderByWorkspace: Record<string, string[]>;
tabOrderSyncErrorByWorkspace: Record<string, string | null>;
tabOrderSyncPendingByWorkspace: Record<string, boolean>;
/** Browser-local last explicit conversation selection by workspace and kind. */
rememberedSelectionByWorkspace: QuickChatSelectionByWorkspace;
/** Most recently touched workspace first, for bounded browser storage. */
rememberedSelectionOrder: QuickChatSelectionOrder;
/** Null means the current authenticated identity cannot use browser storage. */
selectionStorageIdentity: string | null;
/** A workspace is ready only after an accepted boot or list snapshot. */
selectionReadyByWorkspace: Record<string, boolean>;
/** Monotonic revisions invalidate pending generic opens after user actions. */
selectionRevisionByWorkspace: Record<string, number>;
/** Generic launcher request waiting for an authoritative workspace list. */
pendingOpen: QuickChatPendingOpen | null;
};
export type SessionFailureNotification = {
@@ -397,6 +423,14 @@ export type UISliceActions = {
state: { pending: boolean; error: string | null },
) => void;
setQuickChatInitialPrompt: (sessionId: string, prompt?: string) => void;
/** Opens Quick Chat after the requested workspace list becomes authoritative. */
requestQuickChatOpen: (
workspaceId: string,
kind?: QuickChatSessionKind,
tabOrder?: QuickChatSelectionOrder,
) => void;
/** Loads the browser-local selection map for a new authentication identity. */
setQuickChatSelectionIdentity: (identity: string | null) => void;
setSessionFailureNotification: (n: SessionFailureNotification | null) => void;
setTaskDeletedNotification: (n: TaskDeletedNotification | null) => void;
setUpdateAvailableNotification: (n: UpdateAvailableNotification | null) => void;
+7 -1
View File
@@ -149,6 +149,12 @@ export const defaultUIState: UISliceState = {
tabOrderByWorkspace: {},
tabOrderSyncErrorByWorkspace: {},
tabOrderSyncPendingByWorkspace: {},
rememberedSelectionByWorkspace: {},
rememberedSelectionOrder: [],
selectionStorageIdentity: null,
selectionReadyByWorkspace: {},
selectionRevisionByWorkspace: {},
pendingOpen: null,
},
sessionFailureNotification: null,
taskDeletedNotification: null,
@@ -385,7 +391,7 @@ export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], []
...buildDismissedAgentErrors(set),
...buildNotificationActions(set),
...buildQuickTerminalActions(set),
...buildQuickChatActions(set),
...buildQuickChatActions(set, get),
setRightPanelActiveTab: (sessionId, tab) =>
set((draft) => {
draft.rightPanel.activeTabBySessionId[sessionId] = tab;
+16 -1
View File
@@ -4,6 +4,7 @@ import { hydrateState } from "./hydration/hydrator";
import type { AppState, HydrationState } from "./app-state-types";
import { mergeInitialState } from "./default-state";
import { buildStateOverrides } from "./store-overrides";
import { getQuickChatSelectionIdentity } from "@/lib/quick-chat/selection-storage";
import {
createKanbanSlice,
@@ -36,7 +37,7 @@ export type * from "./store-reexports";
export function createAppStore(initialState?: HydrationState) {
const merged = mergeInitialState(initialState);
return createStore<AppState>()(
const store = createStore<AppState>()(
immer((set, get, api) => ({
...merged,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -88,6 +89,20 @@ export function createAppStore(initialState?: HydrationState) {
hydrate: (state, options) => set((draft) => hydrateState(draft as any, state, options)),
})),
);
let previousAuth = store.getState().auth;
const syncQuickChatSelectionIdentity = (auth: AppState["auth"]) => {
const identity = getQuickChatSelectionIdentity(auth);
if (store.getState().quickChat.selectionStorageIdentity !== identity) {
store.getState().setQuickChatSelectionIdentity(identity);
}
};
syncQuickChatSelectionIdentity(previousAuth);
store.subscribe((state) => {
if (state.auth === previousAuth) return;
previousAuth = state.auth;
syncQuickChatSelectionIdentity(state.auth);
});
return store;
}
export type StoreProviderProps = {
+3
View File
@@ -19,6 +19,7 @@ import type {
import type { OnEnterActionType, StepEvents } from "./workflow-actions";
import type { EntityReference } from "./entity-reference";
import type { TaskStatusSummary } from "./task-status-summary";
import type { AgentGoalReconciliation } from "@/lib/agent-goal";
export type { TaskStatusSummary } from "./task-status-summary";
@@ -690,6 +691,8 @@ export type TaskSession = ActiveSubagentCountFields & {
pending_action_revision?: TaskPendingActionRevision;
error_message?: string;
metadata?: Record<string, unknown> | null;
/** Frontend-only ordering guard for live ACP goal updates and stale hydration. */
goal_reconciliation?: AgentGoalReconciliation;
agent_profile_snapshot?: Record<string, unknown> | null;
executor_snapshot?: Record<string, unknown> | null;
environment_snapshot?: Record<string, unknown> | null;
@@ -199,3 +199,138 @@ describe("session.info_updated partial updates", () => {
expect(store.getState().setTaskSession).not.toHaveBeenCalled();
});
});
describe("session.info_updated goal metadata", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("preserves an active goal when unrelated ACP metadata arrives", () => {
const activeGoal = {
objective: "Coordinate contributor PR reviews",
status: "active",
createdAt: 10,
updatedAt: 20,
};
const store = makeStore({
taskSessions: {
items: {
[SESSION_ID]: makeSession({
metadata: {
acp: {
session_id: ACP_SESSION_ID,
title: SESSION_TITLE,
updated_at: SESSION_INFO_UPDATED_AT,
meta: { goal: activeGoal },
},
},
}),
},
},
} as Partial<AppState>);
const handler = registerSessionInfoHandlers(store)["session.info_updated"]!;
handler(
makeMessage(
makePayload({
session_meta: { codex: { threadStatus: "idle" } },
session_updated_at: SPARSE_SESSION_INFO_UPDATED_AT,
}),
),
);
expect(store.getState().setTaskSession).toHaveBeenCalledWith(
expect.objectContaining({
metadata: {
acp: expect.objectContaining({
meta: { codex: { threadStatus: "idle" }, goal: activeGoal },
}),
},
}),
);
});
it("records the live ACP snapshot timestamp for goal reconciliation", () => {
const activeGoal = {
objective: "Coordinate contributor PR reviews",
status: "active",
createdAt: 10,
updatedAt: 20,
};
const store = makeStore();
const handler = registerSessionInfoHandlers(store)["session.info_updated"]!;
handler(
makeMessage(
makePayload({
session_meta: { goal: activeGoal },
session_updated_at: SPARSE_SESSION_INFO_UPDATED_AT,
}),
),
);
expect(store.getState().setTaskSession).toHaveBeenCalledWith(
expect.objectContaining({
goal_reconciliation: expect.objectContaining({
cleared: false,
sourceUpdatedAt: SPARSE_SESSION_INFO_UPDATED_AT,
}),
}),
);
});
});
describe("session.info_updated goal freshness", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("does not advance goal freshness for metadata without a goal field", () => {
const activeGoal = {
objective: "Coordinate contributor PR reviews",
status: "active",
createdAt: 10,
updatedAt: 20,
};
const store = makeStore({
taskSessions: {
items: {
[SESSION_ID]: makeSession({
metadata: {
acp: {
session_id: ACP_SESSION_ID,
title: SESSION_TITLE,
updated_at: SESSION_INFO_UPDATED_AT,
meta: { goal: activeGoal },
},
},
goal_reconciliation: {
revision: 1,
cleared: false,
watermark: { createdAt: 10, updatedAt: 20 },
sourceUpdatedAt: SESSION_INFO_UPDATED_AT,
},
}),
},
},
} as Partial<AppState>);
const handler = registerSessionInfoHandlers(store)["session.info_updated"]!;
handler(
makeMessage(
makePayload({
session_meta: { codex: { threadStatus: "idle" } },
session_updated_at: SPARSE_SESSION_INFO_UPDATED_AT,
}),
),
);
expect(store.getState().setTaskSession).toHaveBeenCalledWith(
expect.objectContaining({
goal_reconciliation: expect.objectContaining({
sourceUpdatedAt: SESSION_INFO_UPDATED_AT,
}),
}),
);
});
});
+143 -13
View File
@@ -2,6 +2,14 @@ import type { StoreApi } from "zustand";
import type { AppState } from "@/lib/state/store";
import type { SessionInfoPayload } from "@/lib/types/backend";
import type { WsHandlers } from "@/lib/ws/handlers/types";
import {
getAgentGoal,
mergeAgentGoalMetadata,
parseAgentGoal,
type AgentGoal,
type AgentGoalReconciliation,
} from "@/lib/agent-goal";
import type { TaskSession } from "@/lib/types/http";
export function registerSessionInfoHandlers(store: StoreApi<AppState>): WsHandlers {
return {
@@ -12,22 +20,139 @@ export function registerSessionInfoHandlers(store: StoreApi<AppState>): WsHandle
if (!existing) return;
const existingACP = readExistingACP(existing.metadata?.acp);
if (isStaleSessionInfoUpdate(payload.session_updated_at, existingACP.updated_at)) return;
store.getState().setTaskSession({
...existing,
metadata: {
...(existing.metadata ?? {}),
acp: {
session_id: payload.acp_session_id || existingACP.session_id,
title: payload.session_title || existingACP.title,
updated_at: payload.session_updated_at || existingACP.updated_at,
meta: payload.session_meta ?? existingACP.meta,
},
},
});
store.getState().setTaskSession(buildNextSessionInfoSession(existing, payload));
},
};
}
function buildNextSessionInfoSession(
existing: TaskSession,
payload: SessionInfoPayload,
): TaskSession {
const existingACP = readExistingACP(existing.metadata?.acp);
const attachmentChanged =
Boolean(payload.acp_session_id) &&
Boolean(existingACP.session_id) &&
payload.acp_session_id !== existingACP.session_id;
const meta =
payload.session_meta !== undefined || attachmentChanged
? mergeAgentGoalMetadata(existingACP.meta, payload.session_meta, {
attachmentChanged,
source: "live",
reconciliation: existing.goal_reconciliation,
})
: existingACP.meta;
const nextSession: TaskSession = {
...existing,
metadata: {
...(existing.metadata ?? {}),
acp: {
session_id: payload.acp_session_id || existingACP.session_id,
title: payload.session_title || existingACP.title,
updated_at: payload.session_updated_at || existingACP.updated_at,
meta,
},
},
};
const reconciliation = nextLiveGoalReconciliation(
existing.goal_reconciliation,
getAgentGoal(existingACP.meta),
payload.session_meta,
attachmentChanged,
meta,
);
if (reconciliation) {
nextSession.goal_reconciliation =
attachmentChanged || hasGoalField(payload.session_meta)
? withGoalSnapshotTimestamp(reconciliation, payload.session_updated_at)
: reconciliation;
}
return nextSession;
}
function withGoalSnapshotTimestamp(
reconciliation: AgentGoalReconciliation,
updatedAt: string | undefined,
): AgentGoalReconciliation {
return updatedAt ? { ...reconciliation, sourceUpdatedAt: updatedAt } : reconciliation;
}
function nextLiveGoalReconciliation(
current: AgentGoalReconciliation | undefined,
currentGoal: AgentGoal | null,
incomingMeta: Record<string, unknown> | undefined,
attachmentChanged: boolean,
mergedMeta: Record<string, unknown>,
): AgentGoalReconciliation | undefined {
const revision = (current?.revision ?? 0) + 1;
const currentWatermark =
current?.watermark ??
(currentGoal ? { createdAt: currentGoal.createdAt, updatedAt: currentGoal.updatedAt } : null);
if (attachmentChanged) return reconciliationForAttachment(revision, mergedMeta);
if (!hasGoalField(incomingMeta)) {
return reconciliationForAbsentGoal(current, currentGoal, currentWatermark);
}
if (incomingMeta?.goal === null) {
return { revision, cleared: true, watermark: currentWatermark };
}
return reconciliationForLiveGoal(current, currentGoal, incomingMeta ?? {}, mergedMeta, revision);
}
function hasGoalField(meta: Record<string, unknown> | undefined): boolean {
return Object.prototype.hasOwnProperty.call(meta ?? {}, "goal");
}
function reconciliationForAttachment(
revision: number,
mergedMeta: Record<string, unknown>,
): AgentGoalReconciliation {
const accepted = parseAgentGoal(mergedMeta.goal);
return {
revision,
cleared: !accepted,
watermark: accepted ? { createdAt: accepted.createdAt, updatedAt: accepted.updatedAt } : null,
};
}
function reconciliationForAbsentGoal(
current: AgentGoalReconciliation | undefined,
currentGoal: AgentGoal | null,
currentWatermark: AgentGoalReconciliation["watermark"],
): AgentGoalReconciliation | undefined {
if (current) return current;
if (!currentGoal) return undefined;
return { revision: 1, cleared: false, watermark: currentWatermark };
}
function reconciliationForLiveGoal(
current: AgentGoalReconciliation | undefined,
currentGoal: AgentGoal | null,
incomingMeta: Record<string, unknown>,
mergedMeta: Record<string, unknown>,
revision: number,
): AgentGoalReconciliation | undefined {
const accepted = parseAgentGoal(mergedMeta.goal);
const incoming = parseAgentGoal(incomingMeta.goal);
if (!accepted || !incoming) return current ?? goalReconciliationFrom(currentGoal);
if (accepted.createdAt !== incoming.createdAt || accepted.updatedAt !== incoming.updatedAt) {
return current ?? goalReconciliationFrom(currentGoal);
}
return {
revision,
cleared: false,
watermark: { createdAt: accepted.createdAt, updatedAt: accepted.updatedAt },
};
}
function goalReconciliationFrom(goal: AgentGoal | null): AgentGoalReconciliation | undefined {
if (!goal) return undefined;
return {
revision: 1,
cleared: false,
watermark: { createdAt: goal.createdAt, updatedAt: goal.updatedAt },
};
}
function isStaleSessionInfoUpdate(
incomingUpdatedAt: string | undefined,
existingUpdatedAt: string,
@@ -39,7 +164,12 @@ function isStaleSessionInfoUpdate(
return incoming < existing;
}
function readExistingACP(value: unknown) {
function readExistingACP(value: unknown): {
session_id: string;
title: string;
updated_at: string;
meta: Record<string, unknown>;
} {
if (!value || typeof value !== "object") {
return { session_id: "", title: "", updated_at: "", meta: {} };
}
+6
View File
@@ -1738,6 +1738,12 @@
"toFocus": "to focus",
"todos": "Todos",
"todosCompleted": "{{completed}}/{{total}} completed",
"goalActive": "Goal Active",
"goalDetailsTitle": "Goal",
"goalStatusActive": "Active",
"goalContinuationExplanation": "The agent may continue automatically between replies.",
"goalDetailsDescription": "The active goal for this session.",
"goalCloseDetails": "Close goal details",
"toggleWordWrap": "Toggle word wrap",
"tokenCount_one": "{{formatted}} token",
"tokenCount_other": "{{formatted}} tokens",
+6
View File
@@ -1738,6 +1738,12 @@
"toFocus": "ţō ƒōćũś",
"todos": "Ţōďōś",
"todosCompleted": "{{completed}}/{{total}} ćōḿƥĺēţēď",
"goalActive": "Ĝōàĺ Àćţĩvē",
"goalDetailsTitle": "Ĝōàĺ",
"goalStatusActive": "Àćţĩvē",
"goalContinuationExplanation": "Ţĥē àĝēńţ ḿàŷ ćōńţĩńũē àũţōḿàţĩćàĺĺŷ ƀēţŵēēń ŕēƥĺĩēś.",
"goalDetailsDescription": "Ţĥē àćţĩvē ĝōàĺ ƒōŕ ţĥĩś śēśśĩōń.",
"goalCloseDetails": "Ćĺōśē ĝōàĺ ďēţàĩĺś",
"toggleWordWrap": "Ţōĝĝĺē ŵōŕď ŵŕàƥ",
"tokenCount_one": "{{formatted}} ţōķēń",
"tokenCount_other": "{{formatted}} ţōķēńś",
+6
View File
@@ -1681,6 +1681,12 @@
"toFocus": "para focar",
"todos": "Tarefas por fazer",
"todosCompleted": "{{completed}}/{{total}} concluídas",
"goalActive": "Objetivo ativo",
"goalDetailsTitle": "Objetivo",
"goalStatusActive": "Ativo",
"goalContinuationExplanation": "O agente pode continuar automaticamente entre respostas.",
"goalDetailsDescription": "O objetivo ativo desta sessão.",
"goalCloseDetails": "Fechar detalhes do objetivo",
"toggleWordWrap": "Alternar a quebra de linha",
"tokenCount_one": "{{formatted}} token",
"tokenCount_other": "{{formatted}} tokens",
+6
View File
@@ -1680,6 +1680,12 @@
"toFocus": "以聚焦",
"todos": "待办事项",
"todosCompleted": "已完成 {{completed}}/{{total}}",
"goalActive": "目标进行中",
"goalDetailsTitle": "目标",
"goalStatusActive": "进行中",
"goalContinuationExplanation": "智能体可能会在回复之间自动继续。",
"goalDetailsDescription": "此会话的活动目标。",
"goalCloseDetails": "关闭目标详情",
"toggleWordWrap": "切换自动换行",
"tokenCount_one": "{{formatted}} 个 token",
"tokenCount_other": "{{formatted}} 个 token",
+6
View File
@@ -1680,6 +1680,12 @@
"toFocus": "以聚焦",
"todos": "待辦事項",
"todosCompleted": "已完成 {{completed}}/{{total}}",
"goalActive": "目標進行中",
"goalDetailsTitle": "目標",
"goalStatusActive": "進行中",
"goalContinuationExplanation": "代理程式可能會在回覆之間自動繼續。",
"goalDetailsDescription": "此工作階段的活動目標。",
"goalCloseDetails": "關閉目標詳情",
"toggleWordWrap": "切換自動換行",
"tokenCount_one": "{{formatted}} 個 token",
"tokenCount_other": "{{formatted}} 個 token",
+6
View File
@@ -1680,6 +1680,12 @@
"toFocus": "以聚焦",
"todos": "待辦事項",
"todosCompleted": "已完成 {{completed}}/{{total}}",
"goalActive": "目標進行中",
"goalDetailsTitle": "目標",
"goalStatusActive": "進行中",
"goalContinuationExplanation": "代理程式可能會在回覆之間自動繼續。",
"goalDetailsDescription": "此工作階段的活動目標。",
"goalCloseDetails": "關閉目標詳情",
"toggleWordWrap": "切換自動換行",
"tokenCount_one": "{{formatted}} 個 token",
"tokenCount_other": "{{formatted}} 個 token",
+286
View File
@@ -0,0 +1,286 @@
---
created: 2026-09-13
status: implemented
requirements:
- REQ-UI-QUICK-TERMINAL-003
- REQ-AGENTS-GOAL-VISIBILITY-001
system_design:
- ../../specs/ui/system-design/quick-chat-selection.md
- ../../specs/agents/system-design/goal-visibility.md
legacy_specs: []
---
# Implementation Plan: Quick Chat selection and goal visibility
## Overview
Restore the last selected conversation for each workspace and conversation kind.
Keep the preference across reloads without allowing background updates to change it.
A second outcome exposes active provider goals beside the existing Todos/PR information.
Two sequential work orders deliver selection first, then retained goal state and its chat disclosure.
Implementation is complete. The two work orders were executed sequentially in this session.
## Evidence and classification
The reported conversation was `List nova28’s open PRs`.
The exact screenshot trigger is not recorded. Two source-proven reproductions establish the gap:
1. In workspace A, select its second ordinary conversation. Visit a conversation
in workspace B. Reopen ordinary Quick Chat in A: the launcher selects A's first conversation.
2. Select the second ordinary conversation, reload the page, then reopen Quick Chat.
A fresh store loses the prior selection and the launcher uses its first matching conversation.
`useQuickChatLauncher` reads one global `activeSessionId`, then uses
`matchingSessions[0]` when that ID does not match. `createUISlice` initializes
the ID to null. Closing the dialog alone does not clear it.
Terminal activation can also clear that ID, so terminal visits expose the same gap.
The current requirement defines launcher kinds and portable tab order, but lacks
remembered conversation selection. This package adds `REQ-UI-QUICK-TERMINAL-003`
to the existing owning requirement and extends its paired design.
The UI system owns this presentation preference; task membership and runtime remain task-owned.
### Goal evidence and ownership
A fresh raw ACP frame from the reported session contains `session_info_update`
with `_meta.goal`, including objective, status, timestamps, and a control-method hint.
Its normalized `session_info` event preserves the field. The inspected Codex ACP
1.11.0 bridge confirms active/paused/blocked/limited/complete snapshots and explicit null clearing.
The observed snapshot is complete, not active. No production session is changed for testing.
`mergedACPSessionInfo` and `registerSessionInfoHandlers` currently replace the entire
metadata object. Unrelated thread-status updates erase goal information.
The first goal regression retains an active goal after such an update.
The agent system owns this provider lifecycle and its visible disclosure; the UI
system continues to own the independent conversation-selection preference.
The approved UI is a static **Goal Active** chip after PR information, with hover,
focus, and click details on desktop and a bottom drawer on phone/coarse pointers.
## Scope
### In scope
- Browser-local selection per user, workspace, and conversation kind.
- Explicit-selection precedence, reload recovery, and list-readiness handling.
- Ordered fallback after authoritative removal; existing setup and terminal policies.
- Desktop and phone regression coverage through the existing launchers.
- Retained provider goal lifecycle, shared Goal Active chip, and accessible details.
- ACP-to-UI regression coverage, localization, and goal-disclosure documentation.
### Out of scope
- Goal controls, provider scheduling, and polling cadence changes.
- Transcript scroll restoration, cross-device selection synchronization, and tab-order changes.
- Runtime auto-start policy, terminal persistence, and passthrough-toolbar redesign.
## Technical approach
Follow [remembered conversation selection](../../specs/ui/system-design/quick-chat-selection.md).
Add typed remembered state and readiness in the UI slice. Add a bounded, versioned
storage codec under `apps/web/lib/quick-chat/` and integrate it with the root store.
Bound the stored map to 200 workspace entries per identity, retaining the most
recent explicitly selected entries. Malformed entries do not block valid siblings.
Use `auth.user.id` for signed-in scope and a separate disabled-auth identity.
Reset remembered state on identity transitions. Keep storage side effects outside
Immer recipes and do not promote background hydration choices into saved preferences.
Resolve generic opens from current store state, remembered selection, and
`orderQuickChatTabs`. Audit `openQuickChat`, new-chat activation, tab selection,
close/delete, `activateQuickTerminal`, hydration, and resync. Preserve the existing
explicit config-chat and terminal launch paths. An explicit open after a pending
generic open cancels that pending restoration.
Do not reject a saved ID before an authoritative workspace list arrives.
Reuse boot hydration and `useQuickChatResync`; add no fetch in a component.
Avoid briefly mounting the fallback conversation because mounting can trigger
session resumption. A late response must respect the current selection revision.
Storage is local by design. The existing portable tab-order ADR still owns order.
This local preference adds no architecture boundary needing a separate ADR.
Public documentation stays unchanged during planning. During implementation, check
`docs/public` for Quick Chat reopening guidance and update any conflicting statement.
### Goal retention and disclosure
Follow the [agent goal design](../../specs/agents/system-design/goal-visibility.md).
Preserve the recognized goal separately from unrelated opaque metadata updates,
using the existing session metadata and session-info delivery path. Keep null clear
semantics and stale hydration guards. No new scheduler or backend schema is needed.
`ChatStatusBar` reads the selected session's goal and renders `AgentGoalChip` after
registered PR status and before the queue chip. An active goal keeps the status
row visible even without task/Todo/PR content. Idle does not hide it. Completion,
clear, paused, blocked, limited, or unsupported state does not show an active chip.
Use the shared status row for ordinary task chat and Quick Chat.
Task 02 owns a typed parser, narrow retention behavior, shared details, localized
copy, and mock ACP scenarios. It must not infer active goals from transcript text
or change provider wakeup frequency. The chip opens no provider-control request.
Update `docs/public/developer-tools.md` during implementation to explain the chip
and the difference between an active goal and a currently generating turn.
## ASCII UI preview
### UI-01: Reopen after reload or a workspace visit
Entry: desktop Quick Chat launcher or keyboard shortcut. Brackets mark selection.
```text
Fallback today: [Archive tasks] List nova28's open PRs
After fix: Archive tasks [List nova28's open PRs]
+--------------------------------------+
| Previously selected conversation |
| Existing messages and composer |
+--------------------------------------+
```
### UI-02: Phone reopen
Entry: listing menu > Quick Chat. The menu closes before the full-height surface opens.
```text
+--------------------------------+
| Quick Chat Close |
| ... [List nova28's open PRs] ...| tab strip scrolls horizontally
| |
| Previously selected messages | content scrolls vertically
| |
| Existing composer |
+--------------------------------+
```
These previews require selection identity and existing surface hierarchy, not new
copy or pixel geometry. Reuse `QuickChatModal` and the shipped mobile listing menu.
Keep dynamic viewport sizing, safe-area handling, touch targets, and focus return.
During initial loading, retain existing loading UI without mounting another conversation.
Without eligible conversations, retain the current setup. A failed load remains dismissible.
UI-01 covers `.1`–`.5`; UI-02 additionally covers `.7` of `AC-UI-QUICK-TERMINAL-003`.
### UI-03: Goal Active above the composer
Entry: hover, focus, or click the active-goal chip. Shared by task chat and Quick Chat.
```text
+[Todos 2/5] [PR #123] [Goal Active] [Queue]----------+
+| + Goal ---------------------------------------+ |
+| | Active | |
+| | Coordinate contributor PR reviews | |
+| | The agent may continue automatically | |
+| | between replies. | |
+| +---------------------------------------------+ |
+| Existing chat input |
++-------------------------------------------------+
+```
The details popover anchors above the chip; its drawn position is illustrative.
The icon is static. Idle retains the chip. Complete/clear removes it and closes details.
With no Todos/PR, the row contains only Goal Active and any existing right controls.
### UI-04: Phone goal details
```text
+[Todos] [PR #123]----------------+
+| [Goal Active] | wraps when needed; 44px touch target
+| Existing chat input |
++-------------------------------+
+
+Tap opens an inset bottom drawer:
++-------------------------------+
+| Goal Close | fixed header
+| Active |
+| Coordinate contributor PRs... | objective scrolls vertically
+| |
+| The agent may continue |
+| automatically between replies.|
++-------------------------------+ clears bottom safe area
+```
UI-03 and UI-04 cover `AC-AGENTS-GOAL-VISIBILITY-001.1`–`.8`.
Use existing status-row hierarchy and Drawer primitives. Labels shown here require
localization. Long text wraps without document overflow. Keyboard Escape dismisses
only the details; completion or session switching closes them without stale content.
## Tests
| Criteria | Planned evidence |
| --- | --- |
| `.1`, `.3` | `use-quick-chat-launcher.test.ts`: restores A's second chat after selecting B; terminal/config visits preserve ordinary selection; explicit opens win |
| `.2`, `.6` | New `lib/quick-chat/selection-storage.test.ts`: reload codec, identity isolation, malformed/blocked storage, bounded retention |
| `.3`, `.5` | `quick-chat-actions.test.ts`, new `quick-chat-selection.test.ts`: background upserts do not save a choice; late restoration loses to explicit selection |
| `.4` | `quick-chat-sync.test.ts`: authoritative removal clears only its scope; fallback follows displayed order; no matching kind opens setup |
| `.5` | `use-quick-chat-resync.test.ts` and hydration tests: defer initial list, reject stale responses, preserve preference on failure, accept boot snapshot |
| `.6` | Store/auth tests: identity changes clear old in-memory selection; independent mounted clients do not follow storage events |
The first RED regression is `restores the last ordinary chat after visiting another workspace`
in `apps/web/hooks/use-quick-chat-launcher.test.ts`, using the real selection actions.
Assert the chosen session ID, not a missing test selector.
### Goal regression matrix
| Criteria | Planned evidence |
| --- | --- |
| `.2`, `.5`, `.6` | New `event_handlers_goal_test.go`: active goal survives unrelated metadata; completion and null are retained; stale snapshots cannot resurrect it |
| `.5`, `.6` | New parser tests and adapter conversion tests: supported status values, absent/null distinction, malformed input, attachment identity |
| `.2`, `.5`–`.7` | `session-info.test.ts` plus hydration tests: sparse updates, late HTTP response, missing row recovery, selected-session isolation |
| `.1`, `.3`, `.4`, `.7`, `.8` | New `agent-goal-chip.test.tsx` and status-row tests: goal-only row, placement, hover/focus/click, drawer, Escape, session changes, no provider calls |
## E2E tests
- Desktop: add `restores the selected conversation after reload` and workspace-switch
scenarios to `e2e/tests/chat/quick-chat.spec.ts`, project `chromium`.
- Phone: add the same non-first selection, dismissal, reload, and reopen flow to
`e2e/tests/chat/mobile-quick-chat-tabs.spec.ts`, project `mobile-chrome`.
- Seed distinct conversation bodies. Assert the restored active body, selected tab,
and unchanged session count. Use real UI selection, not direct store injection.
- Preserve existing tab-order, rename, cross-device membership, and terminal tests.
- Goal desktop: new `e2e/tests/chat/agent-goal.spec.ts`, project `chromium`, covers
Quick Chat and normal task chat through mock ACP notifications.
- Goal phone: new `e2e/tests/chat/mobile-agent-goal.spec.ts`, project `mobile-chrome`,
taps the chip, checks drawer content/containment and 44px target, dismisses,
reloads, then checks completion and clear. No arbitrary sleeps or store injection.
- Seed sibling sessions with different objectives. Switch while details are open
and assert no cross-session objective. Include active-goal/idle-thread state.
## Work orders
- [x] [Task 01: Remember and restore conversation selection](task-01-restore-selection.md)
- [x] [Task 02: Retain and disclose active agent goals](task-02-goal-visibility.md)
Executed sequentially in this session. Each work order records its checks.
Task 02 followed Task 01 for integration of the shared Quick Chat surface.
## Verification results
Package validation passed:
- `python3 scripts/list-docs.py validate`: 265 decisions and 829 specifications.
- `python3 scripts/lint-spec-files.test.py`: 36 tests passed.
- `python3 scripts/lint-spec-files.py --all`: passed.
- Package-relative file links: checked for all three plan/work-order files and the goal specification pair.
- `git diff --check -- docs/specs docs/plans/quick-chat-selection`: passed.
Implementation validation passed:
- Task 01 focused Vitest: 11 files, 135 tests passed, including hydration restoration and delayed persisted-order fallback regressions.
- Task 02 focused Vitest: 10 files, 92 tests passed, including live goal snapshot freshness, fresh reconnect clear, and real pointer-mode transition regressions.
- Backend targeted tests, race tests, `make lint`, and `make -C apps/backend build` passed.
- Web `typecheck`, `lint`, `i18n:ratchet`, and `i18n:check` passed.
- Desktop Quick Chat and goal E2E passed, including 25 Quick Chat tests, 4 cross-device/terminal tests, and 3 goal tests.
- Mobile Quick Chat, terminal, and goal E2E passed, including the selected-tab flow and the 44px touch-drawer coverage.
- `python3 scripts/validate-public-docs.mjs`, `git diff --check`, and the E2E sleep ratchet passed.
## Risks
- Initial hydration can wrongly invalidate a saved ID or briefly resume the wrong agent.
- Partial snapshots can erase another workspace's preference unless readiness is scoped.
- Direct callers can bypass launcher-only persistence; audit all activation actions.
- Global storage subscribers can save transient fallback choices or leak identity state.
- Storage failure must degrade to in-memory behavior without blocking the dialog.
- Sparse provider metadata can erase goal state unless omission and null remain distinct.
- A stale session hydration response can resurrect a completed or cleared goal.
- Idle thread state does not establish goal state or a future wakeup time.
- Older ACP bridges may not report goals; these sessions show no chip.
- Long objectives and several status chips must not make the phone composer overflow.
@@ -0,0 +1,144 @@
---
id: "01-restore-selection"
title: "Remember and restore conversation selection"
status: done
wave: 1
depends_on: []
plan: "plan.md"
requirements:
- REQ-UI-QUICK-TERMINAL-003
acceptance_criteria:
- AC-UI-QUICK-TERMINAL-003.1
- AC-UI-QUICK-TERMINAL-003.2
- AC-UI-QUICK-TERMINAL-003.3
- AC-UI-QUICK-TERMINAL-003.4
- AC-UI-QUICK-TERMINAL-003.5
- AC-UI-QUICK-TERMINAL-003.6
- AC-UI-QUICK-TERMINAL-003.7
system_design:
- ../../specs/ui/system-design/quick-chat-selection.md
---
# Task 01: Remember and restore conversation selection
## Summary
Implement the remembered selection as one complete behavior, from user action
through browser storage to launcher restoration. Prove it on desktop and phone.
## In scope
- Typed selection state, validated storage, user scope, readiness, and race guards.
- All explicit activation paths and authoritative removal paths.
- Launcher, hydration, resync, store, storage, and rendered regression tests.
- Relevant public documentation corrections during implementation, if needed.
## Out of scope
- Agent goal UI and metadata retention belong to Task 02.
- Cross-device selection and transcript scroll restoration.
- New dialog composition, tab-order persistence, and terminal lifecycle changes.
## Acceptance
1. Write the workspace-switch RED test from the plan before production changes.
Record its expected selected session and actual first-tab fallback.
2. Implement all seven criteria without transiently mounting an unrelated conversation.
Preserve explicit launches, kind isolation, and existing terminal behavior.
3. Run every required check below. Record commands and results before marking this work order done.
## ASCII UI preview
Use [UI-01 and UI-02](plan.md#ascii-ui-preview), covering `AC-UI-QUICK-TERMINAL-003.1`–`.7`.
```text
Desktop: Archive tasks [List nova28's open PRs]
Previously selected content
Phone: Quick Chat Close
... [List nova28's open PRs] ...
Previously selected content
Existing composer
```
The phone menu closes before the existing full-height dialog opens. Keep the tab
strip's horizontal scroll and the content's vertical scroll. Loading must not
mount the first conversation while the saved conversation is still unresolved.
Compare the final rendered active content against both previews.
## Verification
Run from the repository root. On a fresh worktree, install once with
`(cd apps && pnpm install --frozen-lockfile)` before package commands.
```bash
(cd apps/web && pnpm exec vitest run hooks/use-quick-chat-launcher.test.ts hooks/use-quick-chat-resync.test.ts lib/quick-chat/selection-storage.test.ts lib/state/slices/ui/quick-chat-selection.test.ts lib/state/slices/ui/quick-chat-selection-actions.test.ts lib/state/slices/ui/quick-chat-actions.test.ts lib/state/slices/ui/quick-chat-sync.test.ts lib/state/slices/auth lib/state/hydration)
(cd apps/web && pnpm run typecheck)
(cd apps/web && pnpm run lint)
(cd apps/web && pnpm run i18n:ratchet)
(cd apps/web && pnpm e2e:run --project chromium tests/chat/quick-chat.spec.ts tests/chat/quick-chat-cross-device.spec.ts tests/terminal/quick-terminal.spec.ts)
(cd apps/web && pnpm e2e:run --project mobile-chrome tests/chat/mobile-quick-chat-tabs.spec.ts tests/terminal/mobile-quick-terminal.spec.ts)
python3 scripts/list-docs.py validate
python3 scripts/lint-spec-files.py --all
git diff --check
```
Managed E2E builds current sources. Run desktop and mobile separately.
`selection-storage.test.ts` and `quick-chat-selection.test.ts` are new files.
Retain all existing test scenarios and include any additional changed suite in final checks.
## Files likely touched
- New `apps/web/lib/quick-chat/selection-storage.ts` and `.test.ts`.
- New `apps/web/lib/state/slices/ui/quick-chat-selection.ts` and `.test.ts`.
- `apps/web/lib/state/slices/ui/types.ts`, `ui-slice.ts`, `quick-chat-actions.ts`, and `quick-chat-sync.ts`.
- `apps/web/lib/state/slices/ui/quick-terminal-actions.ts` and related tests.
- `apps/web/lib/state/store.ts`, `default-state.ts`, `store-overrides.ts`, and `app-state-types.ts` as needed.
- `apps/web/lib/state/hydration/hydrator.ts` and related tests.
- `apps/web/lib/state/slices/auth/auth-slice.ts` and related tests.
- `apps/web/hooks/use-quick-chat-launcher.ts`, `use-quick-chat-resync.ts`, and their tests.
- `apps/web/components/quick-chat/use-quick-chat-modal.ts` and `quick-chat-modal.tsx` only for pending-open integration.
- `apps/web/components/quick-chat/use-quick-chat-close-actions.ts` for replacement-selection integration.
- Existing E2E files listed in Verification.
- Owning requirement/design and this package for final status and results.
## Dependencies
None. Work remains in the primary session.
## Risks
Readiness and remembered choice must remain independent from list order and agent
activity. Preserve the existing resync revision checks and authoritative deletion semantics.
Do not persist setup IDs, secrets, or conversation text.
## Parallelism
`sequential`
## Inputs
- [Requirements](../../specs/ui/requirements/quick-terminal.md), `REQ-UI-QUICK-TERMINAL-003` and existing launcher compatibility.
- [Design](../../specs/ui/system-design/quick-chat-selection.md).
- [Portable order ADR](../../decisions/2026-08-26-quick-chat-tab-order.md).
- [Session resumption](../../specs/tasks/system-design/quick-chat-session-resumption.md).
- `useQuickChatTabOrder`, `orderQuickChatTabs`, and existing launcher tests.
## Results
Implemented remembered Quick Chat selection for each user, workspace, and
conversation kind. The bounded local-storage codec validates entries and keeps
the latest explicit choices. The UI slice now tracks readiness, selection
revisions, and pending restoration. Explicit opens and tab selections update
the remembered choice, while background refreshes, terminal activation, and
fallback selection do not. Close, delete, hydration, resync, and identity
changes clear or restore only the affected scope. Quick Chat waits for an
authoritative list before mounting a remembered or fallback conversation.
Verification passed:
- Focused Quick Chat Vitest: 11 files, 135 tests passed. Review regressions cover hydration restoring the remembered tab and delayed opens carrying persisted mixed-tab order after removal.
- `pnpm run typecheck`, `pnpm run lint`, and `pnpm run i18n:ratchet` passed.
- Desktop Quick Chat E2E: 25 tests passed. Cross-device and terminal E2E: 4 tests passed.
- Mobile Quick Chat and terminal E2E passed with the goal flow: 2 combined tests and 1 mobile terminal test.
- `python3 scripts/list-docs.py validate`, `python3 scripts/lint-spec-files.py --all`, and `git diff --check` passed.
@@ -0,0 +1,201 @@
---
id: "02-goal-visibility"
title: "Retain and disclose active agent goals"
status: done
wave: 2
depends_on:
- "01-restore-selection"
plan: "plan.md"
requirements:
- REQ-AGENTS-GOAL-VISIBILITY-001
acceptance_criteria:
- AC-AGENTS-GOAL-VISIBILITY-001.1
- AC-AGENTS-GOAL-VISIBILITY-001.2
- AC-AGENTS-GOAL-VISIBILITY-001.3
- AC-AGENTS-GOAL-VISIBILITY-001.4
- AC-AGENTS-GOAL-VISIBILITY-001.5
- AC-AGENTS-GOAL-VISIBILITY-001.6
- AC-AGENTS-GOAL-VISIBILITY-001.7
- AC-AGENTS-GOAL-VISIBILITY-001.8
system_design:
- ../../specs/agents/system-design/goal-visibility.md
---
# Task 02: Retain and disclose active agent goals
## Summary
Retain explicit ACP goal state across unrelated metadata updates and display the
active goal beside Todos/PR information above the composer. Deliver backend retention,
frontend hydration, desktop disclosure, phone drawer, and their regression tests together.
## In scope
- Typed validation of the documented Codex goal snapshot and absent/null semantics.
- Goal retention through the existing session metadata, persistence, and WS path.
- Freshness and session isolation across clear, completion, reconnect, and hydration.
- Shared Goal Active chip, read-only details, localization, and public explanation.
- Mock ACP scenarios and desktop/mobile rendered verification.
## Out of scope
- Scheduling/polling changes, goal controls, task/autopilot transitions, and usage dashboards.
- Native transcript-file readers, provider RPCs on hover, and inference from message text.
- Passthrough terminal toolbar redesign and unsupported-provider imitation.
## Acceptance
1. First add `TestHandleSessionInfoEvent_GoalSurvivesUnrelatedMetadata` in a new
`event_handlers_goal_test.go`. Feed active goal then thread-status metadata and
assert persisted and published goal retention. Record the expected RED failure.
2. Deliver all eight acceptance criteria, including null clearing, final-response
persistence, stale hydration rejection, session isolation, and accessible details.
3. Run each required check below. Record actual results and rendered preview comparison
before marking this work order done. Normal task chat and Quick Chat must both pass.
## Implementation sequence
1. Add a defensive goal parser and typed retained view. Capture sanitized fixture
objects from the verified extension shape, never a full production transcript.
2. Apply narrow goal-retention semantics in the existing metadata path. Do not
deep-merge arbitrary provider metadata. Publish retained goal after persistence.
3. Preserve absent/null distinction and freshness in the frontend handler and
hydration. Add the selected-session goal selector without a parallel task store.
4. Add `AgentGoalChip` and detail content to `ChatStatusBar`, after registered PR
status and before queue information. Include goal-only status-row visibility.
5. Add explicit hover/focus/click behavior and the phone/coarse-pointer Drawer.
Scope touch sizes; do not enlarge neighboring fine-pointer desktop controls.
6. Extend mock-agent scenarios with active, unrelated metadata, complete, and
clear frames. Use them for E2E instead of frontend store injection.
7. Localize all fixed copy and explain the chip in `docs/public/developer-tools.md`.
## ASCII UI preview
Use [UI-03 and UI-04](plan.md#ui-03-goal-active-above-the-composer), covering all
`AC-AGENTS-GOAL-VISIBILITY-001` criteria.
```text
Desktop: [Todos] [PR #123] [Goal Active] [Queue]
|
+ Goal ----------------------+
| Active |
| Objective text |
| The agent may continue |
| automatically between |
| replies. |
+----------------------------+
Existing chat input
Phone: [Todos] [PR #123]
[Goal Active]
Existing chat input
Tap opens a bottom drawer:
+ Goal ---------------------- Close ---+
| Active |
| Objective text (internal scrolling) |
| Continuation explanation |
+--------------------------------------+
```
Chip icon is static. Idle keeps the chip. Non-active/clear removes it and closes
details. Session switching closes old details. Hover-to-content movement keeps the
desktop popover open. Escape closes only details, and focus returns when possible.
Phone uses a fixed drawer header, safe-area clearance, and at least a 44px trigger.
Labels and spacing are illustrative; ordering, surfaces, and behavior are required.
## Verification
Run from the repository root after Task 01. Managed E2E rebuilds current sources.
Do not run desktop and mobile simultaneously. New test files below belong to this task.
```bash
(cd apps/backend && go test ./internal/agentctl/server/adapter/transport/acp -run 'Test.*(Goal|SessionInfo)' -count=1)
(cd apps/backend && go test -race ./internal/orchestrator -run 'TestHandleSessionInfoEvent|Test.*Goal' -count=1)
(cd apps/backend && go test ./cmd/mock-agent -count=1)
(cd apps/web && pnpm exec vitest run lib/ws/handlers/session-info.test.ts lib/agent-goal.test.ts components/task/chat/agent-goal-chip.test.tsx components/task/chat/chat-status-bar.test.tsx components/task/chat/chat-input-area.test.tsx lib/state/slices/session/session-merge-goal.test.ts lib/state/hydration)
(cd apps/web && pnpm run typecheck)
(cd apps/web && pnpm run lint)
(cd apps/web && pnpm run i18n:check)
(cd apps/web && pnpm e2e:run --project chromium tests/chat/agent-goal.spec.ts tests/chat/quick-chat.spec.ts)
(cd apps/web && pnpm e2e:run --project mobile-chrome tests/chat/mobile-agent-goal.spec.ts tests/chat/mobile-quick-chat-tabs.spec.ts)
python3 scripts/list-docs.py validate
python3 scripts/lint-spec-files.py --all
git diff --check
```
The backend suite must include tests for all supported statuses, malformed data,
duplicate/older snapshots, current attachment identity, and ordered null clearing.
Hydration tests defer HTTP until after live completion/clear, then release it.
Frontend component tests also prove no backend/provider request occurs on disclosure.
E2E checks active+idle retention, reload, non-first Quick Chat selection, sibling
session isolation, long objective containment, hover/focus/click, touch, and clear/completion.
Assert the touch trigger's rendered bounds, not only its CSS class.
Generate Traditional Chinese with `pnpm run i18n:zh-hant` from `apps/web` before final checks.
## Files likely touched
- New goal parser/tests under `apps/backend/internal/agentctl/server/adapter/transport/acp/` as needed for provider normalization.
- `apps/backend/internal/agentctl/server/adapter/transport/acp/adapter_updates.go` and `conversion_test.go`.
- New `apps/backend/internal/orchestrator/event_handlers_goal.go` and `_test.go` for narrow retention helpers/tests.
- `apps/backend/internal/orchestrator/event_handlers_streaming.go` for the existing persistence and publish integration.
- Session-info lifecycle types/forwarding only if presence or attachment identity needs typed transport support.
- `apps/backend/cmd/mock-agent/scenarios.go` and a new goal scenario file with tests.
- `apps/web/lib/ws/handlers/session-info.ts` and `.test.ts`.
- New `apps/web/lib/agent-goal.ts` and `.test.ts` for the typed goal view.
- `apps/web/lib/state/hydration/hydrator.ts` and related freshness tests as needed.
- New `apps/web/components/task/chat/agent-goal-chip.tsx` and `.test.tsx`.
- `apps/web/components/task/chat/chat-status-bar.tsx` and new `chat-status-bar.test.tsx`.
- `apps/web/src/locales/{en,pt-pt,zh-cn,zh-hk,zh-tw,pseudo}/` affected chat catalogs.
- New `apps/web/e2e/tests/chat/agent-goal.spec.ts`, `mobile-agent-goal.spec.ts`, and shared helpers if needed.
- `docs/public/developer-tools.md`, owning specs, and this package's results.
## Dependencies
Task 01. Reuse its restored selection behavior when checking the goal in Quick Chat.
Keep the work in the primary session; this package does not authorize delegation.
## Risks
- Whole-object metadata replacement or stale hydration can erase or resurrect a goal.
- Absent and null must stay distinct; an unknown status cannot claim automatic continuation.
- Provider timestamps do not timestamp clear events. Retain source order and local live revisions.
- Session changes must invalidate old objectives and open disclosure state.
- Hover-only interaction would exclude keyboard and touch users.
## Parallelism
`sequential`
## Inputs
- [Requirements](../../specs/agents/requirements/goal-visibility.md).
- [Design and verified wire shape](../../specs/agents/system-design/goal-visibility.md).
- `TodoIndicator`, `ChatStatusBar`, `useTouchDrawer`, and existing Drawer patterns.
- Existing `session-info.test.ts` and `TestHandleSessionInfoEvent_PersistsACPDebugInfo`.
- `apps/backend/cmd/mock-agent/AGENTS.md` and `.agents/skills/e2e/SKILL.md`.
## Results
Implemented typed ACP goal retention and read-only disclosure. The backend
recognizes the documented goal extension, preserves it across unrelated session
metadata updates, retains explicit null clearing, rejects malformed or stale
snapshots, and resets the projection when the ACP attachment changes. The
frontend keeps a narrow typed goal projection through live updates and
hydration, prevents late data from resurrecting a cleared goal, and isolates
the selected session. The shared status row now renders the localized Goal
Active chip for task chat and Quick Chat. Desktop uses a hover, focus, and click
popover. Phone and coarse pointers use a bounded bottom drawer with a fixed
header, safe-area handling, internal objective scrolling, and a 44px trigger.
Mock-agent scenarios cover active, unrelated metadata, complete, clear, and
long-objective states. Public documentation and all locale catalogs were
updated.
Verification passed:
- Backend goal, session-info, adapter conversion, mock-agent, and race tests passed.
- `make lint` and `make -C apps/backend build` passed.
- Focused goal Vitest: 10 files, 92 tests passed. The final goal component/session subset passed 22 tests, including live snapshot freshness, fresh reconnect clearing, and a real pointer-mode transition.
- `pnpm run typecheck`, `pnpm run lint`, `pnpm run i18n:check`, and `pnpm run i18n:ratchet` passed.
- Desktop goal E2E: 3 tests passed. Mobile goal E2E: 1 test passed after the final trigger refactor.
- `python3 scripts/list-docs.py validate`, `python3 scripts/lint-spec-files.py --all`, public-doc validation, and `git diff --check` passed.
+13
View File
@@ -75,6 +75,19 @@ Closing a real chat tab permanently deletes its conversation, hidden backing tas
If **Start chat** is disabled, select a profile and finish every repository/branch row. If a repository is missing, confirm that it belongs to the current workspace and refresh the repository configuration. Use a normal task when the result must remain visible on a board or become a reviewed PR.
### Agent continuation goals
Some ACP agents keep an explicit goal after a reply. When the selected task or Quick Chat session
reports an active goal, Kandev shows a **Goal Active** chip above the composer. Select the chip, or
focus it with the keyboard, to read the goal and its status. The details explain that the agent may
continue automatically between replies. They do not provide a wakeup time or change the agent's
goal.
The chip remains visible while the provider reports the goal as active, including while the session
is idle. Completion, clearing, pausing, blocking, or a usage limit removes it. On a phone, select
the chip to open the details in a drawer. The drawer keeps long goal text inside its own scroll
area.
<details>
<summary>Utility agents and configuration chat</summary>
@@ -0,0 +1,59 @@
---
status: active
system: agents
created: 2026-09-13
owners:
- kandev
---
# Agent Goal Visibility Requirements
## Overview
An agent can retain an active goal and continue automatically after a turn ends.
Users need to distinguish that state from an agent waiting for a new instruction.
The agent system owns the provider goal contract and its visible chat outcomes.
## Requirements
### REQ-AGENTS-GOAL-VISIBILITY-001: Active goal disclosure
**Intent:** Show when the selected session has an active goal that can cause automatic continuation.
#### Acceptance criteria
- **AC-AGENTS-GOAL-VISIBILITY-001.1:** When the provider reports an active goal,
the selected session shall show a static **Goal Active** chip above the chat input,
after the Todos and PR information. The chip shall appear even without Todos or a PR.
- **AC-AGENTS-GOAL-VISIBILITY-001.2:** The chip shall remain visible between turns
while the goal remains active. An idle thread, final response, or unrelated
metadata update shall not clear the goal or imply completion.
- **AC-AGENTS-GOAL-VISIBILITY-001.3:** Hover, keyboard focus, and click shall expose
the goal objective and status. The details shall explain that the agent may
continue automatically between replies. They shall not promise a wakeup time.
- **AC-AGENTS-GOAL-VISIBILITY-001.4:** On phone or coarse-pointer devices, tapping
the chip shall open the same details in a bottom drawer. Long objectives shall
scroll within the drawer without document overflow. The trigger shall have a
touch target of at least 44 CSS pixels, and dismissal shall restore focus when possible.
- **AC-AGENTS-GOAL-VISIBILITY-001.5:** Completion, clearing, pausing, blocking, or a
usage/budget limit shall remove the active chip. Without an explicit valid active
goal, the UI shall not infer one from prose, tools, task state, or recurring activity.
- **AC-AGENTS-GOAL-VISIBILITY-001.6:** Reopening, reloading, and reconnecting shall
restore the latest accepted goal state for the same session. Late data shall
not resurrect a cleared goal, regress completion, or expose another session's goal.
- **AC-AGENTS-GOAL-VISIBILITY-001.7:** Ordinary task chat and Quick Chat shall use
the same goal state and disclosure behavior. Switching sessions shall close the
previous details. Unsupported providers shall retain their existing UI.
- **AC-AGENTS-GOAL-VISIBILITY-001.8:** The chip and details shall be read-only.
Opening or dismissing them shall not start a turn, resume an agent, change a goal,
or send a provider request. Labels shall support the application's locales.
## Out of scope
- Goal creation, pause/resume/clear controls, provider scheduling, and polling cadence changes.
- Goal history, progress percentages, invented next-wakeup times, and live usage counters.
- Office/autopilot semantics, task lifecycle changes, and passthrough-terminal toolbar redesign.
## System design
- [Goal visibility](../system-design/goal-visibility.md)
@@ -0,0 +1,152 @@
---
status: current
system: agents
requirements:
- REQ-AGENTS-GOAL-VISIBILITY-001
created: 2026-09-13
owners:
- kandev
---
# Agent Goal Visibility System Design
## Purpose and boundaries
Retain the provider's goal snapshot independently from per-turn activity and expose
it in the shared chat composer status row. Existing ACP/session metadata transport
remains authoritative. This adds no scheduler, provider control request, or database schema.
The [Quick Chat selection design](../../ui/system-design/quick-chat-selection.md)
owns which conversation reopens. This design owns the goal attached to that session.
The [combined fix package](../../../plans/quick-chat-selection/plan.md) delivers both.
## Requirement mapping
| Requirement | Design sections |
| --- | --- |
| `REQ-AGENTS-GOAL-VISIBILITY-001` | Provider contract; retention and delivery; composer disclosure; verification |
## Provider contract
The inspected `@agentclientprotocol/codex-acp` 1.11.0 implementation emits
`session_info_update` with `_meta.goal`. Its `ThreadGoalSnapshot` maps provider
statuses to `active`, `paused`, `blocked`, `limited`, or `complete`.
`thread/goal/cleared` emits `goal: null`. Goal snapshots also arrive during session loading.
This is an ACP extension, not a guarantee from every ACP provider.
```json
{
"sessionUpdate": "session_info_update",
"_meta": {
"goal": {
"objective": "Coordinate contributor PR reviews",
"status": "active",
"createdAt": 1789079689000,
"updatedAt": 1789287777000,
"tokenBudget": null,
"tokensUsed": 9547009,
"timeUsedSeconds": 47312,
"controlMethod": "_session/goal"
}
}
}
```
The active example is a fixture shape, not a claim about the investigated session.
That session's fresh raw and normalized captures reported `complete`.
The bridge can suppress updates when only usage changes, so counters are not live progress.
Do not render them as a timer or progress percentage in this package.
Recognize the documented Codex extension through the adapter's provider identity.
Parse goal data defensively into a typed view with objective, status, and provider
timestamps. Optional usage fields remain optional. Ignore `controlMethod` for UI actions.
Do not execute methods named by arbitrary metadata or inspect native transcript files.
## Retention and delivery
Current flow: `adapter_updates.go` converts the frame to `session_info` and carries
`SessionMeta`. Lifecycle forwarding reaches `handleSessionInfoEvent`, which stores
`metadata.acp` and publishes `SessionInfoEventPayload`. The session broadcaster sends
`session.info_updated`; `registerSessionInfoHandlers` updates the frontend session row.
Both `mergedACPSessionInfo` and the frontend currently replace `meta` on unrelated
updates. A frame containing only `codex.threadStatus` can erase the goal.
Extend this path with a narrow, typed goal-retention rule. Keep the public location
`metadata.acp.meta.goal` and the existing `session_meta` payload. Do not deep-merge
all opaque metadata or create a competing task-level goal store.
| Incoming goal field | Required handling |
| --- | --- |
| Absent | Retain the accepted goal; update unrelated metadata by existing semantics |
| Valid snapshot | Replace the retained goal after freshness checks |
| Explicit null | Retain an explicit cleared marker and hide the chip |
| Malformed or unknown status | Do not present it as active; record bounded diagnostic context without objective text |
Preserve property presence through conversion. A null goal is distinct from an
omitted goal. The backend publishes the full retained goal state after persistence,
including explicit null. The frontend uses the same omission/clear semantics for
sparse events and reads the typed view from the selected session row.
Keep handling ordered per Kandev session and current ACP attachment. Do not reuse
cancellation-intent state as a generic lock. Provider timestamps are Unix milliseconds;
compare valid snapshots by goal creation time and update time. Reject older updates
within the same goal. A newer goal can replace a completed goal.
Clear events have no goal timestamp: apply them in accepted stream order and keep
their local revision so an older HTTP hydration response cannot restore the old value.
Reject events from obsolete attachments before updating the session.
Preserve the existing hydration/live-response freshness boundary. Add deferred tests
for clear or completion followed by a stale HTTP response. A session-info event that
arrives before its session row exists must be recovered by authoritative hydration;
do not create an incomplete session row merely to display the chip.
Retained state survives reconnect and ordinary idle states. A provider session change
invalidates the old provider goal until its authoritative load snapshot arrives.
Historical sessions without a retained goal show no chip until a supported snapshot arrives.
## Composer disclosure
Add `AgentGoalChip` and shared detail content under `components/task/chat/`.
Use `ChatStatusBar.sessionId`, not a global active task/session selector, to resolve it.
Place the chip after `RegisteredChangeRequestStatus` and before the queue chip.
Keep the existing Todos, autopilot, dependency, and PR ordering unchanged.
Include goal visibility in `shouldRenderChatStatusBar` so a goal alone renders the row.
Use a small static target icon and the localized label **Goal Active** only for
`status: active`. Do not use a working spinner. The detail content contains a Goal
heading, active status, the objective as plain text, and this localized explanation:
**The agent may continue automatically between replies.**
Preserve whitespace where useful, wrap long tokens, and do not render objective HTML.
Fine-pointer desktop uses a controlled popover above the trigger. Hover, focus,
and click open the same content; pointer movement into the content keeps it open.
Escape dismisses it without closing Quick Chat. Avoid simultaneous tooltip/popover
copies or a focus-dismiss/reopen loop. Match the surrounding compact status-chip density.
Use `useTouchDrawer` from `hooks/use-compact-task-chrome.ts` and the existing Drawer
primitive for coarse pointers. Phone composition uses the same bottom drawer even
with a fine pointer. Its fixed header has a visible close action; the objective
area owns vertical scrolling inside a safe-area-aware dynamic-viewport limit.
The chip remains after PR information and wraps onto another row when needed.
Keep its touch target at least 44 CSS pixels without enlarging fine-pointer desktop chips.
The nearest exemplars are `TodoIndicator` for status-row placement and shared details,
and `RegisteredChangeRequestStatus` for coarse-pointer disclosure selection.
The approved phone design intentionally uses a drawer rather than copying the Todos popover.
Changing sessions or removing the active goal closes the details. Return focus to
the chip when mounted, otherwise use the surrounding composer's stable focus target.
Expose an accessible name, expanded state, and associated details on the trigger.
## Compatibility and verification
No agent control methods are invoked. Goal state does not replace task state, Todo
progress, or autopilot. Disconnect does not silently complete a retained goal;
the existing connection indicator still describes transport availability.
All fixed copy uses i18n, including the five language catalogs and generated Traditional Chinese.
Backend regression tests prove active -> unrelated metadata -> idle retains the goal,
and complete/null remain effective after later updates. Include malformed input,
all supported statuses, attachment changes, duplicates, and older snapshots.
Frontend tests prove sparse merge, stale hydration, session isolation, and disclosure behavior.
Mock ACP scenarios drive active, unrelated, complete, and clear frames through the real
transport. Desktop and phone E2E verify the chip above the composer, disclosure,
long text, idle persistence, reload recovery, and disappearance on completion/clear.
+39 -1
View File
@@ -2,7 +2,7 @@
status: active
system: ui
created: 2026-08-03
updated: 2026-08-28
updated: 2026-09-13
owners:
- kandev
---
@@ -56,6 +56,44 @@ Quick Chat and Quick Terminal are both short-lived utilities reached from the sa
- **AC-UI-QUICK-TERMINAL-002.7:** Rename mode visibly distinguishes the tab with an edit-state background and border, shows a focused bordered input with selected text, and omits inline **Save** and **Cancel** actions. Enter commits a trimmed name, Escape restores the previous name, and blur commits without a duplicate rename.
- **AC-UI-QUICK-TERMINAL-002.8:** On phone and tablet viewports, the tab strip contains its own horizontal overflow. The selected content remains the dialog scroll owner, and the feature does not cause document horizontal overflow.
### REQ-UI-QUICK-TERMINAL-003: Remembered conversation selection
**Intent:** Returning to Quick Chat restores the conversation the user was reading.
This presentation preference does not control task or agent lifecycle.
#### Acceptance criteria
- **AC-UI-QUICK-TERMINAL-003.1:** Reopening ordinary Quick Chat shall select
the last selected ordinary conversation in that workspace, when it remains available.
Visiting another workspace, a configuration conversation, or a terminal shall not replace that choice.
- **AC-UI-QUICK-TERMINAL-003.2:** The remembered conversation shall survive
dialog dismissal, route navigation, page reload, and browser restart for the same user and browser.
Configuration launchers shall retain a separate remembered configuration conversation.
- **AC-UI-QUICK-TERMINAL-003.3:** Explicit conversation opens and tab selections
shall take precedence over restoration. Background activity, list refreshes, and title changes
shall not replace a valid remembered choice or interrupt the visible conversation.
- **AC-UI-QUICK-TERMINAL-003.4:** When the remembered conversation is unavailable,
reopening shall select the first available conversation of the requested kind in displayed tab order.
Without a matching conversation, it shall open the existing setup surface.
Restoration shall not recreate deleted conversations or select another workspace or kind.
- **AC-UI-QUICK-TERMINAL-003.5:** An incomplete or failed chat-list load shall
not invalidate a remembered choice. Loading shall not briefly activate a different persisted conversation.
A later response shall not override a newer user selection or another workspace's visible surface.
- **AC-UI-QUICK-TERMINAL-003.6:** Different signed-in users shall have separate
remembered choices. Another open client shall not change the currently visible conversation.
Without usable browser storage, close and reopen shall still preserve the in-memory choice.
- **AC-UI-QUICK-TERMINAL-003.7:** Desktop and phone launchers shall restore the
same conversation under these rules. Existing dismissal, focus-return, and touch controls shall remain available.
#### Compatibility
The kind-specific launcher contract in `AC-UI-QUICK-TERMINAL-001.2` remains authoritative.
Quick Terminal retains its existing reuse-or-create policy. Temporary setup tabs remain usable
during the current page lifetime but do not become persisted conversation preferences.
Cross-device selection synchronization and transcript scroll-position restoration are excluded.
## System design
Remembered selection follows the [selection design](../system-design/quick-chat-selection.md).
The migrated technical source is split into [part 1](../system-design/quick-terminal.md).
@@ -0,0 +1,94 @@
---
status: current
system: ui
requirements:
- REQ-UI-QUICK-TERMINAL-003
created: 2026-09-13
owners:
- kandev
---
# Quick Chat Selection System Design
## Purpose and boundaries
This design extends the shared [Quick Chat tab contract](quick-terminal.md).
It owns remembered conversation selection, not tab membership or agent lifecycle.
## Requirement mapping
| Requirement | Design sections |
| --- | --- |
| `REQ-UI-QUICK-TERMINAL-003` | Ownership and persistence; selection and restoration; responsive behavior and verification |
## Ownership and persistence
UI owns the reading preference. Task services still own conversation membership,
and the existing session-resumption hook owns runtime recovery.
This section is the proposed design for `REQ-UI-QUICK-TERMINAL-003`.
Add a typed selection map to `QuickChatState`, separate from the visible
`activeSessionId` and terminal-selection fields. Key it by workspace and conversation
kind (`chat` or `config`). Values identify persisted session IDs, never titles.
Track in-memory setup selection separately from the persisted choice.
Use a small browser-storage module under `apps/web/lib/quick-chat/`.
Store a versioned map in `localStorage`, scoped by authenticated user ID.
Use a distinct local identity only when authentication is disabled. Anonymous
authentication-enabled pages must not read or write another identity's preference.
Validate parsed shapes and entries. Retain at most 200 workspace entries per identity,
ordered by the latest explicit selection. Catch unavailable storage and quota failures.
On identity change, clear the old in-memory map before loading the new identity.
Store only identifiers; never store conversation content or credentials.
Selection belongs to the local reading context, unlike portable tab order.
Backend user settings would couple independent devices and add a write for every
selection. Browser storage provides restart recovery without that coupling.
Do not subscribe to storage events to change an open dialog. Each mounted client
keeps its own selection; a fresh client reads the last stored choice.
No backend schema, endpoint, or preference migration is needed.
## Selection and restoration
Centralize remembered-choice updates for explicit `openQuickChat`,
`setActiveQuickChatSession`, and successful new-conversation activation.
`activateQuickTerminal` must not erase either conversation-kind preference.
Background upserts and hydration fallbacks must not write a new remembered choice.
Keep storage side effects outside Immer recipes. The root store integration must
cover direct action callers, including configuration launchers and new-chat flows.
`useQuickChatLauncher` resolves the requested workspace and kind against current
state at activation time. Prefer an explicitly selected current-page setup, then
the valid remembered conversation. Otherwise use `orderQuickChatTabs` with the
current optimistic or saved workspace order, filtered to eligible conversations.
Without a candidate, retain the existing kind-specific setup behavior.
An explicit session-ID open always wins over remembered selection.
Add per-workspace list readiness to the existing hydration/resync path. An accepted
boot snapshot or successful `syncQuickChatSessions` marks that workspace ready.
An initial empty state, failed request, or discarded stale response does not.
An open request before readiness displays the existing loading presentation without
mounting another persisted session view. A pending request carries workspace,
kind, and a selection revision. Dismissal, a workspace change, or explicit selection
invalidates it. Resolve it once after an accepted snapshot; never poll separately.
Existing resync error handling remains authoritative. A failed load preserves the
remembered ID and leaves the surface dismissible.
`restoreQuickChatSelection`, `reconcileQuickChatSessions`, and deletion paths must
distinguish missing-before-readiness from authoritative removal. After removal,
clear only the matching workspace/kind entry. Preserve existing adjacent-tab
behavior when closing the visible tab; record its replacement only for that kind.
Never prune unrelated workspace preferences from a partial workspace snapshot.
## Responsive behavior and verification
Keep the existing desktop floating dialog and phone full-height dialog.
The phone listing menu remains the entry point and closes before Quick Chat opens.
The tab strip owns horizontal overflow; the selected content owns vertical scrolling.
No new toolbar, sizing, or focus policy is introduced.
Unit tests cover storage failure, identity separation, selection precedence,
terminal/config visits, ordered fallback, authoritative deletion, and delayed hydration.
Desktop and phone E2E select a non-first conversation, dismiss, reload, and reopen.
They assert the active content identity and unchanged conversation count.
The fix package is [Quick Chat selection](../../../plans/quick-chat-selection/plan.md).
@@ -23,6 +23,9 @@ records and Quick Terminal descriptors remain owned by their existing backend se
| `REQ-UI-QUICK-TERMINAL-001` | [Migrated source detail](#migrated-source-detail), [Launcher focus return](#launcher-focus-return), [Launcher toggle and terminal Escape routing](#launcher-toggle-and-terminal-escape-routing) |
| `REQ-UI-QUICK-TERMINAL-002` | [Tab order and editing](#tab-order-and-editing) |
Remembered conversation selection is defined in the
[selection design](quick-chat-selection.md).
## Tab order and editing
### Components and responsibilities