Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat: show a Task's AlterEgo trajectory in a read-only dialog

LeoXing8f736fa21dd7
diff --git a/apps/teamhub/internal/app/handlers_agent_task_executions.go b/apps/teamhub/internal/app/handlers_agent_task_executions.go
index 6c31cb49..7221a8bf 100644
--- a/apps/teamhub/internal/app/handlers_agent_task_executions.go
+++ b/apps/teamhub/internal/app/handlers_agent_task_executions.go
@@ -18,6 +18,7 @@ import (
type taskExecutionService interface {
ResolveAgentParticipantTaskByWorkRoom(context.Context, string, string) (taskexecution.ParticipantTaskResolution, error)
GetExecutionForHuman(context.Context, string, string) (taskexecution.Execution, error)
+ GetConversationForHuman(context.Context, string, string) (taskexecution.Conversation, error)
ClaimExecution(context.Context, taskexecution.WorkerClaimInput) (taskexecution.WorkerExecution, bool, *time.Duration, error)
GetExecutionForWorker(context.Context, taskexecution.WorkerLeaseInput) (taskexecution.WorkerExecution, error)
HeartbeatExecution(context.Context, taskexecution.WorkerHeartbeatInput) (taskexecution.WorkerLease, error)
diff --git a/apps/teamhub/internal/app/handlers_task_conversation.go b/apps/teamhub/internal/app/handlers_task_conversation.go
new file mode 100644
index 00000000..97012f04
--- /dev/null
+++ b/apps/teamhub/internal/app/handlers_task_conversation.go
@@ -0,0 +1,40 @@
+package app
+
+import (
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+// getTaskConversation returns what a Task's Agent was told and the cards its
+// AlterEgo raised, to a person who can read the Task.
+func (a *App) getTaskConversation(c *gin.Context) {
+ conversation, err := a.taskExecutions.GetConversationForHuman(
+ c.Request.Context(), currentPrincipal(c).Session.AccountID, c.Param("taskId"),
+ )
+ if a.writeTaskExecutionError(c, "get Task conversation", err) {
+ return
+ }
+ model := httpapi.TaskConversation{
+ Inputs: make([]httpapi.TaskConversationInput, len(conversation.Inputs)),
+ Cards: make([]httpapi.TaskConversationCard, len(conversation.Cards)),
+ }
+ for index, input := range conversation.Inputs {
+ model.Inputs[index] = httpapi.TaskConversationInput{
+ Id: input.ID, Body: input.Body, CreatedAt: input.CreatedAt.Time,
+ Source: httpapi.TaskConversationInputSource(input.Source),
+ Author: httpapi.ActorRef{
+ Id: input.AuthorActorID, TenantId: conversation.TenantID,
+ Kind: httpapi.ActorKind(input.AuthorKind), DisplayName: input.AuthorDisplayName,
+ },
+ }
+ }
+ for index, card := range conversation.Cards {
+ model.Cards[index] = httpapi.TaskConversationCard{
+ DecisionId: card.ID, RoomId: card.RoomID, MessageId: card.MessageID, CreatedAt: card.CreatedAt.Time,
+ }
+ }
+ c.JSON(http.StatusOK, model)
+}
diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.go
index 28794308..8da3ceca 100644
--- a/apps/teamhub/internal/app/routes_public.go
+++ b/apps/teamhub/internal/app/routes_public.go
@@ -136,6 +136,7 @@ func (a *App) publicRoutes() []contractRoute {
route(http.MethodPost, "/v0/shared-room-history/asset", nil, a.readRoomHistoryShareAsset),
route(http.MethodPost, "/v0/shared-room-history/read", nil, a.readRoomHistoryShare),
route(http.MethodGet, "/v0/tasks/:taskId/execution", nil, session, a.getTaskExecutionProjection),
+ route(http.MethodGet, "/v0/tasks/:taskId/conversation", nil, session, a.getTaskConversation),
route(http.MethodGet, "/v0/tasks/:taskId/runtime-presentation-runs", httpapi.ListTaskRuntimePresentationRunsParams{}, session, a.listTaskRuntimePresentationRuns),
route(http.MethodGet, "/v0/tenants", nil, session, a.listTenants),
route(http.MethodGet, "/v0/tenants/:tenantId", nil, session, a.getTenant),
diff --git a/apps/teamhub/internal/collaboration/message_activities.go b/apps/teamhub/internal/collaboration/message_activities.go
index 5e14a9bc..f04bcbbc 100644
--- a/apps/teamhub/internal/collaboration/message_activities.go
+++ b/apps/teamhub/internal/collaboration/message_activities.go
@@ -41,7 +41,6 @@ type runActivitySource struct {
contextKey string
tenantID string
agentActorID string
- task bool
eventOrdinal int64
}
@@ -333,7 +332,7 @@ func (s *Service) MessageActivities(ctx context.Context, accountID, roomID, mess
}
return s.runtimeActivityLog(ctx, runActivitySource{
runID: run.RunID, contextKey: run.ContextKey, tenantID: run.TenantID, agentActorID: run.AgentActorID,
- task: run.TaskID.Valid, eventOrdinal: run.EventOrdinal,
+ eventOrdinal: run.EventOrdinal,
}, history)
}
@@ -348,14 +347,11 @@ func (s *Service) RunActivities(ctx context.Context, accountID, roomID, runID st
}
return s.runtimeActivityLog(ctx, runActivitySource{
runID: run.RunID, contextKey: run.ContextKey, tenantID: run.TenantID, agentActorID: run.AgentActorID,
- task: run.TaskID.Valid, eventOrdinal: run.EventOrdinal,
+ eventOrdinal: run.EventOrdinal,
}, history)
}
func (s *Service) runtimeActivityLog(ctx context.Context, run runActivitySource, historyReader MessageActivityHistoryReader) (httpapi.MessageActivityLog, error) {
- if run.task {
- return unavailableMessageActivityLog("Task activities are available through public Runtime presentation events"), nil
- }
executionContext, err := s.queries.GetAgentExecutionContext(ctx, run.contextKey)
if errors.Is(err, pgx.ErrNoRows) {
return unavailableMessageActivityLog("The linked Agent Runtime Context is no longer available"), nil
diff --git a/apps/teamhub/internal/collaboration/message_activities_test.go b/apps/teamhub/internal/collaboration/message_activities_test.go
index 3545662c..d7067209 100644
--- a/apps/teamhub/internal/collaboration/message_activities_test.go
+++ b/apps/teamhub/internal/collaboration/message_activities_test.go
@@ -5,7 +5,6 @@ import (
"testing"
"github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
- httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
)
func TestMessageActivityRecordMatchesNativeTurn(t *testing.T) {
@@ -133,11 +132,3 @@ func (s *messageActivityInspectorStub) ReadRuntimeHistory(
}
return s.pages[cursor], nil
}
-
-func TestTaskActivityNeverReadsNativeHistory(t *testing.T) {
- // No native reader or database: both public native activity routes share this guard.
- log, err := (&Service{}).runtimeActivityLog(t.Context(), runActivitySource{task: true}, nil)
- if err != nil || log.Status != httpapi.MessageActivityLogStatusUnavailable {
- t.Fatalf("native Task history log: %+v %v", log, err)
- }
-}
diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.go
index 7db981d2..9cd168a6 100644
--- a/apps/teamhub/internal/store/models.go
+++ b/apps/teamhub/internal/store/models.go
@@ -1728,6 +1728,7 @@ type TaskMetaMessage struct {
Body string `json:"body"`
Segments []byte `json:"segments"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
+ Source string `json:"source"`
}
type ThreadRoomListActor struct {
diff --git a/apps/teamhub/internal/store/queries/task_meta_inbox.sql b/apps/teamhub/internal/store/queries/task_meta_inbox.sql
index a0e1d9de..e7082895 100644
--- a/apps/teamhub/internal/store/queries/task_meta_inbox.sql
+++ b/apps/teamhub/internal/store/queries/task_meta_inbox.sql
@@ -11,12 +11,37 @@ FOR UPDATE;
-- name: CreateTaskMetaMessage :one
INSERT INTO task_meta_messages(
- id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments
+ id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments,source
)
-VALUES($1,$2,$3,$4,$5,$6,$7,$8)
-RETURNING id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments,created_at;
+VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)
+RETURNING id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments,created_at,source;
-- name: SetTaskMetaInboxThroughSeq :execrows
UPDATE task_meta_inboxes
SET through_seq=$4,updated_at=now()
WHERE task_id=$1 AND tenant_id=$2 AND agent_actor_id=$3 AND through_seq<$4;
+
+-- name: ListTaskConversationInputs :many
+-- Every input the Task's own Agent received in its current generation, in
+-- delivery order. Other participants hold copies of the same inputs.
+SELECT message.id,message.author_actor_id,author.kind AS author_kind,
+ author.display_name AS author_display_name,message.body,message.source,message.created_at
+FROM work_items item
+JOIN task_execution_generations generation
+ ON generation.task_id=item.id AND generation.tenant_id=item.tenant_id
+ AND generation.generation=item.task_execution_generation
+JOIN task_meta_messages message
+ ON message.task_id=item.id AND message.tenant_id=item.tenant_id
+ AND message.agent_actor_id=generation.result_agent_actor_id
+JOIN actors author ON author.id=message.author_actor_id AND author.tenant_id=message.tenant_id
+WHERE item.id=sqlc.arg(task_id)::text
+ORDER BY message.meta_seq
+LIMIT 500;
+
+-- name: ListTaskConversationCards :many
+-- Every card the Task's AlterEgo raised, answered or not, by its card Message.
+SELECT id,room_id,message_id,created_at
+FROM decisions
+WHERE tenant_id=sqlc.arg(tenant_id)::text AND alter_ego_task_id=sqlc.arg(task_id)::text
+ORDER BY created_at,id
+LIMIT 200;
diff --git a/apps/teamhub/internal/store/task_meta_inbox.sql.go b/apps/teamhub/internal/store/task_meta_inbox.sql.go
index 94013e6d..1e51bd70 100644
--- a/apps/teamhub/internal/store/task_meta_inbox.sql.go
+++ b/apps/teamhub/internal/store/task_meta_inbox.sql.go
@@ -7,14 +7,16 @@ package store
import (
"context"
+
+ "github.com/jackc/pgx/v5/pgtype"
)
const createTaskMetaMessage = `-- name: CreateTaskMetaMessage :one
INSERT INTO task_meta_messages(
- id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments
+ id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments,source
)
-VALUES($1,$2,$3,$4,$5,$6,$7,$8)
-RETURNING id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments,created_at
+VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9)
+RETURNING id,tenant_id,task_id,agent_actor_id,meta_seq,author_actor_id,body,segments,created_at,source
`
type CreateTaskMetaMessageParams struct {
@@ -26,6 +28,7 @@ type CreateTaskMetaMessageParams struct {
AuthorActorID string `json:"author_actor_id"`
Body string `json:"body"`
Segments []byte `json:"segments"`
+ Source string `json:"source"`
}
func (q *Queries) CreateTaskMetaMessage(ctx context.Context, arg CreateTaskMetaMessageParams) (TaskMetaMessage, error) {
@@ -38,6 +41,7 @@ func (q *Queries) CreateTaskMetaMessage(ctx context.Context, arg CreateTaskMetaM
arg.AuthorActorID,
arg.Body,
arg.Segments,
+ arg.Source,
)
var i TaskMetaMessage
err := row.Scan(
@@ -50,6 +54,7 @@ func (q *Queries) CreateTaskMetaMessage(ctx context.Context, arg CreateTaskMetaM
&i.Body,
&i.Segments,
&i.CreatedAt,
+ &i.Source,
)
return i, err
}
@@ -98,6 +103,108 @@ func (q *Queries) GetTaskMetaInboxForUpdate(ctx context.Context, arg GetTaskMeta
return i, err
}
+const listTaskConversationCards = `-- name: ListTaskConversationCards :many
+SELECT id,room_id,message_id,created_at
+FROM decisions
+WHERE tenant_id=$1::text AND alter_ego_task_id=$2::text
+ORDER BY created_at,id
+LIMIT 200
+`
+
+type ListTaskConversationCardsParams struct {
+ TenantID string `json:"tenant_id"`
+ TaskID string `json:"task_id"`
+}
+
+type ListTaskConversationCardsRow struct {
+ ID string `json:"id"`
+ RoomID string `json:"room_id"`
+ MessageID string `json:"message_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// Every card the Task's AlterEgo raised, answered or not, by its card Message.
+func (q *Queries) ListTaskConversationCards(ctx context.Context, arg ListTaskConversationCardsParams) ([]ListTaskConversationCardsRow, error) {
+ rows, err := q.db.Query(ctx, listTaskConversationCards, arg.TenantID, arg.TaskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListTaskConversationCardsRow{}
+ for rows.Next() {
+ var i ListTaskConversationCardsRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.RoomID,
+ &i.MessageID,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const listTaskConversationInputs = `-- name: ListTaskConversationInputs :many
+SELECT message.id,message.author_actor_id,author.kind AS author_kind,
+ author.display_name AS author_display_name,message.body,message.source,message.created_at
+FROM work_items item
+JOIN task_execution_generations generation
+ ON generation.task_id=item.id AND generation.tenant_id=item.tenant_id
+ AND generation.generation=item.task_execution_generation
+JOIN task_meta_messages message
+ ON message.task_id=item.id AND message.tenant_id=item.tenant_id
+ AND message.agent_actor_id=generation.result_agent_actor_id
+JOIN actors author ON author.id=message.author_actor_id AND author.tenant_id=message.tenant_id
+WHERE item.id=$1::text
+ORDER BY message.meta_seq
+LIMIT 500
+`
+
+type ListTaskConversationInputsRow struct {
+ ID string `json:"id"`
+ AuthorActorID string `json:"author_actor_id"`
+ AuthorKind string `json:"author_kind"`
+ AuthorDisplayName string `json:"author_display_name"`
+ Body string `json:"body"`
+ Source string `json:"source"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
+// Every input the Task's own Agent received in its current generation, in
+// delivery order. Other participants hold copies of the same inputs.
+func (q *Queries) ListTaskConversationInputs(ctx context.Context, taskID string) ([]ListTaskConversationInputsRow, error) {
+ rows, err := q.db.Query(ctx, listTaskConversationInputs, taskID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ListTaskConversationInputsRow{}
+ for rows.Next() {
+ var i ListTaskConversationInputsRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.AuthorActorID,
+ &i.AuthorKind,
+ &i.AuthorDisplayName,
+ &i.Body,
+ &i.Source,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const setTaskMetaInboxThroughSeq = `-- name: SetTaskMetaInboxThroughSeq :execrows
UPDATE task_meta_inboxes
SET through_seq=$4,updated_at=now()
diff --git a/apps/teamhub/internal/taskexecution/conversation.go b/apps/teamhub/internal/taskexecution/conversation.go
new file mode 100644
index 00000000..bac4f361
--- /dev/null
+++ b/apps/teamhub/internal/taskexecution/conversation.go
@@ -0,0 +1,54 @@
+package taskexecution
+
+import (
+ "context"
+ "errors"
+ "strings"
+
+ "github.com/jackc/pgx/v5"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// Conversation is what a Task's Agent was told and the cards its AlterEgo
+// raised, for a person who can read the Task.
+type Conversation struct {
+ TenantID string
+ Inputs []store.ListTaskConversationInputsRow
+ Cards []store.ListTaskConversationCardsRow
+}
+
+// GetConversationForHuman reads a Task's conversation for an Account that can
+// read the Task.
+func (s *Service) GetConversationForHuman(ctx context.Context, accountID, taskID string) (Conversation, error) {
+ if strings.TrimSpace(accountID) == "" || strings.TrimSpace(taskID) == "" {
+ return Conversation{}, ErrInvalid
+ }
+ tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
+ if err != nil {
+ return Conversation{}, err
+ }
+ defer tx.Rollback(ctx)
+ queries := store.New(tx)
+ item, err := queries.GetWorkItemForHuman(ctx, store.GetWorkItemForHumanParams{ID: taskID, AccountID: accountID})
+ if errors.Is(err, pgx.ErrNoRows) || (err == nil && (item.Kind != "task" || !item.TaskExecutionGeneration.Valid)) {
+ return Conversation{}, ErrNotFound
+ }
+ if err != nil {
+ return Conversation{}, err
+ }
+ inputs, err := queries.ListTaskConversationInputs(ctx, taskID)
+ if err != nil {
+ return Conversation{}, err
+ }
+ cards, err := queries.ListTaskConversationCards(ctx, store.ListTaskConversationCardsParams{
+ TenantID: item.TenantID, TaskID: taskID,
+ })
+ if err != nil {
+ return Conversation{}, err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return Conversation{}, err
+ }
+ return Conversation{TenantID: item.TenantID, Inputs: inputs, Cards: cards}, nil
+}
diff --git a/apps/teamhub/internal/taskexecution/delegated.go b/apps/teamhub/internal/taskexecution/delegated.go
index 86fa15b6..c1519a83 100644
--- a/apps/teamhub/internal/taskexecution/delegated.go
+++ b/apps/teamhub/internal/taskexecution/delegated.go
@@ -123,7 +123,11 @@ func AppendTaskInput(ctx context.Context, queries *store.Queries, input TaskInpu
}); err != nil {
return TaskInputResult{}, err
}
- wakes, err := AppendParticipantMetaWakes(ctx, queries, input.TaskID, snapshot.TenantID, author.ID, recipients, message)
+ source := InputSourceMessage
+ if input.Cause == TaskInputSystem {
+ source = InputSourceSystem
+ }
+ wakes, err := AppendParticipantMetaWakes(ctx, queries, input.TaskID, snapshot.TenantID, author.ID, source, recipients, message)
if err != nil {
return TaskInputResult{}, err
}
diff --git a/apps/teamhub/internal/taskexecution/human_message.go b/apps/teamhub/internal/taskexecution/human_message.go
index e39612b3..d0d6b9ac 100644
--- a/apps/teamhub/internal/taskexecution/human_message.go
+++ b/apps/teamhub/internal/taskexecution/human_message.go
@@ -125,7 +125,7 @@ func PromoteLockedHumanTaskRoomMessage(
return HumanTaskRoomMessagePromotion{}, err
}
wakes, err := AppendParticipantMetaWakes(
- ctx, queries, target.taskID, target.tenantID, input.AuthorActorID,
+ ctx, queries, target.taskID, target.tenantID, input.AuthorActorID, InputSourceMessage,
recipients, publicMessage,
)
if err != nil {
diff --git a/apps/teamhub/internal/taskexecution/service.go b/apps/teamhub/internal/taskexecution/service.go
index 85ef1a38..d2739abb 100644
--- a/apps/teamhub/internal/taskexecution/service.go
+++ b/apps/teamhub/internal/taskexecution/service.go
@@ -178,7 +178,7 @@ func CreateManagedGeneration(
wakeAuthorActorID = locked.UpdatedByActorID
}
wakes, err := AppendParticipantMetaWakes(
- ctx, queries, input.TaskID, locked.TenantID, wakeAuthorActorID,
+ ctx, queries, input.TaskID, locked.TenantID, wakeAuthorActorID, InputSourceMessage,
recipients, initialMessage,
)
if err != nil {
diff --git a/apps/teamhub/internal/taskexecution/turn_routing.go b/apps/teamhub/internal/taskexecution/turn_routing.go
index b81545ca..579d6285 100644
--- a/apps/teamhub/internal/taskexecution/turn_routing.go
+++ b/apps/teamhub/internal/taskexecution/turn_routing.go
@@ -38,6 +38,15 @@ type SubmitTurnEffectPayload struct {
Steer bool `json:"steer,omitempty"`
}
+// InputSource says whether a Task input is a message or a system notice.
+type InputSource string
+
+// Task input sources stored with each private wake.
+const (
+ InputSourceMessage InputSource = "message"
+ InputSourceSystem InputSource = "system"
+)
+
// AppendParticipantMetaWakes durably appends exactly one private wake to every
// recipient's frozen Meta Inbox. Callers must run it in the same transaction
// that creates the corresponding InputRevision and submit effect.
@@ -46,11 +55,13 @@ func AppendParticipantMetaWakes(
queries *store.Queries,
taskID, tenantID string,
authorActorID string,
+ source InputSource,
recipientActorIDs []string,
publicMessage TurnMessageInput,
) ([]ParticipantMetaWake, error) {
authorActorID = strings.TrimSpace(authorActorID)
- if queries == nil || strings.TrimSpace(taskID) == "" || strings.TrimSpace(tenantID) == "" || authorActorID == "" {
+ if queries == nil || strings.TrimSpace(taskID) == "" || strings.TrimSpace(tenantID) == "" || authorActorID == "" ||
+ source != InputSourceMessage && source != InputSourceSystem {
return nil, ErrInvalid
}
recipients, err := normalizedUniqueIDs(recipientActorIDs)
@@ -82,7 +93,7 @@ func AppendParticipantMetaWakes(
if _, err := queries.CreateTaskMetaMessage(ctx, store.CreateTaskMetaMessageParams{
ID: message.MessageID, TenantID: tenantID, TaskID: taskID,
AgentActorID: actorID, MetaSeq: nextSeq, AuthorActorID: authorActorID,
- Body: message.RawMessage, Segments: message.Segments,
+ Body: message.RawMessage, Segments: message.Segments, Source: string(source),
}); err != nil {
return nil, err
}
diff --git a/apps/teamhub/migrations/00864_task_meta_message_source.sql b/apps/teamhub/migrations/00864_task_meta_message_source.sql
new file mode 100644
index 00000000..65b3238a
--- /dev/null
+++ b/apps/teamhub/migrations/00864_task_meta_message_source.sql
@@ -0,0 +1,9 @@
+-- +goose Up
+-- A Task input is a message from the Meta or a person, or a system notice, such as an
+-- approval card's result; the Task conversation view shows them differently.
+ALTER TABLE task_meta_messages
+ ADD COLUMN source text NOT NULL DEFAULT 'message' CHECK (source IN ('message', 'system'));
+ALTER TABLE task_meta_messages ALTER COLUMN source DROP DEFAULT;
+
+-- +goose Down
+ALTER TABLE task_meta_messages DROP COLUMN source;
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/agent-live-activity-panel-tab.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/agent-live-activity-panel-tab.tsx
index de494f9e..215c8045 100644
--- a/apps/web/src/features/rooms/task-sidebar/adapters/agent-live-activity-panel-tab.tsx
+++ b/apps/web/src/features/rooms/task-sidebar/adapters/agent-live-activity-panel-tab.tsx
@@ -10,7 +10,7 @@ import { roomMessagesInfiniteQueryOptions } from "../../room-queries";
import { RuntimeActivityPath } from "../../runtime-status/runtime-activity-path-view";
import { useRuntimePresentationEventRecords } from "../../runtime-status/use-runtime-presentation-event-records";
import { PanelLoading } from "../panel-loading";
-import { TaskActivityDrillDown } from "./task-activity-drill-down";
+import { TaskConversationProvider } from "./task-conversation-dialog";
const EMPTY_MESSAGES: readonly TeamHubMessage[] = [];
@@ -65,11 +65,7 @@ export function AgentLiveActivityPanelTab({
const pending = events.pending;
return (
- <TaskActivityDrillDown
- hidden={hidden}
- key={runId ?? runStatusId}
- tenantId={tenantId}
- >
+ <TaskConversationProvider tenantId={tenantId}>
<div
className={hidden ? "hidden" : "flex h-full min-h-0 flex-col bg-card"}
data-testid="agent-live-activity-panel"
@@ -124,7 +120,7 @@ export function AgentLiveActivityPanelTab({
/>
)}
</div>
- </TaskActivityDrillDown>
+ </TaskConversationProvider>
);
}
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/message-activities-panel-tab.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/message-activities-panel-tab.tsx
index bdc7fd68..90434642 100644
--- a/apps/web/src/features/rooms/task-sidebar/adapters/message-activities-panel-tab.tsx
+++ b/apps/web/src/features/rooms/task-sidebar/adapters/message-activities-panel-tab.tsx
@@ -15,7 +15,7 @@ import type { TeamHubMessage } from "@/features/teamhub/teamhub-types";
import { ActorAvatar } from "../../members/actor-avatar";
import { PanelLoading } from "../panel-loading";
-import { TaskActivityDrillDown } from "./task-activity-drill-down";
+import { TaskConversationProvider } from "./task-conversation-dialog";
export function MessageActivitiesPanelTab({
activationKey,
@@ -77,7 +77,7 @@ export function MessageActivitiesPanelTab({
}, [activationKey, hidden, message.id, activities.data?.records.length]);
return (
- <TaskActivityDrillDown hidden={hidden} key={message.id} tenantId={tenantId}>
+ <TaskConversationProvider tenantId={tenantId}>
<div
className={hidden ? "hidden" : "flex h-full min-h-0 flex-col bg-card"}
data-testid="message-activities-panel"
@@ -179,7 +179,7 @@ export function MessageActivitiesPanelTab({
)}
</div>
</div>
- </TaskActivityDrillDown>
+ </TaskConversationProvider>
);
}
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx
index b0a384c9..2ceabb1c 100644
--- a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx
+++ b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-history-view.tsx
@@ -233,7 +233,7 @@ function RuntimeActivityRecord({
}
/** The shell command a native tool call ran, for any Runtime's shape. */
-function nativeCommand(record: TeamHubMessageActivityRecord) {
+export function nativeCommand(record: TeamHubMessageActivityRecord) {
const payload = nativePayload(record);
const block = nativeContentBlock(record, payload);
const input =
@@ -244,7 +244,7 @@ function nativeCommand(record: TeamHubMessageActivityRecord) {
return undefined;
}
-function nativeOutput(record: TeamHubMessageActivityRecord) {
+export function nativeOutput(record: TeamHubMessageActivityRecord) {
const payload = nativePayload(record);
const block = nativeContentBlock(record, payload);
return (
@@ -254,7 +254,7 @@ function nativeOutput(record: TeamHubMessageActivityRecord) {
);
}
-function parseObject(value: unknown) {
+export function parseObject(value: unknown) {
if (typeof value !== "string") return asObject(value);
try {
return asObject(JSON.parse(value));
@@ -267,7 +267,7 @@ function isString(value: unknown): value is string {
return typeof value === "string";
}
-function activityMessageText(record: TeamHubMessageActivityRecord) {
+export function activityMessageText(record: TeamHubMessageActivityRecord) {
const payload = nativePayload(record);
return (
stringValue(payload?.message) ??
@@ -277,7 +277,7 @@ function activityMessageText(record: TeamHubMessageActivityRecord) {
);
}
-function nativePayload(record: TeamHubMessageActivityRecord) {
+export function nativePayload(record: TeamHubMessageActivityRecord) {
const nativeRecord = asObject(record.native_record);
return (
asObject(nativeRecord?.payload) ??
@@ -303,7 +303,7 @@ function claudeBlockCategory(type: unknown): HistoryCategory | undefined {
}
}
-function claudeActivityRecords(
+export function claudeActivityRecords(
record: TeamHubMessageActivityRecord,
): TeamHubMessageActivityRecord[] {
const blocks = claudeMessageBlocks(record);
@@ -325,7 +325,7 @@ function claudeActivityRecords(
});
}
-function reasoningText(
+export function reasoningText(
record: TeamHubMessageActivityRecord,
): string | undefined {
const payload = nativePayload(record);
@@ -339,7 +339,7 @@ function reasoningText(
return stringValue(payload?.text) ?? textContent(payload?.summary);
}
-function nativeContentBlock(
+export function nativeContentBlock(
record: TeamHubMessageActivityRecord,
payload: JsonObject | undefined,
) {
@@ -371,17 +371,17 @@ function nativeContentBlock(
}
}
-function isUserMessage(record: TeamHubMessageActivityRecord) {
+export function isUserMessage(record: TeamHubMessageActivityRecord) {
return record.role === "user" || record.native_type.endsWith(".user_message");
}
-function isAssistantMessage(record: TeamHubMessageActivityRecord) {
+export function isAssistantMessage(record: TeamHubMessageActivityRecord) {
return (
record.role === "assistant" || record.native_type.endsWith(".agent_message")
);
}
-function isEventRecord(record: TeamHubMessageActivityRecord) {
+export function isEventRecord(record: TeamHubMessageActivityRecord) {
return record.native_type.startsWith("event_msg.");
}
@@ -399,7 +399,7 @@ function collectText(value: unknown): string[] {
return object.content === undefined ? [] : collectText(object.content);
}
-function indexToolCalls(records: TeamHubMessageActivityRecord[]) {
+export function indexToolCalls(records: TeamHubMessageActivityRecord[]) {
const candidates = new Map<
string,
{
@@ -449,7 +449,7 @@ function indexToolCalls(records: TeamHubMessageActivityRecord[]) {
type JsonObject = Record<string, unknown>;
-interface ToolCallPair {
+export interface ToolCallPair {
readonly call?: TeamHubMessageActivityRecord;
readonly result?: TeamHubMessageActivityRecord;
}
@@ -483,12 +483,12 @@ function claudeThinkingSummary(block: JsonObject): string | undefined {
);
}
-function asObject(value: unknown): JsonObject | undefined {
+export function asObject(value: unknown): JsonObject | undefined {
return typeof value === "object" && value !== null && !Array.isArray(value)
? (value as JsonObject)
: undefined;
}
-function stringValue(value: unknown) {
+export function stringValue(value: unknown) {
return typeof value === "string" && value.length > 0 ? value : undefined;
}
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsx
new file mode 100644
index 00000000..b83f31ab
--- /dev/null
+++ b/apps/web/src/features/rooms/task-sidebar/adapters/runtime-trajectory-view.tsx
@@ -0,0 +1,276 @@
+import { ChevronRight, Sparkles } from "lucide-react";
+import { useMemo } from "react";
+
+import { toolPresentation } from "@/features/rooms/runtime-status/runtime-tool-presentation";
+
+import type { TeamHubMessageActivityRecord } from "@/features/teamhub/teamhub-types";
+
+import { MessageMarkdown } from "../../chat/message-markdown";
+import {
+ activityMessageText,
+ asObject,
+ claudeActivityRecords,
+ indexToolCalls,
+ isAssistantMessage,
+ isEventRecord,
+ nativeCommand,
+ nativeContentBlock,
+ nativeOutput,
+ nativePayload,
+ parseObject,
+ reasoningText,
+ stringValue,
+ type ToolCallPair,
+} from "./runtime-history-view";
+
+type TrajectoryItem =
+ | { key: string; kind: "reasoning"; text: string }
+ | { key: string; kind: "reply"; text: string }
+ | { key: string; kind: "call"; call: TrajectoryCall };
+
+interface TrajectoryCall {
+ /** What the call acted on: a command, a path, a query. */
+ detail: string;
+ /** The full input, when it says more than the detail. */
+ input?: string;
+ /** The Runtime-neutral tool kind that picks the row's icon. */
+ kind: string;
+ output?: string;
+ /** A patch's lines, coloured as a diff. */
+ patch?: string;
+ pending: boolean;
+ verb: string;
+}
+
+/**
+ * A Runtime's native turn, one row per step: what it thought, each command
+ * or tool call with what it acted on, and what it replied. A call opens to
+ * its full input and output.
+ */
+export function RuntimeTrajectoryView({
+ records,
+}: {
+ records: TeamHubMessageActivityRecord[];
+}) {
+ const items = useMemo(() => trajectoryItems(records), [records]);
+ return (
+ <ol
+ aria-label="Activity log"
+ className="space-y-1 text-xs leading-5 font-normal text-app-body"
+ >
+ {items.map((item) =>
+ item.kind === "reasoning" ? (
+ <li
+ className="flex min-h-8 items-start gap-2 py-1.5 text-app-muted"
+ key={item.key}
+ >
+ <Sparkles
+ aria-hidden="true"
+ className="mt-0.5 shrink-0"
+ size={15}
+ />
+ <p className="min-w-0 flex-1">{item.text}</p>
+ </li>
+ ) : item.kind === "reply" ? (
+ <li className="py-2" key={item.key}>
+ <div className="room-message-bubble text-[15px] leading-[22px] text-app-ink">
+ <MessageMarkdown authorKind="agent" body={item.text} />
+ </div>
+ </li>
+ ) : (
+ <TrajectoryCallRow call={item.call} key={item.key} />
+ ),
+ )}
+ </ol>
+ );
+}
+
+function TrajectoryCallRow({ call }: { call: TrajectoryCall }) {
+ const { icon: ToolIcon } = toolPresentation(call.kind);
+ const output = call.patch ?? call.output;
+ const label = (
+ <span
+ className={`min-w-0 flex-1 truncate ${call.pending ? "town-shimmer-text" : ""}`}
+ title={`${call.verb} ${call.detail}`}
+ >
+ {call.verb} <span className="text-app-body">{call.detail}</span>
+ </span>
+ );
+ if (!output && !call.input)
+ return (
+ <li className="flex min-h-8 items-center gap-2 py-1.5 text-app-muted">
+ <ToolIcon aria-hidden="true" className="shrink-0" size={15} />
+ {label}
+ </li>
+ );
+ return (
+ <li>
+ <details className="group">
+ <summary className="flex min-h-8 cursor-pointer list-none items-center gap-2 py-1.5 text-app-muted hover:text-app-body focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-app-focus [&::-webkit-details-marker]:hidden">
+ <span className="relative inline-flex size-[15px] shrink-0 items-center justify-center">
+ <ToolIcon
+ aria-hidden="true"
+ className="absolute inset-0 m-auto group-hover:hidden group-focus-within:hidden group-open:hidden"
+ size={15}
+ />
+ <ChevronRight
+ aria-hidden="true"
+ className="absolute inset-0 m-auto hidden group-hover:block group-focus-within:block group-open:block group-open:rotate-90 motion-reduce:transition-none"
+ size={15}
+ />
+ </span>
+ {label}
+ </summary>
+ <div className="space-y-2 pb-2 pl-[1.45rem]">
+ {call.input ? (
+ <TrajectoryText label="Input" text={call.input} />
+ ) : null}
+ {output ? (
+ <TrajectoryText
+ diff={Boolean(call.patch)}
+ label={call.patch ? "Changes" : "Output"}
+ text={output}
+ />
+ ) : null}
+ </div>
+ </details>
+ </li>
+ );
+}
+
+function TrajectoryText({
+ diff = false,
+ label,
+ text,
+}: {
+ diff?: boolean;
+ label: string;
+ text: string;
+}) {
+ return (
+ <section aria-label={label}>
+ <p className="pb-1 text-app-muted">{label}</p>
+ <pre className="workspace-scrollbar max-h-72 overflow-auto rounded-md bg-app-surface-soft px-3 py-2 font-mono text-[11px] leading-[17px] whitespace-pre-wrap break-words text-app-body">
+ {diff
+ ? text.split("\n").map((line, index) => (
+ <span className={`block ${diffTone(line)}`} key={index}>
+ {line || " "}
+ </span>
+ ))
+ : text.replace(/\n+$/, "")}
+ </pre>
+ </section>
+ );
+}
+
+function diffTone(line: string) {
+ if (line.startsWith("+") && !line.startsWith("+++"))
+ return "text-app-success";
+ if (line.startsWith("-") && !line.startsWith("---")) return "text-app-danger";
+ return "";
+}
+
+function trajectoryItems(
+ records: TeamHubMessageActivityRecord[],
+): TrajectoryItem[] {
+ const ordered = [...records]
+ .sort((left, right) => left.ordinal - right.ordinal)
+ .flatMap(claudeActivityRecords);
+ const pairs = indexToolCalls(ordered);
+ const items: TrajectoryItem[] = [];
+ const seenReasoning = new Set<string>();
+ for (const record of ordered) {
+ const key = `${record.ordinal}:${items.length}`;
+ if (record.category === "reasoning") {
+ const text = reasoningText(record)
+ ?.replace(/^\*\*([\s\S]+)\*\*$/, "$1")
+ .trim();
+ if (!text || seenReasoning.has(text)) continue;
+ seenReasoning.add(text);
+ items.push({ key, kind: "reasoning", text });
+ } else if (
+ record.category === "message" &&
+ isAssistantMessage(record) &&
+ !isEventRecord(record)
+ ) {
+ items.push({ key, kind: "reply", text: activityMessageText(record) });
+ } else if (record.category === "tool_call") {
+ const pair = record.tool_call_id
+ ? pairs.get(record.tool_call_id)
+ : undefined;
+ items.push({ call: trajectoryCall(record, pair), key, kind: "call" });
+ }
+ }
+ return items;
+}
+
+/** Names a call by what its tool does, from the tool's own name and input. */
+function trajectoryCall(
+ record: TeamHubMessageActivityRecord,
+ pair: ToolCallPair | undefined,
+): TrajectoryCall {
+ const payload = nativePayload(record);
+ const block = nativeContentBlock(record, payload);
+ const name =
+ record.tool_name ?? stringValue(block?.name) ?? stringValue(payload?.name);
+ const rawInput =
+ stringValue(payload?.input) ?? stringValue(payload?.arguments);
+ const args =
+ asObject(block?.input) ?? parseObject(payload?.arguments) ?? undefined;
+ const output = pair?.result ? nativeOutput(pair.result) : undefined;
+ const base = { output, pending: !pair?.result };
+ const tool = (name ?? "tool").toLowerCase();
+ const command = nativeCommand(record);
+ if (command && /^(exec_command|shell|local_shell|bash)$/.test(tool))
+ return { ...base, detail: command, kind: "command", verb: "Ran" };
+ const path = stringValue(args?.path ?? args?.file_path ?? args?.filePath);
+ if (/^(read_file|read|view)$/.test(tool) && path)
+ return { ...base, detail: path, kind: "read", verb: "Read" };
+ const patch =
+ tool === "apply_patch" ? (stringValue(args?.input) ?? rawInput) : undefined;
+ if (patch !== undefined)
+ return {
+ ...base,
+ detail: patchFiles(patch) || "files",
+ // The envelope only repeats the file names the row already shows.
+ patch: patch
+ .split("\n")
+ .filter(
+ (line) =>
+ !/^\*\*\* (Begin Patch|End Patch|Add File:|Update File:|Delete File:)|^@@$/.test(
+ line,
+ ),
+ )
+ .join("\n"),
+ kind: "file_change",
+ verb: "Edited",
+ };
+ if (/^(edit|write|multiedit|str_replace_based_edit_tool)$/.test(tool) && path)
+ return {
+ ...base,
+ detail: path,
+ input: JSON.stringify(args, null, 2),
+ kind: "file_change",
+ verb: "Edited",
+ };
+ const query = stringValue(args?.query);
+ if (/^(web_search|websearch)$/.test(tool) && query)
+ return { ...base, detail: query, kind: "search", verb: "Searched" };
+ const url = stringValue(args?.url);
+ if (/^(web_fetch|webfetch)$/.test(tool) && url)
+ return { ...base, detail: url, kind: "browse", verb: "Fetched" };
+ const input = args ? JSON.stringify(args, null, 2) : rawInput;
+ return {
+ ...base,
+ detail: name ?? "tool",
+ ...(input ? { input } : {}),
+ kind: "tool",
+ verb: "Called",
+ };
+}
+
+function patchFiles(patch: string) {
+ return [...patch.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)]
+ .map((match) => match[1]!.trim())
+ .join(", ");
+}
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx
index 7310aa9a..6e4e2405 100644
--- a/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx
+++ b/apps/web/src/features/rooms/task-sidebar/adapters/task-activities-panel-tab.tsx
@@ -41,26 +41,8 @@ export function TaskActivitiesPanelTab({
tenantId: string;
title?: string;
}) {
- const data = useTaskActivities({ tenantId, taskId, enabled: !hidden });
- const { client } = useTeamHubRuntime();
- const messages = useInfiniteQuery({
- ...roomMessagesInfiniteQueryOptions(client, tenantId, data.roomId ?? ""),
- enabled: !hidden && Boolean(data.roomId),
- refetchInterval:
- !hidden && data.roomId && !taskExecutionStopped(data.execution.data)
- ? 2_000
- : false,
- });
- const publicMessages =
- messages.data?.pages.flatMap((page) => page.items) ?? [];
- const execution = data.execution.data;
- const stopped = taskExecutionStopped(execution);
- const refresh = () => {
- void data.item.refetch();
- void data.execution.refetch();
- void data.activities.refetch();
- if (data.roomId) void messages.refetch();
- };
+ const view = useTaskActivityView({ hidden, taskId, tenantId });
+ const { data, execution, refresh } = view;
return (
<section
className={hidden ? "hidden" : "flex h-full min-h-0 flex-col bg-card"}
@@ -100,54 +82,101 @@ export function TaskActivitiesPanelTab({
</button>
</header>
<div className="workspace-scrollbar min-h-0 flex-1 overflow-y-auto">
- {data.activities.error ? (
- <State>
- {isTaskActivityNotFound(data.activities.error)
- ? "You do not have access to this task’s work room activity."
- : "Activity could not be loaded. Try refreshing."}
- </State>
- ) : data.activities.isPending ? (
- <State busy>Loading activity…</State>
- ) : (
- <>
- {data.roomId && !data.connected ? (
- <State>Reconnecting to live activity…</State>
- ) : null}
- {!data.runStatuses.length ? <State>No activity yet.</State> : null}
- {data.roomId
- ? data.runStatuses.map((runStatus) => (
- <TaskActivityGroup
- key={runStatus.id}
- runStatus={runStatus}
- tenantId={tenantId}
- roomId={data.roomId!}
- visible={!hidden}
- stopped={stopped}
- paused={execution?.status === "waiting_for_approval"}
- messages={publicMessages}
- labeled={data.runStatuses.length > 1}
- />
- ))
- : null}
- {data.activities.hasNextPage ? (
- <div className="px-4 py-3">
- <Button
- size="compact"
- tone="ghost"
- disabled={data.activities.isFetchingNextPage}
- onClick={() => void data.activities.fetchNextPage()}
- >
- Load earlier activity
- </Button>
- </div>
- ) : null}
- </>
- )}
+ <TaskActivityRuns hidden={hidden} tenantId={tenantId} view={view} />
</div>
</section>
);
}
+export function useTaskActivityView({
+ hidden,
+ taskId,
+ tenantId,
+}: {
+ hidden: boolean;
+ taskId: string;
+ tenantId: string;
+}) {
+ const data = useTaskActivities({ tenantId, taskId, enabled: !hidden });
+ const { client } = useTeamHubRuntime();
+ const messages = useInfiniteQuery({
+ ...roomMessagesInfiniteQueryOptions(client, tenantId, data.roomId ?? ""),
+ enabled: !hidden && Boolean(data.roomId),
+ refetchInterval:
+ !hidden && data.roomId && !taskExecutionStopped(data.execution.data)
+ ? 2_000
+ : false,
+ });
+ const refresh = () => {
+ void data.item.refetch();
+ void data.execution.refetch();
+ void data.activities.refetch();
+ if (data.roomId) void messages.refetch();
+ };
+ return {
+ data,
+ execution: data.execution.data,
+ messages: messages.data?.pages.flatMap((page) => page.items) ?? [],
+ refresh,
+ };
+}
+
+function TaskActivityRuns({
+ hidden,
+ tenantId,
+ view: { data, execution, messages },
+}: {
+ hidden: boolean;
+ tenantId: string;
+ view: ReturnType<typeof useTaskActivityView>;
+}) {
+ const stopped = taskExecutionStopped(execution);
+ if (data.activities.error)
+ return (
+ <State>
+ {isTaskActivityNotFound(data.activities.error)
+ ? "You do not have access to this task’s work room activity."
+ : "Activity could not be loaded. Try refreshing."}
+ </State>
+ );
+ if (data.activities.isPending) return <State busy>Loading activity…</State>;
+ return (
+ <>
+ {data.roomId && !data.connected ? (
+ <State>Reconnecting to live activity…</State>
+ ) : null}
+ {!data.runStatuses.length ? <State>No activity yet.</State> : null}
+ {data.roomId
+ ? data.runStatuses.map((runStatus) => (
+ <TaskActivityGroup
+ key={runStatus.id}
+ runStatus={runStatus}
+ tenantId={tenantId}
+ roomId={data.roomId!}
+ visible={!hidden}
+ stopped={stopped}
+ paused={execution?.status === "waiting_for_approval"}
+ messages={messages}
+ labeled={data.runStatuses.length > 1}
+ />
+ ))
+ : null}
+ {data.activities.hasNextPage ? (
+ <div className="px-4 py-3">
+ <Button
+ size="compact"
+ tone="ghost"
+ disabled={data.activities.isFetchingNextPage}
+ onClick={() => void data.activities.fetchNextPage()}
+ >
+ Load earlier activity
+ </Button>
+ </div>
+ ) : null}
+ </>
+ );
+}
+
/** One run of the Task; a Task resumed more than once labels each run. */
function TaskActivityGroup({
runStatus,
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/task-activity-drill-down.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/task-activity-drill-down.tsx
deleted file mode 100644
index e76f7eef..00000000
--- a/apps/web/src/features/rooms/task-sidebar/adapters/task-activity-drill-down.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { useState, type ReactNode } from "react";
-
-import { TaskActivityLinksProvider } from "../../runtime-status/task-activity-block";
-import { TaskActivitiesPanelTab } from "./task-activities-panel-tab";
-
-/**
- * Lets the task blocks in an activity log open their Task's activity in
- * place, with a way back, instead of in another panel tab.
- */
-export function TaskActivityDrillDown({
- children,
- hidden,
- tenantId,
-}: {
- children: ReactNode;
- hidden: boolean;
- tenantId: string;
-}) {
- const [task, setTask] = useState<{ id: string; title: string }>();
- return (
- <TaskActivityLinksProvider
- openTask={(id, title) => setTask({ id, title })}
- tenantId={tenantId}
- >
- <div className={task ? "hidden" : "contents"}>{children}</div>
- {task ? (
- <TaskActivitiesPanelTab
- hidden={hidden}
- onBack={() => setTask(undefined)}
- taskId={task.id}
- tenantId={tenantId}
- title={task.title}
- />
- ) : null}
- </TaskActivityLinksProvider>
- );
-}
diff --git a/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsx b/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsx
new file mode 100644
index 00000000..89d07088
--- /dev/null
+++ b/apps/web/src/features/rooms/task-sidebar/adapters/task-conversation-dialog.tsx
@@ -0,0 +1,358 @@
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { useMemo, useState, type ReactNode } from "react";
+
+import { ModalDialog } from "@/components/ui/modal-dialog";
+import { StatusPill } from "@/components/ui/status-pill";
+import { teamHubData } from "@/features/teamhub/teamhub-api";
+import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
+import type {
+ TeamHubRunStatus,
+ TeamHubTaskExecution,
+} from "@/features/teamhub/teamhub-types";
+
+import { MessageMarkdown } from "../../chat/message-markdown";
+import { createRoomCardDecisionController } from "../../cards/room-card-decision-controller";
+import {
+ knownRoomMessageCard,
+ RoomMessageCard,
+} from "../../cards/room-message-card";
+import { ActorAvatar } from "../../members/actor-avatar";
+import { teamHubIdentityQueryOptions } from "../../room-queries";
+import { RuntimeActivityPath } from "../../runtime-status/runtime-activity-path-view";
+import { TaskActivityLinksProvider } from "../../runtime-status/task-activity-block";
+import { useTaskActivityEvents } from "../../runtime-status/use-task-activity-events";
+import { PanelLoading } from "../panel-loading";
+import { RuntimeTrajectoryView } from "./runtime-trajectory-view";
+import { useTaskActivityView } from "./task-activities-panel-tab";
+
+/** Lets the task blocks in an activity log open their Task's conversation. */
+export function TaskConversationProvider({
+ children,
+ tenantId,
+}: {
+ children: ReactNode;
+ tenantId: string;
+}) {
+ const [task, setTask] = useState<{ id: string; title: string }>();
+ return (
+ <TaskActivityLinksProvider
+ openTask={(id, title) => setTask({ id, title })}
+ tenantId={tenantId}
+ >
+ {children}
+ {task ? (
+ <TaskConversationDialog
+ onClose={() => setTask(undefined)}
+ taskId={task.id}
+ tenantId={tenantId}
+ title={task.title}
+ />
+ ) : null}
+ </TaskActivityLinksProvider>
+ );
+}
+
+/**
+ * A Task, read like a Room: the Meta's brief and follow-ups on the right, and
+ * on the left everything its AlterEgo thought, ran and replied, with the cards
+ * it raised, answerable here.
+ */
+function TaskConversationDialog({
+ onClose,
+ taskId,
+ tenantId,
+ title,
+}: {
+ onClose: () => void;
+ taskId: string;
+ tenantId: string;
+ title: string;
+}) {
+ const { client } = useTeamHubRuntime();
+ const { data, execution } = useTaskActivityView({
+ hidden: false,
+ taskId,
+ tenantId,
+ });
+ const live =
+ execution?.status === "running" ||
+ execution?.status === "waiting_for_approval";
+ const conversation = useQuery({
+ queryKey: ["teamhub", tenantId, "task-conversation", taskId],
+ queryFn: () =>
+ teamHubData(
+ client.api.GET("/v0/tasks/{taskId}/conversation", {
+ params: { path: { taskId } },
+ }),
+ ),
+ refetchInterval: live ? 3_000 : false,
+ });
+ const entries = useMemo(
+ () =>
+ [
+ ...(conversation.data?.inputs ?? []).map((input) => ({
+ at: input.created_at,
+ input,
+ key: `input:${input.id}`,
+ kind: "input" as const,
+ })),
+ ...data.runStatuses.map((runStatus) => ({
+ at: runStatus.created_at,
+ key: `run:${runStatus.id}`,
+ kind: "run" as const,
+ runStatus,
+ })),
+ ...(conversation.data?.cards ?? []).map((card) => ({
+ at: card.created_at,
+ card,
+ key: `card:${card.decision_id}`,
+ kind: "card" as const,
+ })),
+ ].sort((a, b) => a.at.localeCompare(b.at)),
+ [conversation.data, data.runStatuses],
+ );
+ const stopped =
+ execution?.status === "canceled" || execution?.status === "failed";
+ return (
+ <ModalDialog
+ closeOnBackdrop
+ description={
+ execution ? <TaskConversationState execution={execution} /> : undefined
+ }
+ onClose={onClose}
+ size="lg"
+ title={title}
+ >
+ <div
+ aria-label="Task conversation"
+ className="flex min-h-64 flex-col gap-3 px-5 py-4 text-[15px] leading-[22px]"
+ role="log"
+ >
+ {conversation.isPending || data.activities.isPending ? (
+ <PanelLoading label="Loading task" />
+ ) : (
+ entries.map((entry) =>
+ entry.kind === "input" ? (
+ entry.input.source === "system" ? (
+ <p
+ className="px-12 text-center text-xs text-app-muted"
+ key={entry.key}
+ >
+ {entry.input.body}
+ </p>
+ ) : (
+ <div
+ className="room-message-card pl-12"
+ data-current-actor="true"
+ key={entry.key}
+ >
+ <div className="room-message-bubble max-w-[85%]">
+ <MessageMarkdown
+ authorKind={entry.input.author.kind}
+ body={entry.input.body}
+ />
+ </div>
+ </div>
+ )
+ ) : entry.kind === "run" ? (
+ <TaskConversationRun
+ key={entry.key}
+ paused={execution?.status === "waiting_for_approval"}
+ roomId={data.roomId ?? ""}
+ runStatus={entry.runStatus}
+ stopped={stopped}
+ tenantId={tenantId}
+ />
+ ) : (
+ <div className="pr-12 pl-11" key={entry.key}>
+ <TaskApprovalCard
+ messageId={entry.card.message_id}
+ roomId={entry.card.room_id}
+ tenantId={tenantId}
+ />
+ </div>
+ ),
+ )
+ )}
+ </div>
+ </ModalDialog>
+ );
+}
+
+/** One AlterEgo turn, step by step: its own history, or live progress. */
+function TaskConversationRun({
+ paused,
+ roomId,
+ runStatus,
+ stopped,
+ tenantId,
+}: {
+ paused: boolean;
+ roomId: string;
+ runStatus: TeamHubRunStatus;
+ stopped: boolean;
+ tenantId: string;
+}) {
+ const { client } = useTeamHubRuntime();
+ const active = runStatus.status === "active" && !stopped;
+ const history = useQuery({
+ enabled: Boolean(roomId),
+ queryKey: [
+ "teamhub",
+ tenantId,
+ "rooms",
+ roomId,
+ "runs",
+ runStatus.id,
+ "activities",
+ ],
+ queryFn: () =>
+ teamHubData(
+ client.api.GET("/v0/rooms/{roomId}/runs/{runId}/activities", {
+ params: { path: { roomId, runId: runStatus.run_id } },
+ }),
+ ),
+ retry: false,
+ refetchInterval: active ? 1_500 : false,
+ });
+ // Native history may lag a live turn; its published steps stand in.
+ const native = history.data?.status === "available" && history.data.records;
+ const events = useTaskActivityEvents({
+ tenantId,
+ roomId,
+ runStatusId: runStatus.id,
+ revision: runStatus.revision,
+ enabled: Boolean(roomId) && !native && !history.isPending,
+ });
+ const interrupted =
+ (runStatus.status === "aborted" &&
+ runStatus.stop_reason !== "task_terminal") ||
+ (runStatus.status === "active" && stopped);
+ return (
+ <div className="flex gap-2 pr-12">
+ <ActorAvatar
+ actorId={runStatus.agent.id}
+ kind="agent"
+ name={runStatus.agent.display_name}
+ size="sm"
+ />
+ <div className="min-w-0 flex-1">
+ <p className="mb-1 text-sm text-app-ink">
+ {runStatus.agent.display_name}
+ </p>
+ {native ? (
+ <RuntimeTrajectoryView records={native} />
+ ) : events.data ? (
+ <div className="[&_ol]:px-0 [&_ol]:py-1">
+ <RuntimeActivityPath
+ embedded
+ lifecycle={
+ active
+ ? paused
+ ? "paused"
+ : "active"
+ : interrupted
+ ? "interrupted"
+ : "ended"
+ }
+ messages={[]}
+ records={events.data.items}
+ />
+ </div>
+ ) : (
+ <PanelLoading label="Loading activity" />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** A card the AlterEgo raised, answered here as in its Room. */
+/**
+ * A card the Task's AlterEgo raised. The card itself is a Message in the Room
+ * that delegated the Task; it is answerable here too.
+ */
+function TaskApprovalCard({
+ messageId,
+ roomId,
+ tenantId,
+}: {
+ messageId: string;
+ roomId: string;
+ tenantId: string;
+}) {
+ const { client } = useTeamHubRuntime();
+ const queryClient = useQueryClient();
+ const queryKey = [
+ "teamhub",
+ tenantId,
+ "rooms",
+ roomId,
+ "messages",
+ messageId,
+ ];
+ const message = useQuery({
+ queryKey,
+ queryFn: () =>
+ teamHubData(
+ client.api.GET("/v0/rooms/{roomId}/messages/{messageId}", {
+ params: { path: { roomId, messageId } },
+ }),
+ ),
+ retry: false,
+ });
+ const controller = useMemo(
+ () =>
+ createRoomCardDecisionController({
+ client,
+ onResolved: (resolved) => {
+ queryClient.setQueryData(queryKey, resolved);
+ void queryClient.invalidateQueries({
+ queryKey: ["teamhub", tenantId, "task-conversation"],
+ });
+ },
+ roomId,
+ tenantId,
+ }),
+ // queryKey is rebuilt from these same values on every render.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [client, queryClient, roomId, tenantId, messageId],
+ );
+ const identity = useQuery(teamHubIdentityQueryOptions(client));
+ const currentActorId = identity.data?.actors.find(
+ (actor) => actor.tenant_id === tenantId,
+ )?.id;
+ const card = knownRoomMessageCard(message.data?.card);
+ if (!card) return null;
+ return (
+ <RoomMessageCard
+ card={card}
+ currentActorId={currentActorId}
+ messageId={messageId}
+ onDecision={async (decision) => {
+ await controller.decide(decision);
+ }}
+ roomId={roomId}
+ tenantId={tenantId}
+ />
+ );
+}
+
+function TaskConversationState({
+ execution,
+}: {
+ execution: TeamHubTaskExecution;
+}) {
+ switch (execution.status) {
+ case "running":
+ return <StatusPill tone="neutral">Running</StatusPill>;
+ case "waiting_for_approval":
+ return <StatusPill tone="warning">Needs approval</StatusPill>;
+ case "idle":
+ return <StatusPill tone="success">Reported</StatusPill>;
+ case "failed":
+ return <StatusPill tone="danger">Failed</StatusPill>;
+ case "canceled":
+ return <StatusPill>Stopped</StatusPill>;
+ }
+}
diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.go
index 25c4d89f..65c78280 100644
--- a/contracts/generated/go/teamhubpublic/openapi.gen.go
+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go
@@ -2924,6 +2924,24 @@ func (e TaskAttemptSummaryStatus) Valid() bool {
}
}
+// Defines values for TaskConversationInputSource.
+const (
+ TaskConversationInputSourceMessage TaskConversationInputSource = "message"
+ TaskConversationInputSourceSystem TaskConversationInputSource = "system"
+)
+
+// Valid indicates whether the value is a known member of the TaskConversationInputSource enum.
+func (e TaskConversationInputSource) Valid() bool {
+ switch e {
+ case TaskConversationInputSourceMessage:
+ return true
+ case TaskConversationInputSourceSystem:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for TaskExecutionProjectionDesiredControl.
const (
TaskExecutionProjectionDesiredControlRun TaskExecutionProjectionDesiredControl = "run"
@@ -7334,6 +7352,45 @@ type TaskAttemptSummary struct {
// TaskAttemptSummaryStatus defines model for TaskAttemptSummary.Status.
type TaskAttemptSummaryStatus string
+// TaskConversation defines model for TaskConversation.
+type TaskConversation struct {
+ Cards []TaskConversationCard `json:"cards"`
+ Inputs []TaskConversationInput `json:"inputs"`
+}
+
+// TaskConversationCard defines model for TaskConversationCard.
+type TaskConversationCard struct {
+ // CreatedAt UTC timestamp in RFC 3339 format with an explicit offset.
+ CreatedAt Timestamp `json:"created_at"`
+
+ // DecisionId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ DecisionId Id `json:"decision_id"`
+
+ // MessageId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ MessageId Id `json:"message_id"`
+
+ // RoomId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ RoomId Id `json:"room_id"`
+}
+
+// TaskConversationInput defines model for TaskConversationInput.
+type TaskConversationInput struct {
+ Author ActorRef `json:"author"`
+ Body string `json:"body"`
+
+ // CreatedAt UTC timestamp in RFC 3339 format with an explicit offset.
+ CreatedAt Timestamp `json:"created_at"`
+
+ // Id Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ Id Id `json:"id"`
+
+ // Source A message from the Meta or a person, or a system notice such as a card's result.
+ Source TaskConversationInputSource `json:"source"`
+}
+
+// TaskConversationInputSource A message from the Meta or a person, or a system notice such as a card's result.
+type TaskConversationInputSource string
+
// TaskExecutionProjection Human-safe current Task execution projection. It excludes Worker leases, effect payloads, and participant Local Run references.
type TaskExecutionProjection struct {
ControlRevision int64 `json:"control_revision"`
diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
index 96570ffa..104831e2 100644
--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
@@ -1169,7 +1169,7 @@ export interface paths {
};
/**
* Get the exact sanitized Runtime activity log for an Agent Message.
- * @description Authorizes the committed Message through ordinary Room membership, resolves its source Runtime run, and returns only records linked to that run by Activity identity. Task runs return unavailable; their public activities use Runtime presentation events.
+ * @description Authorizes the committed Message through ordinary Room membership, resolves its source Runtime run, and returns only records linked to that run by Activity identity.
*/
get: operations["getMessageActivities"];
put?: never;
@@ -1367,7 +1367,7 @@ export interface paths {
};
/**
* Read sanitized native execution history of an Agent Run shown in a Room.
- * @description Requires ordinary Room membership. Resolves native turns only through trusted invocation identities in persisted Runtime events. History may be unavailable until the Run has recorded such an identity. Task runs always return unavailable; use their public Runtime presentation events.
+ * @description Requires ordinary Room membership. Resolves native turns only through trusted invocation identities in persisted Runtime events. History may be unavailable until the Run has recorded such an identity. A Task Run reads its AlterEgo's history.
*/
get: operations["getRunActivities"];
put?: never;
@@ -3396,6 +3396,28 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/v0/tasks/{taskId}/conversation": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ taskId: components["schemas"]["Id"];
+ };
+ cookie?: never;
+ };
+ /**
+ * Read what a Task's Agent was told and the cards it raised.
+ * @description Returns the inputs the Task's own Agent received in its current generation, in delivery order, and every card its AlterEgo raised. Each card is read through its Message in the card's Room. The Agent's own steps come from each Run's activities.
+ */
+ get: operations["getTaskConversation"];
+ put?: never;
+ post?: never;
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v0/work-items/{workItemId}/archive": {
parameters: {
query?: never;
@@ -7138,6 +7160,27 @@ export interface components {
current_attempt?: components["schemas"]["TaskAttemptSummary"];
execution_updated_at: components["schemas"]["Timestamp"];
};
+ TaskConversationInput: {
+ id: components["schemas"]["Id"];
+ author: components["schemas"]["ActorRef"];
+ body: string;
+ /**
+ * @description A message from the Meta or a person, or a system notice such as a card's result.
+ * @enum {string}
+ */
+ source: "message" | "system";
+ created_at: components["schemas"]["Timestamp"];
+ };
+ TaskConversationCard: {
+ decision_id: components["schemas"]["Id"];
+ room_id: components["schemas"]["Id"];
+ message_id: components["schemas"]["Id"];
+ created_at: components["schemas"]["Timestamp"];
+ };
+ TaskConversation: {
+ inputs: components["schemas"]["TaskConversationInput"][];
+ cards: components["schemas"]["TaskConversationCard"][];
+ };
WorkItemVersionRequest: {
/** Format: int64 */
expected_version: number;
@@ -13433,6 +13476,30 @@ export interface operations {
404: components["responses"]["NotFound"];
};
};
+ getTaskConversation: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ taskId: components["schemas"]["Id"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Task inputs and cards. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["TaskConversation"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ };
+ };
archiveWorkItem: {
parameters: {
query?: never;
diff --git a/contracts/openapi/components/task-executions.yaml b/contracts/openapi/components/task-executions.yaml
index 4c780abe..f905c944 100644
--- a/contracts/openapi/components/task-executions.yaml
+++ b/contracts/openapi/components/task-executions.yaml
@@ -91,6 +91,56 @@ components:
$ref: "./common.yaml#/components/schemas/Timestamp"
finished_at:
$ref: "./common.yaml#/components/schemas/Timestamp"
+ TaskConversation:
+ type: object
+ additionalProperties: false
+ required: [inputs, cards]
+ properties:
+ inputs:
+ type: array
+ maxItems: 500
+ items:
+ $ref: "#/components/schemas/TaskConversationInput"
+ cards:
+ type: array
+ maxItems: 200
+ items:
+ $ref: "#/components/schemas/TaskConversationCard"
+ TaskConversationInput:
+ type: object
+ additionalProperties: false
+ required: [id, author, body, source, created_at]
+ properties:
+ id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ author:
+ $ref: "./common.yaml#/components/schemas/ActorRef"
+ body:
+ type: string
+ minLength: 1
+ maxLength: 50000
+ source:
+ type: string
+ enum: [message, system]
+ description: A message from the Meta or a person, or a system notice such as a card's result.
+ x-enum-varnames:
+ - TaskConversationInputSourceMessage
+ - TaskConversationInputSourceSystem
+ created_at:
+ $ref: "./common.yaml#/components/schemas/Timestamp"
+ TaskConversationCard:
+ type: object
+ additionalProperties: false
+ required: [decision_id, room_id, message_id, created_at]
+ properties:
+ decision_id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ room_id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ message_id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ created_at:
+ $ref: "./common.yaml#/components/schemas/Timestamp"
TaskExecutionProjection:
type: object
additionalProperties: false
diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
index 40fdf1f5..8cb7519c 100644
--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
@@ -1679,7 +1679,6 @@ paths:
description: >-
Authorizes the committed Message through ordinary Room membership, resolves its source
Runtime run, and returns only records linked to that run by Activity identity.
- Task runs return unavailable; their public activities use Runtime presentation events.
responses:
'200':
description: Exact Message activity log or an explicit unavailable state.
@@ -1966,8 +1965,7 @@ paths:
description: >-
Requires ordinary Room membership. Resolves native turns only through trusted
invocation identities in persisted Runtime events. History may be unavailable
- until the Run has recorded such an identity.
- Task runs always return unavailable; use their public Runtime presentation events.
+ until the Run has recorded such an identity. A Task Run reads its AlterEgo's history.
responses:
'200':
description: Native execution records with explicit availability and truncation.
@@ -4257,6 +4255,32 @@ paths:
$ref: '../components/common.yaml#/components/responses/Unauthenticated'
'404':
$ref: '../components/common.yaml#/components/responses/NotFound'
+ /v0/tasks/{taskId}/conversation:
+ parameters:
+ - name: taskId
+ in: path
+ required: true
+ schema:
+ $ref: '../components/common.yaml#/components/schemas/Id'
+ get:
+ tags: [Work Items]
+ operationId: getTaskConversation
+ summary: Read what a Task's Agent was told and the cards it raised.
+ description: >-
+ Returns the inputs the Task's own Agent received in its current generation, in delivery order,
+ and every card its AlterEgo raised. Each card is read through its Message in the card's Room.
+ The Agent's own steps come from each Run's activities.
+ responses:
+ '200':
+ description: Task inputs and cards.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/task-executions.yaml#/components/schemas/TaskConversation'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
/v0/work-items/{workItemId}/archive:
parameters:
- $ref: '#/components/parameters/WorkItemId'