Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
feat(cyclops): move chat threads into sidebar (#7157)
r33drichardsdc3cb67e291c
diff --git a/libs/fleet/backend/auth/policy_characterization_test.go b/libs/fleet/backend/auth/policy_characterization_test.goindex 80e3e41445..3d33426f91 100644--- a/libs/fleet/backend/auth/policy_characterization_test.go+++ b/libs/fleet/backend/auth/policy_characterization_test.go@@ -9,6 +9,7 @@ import ("net/http/httptest""os""path/filepath"+ "slices""sort""strings""testing"@@ -151,6 +152,19 @@ type routeCase struct {// characterizationCases lists the parameter cases for every route. A route with// no entry fails the test rather than being skipped — an unlisted route is one// whose verdicts nobody recorded.+func TestChatConversationPatchUsesExistingAuthorizationSurface(t *testing.T) {+ const route = "/api/chat/conversations/{id}"+ if surface, ok := RouteSurface(route); !ok || surface != "chat" {+ t.Fatalf("RouteSurface(%q) = (%q, %t), want (chat, true)", route, surface, ok)+ }+ if !slices.Contains(characterizationMethods, http.MethodPatch) {+ t.Fatalf("characterizationMethods = %v, missing PATCH", characterizationMethods)+ }+ if len(characterizationCases()[route]) == 0 {+ t.Fatalf("characterizationCases missing %q", route)+ }+}+func characterizationCases() map[string][]routeCase {cases := map[string][]routeCase{}diff --git a/libs/fleet/backend/chat/store.go b/libs/fleet/backend/chat/store.goindex 46b3baa0c4..f36c36fc07 100644--- a/libs/fleet/backend/chat/store.go+++ b/libs/fleet/backend/chat/store.go@@ -14,6 +14,7 @@ import (var (ErrConversationNotFound = errors.New("conversation not found")ErrConversationLimit = errors.New("conversation storage limit reached")+ ErrConversationArchived = errors.New("conversation is archived"))const (@@ -23,8 +24,9 @@ const (type ConversationStore interface {Create(ctx context.Context, ownerID string) (*Conversation, error)- List(ctx context.Context, ownerID string) ([]ConversationSummary, error)+ List(ctx context.Context, ownerID string, archived bool) ([]ConversationSummary, error)Get(ctx context.Context, ownerID, conversationID string) (*Conversation, error)+ SetArchived(ctx context.Context, ownerID, conversationID string, archived bool) (*Conversation, error)Append(ctx context.Context, ownerID, conversationID string, messages ...Message) error}@@ -81,23 +83,27 @@ func (store *MemoryConversationStore) Create(_ context.Context, ownerID string)return cloneConversation(record.Conversation), nil}-func (store *MemoryConversationStore) List(_ context.Context, ownerID string) ([]ConversationSummary, error) {+func (store *MemoryConversationStore) List(_ context.Context, ownerID string, archived bool) ([]ConversationSummary, error) {store.mu.RLock()summaries := make([]ConversationSummary, 0)for _, record := range store.conversations {- if record.OwnerID != ownerID {+ if record.OwnerID != ownerID || (record.ArchivedAt != nil) != archived {continue}summaries = append(summaries, ConversationSummary{- ID: record.ID,- Title: record.Title,- CreatedAt: record.CreatedAt,- UpdatedAt: record.UpdatedAt,+ ID: record.ID,+ Title: record.Title,+ CreatedAt: record.CreatedAt,+ UpdatedAt: record.UpdatedAt,+ ArchivedAt: cloneTime(record.ArchivedAt),})}store.mu.RUnlock()sort.Slice(summaries, func(left, right int) bool {+ if archived {+ return summaries[left].ArchivedAt.After(*summaries[right].ArchivedAt)+ }return summaries[left].UpdatedAt.After(summaries[right].UpdatedAt)})return summaries, nil@@ -116,6 +122,26 @@ func (store *MemoryConversationStore) Get(_ context.Context, ownerID, conversatireturn conversation, nil}+func (store *MemoryConversationStore) SetArchived(_ context.Context, ownerID, conversationID string, archived bool) (*Conversation, error) {+ store.mu.Lock()+ defer store.mu.Unlock()++ record, ok := store.conversations[conversationID]+ if !ok || record.OwnerID != ownerID {+ return nil, ErrConversationNotFound+ }++ now := time.Now().UTC()+ if archived {+ record.ArchivedAt = &now+ } else {+ record.ArchivedAt = nil+ }+ record.UpdatedAt = now++ return cloneConversation(record.Conversation), nil+}+func (store *MemoryConversationStore) Append(_ context.Context, ownerID, conversationID string, messages ...Message) error {store.mu.Lock()defer store.mu.Unlock()@@ -124,6 +150,9 @@ func (store *MemoryConversationStore) Append(_ context.Context, ownerID, conversif !ok || record.OwnerID != ownerID {return ErrConversationNotFound}+ if record.ArchivedAt != nil {+ return ErrConversationArchived+ }if len(messages) == 0 {return nil}@@ -193,6 +222,7 @@ func titleFromFirstUserMessage(messages []Message) string {func cloneConversation(conversation Conversation) *Conversation {cloned := conversation+ cloned.ArchivedAt = cloneTime(conversation.ArchivedAt)cloned.Messages = make([]Message, len(conversation.Messages))for index, message := range conversation.Messages {cloned.Messages[index] = cloneMessage(message)@@ -205,3 +235,11 @@ func cloneMessage(message Message) Message {cloned.ToolCalls = append([]ToolCall(nil), message.ToolCalls...)return cloned}++func cloneTime(value *time.Time) *time.Time {+ if value == nil {+ return nil+ }+ cloned := *value+ return &cloned+}diff --git a/libs/fleet/backend/chat/store_test.go b/libs/fleet/backend/chat/store_test.goindex 9f0b0933ef..d9b8a314da 100644--- a/libs/fleet/backend/chat/store_test.go+++ b/libs/fleet/backend/chat/store_test.go@@ -7,6 +7,7 @@ import ("strings""sync""testing"+ "time")func TestMemoryStoreTitlesAndOrdersConversations(t *testing.T) {@@ -26,7 +27,7 @@ func TestMemoryStoreTitlesAndOrdersConversations(t *testing.T) {t.Fatal(err)}- got, err := store.List(context.Background(), "owner-a")+ got, err := store.List(context.Background(), "owner-a", false)if err != nil {t.Fatal(err)}@@ -35,6 +36,154 @@ func TestMemoryStoreTitlesAndOrdersConversations(t *testing.T) {}}+func TestMemoryConversationStoreArchivesAndRestores(t *testing.T) {+ store := NewMemoryConversationStore()+ conversation, err := store.Create(context.Background(), "owner-a")+ if err != nil {+ t.Fatal(err)+ }++ archived, err := store.SetArchived(context.Background(), "owner-a", conversation.ID, true)+ if err != nil {+ t.Fatal(err)+ }+ if archived.ArchivedAt == nil {+ t.Fatalf("archive = %#v, want archived timestamp", archived)+ }+ if !archived.UpdatedAt.After(conversation.UpdatedAt) {+ t.Fatalf("archive UpdatedAt = %v, creation UpdatedAt = %v", archived.UpdatedAt, conversation.UpdatedAt)+ }+ if !archived.UpdatedAt.Equal(*archived.ArchivedAt) {+ t.Fatalf("archive UpdatedAt = %v, ArchivedAt = %v", archived.UpdatedAt, archived.ArchivedAt)+ }+ if archived.UpdatedAt.Location() != time.UTC || archived.ArchivedAt.Location() != time.UTC {+ t.Fatalf("archive timestamps must be UTC: UpdatedAt=%v ArchivedAt=%v", archived.UpdatedAt.Location(), archived.ArchivedAt.Location())+ }+ archiveTimestamp := *archived.ArchivedAt+ *archived.ArchivedAt = time.Time{}++ stored, err := store.Get(context.Background(), "owner-a", conversation.ID)+ if err != nil {+ t.Fatal(err)+ }+ if stored.ArchivedAt == nil || stored.ArchivedAt.IsZero() {+ t.Fatalf("stored archive timestamp = %v, want non-zero", stored.ArchivedAt)+ }+ if !stored.ArchivedAt.Equal(archiveTimestamp) {+ t.Fatalf("stored archive timestamp = %v, want %v", stored.ArchivedAt, archiveTimestamp)+ }++ active, err := store.List(context.Background(), "owner-a", false)+ if err != nil {+ t.Fatal(err)+ }+ archivedSummaries, err := store.List(context.Background(), "owner-a", true)+ if err != nil {+ t.Fatal(err)+ }+ if len(active) != 0 || len(archivedSummaries) != 1 {+ t.Fatalf("active=%#v archived=%#v", active, archivedSummaries)+ }+ if archivedSummaries[0].ArchivedAt == nil || archivedSummaries[0].ArchivedAt.IsZero() {+ t.Fatalf("archived summary timestamp = %v, want non-zero", archivedSummaries[0].ArchivedAt)+ }++ restored, err := store.SetArchived(context.Background(), "owner-a", conversation.ID, false)+ if err != nil {+ t.Fatal(err)+ }+ if restored.ArchivedAt != nil {+ t.Fatalf("restored archive timestamp = %v, want nil", restored.ArchivedAt)+ }+ if !restored.UpdatedAt.After(archiveTimestamp) {+ t.Fatalf("restored UpdatedAt = %v, archive timestamp = %v", restored.UpdatedAt, archiveTimestamp)+ }+ if restored.UpdatedAt.Location() != time.UTC {+ t.Fatalf("restored UpdatedAt location = %v, want UTC", restored.UpdatedAt.Location())+ }++ active, err = store.List(context.Background(), "owner-a", false)+ if err != nil {+ t.Fatal(err)+ }+ archivedSummaries, err = store.List(context.Background(), "owner-a", true)+ if err != nil {+ t.Fatal(err)+ }+ if len(active) != 1 || active[0].ID != conversation.ID || len(archivedSummaries) != 0 {+ t.Fatalf("restored active=%#v archived=%#v", active, archivedSummaries)+ }+}++func TestMemoryConversationStoreFiltersArchivedByOwner(t *testing.T) {+ store := NewMemoryConversationStore()+ active, err := store.Create(context.Background(), "owner-a")+ if err != nil {+ t.Fatal(err)+ }+ firstArchived, err := store.Create(context.Background(), "owner-a")+ if err != nil {+ t.Fatal(err)+ }+ secondArchived, err := store.Create(context.Background(), "owner-a")+ if err != nil {+ t.Fatal(err)+ }+ otherOwner, err := store.Create(context.Background(), "owner-b")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := store.SetArchived(context.Background(), "owner-a", firstArchived.ID, true); err != nil {+ t.Fatal(err)+ }+ if _, err := store.SetArchived(context.Background(), "owner-a", secondArchived.ID, true); err != nil {+ t.Fatal(err)+ }+ if _, err := store.SetArchived(context.Background(), "owner-b", otherOwner.ID, true); err != nil {+ t.Fatal(err)+ }+ if _, err := store.SetArchived(context.Background(), "owner-b", firstArchived.ID, false); !errors.Is(err, ErrConversationNotFound) {+ t.Fatalf("SetArchived error = %v, want ErrConversationNotFound", err)+ }++ activeSummaries, err := store.List(context.Background(), "owner-a", false)+ if err != nil {+ t.Fatal(err)+ }+ if len(activeSummaries) != 1 || activeSummaries[0].ID != active.ID {+ t.Fatalf("active summaries = %#v", activeSummaries)+ }++ archivedSummaries, err := store.List(context.Background(), "owner-a", true)+ if err != nil {+ t.Fatal(err)+ }+ if len(archivedSummaries) != 2 || archivedSummaries[0].ID != secondArchived.ID || archivedSummaries[1].ID != firstArchived.ID {+ t.Fatalf("archived summaries = %#v", archivedSummaries)+ }+ for _, summary := range archivedSummaries {+ if summary.ArchivedAt == nil {+ t.Fatalf("archived summary = %#v, want archived timestamp", summary)+ }+ }+}++func TestMemoryConversationStoreRejectsAppendToArchived(t *testing.T) {+ store := NewMemoryConversationStore()+ conversation, err := store.Create(context.Background(), "owner-a")+ if err != nil {+ t.Fatal(err)+ }+ if _, err := store.SetArchived(context.Background(), "owner-a", conversation.ID, true); err != nil {+ t.Fatal(err)+ }++ err = store.Append(context.Background(), "owner-a", conversation.ID, Message{Role: RoleUser, Content: "blocked"})+ if !errors.Is(err, ErrConversationArchived) {+ t.Fatalf("Append error = %v, want ErrConversationArchived", err)+ }+}+func TestMemoryStoreHidesOtherOwners(t *testing.T) {store := NewMemoryConversationStore()conversation, err := store.Create(context.Background(), "owner-a")@@ -138,7 +287,7 @@ func TestMemoryStoreCreateDoesNotRaceWithDiscoveryAndAppend(t *testing.T) {default:}- summaries, err := store.List(ctx, "owner-a")+ summaries, err := store.List(ctx, "owner-a", false)if err != nil {t.Errorf("List() error = %v", err)returndiff --git a/libs/fleet/backend/chat/types.go b/libs/fleet/backend/chat/types.goindex d28c32c367..9c1d6537ad 100644--- a/libs/fleet/backend/chat/types.go+++ b/libs/fleet/backend/chat/types.go@@ -34,18 +34,20 @@ type Message struct {}type Conversation struct {- ID string `json:"id"`- Title string `json:"title"`- Messages []Message `json:"messages"`- CreatedAt time.Time `json:"created_at"`- UpdatedAt time.Time `json:"updated_at"`+ ID string `json:"id"`+ Title string `json:"title"`+ Messages []Message `json:"messages"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ ArchivedAt *time.Time `json:"archived_at,omitempty"`}type ConversationSummary struct {- ID string `json:"id"`- Title string `json:"title"`- CreatedAt time.Time `json:"created_at"`- UpdatedAt time.Time `json:"updated_at"`+ ID string `json:"id"`+ Title string `json:"title"`+ CreatedAt time.Time `json:"created_at"`+ UpdatedAt time.Time `json:"updated_at"`+ ArchivedAt *time.Time `json:"archived_at,omitempty"`}type messageJSON struct {diff --git a/libs/fleet/backend/docs/docs.go b/libs/fleet/backend/docs/docs.goindex 306cfc41db..34769b933e 100644--- a/libs/fleet/backend/docs/docs.go+++ b/libs/fleet/backend/docs/docs.go@@ -699,6 +699,14 @@ const docTemplate = `{"chat"],"summary": "List the calling user's chat conversations",+ "parameters": [+ {+ "type": "boolean",+ "description": "Whether to list archived conversations",+ "name": "archived",+ "in": "query"+ }+ ],"responses": {"200": {"description": "OK",@@ -709,6 +717,12 @@ const docTemplate = `{}}},+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },"401": {"description": "Unauthorized","schema": {@@ -825,6 +839,79 @@ const docTemplate = `{}}}+ },+ "patch": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "chat"+ ],+ "summary": "Archive or restore a chat conversation",+ "parameters": [+ {+ "type": "string",+ "description": "Conversation ID",+ "name": "id",+ "in": "path",+ "required": true+ },+ {+ "description": "Archive state",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.ArchiveConversationRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/chat.Conversation"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "413": {+ "description": "Request Entity Too Large",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }}},"/api/chat/conversations/{id}/turns": {@@ -887,6 +974,12 @@ const docTemplate = `{"$ref": "#/definitions/handlers.ErrorResponse"}},+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },"503": {"description": "Service Unavailable","schema": {@@ -1649,6 +1742,9 @@ const docTemplate = `{"chat.Conversation": {"type": "object","properties": {+ "archived_at": {+ "type": "string"+ },"created_at": {"type": "string"},@@ -1672,6 +1768,9 @@ const docTemplate = `{"chat.ConversationSummary": {"type": "object","properties": {+ "archived_at": {+ "type": "string"+ },"created_at": {"type": "string"},@@ -1834,6 +1933,17 @@ const docTemplate = `{}}},+ "handlers.ArchiveConversationRequest": {+ "type": "object",+ "required": [+ "archived"+ ],+ "properties": {+ "archived": {+ "type": "boolean"+ }+ }+ },"handlers.BillingSessionResponse": {"type": "object","properties": {diff --git a/libs/fleet/backend/docs/swagger.json b/libs/fleet/backend/docs/swagger.jsonindex ace231cb3f..0cb96e4382 100644--- a/libs/fleet/backend/docs/swagger.json+++ b/libs/fleet/backend/docs/swagger.json@@ -692,6 +692,14 @@"chat"],"summary": "List the calling user's chat conversations",+ "parameters": [+ {+ "type": "boolean",+ "description": "Whether to list archived conversations",+ "name": "archived",+ "in": "query"+ }+ ],"responses": {"200": {"description": "OK",@@ -702,6 +710,12 @@}}},+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },"401": {"description": "Unauthorized","schema": {@@ -818,6 +832,79 @@}}}+ },+ "patch": {+ "security": [+ {+ "BearerAuth": []+ }+ ],+ "consumes": [+ "application/json"+ ],+ "produces": [+ "application/json"+ ],+ "tags": [+ "chat"+ ],+ "summary": "Archive or restore a chat conversation",+ "parameters": [+ {+ "type": "string",+ "description": "Conversation ID",+ "name": "id",+ "in": "path",+ "required": true+ },+ {+ "description": "Archive state",+ "name": "body",+ "in": "body",+ "required": true,+ "schema": {+ "$ref": "#/definitions/handlers.ArchiveConversationRequest"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "OK",+ "schema": {+ "$ref": "#/definitions/chat.Conversation"+ }+ },+ "400": {+ "description": "Bad Request",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "401": {+ "description": "Unauthorized",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "404": {+ "description": "Not Found",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "413": {+ "description": "Request Entity Too Large",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },+ "503": {+ "description": "Service Unavailable",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ }+ }}},"/api/chat/conversations/{id}/turns": {@@ -880,6 +967,12 @@"$ref": "#/definitions/handlers.ErrorResponse"}},+ "409": {+ "description": "Conflict",+ "schema": {+ "$ref": "#/definitions/handlers.ErrorResponse"+ }+ },"503": {"description": "Service Unavailable","schema": {@@ -1642,6 +1735,9 @@"chat.Conversation": {"type": "object","properties": {+ "archived_at": {+ "type": "string"+ },"created_at": {"type": "string"},@@ -1665,6 +1761,9 @@"chat.ConversationSummary": {"type": "object","properties": {+ "archived_at": {+ "type": "string"+ },"created_at": {"type": "string"},@@ -1827,6 +1926,17 @@}}},+ "handlers.ArchiveConversationRequest": {+ "type": "object",+ "required": [+ "archived"+ ],+ "properties": {+ "archived": {+ "type": "boolean"+ }+ }+ },"handlers.BillingSessionResponse": {"type": "object","properties": {diff --git a/libs/fleet/backend/docs/swagger.yaml b/libs/fleet/backend/docs/swagger.yamlindex b87eb60f16..ef15194450 100644--- a/libs/fleet/backend/docs/swagger.yaml+++ b/libs/fleet/backend/docs/swagger.yaml@@ -74,6 +74,8 @@ definitions:type: objectchat.Conversation:properties:+ archived_at:+ type: stringcreated_at:type: stringid:@@ -89,6 +91,8 @@ definitions:type: objectchat.ConversationSummary:properties:+ archived_at:+ type: stringcreated_at:type: stringid:@@ -200,6 +204,13 @@ definitions:message:type: stringtype: object+ handlers.ArchiveConversationRequest:+ properties:+ archived:+ type: boolean+ required:+ - archived+ type: objecthandlers.BillingSessionResponse:properties:url:@@ -832,6 +843,11 @@ paths:- billing/api/chat/conversations:get:+ parameters:+ - description: Whether to list archived conversations+ in: query+ name: archived+ type: booleanproduces:- application/jsonresponses:@@ -841,6 +857,10 @@ paths:items:$ref: '#/definitions/chat.ConversationSummary'type: array+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'"401":description: Unauthorizedschema:@@ -919,6 +939,53 @@ paths:summary: Get a chat conversationtags:- chat+ patch:+ consumes:+ - application/json+ parameters:+ - description: Conversation ID+ in: path+ name: id+ required: true+ type: string+ - description: Archive state+ in: body+ name: body+ required: true+ schema:+ $ref: '#/definitions/handlers.ArchiveConversationRequest'+ produces:+ - application/json+ responses:+ "200":+ description: OK+ schema:+ $ref: '#/definitions/chat.Conversation'+ "400":+ description: Bad Request+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "401":+ description: Unauthorized+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "404":+ description: Not Found+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "413":+ description: Request Entity Too Large+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ "503":+ description: Service Unavailable+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'+ security:+ - BearerAuth: []+ summary: Archive or restore a chat conversation+ tags:+ - chat/api/chat/conversations/{id}/turns:post:consumes:@@ -954,6 +1021,10 @@ paths:description: Not Foundschema:$ref: '#/definitions/handlers.ErrorResponse'+ "409":+ description: Conflict+ schema:+ $ref: '#/definitions/handlers.ErrorResponse'"503":description: Service Unavailableschema:diff --git a/libs/fleet/backend/handlers/chat.go b/libs/fleet/backend/handlers/chat.goindex 79cb59ee16..0c34cd5324 100644--- a/libs/fleet/backend/handlers/chat.go+++ b/libs/fleet/backend/handlers/chat.go@@ -15,10 +15,11 @@ import ()const (- chatTurnBodyMaxBytes = 256 << 10- chatMessageMaxBytes = 128 << 10- chatHistoryMaxBytes = 1 << 20- chatHistoryMaxCount = 256+ chatTurnBodyMaxBytes = 256 << 10+ chatConversationUpdateBodyMaxBytes = 4 << 10+ chatMessageMaxBytes = 128 << 10+ chatHistoryMaxBytes = 1 << 20+ chatHistoryMaxCount = 256)var errChatTurnTooLarge = errors.New("chat turn is too large")@@ -27,6 +28,10 @@ type TurnRequest struct {Messages []chat.Message `json:"messages"`}+type ArchiveConversationRequest struct {+ Archived *bool `json:"archived" binding:"required"`+}+type turnEvent struct {Type string `json:"type"`Delta string `json:"delta,omitempty"`@@ -93,7 +98,9 @@ func (h Handlers) CreateConversation(w http.ResponseWriter, r *http.Request) {// @Summary List the calling user's chat conversations// @Tags chat// @Produce json+// @Param archived query bool false "Whether to list archived conversations"// @Success 200 {array} chat.ConversationSummary+// @Failure 400 {object} ErrorResponse// @Failure 401 {object} ErrorResponse// @Failure 404 {object} ErrorResponse// @Failure 503 {object} ErrorResponse@@ -104,7 +111,22 @@ func (h Handlers) ListConversations(w http.ResponseWriter, r *http.Request) {if user == nil {return}- conversations, err := h.Conversations.List(r.Context(), user.ID)+ archived := false+ if values, present := r.URL.Query()["archived"]; present {+ if len(values) != 1 {+ writeErr(w, http.StatusBadRequest, "invalid archived query value")+ return+ }+ switch values[0] {+ case "false":+ case "true":+ archived = true+ default:+ writeErr(w, http.StatusBadRequest, "invalid archived query value")+ return+ }+ }+ conversations, err := h.Conversations.List(r.Context(), user.ID, archived)if err != nil {slog.ErrorContext(r.Context(), "list chat conversations", "err", err, "user", user.ID)writeErr(w, http.StatusInternalServerError, "failed to list conversations")@@ -143,6 +165,56 @@ func (h Handlers) GetConversation(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, conversation)}+// UpdateConversation godoc+//+// @Summary Archive or restore a chat conversation+// @Tags chat+// @Accept json+// @Produce json+// @Param id path string true "Conversation ID"+// @Param body body ArchiveConversationRequest true "Archive state"+// @Success 200 {object} chat.Conversation+// @Failure 400 {object} ErrorResponse+// @Failure 401 {object} ErrorResponse+// @Failure 404 {object} ErrorResponse+// @Failure 413 {object} ErrorResponse+// @Failure 503 {object} ErrorResponse+// @Security BearerAuth+// @Router /api/chat/conversations/{id} [patch]+func (h Handlers) UpdateConversation(w http.ResponseWriter, r *http.Request) {+ user := h.chatUser(w, r)+ if user == nil {+ return+ }++ r.Body = http.MaxBytesReader(w, r.Body, chatConversationUpdateBodyMaxBytes)+ request, err := decodeArchiveConversationRequest(r.Body)+ if err != nil {+ var maxErr *http.MaxBytesError+ if errors.As(err, &maxErr) {+ writeErr(w, http.StatusRequestEntityTooLarge, "conversation update body is too large")+ } else {+ writeErr(w, http.StatusBadRequest, "invalid body")+ }+ return+ }++ conversationID := chatConversationID(r)+ unlock := h.lockConversation(conversationID)+ defer unlock()+ conversation, err := h.Conversations.SetArchived(r.Context(), user.ID, conversationID, *request.Archived)+ if errors.Is(err, chat.ErrConversationNotFound) {+ writeErr(w, http.StatusNotFound, "conversation not found")+ return+ }+ if err != nil {+ slog.ErrorContext(r.Context(), "update chat conversation archive state", "err", err, "user", user.ID)+ writeErr(w, http.StatusInternalServerError, "failed to update conversation")+ return+ }+ writeJSON(w, http.StatusOK, conversation)+}+// CreateTurn godoc//// @Summary Send a chat turn and stream the assistant response@@ -155,6 +227,7 @@ func (h Handlers) GetConversation(w http.ResponseWriter, r *http.Request) {// @Failure 400 {object} ErrorResponse// @Failure 401 {object} ErrorResponse// @Failure 404 {object} ErrorResponse+// @Failure 409 {object} ErrorResponse// @Failure 503 {object} ErrorResponse// @Security BearerAuth// @Router /api/chat/conversations/{id}/turns [post]@@ -193,6 +266,10 @@ func (h Handlers) CreateTurn(w http.ResponseWriter, r *http.Request) {writeErr(w, http.StatusInternalServerError, "failed to get conversation")return}+ if conversation.ArchivedAt != nil {+ writeErr(w, http.StatusConflict, "conversation is archived")+ return+ }request.Messages = recoverAbandonedToolCalls(conversation.Messages, request.Messages)if err := validateTurn(conversation.Messages, request.Messages); err != nil {if errors.Is(err, errChatTurnTooLarge) {@@ -204,6 +281,10 @@ func (h Handlers) CreateTurn(w http.ResponseWriter, r *http.Request) {}if len(request.Messages) > 0 {if err := h.Conversations.Append(r.Context(), user.ID, conversationID, request.Messages...); err != nil {+ if errors.Is(err, chat.ErrConversationArchived) {+ writeErr(w, http.StatusConflict, "conversation is archived")+ return+ }if errors.Is(err, chat.ErrConversationLimit) {writeErr(w, http.StatusRequestEntityTooLarge, "conversation storage limit reached")return@@ -385,6 +466,22 @@ func chatConversationID(r *http.Request) string {return strings.TrimSuffix(path, "/turns")}+func decodeArchiveConversationRequest(body io.Reader) (ArchiveConversationRequest, error) {+ var request ArchiveConversationRequest+ decoder := json.NewDecoder(body)+ decoder.DisallowUnknownFields()+ if err := decoder.Decode(&request); err != nil {+ return ArchiveConversationRequest{}, err+ }+ if err := decoder.Decode(&struct{}{}); err != io.EOF {+ return ArchiveConversationRequest{}, errors.New("multiple JSON values")+ }+ if request.Archived == nil {+ return ArchiveConversationRequest{}, errors.New("archived is required")+ }+ return request, nil+}+func decodeTurnRequest(body io.Reader) (TurnRequest, error) {var raw struct {Messages *json.RawMessage `json:"messages"`diff --git a/libs/fleet/backend/handlers/chat_test.go b/libs/fleet/backend/handlers/chat_test.goindex dc8f9f4316..4e1fc1b2d1 100644--- a/libs/fleet/backend/handlers/chat_test.go+++ b/libs/fleet/backend/handlers/chat_test.go@@ -403,6 +403,59 @@ func TestChatTurnSerializesConcurrentTurnsPerConversation(t *testing.T) {}}+func TestChatConversationArchiveWaitsForActiveTurn(t *testing.T) {+ store := chat.NewMemoryConversationStore()+ model := &blockingSequentialModel{+ firstStarted: make(chan struct{}),+ releaseFirst: make(chan struct{}),+ }+ h := Handlers{+ ChatAccess: config.ChatAccessAll,+ Conversations: store,+ Model: model,+ chatLocks: newConversationLockRegistry(),+ }+ conversation := createChatConversation(t, h, alice)++ turnStatus := make(chan int, 1)+ go func() {+ w := httptest.NewRecorder()+ h.CreateTurn(w, newReq(http.MethodPost, "/api/chat/conversations/"+conversation.ID+"/turns", `{"messages":[{"role":"user","content":"hold the lock"}]}`, alice))+ turnStatus <- w.Code+ }()+ <-model.firstStarted++ archiveStatus := make(chan int, 1)+ go func() {+ w := httptest.NewRecorder()+ h.UpdateConversation(w, newReq(http.MethodPatch, "/api/chat/conversations/"+conversation.ID, `{"archived":true}`, alice))+ archiveStatus <- w.Code+ }()++ select {+ case status := <-archiveStatus:+ close(model.releaseFirst)+ <-turnStatus+ t.Fatalf("PATCH completed with status %d while the turn held the conversation lock", status)+ case <-time.After(100 * time.Millisecond):+ }++ close(model.releaseFirst)+ if status := <-turnStatus; status != http.StatusOK {+ t.Fatalf("turn status = %d, want 200", status)+ }+ if status := <-archiveStatus; status != http.StatusOK {+ t.Fatalf("PATCH status = %d, want 200", status)+ }+ updated, err := store.Get(context.Background(), alice.ID, conversation.ID)+ if err != nil {+ t.Fatalf("get archived conversation: %v", err)+ }+ if updated.ArchivedAt == nil {+ t.Fatal("archived_at = nil after PATCH")+ }+}+func TestChatTurnRecoversAbandonedToolCallsBeforeNewPrompt(t *testing.T) {h, store, model := newChatHandlers(chat.Message{Role: chat.RoleAssistant, Content: "recovered"})conversation := createChatConversation(t, h, alice)@@ -553,3 +606,136 @@ func TestChatEndpointsEnforceEffectiveAccess(t *testing.T) {})}}++func TestChatConversationsListFiltersArchived(t *testing.T) {+ h, store, _ := newChatHandlers()+ active := createChatConversation(t, h, alice)+ archived := createChatConversation(t, h, alice)+ if _, err := store.SetArchived(context.Background(), alice.ID, archived.ID, true); err != nil {+ t.Fatalf("archive conversation: %v", err)+ }++ for _, tc := range []struct {+ name string+ target string+ statusCode int+ wantID string+ }{+ {name: "active by default", target: "/api/chat/conversations", statusCode: http.StatusOK, wantID: active.ID},+ {name: "active explicitly", target: "/api/chat/conversations?archived=false", statusCode: http.StatusOK, wantID: active.ID},+ {name: "archived", target: "/api/chat/conversations?archived=true", statusCode: http.StatusOK, wantID: archived.ID},+ {name: "invalid archive value", target: "/api/chat/conversations?archived=1", statusCode: http.StatusBadRequest},+ {name: "present empty archive value", target: "/api/chat/conversations?archived=", statusCode: http.StatusBadRequest},+ {name: "duplicate true archive values", target: "/api/chat/conversations?archived=true&archived=true", statusCode: http.StatusBadRequest},+ {name: "duplicate true and invalid archive values", target: "/api/chat/conversations?archived=true&archived=invalid", statusCode: http.StatusBadRequest},+ {name: "duplicate true and false archive values", target: "/api/chat/conversations?archived=true&archived=false", statusCode: http.StatusBadRequest},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ h.ListConversations(w, newReq(http.MethodGet, tc.target, "", alice))+ if w.Code != tc.statusCode {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, tc.statusCode, w.Body.String())+ }+ if tc.wantID == "" {+ return+ }+ var summaries []chat.ConversationSummary+ if err := json.Unmarshal(w.Body.Bytes(), &summaries); err != nil {+ t.Fatalf("decode summaries: %v", err)+ }+ if len(summaries) != 1 || summaries[0].ID != tc.wantID {+ t.Fatalf("summaries = %#v, want %q", summaries, tc.wantID)+ }+ })+ }+}++func TestChatConversationsArchiveAndRestore(t *testing.T) {+ h, _, _ := newChatHandlers()+ conversation := createChatConversation(t, h, alice)++ for _, tc := range []struct {+ name string+ body string+ archived bool+ }{+ {name: "archive", body: `{"archived":true}`, archived: true},+ {name: "restore", body: `{"archived":false}`, archived: false},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ h.UpdateConversation(w, newReq(http.MethodPatch, "/api/chat/conversations/"+conversation.ID, tc.body, alice))+ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200; body = %s", w.Code, w.Body.String())+ }+ var updated chat.Conversation+ if err := json.Unmarshal(w.Body.Bytes(), &updated); err != nil {+ t.Fatalf("decode conversation: %v", err)+ }+ if (updated.ArchivedAt != nil) != tc.archived {+ t.Fatalf("archived_at = %v, want archived = %t", updated.ArchivedAt, tc.archived)+ }+ })+ }+}++func TestChatConversationsArchiveRejectsInvalidRequests(t *testing.T) {+ h, _, _ := newChatHandlers()+ conversation := createChatConversation(t, h, alice)++ for _, tc := range []struct {+ name string+ body string+ statusCode int+ }{+ {name: "missing archived", body: `{}`, statusCode: http.StatusBadRequest},+ {name: "malformed JSON", body: `{"archived":`, statusCode: http.StatusBadRequest},+ {name: "unknown field", body: `{"archived":true,"unexpected":true}`, statusCode: http.StatusBadRequest},+ {name: "trailing JSON", body: `{"archived":true} {}`, statusCode: http.StatusBadRequest},+ {name: "oversized", body: `{"archived":true,"padding":"` + strings.Repeat("x", 4096) + `"}`, statusCode: http.StatusRequestEntityTooLarge},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ h.UpdateConversation(w, newReq(http.MethodPatch, "/api/chat/conversations/"+conversation.ID, tc.body, alice))+ if w.Code != tc.statusCode {+ t.Fatalf("status = %d, want %d; body = %s", w.Code, tc.statusCode, w.Body.String())+ }+ })+ }+}++func TestChatConversationsArchiveHidesMissingAndOtherOwners(t *testing.T) {+ h, _, _ := newChatHandlers()+ conversation := createChatConversation(t, h, alice)++ for _, tc := range []struct {+ name string+ id string+ user *auth.User+ }{+ {name: "missing", id: "missing", user: alice},+ {name: "other owner", id: conversation.ID, user: &auth.User{ID: "user-bob"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ h.UpdateConversation(w, newReq(http.MethodPatch, "/api/chat/conversations/"+tc.id, `{"archived":true}`, tc.user))+ if w.Code != http.StatusNotFound {+ t.Fatalf("status = %d, want 404; body = %s", w.Code, w.Body.String())+ }+ })+ }+}++func TestChatTurnRejectsArchivedConversation(t *testing.T) {+ h, store, _ := newChatHandlers(chat.Message{Role: chat.RoleAssistant, Content: "unused"})+ conversation := createChatConversation(t, h, alice)+ if _, err := store.SetArchived(context.Background(), alice.ID, conversation.ID, true); err != nil {+ t.Fatalf("archive conversation: %v", err)+ }++ w := httptest.NewRecorder()+ h.CreateTurn(w, newReq(http.MethodPost, "/api/chat/conversations/"+conversation.ID+"/turns", `{"messages":[{"role":"user","content":"hello"}]}`, alice))+ if w.Code != http.StatusConflict {+ t.Fatalf("status = %d, want 409; body = %s", w.Code, w.Body.String())+ }+}diff --git a/libs/fleet/backend/main.go b/libs/fleet/backend/main.goindex 99b827ce5a..cfe28b2b78 100644--- a/libs/fleet/backend/main.go+++ b/libs/fleet/backend/main.go@@ -145,6 +145,8 @@ func setupRouter(c handlers.Handlers) http.Handler {withAuthenticatedMiddlewares("/api/chat/conversations", c.ListConversations))r.Handle("GET /api/chat/conversations/{id}",withAuthenticatedMiddlewares("/api/chat/conversations/{id}", c.GetConversation))+ r.Handle("PATCH /api/chat/conversations/{id}",+ withAuthenticatedMiddlewares("/api/chat/conversations/{id}", c.UpdateConversation))r.Handle("POST /api/chat/conversations/{id}/turns",withAuthenticatedMiddlewares("/api/chat/conversations/{id}/turns", c.CreateTurn))diff --git a/libs/fleet/backend/main_test.go b/libs/fleet/backend/main_test.goindex 867f7394d4..41298691c5 100644--- a/libs/fleet/backend/main_test.go+++ b/libs/fleet/backend/main_test.go@@ -570,25 +570,60 @@ func TestK8sRouteRejectsDisallowedPoolBeforeProxy(t *testing.T) {}}+func TestChatConversationRouteRegistersPatch(t *testing.T) {+ router := setupRouter(handlers.Handlers{})+ request := httptest.NewRequest(http.MethodPatch, "/api/chat/conversations/id-1", nil)+ response := httptest.NewRecorder()+ router.ServeHTTP(response, request)+ if response.Code != http.StatusUnauthorized {+ t.Fatalf("PATCH status = %d, want 401; body = %s", response.Code, response.Body.String())+ }+}+func TestSwaggerIncludesChatRoutes(t *testing.T) {data, err := os.ReadFile("docs/swagger.json")if err != nil {t.Fatal(err)}+ type swaggerParameter struct {+ In string `json:"in"`+ Name string `json:"name"`+ }+ type swaggerOperation struct {+ Parameters []swaggerParameter `json:"parameters"`+ }+ type swaggerSchema struct {+ Required []string `json:"required"`+ }var spec struct {- Paths map[string]map[string]struct{} `json:"paths"`+ Definitions map[string]swaggerSchema `json:"definitions"`+ Paths map[string]map[string]swaggerOperation `json:"paths"`}if err := json.Unmarshal(data, &spec); err != nil {t.Fatalf("unmarshal swagger.json: %v", err)}for _, tc := range []struct{ path, method string }{{"/api/chat/conversations", "post"}, {"/api/chat/conversations", "get"},- {"/api/chat/conversations/{id}", "get"}, {"/api/chat/conversations/{id}/turns", "post"},+ {"/api/chat/conversations/{id}", "get"}, {"/api/chat/conversations/{id}", "patch"},+ {"/api/chat/conversations/{id}/turns", "post"},} {if _, ok := spec.Paths[tc.path][tc.method]; !ok {t.Fatalf("swagger.json missing %s %s", strings.ToUpper(tc.method), tc.path)}}+ archivedQueryFound := false+ for _, parameter := range spec.Paths["/api/chat/conversations"]["get"].Parameters {+ if parameter.In == "query" && parameter.Name == "archived" {+ archivedQueryFound = true+ break+ }+ }+ if !archivedQueryFound {+ t.Fatal("swagger.json GET /api/chat/conversations missing archived query parameter")+ }+ if !slices.Contains(spec.Definitions["handlers.ArchiveConversationRequest"].Required, "archived") {+ t.Fatal("swagger.json ArchiveConversationRequest missing required archived field")+ }}func TestNginxRoutesChatToBackend(t *testing.T) {diff --git a/libs/fleet/e2e/agent-chat.spec.ts b/libs/fleet/e2e/agent-chat.spec.tsindex 022a0c16b0..6f6aae5e8b 100644--- a/libs/fleet/e2e/agent-chat.spec.ts+++ b/libs/fleet/e2e/agent-chat.spec.ts@@ -1,7 +1,7 @@-import { expect, test } from "@playwright/test"+import { expect, test } from "@playwright/test";-import { mockAuth, mockChatApi } from "./fixtures/mock-api"-import { expectSharedPageShell } from "./fixtures/shell-geometry"+import { mockAuth, mockChatApi } from "./fixtures/mock-api";+import { expectSharedPageShell } from "./fixtures/shell-geometry";test.describe("shared Chat page shell", () => {for (const viewport of [@@ -11,442 +11,1371 @@ test.describe("shared Chat page shell", () => {test(`keeps the shared shell and composer in view on ${viewport.name}`, async ({page,}) => {- await page.setViewportSize(viewport)- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page)- await page.goto("/agent")+ await page.setViewportSize(viewport);+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page);+ await page.goto("/agent");- await expectSharedPageShell(page)- await expect(page.getByRole("heading", { name: "Chat" })).toBeVisible()+ await expect(page.getByRole("heading", { name: "Chat" })).toBeVisible();+ await expectSharedPageShell(page);await expect(page.getByText("Run fleet and browser tasks with the Cua agent."),- ).toHaveCount(viewport.width > 700 ? 1 : 0)- await expect(page.locator(".agent-chat-composer")).toBeInViewport()- const composerBox = await page.locator(".agent-chat-composer").boundingBox()- expect(composerBox).not.toBeNull()+ ).toHaveCount(viewport.width > 700 ? 1 : 0);+ await expect(page.locator(".agent-chat-composer")).toBeInViewport();+ const composerBox = await page+ .locator(".agent-chat-composer")+ .boundingBox();+ expect(composerBox).not.toBeNull();expect(viewport.height - ((composerBox?.y ?? 0) + (composerBox?.height ?? 0)),- ).toBeLessThan(40)+ ).toBeLessThan(40);expect(await page.evaluate(() => document.documentElement.scrollHeight - window.innerHeight,),- ).toBeLessThan(4)+ ).toBeLessThan(4);if (viewport.width > 700) {await expect(page.locator(".agent-chat-timestamp").first()).toHaveCSS("color","rgba(164, 173, 187, 0.82)",- )- const geometry = await page.locator(".cua-pagehead").evaluate(- async element => {- const samples: string[] = []+ );+ const geometry = await page+ .locator(".cua-pagehead")+ .evaluate(async (element) => {+ const samples: string[] = [];for (let frame = 0; frame < 30; frame += 1) {- await new Promise<void>(resolve =>+ await new Promise<void>((resolve) =>requestAnimationFrame(() => resolve()),- )- const box = element.getBoundingClientRect()- samples.push(`${box.x}:${box.y}:${box.width}:${box.height}`)+ );+ const box = element.getBoundingClientRect();+ samples.push(`${box.x}:${box.y}:${box.width}:${box.height}`);}- return samples- },- )- expect(new Set(geometry).size).toBe(1)+ return samples;+ });+ expect(new Set(geometry).size).toBe(1);}- })+ });}-})+});test("renders and exercises Chat through the standalone visual preview", async ({page,}) => {- await page.goto("/agent?cua-visual-preview")+ await page.goto("/agent/preview-browser-task?cua-visual-preview");- await expect(page).toHaveTitle("Chat · Cua")- await expect(page.getByRole("heading", { name: "Chat" })).toBeVisible()- await expect(page.getByRole("link", { name: "Chat" })).toBeVisible()- await page- .getByRole("button", { name: "Inspect the browser fleet" })- .click()+ await expect(page).toHaveTitle("Threads · Cua");+ await expect(page.getByRole("heading", { name: "Chat" })).toBeVisible();+ await expect(page.getByText("Threads", { exact: true })).toBeVisible();await expect(page.getByText("Check the browser fleet and summarize its availability."),- ).toBeVisible()- await expect(page.getByText("Command completed")).toBeVisible()+ ).toBeVisible();+ await expect(page.getByText("Command completed")).toBeVisible();await expect(page.getByText("The browser fleet is healthy:", { exact: false }),- ).toBeVisible()+ ).toBeVisible();- const prompt = page.getByPlaceholder("Ask a question")- await prompt.fill("Show me the preview response")- await page.getByRole("button", { name: "Send message" }).click()+ const prompt = page.getByPlaceholder("Ask a question");+ await prompt.fill("Show me the preview response");+ await page.getByRole("button", { name: "Send message" }).click();await expect(page.getByText("Preview mode is connected.", { exact: false }),- ).toBeVisible()- await expect(prompt).toBeEnabled()-})+ ).toBeVisible();+ await expect(prompt).toBeEnabled();+});-test("offers a useful first-run Chat state in the standalone preview", async ({+test("sidebar threads replace Chat and mark the route thread current", async ({page,}) => {- await page.goto("/agent?cua-visual-preview&cua-preview-state=empty")+ await mockAuth(page, { admin: true, billing: true, chat: true });+ await mockChatApi(page);++ await page.goto("/agent/conversation-1");await expect(- page.getByRole("heading", { name: "Start a conversation" }),- ).toBeVisible()+ page.getByRole("link", { name: "Chat", exact: true }),+ ).toHaveCount(0);+ const navigation = page.getByRole("navigation", { name: "Main navigation" });+ await expect(navigation.getByText("Threads", { exact: true })).toBeVisible();+ const [poolsBox, usageBox, userApiKeysBox, settingsBox, featureFlagsBox, threadsBox] =+ await Promise.all([+ navigation.getByRole("link", { name: "Pools", exact: true }).boundingBox(),+ navigation.getByRole("link", { name: "Usage", exact: true }).boundingBox(),+ navigation+ .getByRole("link", { name: "User API keys", exact: true })+ .boundingBox(),+ navigation+ .getByRole("link", { name: "Settings", exact: true })+ .boundingBox(),+ navigation+ .getByRole("link", { name: "Feature flags", exact: true })+ .boundingBox(),+ navigation.getByText("Threads", { exact: true }).boundingBox(),+ ]);+ expect(poolsBox).not.toBeNull();+ expect(usageBox).not.toBeNull();+ expect(userApiKeysBox).not.toBeNull();+ expect(settingsBox).not.toBeNull();+ expect(featureFlagsBox).not.toBeNull();+ expect(threadsBox).not.toBeNull();+ expect(poolsBox!.y + poolsBox!.height).toBeLessThanOrEqual(usageBox!.y);+ expect(usageBox!.y + usageBox!.height).toBeLessThanOrEqual(userApiKeysBox!.y);+ expect(userApiKeysBox!.y + userApiKeysBox!.height).toBeLessThanOrEqual(+ settingsBox!.y,+ );+ expect(settingsBox!.y + settingsBox!.height).toBeLessThanOrEqual(+ featureFlagsBox!.y,+ );+ expect(featureFlagsBox!.y + featureFlagsBox!.height).toBeLessThanOrEqual(+ threadsBox!.y,+ );+ await expect(+ page.getByRole("link", { name: "Example browser task" }),+ ).toHaveAttribute("aria-current", "page");await expect(- page.getByText("Ask a question below to create your first conversation."),- ).toBeVisible()- await expect(page.getByPlaceholder("Ask a question")).toBeEnabled()-})+ page.getByRole("link", { name: "Example browser task" }),+ ).toHaveAttribute("title", "Example browser task");-test("shows chat history, transcript region, prompt shell, and authenticated history time", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- const chat = await mockChatApi(page)+ await page.goto("/agent/archived");+ await expect(+ page.getByRole("link", { name: "Archived threads" }),+ ).toHaveAttribute("aria-current", "page");+});- await page.goto("/agent")+test("new thread posts before navigating", async ({ page }) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [+ {+ id: "conversation-1",+ title: "Existing thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });- await expect(page.getByRole("heading", { name: "Conversations" })).toBeVisible()- await expect(page.getByText("Today")).toBeVisible()- await expect(page.getByRole("region", { name: "Chat" })).toBeVisible()- await expect(page.getByPlaceholder("Ask a question")).toBeVisible()- await expect(page.locator(".agent-chat-history [title]").first()).toHaveAttribute(- "title",- /.+/,- )- expect(chat.authorizationHeaders.length).toBeGreaterThan(0)+ await page.goto("/agent/conversation-1");+ await page.getByRole("button", { name: "New thread" }).click();++ await expect.poll(() => chat.createRequests).toBe(1);+ await expect(page).toHaveURL(/\/agent\/conversation-2$/);+});++test("newest active thread redirects from /agent", async ({ page }) => {+ const now = Date.now();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "older-thread",+ title: "Older thread",+ created_at: new Date(now - 120_000).toISOString(),+ updated_at: new Date(now - 120_000).toISOString(),+ messages: [],+ },+ {+ id: "newest-thread",+ title: "Newest thread",+ created_at: new Date(now - 60_000).toISOString(),+ updated_at: new Date(now - 60_000).toISOString(),+ messages: [],+ },+ ],+ });++ await page.goto("/agent");++ await expect(page).toHaveURL(/\/agent\/newest-thread$/);+});++test("newest active creates a thread when /agent has no active threads", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, { conversations: [] });++ await page.goto("/agent");++ await expect.poll(() => chat.createRequests).toBe(1);+ await expect(page).toHaveURL(/\/agent\/conversation-1$/);+});++test("native New thread follow ignores a live pending create", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdCreate: true,+ conversations: [+ {+ id: "conversation-1",+ title: "Existing thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-1");+ await page.getByRole("link", { name: "New thread" }).click();+ await expect.poll(() => chat.createRequests).toBe(1);+ await page.getByRole("link", { name: "New thread" }).click();+ await expect.poll(() => chat.createRequests).toBe(1);++ chat.releaseCreate();+ await expect(page).toHaveURL(/\/agent\/conversation-2$/);+});++test("stale active-list responses cannot erase a newly created thread", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdList: true,+ conversations: [+ {+ id: "conversation-1",+ title: "Existing thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-1");+ await expect.poll(() => chat.listRequests).toBeGreaterThan(0);+ await page.getByRole("button", { name: "New thread" }).click();+ await expect(page).toHaveURL(/\/agent\/conversation-2$/);++ chat.releaseList();+ await expect(+ page.getByRole("link", { name: "New conversation" }),+ ).toBeVisible();+ await expect(page.getByRole("link", { name: "New thread" })).toBeVisible();+});++test("chat flag gating does not request active threads", async ({ page }) => {+ await mockAuth(page, { admin: false, chat: false });+ const chat = await mockChatApi(page);++ const config = page.waitForResponse("**/api/config");+ await page.goto("/agent");+ await config;++ await expect(page).toHaveURL(/\/pools$/);+ await expect.poll(() => chat.listRequests).toBe(0);+});++test("thread list failure shows retry without creating a thread", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [],+ listError: { message: "Thread list unavailable" },+ });++ await page.goto("/agent");++ await expect(page.getByText("Unable to load threads")).toBeVisible();+ await expect(page.getByRole("button", { name: "Retry" })).toBeVisible();+ await expect.poll(() => chat.createRequests).toBe(0);+});++test("thread actions are contextual and do not navigate before selection", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "conversation-a",+ title: "Context thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ {+ id: "conversation-b",+ title: "Other thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-a");+ await page+ .getByRole("button", { name: "Actions for Context thread" })+ .click();++ await expect(page).toHaveURL(/\/agent\/conversation-a$/);+ await expect(page.getByRole("menuitem", { name: "Archive" })).toBeVisible();+});++test("archiving the active thread falls back and Undo restores it", async ({+ page,+}) => {+ const now = Date.now();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [+ {+ id: "conversation-a",+ title: "Newest thread",+ created_at: new Date(now - 60_000).toISOString(),+ updated_at: new Date(now - 60_000).toISOString(),+ messages: [],+ },+ {+ id: "conversation-b",+ title: "Older thread",+ created_at: new Date(now - 120_000).toISOString(),+ updated_at: new Date(now - 120_000).toISOString(),+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-a");+ await page.getByRole("button", { name: "Actions for Newest thread" }).click();+ await page.getByRole("menuitem", { name: "Archive" }).click();++ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "conversation-a", archived: true }]);+ await expect(page).toHaveURL(/\/agent\/conversation-b$/);+ await page.getByRole("button", { name: "Undo" }).click();+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([+ { conversationId: "conversation-a", archived: true },+ { conversationId: "conversation-a", archived: false },+ ]);+ await expect(page.getByRole("link", { name: "Newest thread" })).toBeVisible();+});++test("delayed archive completion preserves navigation away from the archived thread", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdPatch: true,+ conversations: [+ {+ id: "conversation-a",+ title: "Archive race",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ {+ id: "conversation-b",+ title: "Other thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-a");+ await page.getByRole("button", { name: "Actions for Archive race" }).click();+ await page.getByRole("menuitem", { name: "Archive" }).click();+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "conversation-a", archived: true }]);++ await page.getByRole("link", { name: "Pools", exact: true }).click();+ await expect(page).toHaveURL(/\/pools$/);+ chat.releasePatch();++ await expect(page).toHaveURL(/\/pools$/);+});++test("mobile thread navigation closes the AppLayout drawer after selection", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await page.setViewportSize({ width: 390, height: 844 });+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "conversation-a",+ title: "Mobile first",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ {+ id: "conversation-b",+ title: "Mobile second",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-a");+ await expect(+ page.getByRole("button", { name: "View conversations" }),+ ).toHaveCount(0);+ await page.getByRole("button", { name: "Open navigation" }).click();+ await page.getByRole("link", { name: "Mobile second" }).click();++ await expect(page).toHaveURL(/\/agent\/conversation-b$/);+ await expect(+ page.getByRole("button", { name: "Close navigation" }),+ ).toHaveCount(0);+});++test("offers a useful first-run Chat state in the standalone preview", async ({+ page,+}) => {+ await page.goto("/agent?cua-visual-preview&cua-preview-state=empty");++ await expect(page.getByRole("heading", { name: "Chat" })).toBeVisible();+ await expect(+ page.getByText(+ "Choose a thread from navigation or create a new thread to begin.",+ ),+ ).toBeVisible();+ await expect(page.getByPlaceholder("Ask a question")).toBeEnabled();+});++test("renders full-width routed chat without local conversation controls", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page);++ await page.goto("/agent/conversation-1");++ await expect(page.locator(".agent-chat-history")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "View conversations" }),+ ).toHaveCount(0);+ await expect(page.getByRole("region", { name: "Chat" })).toBeVisible();+ await expect(page.getByPlaceholder("Ask a question")).toBeVisible();+ const mainBox = await page.locator(".agent-chat-main").boundingBox();+ const pageBodyBox = await page.locator(".cua-pagebody").boundingBox();+ expect(mainBox).not.toBeNull();+ expect(pageBodyBox).not.toBeNull();+ expect(+ Math.abs((mainBox?.x ?? 0) - (pageBodyBox?.x ?? 0)),+ ).toBeLessThanOrEqual(32);+ expect(+ Math.abs(+ (mainBox?.x ?? 0) ++ (mainBox?.width ?? 0) -+ ((pageBodyBox?.x ?? 0) + (pageBodyBox?.width ?? 0)),+ ),+ ).toBeLessThanOrEqual(32);+ expect(chat.authorizationHeaders.length).toBeGreaterThan(0);expect(chat.authorizationHeaders).toEqual(expect.arrayContaining([expect.stringMatching(/^Bearer /)]),- )-})--test("renders a full-width multiline composer with hidden announcements", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page)-- await page.goto("/agent")-- const composer = page.locator(".agent-chat-composer")- const prompt = page.locator(".agent-chat-prompt")- const textarea = page.getByPlaceholder("Ask a question")- const composerBox = await composer.boundingBox()- const promptBox = await prompt.boundingBox()- const initialHeight = (await textarea.boundingBox())?.height ?? 0-- expect(composerBox).not.toBeNull()- expect(promptBox).not.toBeNull()- expect((promptBox?.width ?? 0) / (composerBox?.width ?? 1)).toBeGreaterThan(0.9)- expect(initialHeight).toBeGreaterThan(44)-- await textarea.fill("First line\nSecond line\nThird line")- await expect.poll(async () => (await textarea.boundingBox())?.height ?? 0).toBeGreaterThan(initialHeight)-- const announcement = page.locator('[aria-live="polite"]').filter({ hasText: "No conversation selected" })- const announcements = page.locator(".agent-chat-announcements")- await expect(announcement).toBeAttached()- await expect(announcements).toHaveCSS("overflow", "hidden")- await expect.poll(async () => announcements.evaluate(element => ({ width: element.clientWidth, height: element.clientHeight }))).toEqual({ width: 1, height: 1 })-})--test("keeps the prompt visible while conversation history loads", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- const chat = await mockChatApi(page, { holdList: true })-- await page.goto("/agent")-- await expect(page.getByTestId("conversation-skeleton")).toHaveCount(3)- await expect(page.getByPlaceholder("Ask a question")).toBeVisible()- chat.releaseList()-})--test("loads a selected conversation with message skeletons and accessible author times", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- const chat = await mockChatApi(page, { holdConversation: true })-- await page.goto("/agent")- await page.getByRole("button", { name: "Example browser task" }).click()-- await expect(page.getByTestId("message-skeleton")).toHaveCount(2)- await expect(page.getByPlaceholder("Ask a question")).toBeVisible()- chat.releaseConversation()-- await expect(page.getByText("Open the example site.")).toBeVisible()- await expect(page.getByText("The example site is ready.")).toBeVisible()- await expect(page.getByLabel("Your avatar")).toHaveText("Y")- await expect(page.getByLabel(/^You at /)).toBeVisible()- await expect(page.getByLabel(/^Assistant at /)).toBeVisible()-})--test("renders and sanitizes Markdown in user and assistant messages", async ({ page }) => {- const now = new Date().toISOString()- await mockAuth(page, { admin: false, chat: true })+ );+});++test("renders a full-width multiline composer with hidden announcements", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page);++ await page.goto("/agent");++ const composer = page.locator(".agent-chat-composer");+ const prompt = page.locator(".agent-chat-prompt");+ const textarea = page.getByPlaceholder("Ask a question");+ const composerBox = await composer.boundingBox();+ const promptBox = await prompt.boundingBox();+ const initialHeight = (await textarea.boundingBox())?.height ?? 0;++ expect(composerBox).not.toBeNull();+ expect(promptBox).not.toBeNull();+ expect((promptBox?.width ?? 0) / (composerBox?.width ?? 1)).toBeGreaterThan(+ 0.9,+ );+ expect(initialHeight).toBeGreaterThan(44);++ await textarea.fill("First line\nSecond line\nThird line");+ await expect+ .poll(async () => (await textarea.boundingBox())?.height ?? 0)+ .toBeGreaterThan(initialHeight);++ const announcement = page+ .locator('[aria-live="polite"]')+ .filter({ hasText: "Conversation loaded" });+ const announcements = page.locator(".agent-chat-announcements");+ await expect(announcement).toBeAttached();+ await expect(announcements).toHaveCSS("overflow", "hidden");+ await expect+ .poll(async () =>+ announcements.evaluate((element) => ({+ width: element.clientWidth,+ height: element.clientHeight,+ })),+ )+ .toEqual({ width: 1, height: 1 });+});++test("keeps the prompt visible while the routed conversation loads", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, { holdConversation: true });++ await page.goto("/agent/conversation-1");++ await expect(page.getByTestId("message-skeleton")).toHaveCount(2);+ await expect(page.getByPlaceholder("Ask a question")).toBeVisible();+ chat.releaseConversation();+});++test("loads a selected conversation with message skeletons and accessible author times", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, { holdConversation: true });++ await page.goto("/agent/conversation-1");++ await expect(page.getByTestId("message-skeleton")).toHaveCount(2);+ await expect(page.getByPlaceholder("Ask a question")).toBeVisible();+ chat.releaseConversation();++ await expect(page.getByText("Open the example site.")).toBeVisible();+ await expect(page.getByText("The example site is ready.")).toBeVisible();+ await expect(page.getByLabel("Your avatar")).toHaveText("Y");+ await expect(page.getByLabel(/^You at /)).toBeVisible();+ await expect(page.getByLabel(/^Assistant at /)).toBeVisible();+});++test("renders and sanitizes Markdown in user and assistant messages", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {- conversations: [{- id: "markdown-chat",- title: "Markdown chat",- created_at: now,- updated_at: now,- messages: [- {- id: "markdown-user",- role: "user",- content: [- "| Request | Value |",- "| --- | --- |",- "| Format | **Markdown** |",- "",- "[Safe link](https://example.com) [Unsafe link](javascript:alert(1))",- "",- '<script>window.__markdownXss = true</script><img src="https://example.com/tracker.png"><span id="location" style="color:red" onclick="window.__markdownXss = true">Sanitized text</span>',- ].join("\n"),- created_at: now,- },- {- id: "markdown-assistant",- role: "assistant",- content: [- "| Pool | Phase |",- "| --- | --- |",- "| demo | Ready |",- "",- "```ts",- "const ready = true",- "```",- ].join("\n"),- created_at: now,- },- ],- }],- })+ conversations: [+ {+ id: "markdown-chat",+ title: "Markdown chat",+ created_at: now,+ updated_at: now,+ messages: [+ {+ id: "markdown-user",+ role: "user",+ content: [+ "| Request | Value |",+ "| --- | --- |",+ "| Format | **Markdown** |",+ "",+ "[Safe link](https://example.com) [Unsafe link](javascript:alert(1))",+ "",+ '<script>window.__markdownXss = true</script><img src="https://example.com/tracker.png"><span id="location" style="color:red" onclick="window.__markdownXss = true">Sanitized text</span>',+ ].join("\n"),+ created_at: now,+ },+ {+ id: "markdown-assistant",+ role: "assistant",+ content: [+ "| Pool | Phase |",+ "| --- | --- |",+ "| demo | Ready |",+ "",+ "```ts",+ "const ready = true",+ "```",+ ].join("\n"),+ created_at: now,+ },+ ],+ },+ ],+ });- await page.goto("/agent")- await page.getByRole("button", { name: "Markdown chat" }).click()+ await page.goto("/agent/markdown-chat");- const userBubble = page.getByLabel(/^You at /)- const assistantBubble = page.getByLabel(/^Assistant at /)- await expect(userBubble.getByRole("table")).toBeVisible()- await expect(userBubble.getByRole("link", { name: "Safe link" })).toHaveAttribute("href", "https://example.com")+ const userBubble = page.getByLabel(/^You at /);+ const assistantBubble = page.getByLabel(/^Assistant at /);+ await expect(userBubble.getByRole("table")).toBeVisible();+ await expect(+ userBubble.getByRole("link", { name: "Safe link" }),+ ).toHaveAttribute("href", "https://example.com");await expect(userBubble.getByRole("link", { name: "Safe link" })).toHaveCSS("color","rgb(159, 215, 255)",- )- await expect(userBubble.getByText("Unsafe link")).not.toHaveAttribute("href", /.+/)- await expect(assistantBubble.getByRole("table")).toBeVisible()- await expect(assistantBubble.locator("pre code")).toContainText("const ready = true")-- await expect(userBubble.locator("script, img")).toHaveCount(0)- const sanitizedSpan = userBubble.getByText("Sanitized text")- await expect(sanitizedSpan).not.toHaveAttribute("style")- await expect(sanitizedSpan).not.toHaveAttribute("onclick")- await expect(sanitizedSpan).not.toHaveAttribute("id")- expect(await page.evaluate(() => (window as Window & { __markdownXss?: boolean }).__markdownXss)).toBeUndefined()-})--test("does not redirect while chat feature configuration is pending", async ({ page }) => {- const auth = await mockAuth(page, { admin: false, chat: true }, { holdConfig: true })- await mockChatApi(page)-- await page.goto("/agent")- await expect(page).toHaveURL(/\/agent$/)- await expect(page.getByRole("heading", { name: "Conversations" })).toHaveCount(0)-- auth.releaseConfig()- await expect(page.getByRole("heading", { name: "Conversations" })).toBeVisible()-})--test("manages mobile history modal focus, keyboard, inert background, and close restoration", async ({ page }) => {- await page.setViewportSize({ width: 390, height: 844 })- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page)-- await page.goto("/agent")-- const trigger = page.getByRole("button", { name: "View conversations" })- await expect(trigger).toBeVisible()- await expect(page.getByRole("dialog", { name: "Conversations" })).toHaveCount(0)-- await trigger.focus()- await trigger.press("Enter")- const dialog = page.getByRole("dialog", { name: "Conversations" })- const drawer = dialog.locator(".agent-chat-mobile-drawer")- const closeButton = dialog.getByRole("button", { name: "Close conversations" })- await expect(dialog).toBeVisible()- await expect(drawer).toHaveCSS("background-color", "rgb(24, 24, 24)")- await expect(closeButton).toBeFocused()- await expect(dialog.getByRole("heading", { name: "Conversations", exact: true })).toHaveCount(1)- await expect(page.locator("#root")).toHaveAttribute("inert", "")- const cuaIdentity = page.getByRole("link", { name: "Cua", exact: true }).first()- await cuaIdentity.focus()- await expect(cuaIdentity).not.toBeFocused()- await expect(closeButton).toBeFocused()-- const lastFocusable = dialog.locator('button:not([disabled])').last()- await closeButton.press("Shift+Tab")- await expect(lastFocusable).toBeFocused()- await lastFocusable.press("Tab")- await expect(closeButton).toBeFocused()-- await page.keyboard.press("Escape")- await expect(page.getByRole("dialog", { name: "Conversations" })).toHaveCount(0)- await expect(trigger).toBeFocused()- await expect(page.locator("#root")).not.toHaveAttribute("inert", "")-- await trigger.click()- await page.getByTestId("conversation-history-backdrop").click({ position: { x: 380, y: 420 } })- await expect(page.getByRole("dialog", { name: "Conversations" })).toHaveCount(0)- await expect(trigger).toBeFocused()-- await trigger.click()- await closeButton.click()- await expect(page.getByRole("dialog", { name: "Conversations" })).toHaveCount(0)- await expect(trigger).toBeFocused()-})--test("selects mobile history without horizontal page overflow", async ({ page }) => {- await page.setViewportSize({ width: 390, height: 844 })- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page)-- await page.goto("/agent")- await page.getByRole("button", { name: "View conversations" }).click()- await page.getByRole("dialog", { name: "Conversations" }).getByRole("button", { name: "Example browser task" }).click()-- await expect(page.getByText("The example site is ready.")).toBeVisible()- await expect(page.getByRole("dialog", { name: "Conversations" })).toHaveCount(0)- await expect.poll(() => page.evaluate(() => ({- body: document.body.scrollWidth <= document.body.clientWidth,- document: document.documentElement.scrollWidth <= document.documentElement.clientWidth,- }))).toEqual({ body: true, document: true })-})--test("returns focus to the prompt after keyboard submission completes", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+ );+ await expect(userBubble.getByText("Unsafe link")).not.toHaveAttribute(+ "href",+ /.+/,+ );+ await expect(assistantBubble.getByRole("table")).toBeVisible();+ await expect(assistantBubble.locator("pre code")).toContainText(+ "const ready = true",+ );++ await expect(userBubble.locator("script, img")).toHaveCount(0);+ const sanitizedSpan = userBubble.getByText("Sanitized text");+ await expect(sanitizedSpan).not.toHaveAttribute("style");+ await expect(sanitizedSpan).not.toHaveAttribute("onclick");+ await expect(sanitizedSpan).not.toHaveAttribute("id");+ expect(+ await page.evaluate(+ () => (window as Window & { __markdownXss?: boolean }).__markdownXss,+ ),+ ).toBeUndefined();+});++test("does not redirect while chat feature configuration is pending", async ({+ page,+}) => {+ const auth = await mockAuth(+ page,+ { admin: false, chat: true },+ { holdConfig: true },+ );+ await mockChatApi(page);++ await page.goto("/agent");+ await expect(page).toHaveURL(/\/agent$/);+ await expect(page.getByRole("heading", { name: "Chat" })).toHaveCount(1);++ auth.releaseConfig();+ await expect(page).toHaveURL(/\/agent\/conversation-1$/);+});++test("opens archived thread titles through routed navigation", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "archived-open",+ title: "Open archived",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [+ {+ id: "archived-message",+ role: "assistant",+ content: "Archived route transcript",+ created_at: now,+ },+ ],+ },+ ],+ });+ await page.goto("/agent/archived");+ await expect(page.getByRole("link", { name: "Open archived" })).toHaveAttribute(+ "title",+ "Open archived",+ );+ await page.getByRole("link", { name: "Open archived" }).click();+ await expect(page).toHaveURL(/\/agent\/archived-open$/);+ await expect(page.getByText("Archived route transcript")).toBeVisible();+});++test("suppresses duplicate transcript restore and does not hijack later navigation", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdPatch: true,+ conversations: [+ {+ id: "archived-race",+ title: "Archived race",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ],+ });+ await page.goto("/agent/archived-race");+ const restore = page.getByRole("button", { name: "Restore thread" });+ await restore.click();+ await restore.click({ force: true });+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "archived-race", archived: false }]);+ await page.goto("/pools");+ chat.releasePatch();+ await expect(page).toHaveURL(/\/pools$/);+});++test("does not overwrite an active thread when a delayed archived restore finishes", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdPatch: true,+ conversations: [+ {+ id: "archived-a",+ title: "Archived A",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [+ {+ id: "archived-a-message",+ role: "assistant",+ content: "Archived A transcript",+ created_at: now,+ },+ ],+ },+ {+ id: "active-b",+ title: "Active B",+ created_at: now,+ updated_at: now,+ messages: [+ {+ id: "active-b-message",+ role: "assistant",+ content: "Active B transcript",+ created_at: now,+ },+ ],+ },+ ],+ });++ await page.goto("/agent/archived-a");+ await page.getByRole("button", { name: "Restore thread" }).click();+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "archived-a", archived: false }]);+ await page.getByRole("link", { name: "Active B" }).click();+ await expect(page).toHaveURL(/\/agent\/active-b$/);+ await expect(page.getByText("Active B transcript")).toBeVisible();+ const listRequestsBeforeRelease = chat.listRequests;+ chat.releasePatch();+ await expect.poll(() => chat.listRequests).toBeGreaterThan(+ listRequestsBeforeRelease,+ );+ await expect(page).toHaveURL(/\/agent\/active-b$/);+ await expect(page.getByText("Active B transcript")).toBeVisible();+ await expect(page.getByText("Archived A transcript")).toHaveCount(0);+});++test("blocks sending while an archived routed conversation loads", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdConversation: true,+ conversations: [+ {+ id: "archived-loading",+ title: "Archived loading",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ],+ });+ await page.goto("/agent/archived-loading");+ await expect(page.getByPlaceholder("Ask a question")).toBeDisabled();+ await expect(+ page.getByRole("button", { name: "Send message" }),+ ).toBeDisabled();+ chat.releaseConversation();+ await expect(page.getByPlaceholder("Ask a question")).toHaveCount(0);+});++test("turn 409 becomes archived read-only state without retry", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "turn-409",+ title: "Turn 409",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ turns: [+ {+ archiveBeforeError: true,+ error: { status: 409, message: "conversation is archived" },+ },+ ],+ });+ await page.goto("/agent/turn-409");+ await page.getByPlaceholder("Ask a question").fill("Race archive");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText(/archived while generating/)).toBeVisible();+ await expect(page.getByPlaceholder("Ask a question")).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Retry" })).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Restore thread" }),+ ).toBeVisible();+});++test("turn 409 remains read-only when reconciliation fails", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "turn-409-refresh-failure",+ title: "Turn 409 refresh failure",+ created_at: now,+ updated_at: now,+ messages: [+ {+ id: "persisted-message",+ role: "assistant",+ content: "Persisted transcript",+ created_at: now,+ },+ ],+ },+ ],+ refreshError: { afterTurnRequests: 1, message: "Refresh unavailable" },+ turns: [+ {+ archiveBeforeError: true,+ error: { status: 409, message: "conversation is archived" },+ },+ ],+ });+ await page.goto("/agent/turn-409-refresh-failure");+ await page.getByPlaceholder("Ask a question").fill("Race archive");+ await page.getByRole("button", { name: "Send message" }).click();++ await expect(page.getByText(/archived while generating/)).toBeVisible();+ await expect(page.getByText("Persisted transcript")).toBeVisible();+ await expect(page.getByPlaceholder("Ask a question")).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Retry" })).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Restore thread" }),+ ).toBeVisible();+ await expect(page.getByRole("alert")).toContainText("Refresh unavailable");+ await expect(+ page.getByRole("button", { name: "Refresh conversation" }),+ ).toBeVisible();+});++test("keeps chat contained in a short desktop viewport", async ({ page }) => {+ await page.setViewportSize({ width: 900, height: 500 });+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page);+ await page.goto("/agent/conversation-1");+ await expect(page.getByPlaceholder("Ask a question")).toBeInViewport();+ await expect+ .poll(() =>+ page.evaluate(+ () => document.documentElement.scrollHeight - window.innerHeight,+ ),+ )+ .toBeLessThan(4);+});++test("recovers from New thread creation failure without a stuck route", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ createError: { message: "Create failed" },+ conversations: [+ {+ id: "usable-thread",+ title: "Usable thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });+ await page.goto("/agent/usable-thread");+ await page.getByRole("button", { name: "New thread" }).click();+ await expect(page).toHaveURL(/\/agent\/usable-thread$/);+ await expect(page.getByPlaceholder("Ask a question")).toBeEnabled();+ await page.getByRole("button", { name: "New thread" }).click();+ await expect.poll(() => chat.createRequests).toBe(2);+ await expect(page).toHaveURL(/\/agent\/conversation-2$/);+});++test("lists archived threads and restores them from the archive view", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [+ {+ id: "archived-thread",+ title: "Archived transcript",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/archived");++ await expect(+ page.getByRole("heading", { name: "Archived threads" }),+ ).toBeVisible();+ await expect(+ page.getByRole("link", { name: "Archived transcript" }),+ ).toHaveAttribute("href", "#/agent/archived-thread");+ await page+ .getByRole("button", { name: "Restore Archived transcript" })+ .click();+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "archived-thread", archived: false }]);+ await expect(page.getByText("No archived threads.")).toBeVisible();+});++test("renders archived threads read-only and restores from the transcript", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [+ {+ id: "archived-thread",+ title: "Archived transcript",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [+ {+ id: "archived-message",+ role: "assistant",+ content: "Read-only history",+ created_at: now,+ },+ ],+ },+ ],+ });++ await page.goto("/agent/archived-thread");++ await expect(+ page+ .getByRole("region", { name: "Chat" })+ .getByText("This thread is archived and read-only.", { exact: true }),+ ).toBeVisible();+ await expect(page.getByText("Read-only history")).toBeVisible();+ await expect(page.getByPlaceholder("Ask a question")).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Stop generating" }),+ ).toHaveCount(0);+ await page.getByRole("button", { name: "Restore thread" }).click();+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "archived-thread", archived: false }]);+ await expect(page).toHaveURL(/\/agent\/archived-thread$/);+ await expect(page.getByPlaceholder("Ask a question")).toBeVisible();+});++test("successful restore survives an active-list refresh failure", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ listErrorAfterPatch: { message: "Active list unavailable" },+ conversations: [+ {+ id: "archived-conversation",+ title: "Restore despite refresh",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/archived-conversation");+ await page.getByRole("button", { name: "Restore thread" }).click();++ await expect.poll(() => chat.patchRequests.length).toBe(1);+ await expect(page.getByText("This thread is archived and read-only.")).toHaveCount(0);+ await expect(page.getByRole("button", { name: "Send message" })).toBeVisible();+ await expect(page.getByText("Unable to restore thread")).toHaveCount(0);+});++test("archived restore is disabled during another thread mutation", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdCreate: true,+ conversations: [+ {+ id: "archived-conversation",+ title: "Archived mutation target",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/archived");+ await page.getByRole("button", { name: "New thread" }).click();+ await expect.poll(() => chat.createRequests).toBe(1);+ await expect(+ page.getByRole("button", { name: "Restore Archived mutation target" }),+ ).toBeDisabled();++ chat.releaseCreate();+});++test("returns focus to the prompt after keyboard submission completes", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {conversations: [],- turns: [{ events: [{ type: "content_delta", delta: "Keyboard complete." }, assistant("Keyboard complete.")] }],- })-- await page.goto("/agent")- const prompt = page.getByPlaceholder("Ask a question")- await prompt.fill("Submit from keyboard")- await prompt.press("Enter")-- await expect(page.getByText("Keyboard complete.", { exact: true })).toBeVisible()- await expect(page.locator('[aria-live="polite"]').filter({ hasText: /^Latest assistant message available\.$/ })).toHaveCount(1)- await expect(page.locator('[aria-live]').filter({ hasText: /Latest user message available/ })).toHaveCount(0)- await expect(prompt).toBeEnabled()- await expect(prompt).toBeFocused()-})--test("exposes chat states and controls by accessible role and unique name", async ({ page }) => {- const now = new Date().toISOString()- await mockAuth(page, { admin: false, chat: true })+ turns: [+ {+ events: [+ { type: "content_delta", delta: "Keyboard complete." },+ assistant("Keyboard complete."),+ ],+ },+ ],+ });++ await page.goto("/agent");+ const prompt = page.getByPlaceholder("Ask a question");+ await prompt.fill("Submit from keyboard");+ await prompt.press("Enter");++ await expect(+ page.getByText("Keyboard complete.", { exact: true }),+ ).toBeVisible();+ await expect(+ page+ .locator('[aria-live="polite"]')+ .filter({ hasText: /^Latest assistant message available\.$/ }),+ ).toHaveCount(1);+ await expect(+ page+ .locator("[aria-live]")+ .filter({ hasText: /Latest user message available/ }),+ ).toHaveCount(0);+ await expect(prompt).toBeEnabled();+ await expect(prompt).toBeFocused();+});++test("exposes chat states and controls by accessible role and unique name", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {- conversations: [{- id: "accessible-chat",- title: "Accessible chat",- created_at: now,- updated_at: now,- messages: [- { id: "user-one", role: "user", content: "First question", created_at: now },- { id: "user-two", role: "user", content: "Second question", created_at: now },- ],- }],+ conversations: [+ {+ id: "accessible-chat",+ title: "Accessible chat",+ created_at: now,+ updated_at: now,+ messages: [+ {+ id: "user-one",+ role: "user",+ content: "First question",+ created_at: now,+ },+ {+ id: "user-two",+ role: "user",+ content: "Second question",+ created_at: now,+ },+ ],+ },+ ],turns: [- { hold: true, events: [assistant("", [bashCall("accessible-command", "printf accessible")])] },+ {+ hold: true,+ events: [+ assistant("", [bashCall("accessible-command", "printf accessible")]),+ ],+ },{ error: { status: 500, message: "Accessible failure" } },],- })-- await page.goto("/agent")- await page.getByRole("button", { name: "Accessible chat" }).click()- const transcript = page.getByRole("region", { name: "Chat" })- await expect(transcript).toBeVisible()- const bubbleLabels = await transcript.locator("[aria-label]").evaluateAll(elements =>- elements.map(element => element.getAttribute("aria-label")).filter(label => label?.startsWith("You at ")),- )- expect(new Set(bubbleLabels).size).toBe(bubbleLabels.length)-- const prompt = page.getByPlaceholder("Ask a question")- await prompt.fill("Run accessible command")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.locator('[aria-live="polite"]').filter({ hasText: "Generating response" })).toHaveCount(1)- await expect(transcript.locator(':scope > [role="status"]')).toHaveCount(0)- await expect(page.getByRole("button", { name: "Stop generating" })).toBeVisible()- chat.releaseTurn()- await expect(page.getByRole("button", { name: "Command details" })).toBeVisible()- await expect(page.getByRole("alert")).toContainText("Accessible failure")- await expect(page.locator('[aria-live]').filter({ hasText: "Accessible failure" })).toHaveCount(0)-})--test("scrolls the newest message into view while keeping the composer fixed", async ({ page }) => {- const now = new Date().toISOString()- const messages = Array.from({ length: 24 }, (_, index) => ({+ });++ await page.goto("/agent/accessible-chat");+ const transcript = page.getByRole("region", { name: "Chat" });+ await expect(transcript).toBeVisible();+ const bubbleLabels = await transcript+ .locator("[aria-label]")+ .evaluateAll((elements) =>+ elements+ .map((element) => element.getAttribute("aria-label"))+ .filter((label) => label?.startsWith("You at ")),+ );+ expect(new Set(bubbleLabels).size).toBe(bubbleLabels.length);++ const prompt = page.getByPlaceholder("Ask a question");+ await prompt.fill("Run accessible command");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(+ page+ .locator('[aria-live="polite"]')+ .filter({ hasText: "Generating response" }),+ ).toHaveCount(1);+ await expect(transcript.getByText("Thinking...", { exact: true })).toBeVisible();+ await expect(+ transcript.locator('[role="status"], [aria-live]'),+ ).toHaveCount(0);+ await expect(+ page.locator('.agent-chat-announcements[aria-live="polite"]'),+ ).toHaveCount(1);+ await expect(+ page.getByRole("button", { name: "Stop generating" }),+ ).toBeVisible();+ chat.releaseTurn();+ await expect(+ transcript.getByText("Thinking...", { exact: true }),+ ).toHaveCount(0);+ await expect(+ page.getByRole("button", { name: "Command details" }),+ ).toBeVisible();+ await expect(page.getByRole("alert")).toContainText("Accessible failure");+ await expect(+ page.locator("[aria-live]").filter({ hasText: "Accessible failure" }),+ ).toHaveCount(0);+});++test("shows immediate pending feedback until the first assistant delta", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [],+ turns: [+ {+ hold: true,+ events: [+ { type: "content_delta", delta: "Ready." },+ assistant("Ready."),+ ],+ },+ ],+ });++ await page.goto("/agent");+ const transcript = page.getByRole("region", { name: "Chat" });+ await page.getByPlaceholder("Ask a question").fill("Wait for a response");+ await page.getByRole("button", { name: "Send message" }).click();++ await expect(+ transcript.getByText("Wait for a response", { exact: true }),+ ).toBeVisible();+ await expect(transcript.getByText("Thinking...", { exact: true })).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Stop generating" }),+ ).toBeVisible();+ await expect(+ transcript.locator('[role="status"], [aria-live]'),+ ).toHaveCount(0);+ await expect(+ page.locator('.agent-chat-announcements[aria-live="polite"]'),+ ).toHaveCount(1);++ chat.releaseTurn();+ await expect(+ transcript.getByText("Thinking...", { exact: true }),+ ).toHaveCount(0);+ await expect(transcript.getByText("Ready.", { exact: true })).toBeVisible();+});++test("announces generating response for a held second turn", async ({ page }) => {+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [],+ turns: [+ {+ events: [+ { type: "content_delta", delta: "First response." },+ assistant("First response."),+ ],+ },+ { hold: true },+ ],+ });++ await page.goto("/agent");+ const announcements = page.locator(".agent-chat-announcements");+ await page.getByPlaceholder("Ask a question").fill("First turn");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("First response.", { exact: true })).toBeVisible();+ await expect(announcements).toHaveText("Latest assistant message available.");++ await page.getByPlaceholder("Ask a question").fill("Second turn");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("Thinking...", { exact: true })).toBeVisible();+ await expect(announcements).toHaveText("Generating response");+ await page.getByRole("button", { name: "Stop generating" }).click();+});++test("scrolls the newest message into view while keeping the composer fixed", async ({+ page,+}) => {+ const now = new Date().toISOString();+ const messages = Array.from({ length: 48 }, (_, index) => ({id: `overflow-${index}`,- role: index % 2 === 0 ? "user" as const : "assistant" as const,+ role: index % 2 === 0 ? ("user" as const) : ("assistant" as const),content: `Overflow message ${index + 1} with enough text to occupy transcript space.`,created_at: now,- }))- await mockAuth(page, { admin: false, chat: true })+ }));+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {- conversations: [{ id: "overflow-chat", title: "Overflow chat", created_at: now, updated_at: now, messages }],- turns: [{ events: [{ type: "content_delta", delta: "Newest response." }, assistant("Newest response.")] }],- })-- await page.goto("/agent")- await page.getByRole("button", { name: "Overflow chat" }).click()- const transcript = page.getByRole("region", { name: "Chat" })- const composer = page.locator(".agent-chat-composer")- const composerBefore = await composer.boundingBox()- await transcript.evaluate(element => { element.scrollTop = 0 })-- await page.getByPlaceholder("Ask a question").fill("Show the newest response")- await page.getByRole("button", { name: "Send message" }).click()-- await expect(page.getByText("Newest response.", { exact: true })).toBeInViewport()- await expect.poll(() => transcript.evaluate(element => element.scrollTop)).toBeGreaterThan(0)- const composerAfter = await composer.boundingBox()- expect(composerBefore).not.toBeNull()- expect(composerAfter).not.toBeNull()- expect(composerAfter?.y).toBeCloseTo(composerBefore?.y ?? 0, 0)-})--test("contains long chat history without inflating document scroll", async ({ page }) => {- await page.setViewportSize({ width: 1920, height: 1080 })- const now = new Date().toISOString()- const messages = Array.from({ length: 20 }, (_, index) => ({+ conversations: [+ {+ id: "overflow-chat",+ title: "Overflow chat",+ created_at: now,+ updated_at: now,+ messages,+ },+ ],+ turns: [+ {+ events: [+ { type: "content_delta", delta: "Newest response." },+ assistant("Newest response."),+ ],+ },+ ],+ });++ await page.goto("/agent/overflow-chat");+ const transcript = page.getByRole("region", { name: "Chat" });+ const composer = page.locator(".agent-chat-composer");+ const composerBefore = await composer.boundingBox();+ await transcript.evaluate((element) => {+ element.scrollTop = 0;+ });++ await page+ .getByPlaceholder("Ask a question")+ .fill("Show the newest response");+ await page.getByRole("button", { name: "Send message" }).click();++ await expect(+ page.getByText("Newest response.", { exact: true }),+ ).toBeInViewport();+ await expect+ .poll(() => transcript.evaluate((element) => element.scrollTop))+ .toBeGreaterThan(0);+ const composerAfter = await composer.boundingBox();+ expect(composerBefore).not.toBeNull();+ expect(composerAfter).not.toBeNull();+ expect(composerAfter?.y).toBeCloseTo(composerBefore?.y ?? 0, 0);+});++test("contains long chat history without inflating document scroll", async ({+ page,+}) => {+ await page.setViewportSize({ width: 1920, height: 1080 });+ const now = new Date().toISOString();+ const messages = Array.from({ length: 48 }, (_, index) => ({id: `windows-history-${index}`,- role: index % 2 === 0 ? "user" as const : "assistant" as const,+ role: index % 2 === 0 ? ("user" as const) : ("assistant" as const),content: `| Column | Value |\n| --- | --- |\n| Row ${index} | ${"windows-image-value ".repeat(8)} |`,created_at: now,- }))- await mockAuth(page, { admin: false, chat: true })+ }));+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {- conversations: [{ id: "windows-history", title: "Windows history", created_at: now, updated_at: now, messages }],- })-- await page.goto("/agent")- await page.getByRole("button", { name: "Windows history" }).click()-- const transcript = page.getByRole("region", { name: "Chat" })- await expect.poll(() => transcript.evaluate(element => element.scrollHeight - element.clientHeight)).toBeGreaterThan(1000)- await expect.poll(() => page.evaluate(() => document.documentElement.scrollHeight - window.innerHeight)).toBeLessThan(100)-})--test("parses fragmented unterminated NDJSON and rejects malformed final events", async ({ page }) => {- await mockAuth(page)- await page.goto("/pools")+ conversations: [+ {+ id: "windows-history",+ title: "Windows history",+ created_at: now,+ updated_at: now,+ messages,+ },+ ],+ });++ await page.goto("/agent/windows-history");++ const transcript = page.getByRole("region", { name: "Chat" });+ await expect+ .poll(() =>+ transcript.evaluate(+ (element) => element.scrollHeight - element.clientHeight,+ ),+ )+ .toBeGreaterThan(1000);+ await expect+ .poll(() =>+ page.evaluate(+ () => document.documentElement.scrollHeight - window.innerHeight,+ ),+ )+ .toBeLessThan(100);+});++test("parses fragmented unterminated NDJSON and rejects malformed final events", async ({+ page,+}) => {+ await mockAuth(page);+ await page.goto("/pools");const result = await page.evaluate(async () => {- const api = await import("/src/sdk/chat.ts")- const originalFetch = window.fetch- const encode = (value: string) => new TextEncoder().encode(value)+ const api = await import("/src/sdk/chat.ts");+ const originalFetch = window.fetch;+ const encode = (value: string) => new TextEncoder().encode(value);const stream = (chunks: string[]) =>new ReadableStream<Uint8Array>({start(controller) {- for (const chunk of chunks) controller.enqueue(encode(chunk))- controller.close()+ for (const chunk of chunks) controller.enqueue(encode(chunk));+ controller.close();},- })+ });try {window.fetch = async () =>@@ -456,9 +1385,11 @@ test("parses fragmented unterminated NDJSON and rejects malformed final events",'lo"}\n{"type":"assistant","message":{"role":"assistant","content":"Complete"}}',]),{ status: 200 },- )- const deltas: string[] = []- const complete = await api.streamTurn("conversation-1", [], delta => deltas.push(delta))+ );+ const deltas: string[] = [];+ const complete = await api.streamTurn("conversation-1", [], (delta) =>+ deltas.push(delta),+ );window.fetch = async () =>new Response(@@ -466,161 +1397,255 @@ test("parses fragmented unterminated NDJSON and rejects malformed final events",'{"type":"assistant","message":{"role":"assistant","content":"ok","tool_calls":{}}}',]),{ status: 200 },- )- let malformedError = ""+ );+ let malformedError = "";try {- await api.streamTurn("conversation-1", [], () => undefined)+ await api.streamTurn("conversation-1", [], () => undefined);} catch (error) {- malformedError = error instanceof Error ? error.name : String(error)+ malformedError = error instanceof Error ? error.name : String(error);}- return { complete, deltas, malformedError }+ return { complete, deltas, malformedError };} finally {- window.fetch = originalFetch+ window.fetch = originalFetch;}- })+ });- expect(result.deltas).toEqual(["Hello"])- expect(result.complete.content).toBe("Complete")- expect(result.malformedError).toBe("ChatApiError")-})+ expect(result.deltas).toEqual(["Hello"]);+ expect(result.complete.content).toBe("Complete");+ expect(result.malformedError).toBe("ChatApiError");+});-test("hides chat navigation and redirects when the feature is disabled", async ({ page }) => {- await mockAuth(page, { admin: false, chat: false })+test("hides chat navigation and redirects when the feature is disabled", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: false });- await page.goto("/pools")- await expect(page.getByRole("link", { name: "Chat" })).toHaveCount(0)+ await page.goto("/pools");+ await expect(page.getByRole("link", { name: "Chat" })).toHaveCount(0);- await page.goto("/agent")- await expect(page).toHaveURL(/\/pools$/)-})+ await page.goto("/agent");+ await expect(page).toHaveURL(/\/pools$/);+});-test("disables skeleton shimmer when reduced motion is requested", async ({ page }) => {- await page.emulateMedia({ reducedMotion: "reduce" })- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page, { holdList: true })+test("disables skeleton shimmer when reduced motion is requested", async ({+ page,+}) => {+ await page.emulateMedia({ reducedMotion: "reduce" });+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, { holdConversation: true });- await page.goto("/agent")+ await page.goto("/agent/conversation-1");- await expect(page.getByTestId("conversation-skeleton").first()).toBeVisible()- await expect(page.getByTestId("conversation-skeleton").first()).toHaveCSS(+ await expect(page.getByTestId("message-skeleton").first()).toBeVisible();+ await expect(page.getByTestId("message-skeleton").first()).toHaveCSS("animation-name","none",- )-})--const bashCall = (id: string, command: string, options: Record<string, number> = {}) => ({+ );+});++test("disables thinking-dot animation under reduced motion", async ({ page }) => {+ await page.emulateMedia({ reducedMotion: "reduce" });+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, { conversations: [], turns: [{ hold: true }] });++ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Wait without motion");+ await page.getByRole("button", { name: "Send message" }).click();++ const dots = page.locator(".agent-chat-thinking-dots > span");+ await expect(dots).toHaveCount(3);+ for (const dot of await dots.all()) {+ await expect(dot).toBeVisible();+ await expect(dot).toHaveCSS("animation-name", "none");+ }+ await page.getByRole("button", { name: "Stop generating" }).click();+});++const bashCall = (+ id: string,+ command: string,+ options: Record<string, number> = {},+) => ({id,type: "function" as const,- function: { name: "bash", arguments: JSON.stringify({ command, ...options }) },-})--const assistant = (content: string, toolCalls: ReturnType<typeof bashCall>[] = []) => ({+ function: {+ name: "bash",+ arguments: JSON.stringify({ command, ...options }),+ },+});++const assistant = (+ content: string,+ toolCalls: ReturnType<typeof bashCall>[] = [],+) => ({type: "assistant",message: { role: "assistant", content, tool_calls: toolCalls },-})+});-test("runs a browser bash tool loop and shows completed command details", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+test("runs a browser bash tool loop and shows completed command details", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {conversations: [],turns: [- { events: [assistant("", [bashCall("bash-1", "printf hello > note.txt; cat note.txt")])] },- { events: [{ type: "content_delta", delta: "The file contains hello." }, assistant("The file contains hello.")] },+ {+ events: [+ assistant("", [+ bashCall("bash-1", "printf hello > note.txt; cat note.txt"),+ ]),+ ],+ },+ {+ events: [+ { type: "content_delta", delta: "The file contains hello." },+ assistant("The file contains hello."),+ ],+ },],- })+ });- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Create and read note.txt")- await page.getByRole("button", { name: "Send message" }).click()-- await expect(page.getByText("Running command")).toBeVisible()- await expect(page.getByText("Command completed")).toBeVisible()- await expect(page.getByText("The file contains hello.")).toBeVisible()- await page.getByRole("button", { name: "Command details" }).click()- await expect(page.getByText("printf hello > note.txt; cat note.txt")).toBeVisible()- await expect(page.getByText("hello", { exact: true })).toBeVisible()-})+ await page.goto("/agent");+ await page+ .getByPlaceholder("Ask a question")+ .fill("Create and read note.txt");+ await page.getByRole("button", { name: "Send message" }).click();++ await expect(page.getByText("Running command")).toBeVisible();+ await expect(page.getByText("Command completed")).toBeVisible();+ await expect(page.getByText("The file contains hello.")).toBeVisible();+ await page.getByRole("button", { name: "Command details" }).click();+ await expect(+ page.getByText("printf hello > note.txt; cat note.txt"),+ ).toBeVisible();+ await expect(page.getByText("hello", { exact: true })).toBeVisible();+});-test("shows failed, timed out, and truncated bash results", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+test("shows failed, timed out, and truncated bash results", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {conversations: [],turns: [{ events: [assistant("", [bashCall("failed", "false")])] },- { events: [assistant("", [bashCall("timed", "sleep 1", { timeout_ms: 250 })])] },- { events: [assistant("", [bashCall("truncated", "printf '%300s' x | tr ' ' x", { max_output_chars: 256 })])] },+ {+ events: [+ assistant("", [bashCall("timed", "sleep 1", { timeout_ms: 250 })]),+ ],+ },+ {+ events: [+ assistant("", [+ bashCall("truncated", "printf '%300s' x | tr ' ' x", {+ max_output_chars: 256,+ }),+ ]),+ ],+ },{ events: [assistant("Done")] },],- })+ });- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Exercise bash failures")- await page.getByRole("button", { name: "Send message" }).click()+ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Exercise bash failures");+ await page.getByRole("button", { name: "Send message" }).click();- await expect(page.getByText("Command failed")).toBeVisible()- await expect(page.getByText("Command timed out")).toBeVisible()- await page.getByRole("button", { name: "Command details" }).last().click()- await expect(page.getByText("Output was truncated")).toBeVisible()-})+ await expect(page.getByText("Command failed")).toBeVisible();+ await expect(page.getByText("Command timed out")).toBeVisible();+ await page.getByRole("button", { name: "Command details" }).last().click();+ await expect(page.getByText("Output was truncated")).toBeVisible();+});test("stops an active turn and restores the composer", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page, { conversations: [], turns: [{ hold: true }] })-- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Wait forever")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByRole("button", { name: "Stop generating" })).toBeVisible()- await page.getByRole("button", { name: "Stop generating" }).click()- await expect(page.getByRole("button", { name: "Stop generating" })).toHaveCount(0)- await expect(page.getByPlaceholder("Ask a question")).toBeEnabled()- await expect(page.getByText("Generating a response")).toHaveCount(0)-})--test("shows an API error and retries without duplicating the user bubble", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, { conversations: [], turns: [{ hold: true }] });++ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Wait forever");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(+ page.getByRole("button", { name: "Stop generating" }),+ ).toBeVisible();+ await expect(page.getByText("Thinking...", { exact: true })).toBeVisible();+ await page.getByRole("button", { name: "Stop generating" }).click();+ await expect(+ page.getByRole("button", { name: "Stop generating" }),+ ).toHaveCount(0);+ await expect(page.getByPlaceholder("Ask a question")).toBeEnabled();+ await expect(page.getByText("Thinking...", { exact: true })).toHaveCount(0);+});++test("shows an API error and retries without duplicating the user bubble", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {conversations: [],turns: [- { error: { status: 500, message: "Backend unavailable" } },- { events: [{ type: "content_delta", delta: "Recovered." }, assistant("Recovered")] },- ],- })-- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Try again")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByRole("alert")).toContainText("Backend unavailable")- await page.getByRole("button", { name: "Retry" }).click()- await expect(page.getByText("Recovered")).toBeVisible()- await expect(page.getByText("Try again")).toHaveCount(1)- expect(chat.turnRequests.map(request => request.messages)).toEqual([+ {+ hold: true,+ error: { status: 500, message: "Backend unavailable" },+ },+ {+ events: [+ { type: "content_delta", delta: "Recovered." },+ assistant("Recovered"),+ ],+ },+ ],+ });++ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Try again");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("Thinking...", { exact: true })).toBeVisible();++ chat.releaseTurn();+ await expect(page.getByText("Thinking...", { exact: true })).toHaveCount(0);+ await expect(page.getByRole("alert")).toContainText("Backend unavailable");+ await page.getByRole("button", { name: "Retry" }).click();+ await expect(page.getByText("Recovered")).toBeVisible();+ await expect(page.getByText("Try again")).toHaveCount(1);+ expect(chat.turnRequests.map((request) => request.messages)).toEqual([[{ role: "user", content: "Try again" }],[],- ])-})+ ]);+});test("keeps streamed Markdown in one assistant bubble", async ({ page }) => {- const markdown = "| State | Value |\n| --- | --- |\n| Stream | Ready |"- await mockAuth(page, { admin: false, chat: true })+ const markdown = "| State | Value |\n| --- | --- |\n| Stream | Ready |";+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {conversations: [],- turns: [{ events: [{ type: "content_delta", delta: markdown.slice(0, 24) }, { type: "content_delta", delta: markdown.slice(24) }, assistant(markdown)] }],- })-- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Stream")- await page.getByRole("button", { name: "Send message" }).click()- const assistantBubble = page.getByLabel(/^Assistant at /)- await expect(assistantBubble.getByRole("table")).toBeVisible()- await expect(assistantBubble.getByRole("cell", { name: "Ready" })).toBeVisible()- await expect(assistantBubble).toHaveCount(1)-})--test("reconstructs stored bash command steps from tool history", async ({ page }) => {- const now = new Date().toISOString()- await mockAuth(page, { admin: false, chat: true })+ turns: [+ {+ events: [+ { type: "content_delta", delta: markdown.slice(0, 24) },+ { type: "content_delta", delta: markdown.slice(24) },+ assistant(markdown),+ ],+ },+ ],+ });++ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Stream");+ await page.getByRole("button", { name: "Send message" }).click();+ const assistantBubble = page.getByLabel(/^Assistant at /);+ await expect(assistantBubble.getByRole("table")).toBeVisible();+ await expect(+ assistantBubble.getByRole("cell", { name: "Ready" }),+ ).toBeVisible();+ await expect(assistantBubble).toHaveCount(1);+});++test("reconstructs stored bash command steps from tool history", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {conversations: [{@@ -630,225 +1655,695 @@ test("reconstructs stored bash command steps from tool history", async ({ page }updated_at: now,messages: [{ id: "user", role: "user", content: "Read note", created_at: now },- { id: "call", role: "assistant", content: "", tool_calls: [bashCall("stored-call", "cat note.txt")], created_at: now },- { id: "result", role: "tool", tool_call_id: "stored-call", content: JSON.stringify({ stdout: "hello", stderr: "", exit_code: 0, timed_out: false, truncated: false }), created_at: now },- { id: "answer", role: "assistant", content: "The note says hello.", created_at: now },+ {+ id: "call",+ role: "assistant",+ content: "",+ tool_calls: [bashCall("stored-call", "cat note.txt")],+ created_at: now,+ },+ {+ id: "result",+ role: "tool",+ tool_call_id: "stored-call",+ content: JSON.stringify({+ stdout: "hello",+ stderr: "",+ exit_code: 0,+ timed_out: false,+ truncated: false,+ }),+ created_at: now,+ },+ {+ id: "answer",+ role: "assistant",+ content: "The note says hello.",+ created_at: now,+ },],},],- })+ });- await page.goto("/agent")- await page.getByRole("button", { name: "Stored command" }).click()- await expect(page.getByText("Command completed")).toBeVisible()- await page.getByText("Command details").click()- await expect(page.getByText("cat note.txt")).toBeVisible()- await expect(page.getByText("hello", { exact: true })).toBeVisible()- await expect(page.getByText("The note says hello.")).toBeVisible()-})+ await page.goto("/agent/stored");+ await expect(page.getByText("Command completed")).toBeVisible();+ await page.getByText("Command details").click();+ await expect(page.getByText("cat note.txt")).toBeVisible();+ await expect(page.getByText("hello", { exact: true })).toBeVisible();+ await expect(page.getByText("The note says hello.")).toBeVisible();+});-test("reconciles persisted turn history without duplicate transient entries", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+test("reconciles persisted turn history without duplicate transient entries", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });await mockChatApi(page, {conversations: [],turns: [{ events: [assistant("", [bashCall("once", "printf hello")])] },- { events: [{ type: "content_delta", delta: "Final once." }, assistant("Final once")] },- ],- })- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Run once")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("Final once", { exact: true })).toBeVisible()- await expect(page.getByText("Run once", { exact: true })).toHaveCount(1)- await expect(page.getByText("Command completed", { exact: true })).toHaveCount(1)- await expect(page.getByText("Final once", { exact: true })).toHaveCount(1)-})--test("keeps successful transient output and refreshes without rerunning the model", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+ {+ events: [+ { type: "content_delta", delta: "Final once." },+ assistant("Final once"),+ ],+ },+ ],+ });+ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Run once");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("Final once", { exact: true })).toBeVisible();+ await expect(page.getByText("Run once", { exact: true })).toHaveCount(1);+ await expect(+ page.getByText("Command completed", { exact: true }),+ ).toHaveCount(1);+ await expect(page.getByText("Final once", { exact: true })).toHaveCount(1);+});++test("keeps successful transient output and refreshes without rerunning the model", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {conversations: [],refreshError: { afterTurnRequests: 1, message: "Refresh unavailable" },- turns: [{ events: [{ type: "content_delta", delta: "Completed." }, assistant("Completed")] }],- })- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Complete then refresh")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("Completed")).toBeVisible()- await expect(page.getByRole("alert")).toContainText("Refresh unavailable")- await expect(page.getByRole("button", { name: "Refresh conversation" })).toBeVisible()- await page.getByRole("button", { name: "Refresh conversation" }).click()- await expect(page.getByRole("alert")).toHaveCount(0)- expect(chat.turnRequests).toHaveLength(1)-})---test("stops an open streamed response without showing generation retry", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- await mockChatApi(page, { conversations: [] })+ turns: [+ {+ events: [+ { type: "content_delta", delta: "Completed." },+ assistant("Completed"),+ ],+ },+ ],+ });+ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Complete then refresh");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("Completed")).toBeVisible();+ await expect(page.getByRole("alert")).toContainText("Refresh unavailable");+ await expect(+ page.getByRole("button", { name: "Refresh conversation" }),+ ).toBeVisible();+ await page.getByRole("button", { name: "Refresh conversation" }).click();+ await expect(page.getByRole("alert")).toHaveCount(0);+ expect(chat.turnRequests).toHaveLength(1);+});++test("stops an open streamed response without showing generation retry", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, { conversations: [] });await page.addInitScript(() => {- const originalFetch = window.fetch.bind(window)+ const originalFetch = window.fetch.bind(window);window.fetch = async (input, init) => {- const url = typeof input === "string" ? input : input instanceof Request ? input.url : input.toString()- if (!url.includes("/turns")) return originalFetch(input, init)- ;(window as Window & { streamHeaders?: string }).streamHeaders = "x-stream-ready"- const encoder = new TextEncoder()- return new Response(new ReadableStream({- start(controller) {- controller.enqueue(encoder.encode('{"type":"content_delta","delta":"Streaming now"}\n'))- init?.signal?.addEventListener("abort", () => controller.error(new DOMException("Aborted", "AbortError")), { once: true })- },- }), { status: 200, headers: { "X-Stream-Ready": "yes" } })- }- })- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Stop streamed response")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("Streaming now")).toBeVisible()- await expect.poll(() => page.evaluate(() => (window as Window & { streamHeaders?: string }).streamHeaders)).toBe("x-stream-ready")- await page.getByRole("button", { name: "Stop generating" }).click()- await expect(page.getByRole("alert")).toHaveCount(0)- await expect(page.getByPlaceholder("Ask a question")).toBeEnabled()-})--test("announces conversation loading, loaded, and no selected conversation", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })- const chat = await mockChatApi(page, { holdConversation: true })- await page.goto("/agent")- await expect(page.locator('[aria-live]').filter({ hasText: "No conversation selected" })).toBeAttached()- await page.getByRole("button", { name: "Example browser task" }).click()- await expect(page.locator('[aria-live]').filter({ hasText: "Loading conversation" })).toBeAttached()- chat.releaseConversation()- await expect(page.locator('[aria-live]').filter({ hasText: "Conversation loaded" })).toBeAttached()-})---test("locks submission until post-turn refresh reconciliation completes", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+ const url =+ typeof input === "string"+ ? input+ : input instanceof Request+ ? input.url+ : input.toString();+ if (!url.includes("/turns")) return originalFetch(input, init);+ (window as Window & { streamHeaders?: string }).streamHeaders =+ "x-stream-ready";+ const encoder = new TextEncoder();+ return new Response(+ new ReadableStream({+ start(controller) {+ controller.enqueue(+ encoder.encode(+ '{"type":"content_delta","delta":"Streaming now"}\n',+ ),+ );+ init?.signal?.addEventListener(+ "abort",+ () => controller.error(new DOMException("Aborted", "AbortError")),+ { once: true },+ );+ },+ }),+ { status: 200, headers: { "X-Stream-Ready": "yes" } },+ );+ };+ });+ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("Stop streamed response");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("Streaming now")).toBeVisible();+ await expect+ .poll(() =>+ page.evaluate(+ () => (window as Window & { streamHeaders?: string }).streamHeaders,+ ),+ )+ .toBe("x-stream-ready");+ await page.getByRole("button", { name: "Stop generating" }).click();+ await expect(page.getByRole("alert")).toHaveCount(0);+ await expect(page.getByPlaceholder("Ask a question")).toBeEnabled();+});++test("announces conversation loading, loaded, and no selected conversation", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, { holdConversation: true });+ await page.goto("/agent/conversation-1");+ await expect(+ page.locator("[aria-live]").filter({ hasText: "Loading conversation" }),+ ).toBeAttached();+ chat.releaseConversation();+ await expect(+ page.locator("[aria-live]").filter({ hasText: "Conversation loaded" }),+ ).toBeAttached();+});++test("locks submission until post-turn refresh reconciliation completes", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {conversations: [],holdRefresh: true,turns: [- { events: [{ type: "content_delta", delta: "First final." }, assistant("First final.")] },- { events: [{ type: "content_delta", delta: "Second final." }, assistant("Second final.")] },+ {+ events: [+ { type: "content_delta", delta: "First final." },+ assistant("First final."),+ ],+ },+ {+ events: [+ { type: "content_delta", delta: "Second final." },+ assistant("Second final."),+ ],+ },],- })+ });- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("First prompt")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("First final.", { exact: true })).toBeVisible()-- const prompt = page.getByPlaceholder("Ask a question")- await prompt.fill("Second prompt")- await expect(page.getByRole("button", { name: "Send message" })).toBeDisabled()- await page.getByRole("button", { name: "Send message" }).click({ force: true })- expect(chat.turnRequests).toHaveLength(1)-- chat.releaseRefresh()- await expect(page.getByRole("button", { name: "Send message" })).toBeEnabled()- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("Second final.", { exact: true })).toBeVisible()- expect(chat.turnRequests).toHaveLength(2)-})+ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("First prompt");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("First final.", { exact: true })).toBeVisible();+ const prompt = page.getByPlaceholder("Ask a question");+ await prompt.fill("Second prompt");+ await expect(+ page.getByRole("button", { name: "Send message" }),+ ).toBeDisabled();+ await page+ .getByRole("button", { name: "Send message" })+ .click({ force: true });+ expect(chat.turnRequests).toHaveLength(1);-test("serializes held refresh recovery before allowing another turn", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+ chat.releaseRefresh();+ await expect(+ page.getByRole("button", { name: "Send message" }),+ ).toBeEnabled();+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(page.getByText("Second final.", { exact: true })).toBeVisible();+ expect(chat.turnRequests).toHaveLength(2);+});++test("serializes held refresh recovery before allowing another turn", async ({+ page,+}) => {+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {conversations: [],refreshError: { afterTurnRequests: 1, message: "Refresh unavailable" },holdRefresh: true,turns: [- { events: [{ type: "content_delta", delta: "Recovered first." }, assistant("Recovered first.")] },- { events: [{ type: "content_delta", delta: "Second after recovery." }, assistant("Second after recovery.")] },- ],- })-- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("First recovery prompt")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByRole("button", { name: "Refresh conversation" })).toBeVisible()-- await page.getByRole("button", { name: "Refresh conversation" }).click()- const prompt = page.getByPlaceholder("Ask a question")- await prompt.fill("Blocked during recovery")- await expect(page.getByRole("button", { name: "Send message" })).toBeDisabled()- await expect(page.getByRole("button", { name: "Stop generating" })).toHaveCount(0)- await page.getByRole("button", { name: "Send message" }).click({ force: true })- expect(chat.turnRequests).toHaveLength(1)-- chat.releaseRefresh()- await expect(page.getByRole("alert")).toHaveCount(0)- await expect(page.getByText("Recovered first.", { exact: true })).toBeVisible()- await expect(page.getByRole("button", { name: "Send message" })).toBeEnabled()- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("Second after recovery.", { exact: true })).toBeVisible()- expect(chat.turnRequests).toHaveLength(2)-})---test("locks conversation selection until an active turn reconciles", async ({ page }) => {- const now = new Date().toISOString()- await mockAuth(page, { admin: false, chat: true })+ {+ events: [+ { type: "content_delta", delta: "Recovered first." },+ assistant("Recovered first."),+ ],+ },+ {+ events: [+ { type: "content_delta", delta: "Second after recovery." },+ assistant("Second after recovery."),+ ],+ },+ ],+ });++ await page.goto("/agent");+ await page.getByPlaceholder("Ask a question").fill("First recovery prompt");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(+ page.getByRole("button", { name: "Refresh conversation" }),+ ).toBeVisible();++ await page.getByRole("button", { name: "Refresh conversation" }).click();+ const prompt = page.getByPlaceholder("Ask a question");+ await prompt.fill("Blocked during recovery");+ await expect(+ page.getByRole("button", { name: "Send message" }),+ ).toBeDisabled();+ await expect(+ page.getByRole("button", { name: "Stop generating" }),+ ).toHaveCount(0);+ await page+ .getByRole("button", { name: "Send message" })+ .click({ force: true });+ expect(chat.turnRequests).toHaveLength(1);++ chat.releaseRefresh();+ await expect(page.getByRole("alert")).toHaveCount(0);+ await expect(+ page.getByText("Recovered first.", { exact: true }),+ ).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Send message" }),+ ).toBeEnabled();+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(+ page.getByText("Second after recovery.", { exact: true }),+ ).toBeVisible();+ expect(chat.turnRequests).toHaveLength(2);+});++test("locks native thread navigation until an active turn reconciles", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [+ {+ id: "conversation-a",+ title: "Conversation A",+ created_at: now,+ updated_at: now,+ messages: [+ { id: "a-user", role: "user", content: "A history", created_at: now },+ ],+ },+ {+ id: "conversation-b",+ title: "Conversation B",+ created_at: now,+ updated_at: now,+ messages: [+ {+ id: "b-user",+ role: "user",+ content: "B only message",+ created_at: now,+ },+ ],+ },+ ],+ turns: [+ {+ hold: true,+ events: [+ { type: "content_delta", delta: "A final." },+ assistant("A final."),+ ],+ },+ ],+ });++ await page.goto("/agent/conversation-a");+ await expect(page.getByText("A history")).toBeVisible();+ await page.getByPlaceholder("Ask a question").fill("Run in A");+ await page.getByRole("button", { name: "Send message" }).click();+ await page.getByRole("link", { name: "Conversation B" }).click();+ await expect(page).toHaveURL(/\/agent\/conversation-a$/);+ await expect(page.getByText("Run in A", { exact: true })).toBeVisible();+ await expect(page.getByText("B only message")).toHaveCount(0);++ chat.releaseTurn();+ await expect(page.getByText("A final.", { exact: true })).toBeVisible();+ await page.getByRole("link", { name: "Conversation B" }).click();+ await expect(page).toHaveURL(/\/agent\/conversation-b$/);+ await expect(page.getByText("B only message")).toBeVisible();+});++test("clears pending feedback after a forced thread route change", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {conversations: [- { id: "conversation-a", title: "Conversation A", created_at: now, updated_at: now, messages: [{ id: "a-user", role: "user", content: "A history", created_at: now }] },- { id: "conversation-b", title: "Conversation B", created_at: now, updated_at: now, messages: [{ id: "b-user", role: "user", content: "B only message", created_at: now }] },- ],- turns: [{ hold: true, events: [{ type: "content_delta", delta: "A final." }, assistant("A final.")] }],- })-- await page.goto("/agent")- await page.getByRole("button", { name: "Conversation A" }).click()- await expect(page.getByText("A history")).toBeVisible()- await page.getByPlaceholder("Ask a question").fill("Run in A")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByRole("button", { name: "Conversation B" })).toBeDisabled()- await page.getByRole("button", { name: "Conversation B" }).click({ force: true })- await expect(page.getByText("Run in A", { exact: true })).toBeVisible()- await expect(page.getByText("B only message")).toHaveCount(0)-- chat.releaseTurn()- await expect(page.getByText("A final.", { exact: true })).toBeVisible()- await expect(page.getByRole("button", { name: "Conversation B" })).toBeEnabled()- await page.getByRole("button", { name: "Conversation B" }).click()- await expect(page.getByText("B only message")).toBeVisible()- await expect(page.getByText("A final.", { exact: true })).toHaveCount(0)-})---test("retries an initial conversation creation without stranding the lifecycle", async ({ page }) => {- await mockAuth(page, { admin: false, chat: true })+ {+ id: "conversation-a",+ title: "Conversation A",+ created_at: now,+ updated_at: now,+ messages: [+ { id: "a-user", role: "user", content: "A history", created_at: now },+ ],+ },+ {+ id: "conversation-b",+ title: "Conversation B",+ created_at: now,+ updated_at: now,+ messages: [+ {+ id: "b-user",+ role: "user",+ content: "B only message",+ created_at: now,+ },+ ],+ },+ ],+ turns: [{ hold: true }],+ });++ await page.goto("/agent/conversation-a");+ const transcript = page.getByRole("region", { name: "Chat" });+ await page.getByPlaceholder("Ask a question").fill("Run in A");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect(transcript.getByText("Thinking...", { exact: true })).toBeVisible();++ await page.evaluate(() => {+ const transcript = document.querySelector(".agent-chat-transcript");+ if (!transcript) throw new Error("Chat transcript was not rendered");+ const tracker: { observer: MutationObserver; sawPending: boolean } = {+ observer: undefined as unknown as MutationObserver,+ sawPending: false,+ };+ const observer = new MutationObserver((records) => {+ if (window.location.pathname !== "/agent/conversation-b") return;+ if (+ records.some((record) =>+ [...record.addedNodes].some(+ (node) =>+ node instanceof Element &&+ (node.matches(".agent-chat-thinking") ||+ node.querySelector(".agent-chat-thinking")),+ ),+ )+ )+ tracker.sawPending = true;+ });+ tracker.observer = observer;+ observer.observe(transcript, { childList: true, subtree: true });+ (window as typeof window & {+ pendingFeedbackRouteTracker?: typeof tracker;+ }).pendingFeedbackRouteTracker = tracker;+ window.history.pushState({}, "", "/agent/conversation-b");+ window.dispatchEvent(new PopStateEvent("popstate"));+ });++ await expect(page).toHaveURL(/\/agent\/conversation-b$/);+ await expect(transcript.getByText("B only message", { exact: true })).toBeVisible();+ await expect(transcript.getByText("Thinking...", { exact: true })).toHaveCount(0);+ await expect+ .poll(() =>+ page.evaluate(() => {+ const pageWindow = window as typeof window & {+ pendingFeedbackRouteTracker?: {+ observer: MutationObserver;+ sawPending: boolean;+ };+ };+ const tracker = pageWindow.pendingFeedbackRouteTracker;+ tracker?.observer.disconnect();+ return tracker?.sawPending ?? false;+ }),+ )+ .toBe(false);+ chat.releaseTurn();+});++test("pending New thread keeps the created summary without reclaiming navigation", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });const chat = await mockChatApi(page, {- conversations: [],- createError: { message: "Conversation creation failed" },+ holdCreate: true,+ conversations: [+ {+ id: "conversation-1",+ title: "Existing thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-1");+ await page.getByRole("button", { name: "New thread" }).click();+ await expect.poll(() => chat.createRequests).toBe(1);+ await page.goto("/pools");++ chat.releaseCreate();++ await expect(page).toHaveURL(/\/pools$/);+ await page.goto("/agent/conversation-1");+ await expect(page.getByRole("link", { name: "New conversation" })).toBeVisible();+});++test("uses New conversation for empty thread titles", async ({ page }) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "untitled-thread",+ title: "",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/untitled-thread");++ await expect(page.getByRole("link", { name: "New conversation" })).toBeVisible();+ await expect(+ page.getByRole("button", { name: "Actions for New conversation" }),+ ).toBeVisible();+});++test("archiving the last thread moves to archived safety if replacement creation fails", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ createError: { message: "Replacement failed" },+ conversations: [+ {+ id: "last-thread",+ title: "Last active thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/last-thread");+ await page+ .getByRole("button", { name: "Actions for Last active thread" })+ .click();+ await page.getByRole("menuitem", { name: "Archive" }).click();++ await expect+ .poll(() => chat.patchRequests)+ .toEqual([{ conversationId: "last-thread", archived: true }]);+ await expect(page).toHaveURL(/\/agent\/archived$/);+ await expect(page.getByPlaceholder("Ask a question")).toHaveCount(0);+});++test("unknown thread recovery opens the newest shared active thread", async ({+ page,+}) => {+ const now = Date.now();+ await mockAuth(page, { admin: false, chat: true });+ await mockChatApi(page, {+ conversations: [+ {+ id: "older-thread",+ title: "Older thread",+ created_at: new Date(now - 120_000).toISOString(),+ updated_at: new Date(now - 120_000).toISOString(),+ messages: [],+ },+ {+ id: "newest-thread",+ title: "Newest thread",+ created_at: new Date(now - 60_000).toISOString(),+ updated_at: new Date(now - 60_000).toISOString(),+ messages: [],+ },+ ],+ });++ await page.goto("/agent/missing-thread");+ await expect(page.getByText("conversation not found")).toBeVisible();+ await page.getByRole("button", { name: "Open newest thread" }).click();++ await expect(page).toHaveURL(/\/agent\/newest-thread$/);+});++test("archiving the final thread opens its successful replacement", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdCreate: true,+ conversations: [+ {+ id: "last-thread",+ title: "Last active thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/last-thread");+ await page+ .getByRole("button", { name: "Actions for Last active thread" })+ .click();+ await page.getByRole("menuitem", { name: "Archive" }).click();+ await expect(page).toHaveURL(/\/agent\/archived$/);+ await expect.poll(() => chat.createRequests).toBe(1);++ chat.releaseCreate();++ await expect(page).toHaveURL(/\/agent\/conversation-2$/);+ await expect(page.getByRole("link", { name: "New conversation" })).toBeVisible();+});++test("a pending create prevents a turn and opens its created thread", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdCreate: true,+ conversations: [+ {+ id: "conversation-1",+ title: "Existing thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-1");+ await page.getByRole("button", { name: "New thread" }).click();+ await expect.poll(() => chat.createRequests).toBe(1);+ await expect(page.getByPlaceholder("Ask a question")).toBeDisabled();+ await expect(page.getByRole("button", { name: "Send message" })).toBeDisabled();+ await expect.poll(() => chat.turnRequests.length).toBe(0);++ chat.releaseCreate();++ await expect(page).toHaveURL(/\/agent\/conversation-2$/);+ await expect(page.getByRole("link", { name: "New conversation" })).toBeVisible();+});++test("a pending archive prevents a turn", async ({ page }) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ holdPatch: true,+ conversations: [+ {+ id: "conversation-1",+ title: "Archive target",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ {+ id: "conversation-2",+ title: "Fallback thread",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],+ });++ await page.goto("/agent/conversation-1");+ await page.getByPlaceholder("Ask a question").fill("Do not send this");+ await page+ .getByRole("button", { name: "Actions for Archive target" })+ .click();+ await page.getByRole("menuitem", { name: "Archive" }).click();+ await expect.poll(() => chat.patchRequests.length).toBe(1);+ await expect(page.getByPlaceholder("Ask a question")).toBeDisabled();+ await expect(page.getByRole("button", { name: "Send message" })).toBeDisabled();+ await expect.poll(() => chat.turnRequests.length).toBe(0);++ chat.releasePatch();+ await expect(page).toHaveURL(/\/agent\/conversation-2$/);+});++test("Undo is disabled while generating and restores after generation", async ({+ page,+}) => {+ const now = new Date().toISOString();+ await mockAuth(page, { admin: false, chat: true });+ const chat = await mockChatApi(page, {+ conversations: [+ {+ id: "conversation-1",+ title: "Archive target",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ {+ id: "conversation-2",+ title: "Generation target",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ ],turns: [- { events: [{ type: "content_delta", delta: "Created after retry." }, assistant("Created after retry.")] },- { events: [{ type: "content_delta", delta: "Follow-up works." }, assistant("Follow-up works.")] },- ],- })-- await page.goto("/agent")- await page.getByPlaceholder("Ask a question").fill("Create this conversation")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByRole("alert")).toContainText("Conversation creation failed")- await expect(page.getByRole("button", { name: "Retry" })).toBeVisible()- await expect(page.getByPlaceholder("Ask a question")).toBeEnabled()- await expect(page.getByLabel(/^You at /).getByText("Create this conversation", { exact: true })).toHaveCount(0)- expect(chat.createRequests).toBe(1)- expect(chat.turnRequests).toHaveLength(0)-- await page.getByRole("button", { name: "Retry" }).click()- await expect(page.getByText("Created after retry.", { exact: true })).toBeVisible()- await expect(page.getByLabel(/^You at /).getByText("Create this conversation", { exact: true })).toHaveCount(1)- expect(chat.createRequests).toBe(2)- expect(chat.turnRequests).toHaveLength(1)- expect(chat.turnRequests[0].messages).toEqual([{ role: "user", content: "Create this conversation" }])-- await page.getByPlaceholder("Ask a question").fill("Normal follow-up")- await page.getByRole("button", { name: "Send message" }).click()- await expect(page.getByText("Follow-up works.", { exact: true })).toBeVisible()- expect(chat.turnRequests).toHaveLength(2)-})+ {+ hold: true,+ events: [+ {+ type: "assistant",+ message: { role: "assistant", content: "Generation complete" },+ },+ ],+ },+ ],+ });++ await page.goto("/agent/conversation-1");+ await page+ .getByRole("button", { name: "Actions for Archive target" })+ .click();+ await page.getByRole("menuitem", { name: "Archive" }).click();+ await expect(page).toHaveURL(/\/agent\/conversation-2$/);++ await page.getByPlaceholder("Ask a question").fill("Hold this turn");+ await page.getByRole("button", { name: "Send message" }).click();+ await expect.poll(() => chat.turnRequests.length).toBe(1);+ await expect(page.getByRole("button", { name: "Undo" })).toBeDisabled();++ chat.releaseTurn();+ await expect(page.getByRole("button", { name: "Undo" })).toBeEnabled();+ await page.getByRole("button", { name: "Undo" }).click();+ await expect+ .poll(() => chat.patchRequests)+ .toEqual([+ { conversationId: "conversation-1", archived: true },+ { conversationId: "conversation-1", archived: false },+ ]);+});diff --git a/libs/fleet/e2e/billing.spec.ts b/libs/fleet/e2e/billing.spec.tsindex a78cca421f..0b7d87b97d 100644--- a/libs/fleet/e2e/billing.spec.ts+++ b/libs/fleet/e2e/billing.spec.ts@@ -51,17 +51,17 @@ test("usage appears in navigation when billing is enabled", async ({await expect(page.getByRole("link", { name: "Usage", exact: true })).toBeVisible();});-test("usage shows pool costs in a two-column table", async ({ page }) => {+test("usage shows reserved resources and pool costs", async ({ page }) => {await setBillingFlag(page, true);await mockResourceUsage(page);await page.goto("/usage");await expect(page.getByRole("button", { name: "Usage history range Last 24 hours" })).toBeVisible();- await expect(page.getByText("Cost incurred", { exact: true }).first()).toBeVisible();+ await expect(page.getByText("OpenCost incurred", { exact: true }).first()).toBeVisible();const summary = page.getByLabel("Usage summary");await expect(summary.getByText("$3.64")).toBeVisible();await expect(summary.getByText("Timeframe", { exact: true })).toHaveCount(0);await expect(summary.getByText("Data status", { exact: true })).toHaveCount(0);- await expect(page.getByRole("columnheader")).toHaveCount(2);+ await expect(page.getByRole("columnheader")).toHaveCount(4);await expect(page.getByRole("cell", { name: "prod-web-fleet" })).toBeVisible();await expect(page.getByRole("cell", { name: "$2.75" })).toBeVisible();await expect(page.locator(".usage-trend")).toHaveCount(0);@@ -83,7 +83,7 @@ test("usage has a useful empty state", async ({ page }) => {);await page.goto("/usage");await expect(page.getByText("No resource usage yet")).toBeVisible();- await expect(page.getByText(/pools begin reporting resource activity/i)).toBeVisible();+ await expect(page.getByText(/pools begin reporting activity/i)).toBeVisible();});test("usage can retry a failed load", async ({ page }) => {diff --git a/libs/fleet/e2e/fixtures/mock-api.ts b/libs/fleet/e2e/fixtures/mock-api.tsindex 58916bdeb7..ff01658f38 100644--- a/libs/fleet/e2e/fixtures/mock-api.ts+++ b/libs/fleet/e2e/fixtures/mock-api.ts@@ -4,7 +4,7 @@// tests we intercept every outbound request so no real Keycloak or K8s// cluster is needed.-import type { Page } from "@playwright/test"+import type { Page } from "@playwright/test";// ---------------------------------------------------------------------------// Keycloak auth mocking@@ -39,7 +39,7 @@ const FAKE_TOKEN =aud: "cyclops-cs-spa",}),) +- ".fake-signature"+ ".fake-signature";/*** Stub Keycloak auth so the AuthProvider renders children immediately.@@ -52,22 +52,22 @@ const FAKE_TOKEN =* This avoids the real keycloak-js redirecting to the Keycloak login page.*/export interface MockFeatureFlags {- admin?: boolean- billing?: boolean- chat?: boolean- usage?: boolean+ admin?: boolean;+ billing?: boolean;+ chat?: boolean;+ usage?: boolean;}export interface MockAuthOptions {- holdConfig?: boolean- holdAuth?: boolean- initRejects?: boolean- refreshFails?: boolean+ holdConfig?: boolean;+ holdAuth?: boolean;+ initRejects?: boolean;+ refreshFails?: boolean;}export interface MockAuthControl {- releaseConfig(): void- releaseAuth(): Promise<void>+ releaseConfig(): void;+ releaseAuth(): Promise<void>;}export async function mockAuth(@@ -75,11 +75,11 @@ export async function mockAuth(flags: MockFeatureFlags = {},options: MockAuthOptions = {},): Promise<MockAuthControl> {- const config = deferred()- if (!options.holdConfig) config.resolve()- const holdAuth = options.holdAuth ?? false- const initRejects = options.initRejects ?? false- const refreshFails = options.refreshFails ?? false+ const config = deferred();+ if (!options.holdConfig) config.resolve();+ const holdAuth = options.holdAuth ?? false;+ const initRejects = options.initRejects ?? false;+ const refreshFails = options.refreshFails ?? false;// Intercept the Vite pre-bundled keycloak-js module. Vite serves// node_modules deps from /.vite/deps/ or /node_modules/.vite/deps/.// Replace the entire module with a stub Keycloak class.@@ -156,11 +156,11 @@ export async function mockAuth(export default Keycloak;export { Keycloak };`,- })- })+ });+ });- await page.route("**/api/config", async route => {- await config.promise+ await page.route("**/api/config", async (route) => {+ await config.promise;await route.fulfill({contentType: "application/json",body: JSON.stringify({@@ -169,24 +169,26 @@ export async function mockAuth(chat: flags.chat ?? false,usage: flags.usage ?? false,}),- })- })+ });+ });// Intercept any stray Keycloak endpoint requestsawait page.route("**/realms/cyclops-cs/**", (route) =>route.fulfill({ status: 200, contentType: "application/json", body: "{}" }),- )+ );return {releaseConfig: config.resolve,releaseAuth: () =>page.evaluate(() => {- const control = (window as unknown as {- __MOCK_KEYCLOAK__: { releaseAuth(): void }- }).__MOCK_KEYCLOAK__- control.releaseAuth()+ const control = (+ window as unknown as {+ __MOCK_KEYCLOAK__: { releaseAuth(): void };+ }+ ).__MOCK_KEYCLOAK__;+ control.releaseAuth();}),- }+ };}// ---------------------------------------------------------------------------@@ -197,40 +199,40 @@ export async function mockConfigApi(page: Page,config: { admin: boolean; billing?: boolean },): Promise<void> {- await page.route("**/api/config", route =>+ await page.route("**/api/config", (route) =>route.fulfill({contentType: "application/json",body: JSON.stringify({ billing: false, ...config }),}),- )+ );}// ---------------------------------------------------------------------------// Admin feature flags API mocking// ----------------------------------------------------------------------------export type MockFeatureFlagValueType = "boolean" | "number" | "string" | "json"-export type MockFeatureFlagOwnership = "terraform" | "ad_hoc" | "external"+export type MockFeatureFlagValueType = "boolean" | "number" | "string" | "json";+export type MockFeatureFlagOwnership = "terraform" | "ad_hoc" | "external";export interface MockAdminFeatureFlag {- key: string- path: string- value_type: MockFeatureFlagValueType- value: unknown- raw_value: string- ownership: MockFeatureFlagOwnership- managed_by?: string- deletable: boolean- version: number- modified_at: string- description?: string- tags: Record<string, string>+ key: string;+ path: string;+ value_type: MockFeatureFlagValueType;+ value: unknown;+ raw_value: string;+ ownership: MockFeatureFlagOwnership;+ managed_by?: string;+ deletable: boolean;+ version: number;+ modified_at: string;+ description?: string;+ tags: Record<string, string>;}export interface MockFeatureFlagRequest {- method: string- key?: string- body?: Record<string, unknown>+ method: string;+ key?: string;+ body?: Record<string, unknown>;}export const DEFAULT_ADMIN_FEATURE_FLAGS: MockAdminFeatureFlag[] = [@@ -275,85 +277,116 @@ export const DEFAULT_ADMIN_FEATURE_FLAGS: MockAdminFeatureFlag[] = [modified_at: "2026-08-11T17:45:00Z",tags: {},},-]--function rawFeatureFlagValue(value: unknown, valueType: MockFeatureFlagValueType): string {- if (valueType === "string") return String(value)- return JSON.stringify(value)+];++function rawFeatureFlagValue(+ value: unknown,+ valueType: MockFeatureFlagValueType,+): string {+ if (valueType === "string") return String(value);+ return JSON.stringify(value);}export async function mockAdminFeatureFlagsApi(page: Page,initialFlags: MockAdminFeatureFlag[] = DEFAULT_ADMIN_FEATURE_FLAGS,-): Promise<{ flags: MockAdminFeatureFlag[]; requests: MockFeatureFlagRequest[] }> {- const flags = initialFlags.map(flag => ({ ...flag, tags: { ...flag.tags } }))- const requests: MockFeatureFlagRequest[] = []-- await page.route(/\/api\/admin\/feature-flags(?:\/[^/?]+)?(?:\?.*)?$/, async route => {- const request = route.request()- const url = new URL(request.url())- const pathParts = url.pathname.split("/").filter(Boolean)- const encodedKey = pathParts.length > 3 ? pathParts.at(-1) : undefined- const key = encodedKey ? decodeURIComponent(encodedKey) : undefined- const body = request.postData() ? request.postDataJSON() as Record<string, unknown> : undefined- requests.push({ method: request.method(), key, body })-- if (request.method() === "GET" && !key) {- await route.fulfill({ contentType: "application/json", body: JSON.stringify(flags) })- return- }+): Promise<{+ flags: MockAdminFeatureFlag[];+ requests: MockFeatureFlagRequest[];+}> {+ const flags = initialFlags.map((flag) => ({+ ...flag,+ tags: { ...flag.tags },+ }));+ const requests: MockFeatureFlagRequest[] = [];- if (request.method() === "POST" && !key && body) {- const valueType = body.value_type as MockFeatureFlagValueType- const created: MockAdminFeatureFlag = {- key: String(body.key),- path: `/feature-flags/cyclops-cs/${String(body.key)}`,- value_type: valueType,- value: body.value,- raw_value: rawFeatureFlagValue(body.value, valueType),- ownership: "ad_hoc",- managed_by: "cyclops-cs",- deletable: true,- version: 1,- modified_at: "2026-08-13T12:00:00Z",- description: body.description ? String(body.description) : undefined,- tags: { ManagedBy: "cyclops-cs" },+ await page.route(+ /\/api\/admin\/feature-flags(?:\/[^/?]+)?(?:\?.*)?$/,+ async (route) => {+ const request = route.request();+ const url = new URL(request.url());+ const pathParts = url.pathname.split("/").filter(Boolean);+ const encodedKey = pathParts.length > 3 ? pathParts.at(-1) : undefined;+ const key = encodedKey ? decodeURIComponent(encodedKey) : undefined;+ const body = request.postData()+ ? (request.postDataJSON() as Record<string, unknown>)+ : undefined;+ requests.push({ method: request.method(), key, body });++ if (request.method() === "GET" && !key) {+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(flags),+ });+ return;}- flags.push(created)- await route.fulfill({ status: 201, contentType: "application/json", body: JSON.stringify(created) })- return- }- const index = flags.findIndex(flag => flag.key === key)- if (index < 0) {- await route.fulfill({ status: 404, contentType: "application/json", body: JSON.stringify({ code: "flag_not_found", message: "feature flag not found" }) })- return- }+ if (request.method() === "POST" && !key && body) {+ const valueType = body.value_type as MockFeatureFlagValueType;+ const created: MockAdminFeatureFlag = {+ key: String(body.key),+ path: `/feature-flags/cyclops-cs/${String(body.key)}`,+ value_type: valueType,+ value: body.value,+ raw_value: rawFeatureFlagValue(body.value, valueType),+ ownership: "ad_hoc",+ managed_by: "cyclops-cs",+ deletable: true,+ version: 1,+ modified_at: "2026-08-13T12:00:00Z",+ description: body.description ? String(body.description) : undefined,+ tags: { ManagedBy: "cyclops-cs" },+ };+ flags.push(created);+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify(created),+ });+ return;+ }- if (request.method() === "PUT" && body) {- const valueType = body.value_type as MockFeatureFlagValueType- flags[index] = {- ...flags[index],- value_type: valueType,- value: body.value,- raw_value: rawFeatureFlagValue(body.value, valueType),- version: flags[index].version + 1,- modified_at: "2026-08-13T12:05:00Z",+ const index = flags.findIndex((flag) => flag.key === key);+ if (index < 0) {+ await route.fulfill({+ status: 404,+ contentType: "application/json",+ body: JSON.stringify({+ code: "flag_not_found",+ message: "feature flag not found",+ }),+ });+ return;}- await route.fulfill({ contentType: "application/json", body: JSON.stringify(flags[index]) })- return- }- if (request.method() === "DELETE") {- flags.splice(index, 1)- await route.fulfill({ status: 204, body: "" })- return- }+ if (request.method() === "PUT" && body) {+ const valueType = body.value_type as MockFeatureFlagValueType;+ flags[index] = {+ ...flags[index],+ value_type: valueType,+ value: body.value,+ raw_value: rawFeatureFlagValue(body.value, valueType),+ version: flags[index].version + 1,+ modified_at: "2026-08-13T12:05:00Z",+ };+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(flags[index]),+ });+ return;+ }++ if (request.method() === "DELETE") {+ flags.splice(index, 1);+ await route.fulfill({ status: 204, body: "" });+ return;+ }- await route.continue()- })+ await route.continue();+ },+ );- return { flags, requests }+ return { flags, requests };}// ---------------------------------------------------------------------------@@ -361,10 +394,10 @@ export async function mockAdminFeatureFlagsApi(// ---------------------------------------------------------------------------export interface MockNamespace {- name: string- status: string- createdAt: string- labels: Record<string, string> | null+ name: string;+ status: string;+ createdAt: string;+ labels: Record<string, string> | null;}const DEFAULT_NAMESPACES: MockNamespace[] = [@@ -380,7 +413,7 @@ const DEFAULT_NAMESPACES: MockNamespace[] = [createdAt: "2026-02-01T12:00:00Z",labels: null,},-]+];export async function mockNamespacesApi(page: Page,@@ -392,37 +425,37 @@ export async function mockNamespacesApi(await route.fulfill({contentType: "application/json",body: JSON.stringify(namespaces),- })+ });} else if (route.request().method() === "POST") {- const body = route.request().postDataJSON()+ const body = route.request().postDataJSON();const created: MockNamespace = {name: body.name,status: "Active",createdAt: new Date().toISOString(),labels: null,- }- namespaces.push(created)+ };+ namespaces.push(created);await route.fulfill({status: 201,contentType: "application/json",body: JSON.stringify(created),- })+ });} else {- await route.continue()+ await route.continue();}- })+ });await page.route("**/api/namespaces/*", async (route) => {if (route.request().method() === "DELETE") {- const url = new URL(route.request().url())- const name = url.pathname.split("/").pop()- const idx = namespaces.findIndex((ns) => ns.name === name)- if (idx >= 0) namespaces.splice(idx, 1)- await route.fulfill({ status: 204, body: "" })+ const url = new URL(route.request().url());+ const name = url.pathname.split("/").pop();+ const idx = namespaces.findIndex((ns) => ns.name === name);+ if (idx >= 0) namespaces.splice(idx, 1);+ await route.fulfill({ status: 204, body: "" });} else {- await route.continue()+ await route.continue();}- })+ });}// ---------------------------------------------------------------------------@@ -430,10 +463,10 @@ export async function mockNamespacesApi(// ---------------------------------------------------------------------------export interface MockUserApiKey {- id: string- client_id: string- name: string- scope: string[]+ id: string;+ client_id: string;+ name: string;+ scope: string[];}const DEFAULT_USER_KEYS: MockUserApiKey[] = [@@ -443,7 +476,7 @@ const DEFAULT_USER_KEYS: MockUserApiKey[] = [name: "my-key",scope: [],},-]+];export async function mockUserKeysApi(page: Page,@@ -454,16 +487,16 @@ export async function mockUserKeysApi(await route.fulfill({contentType: "application/json",body: JSON.stringify({ keys }),- })+ });} else if (route.request().method() === "POST") {- const body = route.request().postDataJSON()+ const body = route.request().postDataJSON();const newKey: MockUserApiKey = {id: `key-${Date.now()}`,client_id: `sa-testuser-${body.name}`,name: body.name,scope: body.scope ?? [],- }- keys.push(newKey)+ };+ keys.push(newKey);await route.fulfill({status: 201,contentType: "application/json",@@ -475,23 +508,23 @@ export async function mockUserKeysApi(name: newKey.name,scope: newKey.scope,}),- })+ });} else {- await route.continue()+ await route.continue();}- })+ });await page.route("**/api/user-keys/*", async (route) => {if (route.request().method() === "DELETE") {- const url = new URL(route.request().url())- const id = url.pathname.split("/").pop()- const idx = keys.findIndex((k) => k.id === id)- if (idx >= 0) keys.splice(idx, 1)- await route.fulfill({ status: 204, body: "" })+ const url = new URL(route.request().url());+ const id = url.pathname.split("/").pop();+ const idx = keys.findIndex((k) => k.id === id);+ if (idx >= 0) keys.splice(idx, 1);+ await route.fulfill({ status: 204, body: "" });} else {- await route.continue()+ await route.continue();}- })+ });}// ---------------------------------------------------------------------------@@ -499,14 +532,14 @@ export async function mockUserKeysApi(// ---------------------------------------------------------------------------export interface MockGitHubTrustPolicy {- id: string- owner_sub: string- name: string- repository: string- allowed_namespaces: string[]- enabled: boolean- created_at: string- updated_at: string+ id: string;+ owner_sub: string;+ name: string;+ repository: string;+ allowed_namespaces: string[];+ enabled: boolean;+ created_at: string;+ updated_at: string;}const DEFAULT_GITHUB_TRUST_POLICIES: MockGitHubTrustPolicy[] = [@@ -520,7 +553,7 @@ const DEFAULT_GITHUB_TRUST_POLICIES: MockGitHubTrustPolicy[] = [created_at: "2026-06-26T10:00:00Z",updated_at: "2026-06-26T10:30:00Z",},-]+];export async function mockGitHubTrustPoliciesApi(page: Page,@@ -537,11 +570,11 @@ export async function mockGitHubTrustPoliciesApi(audience: "fleets",},}),- })- return+ });+ return;}if (route.request().method() === "POST") {- const body = route.request().postDataJSON()+ const body = route.request().postDataJSON();const created: MockGitHubTrustPolicy = {id: `gh-policy-${Date.now()}`,owner_sub: "test-user-id",@@ -551,43 +584,46 @@ export async function mockGitHubTrustPoliciesApi(enabled: body.enabled ?? true,created_at: new Date().toISOString(),updated_at: new Date().toISOString(),- }- policies.unshift(created)+ };+ policies.unshift(created);await route.fulfill({status: 201,contentType: "application/json",body: JSON.stringify(created),- })- return+ });+ return;}- await route.continue()- })+ await route.continue();+ });await page.route("**/api/github-trust-policies/*", async (route) => {- const url = new URL(route.request().url())- const id = url.pathname.split("/").pop()- const policy = policies.find(item => item.id === id)+ const url = new URL(route.request().url());+ const id = url.pathname.split("/").pop();+ const policy = policies.find((item) => item.id === id);if (route.request().method() === "PATCH") {if (!policy) {- await route.fulfill({ status: 404, body: JSON.stringify({ error: "not found" }) })- return+ await route.fulfill({+ status: 404,+ body: JSON.stringify({ error: "not found" }),+ });+ return;}- const body = route.request().postDataJSON()- Object.assign(policy, body, { updated_at: new Date().toISOString() })+ const body = route.request().postDataJSON();+ Object.assign(policy, body, { updated_at: new Date().toISOString() });await route.fulfill({contentType: "application/json",body: JSON.stringify(policy),- })- return+ });+ return;}if (route.request().method() === "DELETE") {- const idx = policies.findIndex(item => item.id === id)- if (idx >= 0) policies.splice(idx, 1)- await route.fulfill({ status: 204, body: "" })- return+ const idx = policies.findIndex((item) => item.id === id);+ if (idx >= 0) policies.splice(idx, 1);+ await route.fulfill({ status: 204, body: "" });+ return;}- await route.continue()- })+ await route.continue();+ });}// ---------------------------------------------------------------------------@@ -604,7 +640,7 @@ export async function mockPoolsApi(page: Page): Promise<void> {sandboxTemplateRef: { name: "demo-pool-template" },},status: { replicas: 2, readyReplicas: 2 },- }+ };const template = {apiVersion: "osgym.cua.ai/v1alpha1",kind: "OSGymSandboxTemplate",@@ -617,42 +653,54 @@ export async function mockPoolsApi(page: Page): Promise<void> {services: [],},},- }+ };await page.route("**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxwarmpools",async (route) => {- const namespace = route.request().url().split("/namespaces/")[1].split("/")[0]+ const namespace = route+ .request()+ .url()+ .split("/namespaces/")[1]+ .split("/")[0];if (route.request().method() === "GET") {await route.fulfill({contentType: "application/json",- body: JSON.stringify({ items: namespace === "demo-pool" ? [pool] : [] }),- })+ body: JSON.stringify({+ items: namespace === "demo-pool" ? [pool] : [],+ }),+ });} else if (route.request().method() === "POST") {- const body = route.request().postDataJSON()+ const body = route.request().postDataJSON();await route.fulfill({status: 201,contentType: "application/json",- body: JSON.stringify({ ...body, status: { replicas: body.spec.replicas } }),- })+ body: JSON.stringify({+ ...body,+ status: { replicas: body.spec.replicas },+ }),+ });} else {- await route.continue()+ await route.continue();}},- )+ );await page.route("**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/demo-pool/osgymsandboxwarmpools/demo-pool",async (route) => {if (route.request().method() === "GET") {- await route.fulfill({ contentType: "application/json", body: JSON.stringify(pool) })+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(pool),+ });} else if (route.request().method() === "DELETE") {- await route.fulfill({ status: 204, body: "" })+ await route.fulfill({ status: 204, body: "" });} else {- await route.continue()+ await route.continue();}},- )+ );await page.route("**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxtemplates",@@ -662,19 +710,22 @@ export async function mockPoolsApi(page: Page): Promise<void> {status: 201,contentType: "application/json",body: route.request().postData() ?? "{}",- })+ });} else {- await route.continue()+ await route.continue();}},- )+ );await page.route("**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/demo-pool/osgymsandboxtemplates/demo-pool-template",async (route) => {- await route.fulfill({ contentType: "application/json", body: JSON.stringify(template) })+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(template),+ });},- )+ );}// ---------------------------------------------------------------------------@@ -779,9 +830,9 @@ export async function mockClaimsApi(page: Page): Promise<void> {},],}),- })+ });} else if (route.request().method() === "POST") {- const body = route.request().postDataJSON()+ const body = route.request().postDataJSON();await route.fulfill({status: 201,contentType: "application/json",@@ -796,88 +847,101 @@ export async function mockClaimsApi(page: Page): Promise<void> {spec: body.spec,status: { phase: "Pending" },}),- })+ });} else {- await route.continue()+ await route.continue();}},- )+ );// DELETE for individual claimsawait page.route("**/api/k8s/apis/osgym.cua.ai/v1alpha1/namespaces/*/osgymsandboxclaims/*",async (route) => {if (route.request().method() === "DELETE") {- await route.fulfill({ status: 200, body: "{}" })+ await route.fulfill({ status: 200, body: "{}" });} else {- await route.continue()+ await route.continue();}},- )+ );}-// ---------------------------------------------------------------------------// Chat API mocking// ---------------------------------------------------------------------------export interface MockChatMessage {- id: string- role: "user" | "assistant" | "tool"- content: string- created_at: string- tool_call_id?: string+ id: string;+ role: "user" | "assistant" | "tool";+ content: string;+ created_at: string;+ tool_call_id?: string;tool_calls?: Array<{- id: string- type: "function"- function: { name: string; arguments: string }- }>+ id: string;+ type: "function";+ function: { name: string; arguments: string };+ }>;}export interface MockChatConversation {- id: string- title: string- created_at: string- updated_at: string- messages: MockChatMessage[]+ id: string;+ title: string;+ created_at: string;+ updated_at: string;+ archived_at?: string;+ messages: MockChatMessage[];}export interface MockChatApiOptions {- conversations?: MockChatConversation[]- holdList?: boolean- holdConversation?: boolean- turns?: MockChatTurn[]- refreshError?: { afterTurnRequests: number; message: string }- holdRefresh?: boolean- createError?: { message: string }+ conversations?: MockChatConversation[];+ holdList?: boolean;+ listError?: { message: string };+ listErrorAfterPatch?: { message: string };+ holdConversation?: boolean;+ turns?: MockChatTurn[];+ refreshError?: { afterTurnRequests: number; message: string };+ holdRefresh?: boolean;+ createError?: { message: string };+ holdPatch?: boolean;+ holdCreate?: boolean;}export interface MockChatApiControl {- authorizationHeaders: string[]- createRequests: number- turnRequests: Array<{ conversationId: string; messages: Array<Record<string, unknown>> }>- releaseList(): void- releaseConversation(): void- releaseRefresh(): void- releaseTurn(): void+ authorizationHeaders: string[];+ createRequests: number;+ listRequests: number;+ turnRequests: Array<{+ conversationId: string;+ messages: Array<Record<string, unknown>>;+ }>;+ patchRequests: Array<{ conversationId: string; archived: boolean }>;+ remainingTurns: number;+ releaseList(): void;+ releaseConversation(): void;+ releaseRefresh(): void;+ releaseTurn(): void;+ releasePatch(): void;+ releaseCreate(): void;}export interface MockChatTurn {- events?: Array<Record<string, unknown>>- error?: { status: number; message: string }- hold?: boolean+ events?: Array<Record<string, unknown>>;+ error?: { status: number; message: string };+ hold?: boolean;+ archiveBeforeError?: boolean;}function deferred(): { promise: Promise<void>; resolve: () => void } {- let resolve = () => {}- const promise = new Promise<void>(complete => {- resolve = complete- })- return { promise, resolve }+ let resolve = () => {};+ const promise = new Promise<void>((complete) => {+ resolve = complete;+ });+ return { promise, resolve };}function defaultChatConversations(): MockChatConversation[] {- const now = new Date().toISOString()+ const now = new Date().toISOString();return [{id: "conversation-1",@@ -899,151 +963,341 @@ function defaultChatConversations(): MockChatConversation[] {},],},- ]+ {+ id: "archived-conversation-1",+ title: "Archived browser task",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ];}export async function mockChatApi(page: Page,options: MockChatApiOptions = {},): Promise<MockChatApiControl> {- const conversations = options.conversations ?? defaultChatConversations()- const authorizationHeaders: string[] = []- const createRequests = { count: 0 }- const turnRequests: Array<{ conversationId: string; messages: Array<Record<string, unknown>> }> = []- const list = deferred()- const conversation = deferred()- const refresh = deferred()- const turnGate = deferred()- const turns = [...(options.turns ?? [])]- let refreshFailuresRemaining = options.refreshError ? 1 : 0- let createFailuresRemaining = options.createError ? 1 : 0-- if (!options.holdList) list.resolve()- if (!options.holdConversation) conversation.resolve()- if (!options.holdRefresh) refresh.resolve()- if (!turns.some(item => item.hold)) turnGate.resolve()-- await page.route("**/api/chat/conversations", async route => {- if (route.request().method() === "GET") {- authorizationHeaders.push(route.request().headers().authorization ?? "")- if (options.refreshError && turnRequests.length >= options.refreshError.afterTurnRequests && refreshFailuresRemaining > 0) {- refreshFailuresRemaining -= 1- await route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: options.refreshError.message }) })- return+ const conversations = options.conversations ?? defaultChatConversations();+ const authorizationHeaders: string[] = [];+ const createRequests = { count: 0 };+ const listRequests = { count: 0 };+ const turnRequests: Array<{+ conversationId: string;+ messages: Array<Record<string, unknown>>;+ }> = [];+ const patchRequests: Array<{ conversationId: string; archived: boolean }> =+ [];+ const list = deferred();+ const conversation = deferred();+ const refresh = deferred();+ const turnGate = deferred();+ const patch = deferred();+ const create = deferred();+ const turns = [...(options.turns ?? [])];+ let refreshFailuresRemaining = options.refreshError ? 1 : 0;+ let postPatchListFailuresRemaining = options.listErrorAfterPatch ? 1 : 0;+ let createFailuresRemaining = options.createError ? 1 : 0;++ if (!options.holdList) list.resolve();+ if (!options.holdConversation) conversation.resolve();+ if (!options.holdRefresh) refresh.resolve();+ if (!turns.some((item) => item.hold)) turnGate.resolve();+ if (!options.holdPatch) patch.resolve();+ if (!options.holdCreate) create.resolve();++ await page.route(+ (url) => url.pathname === "/api/chat/conversations",+ async (route) => {+ if (route.request().method() === "GET") {+ listRequests.count += 1;+ authorizationHeaders.push(+ route.request().headers().authorization ?? "",+ );+ if (options.listError) {+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: options.listError.message }),+ });+ return;+ }+ if (+ options.listErrorAfterPatch &&+ patchRequests.length > 0 &&+ postPatchListFailuresRemaining > 0+ ) {+ postPatchListFailuresRemaining -= 1;+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: options.listErrorAfterPatch.message }),+ });+ return;+ }+ if (+ options.refreshError &&+ turnRequests.length >= options.refreshError.afterTurnRequests &&+ refreshFailuresRemaining > 0+ ) {+ refreshFailuresRemaining -= 1;+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: options.refreshError.message }),+ });+ return;+ }+ const archivedValues = new URL(route.request().url()).searchParams.getAll("archived");+ let archived = false;+ if (archivedValues.length === 1 && archivedValues[0] === "true") archived = true;+ else if (archivedValues.length !== 0 && (archivedValues.length !== 1 || archivedValues[0] !== "false")) {+ await route.fulfill({+ status: 400,+ contentType: "application/json",+ body: JSON.stringify({ error: "invalid archived query value" }),+ });+ return;+ }+ const summaries = conversations+ .filter((item) => Boolean(item.archived_at) === archived)+ .map(({ messages: _messages, ...summary }) => summary);+ await list.promise;+ if (options.holdRefresh && turnRequests.length > 0)+ await refresh.promise;+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(summaries),+ });+ return;}- await list.promise- if (options.holdRefresh && turnRequests.length > 0) await refresh.promise++ if (route.request().method() === "POST") {+ createRequests.count += 1;+ await create.promise;+ if (createFailuresRemaining > 0) {+ createFailuresRemaining -= 1;+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: options.createError!.message }),+ });+ return;+ }+ const now = new Date().toISOString();+ const created: MockChatConversation = {+ id: `conversation-${conversations.length + 1}`,+ title: "",+ created_at: now,+ updated_at: now,+ messages: [],+ };+ conversations.unshift(created);+ await route.fulfill({+ status: 201,+ contentType: "application/json",+ body: JSON.stringify(created),+ });+ return;+ }++ await route.continue();+ },+ );++ await page.route("**/api/chat/conversations/*", async (route) => {+ const request = route.request();+ const url = new URL(request.url());+ const pathParts = url.pathname.split("/").filter(Boolean);+ if (+ pathParts.length !== 4 ||+ pathParts.slice(0, 3).join("/") !== "api/chat/conversations"+ ) {+ await route.fallback();+ return;+ }++ const id = pathParts[3];+ const selected = conversations.find((item) => item.id === id);+ if (!selected) {await route.fulfill({+ status: 404,contentType: "application/json",- body: JSON.stringify(- conversations.map(({ messages: _messages, ...summary }) => summary),- ),- })- return+ body: JSON.stringify({ error: "conversation not found" }),+ });+ return;}- if (route.request().method() === "POST") {- createRequests.count += 1- if (createFailuresRemaining > 0) {- createFailuresRemaining -= 1- await route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: options.createError!.message }) })- return+ if (request.method() === "PATCH") {+ let body: unknown;+ try {+ body = JSON.parse(request.postData() ?? "");+ } catch {+ await route.fulfill({+ status: 400,+ contentType: "application/json",+ body: JSON.stringify({ error: "invalid body" }),+ });+ return;}- const now = new Date().toISOString()- const created: MockChatConversation = {- id: `conversation-${conversations.length + 1}`,- title: "New conversation",- created_at: now,- updated_at: now,- messages: [],+ if (typeof body !== "object" || body === null || Array.isArray(body)) {+ await route.fulfill({+ status: 400,+ contentType: "application/json",+ body: JSON.stringify({ error: "invalid body" }),+ });+ return;}- conversations.unshift(created)+ const archiveRequest = body as Record<string, unknown>;+ const fields = Object.keys(archiveRequest);+ if (+ fields.length !== 1 ||+ fields[0] !== "archived" ||+ typeof archiveRequest.archived !== "boolean"+ ) {+ await route.fulfill({+ status: 400,+ contentType: "application/json",+ body: JSON.stringify({ error: "invalid body" }),+ });+ return;+ }+ patchRequests.push({ conversationId: id, archived: archiveRequest.archived });+ await patch.promise;+ const now = new Date().toISOString();+ selected.updated_at = now;+ if (archiveRequest.archived) selected.archived_at = now;+ else delete selected.archived_at;await route.fulfill({- status: 201,contentType: "application/json",- body: JSON.stringify(created),- })- return+ body: JSON.stringify(selected),+ });+ return;}- await route.continue()- })-- await page.route("**/api/chat/conversations/*", async route => {- if (route.request().method() !== "GET") {- await route.continue()- return+ if (request.method() !== "GET") {+ await route.fallback();+ return;}- if (options.refreshError && turnRequests.length >= options.refreshError.afterTurnRequests && refreshFailuresRemaining > 0) {- refreshFailuresRemaining -= 1- await route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: options.refreshError.message }) })- return- }- await conversation.promise- if (options.holdRefresh && turnRequests.length > 0) await refresh.promise- const id = new URL(route.request().url()).pathname.split("/").pop()- const selected = conversations.find(item => item.id === id)- if (!selected) {+ if (+ options.refreshError &&+ turnRequests.length >= options.refreshError.afterTurnRequests &&+ refreshFailuresRemaining > 0+ ) {+ refreshFailuresRemaining -= 1;await route.fulfill({- status: 404,+ status: 500,contentType: "application/json",- body: JSON.stringify({ error: "conversation not found" }),- })- return+ body: JSON.stringify({ error: options.refreshError.message }),+ });+ return;}- await route.fulfill({ contentType: "application/json", body: JSON.stringify(selected) })- })+ await conversation.promise;+ if (options.holdRefresh && turnRequests.length > 0) await refresh.promise;+ await route.fulfill({+ contentType: "application/json",+ body: JSON.stringify(selected),+ });+ });- await page.route("**/api/chat/conversations/*/turns", async route => {+ await page.route("**/api/chat/conversations/*/turns", async (route) => {if (route.request().method() !== "POST") {- await route.continue()- return+ await route.continue();+ return;}- const url = new URL(route.request().url())- const conversationId = url.pathname.split("/").slice(-2, -1)[0]- const body = route.request().postDataJSON() as { messages?: Array<Record<string, unknown>> }- turnRequests.push({ conversationId, messages: body.messages ?? [] })- const now = new Date().toISOString()- const selected = conversations.find(item => item.id === conversationId)+ const url = new URL(route.request().url());+ const conversationId = url.pathname.split("/").slice(-2, -1)[0];+ const body = route.request().postDataJSON() as {+ messages?: Array<Record<string, unknown>>;+ };+ turnRequests.push({ conversationId, messages: body.messages ?? [] });+ const now = new Date().toISOString();+ const selected = conversations.find((item) => item.id === conversationId);+ if (selected?.archived_at) {+ await route.fulfill({+ status: 409,+ contentType: "application/json",+ body: JSON.stringify({ error: "conversation is archived" }),+ });+ return;+ }if (selected) {for (const message of body.messages ?? []) {- selected.messages.push({ id: `message-${selected.messages.length + 1}`, role: message.role as MockChatMessage["role"], content: String(message.content ?? ""), created_at: now, ...(typeof message.tool_call_id === "string" ? { tool_call_id: message.tool_call_id } : {}) })+ selected.messages.push({+ id: `message-${selected.messages.length + 1}`,+ role: message.role as MockChatMessage["role"],+ content: String(message.content ?? ""),+ created_at: now,+ ...(typeof message.tool_call_id === "string"+ ? { tool_call_id: message.tool_call_id }+ : {}),+ });}- selected.updated_at = now+ selected.updated_at = now;}- const turn = turns.shift()+ const turn = turns.shift();if (!turn) {- await route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "No mock turn" }) })- return+ await route.fulfill({+ status: 500,+ contentType: "application/json",+ body: JSON.stringify({ error: "No mock turn" }),+ });+ return;}- if (turn.hold) await turnGate.promise+ if (turn.hold) await turnGate.promise;+ if (turn.archiveBeforeError && selected) selected.archived_at = now;if (turn.error) {await route.fulfill({status: turn.error.status,contentType: "application/json",body: JSON.stringify({ error: turn.error.message }),- })- return+ });+ return;}if (selected) {- const final = [...(turn.events ?? [])].reverse().find(event => event.type === "assistant")?.message as Record<string, unknown> | undefined- if (final) selected.messages.push({ id: `message-${selected.messages.length + 1}`, role: "assistant", content: String(final.content ?? ""), created_at: now, ...(Array.isArray(final.tool_calls) ? { tool_calls: final.tool_calls as MockChatMessage["tool_calls"] } : {}) })+ const final = [...(turn.events ?? [])]+ .reverse()+ .find((event) => event.type === "assistant")?.message as+ Record<string, unknown> | undefined;+ if (final)+ selected.messages.push({+ id: `message-${selected.messages.length + 1}`,+ role: "assistant",+ content: String(final.content ?? ""),+ created_at: now,+ ...(Array.isArray(final.tool_calls)+ ? { tool_calls: final.tool_calls as MockChatMessage["tool_calls"] }+ : {}),+ });}await route.fulfill({contentType: "application/x-ndjson",- body: (turn.events ?? []).map(event => JSON.stringify(event) + "\n").join(""),- })- })+ body: (turn.events ?? [])+ .map((event) => JSON.stringify(event) + "\n")+ .join(""),+ });+ });return {authorizationHeaders,- get createRequests() { return createRequests.count },+ get createRequests() {+ return createRequests.count;+ },+ get listRequests() {+ return listRequests.count;+ },+ get remainingTurns() {+ return turns.length;+ },turnRequests,+ patchRequests,releaseList: list.resolve,releaseConversation: conversation.resolve,releaseRefresh: refresh.resolve,releaseTurn: turnGate.resolve,- }+ releasePatch: patch.resolve,+ releaseCreate: create.resolve,+ };}diff --git a/libs/fleet/e2e/fixtures/shell-geometry.ts b/libs/fleet/e2e/fixtures/shell-geometry.tsindex e65e179e3c..f8cf9cff86 100644--- a/libs/fleet/e2e/fixtures/shell-geometry.ts+++ b/libs/fleet/e2e/fixtures/shell-geometry.ts@@ -6,12 +6,15 @@ export async function expectSharedPageShell(page: Page): Promise<void> {await expect(header).toBeVisible()await expect(body).toBeVisible()- const [headerBox, bodyBox] = await Promise.all([- header.boundingBox(),- body.boundingBox(),- ])- expect(headerBox).not.toBeNull()- expect(bodyBox).not.toBeNull()+ let headerBox = null+ let bodyBox = null+ await expect.poll(async () => {+ [headerBox, bodyBox] = await Promise.all([+ header.boundingBox(),+ body.boundingBox(),+ ])+ return headerBox !== null && bodyBox !== null+ }).toBe(true)expect(Math.abs(headerBox!.x - bodyBox!.x)).toBeLessThanOrEqual(1)expect(Math.abs(diff --git a/libs/fleet/e2e/mock-chat-api.spec.ts b/libs/fleet/e2e/mock-chat-api.spec.tsnew file mode 100644index 0000000000..527ddcf28d--- /dev/null+++ b/libs/fleet/e2e/mock-chat-api.spec.ts@@ -0,0 +1,142 @@+import { expect, test, type Page } from "@playwright/test";+import {+ mockChatApi,+ type MockChatConversation,+} from "./fixtures/mock-api";++async function request(+ page: Page,+ path: string,+ init: { body?: string; method?: string } = {},+): Promise<{ body: unknown; status: number }> {+ return page.evaluate(+ async ({ path, init }) => {+ const response = await fetch(path, {+ ...init,+ headers: init.body ? { "Content-Type": "application/json" } : undefined,+ });+ return { body: await response.json(), status: response.status };+ },+ { path, init },+ );+}++test("mock chat API enforces archive contract", async ({ page }) => {+ const now = "2026-08-16T20:20:00.000Z";+ const conversations: MockChatConversation[] = [+ {+ id: "active-conversation",+ title: "Active conversation",+ created_at: now,+ updated_at: now,+ messages: [],+ },+ {+ id: "archived-conversation",+ title: "Archived conversation",+ created_at: now,+ updated_at: now,+ archived_at: now,+ messages: [],+ },+ ];++ await page.route("http://mock.test/", (route) =>+ route.fulfill({ body: "<main>mock</main>" }),+ );+ const chat = await mockChatApi(page, {+ conversations,+ turns: [+ {+ events: [+ {+ type: "assistant",+ message: { role: "assistant", content: "unused" },+ },+ ],+ },+ ],+ });+ await page.goto("http://mock.test/");++ const active = await request(page, "/api/chat/conversations");+ expect(active.status).toBe(200);+ expect((active.body as Array<{ id: string }>).map((item) => item.id)).toEqual([+ "active-conversation",+ ]);++ const archived = await request(+ page,+ "/api/chat/conversations?archived=true",+ );+ expect(archived.status).toBe(200);+ expect(+ (archived.body as Array<{ id: string }>).map((item) => item.id),+ ).toEqual(["archived-conversation"]);++ for (const path of [+ "/api/chat/conversations?archived=",+ "/api/chat/conversations?archived=invalid",+ "/api/chat/conversations?archived=true&archived=true",+ "/api/chat/conversations?archived=true&archived=false",+ ]) {+ const response = await request(page, path);+ expect(response.status, `${path} is rejected`).toBe(400);+ }++ for (const body of [+ "not-json",+ "[]",+ "{}",+ '{"archived":true,"extra":false}',+ '{"archived":"true"}',+ ]) {+ const response = await request(+ page,+ "/api/chat/conversations/active-conversation",+ { method: "PATCH", body },+ );+ expect(response.status, `PATCH body ${body} is rejected`).toBe(400);+ }+ expect(chat.patchRequests).toHaveLength(0);++ const archive = await request(+ page,+ "/api/chat/conversations/active-conversation",+ { method: "PATCH", body: '{"archived":true}' },+ );+ expect(archive.status).toBe(200);+ expect((archive.body as { archived_at?: string }).archived_at).toBe(+ (archive.body as { updated_at: string }).updated_at,+ );+ expect(chat.patchRequests).toEqual([+ { conversationId: "active-conversation", archived: true },+ ]);++ const turn = await request(+ page,+ "/api/chat/conversations/active-conversation/turns",+ {+ method: "POST",+ body: '{"messages":[{"role":"user","content":"must not persist"}]}',+ },+ );+ expect(turn.status).toBe(409);+ expect(conversations[0].messages).toHaveLength(0);+ expect(conversations[0].updated_at).toBe(+ (archive.body as { updated_at: string }).updated_at,+ );+ expect(chat.remainingTurns).toBe(1);++ const restore = await request(+ page,+ "/api/chat/conversations/active-conversation",+ { method: "PATCH", body: '{"archived":false}' },+ );+ expect(restore.status).toBe(200);+ expect((restore.body as { archived_at?: string }).archived_at).toBeUndefined();+ expect(chat.patchRequests).toEqual([+ { conversationId: "active-conversation", archived: true },+ { conversationId: "active-conversation", archived: false },+ ]);+});diff --git a/libs/fleet/e2e/sdk-models.unit.ts b/libs/fleet/e2e/sdk-models.unit.tsindex effeb16161..8de6928c27 100644--- a/libs/fleet/e2e/sdk-models.unit.ts+++ b/libs/fleet/e2e/sdk-models.unit.ts@@ -1,4 +1,10 @@import { deriveWarmPoolPhase } from "../src/sdk/status.js"+import type {+ Conversation,+ ConversationSummary,+ listConversations,+ setConversationArchived,+} from "../src/sdk/chat.js"function assertEqual<T>(actual: T, expected: T, message: string): void {if (actual !== expected) {@@ -26,3 +32,41 @@ assertEqual("Ready","a fully ready pool is healthy",)++const archivedAt = "2026-08-16T20:20:00.000Z"+const archivedConversation: ConversationSummary = {+ id: "archived-conversation",+ title: "Archived conversation",+ created_at: "2026-08-15T20:20:00.000Z",+ updated_at: archivedAt,+ archived_at: archivedAt,+}++type Assert<T extends true> = T+type Equal<Actual, Expected> = (+ <Value>() => Value extends Actual ? 1 : 2+) extends (<Value>() => Value extends Expected ? 1 : 2)+ ? (<Value>() => Value extends Expected ? 1 : 2) extends (+ <Value>() => Value extends Actual ? 1 : 2+ )+ ? true+ : false+ : false+type ListConversationsParameters = Assert<+ Equal<Parameters<typeof listConversations>, [options?: { archived?: boolean }]>+>+type ListConversationsReturn = Assert<+ Equal<ReturnType<typeof listConversations>, Promise<ConversationSummary[]>>+>+type SetConversationArchivedParameters = Assert<+ Equal<Parameters<typeof setConversationArchived>, [id: string, archived: boolean]>+>+type SetConversationArchivedReturn = Assert<+ Equal<ReturnType<typeof setConversationArchived>, Promise<Conversation>>+>++assertEqual(+ archivedConversation.archived_at,+ archivedAt,+ "an archived conversation summary exposes its archive timestamp",+)diff --git a/libs/fleet/e2e/usage.performance.spec.ts b/libs/fleet/e2e/usage.performance.spec.tsindex 5c82dcd036..672ad5a2a1 100644--- a/libs/fleet/e2e/usage.performance.spec.ts+++ b/libs/fleet/e2e/usage.performance.spec.ts@@ -22,7 +22,7 @@ async function delayedJSON(route: Route, body: unknown) {test("measures Usage dashboard ready time", async ({ page }) => {const visualPreview = process.env.CYCLOPS_BROWSER_VISUAL_PREVIEW === "true"- if (!visualPreview) await mockAuth(page, { admin: false, usage: true })+ if (!visualPreview) await mockAuth(page, { admin: false, billing: true })let usageRequests = 0let browserTimings: Record<string, number> | null = nullawait page.route("**/api/usage/overview**", async (route) => {@@ -37,14 +37,14 @@ test("measures Usage dashboard ready time", async ({ page }) => {const started = performance.now()await page.goto(visualPreview ? "/usage?cua-visual-preview" : "/usage")await expect(- page.getByRole("heading", { name: "Cost by pool" }),+ page.getByRole("heading", { name: "Reserved resources by pool" }),).toBeVisible()const readyMS = performance.now() - startedawait expect.poll(() => browserTimings).not.toBeNull()console.log(`METRIC browser_ready_ms=${readyMS.toFixed(3)}`)console.log(`METRIC browser_usage_requests=${usageRequests}`)- expect(usageRequests).toBe(1)+ expect(usageRequests).toBe(2)expect(browserTimings?.initial_load_ms).toBeGreaterThanOrEqual(200)expect(browserTimings?.dashboard_ready_ms).toBeGreaterThanOrEqual(200)})diff --git a/libs/fleet/package.json b/libs/fleet/package.jsonindex e1f99e3b18..7ca9e478ff 100644--- a/libs/fleet/package.json+++ b/libs/fleet/package.json@@ -17,7 +17,7 @@"test:auth-contract": "tsx --test tests/auth-redirects.test.ts","test:design-boundary": "node --test tests/design-package-boundary.test.mjs","test:favicon": "node --test tests/favicon.test.mjs",- "test:sdk-models": "rm -rf target/sdk-model-tests && tsc e2e/sdk-models.unit.ts src/sdk/status.ts --target ES2022 --module NodeNext --moduleResolution NodeNext --outDir target/sdk-model-tests --skipLibCheck && node target/sdk-model-tests/e2e/sdk-models.unit.js",+ "test:sdk-models": "rm -rf target/sdk-model-tests && tsc -p tsconfig.sdk-models.json && node target/sdk-model-tests/e2e/sdk-models.unit.js","test:agent": "tsx --test agent.test.ts"},"dependencies": {diff --git a/libs/fleet/src/App.tsx b/libs/fleet/src/App.tsxindex eed4c3db30..506781eeb3 100644--- a/libs/fleet/src/App.tsx+++ b/libs/fleet/src/App.tsx@@ -6,261 +6,317 @@ import {Routes,useLocation,useNavigate,-} from "react-router-dom"-import AppLayout from "@cloudscape-design/components/app-layout"-import Badge from "@cloudscape-design/components/badge"-import Button from "@cloudscape-design/components/button"-import SideNavigation from "@cloudscape-design/components/side-navigation"-import TopNavigation from "@cloudscape-design/components/top-navigation"+} from "react-router-dom";+import AppLayout from "@cloudscape-design/components/app-layout";+import Badge from "@cloudscape-design/components/badge";+import Button from "@cloudscape-design/components/button";+import SideNavigation from "@cloudscape-design/components/side-navigation";+import TopNavigation from "@cloudscape-design/components/top-navigation";import Flashbar, {type FlashbarProps,-} from "@cloudscape-design/components/flashbar"-import { useCallback, useEffect, useMemo, useRef, useState } from "react"-import { PoolsList } from "./pages/PoolsList"-import { ClaimDetail } from "./pages/ClaimDetail"-import { PoolDetail } from "./pages/PoolDetail"-import { PoolNew } from "./pages/PoolNew"-import { UserApiKeys } from "./pages/UserApiKeys"-import { Settings } from "./pages/Settings"-import { AgentChat } from "./pages/AgentChat"-import { BillingUsagePage } from "./pages/BillingUsage"-import { PageShell } from "./components/PageShell"-import { FeatureFlags } from "./pages/FeatureFlags"-import { FeatureFlagProvider, useFeatureFlags } from "./components/FeatureFlagContext"-import { AdminRoute } from "./components/AdminRoute"-import { FlashContext, type FlashMsg } from "./components/FlashContext"-import { logout, userInfo } from "./auth/keycloak"-import cuaLockup from "@cua/design/assets/brand/cua-lockup-white.svg"-import designTokens from "@cua/design/tokens.json"-import { localVisualPreviewPath } from "./local-visual-preview"+} from "@cloudscape-design/components/flashbar";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import { PoolsList } from "./pages/PoolsList";+import { ClaimDetail } from "./pages/ClaimDetail";+import { PoolDetail } from "./pages/PoolDetail";+import { PoolNew } from "./pages/PoolNew";+import { UserApiKeys } from "./pages/UserApiKeys";+import { Settings } from "./pages/Settings";+import { AgentChat } from "./pages/AgentChat";+import { ArchivedThreads } from "./pages/ArchivedThreads";+import { BillingUsagePage } from "./pages/BillingUsage";+import { PageShell } from "./components/PageShell";+import { FeatureFlags } from "./pages/FeatureFlags";+import {+ FeatureFlagProvider,+ useFeatureFlags,+} from "./components/FeatureFlagContext";+import { AdminRoute } from "./components/AdminRoute";+import { FlashContext, type FlashMsg } from "./components/FlashContext";+import { logout, userInfo } from "./auth/keycloak";+import cuaLockup from "@cua/design/assets/brand/cua-lockup-white.svg";+import designTokens from "@cua/design/tokens.json";+import { localVisualPreviewPath } from "./local-visual-preview";+import { ChatThreadsProvider } from "./chat/ChatThreadsContext";+import {+ isThreadNavigationHref,+ useThreadNavigation,+} from "./components/ThreadNavigation";-const VERSION_CHECK_INTERVAL_MS = 60_000+const VERSION_CHECK_INTERVAL_MS = 60_000;function useMediaQuery(query: string): boolean {- const [matches, setMatches] = useState(() => window.matchMedia(query).matches)+ const [matches, setMatches] = useState(+ () => window.matchMedia(query).matches,+ );useEffect(() => {- const media = window.matchMedia(query)- const update = () => setMatches(media.matches)- media.addEventListener("change", update)- return () => media.removeEventListener("change", update)- }, [query])- return matches+ const media = window.matchMedia(query);+ const update = () => setMatches(media.matches);+ media.addEventListener("change", update);+ return () => media.removeEventListener("change", update);+ }, [query]);+ return matches;}function useStaleCheck(): { stale: boolean } {- const [stale, setStale] = useState(false)- const currentEntry = useRef<string | null>(null)+ const [stale, setStale] = useState(false);+ const currentEntry = useRef<string | null>(null);useEffect(() => {- if (stale) return+ if (stale) return;// The entry script is what's actually executing; lazy chunk hashes// changing don't make the running app stale on their own.const entry = Array.from(- document.querySelectorAll<HTMLScriptElement>('script[type="module"][src]'),+ document.querySelectorAll<HTMLScriptElement>(+ 'script[type="module"][src]',+ ),)- .map(s => s.src)- .find(src => src.includes('/assets/'))- if (!entry) return- currentEntry.current = entry+ .map((s) => s.src)+ .find((src) => src.includes("/assets/"));+ if (!entry) return;+ currentEntry.current = entry;const check = async () => {try {// High-signal: if the CDN no longer serves our entry chunk,// the deploy invalidated us — next dynamic import would fail anyway.- const head = await fetch(currentEntry.current!, { method: 'HEAD', cache: 'no-cache' })+ const head = await fetch(currentEntry.current!, {+ method: "HEAD",+ cache: "no-cache",+ });if (head.status === 404) {- setStale(true)- return+ setStale(true);+ return;}- const res = await fetch('/', { cache: 'no-cache' })- const html = await res.text()- const match = html.match(/<script[^>]+type="module"[^>]+src="(\/assets\/[^"']+)"/)- const latestEntry = match?.[1]+ const res = await fetch("/", { cache: "no-cache" });+ const html = await res.text();+ const match = html.match(+ /<script[^>]+type="module"[^>]+src="(\/assets\/[^"']+)"/,+ );+ const latestEntry = match?.[1];if (latestEntry && !currentEntry.current!.endsWith(latestEntry)) {- setStale(true)+ setStale(true);}} catch {// Network error — ignore}- }+ };- const id = window.setInterval(check, VERSION_CHECK_INTERVAL_MS)- return () => window.clearInterval(id)- }, [stale])+ const id = window.setInterval(check, VERSION_CHECK_INTERVAL_MS);+ return () => window.clearInterval(id);+ }, [stale]);- return { stale }+ return { stale };}function Shell() {- const location = useLocation()- const navigate = useNavigate()- const [flashes, setFlashes] = useState<FlashbarProps.MessageDefinition[]>([])- const { stale } = useStaleCheck()- const [staleDismissed, setStaleDismissed] = useState(false)+ const [flashes, setFlashes] = useState<FlashbarProps.MessageDefinition[]>([]);+ const pushFlash = useCallback((msg: FlashMsg) => {+ const id = crypto.randomUUID();+ const dismiss = () =>+ setFlashes((prev) => prev.filter((flash) => flash.id !== id));+ setFlashes((prev) => [+ ...prev,+ { ...msg, id, dismissible: true, onDismiss: dismiss },+ ]);+ if (msg.type === "success") window.setTimeout(dismiss, 5000);+ }, []);+ const flashContext = useMemo(() => ({ push: pushFlash }), [pushFlash]);++ return (+ <FlashContext.Provider value={flashContext}>+ <ChatThreadsProvider>+ <ShellLayout flashes={flashes} />+ </ChatThreadsProvider>+ </FlashContext.Provider>+ );+}++function ShellLayout({+ flashes,+}: {+ flashes: FlashbarProps.MessageDefinition[];+}) {+ const location = useLocation();+ const navigate = useNavigate();+ const [staleDismissed, setStaleDismissed] = useState(false);+ const { stale } = useStaleCheck();const [navigationOpen, setNavigationOpen] = useState(() => window.innerWidth >= designTokens.layout.breakpoint.tablet,- )+ );const tabletOrWider = useMediaQuery(`(min-width: ${designTokens.layout.breakpoint.tablet}px)`,- )+ );const mobile = useMediaQuery(`(max-width: ${designTokens.layout.breakpoint.mobile - 1}px)`,- )+ );+ const previousPath = useRef(location.pathname);+ const user = userInfo();+ const { admin, billing, chat } = useFeatureFlags();+ const threadNavigation = useThreadNavigation();++ useEffect(() => {+ setNavigationOpen(tabletOrWider);+ }, [tabletOrWider]);+useEffect(() => {- setNavigationOpen(tabletOrWider)- }, [tabletOrWider])- const user = userInfo()- const { admin, billing, chat } = useFeatureFlags()+ const titlesByHref = new Map(+ threadNavigation.threadTitles.map(({ href, title }) => [href, title]),+ );+ for (const link of document.querySelectorAll<HTMLAnchorElement>(+ ".cua-shell__nav a",+ )) {+ const title = titlesByHref.get(link.getAttribute("href") ?? "");+ if (title) link.title = title;+ }+ }, [threadNavigation.threadTitles]);+useEffect(() => {- const path = location.pathname- const pageTitle = path === "/usage"- ? "Usage"- : path === "/agent"- ? "Chat"- : path === "/user-keys"- ? "User API keys"- : path === "/settings"- ? "Settings"- : path === "/pools/new"- ? "New pool"- : path.includes("/claims/")- ? "Claim details"- : path.startsWith("/pools/")- ? "Pool details"- : "Pools"- document.title = `${pageTitle} · Cua`- }, [location.pathname])- const pushFlash = useCallback((msg: FlashMsg) => {- const id = crypto.randomUUID()- const dismiss = () =>- setFlashes(prev => prev.filter(f => f.id !== id))- setFlashes(prev => [- ...prev,- {- ...msg,- id,- dismissible: true,- onDismiss: dismiss,- },- ])- if (msg.type === "success") {- window.setTimeout(dismiss, 5000)+ const changed = previousPath.current !== location.pathname;+ if (changed && mobile && location.pathname.startsWith("/agent")) {+ setNavigationOpen(false);}- }, [])- const flashContext = useMemo(() => ({ push: pushFlash }), [pushFlash])+ previousPath.current = location.pathname;+ }, [location.pathname, mobile]);++ useEffect(() => {+ const path = location.pathname;+ const pageTitle =+ path === "/usage"+ ? "Usage"+ : path.startsWith("/agent")+ ? "Threads"+ : path === "/user-keys"+ ? "User API keys"+ : path === "/settings"+ ? "Settings"+ : path === "/pools/new"+ ? "New pool"+ : path.includes("/claims/")+ ? "Claim details"+ : path.startsWith("/pools/")+ ? "Pool details"+ : "Pools";+ document.title = `${pageTitle} · Cua`;+ }, [location.pathname]);return (- <FlashContext.Provider value={flashContext}>- <div className="cua-dashboard-theme cua-shell">- <div id="cua-shell-topnav" className="cua-shell__topnav">- <TopNavigation- identity={{- href: "#/",- logo: { src: cuaLockup, alt: "Cua" },- }}- utilities={[- {- type: "menu-dropdown",- text: user.name ?? user.email ?? "Account",- iconName: "user-profile",- items: [{ id: "signout", text: "Sign out" }],- onItemClick: e => {- if (e.detail.id === "signout") logout()- },- },- ]}- />- </div>- <AppLayout- headerSelector="#cua-shell-topnav"- ariaLabels={{- navigation: "Main navigation",- navigationClose: "Close navigation",- navigationToggle: "Open navigation",+ <div className="cua-dashboard-theme cua-shell">+ <div id="cua-shell-topnav" className="cua-shell__topnav">+ <TopNavigation+ identity={{+ href: "#/",+ logo: { src: cuaLockup, alt: "Cua" },}}- toolsHide- navigationOpen={navigationOpen}- onNavigationChange={({ detail }) => setNavigationOpen(detail.open)}- navigation={- <div className="cua-shell__nav">- <SideNavigation- header={mobile ? undefined : { href: "#/pools", text: "Cua" }}- activeHref={`#${location.pathname}`}- onFollow={e => {- if (!e.detail.external) {- e.preventDefault()- navigate(- localVisualPreviewPath(- e.detail.href.replace(/^#/, ""),- ),- )- }- }}- items={[- { type: "link", text: "Pools", href: "#/pools" },-- ...(chat- ? [{ type: "link" as const, text: "Chat", href: "#/agent" }]- : []),- ...(billing- ? [- {- type: "link" as const,- text: "Usage",- href: "#/usage",- info: <Badge color="blue">Admin</Badge>,- },- ]- : []),- { type: "link", text: "User API keys", href: "#/user-keys" },- { type: "link", text: "Settings", href: "#/settings" },- ...(admin- ? [- {- type: "link" as const,- text: "Feature flags",- href: "#/admin/feature-flags",- info: <Badge color="blue">Admin</Badge>,- },- ]- : []),- ]}- />- </div>- }- notifications={- <Flashbar+ utilities={[+ {+ type: "menu-dropdown",+ text: user.name ?? user.email ?? "Account",+ iconName: "user-profile",+ items: [{ id: "signout", text: "Sign out" }],+ onItemClick: (event) => {+ if (event.detail.id === "signout") logout();+ },+ },+ ]}+ />+ </div>+ <AppLayout+ disableBodyScroll={location.pathname.startsWith("/agent")}+ headerSelector="#cua-shell-topnav"+ ariaLabels={{+ navigation: "Main navigation",+ navigationClose: "Close navigation",+ navigationToggle: "Open navigation",+ }}+ toolsHide+ navigationOpen={navigationOpen}+ onNavigationChange={({ detail }) => setNavigationOpen(detail.open)}+ navigation={+ <div className="cua-shell__nav">+ <SideNavigation+ header={mobile ? undefined : { href: "#/pools", text: "Cua" }}+ activeHref={`#${location.pathname}`}+ onFollow={(event) => {+ if (event.detail.external) return;+ event.preventDefault();+ const path = event.detail.href.replace(/^#/, "");+ if (+ isThreadNavigationHref(event.detail.href) &&+ threadNavigation.generationLocked+ )+ return;+ if (path === "/agent/new") {+ if (threadNavigation.isCreatePending()) return;+ void threadNavigation.createThread();+ return;+ }+ if (path === "/agent/retry") return;+ navigate(localVisualPreviewPath(path));+ }}items={[- ...(stale && !staleDismissed+ { type: "link", text: "Pools", href: "#/pools" },+ ...(billing+ ? [+ {+ type: "link" as const,+ text: "Usage",+ href: "#/usage",+ info: <Badge color="blue">Admin</Badge>,+ },+ ]+ : []),+ { type: "link", text: "User API keys", href: "#/user-keys" },+ { type: "link", text: "Settings", href: "#/settings" },+ ...(admin? [{- type: "info" as const,- header: "A new version is available",- content: "Refresh to get the latest features and fixes.",- action: (- <Button onClick={() => window.location.reload()}>- Refresh now- </Button>- ),- dismissible: true,- onDismiss: () => setStaleDismissed(true),- id: "__stale__",+ type: "link" as const,+ text: "Feature flags",+ href: "#/admin/feature-flags",+ info: <Badge color="blue">Admin</Badge>,},]: []),- ...flashes,+ ...(chat+ ? [{ type: "divider" as const }, ...threadNavigation.items]+ : []),]}- stackItems/>- }- content={<Outlet />}- contentType="default"- />- </div>- </FlashContext.Provider>- )+ </div>+ }+ notifications={+ <Flashbar+ items={[+ ...(stale && !staleDismissed+ ? [+ {+ type: "info" as const,+ header: "A new version is available",+ content: "Refresh to get the latest features and fixes.",+ action: (+ <Button onClick={() => window.location.reload()}>+ Refresh now+ </Button>+ ),+ dismissible: true,+ onDismiss: () => setStaleDismissed(true),+ id: "__stale__",+ },+ ]+ : []),+ ...flashes,+ ]}+ stackItems+ />+ }+ content={<Outlet />}+ contentType="default"+ />+ </div>+ );}export function App() {@@ -281,6 +337,12 @@ export function App() {<Route path="/settings" element={<Settings />} /><Route path="/usage" element={<BillingUsageRoute />} /><Route path="/agent" element={<ChatRoute />} />+ <Route path="/agent/archived" element={<ArchivedThreadsRoute />} />+ <Route path="/agent/:threadId" element={<ChatRoute />} />+ <Route+ path="/billing"+ element={<Navigate to="/settings" replace />}+ /><Route element={<AdminRoute />}><Route path="/admin/feature-flags" element={<FeatureFlags />} /></Route>@@ -295,39 +357,53 @@ export function App() {/><Route path="/modules/:name" element={<RedirectModule />} /><Route path="*" element={<Navigate to="/pools" replace />} />- <Route path="/pools/:name" element={<Navigate to="/pools" replace />} />+ <Route+ path="/pools/:name"+ element={<Navigate to="/pools" replace />}+ /></Route></Routes></FeatureFlagProvider></BrowserRouter>- )+ );}function RedirectModule() {- const path = window.location.pathname.replace(/^\/modules/, "/pools")- return <Navigate to={path} replace />+ const path = window.location.pathname.replace(/^\/modules/, "/pools");+ return <Navigate to={path} replace />;}function ChatRoute() {- const { chat, resolved } = useFeatureFlags()+ const { chat, resolved } = useFeatureFlags();if (!resolved) {return (<PageShell eyebrow="Agent" title="Chat"><div className="agent-chat-page" /></PageShell>- )+ );}- return chat ? <AgentChat /> : <Navigate to="/pools" replace />+ return chat ? <AgentChat /> : <Navigate to="/pools" replace />;+}++function ArchivedThreadsRoute() {+ const { chat, resolved } = useFeatureFlags();+ if (!resolved)+ return (+ <PageShell eyebrow="Agent" title="Archived threads">+ <div />+ </PageShell>+ );+ return chat ? <ArchivedThreads /> : <Navigate to="/pools" replace />;}function BillingUsageRoute() {- const { billing, resolved } = useFeatureFlags()+ const { billing, resolved } = useFeatureFlags();if (!resolved) {return (<PageShell eyebrow="Billing" title="Usage"><div className="usage-layout" /></PageShell>- )+ );}- return billing ? <BillingUsagePage /> : <Navigate to="/settings" replace />+ return billing ? <BillingUsagePage /> : <Navigate to="/settings" replace />;}diff --git a/libs/fleet/src/chat/ChatThreadsContext.tsx b/libs/fleet/src/chat/ChatThreadsContext.tsxnew file mode 100644index 0000000000..d4479f76d9--- /dev/null+++ b/libs/fleet/src/chat/ChatThreadsContext.tsx@@ -0,0 +1,496 @@+import Button from "@cloudscape-design/components/button"+import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useRef,+ useState,+ type ReactNode,+} from "react"+import { useLocation, useNavigate } from "react-router-dom"+import { useFeatureFlags } from "../components/FeatureFlagContext"+import { useFlash } from "../components/FlashContext"+import { localVisualPreviewPath } from "../local-visual-preview"+import {+ createConversation,+ listConversations,+ setConversationArchived,+ type Conversation,+ type ConversationSummary,+} from "../sdk/chat"++interface ChatThreadsContextValue {+ activeThreads: ConversationSummary[]+ activeThreadsLoading: boolean+ activeThreadsError?: string+ creatingThread: boolean+ generationLocked: boolean+ threadMutationLocked: boolean+ refreshActiveThreads: () => Promise<ConversationSummary[]>+ createThread: () => Promise<Conversation | undefined>+ archiveThread: (threadId: string) => Promise<boolean>+ restoreThread: (threadId: string) => Promise<Conversation | undefined>+ recoverToActiveThread: () => Promise<void>+ setGenerationLocked: (locked: boolean) => void+ isCreatePending: () => boolean+ isThreadMutationPending: () => boolean+}++interface ProviderLifecycle {+ mounted: boolean+ enabled: boolean+ generation: number+ listSequence: number+}++const unavailable = async () => [] as ConversationSummary[]+const ChatThreadsContext = createContext<ChatThreadsContextValue>({+ activeThreads: [],+ activeThreadsLoading: false,+ creatingThread: false,+ generationLocked: false,+ threadMutationLocked: false,+ refreshActiveThreads: unavailable,+ createThread: async () => undefined,+ archiveThread: async () => false,+ restoreThread: async () => undefined,+ recoverToActiveThread: async () => undefined,+ setGenerationLocked: () => undefined,+ isCreatePending: () => false,+ isThreadMutationPending: () => false,+})++export function displayThreadTitle(title: string): string {+ return title.trim() || "New conversation"+}++function sortActiveThreads(threads: ConversationSummary[]): ConversationSummary[] {+ return [...threads].sort(+ (left, right) => Date.parse(right.updated_at) - Date.parse(left.updated_at),+ )+}++function errorMessage(error: unknown, fallback: string): string {+ return error instanceof Error ? error.message : fallback+}++function UndoThreadAction({ threadId }: { threadId: string }) {+ const { generationLocked, isThreadMutationPending, restoreThread } = useChatThreads()+ const disabled = generationLocked || isThreadMutationPending()+ return (+ <Button disabled={disabled} onClick={() => void restoreThread(threadId)}>+ Undo+ </Button>+ )+}++export function ChatThreadsProvider({ children }: { children: ReactNode }) {+ const { chat, resolved } = useFeatureFlags()+ const { push } = useFlash()+ const location = useLocation()+ const navigate = useNavigate()+ const enabled = resolved && chat+ const [activeThreads, setActiveThreads] = useState<ConversationSummary[]>([])+ const [activeThreadsLoading, setActiveThreadsLoading] = useState(true)+ const [activeThreadsLoaded, setActiveThreadsLoaded] = useState(false)+ const [activeThreadsLoadVersion, setActiveThreadsLoadVersion] = useState(0)+ const [activeThreadsError, setActiveThreadsError] = useState<string>()+ const [creatingThread, setCreatingThread] = useState(false)+ const [generationLocked, setGenerationLockedState] = useState(false)+ const [threadMutationLocked, setThreadMutationLocked] = useState(false)+ const activeThreadsRef = useRef<ConversationSummary[]>([])+ const nextThreadMutationTokenRef = useRef(0)+ const activeThreadMutationTokenRef = useRef<number>()+ const generationLockedRef = useRef(false)+ const lifecycleRef = useRef<ProviderLifecycle>({+ mounted: false,+ enabled: false,+ generation: 0,+ listSequence: 0,+ })+ const fallbackStartedForLoad = useRef<number>()+ const pathnameRef = useRef(location.pathname)+ pathnameRef.current = location.pathname++ const threadPath = useCallback((threadId: string) => (+ localVisualPreviewPath(`/agent/${encodeURIComponent(threadId)}`)+ ), [])++ const isCurrentGeneration = useCallback((generation: number) => {+ const lifecycle = lifecycleRef.current+ return lifecycle.mounted && lifecycle.enabled && lifecycle.generation === generation+ }, [])++ const setCurrentThreads = useCallback((next: ConversationSummary[] | ((current: ConversationSummary[]) => ConversationSummary[])) => {+ const resolvedThreads = typeof next === "function"+ ? next(activeThreadsRef.current)+ : next+ activeThreadsRef.current = resolvedThreads+ setActiveThreads(resolvedThreads)+ return resolvedThreads+ }, [])++ const invalidateListRequests = useCallback(() => {+ lifecycleRef.current.listSequence += 1+ setActiveThreadsLoading(false)+ }, [])++ const refreshActiveThreads = useCallback(async () => {+ const lifecycle = lifecycleRef.current+ if (!lifecycle.mounted || !lifecycle.enabled) return []+ const generation = lifecycle.generation+ const listSequence = ++lifecycle.listSequence+ setActiveThreadsLoading(true)+ setActiveThreadsLoaded(false)+ setActiveThreadsError(undefined)++ try {+ const threads = sortActiveThreads(await listConversations())+ if (!isCurrentGeneration(generation) || lifecycleRef.current.listSequence !== listSequence) return []+ setCurrentThreads(threads)+ setActiveThreadsLoaded(true)+ setActiveThreadsLoadVersion(current => current + 1)+ return threads+ } catch (error) {+ if (!isCurrentGeneration(generation) || lifecycleRef.current.listSequence !== listSequence) return []+ setActiveThreadsError(errorMessage(error, "Unable to load threads"))+ throw error+ } finally {+ if (isCurrentGeneration(generation) && lifecycleRef.current.listSequence === listSequence) {+ setActiveThreadsLoading(false)+ }+ }+ }, [isCurrentGeneration, setCurrentThreads])++ useEffect(() => {+ const lifecycle = lifecycleRef.current+ lifecycle.mounted = true+ return () => {+ lifecycle.mounted = false+ lifecycle.enabled = false+ lifecycle.generation += 1+ lifecycle.listSequence += 1+ activeThreadMutationTokenRef.current = undefined+ }+ }, [])++ useEffect(() => {+ const lifecycle = lifecycleRef.current+ lifecycle.generation += 1+ lifecycle.listSequence += 1+ lifecycle.enabled = enabled+ fallbackStartedForLoad.current = undefined++ if (!enabled) {+ activeThreadMutationTokenRef.current = undefined+ generationLockedRef.current = false+ setCreatingThread(false)+ setGenerationLockedState(false)+ setThreadMutationLocked(false)+ setCurrentThreads([])+ setActiveThreadsError(undefined)+ setActiveThreadsLoaded(false)+ setActiveThreadsLoading(false)+ return+ }++ void refreshActiveThreads().catch(() => undefined)+ }, [enabled, refreshActiveThreads, setCurrentThreads])++ const isThreadMutationPending = useCallback(() => (+ activeThreadMutationTokenRef.current !== undefined+ ), [])++ const ownsThreadMutation = useCallback((token: number) => (+ activeThreadMutationTokenRef.current === token+ ), [])++ const beginThreadMutation = useCallback((generation: number): number | undefined => {+ if (+ !isCurrentGeneration(generation) ||+ generationLockedRef.current ||+ activeThreadMutationTokenRef.current !== undefined+ )+ return undefined+ const token = ++nextThreadMutationTokenRef.current+ activeThreadMutationTokenRef.current = token+ setThreadMutationLocked(true)+ return token+ }, [isCurrentGeneration])++ const finishThreadMutation = useCallback((token: number) => {+ if (!ownsThreadMutation(token)) return+ activeThreadMutationTokenRef.current = undefined+ if (lifecycleRef.current.mounted) setThreadMutationLocked(false)+ }, [ownsThreadMutation])++ const setGenerationLocked = useCallback((locked: boolean) => {+ if (locked && isThreadMutationPending()) return+ generationLockedRef.current = locked+ if (lifecycleRef.current.mounted) setGenerationLockedState(locked)+ }, [isThreadMutationPending])++ const isCreatePending = isThreadMutationPending++ const createThreadWithMutation = useCallback(async (+ generation: number,+ mutationToken: number,+ navigationPath: string,+ ) => {+ invalidateListRequests()+ setCreatingThread(true)++ const ownsCreate = () => (+ isCurrentGeneration(generation) && ownsThreadMutation(mutationToken)+ )++ try {+ const conversation = await createConversation()+ if (!ownsCreate()) return undefined+ const summary: ConversationSummary = {+ id: conversation.id,+ title: conversation.title,+ created_at: conversation.created_at,+ updated_at: conversation.updated_at,+ ...(conversation.archived_at ? { archived_at: conversation.archived_at } : {}),+ }+ setCurrentThreads(current => sortActiveThreads([summary, ...current]))+ setActiveThreadsLoaded(true)+ if (pathnameRef.current === navigationPath) navigate(threadPath(conversation.id))+ return conversation+ } catch (error) {+ if (ownsCreate()) {+ push({+ type: "error",+ header: "Unable to create thread",+ content: errorMessage(error, "Please try again."),+ })+ }+ return undefined+ } finally {+ if (ownsCreate()) setCreatingThread(false)+ }+ }, [+ invalidateListRequests,+ isCurrentGeneration,+ navigate,+ ownsThreadMutation,+ push,+ setCurrentThreads,+ threadPath,+ ])++ const createThread = useCallback(async () => {+ const generation = lifecycleRef.current.generation+ const mutationToken = beginThreadMutation(generation)+ if (mutationToken === undefined) return undefined++ try {+ return await createThreadWithMutation(generation, mutationToken, pathnameRef.current)+ } finally {+ finishThreadMutation(mutationToken)+ }+ }, [beginThreadMutation, createThreadWithMutation, finishThreadMutation])++ useEffect(() => {+ if (!enabled || !activeThreadsLoaded || activeThreadsError || activeThreadsLoading) return+ if (location.pathname !== "/agent") return+ if (activeThreads.length > 0) {+ navigate(threadPath(activeThreads[0].id), { replace: true })+ return+ }+ if (fallbackStartedForLoad.current === activeThreadsLoadVersion) return+ fallbackStartedForLoad.current = activeThreadsLoadVersion+ void createThread()+ }, [+ activeThreads,+ activeThreadsError,+ activeThreadsLoaded,+ activeThreadsLoading,+ activeThreadsLoadVersion,+ createThread,+ enabled,+ location.pathname,+ navigate,+ threadPath,+ ])++ const restoreThread = useCallback(async (threadId: string) => {+ const generation = lifecycleRef.current.generation+ const mutationToken = beginThreadMutation(generation)+ if (mutationToken === undefined) return undefined+ invalidateListRequests()++ const ownsRestore = () => (+ isCurrentGeneration(generation) && ownsThreadMutation(mutationToken)+ )++ let conversation: Conversation+ try {+ conversation = await setConversationArchived(threadId, false)+ } catch (error) {+ if (ownsRestore()) {+ push({+ type: "error",+ header: "Unable to restore thread",+ content: errorMessage(error, "Please try again."),+ })+ }+ return undefined+ }++ try {+ if (!ownsRestore()) return undefined+ const summary: ConversationSummary = {+ id: conversation.id,+ title: conversation.title,+ created_at: conversation.created_at,+ updated_at: conversation.updated_at,+ }+ setCurrentThreads(current => sortActiveThreads([+ summary,+ ...current.filter(thread => thread.id !== threadId),+ ]))+ setActiveThreadsLoaded(true)+ await refreshActiveThreads().catch(() => undefined)+ if (!ownsRestore()) return undefined+ return conversation+ } finally {+ finishThreadMutation(mutationToken)+ }+ }, [+ beginThreadMutation,+ finishThreadMutation,+ invalidateListRequests,+ isCurrentGeneration,+ ownsThreadMutation,+ push,+ refreshActiveThreads,+ setCurrentThreads,+ ])++ const archiveThread = useCallback(async (threadId: string) => {+ const generation = lifecycleRef.current.generation+ const mutationToken = beginThreadMutation(generation)+ if (mutationToken === undefined) return false+ invalidateListRequests()++ const ownsArchive = () => (+ isCurrentGeneration(generation) && ownsThreadMutation(mutationToken)+ )++ try {+ await setConversationArchived(threadId, true)+ if (!ownsArchive()) return false+ const remaining = setCurrentThreads(current => current.filter(thread => thread.id !== threadId))+ push({+ type: "success",+ header: "Thread archived",+ action: <UndoThreadAction threadId={threadId} />,+ })++ if (pathnameRef.current !== `/agent/${encodeURIComponent(threadId)}`) return true+ if (remaining.length > 0) {+ navigate(threadPath(remaining[0].id), { replace: true })+ return true+ }+ const archivedPath = "/agent/archived"+ navigate(localVisualPreviewPath(archivedPath), { replace: true })+ await createThreadWithMutation(generation, mutationToken, archivedPath)+ return true+ } catch (error) {+ if (ownsArchive()) {+ push({+ type: "error",+ header: "Unable to archive thread",+ content: errorMessage(error, "Please try again."),+ })+ }+ return false+ } finally {+ finishThreadMutation(mutationToken)+ }+ }, [+ beginThreadMutation,+ createThreadWithMutation,+ finishThreadMutation,+ invalidateListRequests,+ isCurrentGeneration,+ navigate,+ ownsThreadMutation,+ push,+ setCurrentThreads,+ threadPath,+ ])++ const recoverToActiveThread = useCallback(async () => {+ const generation = lifecycleRef.current.generation+ if (+ !isCurrentGeneration(generation) ||+ generationLockedRef.current ||+ isThreadMutationPending()+ )+ return++ try {+ const threads = await refreshActiveThreads()+ if (+ !isCurrentGeneration(generation) ||+ generationLockedRef.current ||+ isThreadMutationPending()+ )+ return+ if (threads.length > 0) {+ navigate(threadPath(threads[0].id), { replace: true })+ return+ }+ await createThread()+ } catch {+ // The shared thread list retains and announces its load failure.+ }+ }, [createThread, isCurrentGeneration, isThreadMutationPending, navigate, refreshActiveThreads, threadPath])++ const value = useMemo<ChatThreadsContextValue>(() => ({+ activeThreads,+ activeThreadsLoading,+ activeThreadsError,+ creatingThread,+ generationLocked,+ threadMutationLocked,+ refreshActiveThreads,+ createThread,+ archiveThread,+ restoreThread,+ recoverToActiveThread,+ setGenerationLocked,+ isCreatePending,+ isThreadMutationPending,+ }), [+ activeThreads,+ activeThreadsError,+ activeThreadsLoading,+ archiveThread,+ createThread,+ creatingThread,+ generationLocked,+ threadMutationLocked,+ refreshActiveThreads,+ restoreThread,+ recoverToActiveThread,+ setGenerationLocked,+ isCreatePending,+ isThreadMutationPending,+ ])++ return (+ <ChatThreadsContext.Provider value={value}>+ {children}+ </ChatThreadsContext.Provider>+ )+}++export function useChatThreads(): ChatThreadsContextValue {+ return useContext(ChatThreadsContext)+}diff --git a/libs/fleet/src/components/PageShell.tsx b/libs/fleet/src/components/PageShell.tsxindex 47be0dc455..bc3221bfc6 100644--- a/libs/fleet/src/components/PageShell.tsx+++ b/libs/fleet/src/components/PageShell.tsx@@ -10,6 +10,7 @@ export interface PageShellProps {actions?: ReactNodesecondaryActions?: ReactNodeprimaryAction?: ReactNode+ className?: stringchildren: ReactNode}@@ -21,10 +22,12 @@ export function PageShell({actions,secondaryActions,primaryAction,+ className,children,}: PageShellProps) {return (<ContentLayout+ className={className}disableOverlapheader={<div className="cua-pagehead">diff --git a/libs/fleet/src/components/ThreadNavigation.tsx b/libs/fleet/src/components/ThreadNavigation.tsxnew file mode 100644index 0000000000..a126544d7e--- /dev/null+++ b/libs/fleet/src/components/ThreadNavigation.tsx@@ -0,0 +1,111 @@+import Button from "@cloudscape-design/components/button"+import ButtonDropdown from "@cloudscape-design/components/button-dropdown"+import type { SideNavigationProps } from "@cloudscape-design/components/side-navigation"+import { useLocation } from "react-router-dom"+import { displayThreadTitle, useChatThreads } from "../chat/ChatThreadsContext"+import { groupConversations } from "../pages/AgentChat"++export function isThreadNavigationHref(href: string): boolean {+ return href === "#/agent/new" || href.startsWith("#/agent/")+}++export function useThreadNavigation(): {+ items: SideNavigationProps.Item[]+ threadTitles: Array<{ href: string; title: string }>+ generationLocked: boolean+ createThread: () => Promise<void>+ isCreatePending: () => boolean+} {+ const location = useLocation()+ const {+ activeThreads,+ activeThreadsError,+ activeThreadsLoading,+ archiveThread,+ createThread,+ creatingThread,+ generationLocked,+ threadMutationLocked,+ isCreatePending,+ refreshActiveThreads,+ } = useChatThreads()+ const disabled = generationLocked || threadMutationLocked || isCreatePending()+ const groups = groupConversations(new Date(), activeThreads)+ const threadTitles = activeThreads.map(thread => ({+ href: `#/agent/${encodeURIComponent(thread.id)}`,+ title: displayThreadTitle(thread.title),+ }))+ const retryControl = activeThreadsError ? (+ <Button ariaLabel="Retry thread list" onClick={() => void refreshActiveThreads()} variant="inline-link">+ Retry+ </Button>+ ) : undefined++ const items: SideNavigationProps.Item[] = [+ {+ type: "section",+ text: "Threads",+ defaultExpanded: location.pathname.startsWith("/agent"),+ items: [+ {+ type: "link",+ text: activeThreadsLoading ? "Loading threads" : "New thread",+ href: "#/agent/new",+ info: (+ <Button+ ariaLabel="New thread"+ disabled={disabled}+ iconName="add-plus"+ loading={creatingThread}+ loadingText="Creating thread"+ onClick={() => void createThread()}+ variant="inline-icon"+ />+ ),+ },+ ...(activeThreadsError+ ? [{ type: "link" as const, text: "Unable to load threads", href: "#/agent/retry", info: retryControl }]+ : []),+ ...groups.map(group => ({+ type: "section" as const,+ text: group.label,+ defaultExpanded: true,+ items: group.conversations.map(thread => {+ const title = displayThreadTitle(thread.title)+ return {+ type: "link" as const,+ text: title,+ href: `#/agent/${encodeURIComponent(thread.id)}`,+ info: (+ <ButtonDropdown+ ariaLabel={`Actions for ${title}`}+ disabled={disabled}+ expandToViewport+ items={[{ id: "archive", text: "Archive" }]}+ onItemClick={({ detail }) => {+ if (detail.id === "archive") void archiveThread(thread.id)+ }}+ variant="icon"+ />+ ),+ }}),+ })),+ {+ type: "link",+ text: "Archived threads",+ href: "#/agent/archived",+ },+ ],+ },+ ]++ return {+ items,+ threadTitles,+ generationLocked,+ createThread: async () => {+ await createThread()+ },+ isCreatePending,+ }+}diff --git a/libs/fleet/src/local-visual-preview.ts b/libs/fleet/src/local-visual-preview.tsindex d7d6d4e654..cbaed5b0eb 100644--- a/libs/fleet/src/local-visual-preview.ts+++ b/libs/fleet/src/local-visual-preview.ts@@ -147,11 +147,19 @@ const localVisualPreviewConversations: Conversation[] = [updated_at: "2026-08-15T18:10:00.000Z",messages: [],},+ {+ id: "preview-archived-task",+ title: "Archived browser investigation",+ created_at: "2026-08-14T16:00:00.000Z",+ updated_at: "2026-08-14T17:00:00.000Z",+ archived_at: "2026-08-14T17:00:00.000Z",+ messages: [],+ },]-export async function listLocalVisualPreviewConversations(): Promise<- ConversationSummary[]-> {+export async function listLocalVisualPreviewConversations(+ { archived = false }: { archived?: boolean } = {},+): Promise<ConversationSummary[]> {const state = new URLSearchParams(window.location.search).get("cua-preview-state",)@@ -159,9 +167,9 @@ export async function listLocalVisualPreviewConversations(): Promise<await new Promise(resolve => window.setTimeout(resolve, 2_000))}if (state === "empty") return []- return localVisualPreviewConversations.map(({ messages: _messages, ...summary }) => ({- ...summary,- }))+ return localVisualPreviewConversations+ .filter(conversation => Boolean(conversation.archived_at) === archived)+ .map(({ messages: _messages, ...summary }) => ({ ...summary }))}export function getLocalVisualPreviewConversation(@@ -170,6 +178,20 @@ export function getLocalVisualPreviewConversation(return localVisualPreviewConversations.find(conversation => conversation.id === id)}+export function setLocalVisualPreviewConversationArchived(+ id: string,+ archived: boolean,+): Conversation | undefined {+ const conversation = getLocalVisualPreviewConversation(id)+ if (!conversation) return undefined++ const timestamp = new Date().toISOString()+ conversation.updated_at = timestamp+ if (archived) conversation.archived_at = timestamp+ else delete conversation.archived_at+ return conversation+}+export function createLocalVisualPreviewConversation(): Conversation {const timestamp = new Date().toISOString()const conversation: Conversation = {@@ -190,6 +212,11 @@ export async function streamLocalVisualPreviewTurn(): Promise<ChatMessage> {const conversation = getLocalVisualPreviewConversation(conversationId)if (!conversation) throw new Error("Preview conversation not found")+ if (conversation.archived_at) {+ const error = new Error("Conversation is archived") as Error & { status: number }+ error.status = 409+ throw error+ }const timestamp = new Date().toISOString()const content =diff --git a/libs/fleet/src/pages/AgentChat.css b/libs/fleet/src/pages/AgentChat.cssindex 161cb5bab3..8dd7001580 100644--- a/libs/fleet/src/pages/AgentChat.css+++ b/libs/fleet/src/pages/AgentChat.css@@ -1,10 +1,10 @@+.agent-chat-shell.agent-chat-shell:not(#\9) {+ min-block-size: 0;+}+.agent-chat-page {- display: grid;- gap: 24px;- grid-template-columns: minmax(230px, 300px) minmax(0, 1fr);height: calc(100dvh - var(--cua-chat-viewport-offset, 160px));margin-block-end: calc(-1 * var(--cua-layout-application-inline));- min-height: 560px;}@supports not (height: 100dvh) {@@ -13,16 +13,10 @@}}-.agent-chat-history {- border-inline-end: 1px solid var(--cua-color-line-soft);- min-width: 0;- overflow-y: auto;- padding-inline-end: 20px;-}-.agent-chat-main {display: grid;grid-template-rows: minmax(0, 1fr) auto;+ height: 100%;min-height: 0;min-width: 0;}@@ -53,7 +47,11 @@}.agent-chat-composer {- background: linear-gradient(180deg, transparent, var(--cua-dashboard-background) 28%);+ background: linear-gradient(+ 180deg,+ transparent,+ var(--cua-dashboard-background) 28%+ );bottom: 0;padding: 24px 8px 12px;position: sticky;@@ -74,6 +72,45 @@font-size: 0.75rem;}+.agent-chat-thinking {+ align-items: center;+ color: var(--cua-color-text-muted);+ display: flex;+ gap: 6px;+}++.agent-chat-thinking-dots {+ display: inline-flex;+ gap: 3px;+}++.agent-chat-thinking-dots > span {+ animation: agent-chat-thinking-dot 1.2s ease-in-out infinite;+ background: currentColor;+ border-radius: 50%;+ height: 4px;+ opacity: 0.3;+ width: 4px;+}++.agent-chat-thinking-dots > span:nth-child(2) {+ animation-delay: 0.15s;+}++.agent-chat-thinking-dots > span:nth-child(3) {+ animation-delay: 0.3s;+}++@keyframes agent-chat-thinking-dot {+ 0%,+ 100% {+ opacity: 0.3;+ }+ 50% {+ opacity: 1;+ }+}+.agent-chat-skeleton {animation: agent-chat-shimmer 1.4s ease-in-out infinite;background: linear-gradient(@@ -86,11 +123,6 @@border-radius: var(--cua-radius-control);}-.agent-chat-skeleton--conversation {- height: 48px;- width: 100%;-}-.agent-chat-skeleton--message {height: 88px;max-width: 78%;@@ -100,10 +132,6 @@margin-inline-start: auto;}-.agent-chat-mobile-history {- display: none;-}-@keyframes agent-chat-shimmer {0% {background-position: 100% 0;@@ -115,24 +143,9 @@@media (max-width: 700px) {.agent-chat-page {- display: block;min-height: 0;}- .agent-chat-main {- grid-template-rows: auto minmax(0, 1fr) auto;- height: 100%;- }-- .agent-chat-history {- display: none;- }-- .agent-chat-mobile-history {- display: block;- padding-bottom: 12px;- }-.agent-chat-transcript {padding-inline: 0;}@@ -151,38 +164,15 @@}}-.agent-chat-mobile-overlay {- align-items: stretch;- background: var(--cua-color-scrim-overlay);- display: flex;- inset: 0;- position: fixed;- z-index: 1000;-}--.agent-chat-mobile-backdrop {- background: transparent;- border: 0;- cursor: default;- inset: 0;- padding: 0;- position: absolute;-}--.agent-chat-mobile-drawer {- position: relative;- z-index: 1;- background: var(--cua-color-surface-elevated-1);- box-shadow: var(--cua-shadow-medium);- max-width: min(360px, 92vw);- min-width: min(320px, 92vw);- overflow-y: auto;-}-@media (prefers-reduced-motion: reduce) {- .agent-chat-skeleton {+ .agent-chat-skeleton,+ .agent-chat-thinking-dots > span {animation: none;}++ .agent-chat-thinking-dots > span {+ opacity: 1;+ }}.agent-chat-command {@@ -191,12 +181,6 @@padding: 8px 12px;}-.agent-chat-prompt {- flex: 1 1 auto;- min-width: 0;- width: 100%;-}-.agent-chat-markdown {line-height: 1.5;max-width: 100%;@@ -287,3 +271,13 @@text-decoration: underline;text-underline-offset: 0.15em;}++.agent-chat-prompt {+ flex: 1 1 auto;+ min-width: 0;+ width: 100%;+}++.agent-chat-prompt textarea {+ min-height: 48px;+}diff --git a/libs/fleet/src/pages/AgentChat.tsx b/libs/fleet/src/pages/AgentChat.tsxindex dd1d4756f7..2fab5e6ad2 100644--- a/libs/fleet/src/pages/AgentChat.tsx+++ b/libs/fleet/src/pages/AgentChat.tsx@@ -1,68 +1,83 @@-import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react"-import { createPortal } from "react-dom"-import Avatar from "@cloudscape-design/chat-components/avatar"-import ChatBubble from "@cloudscape-design/chat-components/chat-bubble"-import Alert from "@cloudscape-design/components/alert"-import Box from "@cloudscape-design/components/box"-import Button, { type ButtonProps } from "@cloudscape-design/components/button"-import Drawer from "@cloudscape-design/components/drawer"-import ExpandableSection from "@cloudscape-design/components/expandable-section"-import Header from "@cloudscape-design/components/header"-import List from "@cloudscape-design/components/list"-import LiveRegion from "@cloudscape-design/components/live-region"-import PromptInput from "@cloudscape-design/components/prompt-input"-import SpaceBetween from "@cloudscape-design/components/space-between"-import StatusIndicator from "@cloudscape-design/components/status-indicator"-import { MarkdownMessage } from "../components/MarkdownMessage"-import { PageShell } from "../components/PageShell"-import { createClaim, deleteClaim, getClaim, listClaims } from "../sdk/claims"-import { createPool, deletePool, getPool, listNamespaces, listPools, updatePoolServices } from "../sdk/pools"-import { createUserKey, deleteUserKey, listUserKeys } from "../sdk/userKeys"+import { useEffect, useLayoutEffect, useRef, useState } from "react";+import { useLocation, useNavigate, useParams } from "react-router-dom";+import Avatar from "@cloudscape-design/chat-components/avatar";+import ChatBubble from "@cloudscape-design/chat-components/chat-bubble";+import Alert from "@cloudscape-design/components/alert";+import Box from "@cloudscape-design/components/box";+import Button from "@cloudscape-design/components/button";+import ExpandableSection from "@cloudscape-design/components/expandable-section";+import Header from "@cloudscape-design/components/header";+import PromptInput from "@cloudscape-design/components/prompt-input";+import SpaceBetween from "@cloudscape-design/components/space-between";+import StatusIndicator from "@cloudscape-design/components/status-indicator";+import { MarkdownMessage } from "../components/MarkdownMessage";+import { PageShell } from "../components/PageShell";+import { createClaim, deleteClaim, getClaim, listClaims } from "../sdk/claims";import {- createConversation,+ createPool,+ deletePool,+ getPool,+ listNamespaces,+ listPools,+ updatePoolServices,+} from "../sdk/pools";+import { createUserKey, deleteUserKey, listUserKeys } from "../sdk/userKeys";+import {+ ChatApiError,getConversation,- listConversations,streamTurn,type ChatMessage,type ChatToolCall,type Conversation,type ConversationSummary,-} from "../sdk/chat"+} from "../sdk/chat";import {BrowserBashAgent,type BashToolResult,type ClientMessage,type NormalizedBashArguments,type ToolCall,-} from "../browser-agent"-import { createBrowserMcpCommands } from "../browser-mcp-commands"-import { createBrowserSdkCommands, type BrowserSdk } from "../browser-sdk-commands"-import "./AgentChat.css"+} from "../browser-agent";+import { createBrowserMcpCommands } from "../browser-mcp-commands";+import { useChatThreads } from "../chat/ChatThreadsContext";+import { localVisualPreviewPath } from "../local-visual-preview";+import {+ createBrowserSdkCommands,+ type BrowserSdk,+} from "../browser-sdk-commands";+import "./AgentChat.css";export interface ConversationGroup {- label: string- conversations: ConversationSummary[]+ label: string;+ conversations: ConversationSummary[];}interface CommandStep {- id: string- arguments: NormalizedBashArguments- result?: BashToolResult- running?: boolean+ id: string;+ arguments: NormalizedBashArguments;+ result?: BashToolResult;+ running?: boolean;}-type TranscriptItem = { type: "message"; message: ChatMessage } | { type: "command"; command: CommandStep }+type TranscriptItem =+ | { type: "message"; message: ChatMessage }+ | { type: "command"; command: CommandStep };-export function groupConversations(now: Date, summaries: ConversationSummary[]): ConversationGroup[] {- const startOfToday = new Date(now)- startOfToday.setHours(0, 0, 0, 0)- const groups = new Map<string, ConversationSummary[]>()+export function groupConversations(+ now: Date,+ summaries: ConversationSummary[],+): ConversationGroup[] {+ const startOfToday = new Date(now);+ startOfToday.setHours(0, 0, 0, 0);+ const groups = new Map<string, ConversationSummary[]>();for (const summary of summaries) {- const updatedAt = new Date(summary.updated_at)- const startOfDate = new Date(updatedAt)- startOfDate.setHours(0, 0, 0, 0)- const daysAgo = Math.round((startOfToday.getTime() - startOfDate.getTime()) / 86_400_000)+ const updatedAt = new Date(summary.updated_at);+ const startOfDate = new Date(updatedAt);+ startOfDate.setHours(0, 0, 0, 0);+ const daysAgo = Math.round(+ (startOfToday.getTime() - startOfDate.getTime()) / 86_400_000,+ );const label =daysAgo === 0? "Today"@@ -70,17 +85,22 @@ export function groupConversations(now: Date, summaries: ConversationSummary[]):? "Yesterday": daysAgo >= 2 && daysAgo <= 7? "Past 7 days"- : updatedAt.toLocaleDateString(undefined, { year: "numeric", month: "long", day: "numeric" })- const group = groups.get(label) ?? []- group.push(summary)- groups.set(label, group)+ : updatedAt.toLocaleDateString(undefined, {+ year: "numeric",+ month: "long",+ day: "numeric",+ });+ const group = groups.get(label) ?? [];+ group.push(summary);+ groups.set(label, group);}- return [...groups].map(([label, conversations]) => ({ label, conversations }))+ return [...groups].map(([label, conversations]) => ({+ label,+ conversations,+ }));}-const MOBILE_HISTORY_QUERY = "(max-width: 700px)"-const GENERATION_LOADING_DELAY_MS = 300const browserSdk: BrowserSdk = {listNamespaces,listPools,@@ -95,35 +115,33 @@ const browserSdk: BrowserSdk = {listUserKeys,createUserKey,deleteUserKey,-}--function useMobileHistory(): boolean {- const [mobile, setMobile] = useState(() => window.matchMedia(MOBILE_HISTORY_QUERY).matches)-- useEffect(() => {- const mediaQuery = window.matchMedia(MOBILE_HISTORY_QUERY)- const update = () => setMobile(mediaQuery.matches)- update()- mediaQuery.addEventListener("change", update)- return () => mediaQuery.removeEventListener("change", update)- }, [])-- return mobile-}+};function Skeleton({ kind }: { kind: "conversation" | "message" }) {- return <div aria-hidden="true" className={`agent-chat-skeleton agent-chat-skeleton--${kind}`} data-testid={`${kind}-skeleton`} />+ return (+ <div+ aria-hidden="true"+ className={`agent-chat-skeleton agent-chat-skeleton--${kind}`}+ data-testid={`${kind}-skeleton`}+ />+ );}function formatTime(timestamp?: string): { full: string; local: string } {- if (!timestamp) return { full: "Unknown time", local: "Unknown time" }- const date = new Date(timestamp)- return { full: date.toLocaleString(), local: date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit" }) }+ if (!timestamp) return { full: "Unknown time", local: "Unknown time" };+ const date = new Date(timestamp);+ return {+ full: date.toLocaleString(),+ local: date.toLocaleTimeString(undefined, {+ hour: "numeric",+ minute: "2-digit",+ }),+ };}function parseStoredResult(content: string): BashToolResult | undefined {try {- const value = JSON.parse(content) as Partial<BashToolResult>+ const value = JSON.parse(content) as Partial<BashToolResult>;if (typeof value.stdout !== "string" ||typeof value.stderr !== "string" ||@@ -131,488 +149,863 @@ function parseStoredResult(content: string): BashToolResult | undefined {typeof value.timed_out !== "boolean" ||typeof value.truncated !== "boolean") {- return undefined+ return undefined;}- return value as BashToolResult+ return value as BashToolResult;} catch {- return undefined+ return undefined;}}-function parseStoredCommand(toolCall: ChatToolCall, messages: ChatMessage[], index: number): CommandStep | undefined {- if (toolCall.function.name !== "bash") return undefined+function parseStoredCommand(+ toolCall: ChatToolCall,+ messages: ChatMessage[],+ index: number,+): CommandStep | undefined {+ if (toolCall.function.name !== "bash") return undefined;try {- const value = JSON.parse(toolCall.function.arguments) as NormalizedBashArguments- if (typeof value.command !== "string" || !value.command.trim()) return undefined- const toolMessage = messages.slice(index + 1).find(message => message.role === "tool" && message.tool_call_id === toolCall.id)+ const value = JSON.parse(+ toolCall.function.arguments,+ ) as NormalizedBashArguments;+ if (typeof value.command !== "string" || !value.command.trim())+ return undefined;+ const toolMessage = messages+ .slice(index + 1)+ .find(+ (message) =>+ message.role === "tool" && message.tool_call_id === toolCall.id,+ );return {id: toolCall.id,arguments: {command: value.command,- timeout_ms: typeof value.timeout_ms === "number" ? value.timeout_ms : 10_000,- max_output_chars: typeof value.max_output_chars === "number" ? value.max_output_chars : 20_000,+ timeout_ms:+ typeof value.timeout_ms === "number" ? value.timeout_ms : 10_000,+ max_output_chars:+ typeof value.max_output_chars === "number"+ ? value.max_output_chars+ : 20_000,},result: toolMessage ? parseStoredResult(toolMessage.content) : undefined,- }+ };} catch {- return undefined+ return undefined;}}function reconstructTranscript(messages: ChatMessage[]): TranscriptItem[] {return messages.flatMap((message, index) => {- if (message.role === "tool") return []- const items: TranscriptItem[] = []- if (!(message.role === "assistant" && message.tool_calls?.length && !message.content.trim())) {- items.push({ type: "message", message })+ if (message.role === "tool") return [];+ const items: TranscriptItem[] = [];+ if (!(+ message.role === "assistant" &&+ message.tool_calls?.length &&+ !message.content.trim()+ )) {+ items.push({ type: "message", message });}if (message.role === "assistant") {for (const toolCall of message.tool_calls ?? []) {- const command = parseStoredCommand(toolCall, messages, index)- if (command) items.push({ type: "command", command })+ const command = parseStoredCommand(toolCall, messages, index);+ if (command) items.push({ type: "command", command });}}- return items- })+ return items;+ });}-function ConversationHistory({ conversations, loading, onSelect, disabled = false, showHeading = true }: { conversations: ConversationSummary[]; loading: boolean; onSelect: (id: string) => void; disabled?: boolean; showHeading?: boolean }) {- const groups = useMemo(() => groupConversations(new Date(), conversations), [conversations])+function MessageBubble({+ message,+ position,+ loading = false,+}: {+ message: ChatMessage;+ position: number;+ loading?: boolean;+}) {+ const incoming = message.role !== "user";+ const author = incoming ? "Assistant" : "You";+ const time = formatTime(message.created_at);return (- <SpaceBetween size="m">- {showHeading && <Header variant="h2" counter={loading ? undefined : `(${conversations.length})`}>Conversations</Header>}- {loading ? <SpaceBetween size="s"><Skeleton kind="conversation" /><Skeleton kind="conversation" /><Skeleton kind="conversation" /></SpaceBetween> : groups.length === 0 ? <Box color="text-body-secondary">No conversations yet.</Box> : (- <SpaceBetween size="l">- {groups.map(group => (- <section aria-label={group.label} key={group.label}>- <Box fontWeight="bold" padding={{ bottom: "xs" }}>{group.label}</Box>- <List ariaLabel={`${group.label} conversations`} items={group.conversations} renderItem={conversation => {- const timestamp = formatTime(conversation.updated_at)- return {- id: conversation.id,- content: <Button disabled={disabled} disabledReason="Wait for the current turn to finish." onClick={() => onSelect(conversation.id)} variant="inline-link">{conversation.title || "Untitled conversation"}</Button>,- secondaryContent: <span className="agent-chat-timestamp" title={new Date(conversation.updated_at).toLocaleString()}>{timestamp.local}</span>,- }- }} />- </section>- ))}- </SpaceBetween>- )}- </SpaceBetween>- )-}--function MessageBubble({ message, position, loading = false }: { message: ChatMessage; position: number; loading?: boolean }) {- const incoming = message.role !== "user"- const author = incoming ? "Assistant" : "You"- const time = formatTime(message.created_at)- return (- <ChatBubble ariaLabel={`${author} at ${time.full}, message ${position}`} avatar={incoming ? <Avatar ariaLabel="Assistant avatar" color="gen-ai" iconName="gen-ai" loading={loading} /> : <Avatar ariaLabel="Your avatar" initials="Y" />} type={incoming ? "incoming" : "outgoing"}>+ <ChatBubble+ ariaLabel={`${author} at ${time.full}, message ${position}`}+ avatar={+ incoming ? (+ <Avatar+ ariaLabel="Assistant avatar"+ color="gen-ai"+ iconName="gen-ai"+ loading={loading}+ />+ ) : (+ <Avatar ariaLabel="Your avatar" initials="Y" />+ )+ }+ type={incoming ? "incoming" : "outgoing"}+ ><SpaceBetween size="xxs">- {loading && !message.content ? <div>Generating a response</div> : <MarkdownMessage content={message.content} />}- {!loading && <span className="agent-chat-timestamp" title={time.full}>{author} - {time.local}</span>}+ {loading && !message.content ? (+ <div aria-hidden="true" className="agent-chat-thinking">+ <span>Thinking...</span>+ <span className="agent-chat-thinking-dots">+ <span />+ <span />+ <span />+ </span>+ </div>+ ) : (+ <MarkdownMessage content={message.content} />+ )}+ {!loading && (+ <span className="agent-chat-timestamp" title={time.full}>+ {author} - {time.local}+ </span>+ )}</SpaceBetween></ChatBubble>- )+ );}function CommandStatus({ command }: { command: CommandStep }) {- const { result } = command- const running = command.running ?? !result- const statusText = running ? "Running command" : result?.timed_out ? "Command timed out" : result?.exit_code === 0 ? "Command completed" : "Command failed"- const statusType = running ? "in-progress" : result?.timed_out ? "warning" : result?.exit_code === 0 ? "success" : "error"+ const { result } = command;+ const running = command.running ?? !result;+ const statusText = running+ ? "Running command"+ : result?.timed_out+ ? "Command timed out"+ : result?.exit_code === 0+ ? "Command completed"+ : "Command failed";+ const statusType = running+ ? "in-progress"+ : result?.timed_out+ ? "warning"+ : result?.exit_code === 0+ ? "success"+ : "error";return (<div className="agent-chat-command"><StatusIndicator type={statusType}>{statusText}</StatusIndicator>- <ExpandableSection headerAriaLabel="Command details" headerText="Command details" variant="inline">+ <ExpandableSection+ headerAriaLabel="Command details"+ headerText="Command details"+ variant="inline"+ ><SpaceBetween size="xs"><Box variant="code">{command.arguments.command}</Box>- {result && <>- {result.stdout && <Box variant="code">{result.stdout}</Box>}- {result.stderr && <Box variant="code">{result.stderr}</Box>}- {result.truncated && <Box color="text-status-warning">Output was truncated</Box>}- </>}+ {result && (+ <>+ {result.stdout && <Box variant="code">{result.stdout}</Box>}+ {result.stderr && <Box variant="code">{result.stderr}</Box>}+ {result.truncated && (+ <Box color="text-status-warning">Output was truncated</Box>+ )}+ </>+ )}</SpaceBetween></ExpandableSection></div>- )+ );}function isAbort(error: unknown): boolean {- return error instanceof DOMException && error.name === "AbortError"+ return error instanceof DOMException && error.name === "AbortError";}export function AgentChat() {- const [conversations, setConversations] = useState<ConversationSummary[]>([])- const [listLoading, setListLoading] = useState(true)- const [selectedId, setSelectedId] = useState<string>()- const [selectedConversation, setSelectedConversation] = useState<Conversation>()- const [conversationLoading, setConversationLoading] = useState(false)- const [historyOpen, setHistoryOpen] = useState(false)- const [draft, setDraft] = useState("")- const [liveItems, setLiveItems] = useState<TranscriptItem[]>([])- const [liveAssistant, setLiveAssistant] = useState<ChatMessage>()- const [assistantLoading, setAssistantLoading] = useState(false)- const [running, setRunning] = useState(false)- const [abortable, setAbortable] = useState(false)- const [turnError, setTurnError] = useState<string>()- const [refreshError, setRefreshError] = useState<string>()- const [initialCreatePrompt, setInitialCreatePrompt] = useState<string>()- const mobileHistory = useMobileHistory()- const pageRef = useRef<HTMLDivElement>(null)- const triggerRef = useRef<ButtonProps.Ref>(null)- const closeButtonRef = useRef<ButtonProps.Ref>(null)- const dialogRef = useRef<HTMLDivElement>(null)- const transcriptRef = useRef<HTMLElement>(null)- const wasHistoryOpenRef = useRef(false)- const agentRef = useRef<BrowserBashAgent>()- const abortControllerRef = useRef<AbortController>()- const loadingTimerRef = useRef<number>()- const ignoreNextConversationLoadRef = useRef(false)- const nextRunIdRef = useRef(0)- const activeRunIdRef = useRef<number>()- const activeRunConversationIdRef = useRef<string>()- const selectedConversationIdRef = useRef<string>()- const loadingRunIdRef = useRef<number>()+ const { threadId } = useParams<{ threadId: string }>();+ const location = useLocation();+ const navigate = useNavigate();+ const {+ generationLocked,+ isThreadMutationPending,+ recoverToActiveThread,+ refreshActiveThreads,+ restoreThread,+ setGenerationLocked,+ threadMutationLocked,+ } = useChatThreads();+ const [conversation, setConversation] = useState<Conversation>();+ const [conversationLoading, setConversationLoading] = useState(+ Boolean(threadId),+ );+ const [conversationError, setConversationError] = useState<string>();+ const [conversationErrorStatus, setConversationErrorStatus] = useState<number>();+ const [draft, setDraft] = useState("");+ const [liveItems, setLiveItems] = useState<TranscriptItem[]>([]);+ const [liveAssistant, setLiveAssistant] = useState<ChatMessage>();+ const [assistantLoading, setAssistantLoading] = useState(false);+ const [running, setRunning] = useState(false);+ const [abortable, setAbortable] = useState(false);+ const [turnError, setTurnError] = useState<string>();+ const [refreshError, setRefreshError] = useState<string>();+ const [latestAnnouncement, setLatestAnnouncement] = useState("");+ const [restorePending, setRestorePending] = useState(false);+ const [archivedTurnNotice, setArchivedTurnNotice] = useState<string>();+ const pageRef = useRef<HTMLDivElement>(null);+ const transcriptRef = useRef<HTMLElement>(null);+ const agentRef = useRef<BrowserBashAgent>();+ const abortControllerRef = useRef<AbortController>();+ const loadSequenceRef = useRef(0);+ const nextRunIdRef = useRef(0);+ const activeRunIdRef = useRef<number>();+ const activeRunConversationIdRef = useRef<string>();+ const currentThreadIdRef = useRef<string>();+ const restoreTokenRef = useRef(0);+ const routePath = location.pathname;+ const pathnameRef = useRef(routePath);+ pathnameRef.current = routePath;useLayoutEffect(() => {- const element = pageRef.current- if (!element) return+ const element = pageRef.current;+ if (!element) return;const measure = () => {- const box = element.getBoundingClientRect()- const top = Math.max(0, Math.round(box.top))+ const box = element.getBoundingClientRect();+ const top = Math.max(0, Math.round(box.top));element.style.setProperty("--cua-chat-viewport-offset",- `${top + 16}px`,- )- }- measure()- const observer = new ResizeObserver(measure)- observer.observe(document.documentElement)- window.addEventListener("resize", measure)+ `${String(top + 16)}px`,+ );+ };+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(document.documentElement);+ window.addEventListener("resize", measure);return () => {- observer.disconnect()- window.removeEventListener("resize", measure)- }- }, [])+ observer.disconnect();+ window.removeEventListener("resize", measure);+ };+ }, []);if (!agentRef.current) {- agentRef.current = new BrowserBashAgent(async (conversationID, messages, signal, onDelta) => {- const message = await streamTurn(conversationID, messages, onDelta ?? (() => undefined), signal)- return {- role: "assistant",- content: message.content,- tool_calls: (message.tool_calls ?? []).filter((toolCall): toolCall is ToolCall => toolCall.type === "function"),- }- }, [...createBrowserSdkCommands(browserSdk), ...createBrowserMcpCommands()])+ agentRef.current = new BrowserBashAgent(+ async (conversationID, messages, signal, onDelta) => {+ const message = await streamTurn(+ conversationID,+ messages,+ onDelta ?? (() => undefined),+ signal,+ );+ return {+ role: "assistant",+ content: message.content,+ tool_calls: (message.tool_calls ?? []).filter(+ (toolCall): toolCall is ToolCall => toolCall.type === "function",+ ),+ };+ },+ [...createBrowserSdkCommands(browserSdk), ...createBrowserMcpCommands()],+ );}const ownsRun = (runId: number, conversationID: string) =>activeRunIdRef.current === runId &&activeRunConversationIdRef.current === conversationID &&- selectedConversationIdRef.current === conversationID+ currentThreadIdRef.current === conversationID;- const ownsUnboundRun = (runId: number) =>- activeRunIdRef.current === runId && activeRunConversationIdRef.current === undefined-- const ownsLifecycle = (runId: number, conversationID?: string) =>- conversationID === undefined ? ownsUnboundRun(runId) : ownsRun(runId, conversationID)+ const clearLoading = (runId?: number, conversationID?: string) => {+ if (+ runId !== undefined &&+ conversationID !== undefined &&+ !ownsRun(runId, conversationID)+ )+ return;+ setAssistantLoading(false);+ };++ const finishRun = (runId: number, conversationID: string) => {+ if (!ownsRun(runId, conversationID)) return;+ clearLoading(runId, conversationID);+ abortControllerRef.current = undefined;+ activeRunIdRef.current = undefined;+ activeRunConversationIdRef.current = undefined;+ setAbortable(false);+ setRunning(false);+ setGenerationLocked(false);+ window.setTimeout(() =>+ pageRef.current?.querySelector<HTMLTextAreaElement>("textarea")?.focus(),+ );+ };const refresh = async (conversationID: string, runId?: number) => {- const [conversation, summaries] = await Promise.all([getConversation(conversationID), listConversations()])- if (runId !== undefined && !ownsRun(runId, conversationID)) return false- setSelectedConversation(conversation)- setConversations(summaries)- setLiveItems([])- setLiveAssistant(undefined)- setRefreshError(undefined)- return true- }-- const recoverRefresh = async (conversationID: string) => {- if (activeRunIdRef.current !== undefined || selectedConversationIdRef.current !== conversationID) return- const runId = ++nextRunIdRef.current- activeRunIdRef.current = runId- activeRunConversationIdRef.current = conversationID- setRunning(true)- setRefreshError(undefined)- try {- await refresh(conversationID, runId)- } catch (error) {- if (ownsRun(runId, conversationID)) setRefreshError(error instanceof Error ? error.message : "Unable to refresh conversation")- } finally {- finishRun(runId, conversationID)- }- }-- useEffect(() => {- let active = true- void listConversations().then(items => { if (active) setConversations(items) }).catch(() => { if (active) setConversations([]) }).finally(() => { if (active) setListLoading(false) })- return () => { active = false }- }, [])+ const refreshed = await getConversation(conversationID);+ if (runId !== undefined && !ownsRun(runId, conversationID)) return false;+ if (runId === undefined && currentThreadIdRef.current !== conversationID)+ return false;+ setConversation(refreshed);+ setLiveItems([]);+ setLiveAssistant(undefined);+ setRefreshError(undefined);+ await refreshActiveThreads();+ return true;+ };useEffect(() => {- selectedConversationIdRef.current = selectedId- }, [selectedId])-- useEffect(() => {- if (!selectedId) { setSelectedConversation(undefined); return }- let active = true- if (ignoreNextConversationLoadRef.current) {- ignoreNextConversationLoadRef.current = false- return- }- setConversationLoading(true)- setSelectedConversation(undefined)- setLiveItems([])- setLiveAssistant(undefined)- void getConversation(selectedId).then(conversation => { if (active && selectedConversationIdRef.current === selectedId) setSelectedConversation(conversation) }).catch(() => { if (active && selectedConversationIdRef.current === selectedId) setSelectedConversation(undefined) }).finally(() => { if (active && selectedConversationIdRef.current === selectedId) setConversationLoading(false) })- return () => { active = false }- }, [selectedId])-- useEffect(() => () => {- abortControllerRef.current?.abort()- if (loadingTimerRef.current) window.clearTimeout(loadingTimerRef.current)- }, [])-- useEffect(() => {- const appRoot = document.getElementById("root")- if (appRoot) appRoot.inert = historyOpen- if (historyOpen) {- wasHistoryOpenRef.current = true- closeButtonRef.current?.focus()- return () => { if (appRoot) appRoot.inert = false }- }- if (wasHistoryOpenRef.current) { wasHistoryOpenRef.current = false; triggerRef.current?.focus() }- }, [historyOpen])+ if (pathnameRef.current !== routePath) return;++ const invalidateRouteRun = () => {+ abortControllerRef.current?.abort();+ abortControllerRef.current = undefined;+ activeRunIdRef.current = undefined;+ activeRunConversationIdRef.current = undefined;+ setAssistantLoading(false);+ setAbortable(false);+ setRunning(false);+ setGenerationLocked(false);+ };++ restoreTokenRef.current += 1;+ setRestorePending(false);+ setArchivedTurnNotice(undefined);+ currentThreadIdRef.current = threadId;+ const loadSequence = ++loadSequenceRef.current;+ if (+ activeRunConversationIdRef.current &&+ activeRunConversationIdRef.current !== threadId+ )+ invalidateRouteRun();+ setConversation(undefined);+ setLiveItems([]);+ setLiveAssistant(undefined);+ setConversationError(undefined);+ setConversationErrorStatus(undefined);+ setTurnError(undefined);+ setRefreshError(undefined);+ setConversationLoading(Boolean(threadId));++ if (!threadId)+ return () => {+ loadSequenceRef.current += 1;+ };++ void getConversation(threadId)+ .then((loaded) => {+ if (+ loadSequenceRef.current !== loadSequence ||+ currentThreadIdRef.current !== threadId+ )+ return;+ setConversation(loaded);+ })+ .catch((error) => {+ if (+ loadSequenceRef.current !== loadSequence ||+ currentThreadIdRef.current !== threadId+ )+ return;+ setConversationError(+ error instanceof Error+ ? error.message+ : "Unable to load conversation",+ );+ setConversationErrorStatus(+ error instanceof ChatApiError ? error.status : undefined,+ );+ })+ .finally(() => {+ if (+ loadSequenceRef.current === loadSequence &&+ currentThreadIdRef.current === threadId+ )+ setConversationLoading(false);+ });- useEffect(() => { if (!mobileHistory) setHistoryOpen(false) }, [mobileHistory])+ return () => {+ loadSequenceRef.current += 1;+ if (activeRunConversationIdRef.current === threadId) invalidateRouteRun();+ };+ }, [routePath, threadId, setGenerationLocked]);++ useEffect(+ () => () => {+ currentThreadIdRef.current = undefined;+ abortControllerRef.current?.abort();+ abortControllerRef.current = undefined;+ activeRunIdRef.current = undefined;+ activeRunConversationIdRef.current = undefined;+ setAssistantLoading(false);+ setGenerationLocked(false);+ },+ [setGenerationLocked],+ );useEffect(() => {- const transcriptElement = transcriptRef.current- const hasTranscriptUpdate = assistantLoading || Boolean(liveAssistant?.content) || liveItems.length > 0 || Boolean(selectedConversation)- if (!transcriptElement || conversationLoading || !hasTranscriptUpdate) return- transcriptElement.scrollTop = transcriptElement.scrollHeight- }, [assistantLoading, conversationLoading, liveAssistant?.content, liveItems.length, selectedConversation])-- const clearLoading = (runId?: number, conversationID?: string) => {- if (runId !== undefined && !ownsLifecycle(runId, conversationID)) return- if (loadingTimerRef.current) window.clearTimeout(loadingTimerRef.current)- loadingTimerRef.current = undefined- loadingRunIdRef.current = undefined- setAssistantLoading(false)- }-- const finishAbortable = (runId: number, conversationID: string, controller: AbortController) => {- if (!ownsRun(runId, conversationID)) return- if (abortControllerRef.current === controller) abortControllerRef.current = undefined- setAbortable(false)- }-- const finishRun = (runId: number, conversationID?: string) => {- if (!ownsLifecycle(runId, conversationID)) return- clearLoading(runId, conversationID)- abortControllerRef.current = undefined- activeRunIdRef.current = undefined- activeRunConversationIdRef.current = undefined- setAbortable(false)- setRunning(false)- }-- const runAgent = async (runId: number, conversationID: string, messages: ClientMessage[]) => {- const controller = new AbortController()- let completedCommand = false- abortControllerRef.current = controller- setAbortable(true)+ const transcriptElement = transcriptRef.current;+ const hasTranscriptUpdate =+ assistantLoading ||+ Boolean(liveAssistant?.content) ||+ liveItems.length > 0 ||+ Boolean(conversation);+ if (!transcriptElement || conversationLoading || !hasTranscriptUpdate)+ return;+ transcriptElement.scrollTop = transcriptElement.scrollHeight;+ }, [+ assistantLoading,+ conversation,+ conversationLoading,+ liveAssistant?.content,+ liveItems.length,+ ]);++ const runAgent = async (+ runId: number,+ conversationID: string,+ messages: ClientMessage[],+ ) => {+ const controller = new AbortController();+ let completedCommand = false;+ abortControllerRef.current = controller;+ setAbortable(true);try {- await agentRef.current!.run(conversationID, messages, event => {- if (!ownsRun(runId, conversationID)) return- if (event.type === "generation_start") {- clearLoading(runId, conversationID)- loadingRunIdRef.current = runId- loadingTimerRef.current = window.setTimeout(() => {- if (ownsRun(runId, conversationID) && loadingRunIdRef.current === runId) setAssistantLoading(true)- }, GENERATION_LOADING_DELAY_MS)- } else if (event.type === "assistant_delta") {- clearLoading(runId, conversationID)- setLiveAssistant(current => ({ role: "assistant", content: `${current?.content ?? ""}${event.delta}`, created_at: new Date().toISOString() }))- } else if (event.type === "tool_start") {- clearLoading(runId, conversationID)- setLiveItems(current => [...current, { type: "command", command: { id: event.toolCall.id, arguments: event.arguments, running: true } }])- } else if (event.type === "tool_result") {- setLiveItems(current => current.map(item => item.type === "command" && item.command.id === event.toolCall.id ? { type: "command", command: { ...item.command, result: event.result, running: true } } : item))- completedCommand = true- window.setTimeout(() => {- if (!ownsRun(runId, conversationID)) return- setLiveItems(current => current.map(item => item.type === "command" && item.command.id === event.toolCall.id ? { type: "command", command: { ...item.command, running: false } } : item))- }, 350)- } else if (event.type === "complete") {- clearLoading(runId, conversationID)- setLiveAssistant(current => ({ role: "assistant", content: current?.content || event.message.content, created_at: new Date().toISOString() }))- }- }, controller.signal)+ await agentRef.current!.run(+ conversationID,+ messages,+ (event) => {+ if (!ownsRun(runId, conversationID)) return;+ if (event.type === "assistant_delta") {+ clearLoading(runId, conversationID);+ setLiveAssistant((current) => ({+ role: "assistant",+ content: (current?.content ?? "") + event.delta,+ created_at: new Date().toISOString(),+ }));+ } else if (event.type === "tool_start") {+ clearLoading(runId, conversationID);+ setLiveItems((current) => [+ ...current,+ {+ type: "command",+ command: {+ id: event.toolCall.id,+ arguments: event.arguments,+ running: true,+ },+ },+ ]);+ } else if (event.type === "tool_result") {+ setLiveItems((current) =>+ current.map((item) =>+ item.type === "command" && item.command.id === event.toolCall.id+ ? {+ type: "command",+ command: {+ ...item.command,+ result: event.result,+ running: true,+ },+ }+ : item,+ ),+ );+ completedCommand = true;+ window.setTimeout(() => {+ if (!ownsRun(runId, conversationID)) return;+ setLiveItems((current) =>+ current.map((item) =>+ item.type === "command" &&+ item.command.id === event.toolCall.id+ ? {+ type: "command",+ command: { ...item.command, running: false },+ }+ : item,+ ),+ );+ }, 350);+ } else if (event.type === "complete") {+ setLatestAnnouncement("Latest assistant message available.");+ clearLoading(runId, conversationID);+ setLiveAssistant((current) => ({+ role: "assistant",+ content: current?.content || event.message.content,+ created_at: new Date().toISOString(),+ }));+ }+ },+ controller.signal,+ );} catch (error) {- if (ownsRun(runId, conversationID) && !isAbort(error)) setTurnError(error instanceof Error ? error.message : "Unable to generate a response")- finishAbortable(runId, conversationID, controller)- finishRun(runId, conversationID)- return+ if (!ownsRun(runId, conversationID)) return;+ if (error instanceof ChatApiError && error.status === 409) {+ setTurnError(undefined);+ setConversation((current) =>+ current?.id === conversationID+ ? {+ ...current,+ archived_at: current.archived_at ?? new Date().toISOString(),+ }+ : current,+ );+ setArchivedTurnNotice(+ "This thread was archived while generating and is now read-only.",+ );+ try {+ await refresh(conversationID, runId);+ } catch (refreshFailure) {+ if (ownsRun(runId, conversationID))+ setRefreshError(+ refreshFailure instanceof Error+ ? refreshFailure.message+ : "Unable to refresh conversation",+ );+ }+ } else if (!isAbort(error)) {+ setTurnError(+ error instanceof Error+ ? error.message+ : "Unable to generate a response",+ );+ }+ finishRun(runId, conversationID);+ return;}- finishAbortable(runId, conversationID, controller)- if (completedCommand) await new Promise<void>(resolve => window.setTimeout(resolve, 360))-- try {- await refresh(conversationID, runId)- } catch (error) {- if (ownsRun(runId, conversationID)) setRefreshError(error instanceof Error ? error.message : "Unable to refresh conversation")- } finally {- finishRun(runId, conversationID)+ if (+ ownsRun(runId, conversationID) &&+ abortControllerRef.current === controller+ ) {+ abortControllerRef.current = undefined;+ setAbortable(false);}- }-- const submitPrompt = async (prompt: string, initialConversationID = selectedId) => {- if (activeRunIdRef.current !== undefined) return- const runId = ++nextRunIdRef.current- activeRunIdRef.current = runId- activeRunConversationIdRef.current = initialConversationID- setRunning(true)- setTurnError(undefined)- setRefreshError(undefined)- setInitialCreatePrompt(undefined)- let conversationID = initialConversationID+ if (completedCommand)+ await new Promise<void>((resolve) => window.setTimeout(resolve, 360));try {- if (!conversationID) {- const conversation = await createConversation()- if (!ownsUnboundRun(runId)) return- conversationID = conversation.id- activeRunConversationIdRef.current = conversation.id- selectedConversationIdRef.current = conversation.id- ignoreNextConversationLoadRef.current = true- setSelectedId(conversation.id)- setSelectedConversation(conversation)- }- setDraft("")- setLiveItems([{ type: "message", message: { role: "user", content: prompt, created_at: new Date().toISOString() } }])- await runAgent(runId, conversationID, [{ role: "user", content: prompt }])+ await refresh(conversationID, runId);} catch (error) {- if (!conversationID && ownsUnboundRun(runId)) {- setInitialCreatePrompt(prompt)- setTurnError(error instanceof Error ? error.message : "Unable to create conversation")- finishRun(runId)- } else if (conversationID && ownsRun(runId, conversationID)) {- setTurnError(error instanceof Error ? error.message : "Unable to create conversation")- finishRun(runId, conversationID)- }+ if (ownsRun(runId, conversationID))+ setRefreshError(+ error instanceof Error+ ? error.message+ : "Unable to refresh conversation",+ );+ } finally {+ finishRun(runId, conversationID);}- }+ };- const submit = async () => {- const prompt = draft.trim()- if (!prompt) return- await submitPrompt(prompt)- }+ const submit = () => {+ const prompt = draft.trim();+ if (+ !prompt ||+ !threadId ||+ !conversation ||+ conversationLoading ||+ activeRunIdRef.current !== undefined ||+ isThreadMutationPending() ||+ conversation.archived_at+ )+ return;+ const runId = ++nextRunIdRef.current;+ activeRunIdRef.current = runId;+ activeRunConversationIdRef.current = threadId;+ setGenerationLocked(true);+ setRunning(true);+ setAssistantLoading(true);+ setLatestAnnouncement("");+ setTurnError(undefined);+ setRefreshError(undefined);+ setDraft("");+ setLiveItems([+ {+ type: "message",+ message: {+ role: "user",+ content: prompt,+ created_at: new Date().toISOString(),+ },+ },+ ]);+ void runAgent(runId, threadId, [{ role: "user", content: prompt }]);+ };const retryTurn = () => {- if (!selectedId || activeRunIdRef.current !== undefined) return- const runId = ++nextRunIdRef.current- activeRunIdRef.current = runId- activeRunConversationIdRef.current = selectedId- setRunning(true)- setTurnError(undefined)- setRefreshError(undefined)- setLiveAssistant(undefined)- void runAgent(runId, selectedId, [])- }-- const retryInitialCreate = () => {- if (!initialCreatePrompt) return- void submitPrompt(initialCreatePrompt, undefined)- }+ if (+ !threadId ||+ activeRunIdRef.current !== undefined ||+ isThreadMutationPending() ||+ conversation?.archived_at+ )+ return;+ const runId = ++nextRunIdRef.current;+ activeRunIdRef.current = runId;+ activeRunConversationIdRef.current = threadId;+ setGenerationLocked(true);+ setRunning(true);+ setAssistantLoading(true);+ setLatestAnnouncement("");+ setTurnError(undefined);+ setRefreshError(undefined);+ setLiveAssistant(undefined);+ void runAgent(runId, threadId, []);+ };++ const recoverRefresh = () => {+ if (+ !threadId ||+ activeRunIdRef.current !== undefined ||+ isThreadMutationPending()+ )+ return;+ const runId = ++nextRunIdRef.current;+ activeRunIdRef.current = runId;+ activeRunConversationIdRef.current = threadId;+ setGenerationLocked(true);+ setRunning(true);+ setRefreshError(undefined);+ void refresh(threadId, runId)+ .catch((error) => {+ if (ownsRun(runId, threadId))+ setRefreshError(+ error instanceof Error+ ? error.message+ : "Unable to refresh conversation",+ );+ })+ .finally(() => finishRun(runId, threadId));+ };const stop = () => {- if (!abortable) return- abortControllerRef.current?.abort()- clearLoading(activeRunIdRef.current, activeRunConversationIdRef.current)- setLiveAssistant(undefined)- }-- const closeHistory = () => setHistoryOpen(false)- const trapDialogFocus = (event: React.KeyboardEvent<HTMLDivElement>) => {- if (event.key === "Escape") { event.preventDefault(); closeHistory(); return }- if (event.key !== "Tab") return- const focusable = dialogRef.current?.querySelectorAll<HTMLElement>('a[href], button:not([disabled]):not([tabindex="-1"]), input:not([disabled]):not([tabindex="-1"]), select:not([disabled]):not([tabindex="-1"]), textarea:not([disabled]):not([tabindex="-1"]), [tabindex]:not([tabindex="-1"])')- if (!focusable?.length) { event.preventDefault(); return }- const first = focusable[0]- const last = focusable[focusable.length - 1]- if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus() }- else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus() }- }+ if (!abortable) return;+ abortControllerRef.current?.abort();+ clearLoading(activeRunIdRef.current, activeRunConversationIdRef.current);+ setLiveAssistant(undefined);+ };- const selectConversation = (conversationID: string) => {- if (activeRunIdRef.current !== undefined) return false- selectedConversationIdRef.current = conversationID- setSelectedId(conversationID)- return true- }-- const persistedItems = selectedConversation ? reconstructTranscript(selectedConversation.messages) : []- const transcript = [...persistedItems, ...liveItems]- const latestMessage = [...transcript].reverse().find((item): item is Extract<TranscriptItem, { type: "message" }> => item.type === "message")?.message- const effectiveMessage = liveAssistant ?? latestMessage- const latestAnnouncement = abortable- ? "Generating response"- : effectiveMessage?.content- ? `Latest ${effectiveMessage.role === "user" ? "user" : "assistant"} message available.`- : ""- const drawerHistory = <ConversationHistory conversations={conversations} disabled={running} loading={listLoading} onSelect={id => { if (selectConversation(id)) closeHistory() }} showHeading={false} />- const firstConversation = !listLoading && conversations.length === 0+ const restore = () => {+ if (+ !conversation ||+ conversation.archived_at === undefined ||+ restorePending+ )+ return;+ const token = ++restoreTokenRef.current;+ const archivedPath = `/agent/${encodeURIComponent(conversation.id)}`;+ setRestorePending(true);+ void restoreThread(conversation.id)+ .then((restored) => {+ if (+ !restored ||+ token !== restoreTokenRef.current ||+ currentThreadIdRef.current !== conversation.id ||+ pathnameRef.current !== archivedPath+ )+ return;+ setConversation(restored);+ setArchivedTurnNotice(undefined);+ navigate(localVisualPreviewPath(archivedPath), { replace: true });+ })+ .finally(() => {+ if (token === restoreTokenRef.current) setRestorePending(false);+ });+ };++ const archived = Boolean(conversation?.archived_at);+ const canRecoverLoad = conversationErrorStatus === 401 || conversationErrorStatus === 404;+ const transcript = conversation+ ? reconstructTranscript(conversation.messages)+ : [];+ const visibleItems = [...transcript, ...liveItems];+ const showPendingAssistant =+ assistantLoading &&+ !liveAssistant &&+ activeRunConversationIdRef.current === threadId &&+ currentThreadIdRef.current === threadId;return (- <>- <PageShell- eyebrow="Agent"- title="Chat"- description={- mobileHistory- ? undefined- : "Run fleet and browser tasks with the Cua agent."- }- >- <div className="agent-chat-page" ref={pageRef}>- <aside className="agent-chat-history"><ConversationHistory conversations={conversations} disabled={running} loading={listLoading} onSelect={selectConversation} /></aside>- <div className="agent-chat-main">- <div className="agent-chat-mobile-history"><Button ariaLabel="View conversations" iconName="menu" onClick={() => setHistoryOpen(true)} ref={triggerRef}>Conversations</Button></div>- <section aria-label="Chat" className="agent-chat-transcript" ref={transcriptRef}>- {conversationLoading ? <SpaceBetween size="m"><Skeleton kind="message" /><Skeleton kind="message" /></SpaceBetween> : transcript.length || liveAssistant || assistantLoading ? (+ <PageShell+ className="agent-chat-shell"+ eyebrow="Agent"+ title="Chat"+ description={+ archived+ ? "This thread is archived and read-only."+ : window.matchMedia("(min-width: 701px)").matches+ ? "Run fleet and browser tasks with the Cua agent."+ : undefined+ }+ primaryAction={+ archived ? (+ <Button+ disabled={restorePending || generationLocked || threadMutationLocked}+ loading={restorePending}+ onClick={restore}+ >+ Restore thread+ </Button>+ ) : undefined+ }+ >+ <div className="agent-chat-page" ref={pageRef}>+ <div className="agent-chat-main">+ <div aria-live="polite" className="agent-chat-announcements">+ {latestAnnouncement ||+ (running+ ? "Generating response"+ : conversationLoading+ ? "Loading conversation"+ : conversation+ ? "Conversation loaded"+ : "No conversation selected")}+ </div>+ <section+ aria-label="Chat"+ className="agent-chat-transcript"+ ref={transcriptRef}+ ><SpaceBetween size="m">- {transcript.map((item, index) => item.type === "message" ? <MessageBubble key={item.message.id ?? `message-${index}`} message={item.message} position={index + 1} /> : <CommandStatus command={item.command} key={item.command.id} />)}- {liveAssistant && <MessageBubble loading={abortable} message={liveAssistant} position={transcript.length + 1} />}- {!liveAssistant && assistantLoading && <MessageBubble loading message={{ role: "assistant", content: "", created_at: new Date().toISOString() }} position={transcript.length + 1} />}+ {archived && (+ <Alert type="info">+ {archivedTurnNotice ??+ "This thread is archived and read-only."}+ </Alert>+ )}+ {conversationError && (+ <Alert+ action={+ canRecoverLoad ? (+ <Button onClick={() => void recoverToActiveThread()}>+ Open newest thread+ </Button>+ ) : undefined+ }+ type="error"+ >+ {conversationError}+ </Alert>+ )}+ {conversationLoading ? (+ <>+ <Skeleton kind="message" />+ <Skeleton kind="message" />+ </>+ ) : !conversation ? (+ <div className="agent-chat-empty">+ <Header variant="h2">Start a conversation</Header>+ <Box color="text-body-secondary">+ Choose a thread from navigation or create a new thread to+ begin.+ </Box>+ </div>+ ) : visibleItems.length === 0 && !liveAssistant && !showPendingAssistant ? (+ <div className="agent-chat-empty">+ <Header variant="h2">+ {archived+ ? "No messages in this archived thread"+ : "Start the conversation"}+ </Header>+ <Box color="text-body-secondary">+ {archived+ ? "Restore this thread to continue it."+ : "Ask the agent to inspect or change your Cua environment."}+ </Box>+ </div>+ ) : (+ visibleItems.map((item, index) =>+ item.type === "message" ? (+ <MessageBubble+ key={`message-${index}`}+ message={item.message}+ position={index + 1}+ />+ ) : (+ <CommandStatus+ command={item.command}+ key={item.command.id}+ />+ ),+ )+ )}+ {showPendingAssistant && (+ <MessageBubble+ loading+ message={{+ role: "assistant",+ content: "",+ created_at: new Date().toISOString(),+ }}+ position={visibleItems.length + 1}+ />+ )}+ {liveAssistant && (+ <MessageBubble+ loading+ message={liveAssistant}+ position={visibleItems.length + 1}+ />+ )}+ {turnError && (+ <div role="alert">+ <Alert+ action={<Button onClick={retryTurn}>Retry</Button>}+ type="error"+ >+ {turnError}+ </Alert>+ </div>+ )}+ {refreshError && (+ <div role="alert">+ <Alert+ action={+ <Button onClick={recoverRefresh}>+ Refresh conversation+ </Button>+ }+ type="error"+ >+ {refreshError}+ </Alert>+ </div>+ )}</SpaceBetween>- ) : <div className="agent-chat-empty"><Box variant="h2">{firstConversation ? "Start a conversation" : "Select a conversation"}</Box><Box color="text-body-secondary">{firstConversation ? "Ask a question below to create your first conversation." : "Choose a previous conversation to view its transcript."}</Box></div>}- {turnError && <div role="alert"><Alert action={<Button onClick={initialCreatePrompt ? retryInitialCreate : retryTurn}>Retry</Button>} type="error">{turnError}</Alert></div>}- {refreshError && <div role="alert"><Alert action={<Button disabled={running} onClick={() => { if (selectedId) void recoverRefresh(selectedId) }}>Refresh conversation</Button>} type="error">{refreshError}</Alert></div>}- <div className="agent-chat-announcements">- <LiveRegion>{conversationLoading ? "Loading conversation" : selectedConversation ? "Conversation loaded" : "No conversation selected"}</LiveRegion>- <LiveRegion>{latestAnnouncement}</LiveRegion>- </div>- </section>- <div className="agent-chat-composer">- <div className="agent-chat-composer-surface">- <div className="agent-chat-prompt"><PromptInput actionButtonAriaLabel="Send message" actionButtonIconName="send" disableActionButton={running || !draft.trim()} maxRows={6} minRows={2} onAction={() => void submit()} onChange={({ detail }) => setDraft(detail.value)} placeholder="Ask a question" value={draft} /></div>- {abortable && <Button ariaLabel="Stop generating" onClick={stop}>Stop</Button>}- </div>+ </section>+ {!archived && (+ <div className="agent-chat-composer">+ <div className="agent-chat-composer-surface">+ <PromptInput+ className="agent-chat-prompt"+ ariaLabel="Ask a question"+ disabled={!threadId || !conversation || conversationLoading || threadMutationLocked}+ onChange={({ detail }) => setDraft(detail.value)}+ onKeyDown={(event) => {+ if (+ event.detail.key === "Enter" &&+ !event.detail.shiftKey+ ) {+ event.preventDefault();+ submit();+ }+ }}+ placeholder="Ask a question"+ value={draft}+ />+ {running && abortable ? (+ <Button+ ariaLabel="Stop generating"+ iconName="status-negative"+ onClick={stop}+ />+ ) : (+ <Button+ ariaLabel="Send message"+ disabled={+ !draft.trim() ||+ !threadId ||+ !conversation ||+ conversationLoading ||+ threadMutationLocked ||+ running+ }+ iconName="send"+ onClick={submit}+ />+ )}+ </div>+ </div>+ )}</div></div>- </div>- </PageShell>- {mobileHistory && historyOpen && createPortal(- <div aria-label="Conversations" aria-modal="true" className="agent-chat-mobile-overlay" onKeyDown={trapDialogFocus} ref={dialogRef} role="dialog">- <div aria-hidden="true" className="agent-chat-mobile-backdrop" data-testid="conversation-history-backdrop" onClick={closeHistory} />- <div className="agent-chat-mobile-drawer"><Drawer header={<h2>Conversations</h2>} headerActions={<Button ariaLabel="Close conversations" iconName="close" onClick={closeHistory} ref={closeButtonRef} variant="icon" />}>{drawerHistory}</Drawer></div>- </div>, document.body,- )}- </>- )+ </PageShell>+ );}diff --git a/libs/fleet/src/pages/ArchivedThreads.tsx b/libs/fleet/src/pages/ArchivedThreads.tsxnew file mode 100644index 0000000000..b33fadf5ae--- /dev/null+++ b/libs/fleet/src/pages/ArchivedThreads.tsx@@ -0,0 +1,142 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useNavigate } from "react-router-dom";+import Alert from "@cloudscape-design/components/alert";+import Box from "@cloudscape-design/components/box";+import Button from "@cloudscape-design/components/button";+import Header from "@cloudscape-design/components/header";+import SpaceBetween from "@cloudscape-design/components/space-between";+import { displayThreadTitle, useChatThreads } from "../chat/ChatThreadsContext";+import { localVisualPreviewPath } from "../local-visual-preview";+import { listConversations, type ConversationSummary } from "../sdk/chat";+import { PageShell } from "../components/PageShell";+import "./AgentChat.css";++function formatArchivedAt(timestamp?: string): string {+ return timestamp+ ? new Date(timestamp).toLocaleString()+ : "Unknown archive time";+}++export function ArchivedThreads() {+ const navigate = useNavigate();+ const { generationLocked, restoreThread, threadMutationLocked } = useChatThreads();+ const [threads, setThreads] = useState<ConversationSummary[]>([]);+ const [loading, setLoading] = useState(true);+ const [error, setError] = useState<string>();+ const [restoringId, setRestoringId] = useState<string>();+ const requestIdRef = useRef(0);++ const load = useCallback(() => {+ const requestId = ++requestIdRef.current;+ setLoading(true);+ setError(undefined);+ void listConversations({ archived: true })+ .then((items) => {+ if (requestId !== requestIdRef.current) return;+ setThreads(items);+ })+ .catch((loadError) => {+ if (requestId !== requestIdRef.current) return;+ setError(+ loadError instanceof Error+ ? loadError.message+ : "Unable to load archived threads",+ );+ })+ .finally(() => {+ if (requestId === requestIdRef.current) setLoading(false);+ });+ }, []);++ useEffect(() => {+ load();+ return () => {+ requestIdRef.current += 1;+ };+ }, [load]);++ const restore = (thread: ConversationSummary) => {+ if (generationLocked || threadMutationLocked || restoringId) return;+ setRestoringId(thread.id);+ void restoreThread(thread.id)+ .then((restored) => {+ if (!restored) return;+ setThreads((current) =>+ current.filter((item) => item.id !== thread.id),+ );+ })+ .finally(() =>+ setRestoringId((current) =>+ current === thread.id ? undefined : current,+ ),+ );+ };++ return (+ <PageShell+ eyebrow="Agent"+ title="Archived threads"+ description="Read or restore conversations that are no longer active."+ >+ <SpaceBetween size="l">+ {error && (+ <Alert action={<Button onClick={load}>Retry</Button>} type="error">+ {error}+ </Alert>+ )}+ {loading ? (+ <SpaceBetween size="s">+ <div+ className="agent-chat-skeleton agent-chat-skeleton--message"+ data-testid="archived-thread-skeleton"+ />+ <div+ className="agent-chat-skeleton agent-chat-skeleton--message"+ data-testid="archived-thread-skeleton"+ />+ </SpaceBetween>+ ) : threads.length === 0 ? (+ <Box color="text-body-secondary">No archived threads.</Box>+ ) : (+ <SpaceBetween size="m">+ {threads.map((thread) => (+ <section key={thread.id}>+ <SpaceBetween direction="horizontal" size="s">+ <Header variant="h2">+ <a+ href={`#${localVisualPreviewPath(`/agent/${encodeURIComponent(thread.id)}`)}`}+ title={displayThreadTitle(thread.title)}+ onClick={(event) => {+ event.preventDefault();+ navigate(+ localVisualPreviewPath(+ `/agent/${encodeURIComponent(thread.id)}`,+ ),+ );+ }}+ >+ {displayThreadTitle(thread.title)}+ </a>+ </Header>+ <Button+ ariaLabel={`Restore ${displayThreadTitle(thread.title)}`}+ disabled={+ generationLocked || threadMutationLocked || Boolean(restoringId)+ }+ loading={restoringId === thread.id}+ onClick={() => restore(thread)}+ >+ Restore+ </Button>+ </SpaceBetween>+ <Box color="text-body-secondary" fontSize="body-s">+ Archived {formatArchivedAt(thread.archived_at)}+ </Box>+ </section>+ ))}+ </SpaceBetween>+ )}+ </SpaceBetween>+ </PageShell>+ );+}diff --git a/libs/fleet/src/sdk/chat.ts b/libs/fleet/src/sdk/chat.tsindex 8c4270119f..4f14a892f5 100644--- a/libs/fleet/src/sdk/chat.ts+++ b/libs/fleet/src/sdk/chat.ts@@ -4,6 +4,7 @@ import {getLocalVisualPreviewConversation,isLocalVisualPreview,listLocalVisualPreviewConversations,+ setLocalVisualPreviewConversationArchived,streamLocalVisualPreviewTurn,} from "../local-visual-preview"@@ -35,6 +36,7 @@ export interface Conversation {messages: ChatMessage[]created_at: stringupdated_at: string+ archived_at?: string}export interface ConversationSummary {@@ -42,6 +44,7 @@ export interface ConversationSummary {title: stringcreated_at: stringupdated_at: string+ archived_at?: string}export class ChatApiError extends Error {@@ -142,9 +145,27 @@ export async function createConversation(): Promise<Conversation> {return chatJson<Conversation>("/api/chat/conversations", { method: "POST" })}-export async function listConversations(): Promise<ConversationSummary[]> {- if (isLocalVisualPreview()) return listLocalVisualPreviewConversations()- return chatJson<ConversationSummary[]>("/api/chat/conversations")+export async function listConversations(+ options: { archived?: boolean } = {},+): Promise<ConversationSummary[]> {+ if (isLocalVisualPreview()) return listLocalVisualPreviewConversations(options)+ const query = options.archived ? "?archived=true" : ""+ return chatJson<ConversationSummary[]>(`/api/chat/conversations${query}`)+}++export async function setConversationArchived(+ id: string,+ archived: boolean,+): Promise<Conversation> {+ if (isLocalVisualPreview()) {+ const conversation = setLocalVisualPreviewConversationArchived(id, archived)+ if (!conversation) throw new ChatApiError("Conversation not found", 404)+ return conversation+ }+ return chatJson<Conversation>(`/api/chat/conversations/${encodeURIComponent(id)}`, {+ method: "PATCH",+ body: JSON.stringify({ archived }),+ })}export async function getConversation(id: string): Promise<Conversation> {@@ -163,7 +184,14 @@ export async function streamTurn(signal?: AbortSignal,): Promise<ChatMessage> {if (isLocalVisualPreview()) {- return streamLocalVisualPreviewTurn(conversationId, messages, onDelta)+ try {+ return await streamLocalVisualPreviewTurn(conversationId, messages, onDelta)+ } catch (error) {+ if (error instanceof Error && "status" in error && typeof error.status === "number") {+ throw new ChatApiError(error.message, error.status)+ }+ throw error+ }}const response = await chatFetch(`/api/chat/conversations/${encodeURIComponent(conversationId)}/turns`,diff --git a/libs/fleet/tsconfig.sdk-models.json b/libs/fleet/tsconfig.sdk-models.jsonnew file mode 100644index 0000000000..d323a3a965--- /dev/null+++ b/libs/fleet/tsconfig.sdk-models.json@@ -0,0 +1,24 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": [+ "ES2022",+ "DOM",+ "DOM.Iterable"+ ],+ "module": "ESNext",+ "moduleResolution": "Bundler",+ "outDir": "target/sdk-model-tests",+ "skipLibCheck": true,+ "types": [+ "vite/client",+ "node"+ ],+ "strict": true+ },+ "files": [+ "e2e/sdk-models.unit.ts",+ "e2e/mock-chat-api.spec.ts",+ "src/sdk/status.ts"+ ]+}