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.
fix(activities): read the whole Runtime turn a Run started
LeoXingfb2243573b93
diff --git a/apps/computer/local-daemon/internal/linger/runtimehistory/history.go b/apps/computer/local-daemon/internal/linger/runtimehistory/history.goindex aada5ac9..8c19bf67 100644--- a/apps/computer/local-daemon/internal/linger/runtimehistory/history.go+++ b/apps/computer/local-daemon/internal/linger/runtimehistory/history.go@@ -217,6 +217,7 @@ func inspect(ctx context.Context, request Request) (Page, error) {if len(records) == 0 || stringValue(records[0].original, "type", 256) != "session_meta" || stringValue(objectValue(records[0].original["payload"]), "id", 256) != request.ThreadID {return Page{}, fail("rollout_session_mismatch")}+ stampCodexTurns(records)capturedAt := ""end := len(records)if cursor != nil {@@ -334,6 +335,25 @@ func findRollout(ctx context.Context, home, threadID string) (string, string, erreturn matches[0], canonicalHome, nil}+// stampCodexTurns gives every record of a Codex turn that turn's ID. Codex+// writes turn_id only on its lifecycle and usage records, so the tool calls+// and replies between a turn's start and its end carry it forward.+func stampCodexTurns(records []parsedRecord) {+ turn := ""+ for i := range records {+ history := &records[i].history+ if history.TurnID != "" {+ turn = history.TurnID+ } else {+ history.TurnID = turn+ }+ switch stringValue(objectValue(records[i].original["payload"]), "type", 256) {+ case "task_complete", "turn_aborted":+ turn = ""+ }+ }+}+func readFrozen(path string, frozenBytes int) ([]byte, error) {file, err := openNoFollow(path)if err != nil {diff --git a/apps/computer/local-daemon/internal/linger/runtimehistory/history_test.go b/apps/computer/local-daemon/internal/linger/runtimehistory/history_test.goindex 3a0c9793..abe99c2a 100644--- a/apps/computer/local-daemon/internal/linger/runtimehistory/history_test.go+++ b/apps/computer/local-daemon/internal/linger/runtimehistory/history_test.go@@ -129,6 +129,35 @@ func TestInspectCategorizesCompactionRecords(t *testing.T) {}}+func TestInspectCarriesTurnIDToEveryRecordOfItsTurn(t *testing.T) {+ turnContext := record("turn_context", "", map[string]any{"turn_id": "turn-2"})+ delete(turnContext["payload"].(map[string]any), "type")+ home, _ := writeRollout(t, "thread-turns", []map[string]any{+ sessionMeta("thread-turns", ""),+ record("event_msg", "task_started", map[string]any{"turn_id": "turn-1"}),+ record("response_item", "custom_tool_call", map[string]any{"call_id": "call-1", "name": "exec"}),+ record("response_item", "custom_tool_call_output", map[string]any{"call_id": "call-1"}),+ record("response_item", "message", map[string]any{"role": "assistant"}),+ record("event_msg", "task_complete", map[string]any{"turn_id": "turn-1"}),+ record("event_msg", "thread_settings_applied", nil),+ turnContext,+ record("event_msg", "agent_message", map[string]any{"message": "reply only"}),+ record("event_msg", "turn_aborted", map[string]any{"turn_id": "turn-2"}),+ }, false, "")+ page := Inspect(context.Background(), Request{CodexHome: home, ThreadID: "thread-turns"})+ if page.Status != "available" {+ t.Fatalf("page = %#v", page)+ }+ var got []string+ for _, item := range page.Records {+ got = append(got, item.TurnID)+ }+ want := []string{"", "turn-1", "turn-1", "turn-1", "turn-1", "turn-1", "", "turn-2", "turn-2", "turn-2"}+ if strings.Join(got, ",") != strings.Join(want, ",") {+ t.Fatalf("turn IDs = %q, want %q", got, want)+ }+}+func TestInspectRejectsMismatchedAndAmbiguousRollouts(t *testing.T) {home, rollout := writeRollout(t, "thread-target", []map[string]any{sessionMeta("thread-wrong", "")}, false, "")mismatch := Inspect(context.Background(), Request{CodexHome: home, ThreadID: "thread-target"})diff --git a/apps/node-services/src/agent/main.ts b/apps/node-services/src/agent/main.tsindex d1c6e9b4..102d5c5f 100644--- a/apps/node-services/src/agent/main.ts+++ b/apps/node-services/src/agent/main.ts@@ -127,6 +127,7 @@ export async function startAgentService(run_id: record.runId,operation_id: record.operationId,runtime_type: record.runtimeType,+ ...(record.turnId ? { turn_id: record.turnId } : {}),...(record.usage ? { usage: [...record.usage] } : {}),});},diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway-context.tsindex f64f840c..a3bbf25b 100644--- a/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway-context.ts@@ -152,6 +152,8 @@ export interface RunnerRunOperationRecord {readonly runId: string;readonly operationId: string;readonly runtimeType: "codex" | "claude" | "pi";+ /** The Runtime turn the Operation started, once the Daemon reported it. */+ readonly turnId?: string;readonly usage?: readonly Record<string, unknown>[];}diff --git a/apps/node-services/src/agent/runner-gateway/runner-operation.ts b/apps/node-services/src/agent/runner-gateway/runner-operation.tsindex 20732a64..1f79ec53 100644--- a/apps/node-services/src/agent/runner-gateway/runner-operation.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-operation.ts@@ -250,6 +250,7 @@ export class RunnerOperationState {#startSentCount = 0;#inputReceiptTimer: ReturnType<typeof setTimeout> | undefined;#inputReceipts: Deferred<void> | undefined;+ #turnId: string | undefined;// Called after the operation.start frame is written to the Computer peer.// Replays on reconnect are later writes of the same frame.@@ -348,6 +349,11 @@ export class RunnerOperationState {: undefined;}+ /** The Runtime turn the Operation started, once the Daemon reports it. */+ get turnId(): string | undefined {+ return this.#turnId;+ }+/** The usage the Daemon reported with the terminal, when it reported one. */get usage(): readonly Record<string, unknown>[] | undefined {const outcome = this.#outcomeEnvelope;@@ -774,6 +780,8 @@ export class RunnerOperationState {case "operation.accepted":break;case "operation.event":+ if (envelope.event.type === "run.started")+ this.#turnId = envelope.event.turn_id;await this.#events.push(envelope.event);break;case "operation.input_result":diff --git a/apps/node-services/src/agent/runner-gateway/runner-operations.ts b/apps/node-services/src/agent/runner-gateway/runner-operations.tsindex e719254d..2ae99d87 100644--- a/apps/node-services/src/agent/runner-gateway/runner-operations.ts+++ b/apps/node-services/src/agent/runner-gateway/runner-operations.ts@@ -335,9 +335,9 @@ export class RunnerOperations {}/**- * Records a run.start Operation on its Run, and its usage once it ends.- * Message activities and usage totals read the record; the Run's own- * outcome never waits for it.+ * Records a run.start Operation on its Run, the Runtime turn it started, and+ * its usage once it ends. Message activities and usage totals read the+ * record; the Run's own outcome never waits for it.*/#recordRunOperation(operation: RunnerOperationState): void {const record = this.context.options.recordRunOperation;@@ -346,12 +346,14 @@ export class RunnerOperations {return;const usage = operation.terminal ? operation.usage : undefined;if (operation.terminal && !usage) return;+ const turnId = operation.turnId;void record({contextKey: operation.start.execution_context_key,epoch,runId: operation.start.request.run_context.execution_run_ref,operationId: operation.start.operation_id,runtimeType: operation.start.runtime_type,+ ...(turnId ? { turnId } : {}),...(usage ? { usage } : {}),}).catch((error: unknown) =>logAgentEvent("warn", "runner.operation.record_failed", {@@ -628,6 +630,15 @@ export class RunnerOperations {envelope.event.type === "model.responded")this.#observeModelResponse(operation, envelope.event);+ // The turn is recorded as soon as it starts, so a live Run's activities+ // can already read it.+ if (+ envelope.type === "operation.event" &&+ envelope.event.type === "run.started" &&+ operation.turnId !== undefined &&+ !operation.terminal+ )+ this.#recordRunOperation(operation);if (operation.terminal) this.#retireOperation(operation);if (acknowledgement)await this.owners.connections().send(connection, acknowledgement);diff --git a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.tsindex 586ccbce..b7730ba0 100644--- a/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts+++ b/apps/node-services/tests/agent/runner-gateway/runner-operations-public.test.ts@@ -94,6 +94,85 @@ describe("RunnerGateway", () => {await expect(operation.result).resolves.toMatchObject({ type: "run" });});+ it("records the Runtime turn a Run's Operation started as soon as it starts", async () => {+ const recordRunOperation = vi.fn(async () => {});+ const gateway = createTestRunnerGateway({+ heartbeatIntervalMs: 1_000,+ createId: sequenceIds(),+ recordRunOperation,+ });+ const peer = new RecordingPeer();+ const connection = await acceptReadyConnection(+ gateway,+ peer,+ contextHello(),+ defaultAgentPlacement({ workspaceGrantId: "grant-owner" }),+ );+ const operation = await gateway.startOperation({+ ...contextRunTarget(localContextViewIdentity()),+ executionEpoch: "epoch-1",+ });+ const start = peer.sent+ .filter((command) => command.type === "operation.start")+ .at(-1);+ if (start?.type !== "operation.start") {+ throw new Error("Expected operation.start");+ }+ const identity = {+ contextKey: start.execution_context_key,+ epoch: "epoch-1",+ runId: "local-run-context-1",+ operationId: start.operation_id,+ runtimeType: "codex",+ };+ expect(recordRunOperation).toHaveBeenLastCalledWith(identity);+ await connection.receive(+ event(start, 1, {+ type: "operation.accepted",+ command_id: start.command_id,+ runner_pid: 100,+ }),+ );+ await connection.receive(+ event(start, 2, {+ type: "operation.event",+ event: { type: "run.started", turn_id: "turn-1" },+ }),+ );+ expect(recordRunOperation).toHaveBeenLastCalledWith({+ ...identity,+ turnId: "turn-1",+ });+ const usage = [+ {+ model: "gpt-test",+ provider: "openai",+ input: 1,+ cache_read: 0,+ cache_write: 0,+ output: 1,+ },+ ];+ await connection.receive(+ event(start, 3, {+ type: "operation.completed",+ result: {+ type: "run",+ final_response: "done",+ session: { thread_id: "thread-1" },+ usage,+ },+ }),+ );+ await expect(operation.result).resolves.toMatchObject({ type: "run" });+ expect(recordRunOperation).toHaveBeenLastCalledWith({+ ...identity,+ turnId: "turn-1",+ usage,+ });+ expect(recordRunOperation).toHaveBeenCalledTimes(3);+ });+it("reserves capacity atomically and cancels waiters", async () => {const gateway = createTestRunnerGateway({ createId: sequenceIds() });await gateway.acceptConnection(diff --git a/apps/teamhub/internal/agentruntimestate/run_usage.go b/apps/teamhub/internal/agentruntimestate/run_usage.goindex 2214cce3..ec9a5474 100644--- a/apps/teamhub/internal/agentruntimestate/run_usage.go+++ b/apps/teamhub/internal/agentruntimestate/run_usage.go@@ -114,7 +114,8 @@ func filterLocalRunUsage(raw json.RawMessage, runtimeType string) ([]RunUsage, [return valid, rejected}-// RecordRunOperationInput names a Runner Operation of a Run. Usage is the+// RecordRunOperationInput names a Runner Operation of a Run. TurnID is the+// Runtime turn it started, empty until the Runtime reports one. Usage is the// array its terminal reported; nil records the Operation as it starts.type RecordRunOperationInput struct {ContextKey string@@ -122,6 +123,7 @@ type RecordRunOperationInput struct {RunID stringOperationID stringRuntimeType string+ TurnID stringUsage json.RawMessage}@@ -129,7 +131,8 @@ type RecordRunOperationInput struct {// lands a terminal's usage once. Invalid usage entries are logged and// skipped; they never fail the write.func (s *Service) RecordRunOperation(ctx context.Context, input RecordRunOperationInput) error {- if !validText(input.RunID, 1, 256) || !validText(input.OperationID, 1, 256) || !IsSupportedLocalRuntimeType(input.RuntimeType) {+ if !validText(input.RunID, 1, 256) || !validText(input.OperationID, 1, 256) || !IsSupportedLocalRuntimeType(input.RuntimeType) ||+ (input.TurnID != "" && !validText(input.TurnID, 1, 256)) {return ErrInvalid}_, err := executeEpochTx(ctx, s, input.Epoch, func(ctx context.Context, _ pgx.Tx, queries *store.Queries) (bool, error) {@@ -148,6 +151,13 @@ func (s *Service) RecordRunOperation(ctx context.Context, input RecordRunOperati}); err != nil {return false, err}+ if input.TurnID != "" {+ if err := queries.RecordAgentLocalRunTurn(ctx, store.RecordAgentLocalRunTurnParams{+ TurnID: input.TurnID, RunID: input.RunID,+ }); err != nil {+ return false, err+ }+ }if len(input.Usage) == 0 {return true, nil}diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_runner.go b/apps/teamhub/internal/app/contract_server_agent_runtime_runner.goindex 0d76b491..014ba15b 100644--- a/apps/teamhub/internal/app/contract_server_agent_runtime_runner.go+++ b/apps/teamhub/internal/app/contract_server_agent_runtime_runner.go@@ -144,9 +144,13 @@ func (a *App) recordAgentLocalRunOperation(c *gin.Context) {}usage = encoded}+ var turnID string+ if request.TurnId != nil {+ turnID = *request.TurnId+ }err := a.agentRuntimeState.RecordRunOperation(c.Request.Context(), agentruntimestate.RecordRunOperationInput{ContextKey: request.ContextKey, Epoch: request.Epoch, RunID: request.RunId,- OperationID: request.OperationId, RuntimeType: string(request.RuntimeType), Usage: usage,+ OperationID: request.OperationId, RuntimeType: string(request.RuntimeType), TurnID: turnID, Usage: usage,})if a.writeAgentRuntimeStateError(c, "record Runner Operation", err) {returndiff --git a/apps/teamhub/internal/collaboration/message_activities.go b/apps/teamhub/internal/collaboration/message_activities.goindex f04bcbbc..67daf124 100644--- a/apps/teamhub/internal/collaboration/message_activities.go+++ b/apps/teamhub/internal/collaboration/message_activities.go@@ -72,13 +72,22 @@ func (s *Service) loadMessageActivityIDs(ctx context.Context, localRunID string,return activityIDs, false, nil}+// findMessageActivityIdentity finds the native records of a Run: the tool+// calls behind its published activities, and the turns those calls or the+// Run's own recorded turns belong to. A recorded turn links only when the+// Runtime stamps its native records with the same ID.func findMessageActivityIdentity(ctx context.Context,historyReader messageActivityHistoryReader,target roomagent.RuntimeContextTarget,activityIDs map[string]struct{},- operationIDs ...string,+ runTurnIDs []string,+ operationIDs []string,) (messageActivityIdentity, error) {+ recordedTurns := make(map[string]struct{}, len(runTurnIDs))+ for _, turnID := range runTurnIDs {+ recordedTurns[turnID] = struct{}{}+ }identity := messageActivityIdentity{callIDs: map[string]struct{}{}, status: httpapi.MessageActivityLogStatusAvailable, turnIDs: map[string]struct{}{},}@@ -120,6 +129,9 @@ func findMessageActivityIdentity(if _, exact := identity.callIDs[record.ToolCallID]; exact && record.TurnID != "" {identity.turnIDs[record.TurnID] = struct{}{}}+ if _, recorded := recordedTurns[record.TurnID]; recorded && record.TurnID != "" {+ identity.turnIDs[record.TurnID] = struct{}{}+ }}if page.PreviousCursor == "" {return identity, nil@@ -373,14 +385,18 @@ func (s *Service) runtimeActivityLog(ctx context.Context, run runActivitySource,if err != nil {return httpapi.MessageActivityLog{}, internal("load Message activity identities", err)}- if len(activityIDs) == 0 {+ turnIDs, err := s.queries.ListAgentRuntimeNativeTurnIDs(ctx, run.runID)+ if err != nil {+ return httpapi.MessageActivityLog{}, internal("load Message activity native turns", err)+ }+ if len(activityIDs) == 0 && len(turnIDs) == 0 {return unavailableMessageActivityLog("This Runtime run has no Activity identity for native History"), nil}operationIDs, err := s.queries.ListAgentRuntimeNativeOperationIDs(ctx, run.runID)if err != nil {return httpapi.MessageActivityLog{}, internal("load Message activity native operations", err)}- identity, err := findMessageActivityIdentity(ctx, historyReader, target, activityIDs, operationIDs...)+ identity, err := findMessageActivityIdentity(ctx, historyReader, target, activityIDs, turnIDs, operationIDs)if err != nil {return httpapi.MessageActivityLog{}, ErrMessageActivitiesUnavailable}diff --git a/apps/teamhub/internal/collaboration/message_activities_test.go b/apps/teamhub/internal/collaboration/message_activities_test.goindex d7067209..333cc171 100644--- a/apps/teamhub/internal/collaboration/message_activities_test.go+++ b/apps/teamhub/internal/collaboration/message_activities_test.go@@ -62,7 +62,7 @@ func TestMessageActivityHistoryReadsTheCompleteExactNativeTurn(t *testing.T) {target := roomagent.RuntimeContextTarget{TenantID: "tenant-1", ContextKey: "context-1"}activityIDs := map[string]struct{}{"call-target": {}}- identity, err := findMessageActivityIdentity(context.Background(), inspector, target, activityIDs)+ identity, err := findMessageActivityIdentity(context.Background(), inspector, target, activityIDs, nil, nil)if err != nil {t.Fatal(err)}@@ -106,7 +106,7 @@ func TestMessageActivityHistoryUsesPersistedNativeActivities(t *testing.T) {"activity-" + "e3bb0c30dd84b186f252f69cd20cc9c5", // Local Computer, stable across recovery.} {activities := map[string]struct{}{activityID: {}}- identity, err := findMessageActivityIdentity(context.Background(), inspector, roomagent.RuntimeContextTarget{}, activities, "operation_local")+ identity, err := findMessageActivityIdentity(context.Background(), inspector, roomagent.RuntimeContextTarget{}, activities, nil, []string{"operation_local"})if err != nil {t.Fatal(err)}@@ -117,6 +117,36 @@ func TestMessageActivityHistoryUsesPersistedNativeActivities(t *testing.T) {}}+func TestMessageActivityHistoryReadsRecordedTurnWithoutLinkedCall(t *testing.T) {+ // The published activity names a nested call the native history never+ // records, as Codex code mode does; the Run's recorded turn still links.+ inspector := &messageActivityInspectorStub{pages: map[string]roomagent.RuntimeHistory{+ "": {Status: "available", ProviderKind: "codex", Records: []roomagent.RuntimeHistoryRecord{+ {Ordinal: 1, TurnID: "turn-earlier", Category: "message"},+ {Ordinal: 2, TurnID: "turn-run", Category: "lifecycle"},+ {Ordinal: 3, TurnID: "turn-run", ToolCallID: "call_outer", Category: "tool_call"},+ {Ordinal: 4, TurnID: "turn-run", ToolCallID: "call_outer", Category: "tool_result"},+ {Ordinal: 5, TurnID: "turn-run", Category: "message"},+ }},+ }}+ activities := map[string]struct{}{"activity-0123456789abcdef0123456789abcdef": {}}+ runTurns := []string{"turn-run", "turn-unrecorded"}+ identity, err := findMessageActivityIdentity(context.Background(), inspector, roomagent.RuntimeContextTarget{}, activities, runTurns, []string{"operation_local"})+ if err != nil {+ t.Fatal(err)+ }+ if len(identity.turnIDs) != 1 {+ t.Fatalf("turn IDs=%v, want only the turn the native history records", identity.turnIDs)+ }+ records, _, err := readMessageActivityRecords(context.Background(), inspector, roomagent.RuntimeContextTarget{}, identity)+ if err != nil {+ t.Fatal(err)+ }+ if len(records) != 4 || records[0].Ordinal != 2 || records[3].Ordinal != 5 {+ t.Fatalf("records=%+v", records)+ }+}+type messageActivityInspectorStub struct {pages map[string]roomagent.RuntimeHistory}diff --git a/apps/teamhub/internal/store/agent_run_usage.sql.go b/apps/teamhub/internal/store/agent_run_usage.sql.goindex f6b11408..36234969 100644--- a/apps/teamhub/internal/store/agent_run_usage.sql.go+++ b/apps/teamhub/internal/store/agent_run_usage.sql.go@@ -66,6 +66,27 @@ func (q *Queries) RecordAgentLocalRunOperation(ctx context.Context, arg RecordAgreturn err}+const recordAgentLocalRunTurn = `-- name: RecordAgentLocalRunTurn :exec+UPDATE agent_local_runs+SET turn_ids=array_append(turn_ids,$1::text),+ updated_at=clock_timestamp()+WHERE run_id=$2::text+ AND NOT $1::text=ANY(turn_ids)+ AND cardinality(turn_ids)<64+`++type RecordAgentLocalRunTurnParams struct {+ TurnID string `json:"turn_id"`+ RunID string `json:"run_id"`+}++// A Run keeps each Runtime turn its Operations started once; a Run runs a+// handful of Operations, so the cap only bounds a misbehaving Runtime.+func (q *Queries) RecordAgentLocalRunTurn(ctx context.Context, arg RecordAgentLocalRunTurnParams) error {+ _, err := q.db.Exec(ctx, recordAgentLocalRunTurn, arg.TurnID, arg.RunID)+ return err+}+const recordAgentLocalRunUsage = `-- name: RecordAgentLocalRunUsage :execrowsUPDATE agent_local_runsSET usage=coalesce(usage,'{}'::jsonb)||jsonb_build_object($1::text,$2::jsonb),diff --git a/apps/teamhub/internal/store/agent_runtime_state.sql.go b/apps/teamhub/internal/store/agent_runtime_state.sql.goindex 02297a5b..4c09976b 100644--- a/apps/teamhub/internal/store/agent_runtime_state.sql.go+++ b/apps/teamhub/internal/store/agent_runtime_state.sql.go@@ -319,7 +319,7 @@ WHERE run_id=$4::textAND context_key=$5::textAND status='queued'AND agent_document_run_claimable(agent_local_runs.run_id,agent_local_runs.context_key)-RETURNING run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision+RETURNING run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids`type ClaimAgentLocalRunParams struct {@@ -356,6 +356,7 @@ func (q *Queries) ClaimAgentLocalRun(ctx context.Context, arg ClaimAgentLocalRun&i.Usage,&i.StatusRoomID,&i.ClaimProfileRevision,+ &i.TurnIds,)return i, err}@@ -447,7 +448,7 @@ func (q *Queries) CountAgentRunStatusSegments(ctx context.Context, localRunID stconst createAgentLocalRun = `-- name: CreateAgentLocalRun :oneINSERT INTO agent_local_runs(run_id,context_key,status)VALUES($1::text,$2::text,'queued')-RETURNING run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision+RETURNING run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids`type CreateAgentLocalRunParams struct {@@ -475,6 +476,7 @@ func (q *Queries) CreateAgentLocalRun(ctx context.Context, arg CreateAgentLocalR&i.Usage,&i.StatusRoomID,&i.ClaimProfileRevision,+ &i.TurnIds,)return i, err}@@ -687,7 +689,7 @@ func (q *Queries) GetAgentExecutionContextRuntimeEventCount(ctx context.Context,}const getAgentLocalRun = `-- name: GetAgentLocalRun :one-SELECT run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision+SELECT run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_idsFROM agent_local_runsWHERE context_key=$1::textAND run_id=$2::text@@ -718,6 +720,7 @@ func (q *Queries) GetAgentLocalRun(ctx context.Context, arg GetAgentLocalRunPara&i.Usage,&i.StatusRoomID,&i.ClaimProfileRevision,+ &i.TurnIds,)return i, err}@@ -1345,7 +1348,7 @@ func (q *Queries) GetRoomRunStatusForAccount(ctx context.Context, arg GetRoomRun}const getRunningAgentLocalRun = `-- name: GetRunningAgentLocalRun :one-SELECT run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision FROM agent_local_runs+SELECT run_id, context_key, status, terminal, created_at, updated_at, started_at, finished_at, attempt_count, cancellation_requested, epoch, claim_id, claim_configuration_revision, usage, status_room_id, claim_profile_revision, turn_ids FROM agent_local_runsWHERE context_key=$1::text AND status='running'LIMIT 1`@@ -1370,6 +1373,7 @@ func (q *Queries) GetRunningAgentLocalRun(ctx context.Context, contextKey string&i.Usage,&i.StatusRoomID,&i.ClaimProfileRevision,+ &i.TurnIds,)return i, err}@@ -2269,6 +2273,34 @@ func (q *Queries) ListAgentRuntimeNativeOperationIDs(ctx context.Context, localRreturn items, nil}+const listAgentRuntimeNativeTurnIDs = `-- name: ListAgentRuntimeNativeTurnIDs :many+SELECT turn.turn_id::text AS turn_id+FROM agent_local_runs run+CROSS JOIN LATERAL unnest(run.turn_ids) AS turn(turn_id)+WHERE run.run_id=$1::text+ORDER BY turn.turn_id+`++func (q *Queries) ListAgentRuntimeNativeTurnIDs(ctx context.Context, localRunID string) ([]string, error) {+ rows, err := q.db.Query(ctx, listAgentRuntimeNativeTurnIDs, localRunID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []string{}+ for rows.Next() {+ var turn_id string+ if err := rows.Scan(&turn_id); err != nil {+ return nil, err+ }+ items = append(items, turn_id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listAgentRuntimeSteeringInputs = `-- name: ListAgentRuntimeSteeringInputs :manySELECT context_key, input_id, input_sequence, payload, payload_hash, source_kind, source_message_id, source_inbox_id, status, selection_result, steer_group_id, local_run_id, steer_outcome, created_at, updated_atFROM agent_runtime_inputs@@ -3299,7 +3331,7 @@ func (q *Queries) LockMetaContextsForRoomMemberships(ctx context.Context, arg Lo}const lockNextQueuedAgentLocalRun = `-- name: LockNextQueuedAgentLocalRun :one-SELECT run.run_id, run.context_key, run.status, run.terminal, run.created_at, run.updated_at, run.started_at, run.finished_at, run.attempt_count, run.cancellation_requested, run.epoch, run.claim_id, run.claim_configuration_revision, run.usage, run.status_room_id, run.claim_profile_revision+SELECT run.run_id, run.context_key, run.status, run.terminal, run.created_at, run.updated_at, run.started_at, run.finished_at, run.attempt_count, run.cancellation_requested, run.epoch, run.claim_id, run.claim_configuration_revision, run.usage, run.status_room_id, run.claim_profile_revision, run.turn_idsFROM agent_local_runs runWHERE run.context_key=$1::text AND run.status='queued'AND agent_document_run_claimable(run.run_id,run.context_key)@@ -3328,6 +3360,7 @@ func (q *Queries) LockNextQueuedAgentLocalRun(ctx context.Context, contextKey st&i.Usage,&i.StatusRoomID,&i.ClaimProfileRevision,+ &i.TurnIds,)return i, err}diff --git a/apps/teamhub/internal/store/models.go b/apps/teamhub/internal/store/models.goindex 53a794cc..0ac56e6d 100644--- a/apps/teamhub/internal/store/models.go+++ b/apps/teamhub/internal/store/models.go@@ -188,6 +188,7 @@ type AgentLocalRun struct {Usage []byte `json:"usage"`StatusRoomID pgtype.Text `json:"status_room_id"`ClaimProfileRevision pgtype.Int8 `json:"claim_profile_revision"`+ TurnIds []string `json:"turn_ids"`}type AgentLocalRunInput struct {diff --git a/apps/teamhub/internal/store/queries/agent_run_usage.sql b/apps/teamhub/internal/store/queries/agent_run_usage.sqlindex bc1cb1de..7c02de7f 100644--- a/apps/teamhub/internal/store/queries/agent_run_usage.sql+++ b/apps/teamhub/internal/store/queries/agent_run_usage.sql@@ -7,6 +7,16 @@ SET usage=coalesce(usage,'{}'::jsonb)||jsonb_build_object(sqlc.arg(operation_id)WHERE run_id=sqlc.arg(run_id)::textAND NOT coalesce(usage,'{}'::jsonb) ? sqlc.arg(operation_id)::text;+-- name: RecordAgentLocalRunTurn :exec+-- A Run keeps each Runtime turn its Operations started once; a Run runs a+-- handful of Operations, so the cap only bounds a misbehaving Runtime.+UPDATE agent_local_runs+SET turn_ids=array_append(turn_ids,sqlc.arg(turn_id)::text),+ updated_at=clock_timestamp()+WHERE run_id=sqlc.arg(run_id)::text+ AND NOT sqlc.arg(turn_id)::text=ANY(turn_ids)+ AND cardinality(turn_ids)<64;+-- name: RecordAgentLocalRunUsage :execrows-- One Runner Operation's usage lands on its Run once; a repeated terminal of-- the same Operation changes nothing.diff --git a/apps/teamhub/internal/store/queries/agent_runtime_state.sql b/apps/teamhub/internal/store/queries/agent_runtime_state.sqlindex 56dda3b4..64a36a0b 100644--- a/apps/teamhub/internal/store/queries/agent_runtime_state.sql+++ b/apps/teamhub/internal/store/queries/agent_runtime_state.sql@@ -789,6 +789,13 @@ CROSS JOIN LATERAL jsonb_object_keys(coalesce(run.usage,'{}'::jsonb)) AS operatiWHERE run.run_id=sqlc.arg(local_run_id)::textORDER BY operation.operation_id;+-- name: ListAgentRuntimeNativeTurnIDs :many+SELECT turn.turn_id::text AS turn_id+FROM agent_local_runs run+CROSS JOIN LATERAL unnest(run.turn_ids) AS turn(turn_id)+WHERE run.run_id=sqlc.arg(local_run_id)::text+ORDER BY turn.turn_id;+-- name: GetAgentRuntimeTaskInboxRoom :oneSELECT link.room_idFROM work_items itemdiff --git a/apps/teamhub/migrations/00868_record_local_run_turns.sql b/apps/teamhub/migrations/00868_record_local_run_turns.sqlnew file mode 100644index 00000000..d13f1920--- /dev/null+++ b/apps/teamhub/migrations/00868_record_local_run_turns.sql@@ -0,0 +1,10 @@+-- +goose Up+-- The Runtime turns a Run's Operations started. Message activities read the+-- native records a Runtime stamps with these IDs, so a turn links even when+-- none of its tool calls does.+ALTER TABLE agent_local_runs+ ADD COLUMN turn_ids text[] NOT NULL DEFAULT '{}'::text[];++-- +goose Down+ALTER TABLE agent_local_runs+ DROP COLUMN turn_ids;diff --git a/apps/teamhub/tests/integration/agent_runtime_runner_operation_usage_test.go b/apps/teamhub/tests/integration/agent_runtime_runner_operation_usage_test.goindex e8843129..f160d2ac 100644--- a/apps/teamhub/tests/integration/agent_runtime_runner_operation_usage_test.go+++ b/apps/teamhub/tests/integration/agent_runtime_runner_operation_usage_test.go@@ -77,3 +77,48 @@ func TestAgentRuntimeRunnerOperationUsageLandsOnTheRunOnce(t *testing.T) {t.Fatalf("unrelated operations=%v err=%v", unrelated, err)}}++func TestAgentRuntimeRunnerOperationTurnsLandOnTheRunOnce(t *testing.T) {+ allowParallelIntegrationTest(t)+ env := newRuntimeStateTestEnv(t)+ submitted, err := env.service.SubmitTrustedTurn(t.Context(), agentruntimestate.SubmitTrustedTurnInput{ContextKey: env.contextKey, Epoch: env.epoch,+ Inputs: []agentruntimestate.RuntimeInput{runtimeInput("operation-turn-input", "trusted_turn", "", "once")},+ })+ if err != nil {+ t.Fatal(err)+ }+ claimed, err := env.service.ClaimLocalRun(t.Context(), agentruntimestate.ClaimLocalRunInput{ClaimID: "operation-turn-claim", ContextKey: env.contextKey, Epoch: env.epoch})+ if err != nil || claimed.Run == nil {+ t.Fatalf("claim: %+v %v", claimed, err)+ }+ const usage = `[{"provider":"openai","model":"turn-test-model","input":1,"cache_read":0,"cache_write":0,"output":1}]`+ // The start, the turn and the terminal of each Operation are separate,+ // possibly repeated reports; each turn is kept once.+ for _, report := range []struct{ operationID, turnID, usage string }{+ {"operation-earlier", "", ""},+ {"operation-earlier", "turn-earlier", ""},+ {"operation-earlier", "turn-earlier", usage},+ {"operation-latest", "turn-latest", ""},+ {"operation-latest", "turn-latest", ""},+ } {+ input := agentruntimestate.RecordRunOperationInput{+ ContextKey: env.contextKey, Epoch: env.epoch, RunID: submitted.RunID,+ OperationID: report.operationID, RuntimeType: "codex", TurnID: report.turnID,+ }+ if report.usage != "" {+ input.Usage = json.RawMessage(report.usage)+ }+ if err := env.service.RecordRunOperation(t.Context(), input); err != nil {+ t.Fatalf("record %+v: %v", report, err)+ }+ }+ if err := env.service.RecordRunOperation(t.Context(), agentruntimestate.RecordRunOperationInput{+ ContextKey: env.contextKey, Epoch: env.epoch, RunID: submitted.RunID, OperationID: "operation-latest", RuntimeType: "codex", TurnID: " ",+ }); !errors.Is(err, agentruntimestate.ErrInvalid) {+ t.Fatalf("blank turn: err=%v, want invalid", err)+ }+ turns, err := store.New(env.pool).ListAgentRuntimeNativeTurnIDs(t.Context(), submitted.RunID)+ if err != nil || len(turns) != 2 || turns[0] != "turn-earlier" || turns[1] != "turn-latest" {+ t.Fatalf("native turns=%v err=%v", turns, err)+ }+}diff --git a/contracts/generated/go/teamhubinternal/openapi.gen.go b/contracts/generated/go/teamhubinternal/openapi.gen.goindex 18699922..9faf8db2 100644--- a/contracts/generated/go/teamhubinternal/openapi.gen.go+++ b/contracts/generated/go/teamhubinternal/openapi.gen.go@@ -3037,6 +3037,9 @@ type RecordAgentLocalRunOperationRequest struct {RunId string `json:"run_id"`RuntimeType LocalRuntimeType `json:"runtime_type"`+ // TurnId The Runtime turn the Operation started. Message activities read the native records stamped with it, so a turn that a Runtime records under the same ID links even when no tool call does.+ TurnId *string `json:"turn_id,omitempty"`+// Usage The usage the Operation's terminal reported; absent when the Operation starts.Usage *[]map[string]interface{} `json:"usage,omitempty"`}diff --git a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts b/contracts/generated/typescript/src/generated/teamhub-internal/types.tsindex 580aaebc..6fea63e8 100644--- a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts@@ -2152,6 +2152,8 @@ export interface components {run_id: string;operation_id: string;runtime_type: components["schemas"]["LocalRuntimeType"];+ /** @description The Runtime turn the Operation started. Message activities read the native records stamped with it, so a turn that a Runtime records under the same ID links even when no tool call does. */+ turn_id?: string;/** @description The usage the Operation's terminal reported; absent when the Operation starts. */usage?: {[key: string]: unknown;diff --git a/contracts/openapi/components/agent-runtime-state.yaml b/contracts/openapi/components/agent-runtime-state.yamlindex 1218be87..addc51ef 100644--- a/contracts/openapi/components/agent-runtime-state.yaml+++ b/contracts/openapi/components/agent-runtime-state.yaml@@ -1594,6 +1594,14 @@ components:maxLength: 256runtime_type:$ref: "./domain.yaml#/components/schemas/LocalRuntimeType"+ turn_id:+ type: string+ minLength: 1+ maxLength: 256+ description: >-+ The Runtime turn the Operation started. Message activities read the+ native records stamped with it, so a turn that a Runtime records+ under the same ID links even when no tool call does.usage:type: arrayminItems: 1diff --git a/docs/task-delegation.md b/docs/task-delegation.mdindex 7d936609..2bb4aa3d 100644--- a/docs/task-delegation.md+++ b/docs/task-delegation.md@@ -31,8 +31,8 @@ whether to ask.</sub>Each `task` step in the Meta's activity is one line with the Task's name andstate. Open it, or a Task under _tasks running in the background_, to read theTask like a chat: the brief and follow-ups the Meta sent, every step the-AlterEgo took with the command, file or search it acted on, and the approval-cards it raised. A card is answered there or in your chat, where it also+AlterEgo took with the command, file or search it acted on, its replies, and+the approval cards it raised. A card is answered there or in your chat, where it alsoappears, and a running Task can be canceled from the same view. Steps are readfrom the AlterEgo's session on your computer each time it takes a new one.