feat(FN-4595): implement cumulative execution timing semantics

Fusion-Task-Id: FN-4595
Fusion-Task-Lineage: 73a3d0ad-5c10-4560-aec5-f9d138deeefd
This commit is contained in:
Fusion
2026-05-15 07:28:34 -07:00
committed by gsxdsm
parent b1f70a20d4
commit 3648d1e1df
18 changed files with 355 additions and 49 deletions

View File

@@ -717,7 +717,7 @@ describe("schema migration", () => {
{ id: "WS-001", mode: "prompt", gateMode: "advisory" },
{ id: "WS-002", mode: "script", gateMode: "advisory" },
]);
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
db.close();
});
@@ -767,7 +767,7 @@ describe("schema migration", () => {
reviewerContextRetryCount: 0,
reviewerFallbackRetryCount: 0,
});
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
db.close();
});
@@ -796,7 +796,7 @@ describe("schema migration", () => {
const columns = db.prepare("PRAGMA table_info(milestones)").all() as Array<{ name: string }>;
expect(columns.map((column) => column.name)).toContain("acceptanceCriteria");
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
db.close();
});
@@ -831,7 +831,7 @@ describe("schema migration", () => {
{ id: "WS-002", mode: "script", enabled: 1, gateMode: "advisory" },
{ id: "WS-003", mode: "prompt", enabled: 0, gateMode: "advisory" },
]);
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
db.close();
});

View File

@@ -290,7 +290,7 @@ describe("Database", () => {
});
it("seeds schema version", () => {
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
});
it("includes tokenUsageCacheWriteTokens on freshly initialized tasks table", () => {
@@ -318,7 +318,7 @@ describe("Database", () => {
it("is idempotent - calling init() twice does not fail", () => {
expect(() => db.init()).not.toThrow();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
});
it("does not overwrite existing config on re-init", () => {
// Update the config
@@ -1383,7 +1383,7 @@ describe("schema migrations", () => {
db.init();
// Verify version bumped to 29 (includes v1→v2 through v26→v29)
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
// Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -1408,11 +1408,11 @@ describe("schema migrations", () => {
const db = new Database(fusionDir);
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
// Re-init should not fail
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
db.close();
});
@@ -1447,7 +1447,7 @@ describe("schema migrations", () => {
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
expect(cols.map((col) => col.name)).toContain("priority");
@@ -1488,7 +1488,7 @@ describe("schema migrations", () => {
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
const colNames = cols.map((col) => col.name);
@@ -1560,7 +1560,7 @@ describe("schema migrations", () => {
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
const colNames = cols.map((col) => col.name);
@@ -1800,7 +1800,7 @@ describe("schema migrations", () => {
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const cols = db.prepare("PRAGMA table_info(chat_messages)").all() as Array<{ name: string }>;
expect(cols.map((col) => col.name)).toContain("attachments");
@@ -1874,7 +1874,7 @@ describe("schema migrations", () => {
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = 'agentRatings'").all() as Array<{ name: string }>;
expect(tables).toEqual([{ name: "agentRatings" }]);
@@ -1898,7 +1898,7 @@ describe("schema migrations", () => {
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = 'mission_events'").all() as Array<{ name: string }>;
expect(tables).toEqual([{ name: "mission_events" }]);
@@ -2002,7 +2002,7 @@ describe("schema migrations", () => {
db.init();
// Verify version bumped to 29
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
// Verify new columns exist and existing data is intact
const cols = db.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
@@ -2221,7 +2221,7 @@ describe("schema migrations", () => {
localDb.init();
expect(localDb.getSchemaVersion()).toBe(80);
expect(localDb.getSchemaVersion()).toBe(81);
const columns = localDb.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
expect(columns.map((column) => column.name)).toContain("tokenUsageCacheWriteTokens");
@@ -2532,7 +2532,7 @@ describe("createDatabase factory", () => {
const db = createDatabase(fusionDir);
db.init();
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
expect(db.getLastModified()).toBeGreaterThan(0);
db.close();
@@ -2688,7 +2688,7 @@ describe("migration v77 task token budget columns", () => {
migrated = new Database(fusion);
migrated.init();
expect(migrated.getSchemaVersion()).toBe(80);
expect(migrated.getSchemaVersion()).toBe(81);
const rows = migrated.prepare("PRAGMA table_info(tasks)").all() as Array<{ name: string }>;
const names = new Set(rows.map((row) => row.name));
expect(names.has("tokenBudgetSoftAlertedAt")).toBe(true);
@@ -2734,7 +2734,7 @@ describe("migration v67 drops orphan project auth tables", () => {
migrated = new Database(fusion);
migrated.init();
expect(migrated.getSchemaVersion()).toBe(80);
expect(migrated.getSchemaVersion()).toBe(81);
const tables = migrated
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'project_auth_%'")
.all() as Array<{ name: string }>;
@@ -2761,7 +2761,7 @@ describe("migration v67 drops orphan project auth tables", () => {
try {
fresh.init();
expect(fresh.getSchemaVersion()).toBe(80);
expect(fresh.getSchemaVersion()).toBe(81);
const tables = fresh
.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'project_auth_%'")
.all() as Array<{ name: string }>;

View File

@@ -886,7 +886,7 @@ describe("Migration: pre-33 DB upgrade", () => {
// Step 1: Create a fresh database at v33 (runs all migrations up to 33)
const db1 = createDatabase(legacyDir);
db1.init();
expect(db1.getSchemaVersion()).toBe(80);
expect(db1.getSchemaVersion()).toBe(81);
db1.close();
// Step 2: Manually downgrade to version 32 and drop insight tables
@@ -921,7 +921,7 @@ describe("Migration: pre-33 DB upgrade", () => {
expect(tableNamesBefore).not.toContain("project_insight_runs");
// Now run init — this triggers the v32→v33 migration
db3.init();
expect(db3.getSchemaVersion()).toBe(80);
expect(db3.getSchemaVersion()).toBe(81);
// Step 4: Verify insight tables exist after migration
const tablesAfter = db3.prepare(
@@ -952,12 +952,12 @@ describe("Migration: pre-33 DB upgrade", () => {
try {
const db1 = createDatabase(testDir);
db1.init();
expect(db1.getSchemaVersion()).toBe(80);
expect(db1.getSchemaVersion()).toBe(81);
db1.close();
const db2 = createDatabase(testDir);
expect(() => db2.init()).not.toThrow();
expect(db2.getSchemaVersion()).toBe(80);
expect(db2.getSchemaVersion()).toBe(81);
db2.close();
} finally {
rmSync(testDir, { recursive: true, force: true });
@@ -971,7 +971,7 @@ describe("Migration: pre-33 DB upgrade", () => {
// Step 1: Create a fresh DB and run migrations
const db1 = createDatabase(compatDir);
db1.init();
expect(db1.getSchemaVersion()).toBe(80);
expect(db1.getSchemaVersion()).toBe(81);
// Step 2: Strip lifecycle and cancelledAt columns by recreating the
// table without them. This simulates a DB that was created before the

View File

@@ -2774,7 +2774,7 @@ describe("MissionStore", () => {
describe("Loop State & Validator Run Schema (v31)", () => {
it("schema version is 40 after migration", () => {
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
});
it("mission_features table has loop state columns", () => {

View File

@@ -584,7 +584,7 @@ describe("Run Audit", () => {
});
it("schema version is bumped to 40", () => {
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
});
});
});

View File

@@ -0,0 +1,88 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { createTaskStoreTestHarness } from "./store-test-helpers.js";
describe("TaskStore execution timing semantics", () => {
const harness = createTaskStoreTestHarness();
let store = harness.store();
beforeEach(async () => {
await harness.beforeEach();
store = harness.store();
});
afterEach(async () => {
await harness.afterEach();
});
it("hydrates legacy tasks without firstExecutionAt and initializes on next in-progress transition", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-15T10:00:00.000Z"));
const task = await store.createTask({ description: "legacy timing row" });
await store.moveTask(task.id, "todo");
await store.updateTask(task.id, {
firstExecutionAt: null,
cumulativeActiveMs: null,
executionStartedAt: null,
});
const moved = await store.moveTask(task.id, "in-progress");
expect(moved.firstExecutionAt).toBe("2026-05-15T10:00:00.000Z");
expect(moved.cumulativeActiveMs).toBe(0);
});
it("tracks firstExecutionAt and cumulativeActiveMs across reopen/resume cycles", async () => {
vi.useFakeTimers();
const t0 = new Date("2026-05-15T08:42:00.000Z");
vi.setSystemTime(t0);
const task = await store.createTask({ description: "timing lifecycle" });
await store.moveTask(task.id, "todo");
await store.moveTask(task.id, "in-progress");
vi.setSystemTime(new Date("2026-05-15T08:46:00.000Z"));
await store.moveTask(task.id, "todo", { moveSource: "user" });
vi.setSystemTime(new Date("2026-05-15T13:15:00.000Z"));
const resumed = await store.moveTask(task.id, "in-progress");
vi.setSystemTime(new Date("2026-05-15T13:17:00.000Z"));
const reviewed = await store.moveTask(task.id, "in-review");
expect(resumed.executionStartedAt).toBe("2026-05-15T13:15:00.000Z");
expect(reviewed.firstExecutionAt).toBe("2026-05-15T08:42:00.000Z");
expect(reviewed.cumulativeActiveMs).toBe(6 * 60_000);
});
it("accumulates active segment when preserveResumeState bounce exits in-progress", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-15T09:00:00.000Z"));
const task = await store.createTask({ description: "preserve resume timing" });
await store.moveTask(task.id, "todo");
const running = await store.moveTask(task.id, "in-progress");
vi.setSystemTime(new Date("2026-05-15T09:03:00.000Z"));
const bounced = await store.moveTask(task.id, "todo", { preserveResumeState: true });
expect(bounced.executionStartedAt).toBe(running.executionStartedAt);
expect(bounced.cumulativeActiveMs).toBe(3 * 60_000);
});
it("counts only in-progress time for in-progress → in-review → done", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-15T11:00:00.000Z"));
const task = await store.createTask({ description: "in review wait excluded" });
await store.moveTask(task.id, "todo");
await store.moveTask(task.id, "in-progress");
vi.setSystemTime(new Date("2026-05-15T11:05:00.000Z"));
await store.moveTask(task.id, "in-review");
vi.setSystemTime(new Date("2026-05-15T11:25:00.000Z"));
const done = await store.moveTask(task.id, "done");
expect(done.cumulativeActiveMs).toBe(5 * 60_000);
});
});

View File

@@ -51,7 +51,7 @@ describe("TaskStore task documents", () => {
expect(tableNames.has("task_documents")).toBe(true);
expect(tableNames.has("task_document_revisions")).toBe(true);
expect(db.getSchemaVersion()).toBe(80);
expect(db.getSchemaVersion()).toBe(81);
const index = db
.prepare(

View File

@@ -119,7 +119,7 @@ export function probeFts5(db: DatabaseSync): boolean {
// ── Schema Definition ────────────────────────────────────────────────
const SCHEMA_VERSION = 80;
const SCHEMA_VERSION = 81;
function normalizeTaskComments(
steeringComments: SteeringComment[] | undefined,
@@ -233,6 +233,8 @@ CREATE TABLE IF NOT EXISTS tasks (
createdAt TEXT NOT NULL,
updatedAt TEXT NOT NULL,
columnMovedAt TEXT,
firstExecutionAt TEXT,
cumulativeActiveMs INTEGER,
executionStartedAt TEXT,
executionCompletedAt TEXT,
-- JSON columns for nested arrays/objects
@@ -3298,6 +3300,23 @@ export class Database {
});
}
if (version < 81) {
this.applyMigration(81, () => {
this.addColumnIfMissing("tasks", "firstExecutionAt", "TEXT");
this.addColumnIfMissing("tasks", "cumulativeActiveMs", "INTEGER");
if (this.hasColumn("tasks", "executionStartedAt")) {
this.db
.prepare(
`UPDATE tasks
SET firstExecutionAt = executionStartedAt
WHERE firstExecutionAt IS NULL
AND executionStartedAt IS NOT NULL`
)
.run();
}
});
}
}
/**

View File

@@ -105,6 +105,8 @@ interface TaskRow {
createdAt: string;
updatedAt: string;
columnMovedAt: string | null;
firstExecutionAt: string | null;
cumulativeActiveMs: number | null;
executionStartedAt: string | null;
executionCompletedAt: string | null;
dependencies: string | null;
@@ -1026,6 +1028,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
createdAt: row.createdAt,
updatedAt: row.updatedAt,
columnMovedAt: row.columnMovedAt || undefined,
firstExecutionAt: row.firstExecutionAt || undefined,
cumulativeActiveMs: row.cumulativeActiveMs ?? undefined,
executionStartedAt: row.executionStartedAt || undefined,
executionCompletedAt: row.executionCompletedAt || undefined,
dependencies: fromJson<string[]>(row.dependencies) || [],
@@ -1159,6 +1163,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
createdAt: entry.createdAt,
updatedAt: entry.updatedAt,
columnMovedAt: entry.columnMovedAt,
firstExecutionAt: entry.firstExecutionAt,
cumulativeActiveMs: entry.cumulativeActiveMs,
executionStartedAt: entry.executionStartedAt,
executionCompletedAt: entry.executionCompletedAt,
modelPresetId: entry.modelPresetId,
@@ -1288,6 +1294,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
createdAt: task.createdAt,
updatedAt: task.updatedAt,
columnMovedAt: task.columnMovedAt,
firstExecutionAt: task.firstExecutionAt,
cumulativeActiveMs: task.cumulativeActiveMs,
executionStartedAt: task.executionStartedAt,
executionCompletedAt: task.executionCompletedAt,
archivedAt,
@@ -1360,7 +1368,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
"mergeRetries", "workflowStepRetries", "stuckKillCount", "postReviewFixCount", "recoveryRetryCount", "taskDoneRetryCount", "verificationFailureCount", "mergeConflictBounceCount", "mergeAuditBounceCount", "branchConflictRecoveryCount", "reviewerContextRetryCount", "reviewerFallbackRetryCount", "nextRecoveryAt",
"error", "summary", "thinkingLevel", "executionMode",
"tokenUsageInputTokens", "tokenUsageOutputTokens", "tokenUsageCachedTokens", "tokenUsageCacheWriteTokens", "tokenUsageTotalTokens", "tokenUsageFirstUsedAt", "tokenUsageLastUsedAt", "tokenBudgetSoftAlertedAt", "tokenBudgetHardAlertedAt", "tokenBudgetOverride",
"createdAt", "updatedAt", "columnMovedAt", "executionStartedAt", "executionCompletedAt",
"createdAt", "updatedAt", "columnMovedAt", "firstExecutionAt", "cumulativeActiveMs", "executionStartedAt", "executionCompletedAt",
"dependencies", "steps", "comments", "review", "reviewState", "workflowStepResults", "steeringComments",
"attachments", "prInfo", "issueInfo", "githubTracking", "sourceIssueProvider", "sourceIssueRepository", "sourceIssueExternalIssueId", "sourceIssueNumber", "sourceIssueUrl", "mergeDetails",
"breakIntoSubtasks", "noCommitsExpected", "enabledWorkflowSteps", "modifiedFiles",
@@ -1409,7 +1417,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
"mergeRetries", "workflowStepRetries", "stuckKillCount", "postReviewFixCount", "recoveryRetryCount", "taskDoneRetryCount", "verificationFailureCount", "mergeConflictBounceCount", "mergeAuditBounceCount", "branchConflictRecoveryCount", "reviewerContextRetryCount", "reviewerFallbackRetryCount", "nextRecoveryAt",
"error", "summary", "thinkingLevel", "executionMode",
"tokenUsageInputTokens", "tokenUsageOutputTokens", "tokenUsageCachedTokens", "tokenUsageCacheWriteTokens", "tokenUsageTotalTokens", "tokenUsageFirstUsedAt", "tokenUsageLastUsedAt", "tokenBudgetSoftAlertedAt", "tokenBudgetHardAlertedAt", "tokenBudgetOverride",
"createdAt", "updatedAt", "columnMovedAt", "executionStartedAt", "executionCompletedAt",
"createdAt", "updatedAt", "columnMovedAt", "firstExecutionAt", "cumulativeActiveMs", "executionStartedAt", "executionCompletedAt",
"dependencies", "steps", "attachments", "steeringComments",
"comments", "review", "reviewState", "workflowStepResults", "prInfo", "issueInfo", "githubTracking", "sourceIssueProvider", "sourceIssueRepository", "sourceIssueExternalIssueId", "sourceIssueNumber", "sourceIssueUrl", "mergeDetails",
"breakIntoSubtasks", "noCommitsExpected", "enabledWorkflowSteps", "modifiedFiles",
@@ -1498,6 +1506,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
task.createdAt,
task.updatedAt,
task.columnMovedAt ?? null,
task.firstExecutionAt ?? null,
task.cumulativeActiveMs ?? null,
task.executionStartedAt ?? null,
task.executionCompletedAt ?? null,
toJson(task.dependencies || []),
@@ -1563,7 +1573,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
workflowStepRetries, stuckKillCount, postReviewFixCount, recoveryRetryCount, taskDoneRetryCount, verificationFailureCount, mergeConflictBounceCount, mergeAuditBounceCount, branchConflictRecoveryCount, reviewerContextRetryCount, reviewerFallbackRetryCount, nextRecoveryAt, error,
summary, thinkingLevel, executionMode, tokenUsageInputTokens, tokenUsageOutputTokens, tokenUsageCachedTokens,
tokenUsageCacheWriteTokens, tokenUsageTotalTokens, tokenUsageFirstUsedAt, tokenUsageLastUsedAt, tokenBudgetSoftAlertedAt, tokenBudgetHardAlertedAt, tokenBudgetOverride, createdAt, updatedAt, columnMovedAt,
executionStartedAt, executionCompletedAt,
firstExecutionAt, cumulativeActiveMs, executionStartedAt, executionCompletedAt,
dependencies, steps, log, attachments, steeringComments,
comments, review, reviewState, workflowStepResults, prInfo, issueInfo, githubTracking,
sourceIssueProvider, sourceIssueRepository, sourceIssueExternalIssueId, sourceIssueNumber, sourceIssueUrl,
@@ -1588,7 +1598,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
workflowStepRetries, stuckKillCount, postReviewFixCount, recoveryRetryCount, taskDoneRetryCount, verificationFailureCount, mergeConflictBounceCount, mergeAuditBounceCount, branchConflictRecoveryCount, reviewerContextRetryCount, reviewerFallbackRetryCount, nextRecoveryAt, error,
summary, thinkingLevel, executionMode, tokenUsageInputTokens, tokenUsageOutputTokens, tokenUsageCachedTokens,
tokenUsageCacheWriteTokens, tokenUsageTotalTokens, tokenUsageFirstUsedAt, tokenUsageLastUsedAt, tokenBudgetSoftAlertedAt, tokenBudgetHardAlertedAt, tokenBudgetOverride, createdAt, updatedAt, columnMovedAt,
executionStartedAt, executionCompletedAt,
firstExecutionAt, cumulativeActiveMs, executionStartedAt, executionCompletedAt,
dependencies, steps, log, attachments, steeringComments,
comments, review, reviewState, workflowStepResults, prInfo, issueInfo, githubTracking,
sourceIssueProvider, sourceIssueRepository, sourceIssueExternalIssueId, sourceIssueNumber, sourceIssueUrl,
@@ -1650,6 +1660,8 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
createdAt = excluded.createdAt,
updatedAt = excluded.updatedAt,
columnMovedAt = excluded.columnMovedAt,
firstExecutionAt = excluded.firstExecutionAt,
cumulativeActiveMs = excluded.cumulativeActiveMs,
executionStartedAt = excluded.executionStartedAt,
executionCompletedAt = excluded.executionCompletedAt,
dependencies = excluded.dependencies,
@@ -3794,13 +3806,27 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
task.columnMovedAt = new Date().toISOString();
task.updatedAt = task.columnMovedAt;
if (fromColumn === "in-progress" && toColumn !== "in-progress") {
const segmentStartMs = Date.parse(task.executionStartedAt ?? task.columnMovedAt);
const segmentEndMs = Date.parse(task.columnMovedAt);
const segmentDeltaMs =
Number.isFinite(segmentStartMs) && Number.isFinite(segmentEndMs)
? Math.max(0, segmentEndMs - segmentStartMs)
: 0;
task.cumulativeActiveMs = Math.max(0, task.cumulativeActiveMs ?? 0) + segmentDeltaMs;
}
// Wall-clock end-to-end runtime: set on first transition into in-progress
// and first transition into done. Never overwritten — see retry-clear
// logic below for the path that resets these for a fresh run.
if (toColumn === "in-progress" && !task.executionStartedAt) {
task.executionStartedAt = task.columnMovedAt;
}
if (toColumn === "in-progress") {
task.cumulativeActiveMs ??= 0;
if (!task.firstExecutionAt) {
task.firstExecutionAt = task.columnMovedAt;
}
if (!task.executionStartedAt) {
task.executionStartedAt = task.columnMovedAt;
}
task.userPaused = undefined;
}
if (toColumn === "done" && !task.executionCompletedAt) {
@@ -3965,7 +3991,7 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
async updateTask(
id: string,
updates: { title?: string; description?: string; priority?: TaskPriority | null; prompt?: string; worktree?: string | null; status?: string | null; dependencies?: string[]; steps?: import("./types.js").TaskStep[]; currentStep?: number; blockedBy?: string | null; overlapBlockedBy?: string | null; assignedAgentId?: string | null; pausedByAgentId?: string | null; pausedReason?: string | null; tokenBudgetSoftAlertedAt?: string | null; tokenBudgetHardAlertedAt?: string | null; tokenBudgetOverride?: import("./types.js").TaskTokenBudgetOverride | null; dispatchStormCount?: number | null; lastDispatchAt?: string | null; assigneeUserId?: string | null; scopeOverride?: boolean | null; scopeOverrideReason?: string | null; nodeId?: string | null; effectiveNodeId?: string | null; effectiveNodeSource?: string | null; checkedOutBy?: string | null; checkedOutAt?: string | null; checkoutNodeId?: string | null; checkoutRunId?: string | null; checkoutLeaseRenewedAt?: string | null; checkoutLeaseEpoch?: number | null; paused?: boolean; baseBranch?: string | null; branch?: string | null; executionStartBranch?: string | null; baseCommitSha?: string | null; size?: "S" | "M" | "L"; reviewLevel?: number; executionMode?: import("./types.js").ExecutionMode | null; mergeRetries?: number; workflowStepRetries?: number; stuckKillCount?: number | null; postReviewFixCount?: number | null; recoveryRetryCount?: number | null; taskDoneRetryCount?: number | null; verificationFailureCount?: number | null; mergeConflictBounceCount?: number | null; mergeAuditBounceCount?: number | null; branchConflictRecoveryCount?: number | null; reviewerContextRetryCount?: number | null; reviewerFallbackRetryCount?: number | null; nextRecoveryAt?: string | null; enabledWorkflowSteps?: string[]; noCommitsExpected?: boolean | null; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; planningModelProvider?: string | null; planningModelId?: string | null; thinkingLevel?: string | null; error?: string | null; summary?: string | null; sessionFile?: string | null; executionStartedAt?: string | null; executionCompletedAt?: string | null; review?: import("./types.js").TaskReview | null; reviewState?: import("./types.js").TaskReviewState | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null; mergeDetails?: import("./types.js").MergeDetails | null; sourceIssue?: import("./types.js").TaskSourceIssue | null; githubTracking?: import("./types.js").TaskGithubTracking | null; tokenUsage?: import("./types.js").TaskTokenUsage | null; modifiedFiles?: string[] | null; missionId?: string | null; sliceId?: string | null },
updates: { title?: string; description?: string; priority?: TaskPriority | null; prompt?: string; worktree?: string | null; status?: string | null; dependencies?: string[]; steps?: import("./types.js").TaskStep[]; currentStep?: number; blockedBy?: string | null; overlapBlockedBy?: string | null; assignedAgentId?: string | null; pausedByAgentId?: string | null; pausedReason?: string | null; tokenBudgetSoftAlertedAt?: string | null; tokenBudgetHardAlertedAt?: string | null; tokenBudgetOverride?: import("./types.js").TaskTokenBudgetOverride | null; dispatchStormCount?: number | null; lastDispatchAt?: string | null; assigneeUserId?: string | null; scopeOverride?: boolean | null; scopeOverrideReason?: string | null; nodeId?: string | null; effectiveNodeId?: string | null; effectiveNodeSource?: string | null; checkedOutBy?: string | null; checkedOutAt?: string | null; checkoutNodeId?: string | null; checkoutRunId?: string | null; checkoutLeaseRenewedAt?: string | null; checkoutLeaseEpoch?: number | null; paused?: boolean; baseBranch?: string | null; branch?: string | null; executionStartBranch?: string | null; baseCommitSha?: string | null; size?: "S" | "M" | "L"; reviewLevel?: number; executionMode?: import("./types.js").ExecutionMode | null; mergeRetries?: number; workflowStepRetries?: number; stuckKillCount?: number | null; postReviewFixCount?: number | null; recoveryRetryCount?: number | null; taskDoneRetryCount?: number | null; verificationFailureCount?: number | null; mergeConflictBounceCount?: number | null; mergeAuditBounceCount?: number | null; branchConflictRecoveryCount?: number | null; reviewerContextRetryCount?: number | null; reviewerFallbackRetryCount?: number | null; nextRecoveryAt?: string | null; enabledWorkflowSteps?: string[]; noCommitsExpected?: boolean | null; modelProvider?: string | null; modelId?: string | null; validatorModelProvider?: string | null; validatorModelId?: string | null; planningModelProvider?: string | null; planningModelId?: string | null; thinkingLevel?: string | null; error?: string | null; summary?: string | null; sessionFile?: string | null; firstExecutionAt?: string | null; cumulativeActiveMs?: number | null; executionStartedAt?: string | null; executionCompletedAt?: string | null; review?: import("./types.js").TaskReview | null; reviewState?: import("./types.js").TaskReviewState | null; workflowStepResults?: import("./types.js").WorkflowStepResult[] | null; mergeDetails?: import("./types.js").MergeDetails | null; sourceIssue?: import("./types.js").TaskSourceIssue | null; githubTracking?: import("./types.js").TaskGithubTracking | null; tokenUsage?: import("./types.js").TaskTokenUsage | null; modifiedFiles?: string[] | null; missionId?: string | null; sliceId?: string | null },
runContext?: RunMutationContext,
): Promise<Task> {
return this.withTaskLock(id, async () => {
@@ -4334,6 +4360,16 @@ export class TaskStore extends EventEmitter<TaskStoreEvents> {
} else if (updates.sessionFile !== undefined) {
task.sessionFile = updates.sessionFile;
}
if (updates.firstExecutionAt === null) {
task.firstExecutionAt = undefined;
} else if (updates.firstExecutionAt !== undefined) {
task.firstExecutionAt = updates.firstExecutionAt;
}
if (updates.cumulativeActiveMs === null) {
task.cumulativeActiveMs = undefined;
} else if (updates.cumulativeActiveMs !== undefined) {
task.cumulativeActiveMs = updates.cumulativeActiveMs;
}
if (updates.executionStartedAt === null) {
task.executionStartedAt = undefined;
} else if (updates.executionStartedAt !== undefined) {

View File

@@ -23,7 +23,7 @@ import { getInReviewStallCopy, shouldShowInReviewStallBadge } from "../utils/inR
import { getStalePausedReviewCopy, shouldShowStalePausedReviewBadge } from "../utils/stalePausedReviewCopy";
import { getTaskAgeStalenessCopy, shouldShowTaskAgeStalenessBadge } from "../utils/taskAgeStalenessCopy";
import { getUnifiedTaskProgress } from "../utils/taskProgress";
import { getEndToEndDurationMs, getTimedDurationMs, getWorkflowRuntimeMs, parseTimestampToMs } from "../utils/taskTiming";
import { getActiveRuntimeMs, getEndToEndDurationMs, getTimedDurationMs, getWorkflowRuntimeMs, parseTimestampToMs } from "../utils/taskTiming";
import type { ToastType } from "../hooks/useToast";
import { useConfirm } from "../hooks/useConfirm";
import { extractDependencyDeleteConflict } from "../utils/taskDelete";
@@ -161,7 +161,10 @@ function getInProgressElapsedMs(task: Task, nowMs: number): number | null {
// inside instrumented code paths. Returns null on legacy tasks that completed
// before `executionStartedAt` was tracked, so callers can fall back.
function getTaskEndToEndDurationMs(task: Task, nowMs: number): number | null {
return getEndToEndDurationMs(task.executionStartedAt, task.executionCompletedAt, nowMs);
if (task.cumulativeActiveMs == null && task.firstExecutionAt == null) {
return getEndToEndDurationMs(task.executionStartedAt, task.executionCompletedAt, nowMs);
}
return getActiveRuntimeMs(task, nowMs);
}
function getInReviewCompletionMs(task: Task): number | null {
@@ -866,7 +869,7 @@ function TaskCardComponent({
}, LIVE_TIME_INDICATOR_POLL_MS);
return () => window.clearInterval(interval);
}, [task.column, task.status, task.columnMovedAt, task.updatedAt, task.workflowStepResults, task.timedExecutionMs, task.executionStartedAt, task.executionCompletedAt]);
}, [task.column, task.status, task.columnMovedAt, task.updatedAt, task.workflowStepResults, task.timedExecutionMs, task.firstExecutionAt, task.cumulativeActiveMs, task.executionStartedAt, task.executionCompletedAt]);
const timeIndicator = useMemo(() => {
if (!TIME_INDICATOR_COLUMNS.has(task.column)) {
@@ -948,7 +951,7 @@ function TaskCardComponent({
title: `Execution time ${elapsedLabel}. Completed ${completedAt}`,
ariaLabel: `Execution time ${elapsedLabel}. Completed ${completedAt}`,
};
}, [task.column, task.status, task.columnMovedAt, task.timedExecutionMs, task.updatedAt, task.workflowStepResults, task.log, task.executionStartedAt, task.executionCompletedAt, timeIndicatorNowMs]);
}, [task.column, task.status, task.columnMovedAt, task.timedExecutionMs, task.updatedAt, task.workflowStepResults, task.log, task.firstExecutionAt, task.cumulativeActiveMs, task.executionStartedAt, task.executionCompletedAt, timeIndicatorNowMs]);
const liveBadgeData = badgeUpdates.get(`${projectId ?? "default"}:${task.id}`);

View File

@@ -1,5 +1,5 @@
import type { Task, TaskTokenUsage, WorkflowStepResult } from "@fusion/core";
import { extractTimingEvents, getEndToEndDurationMs, getTimedDurationMs, getWorkflowRuntimeMs, type TimingEvent } from "../utils/taskTiming";
import { extractTimingEvents, getActiveRuntimeMs, getEndToEndDurationMs, getTimedDurationMs, getWallClockSinceFirstExecutionMs, getWorkflowRuntimeMs, type TimingEvent } from "../utils/taskTiming";
import "./TaskTokenStatsPanel.css";
interface TaskTokenStatsPanelProps {
@@ -28,6 +28,10 @@ interface TaskTokenStatsPanelProps {
| "sessionFile"
| "executionStartedAt"
| "executionCompletedAt"
| "firstExecutionAt"
| "cumulativeActiveMs"
| "column"
| "columnMovedAt"
>;
}
@@ -126,15 +130,26 @@ export function TaskTokenStatsPanel({ tokenUsage, loading, task }: TaskTokenStat
}, undefined);
const workflowTiming = summarizeWorkflowTiming(task?.workflowStepResults ?? []);
const activeRuntimeMs = task ? getActiveRuntimeMs(task, nowMs) : null;
const endToEndDurationMs = getEndToEndDurationMs(task?.executionStartedAt, task?.executionCompletedAt, nowMs);
const wallClockSinceFirstExecutionMs = getWallClockSinceFirstExecutionMs(
task?.firstExecutionAt,
task?.executionCompletedAt,
nowMs,
);
// Canonical fallback order for Task Detail Stats total runtime:
// 1) durable wall-clock execution window (`executionStartedAt` → `executionCompletedAt`),
// 2) server aggregate `timedExecutionMs` when present,
// 3) legacy local aggregate (`[timing]` sum + workflow runtime).
// This avoids double counting when workflow timings appear in both `[timing]`
// logs and `workflowStepResults`.
const totalExecutionMs = endToEndDurationMs
?? (typeof task?.timedExecutionMs === "number" ? task.timedExecutionMs : totalTimingDurationMs + workflowTiming.totalDurationMs);
const totalExecutionMs = activeRuntimeMs
?? (typeof task?.timedExecutionMs === "number"
? task.timedExecutionMs
: endToEndDurationMs ?? (totalTimingDurationMs + workflowTiming.totalDurationMs));
const showWallClockSinceFirstExecution =
wallClockSinceFirstExecutionMs != null
&& wallClockSinceFirstExecutionMs !== totalExecutionMs;
const taskStepCount = task?.steps?.length ?? 0;
return (
@@ -164,6 +179,12 @@ export function TaskTokenStatsPanel({ tokenUsage, loading, task }: TaskTokenStat
<span className="task-token-stats-panel__label">Total execution time</span>
<span className="task-token-stats-panel__value">{formatDuration(totalExecutionMs)}</span>
</div>
{showWallClockSinceFirstExecution ? (
<div className="task-token-stats-panel__metric" role="listitem">
<span className="task-token-stats-panel__label">Wall-clock since first execution</span>
<span className="task-token-stats-panel__value">{formatDuration(wallClockSinceFirstExecutionMs)}</span>
</div>
) : null}
</div>
<dl className="task-token-stats-panel__timestamps">

View File

@@ -2323,6 +2323,31 @@ describe("TaskCard", () => {
expect(container.querySelector(".card-time-indicator")?.getAttribute("title")).toBe("Execution time 35m");
});
it("shows cumulative runtime across a user reopen", () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-15T13:17:00.000Z"));
const { container } = render(
<TaskCard
task={makeTask({
column: "in-review",
firstExecutionAt: "2026-05-15T08:42:00.000Z",
cumulativeActiveMs: 6 * 60_000,
executionStartedAt: "2026-05-15T13:15:00.000Z",
columnMovedAt: "2026-05-15T13:17:00.000Z",
updatedAt: "2026-05-15T13:17:00.000Z",
})}
onOpenDetail={noop}
addToast={noop}
/>,
);
const timer = container.querySelector(".card-time-indicator");
expect(timer).not.toBeNull();
expect(timer?.textContent).toContain("6m");
expect(timer?.getAttribute("title")).toBe("Execution time 6m");
});
it.each(["merging", "merging-fix"] as const)("shows live merge elapsed in timer chip while task.status is %s", (status) => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-04-25T13:45:00.000Z"));

View File

@@ -1,4 +1,4 @@
import { describe, expect, it } from "vitest";
import { describe, expect, it, vi } from "vitest";
import { render, screen } from "@testing-library/react";
import { TaskTokenStatsPanel } from "../TaskTokenStatsPanel";
import type { Task } from "@fusion/core";
@@ -188,6 +188,33 @@ describe("TaskTokenStatsPanel", () => {
expect(screen.getByText("5m 0s")).toBeInTheDocument();
});
it("shows cumulative active runtime for in-progress tasks", () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-05-15T13:16:00.000Z"));
try {
render(
<TaskTokenStatsPanel
loading={false}
tokenUsage={undefined}
task={makeTask({
column: "in-progress",
cumulativeActiveMs: 240_000,
executionStartedAt: "2026-05-15T13:15:00.000Z",
firstExecutionAt: "2026-05-15T08:42:00.000Z",
timedExecutionMs: undefined,
workflowStepResults: [],
log: [],
})}
/>,
);
const metric = screen.getByText("Total execution time").closest(".task-token-stats-panel__metric");
expect(metric).toHaveTextContent("5m 0s");
} finally {
vi.useRealTimers();
}
});
it("does not double count workflow runtime when timedExecutionMs is present", () => {
render(
<TaskTokenStatsPanel

View File

@@ -0,0 +1,43 @@
import { describe, it, expect } from "vitest";
import { getActiveRuntimeMs, getWallClockSinceFirstExecutionMs } from "../taskTiming";
describe("taskTiming helpers", () => {
it("returns persisted plus live segment for in-progress tasks", () => {
const nowMs = Date.parse("2026-05-15T13:16:00.000Z");
const runtime = getActiveRuntimeMs(
{
column: "in-progress",
cumulativeActiveMs: 240_000,
executionStartedAt: "2026-05-15T13:15:00.000Z",
columnMovedAt: "2026-05-15T13:15:00.000Z",
},
nowMs,
);
expect(runtime).toBe(300_000);
});
it("returns null when there is no active-runtime signal", () => {
const runtime = getActiveRuntimeMs(
{
column: "todo",
cumulativeActiveMs: undefined,
executionStartedAt: undefined,
columnMovedAt: undefined,
},
Date.now(),
);
expect(runtime).toBeNull();
});
it("returns wall-clock runtime since first execution", () => {
const wallClock = getWallClockSinceFirstExecutionMs(
"2026-05-15T08:42:00.000Z",
"2026-05-15T13:17:00.000Z",
Date.parse("2026-05-15T13:20:00.000Z"),
);
expect(wallClock).toBe(16_500_000);
});
});

View File

@@ -1,4 +1,4 @@
import type { TaskLogEntry, WorkflowStepResult } from "@fusion/core";
import type { Task, TaskLogEntry, WorkflowStepResult } from "@fusion/core";
export interface TimingEvent {
timestamp: string;
@@ -92,3 +92,37 @@ export function getEndToEndDurationMs(
const endMs = completedMs != null && completedMs >= startedMs ? completedMs : nowMs;
return Math.max(0, endMs - startedMs);
}
export function getActiveRuntimeMs(
task: Pick<Task, "column" | "cumulativeActiveMs" | "executionStartedAt" | "columnMovedAt">,
nowMs: number,
): number | null {
const persisted = task.cumulativeActiveMs;
const base = persisted ?? 0;
if (task.column === "in-progress") {
const startedMs = parseTimestampToMs(task.executionStartedAt);
if (startedMs != null) {
return base + Math.max(0, nowMs - startedMs);
}
}
if (persisted != null) {
return Math.max(0, persisted);
}
return null;
}
export function getWallClockSinceFirstExecutionMs(
firstExecutionAt: string | undefined,
executionCompletedAt: string | undefined,
nowMs: number,
): number | null {
const firstMs = parseTimestampToMs(firstExecutionAt);
if (firstMs == null) return null;
const completedMs = parseTimestampToMs(executionCompletedAt);
const endMs = completedMs != null ? completedMs : nowMs;
return Math.max(0, endMs - firstMs);
}