Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(server): track session lastActiveAt with migration and backfill (#280)

Yaowei Zheng0fe3ef4c420d
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 82516f42..df107910 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -746,6 +746,22 @@ export interface SessionInfo {
/** Session source (for list badges/folders), derived from core session_meta — the single source of truth (not stored in the DB); unset for user-created sessions. */
source?: SessionSource;
createdAt: string;
+ /**
+ * Last activity the server drove for this Session (ISO 8601, same convention as
+ * createdAt), monotonic — it never moves backwards. Set to createdAt at creation, then
+ * stamped when a run starts and again when it ends; a run here is one Task, one
+ * compaction, or one whole goal loop (every round of a goal belongs to a single run, so
+ * an N-round goal stamps twice, not 2N times).
+ *
+ * Two kinds of row therefore stay at createdAt no matter how busy they look: Sessions
+ * adopted from a CLI Trace (this server drives none of their runs) and subagent rows
+ * (their work is driven through the parent Session's entry). Reading real activity for
+ * those would mean consulting the Trace tree, which this field deliberately does not do.
+ *
+ * Rows that predate the field are backfilled once at startup from the Session's most
+ * recent request timestamp, falling back to createdAt.
+ */
+ lastActiveAt: string;
status: SessionStatus;
/** Number of approvals awaiting human decision (a persisted count outside server events, for list badges). */
pendingApprovalCount: number;
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index c4cc9580..ac938795 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -236,6 +236,7 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
titles,
log,
goals: goalsRepo,
+ ...(overrides.now ? { now: overrides.now } : {}),
});
managerRef = manager;
diff --git a/packages/server/src/db/database.ts b/packages/server/src/db/database.ts
index 07341102..9c75d673 100644
--- a/packages/server/src/db/database.ts
+++ b/packages/server/src/db/database.ts
@@ -31,12 +31,50 @@ export function openDatabase(dbPath: string): DatabaseSync {
ensureColumn(db, "sessions", "has_trace", "INTEGER NOT NULL DEFAULT 0");
ensureColumn(db, "auth_sessions", "via", "TEXT");
ensureColumn(db, "trace_files", "page_stats", "TEXT");
+ // Superseded by idx_usage_session_ts (session_id, ts), which SCHEMA_SQL just created on
+ // this database: the old index is a strict prefix of it, so every query it served is
+ // served identically. Dropping is safe — an index is derived, never data.
+ db.exec("DROP INDEX IF EXISTS idx_usage_session");
+ upgradeLastActiveAt(db);
return db;
}
-/** Idempotent per-column upgrade for databases formed before the column existed. */
-function ensureColumn(db: DatabaseSync, table: string, column: string, ddl: string): void {
+/**
+ * One-time `sessions.last_active_at` upgrade, ALTER + backfill in a single transaction.
+ *
+ * The backfill runs **only in the open that actually adds the column** (SQLite's ALTER
+ * TABLE ADD COLUMN is transactional, so a crash mid-upgrade rolls back to "no column" and
+ * the next open redoes both halves — never a half-migrated table, and never a full
+ * `sessions` scan on the millions of opens that follow). Legacy rows take the session's
+ * most recent request timestamp — usage_records, covered by idx_usage_session_ts, the
+ * closest persisted proxy for "last Trace activity" — else their own created_at.
+ */
+function upgradeLastActiveAt(db: DatabaseSync): void {
+ db.exec("BEGIN");
+ try {
+ if (ensureColumn(db, "sessions", "last_active_at", "TEXT")) {
+ db.exec(
+ `UPDATE sessions SET last_active_at = COALESCE(
+ (SELECT MAX(ts) FROM usage_records WHERE usage_records.session_id = sessions.session_id),
+ created_at
+ )`,
+ );
+ }
+ db.exec("COMMIT");
+ } catch (err) {
+ db.exec("ROLLBACK");
+ throw err;
+ }
+}
+
+/**
+ * Idempotent per-column upgrade for databases formed before the column existed.
+ * Returns whether this call actually ALTERed the table (false = the column was already
+ * there), so a caller can gate one-time backfill work on it.
+ */
+function ensureColumn(db: DatabaseSync, table: string, column: string, ddl: string): boolean {
const cols = db.prepare(`PRAGMA table_info(${table})`).all() as { name: string }[];
- if (cols.some((c) => c.name === column)) return;
+ if (cols.some((c) => c.name === column)) return false;
db.exec(`ALTER TABLE ${table} ADD COLUMN ${column} ${ddl}`);
+ return true;
}
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index 7196c239..da933264 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -29,6 +29,15 @@ export interface SessionRow {
client?: "web" | "cli" | null;
/** Cache: a Trace record exists (set at task start / adoption / subagent registration; backfilled by list hydration). */
hasTrace?: boolean;
+ /**
+ * Last activity this server drove for the session, ISO: stamped once when a run starts
+ * and once when it ends (see SessionManager.drive — a goal run is ONE drive over all its
+ * rounds, so it stamps twice, not per round). Set to createdAt at insert, and only ever
+ * moves forward (markDriven/touchLastActive clamp with MAX, so a backwards clock step
+ * cannot regress it). Rows this server never drives — CLI-adopted Sessions, subagent
+ * rows (their activity is driven through the parent's entry) — keep createdAt.
+ */
+ lastActiveAt: string;
createdAt: string;
}
@@ -45,6 +54,9 @@ function mapRow(r: Record<string, unknown>): SessionRow {
archivedAt: (r.archived_at as string | null) ?? null,
client: (r.client as "web" | "cli" | null) ?? null,
hasTrace: (r.has_trace as number) === 1,
+ // The open-time backfill leaves no NULLs; the coalesce only hardens against a row
+ // somehow inserted as NULL (degrades to createdAt instead of surfacing undefined).
+ lastActiveAt: (r.last_active_at as string | null) ?? (r.created_at as string),
createdAt: r.created_at as string,
};
}
@@ -53,32 +65,27 @@ export class SessionsRepo {
constructor(private readonly db: DatabaseSync) {}
insert(row: SessionRow): void {
- this.db
- .prepare(
- `INSERT INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, approval_mode, title, client, has_trace, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
- )
- .run(
- row.sessionId,
- row.projectId,
- row.agentId,
- row.provider,
- row.modelId,
- row.workspace,
- row.approvalMode,
- row.title,
- row.client ?? null,
- row.hasTrace ? 1 : 0,
- row.createdAt,
- );
+ this.runInsert("INSERT", row);
}
/** Idempotent insert: used when Trace directory discovery backfills a row (concurrent listing discovering the same Session no longer triggers a UNIQUE violation). */
insertOrIgnore(row: SessionRow): void {
+ this.runInsert("INSERT OR IGNORE", row);
+ }
+
+ /**
+ * The two inserts' shared column list and binding order (they differ only in conflict
+ * handling). `last_active_at` defaults **in SQL** (`COALESCE(?, ?)` over the row's own
+ * created_at, bound twice — SQLite forbids referencing a sibling column inside VALUES,
+ * and a column added by ALTER TABLE cannot be given a DEFAULT): the column is nullable
+ * for legacy reasons, so this is the one place that can guarantee it is never written
+ * NULL, whatever a caller passes.
+ */
+ private runInsert(verb: "INSERT" | "INSERT OR IGNORE", row: SessionRow): void {
this.db
.prepare(
- `INSERT OR IGNORE INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, approval_mode, title, client, has_trace, created_at)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
+ `${verb} INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, approval_mode, title, client, has_trace, last_active_at, created_at)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, COALESCE(?, ?), ?)`,
)
.run(
row.sessionId,
@@ -91,15 +98,42 @@ export class SessionsRepo {
row.title,
row.client ?? null,
row.hasTrace ? 1 : 0,
+ row.lastActiveAt ?? null,
+ row.createdAt,
row.createdAt,
);
}
- /** Flip the has_trace cache once a Trace record exists (task start / discovery hydration); idempotent. */
+ /** Flip the has_trace cache once a Trace record exists (discovery hydration); idempotent. */
markHasTrace(sessionId: string): void {
this.db.prepare("UPDATE sessions SET has_trace = 1 WHERE session_id = ?").run(sessionId);
}
+ /**
+ * A driven run touched this Session: flip the has_trace cache and stamp last_active_at in
+ * ONE statement (drive's run start — one WAL commit instead of two).
+ * `MAX(COALESCE(...))` keeps the stamp monotonic: a backwards clock step (NTP, resume
+ * from suspend) leaves the stored value alone rather than regressing the row.
+ */
+ markDriven(sessionId: string, at: string): void {
+ this.db
+ .prepare(
+ `UPDATE sessions SET has_trace = 1, last_active_at = MAX(COALESCE(last_active_at, ''), ?)
+ WHERE session_id = ?`,
+ )
+ .run(at, sessionId);
+ }
+
+ /** Stamp last_active_at alone (drive's run end); monotonic like markDriven. */
+ touchLastActive(sessionId: string, at: string): void {
+ this.db
+ .prepare(
+ `UPDATE sessions SET last_active_at = MAX(COALESCE(last_active_at, ''), ?)
+ WHERE session_id = ?`,
+ )
+ .run(at, sessionId);
+ }
+
findById(sessionId: string): SessionRow | null {
const r = this.db.prepare("SELECT * FROM sessions WHERE session_id = ?").get(sessionId);
return r ? mapRow(r) : null;
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index d86a5ca8..7e1105cf 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -7,7 +7,9 @@
* Product not yet released: no migration branches — everything is CREATE IF NOT EXISTS, formed
* once. The one exception: columns added to an existing table after release of a web.db are
* ALTERed in by the idempotent per-column guard in database.ts (ensureColumn), since CREATE
- * TABLE IF NOT EXISTS never touches an existing table.
+ * TABLE IF NOT EXISTS never touches an existing table. A *reshaped* index follows the same
+ * rule under a new name, with the superseded one dropped on open (idx_usage_session →
+ * idx_usage_session_ts): CREATE INDEX IF NOT EXISTS never rebuilds an existing index either.
*/
export const SCHEMA_SQL = `
@@ -54,6 +56,7 @@ CREATE TABLE IF NOT EXISTS sessions (
archived_at TEXT, -- archive time; NULL=not archived (shown by default; archived ones move under "Archived")
client TEXT, -- creating client: 'web' (created via the Web App) | 'cli' (adopted from a CLI Trace); NULL = legacy row, treated as web
has_trace INTEGER NOT NULL DEFAULT 0, -- cache: a Trace record exists (set at task start / adoption / subagent registration; lazily backfilled by list hydration)
+ last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill
created_at TEXT NOT NULL
); -- the schedule/subagent SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row)
CREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);
@@ -74,7 +77,7 @@ CREATE TABLE IF NOT EXISTS usage_records (
status TEXT NOT NULL DEFAULT 'completed' -- request outcome: completed=success (with tokens); others=failure (0 tokens, for success rate)
); -- cost is not stored: computed at query time from current pricing
CREATE INDEX IF NOT EXISTS idx_usage_project_date ON usage_records(project_id, date);
-CREATE INDEX IF NOT EXISTS idx_usage_session ON usage_records(session_id);
+CREATE INDEX IF NOT EXISTS idx_usage_session_ts ON usage_records(session_id, ts); -- (session_id) alone was idx_usage_session (dropped on open): ts makes the last_active_at backfill's MAX(ts) a covering index scan instead of a random row lookup per usage record
CREATE TABLE IF NOT EXISTS error_records ( -- server-side error capture (the Costs page's "Errors" tab)
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 0fec133a..94694bd4 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -460,8 +460,14 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
updated = { ...updated, archivedAt: at };
}
const hasTrace = await deps.sessionService.hasTrace(updated);
+ // Re-read after the writes (and after the awaits above): a run finishing anywhere in
+ // this window advances last_active_at, and `updated` is a snapshot taken before the
+ // PATCH even started. Returning it would hand back a REGRESSED value that the web
+ // store swaps in wholesale, rolling the row backwards with no event to repair it.
+ // Falls back to the snapshot if the Session was deleted meanwhile.
+ const fresh = deps.sessionsRepo.findById(row.sessionId) ?? updated;
return c.json({
- session: await deps.sessionService.toInfo(updated, hasTrace),
+ session: await deps.sessionService.toInfo(fresh, hasTrace),
} satisfies SessionResponse);
});
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index e78464b9..264200cf 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -222,6 +222,12 @@ export interface SessionManagerDeps {
log?: (line: string) => void;
/** Goal run-state persistence (optional like `titles`: without it, goals run but leave no restorable record). */
goals?: GoalsRepo;
+ /**
+ * Clock for persisted timestamps (last_active_at). Injected like the other services' so a
+ * stubbed clock moves this and `usage_records.ts` together — the pairing the legacy
+ * backfill assumes when it reads MAX(ts) as a session's last activity.
+ */
+ now?: () => Date;
}
/** One queued follow-up task (`queueIfBusy`): the task input plus the per-turn thinking level it was posted with. */
@@ -396,9 +402,12 @@ export class SessionManager {
/** Open streaming fragments of running sessions (fed by drive, served to GET /messages; see live-tail.ts). */
private readonly liveTail = new LiveTailTracker();
private readonly sweepTimer: NodeJS.Timeout;
+ /** Clock for persisted timestamps (see SessionManagerDeps.now); wall clock unless injected. */
+ private readonly now: () => Date;
constructor(private readonly deps: SessionManagerDeps) {
this.log = deps.log ?? ((line) => console.error(line));
+ this.now = deps.now ?? (() => new Date());
this.sweepTimer = setInterval(() => this.sweepIdle(), ENTRY_SWEEP_INTERVAL_MS);
this.sweepTimer.unref?.();
}
@@ -1192,10 +1201,6 @@ export class SessionManager {
gen: AsyncGenerator<OmniMessage>,
titleSource?: { userExcerpt: string },
): Promise<void> {
- // Every driven run (task, goal round, compaction) writes Trace lines: flip the row's
- // has_trace cache here, the single choke point, so listing can serve it from the DB
- // without a directory walk (see SessionService.listSessions).
- this.deps.sessions.markHasTrace(entry.sessionId);
let earlyTitleFired = false;
let mainBodyChars = 0;
const ctx: UsageContext = {
@@ -1205,6 +1210,17 @@ export class SessionManager {
provider: entry.provider,
modelId: entry.modelId,
};
+ // Every driven run (a Task, a compaction, or a whole goal loop — startGoal hands all of
+ // its rounds to ONE drive) writes Trace lines: flip the row's has_trace cache here, the
+ // single choke point, so listing can serve it from the DB without a directory walk (see
+ // SessionService.listSessions). The same statement stamps last_active_at, so a run costs
+ // one row write here and one more when it ends (see the finally) — never one per streamed
+ // message; activity during the run (steering, approvals, queued follow-ups) rides on the
+ // run-end stamp. Guarded: this runs BEFORE the try below, so an unexpected DB failure
+ // (a closed handle after shutdown) would otherwise reject drive() with no finally to
+ // reach — leaving the entry pinned "running" and every later Task 409ing for the
+ // process's lifetime.
+ this.touchRow(ctx, (repo, at) => repo.markDriven(ctx.sessionId, at));
// LLM request failures and tool execution failures aren't expressed via throw (core
// converges them into the message stream), so the try/catch below can't catch them:
// the watcher inspects messages one by one and fishes them out for persistence
@@ -1371,6 +1387,14 @@ export class SessionManager {
// now-empty state.
entry.pendingSteering = [];
entry.lastActivityMs = Date.now();
+ // Run-end stamp (see the run-start counterpart at the top of drive). Guarded like
+ // every other write in this finally: what follows — the idle broadcast, title
+ // generation, and the auto-start of queued follow-ups (this is its only call site) —
+ // must not be skippable by a DB failure, or SSE clients would sit on "running"
+ // forever with their queue stranded. A no-op UPDATE when the row is already gone:
+ // deletion normally awaits the drive first, so that only happens once its 5s wait
+ // times out.
+ this.touchRow(ctx, (repo, at) => repo.touchLastActive(ctx.sessionId, at));
this.publishState(entry, "idle");
if (titleSource && titleSource.userExcerpt.trim()) {
// Attempt generation whenever there's user material; whether generation is
@@ -1438,6 +1462,7 @@ export class SessionManager {
// row deliberately stores no source column.
const source = asSessionSource(p.source) ?? "subagent";
this.deps.sources.set(childSid, source);
+ const createdAt = this.now().toISOString();
this.deps.sessions.insertOrIgnore({
sessionId: childSid,
projectId: entry.projectId,
@@ -1451,7 +1476,10 @@ export class SessionManager {
title: null,
// Spawned by this server's run (client NULL = web); its Trace exists by construction.
hasTrace: true,
- createdAt: new Date().toISOString(),
+ // A subagent's own runs are driven through the PARENT entry's drive, so nothing ever
+ // stamps this row: it stays at its registration time (see SessionRow.lastActiveAt).
+ lastActiveAt: createdAt,
+ createdAt,
});
// Make the subagent appear immediately in the sidebar: notify via the parent
// Session's channel (a frontend currently watching the parent run refreshes its list in place).
@@ -1473,6 +1501,25 @@ export class SessionManager {
return child;
}
+ /**
+ * Runs one `sessions` row write for a driven run's bookkeeping (has_trace /
+ * last_active_at), swallowing failures the same way the per-message `recorder.record`
+ * call does: bookkeeping must never take down a run's lifecycle. The two call sites both
+ * sit outside a covering try — the run-start write precedes drive's try block, the
+ * run-end one lives in its finally — and the realistic failure (the DatabaseSync handle
+ * closed by shutdown while a run outlived its drain window) throws ERR_INVALID_STATE.
+ */
+ private touchRow(ctx: UsageContext, write: (repo: SessionsRepo, at: string) => void): void {
+ try {
+ write(this.deps.sessions, this.now().toISOString());
+ } catch (err) {
+ this.log(
+ `[session] last-active bookkeeping failed: ${err instanceof Error ? err.message : String(err)}`,
+ );
+ this.deps.errors?.record({ source: "session", err, ctx, code: "session_touch_failed" });
+ }
+ }
+
private publishState(entry: RuntimeEntry, state: SessionStatus): void {
// Every state flip also reports the queued follow-up count and the undelivered steering
// mirror, so subscribers can render both hints without a dedicated event type.
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 46203d42..e6db5bc6 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -82,6 +82,7 @@ export class SessionService {
...(row.title !== null ? { title: row.title } : {}),
...(source !== undefined ? { source } : {}),
createdAt: row.createdAt,
+ lastActiveAt: row.lastActiveAt,
status: this.deps.manager.statusOf(row.sessionId),
pendingApprovalCount: this.deps.manager.pendingApprovalCount(row.sessionId),
pendingFollowUpCount: this.deps.manager.pendingFollowUpCount(row.sessionId),
@@ -356,6 +357,7 @@ export class SessionService {
session.sessionId,
isSessionMeta(metaMsg) ? (asSessionSource(metaMsg.payload.source) ?? null) : null,
);
+ const createdAt = new Date().toISOString();
const row: SessionRow = {
sessionId: session.sessionId,
projectId: args.projectId,
@@ -368,7 +370,9 @@ export class SessionService {
// Everything created through this service is the Web App's (schedule runs included);
// "cli" is stamped only by Trace adoption. NULL means a legacy row, treated as web.
client: "web",
- createdAt: new Date().toISOString(),
+ // Creation is the first activity; the first driven run advances it (see SessionManager.drive).
+ lastActiveAt: createdAt,
+ createdAt,
};
this.deps.sessions.insert(row);
this.deps.manager.adopt(row, session);
@@ -437,6 +441,7 @@ export class SessionService {
if (facts.provider === null || facts.modelId === null) return null;
// Registration already narrowed the origin; record it in the registry (single source of truth).
this.deps.sources.set(sessionId, facts.source);
+ const createdAt = sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString();
const row: SessionRow = {
sessionId,
projectId,
@@ -451,7 +456,11 @@ export class SessionService {
// (web-only) excludes these rows; the "show CLI sessions" preference includes them.
client: "cli",
hasTrace: true,
- createdAt: sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString(),
+ createdAt,
+ // The CLI's own activity leaves no mark on this row (this server drives none of its
+ // runs), so an adopted Session reads as last-active at its creation time until it is
+ // resumed here; the Trace tail is not consulted (see SessionRow.lastActiveAt).
+ lastActiveAt: createdAt,
};
// Idempotent backfill: concurrent list calls may discover the same Session for the first time simultaneously (consistent with AgentsRepo's convention).
this.deps.sessions.insertOrIgnore(row);
diff --git a/packages/server/test/agent-trace-detail.test.ts b/packages/server/test/agent-trace-detail.test.ts
index a3234ba9..57f29a26 100644
--- a/packages/server/test/agent-trace-detail.test.ts
+++ b/packages/server/test/agent-trace-detail.test.ts
@@ -145,6 +145,7 @@ describe("agent-trace-detail", () => {
title: "已生成的标题",
client: "cli",
createdAt: "2026-07-06T09:00:00.000Z",
+ lastActiveAt: "2026-07-06T09:00:00.000Z",
});
const titled = (await (
await owner.get(`${base()}?limit=10&cli=1`)
diff --git a/packages/server/test/body-limit.test.ts b/packages/server/test/body-limit.test.ts
index ef1caad3..9f2a25d1 100644
--- a/packages/server/test/body-limit.test.ts
+++ b/packages/server/test/body-limit.test.ts
@@ -82,6 +82,7 @@ describe("request body cap", () => {
approvalMode: "allow-all",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
runs = [];
diff --git a/packages/server/test/db-upgrade.test.ts b/packages/server/test/db-upgrade.test.ts
index 0d88a2b6..0b1d9bc4 100644
--- a/packages/server/test/db-upgrade.test.ts
+++ b/packages/server/test/db-upgrade.test.ts
@@ -8,8 +8,11 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
+import type { DatabaseSync } from "node:sqlite";
import { openDatabase } from "../src/db/database.js";
+import { SCHEMA_SQL } from "../src/db/schema.js";
import { SessionsRepo } from "../src/db/repos/sessions.js";
+import type { SessionRow } from "../src/db/repos/sessions.js";
const sqlite = process.getBuiltinModule("node:sqlite");
@@ -19,9 +22,38 @@ beforeEach(async () => {
dir = await mkdtemp(path.join(tmpdir(), "penguin-db-upgrade-"));
});
afterEach(async () => {
- await rm(dir, { recursive: true, force: true });
+ // maxRetries for the same reason helpers.ts documents: on Windows a handle that is
+ // closing can hold the directory briefly, and an unretried rm turns that into a failure.
+ await rm(dir, { recursive: true, force: true, maxRetries: 10 });
});
+/**
+ * Seeds a database in the shape it had **before** last_active_at existed, derived from the
+ * real SCHEMA_SQL rather than a hand-copied DDL replica (a copy silently forks from the
+ * schema it is supposed to imitate): create today's schema, then undo exactly the two
+ * things this change introduced — the column, and the reshaped usage index.
+ */
+function seedPreLastActiveDb(dbPath: string, seed: (db: DatabaseSync) => void): void {
+ const db = new sqlite.DatabaseSync(dbPath);
+ try {
+ db.exec(SCHEMA_SQL);
+ db.exec("ALTER TABLE sessions DROP COLUMN last_active_at");
+ db.exec("DROP INDEX IF EXISTS idx_usage_session_ts");
+ db.exec("CREATE INDEX IF NOT EXISTS idx_usage_session ON usage_records(session_id)");
+ seed(db);
+ } finally {
+ db.close();
+ }
+}
+
+/** Reads the stored cell directly, bypassing mapRow's coalesce (which would mask a NULL). */
+function rawLastActive(db: DatabaseSync, sessionId: string): unknown {
+ const r = db
+ .prepare("SELECT last_active_at AS v FROM sessions WHERE session_id = ?")
+ .get(sessionId) as { v: unknown } | undefined;
+ return r?.v;
+}
+
describe("openDatabase column upgrade", () => {
it("adds client/has_trace to a sessions table formed before the columns existed", () => {
const dbPath = path.join(dir, "web.db");
@@ -56,6 +88,8 @@ describe("openDatabase column upgrade", () => {
expect(legacy).not.toBeNull();
expect(legacy!.client).toBeNull();
expect(legacy!.hasTrace).toBe(false);
+ // last_active_at is ALTERed in too; with no usage_records the backfill falls to created_at.
+ expect(legacy!.lastActiveAt).toBe("2026-01-01T00:00:00.000Z");
expect(repo.listByAgent("p1", "a1", { webOnly: true }).map((r) => r.sessionId)).toEqual([
"session-legacy",
]);
@@ -72,6 +106,7 @@ describe("openDatabase column upgrade", () => {
client: "cli",
hasTrace: true,
createdAt: "2026-01-02T00:00:00.000Z",
+ lastActiveAt: "2026-01-02T00:00:00.000Z",
});
expect(repo.findById("session-new")!.client).toBe("cli");
expect(repo.listByAgent("p1", "a1", { webOnly: true }).map((r) => r.sessionId)).toEqual([
@@ -92,8 +127,152 @@ describe("openDatabase column upgrade", () => {
const cols = db.prepare("PRAGMA table_info(sessions)").all() as { name: string }[];
expect(cols.filter((c) => c.name === "client")).toHaveLength(1);
expect(cols.filter((c) => c.name === "has_trace")).toHaveLength(1);
+ expect(cols.filter((c) => c.name === "last_active_at")).toHaveLength(1);
+ } finally {
+ db.close();
+ }
+ });
+
+ it("backfills last_active_at once: last request timestamp when the session has usage, else created_at", () => {
+ const dbPath = path.join(dir, "web.db");
+ seedPreLastActiveDb(dbPath, (old) => {
+ const insertSession = old.prepare(
+ `INSERT INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, created_at)
+ VALUES (?, 'p1', 'a1', 'custom', 'm1', '/w', ?)`,
+ );
+ insertSession.run("session-used", "2026-01-01T00:00:00.000Z");
+ insertSession.run("session-quiet", "2026-01-02T00:00:00.000Z");
+ const insertUsage = old.prepare(
+ `INSERT INTO usage_records (ts, date, project_id, agent_id, session_id, provider, model_id, cache_read, cache_write, output, total)
+ VALUES (?, ?, 'p1', 'a1', 'session-used', 'custom', 'm1', 0, 0, 1, 1)`,
+ );
+ insertUsage.run("2026-02-01T10:00:00.000Z", "2026-02-01");
+ insertUsage.run("2026-02-03T09:30:00.000Z", "2026-02-03");
+ });
+
+ const db = openDatabase(dbPath);
+ try {
+ const repo = new SessionsRepo(db);
+ // The most recent request timestamp is the closest persisted proxy for last Trace
+ // activity. Read raw as well: mapRow would report created_at for a row the backfill
+ // never touched, hiding a no-op migration behind a plausible-looking value.
+ expect(rawLastActive(db, "session-used")).toBe("2026-02-03T09:30:00.000Z");
+ expect(repo.findById("session-used")!.lastActiveAt).toBe("2026-02-03T09:30:00.000Z");
+ // No usage rows: falls back to the row's own created_at.
+ expect(rawLastActive(db, "session-quiet")).toBe("2026-01-02T00:00:00.000Z");
+ // The reshaped usage index is in place and the superseded one is gone.
+ const indexes = (
+ db
+ .prepare("SELECT name FROM sqlite_master WHERE type = 'index' AND name LIKE 'idx_usage%'")
+ .all() as { name: string }[]
+ ).map((r) => r.name);
+ expect(indexes).toContain("idx_usage_session_ts");
+ expect(indexes).not.toContain("idx_usage_session");
+ // A live value written after the upgrade must survive reopens.
+ repo.touchLastActive("session-quiet", "2026-03-01T00:00:00.000Z");
+ } finally {
+ db.close();
+ }
+
+ const reopened = openDatabase(dbPath);
+ try {
+ const repo = new SessionsRepo(reopened);
+ expect(repo.findById("session-used")!.lastActiveAt).toBe("2026-02-03T09:30:00.000Z");
+ expect(repo.findById("session-quiet")!.lastActiveAt).toBe("2026-03-01T00:00:00.000Z");
+ } finally {
+ reopened.close();
+ }
+ });
+
+ it("the backfill is gated on the ALTER: a later open neither re-runs it nor rewrites a row", () => {
+ const dbPath = path.join(dir, "web.db");
+ seedPreLastActiveDb(dbPath, (old) => {
+ old
+ .prepare(
+ `INSERT INTO sessions (session_id, project_id, agent_id, provider, model_id, workspace, created_at)
+ VALUES ('session-1', 'p1', 'a1', 'custom', 'm1', '/w', '2026-01-01T00:00:00.000Z')`,
+ )
+ .run();
+ });
+ const first = openDatabase(dbPath);
+ // Blank the cell by hand: only a re-running backfill would fill it in again, so this
+ // pins that the migration is scoped to the open that actually adds the column (a
+ // `sessions` full scan on every open forever is the cost of getting this wrong).
+ first.exec("UPDATE sessions SET last_active_at = NULL");
+ first.close();
+
+ const db = openDatabase(dbPath);
+ try {
+ expect(rawLastActive(db, "session-1")).toBeNull();
+ // ...and mapRow's coalesce is what keeps that invisible to callers: the safety net,
+ // not the mechanism (nothing else can repair a NULL once the gate has closed).
+ expect(new SessionsRepo(db).findById("session-1")!.lastActiveAt).toBe(
+ "2026-01-01T00:00:00.000Z",
+ );
} finally {
db.close();
}
});
});
+
+describe("SessionsRepo last_active_at writes", () => {
+ let db: DatabaseSync;
+ let repo: SessionsRepo;
+ const base = {
+ projectId: "p1",
+ agentId: "a1",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/w",
+ approvalMode: "allow-all" as const,
+ title: null,
+ createdAt: "2026-05-01T00:00:00.000Z",
+ };
+
+ beforeEach(() => {
+ db = openDatabase(":memory:");
+ repo = new SessionsRepo(db);
+ });
+ afterEach(() => {
+ db.close();
+ });
+
+ it("both insert paths store a non-NULL cell, defaulting to created_at in SQL", () => {
+ repo.insert({ ...base, sessionId: "s-insert", lastActiveAt: base.createdAt });
+ repo.insertOrIgnore({ ...base, sessionId: "s-ignore", lastActiveAt: base.createdAt });
+ // The column is nullable (ALTER TABLE cannot add a DEFAULT), so the statement's own
+ // COALESCE is the guarantee — a caller reaching the repo without the field (JS, or a
+ // row shape built before it existed) must still leave a usable cell behind. Asserted
+ // on the raw cells: every mapped read coalesces, so a NULL would look identical there.
+ repo.insert({ ...base, sessionId: "s-missing" } as SessionRow);
+ repo.insertOrIgnore({ ...base, sessionId: "s-missing-ignore" } as SessionRow);
+ for (const id of ["s-insert", "s-ignore", "s-missing", "s-missing-ignore"]) {
+ expect(rawLastActive(db, id)).toBe(base.createdAt);
+ }
+ // An explicit value is stored as given, not overwritten by the default.
+ repo.insert({ ...base, sessionId: "s-explicit", lastActiveAt: "2026-06-01T00:00:00.000Z" });
+ expect(rawLastActive(db, "s-explicit")).toBe("2026-06-01T00:00:00.000Z");
+ });
+
+ it("markDriven and touchLastActive only ever move the stamp forward", () => {
+ repo.insert({ ...base, sessionId: "s1", lastActiveAt: base.createdAt });
+ repo.markDriven("s1", "2026-05-02T00:00:00.000Z");
+ expect(repo.findById("s1")!.lastActiveAt).toBe("2026-05-02T00:00:00.000Z");
+ expect(repo.findById("s1")!.hasTrace).toBe(true); // markDriven folds in the has_trace flip
+ repo.touchLastActive("s1", "2026-05-03T00:00:00.000Z");
+ expect(repo.findById("s1")!.lastActiveAt).toBe("2026-05-03T00:00:00.000Z");
+ // A backwards clock (NTP step, resume from suspend) must not regress the row.
+ repo.touchLastActive("s1", "2026-05-01T12:00:00.000Z");
+ repo.markDriven("s1", "2026-04-01T00:00:00.000Z");
+ expect(repo.findById("s1")!.lastActiveAt).toBe("2026-05-03T00:00:00.000Z");
+ });
+
+ it("writes for one Session leave every other row alone", () => {
+ repo.insert({ ...base, sessionId: "s1", lastActiveAt: base.createdAt });
+ repo.insert({ ...base, sessionId: "s2", lastActiveAt: base.createdAt });
+ repo.markDriven("s1", "2026-05-09T00:00:00.000Z");
+ repo.touchLastActive("s1", "2026-05-10T00:00:00.000Z");
+ expect(repo.findById("s2")!.lastActiveAt).toBe(base.createdAt);
+ expect(repo.findById("s2")!.hasTrace).toBe(false);
+ });
+});
diff --git a/packages/server/test/followup.test.ts b/packages/server/test/followup.test.ts
index 1ba062ce..c2b23078 100644
--- a/packages/server/test/followup.test.ts
+++ b/packages/server/test/followup.test.ts
@@ -57,6 +57,7 @@ describe("follow-up queue route", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
runs = [];
diff --git a/packages/server/test/goals.test.ts b/packages/server/test/goals.test.ts
index 9416ff1e..b9bd535c 100644
--- a/packages/server/test/goals.test.ts
+++ b/packages/server/test/goals.test.ts
@@ -36,6 +36,7 @@ const ROW: SessionRow = {
approvalMode: "allow-all",
title: null,
createdAt: "2026-07-06T00:00:00.000Z",
+ lastActiveAt: "2026-07-06T00:00:00.000Z",
};
function usage(total: number): TokenCounts {
diff --git a/packages/server/test/messages-live.test.ts b/packages/server/test/messages-live.test.ts
index e11c509f..d2e82497 100644
--- a/packages/server/test/messages-live.test.ts
+++ b/packages/server/test/messages-live.test.ts
@@ -82,6 +82,7 @@ describe("messages live tail", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
});
diff --git a/packages/server/test/messages-pending-input.test.ts b/packages/server/test/messages-pending-input.test.ts
index ef8b2ff1..8ffbbf75 100644
--- a/packages/server/test/messages-pending-input.test.ts
+++ b/packages/server/test/messages-pending-input.test.ts
@@ -77,6 +77,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
const bootstrapGate = new Promise<void>((resolve) => {
@@ -165,6 +166,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
// First run: connect aborted before any request (the core cancels the bootstrap and
diff --git a/packages/server/test/models.test.ts b/packages/server/test/models.test.ts
index 2e278e71..3eaf0495 100644
--- a/packages/server/test/models.test.ts
+++ b/packages/server/test/models.test.ts
@@ -619,6 +619,7 @@ describe("models update reaches loaded sessions (invalidation + live unlock)", (
approvalMode: "allow-all",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
});
};
diff --git a/packages/server/test/retry-now.test.ts b/packages/server/test/retry-now.test.ts
index 646afad2..26b713ee 100644
--- a/packages/server/test/retry-now.test.ts
+++ b/packages/server/test/retry-now.test.ts
@@ -62,6 +62,7 @@ describe("retry-now route", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
skips = [];
diff --git a/packages/server/test/scheduler.test.ts b/packages/server/test/scheduler.test.ts
index 9d4e68e4..66ee0e57 100644
--- a/packages/server/test/scheduler.test.ts
+++ b/packages/server/test/scheduler.test.ts
@@ -124,6 +124,7 @@ describe("scheduler", () => {
approvalMode: "allow-all",
title: null,
createdAt: new Date(nowMs).toISOString(),
+ lastActiveAt: new Date(nowMs).toISOString(),
});
}
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index 04725a12..c3fe8bfe 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -103,6 +103,47 @@ describe("session-index", () => {
expect(list.sessions.map((s) => s.sessionId)).toContain(session.sessionId);
});
+ it("SessionInfo carries lastActiveAt (ISO, = createdAt at creation) through create, list, and single GET", async () => {
+ await configureModels();
+ const res = await api.post(base(), {});
+ expect(res.status).toBe(201);
+ const { session } = (await res.json()) as SessionCreateResponse;
+ expect(session.lastActiveAt).toBe(session.createdAt);
+ expect(session.lastActiveAt).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/);
+
+ const list = (await (await api.get(base())).json()) as SessionsResponse;
+ const listed = list.sessions.find((s) => s.sessionId === session.sessionId);
+ expect(listed?.lastActiveAt).toBe(session.createdAt);
+
+ const got = (await (
+ await api.get(`/api/sessions/${session.sessionId}`)
+ ).json()) as SessionResponse;
+ expect(got.session.lastActiveAt).toBe(session.createdAt);
+
+ // The real creation path must leave a stored cell, not just a value the read layer
+ // computes: every mapped read coalesces to created_at, so a row written NULL would
+ // answer all three assertions above identically.
+ const stored = t.deps.db
+ .prepare("SELECT last_active_at AS v FROM sessions WHERE session_id = ?")
+ .get(session.sessionId) as { v: unknown } | undefined;
+ expect(stored?.v).toBe(session.createdAt);
+ });
+
+ it("PATCH answers with the row as it stands after the write, not the pre-PATCH snapshot", async () => {
+ await configureModels();
+ const { session } = (await (await api.post(base(), {})).json()) as SessionCreateResponse;
+ // Stand in for a run that advanced the stamp while the PATCH was in flight: the route
+ // reads its row before awaiting, so without a re-read the response would carry — and
+ // the web store would adopt — a value older than what is on disk.
+ const advanced = "2027-01-01T00:00:00.000Z";
+ t.deps.sessionsRepo.touchLastActive(session.sessionId, advanced);
+ const patched = (await (
+ await api.patch(`/api/sessions/${session.sessionId}`, { title: "renamed" })
+ ).json()) as SessionResponse;
+ expect(patched.session.title).toBe("renamed");
+ expect(patched.session.lastActiveAt).toBe(advanced);
+ });
+
it("schedule-created Session: source derives from session_meta (registry), never from the DB row; user sessions carry none", async () => {
await configureModels();
// The scheduler goes through SessionService.createSession directly (no HTTP route exposes source).
@@ -141,6 +182,7 @@ describe("session-index", () => {
approvalMode: "allow-all",
title: null,
createdAt: "2026-07-02T09:00:00.000Z",
+ lastActiveAt: "2026-07-02T09:00:00.000Z",
});
const meta: SessionMetaPayload = {
session_id: sid,
@@ -210,6 +252,7 @@ describe("session-index", () => {
approvalMode: "allow-all" as const,
title: null,
createdAt: `2026-07-0${n}T08:00:00.000Z`,
+ lastActiveAt: `2026-07-0${n}T08:00:00.000Z`,
});
for (const n of [1, 2, 3]) t.deps.sessionsRepo.insert(mk(n));
@@ -268,6 +311,7 @@ describe("session-index", () => {
approvalMode: "allow-all",
title: null,
createdAt: "2026-07-02T09:30:00.000Z",
+ lastActiveAt: "2026-07-02T09:30:00.000Z",
});
await writeTraceFile(t.root, projectId, "default_agent", "2026-07-02", subagentE, 1, [
sessionMeta({
@@ -428,6 +472,7 @@ describe("session-index", () => {
approvalMode: "allow-all",
title: null,
createdAt: "2026-07-02T09:00:00.000Z",
+ lastActiveAt: "2026-07-02T09:00:00.000Z",
});
const list = (await (await api.get(base())).json()) as SessionsResponse;
expect(list.sessions.find((s) => s.sessionId === legacy)).toBeDefined();
@@ -530,6 +575,7 @@ describe("session-index", () => {
});
it("insertOrIgnore is idempotent: concurrent first discovery of one Session doesn't throw on the UNIQUE constraint", async () => {
+ const createdAt = new Date().toISOString();
const row = {
sessionId: "session-2026-07-02-00-00-00-11223344",
projectId,
@@ -539,7 +585,8 @@ describe("session-index", () => {
workspace: "/tmp/w",
approvalMode: "always-ask" as const,
title: null,
- createdAt: new Date().toISOString(),
+ createdAt,
+ lastActiveAt: createdAt,
};
t.deps.sessionsRepo.insertOrIgnore(row);
// A second insert with different fields for the same id: silently ignored, no throw, first-inserted value is kept.
diff --git a/packages/server/test/session-loader.test.ts b/packages/server/test/session-loader.test.ts
index 8626232e..d44b0abd 100644
--- a/packages/server/test/session-loader.test.ts
+++ b/packages/server/test/session-loader.test.ts
@@ -43,6 +43,7 @@ function row(workspace: string): SessionRow {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
}
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index 7a2766bf..31b2ec0a 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -49,6 +49,7 @@ const ROW: SessionRow = {
approvalMode: "always-ask",
title: null,
createdAt: "2026-07-06T00:00:00.000Z",
+ lastActiveAt: "2026-07-06T00:00:00.000Z",
};
/** A simple, scriptable fake Session: run yields one tool_call and requests approval for it. */
@@ -78,6 +79,24 @@ function approvalFakeSession(sessionId: string, toolName = "write_file"): Runtim
};
}
+/**
+ * A repo whose last-active writes always throw — the realistic failure being a
+ * DatabaseSync handle closed by shutdown while a run outlived its drain window. Everything
+ * else behaves normally, so a test can assert that the run's wrap-up survives it.
+ */
+function brokenTouchRepo(repo: SessionsRepo): SessionsRepo {
+ return new Proxy(repo, {
+ get(target, prop, receiver): unknown {
+ if (prop === "markDriven" || prop === "touchLastActive") {
+ return () => {
+ throw new Error("database is not open");
+ };
+ }
+ return Reflect.get(target, prop, receiver) as unknown;
+ },
+ });
+}
+
describe("session-manager", () => {
let db: DatabaseSync;
let sessions: SessionsRepo;
@@ -86,7 +105,12 @@ describe("session-manager", () => {
let recorded: OmniMessage[];
let recordedCtx: UsageContext[];
- const makeManager = (loader: SessionLoader, errors?: ErrorSink): SessionManager =>
+ const makeManager = (
+ loader: SessionLoader,
+ errors?: ErrorSink,
+ /** Stubbed clock for persisted timestamps (see the last_active_at test). */
+ now?: () => Date,
+ ): SessionManager =>
new SessionManager({
sessions,
channels,
@@ -99,6 +123,7 @@ describe("session-manager", () => {
},
},
...(errors ? { errors } : {}),
+ ...(now ? { now } : {}),
log: () => {},
});
@@ -160,6 +185,82 @@ describe("session-manager", () => {
});
});
+ it("drive stamps last_active_at twice per run — once at the start, once at the end — and leaves other rows alone", async () => {
+ sessions.insert({
+ ...ROW,
+ sessionId: "session-other",
+ createdAt: "2026-07-07T00:00:00.000Z",
+ lastActiveAt: "2026-07-07T00:00:00.000Z",
+ });
+ // A stubbed clock, one second per read, so each stamp has an exact expected value:
+ // sampling only after the run (when both stamps have landed) cannot tell the two
+ // apart, and a run-end stamp that stops happening would still look "advanced".
+ let tick = 0;
+ const at = (n: number): string => `2026-07-10T00:00:0${n}.000Z`;
+ const manager = makeManager(loaderOf(approvalFakeSession("session-1")), undefined, () => {
+ const d = new Date(at(tick));
+ tick += 1;
+ return d;
+ });
+ const lastActive = (id: string): string => sessions.findById(id)!.lastActiveAt;
+ // Insert default: last_active_at = created_at until the first driven run.
+ expect(lastActive("session-1")).toBe(ROW.createdAt);
+
+ // The session pauses mid-run on the always-ask approval — the one moment where the
+ // run-start stamp is observable on its own.
+ await manager.startTask("session-1", [userText("hello")]);
+ await waitFor(() => manager.pendingApprovalCount("session-1") === 1);
+ const midRun = lastActive("session-1");
+ expect(midRun).toBe(at(0));
+ expect(midRun > ROW.createdAt).toBe(true);
+
+ manager.decideApproval("session-1", "tc-1", "allow");
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ // Strictly greater: the run END must have its own stamp, or a long Task would report
+ // the moment it began as its last activity for as long as it runs.
+ expect(lastActive("session-1")).toBe(at(1));
+ expect(lastActive("session-1") > midRun).toBe(true);
+
+ // A compaction is a driven run too, and stamps its own pair.
+ await manager.startCompact("session-1");
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ expect(lastActive("session-1")).toBe(at(3));
+ // A session with no activity keeps its creation stamp.
+ expect(lastActive("session-other")).toBe("2026-07-07T00:00:00.000Z");
+ });
+
+ it("a failing last-active write cannot strand a run: idle is still published and queued follow-ups still start", async () => {
+ sessions.updateApprovalMode("session-1", "allow-all");
+ const logs: string[] = [];
+ const recordedErrors: ErrorRecordArgs[] = [];
+ const manager = new SessionManager({
+ sessions: brokenTouchRepo(sessions),
+ channels,
+ sources,
+ loader: loaderOf(approvalFakeSession("session-1")),
+ recorder: { record: async () => {} },
+ errors: { record: (args) => recordedErrors.push(args) },
+ log: (line) => logs.push(line),
+ });
+ const events = capture("session-1");
+ await manager.startTask("session-1", [userText("hello")]);
+ // Queue a follow-up while the first run is in flight: its auto-start lives in the same
+ // finally, AFTER the stamp — a throw there would stall it forever.
+ await manager.startTask("session-1", [userText("second")], { queueIfBusy: true });
+ await waitFor(() => manager.statusOf("session-1") === "idle" && logs.length >= 4);
+ const states = serverEvents(events)
+ .filter((e) => e.type === "task_state")
+ .map((s) => s.state);
+ // Two runs reached their wrap-up — the queued one only ever starts from inside the
+ // finally, after the failing write — and the session ends up idle, not stuck running.
+ expect(states.filter((s) => s === "idle")).toHaveLength(2);
+ expect(states.at(-1)).toBe("idle");
+ expect(manager.pendingFollowUpCount("session-1")).toBe(0);
+ // The failure is reported, not silent.
+ expect(logs.some((l) => l.includes("last-active bookkeeping failed"))).toBe(true);
+ expect(recordedErrors.map((e) => e.code)).toContain("session_touch_failed");
+ });
+
it("startTask forwards thinkingLevel into session.run options (per-turn, this Task only)", async () => {
sessions.updateApprovalMode("session-1", "allow-all");
const seen: (string | undefined)[] = [];
diff --git a/packages/server/test/sse-stream.test.ts b/packages/server/test/sse-stream.test.ts
index 30d48d9d..82a41dac 100644
--- a/packages/server/test/sse-stream.test.ts
+++ b/packages/server/test/sse-stream.test.ts
@@ -96,6 +96,7 @@ describe("sse-stream", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
});
diff --git a/packages/server/test/steer.test.ts b/packages/server/test/steer.test.ts
index 9755bea3..fa0cb2e5 100644
--- a/packages/server/test/steer.test.ts
+++ b/packages/server/test/steer.test.ts
@@ -79,6 +79,7 @@ describe("steer route", () => {
approvalMode: "always-ask",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
steered = [];
diff --git a/packages/server/test/task-attachments.test.ts b/packages/server/test/task-attachments.test.ts
index 2a93d350..789b0fc6 100644
--- a/packages/server/test/task-attachments.test.ts
+++ b/packages/server/test/task-attachments.test.ts
@@ -98,6 +98,7 @@ describe("task input file attachments", () => {
approvalMode: "allow-all",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
};
t.deps.sessionsRepo.insert(row);
runs = [];
@@ -384,6 +385,7 @@ describe("task attachments are removed when the Task never starts", () => {
approvalMode: "allow-all",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
});
dir = path.join(scratchpadDir(t.root, PID, "default_agent"), FAIL_SID);
});
@@ -426,6 +428,7 @@ describe("scratchpad directory containment", () => {
approvalMode: "allow-all",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
});
t.deps.manager.adopt(
t.deps.sessionsRepo.findById(LINK_SID)!,
diff --git a/packages/server/test/title-generator.test.ts b/packages/server/test/title-generator.test.ts
index fb39a548..b99d2678 100644
--- a/packages/server/test/title-generator.test.ts
+++ b/packages/server/test/title-generator.test.ts
@@ -30,6 +30,7 @@ const ROW: SessionRow = {
approvalMode: "always-ask",
title: null,
createdAt: "2026-07-07T00:00:00.000Z",
+ lastActiveAt: "2026-07-07T00:00:00.000Z",
};
const CTX: UsageContext = {
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index 9cc50f0f..830a9912 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -76,6 +76,7 @@ function dbRow(over: Partial<SessionRow> & { sessionId: string }): SessionRow {
approvalMode: "allow-all",
title: null,
createdAt: "2026-07-05T10:00:00.000Z",
+ lastActiveAt: "2026-07-05T10:00:00.000Z",
...over,
};
}
diff --git a/packages/server/test/vault.test.ts b/packages/server/test/vault.test.ts
index 7a2c0f96..7e83130e 100644
--- a/packages/server/test/vault.test.ts
+++ b/packages/server/test/vault.test.ts
@@ -150,6 +150,7 @@ describe("vault api", () => {
approvalMode: "allow-all",
title: null,
createdAt: new Date().toISOString(),
+ lastActiveAt: new Date().toISOString(),
});
const idle = () => t.deps.manager.statusOf("vault-sess-1") === "idle";
diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.ts
index bedfb9ac..96e619a5 100644
--- a/packages/web/test/session-grouping.test.ts
+++ b/packages/web/test/session-grouping.test.ts
@@ -46,6 +46,7 @@ function session(
workspace,
approvalMode: "allow-all",
createdAt,
+ lastActiveAt: createdAt,
status: "idle",
pendingApprovalCount: 0,
pendingFollowUpCount: 0,