Files
OmniRoute/src/lib/db/agenticConversations.ts
Markus Hartung beb6ec857b feat(dashboard): agentic conversation tracking — v4, decoupled + storage-architecture concern resolved (#10263)
* feat(responses): virtualize previous_response_id continuation regardless of upstream support

OmniRoute now exposes OpenAI-compatible previous_response_id/store
continuation to clients unconditionally, even when the selected upstream
provider has no native Responses-API state support. Reconstruction happens
server-side in handleChatImplementation, before any downstream validation
or provider translation: OmniRoute resolves the response id back to the
full input/output it previously produced, prepends it to the client's
delta, and forwards the full reconstructed history upstream exactly as it
does today. Client<->OmniRoute traffic shrinks to the new delta only;
OmniRoute<->provider traffic is unchanged.

Storage reuses the existing call-log pipeline artifact (already gated by
call_log_pipeline_enabled, already retained/cleaned up by the existing
call-log lifecycle) instead of duplicating conversation content into a
second store -- only a lightweight call_logs.response_id index is new.
Every lookup is scoped by api_key_id so one client can never resolve
another client's stored conversation, and any unresolvable/missing/
size-limit-omitted state fails closed with OpenAI's own
previous_response_not_found contract.

Stacked on feat/openai-responses-store-toggle (#10121).

* feat(dashboard): agentic conversation tracking with live transcript view

Every agentic chat request now gets a conversation id (X-ConversationId
response header). OmniRoute detects when a follow-up request continues the
same conversation via fingerprint + bounded prefix-hash matching, with a
strict-growth invariant to prevent false merges between independent
single-shot requests that happen to share identical opening content.
Continuation detection excludes the system message from the identity
anchor, since real coding-agent CLIs commonly regenerate it every request
with live context (timestamp, cwd, git status) — without this, that
volatility alone broke every continuation check against real traffic.

- `/dashboard/logs`: new toggleable Conversation column.
- `/dashboard/logs/timeline`: requests sharing a conversation id share a
  timeline lane, connected by an arrow, with a configurable lane-reuse
  window.
- Request detail panel: new Full Conversation transcript above the raw SSE
  event stream — Markdown rendering, per-turn timestamps, turn-relative
  view, click-any-turn navigation, live auto-refresh building the
  transcript in real time from the in-flight SSE chunk buffer while a
  request is still streaming, auto-scroll-to-bottom as the live turn grows.
- New `/dashboard/conversations` page listing conversations with 2+ turns,
  no-forking model (an edited/duplicated mid-history turn mints its own
  independent conversation instead of merging), pagination, duplicate-
  anchor fix.
- Configurable auto-refresh intervals on both the timeline and
  conversations list pages.
- Responses API tool-call gap fix: turnsFromOpenAiMessages only handled
  role-based Chat Completions messages, so bare {type:"function_call"} /
  {type:"function_call_output"} / {type:"reasoning"} items (real Responses
  API traffic) silently vanished from the Conversation Context panel.
- truncateForLog now counts input[] (Responses API), not just messages[]
  (Chat Completions), so a truncated /v1/responses request still shows a
  placeholder instead of nothing.
- RequestTimeline.tsx now reads the same debugEnabled/emailsVisible
  settings RequestLoggerV2.tsx already used, instead of hardcoding both
  false — the timeline view never showed SSE/stream-chunk events or
  respected email-masking, regardless of the actual setting.

Migrations 147/148 (agentic_conversations, conversation_turn_nodes) — 135
and 136 are now taken upstream; 143-145 are documented KNOWN_GAPS, so this
uses the next free slot past upstream's current highest.

Test plan:
- npm run typecheck:core — clean
- npm run lint — clean
- node --import tsx/esm scripts/check/check-migration-numbering.mjs — OK, 0 collisions
- 109 unit tests across the conversation-tracking, migration-renumber, and
  dashboard-wiring surface — 0 failures

* refactor(dashboard): reuse call-log artifacts for conversation transcript content

conversation_turn_nodes no longer stores turn text/tool-call content
(text_preview/block_kind/tool_name) -- it's identity-only now (id/parent/
content_hash), matching agentic_conversations' existing lightweight-index
shape. Every node's originating request is already fully captured by the
call-log pipeline artifact its last_correlation_id points at, so the
/dashboard/conversations tree view resolves each node's actual display
content on demand from there (open-sse/services/conversationTurnContent.ts),
re-running the same extractCanonicalTurns/hashTurnContent the write path
used and matching by content_hash, instead of duplicating conversation
content into a second store under a separate retention/gating policy. This
also drops the old 8000-char text_preview truncation entirely -- resolved
content is always full and untruncated.

The frontend contract is unchanged (tree API still returns
{textPreview, blockKind, toolName} per node), so the dashboard UI itself
(page.tsx, RequestLoggerDetail/RequestTimeline, sidebar, i18n) needed no
changes.

Renumbered the cherry-picked 147/148 migrations to 153/154 -- 147 now
collides with 147_api_keys_model_access_mode.sql, which landed on
release/v3.8.50 after this work was originally built.

Also includes a standalone, unrelated fix carried along from this rebase:
close isProviderModelHidden's missing function-body brace in
modelSelectModalHelpers.ts (separately landed as #10206).

Stacked on feat/responses-previous-response-id-virtualization (#3), which
is itself stacked on feat/openai-responses-store-toggle (#10121).

* fix(dashboard): resync conversation list on open so the live-text poll starts immediately

openConversation() seeded activeConversation (and therefore activeCallLogId,
which gates the live-partial-text poll effect) from whatever row snapshot the
list's own fixed-interval poll last produced. A conversation opened right
after a reply started streaming -- after that tick, before the next -- had
activeCallLogId still null, so the live-text poll never started; only a
subsequent background list-poll resync (already existed) picked it up,
which is why closing and reopening the same conversation "just worked".

loadConversations() is now a shared callback so openConversation can force
one immediately on open instead of waiting on pollSeconds.

Live-verified against omniroute-dev: opening a conversation mid-stream now
shows live reasoning on the first open.

* style: prettier formatting for conversationTurnContent.test.ts

* fix(db): close migration numbering gap left by decoupling from #3/#10262

153/154 (originally 154/155) were chosen back when this branch stacked on
top of the previous_response_id migration (153_call_logs_response_id.sql).
Decoupling removed that migration from this branch's history, leaving an
unused 153 slot that check-migration-numbering.test.ts correctly flags as
a gap.

* refactor(dashboard): split RequestTimeline/RequestLoggerDetail under the 1000-line file-size cap

Both files exceeded check-file-size's new-file cap after this PR's own
additions (RequestTimeline 1048, RequestLoggerDetail 1163). Extracted pure
non-component logic (types, constants, allocateLanes and its helpers) out
of RequestTimeline.tsx into RequestTimeline.utils.ts, and the two
self-contained presentational sub-components (PayloadSection,
ConversationContextSection + its private helper) out of
RequestLoggerDetail.tsx into RequestLoggerDetail.sections.tsx. No behavior
change; existing external imports (default exports, allocateLanes,
TimelineLog, CONVERSATION_LANE_REUSE_STORAGE_KEY) still resolve from the
original file paths.

* fix(db): renumber agentic-conversation migrations to clear 153 collision + sync migration-count docs

The refresh-merge of release/v3.8.50 exposed that the feature's three
migrations collided at slot 153 with the base's radar_local_model_state
(153) and its own call_logs_response_id. Migration runner enforces unique
numeric prefixes -> every DB init threw, red-ing Vitest, all Unit shards and
the DB-backed quality gates. Renumber the feature's pair to
155_agentic_conversations / 156_conversation_turn_nodes and move
call_logs_response_id to 154 (keeps 153_radar base-owned, preserves
agentic-before-turn_nodes ordering). Update SQL headers and the
154/156 references in feature code + tests.

Migration count is now 151 (was 148 stale in README/AGENTS/llm.txt) — sync
the doc counts to clear the docs-accuracy gate.

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* fix(ui): drop unused CONVERSATION_LANE_REUSE_STORAGE_KEY re-export from RequestTimeline

Knip 6.32 (baseline 415) flags the public re-export of
CONVERSATION_LANE_REUSE_STORAGE_KEY from RequestTimeline.tsx as dead: no
external consumer imports it through that re-export (it is imported and
used directly from RequestTimeline.utils.ts inside the component). Removed
the unused re-export; the internal import stays. DEAD_TOTAL 416 -> 415,
back to the frozen baseline.

Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>

* fix(agentic-conversations): guard resolveConversationId, drop dead whole-chain export

- Wrap resolveConversationId() in try/catch in chat.ts, matching the
  defensive pattern used by every other best-effort side call nearby, so a
  DB hiccup in conversation tracking can't turn a working chat request into
  a hard failure.
- Remove getConversationTurnTree: knip's project scope excludes tests/**,
  so an export used only by tests can never register as used there. Swap
  its 8 test call sites to the paginated getConversationTurnPage (already
  the dashboard's canonical query) with a generous limit, collapsing to one
  query path instead of keeping a second whole-chain export alive solely
  for test convenience.
- Regenerate i18n llm.txt mirrors from root (pre-existing drift on this
  branch, unrelated to the above, caught by the docs-sync pre-commit gate).

Addresses PR review feedback.

* fix(i18n): close requestLogger conversation-column gap, fix domain-modules count drift

- fr.json, vi.json were missing requestLogger.columns.conversation (added
  in the conversation-tracking feature), failing i18n-vi-completeness.test.ts.
- docs/i18n/*/llm.txt mirrors still said 117 domain-specific files after an
  earlier rebase fixed the migration count but missed this companion number,
  failing check-docs-sync.mjs across all 42 locales.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

* fix(docs): restore PROXY_LOG_INCLUDE_IPS env/doc entries (env-doc-sync red)

.env.example and docs/reference/ENVIRONMENT.md were both missing the
PROXY_LOG_INCLUDE_IPS entry that src/lib/proxyLogger.ts already reads
(confirmed present at this branch's merge-base too, so this predates
the conversation-tracking work and is unrelated to it) -- the entry
was added on release/v3.8.50 after this branch's last sync and this
branch never picked it up. That gap red-lines
tests/unit/check-env-doc-sync.test.ts and
tests/unit/issue-7793-env-doc-sync-repro.test.ts (Unit Tests
fast-path 2/4 in CI). Restore both entries verbatim from the current
release/v3.8.50 tip -- no feature-code change.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: hartmark <hartmark@users.noreply.github.com>
Co-authored-by: diegosouzapw <diegosouza.pw@gmail.com>
Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>
2026-08-18 11:32:33 -03:00

433 lines
16 KiB
TypeScript

/**
* db/agenticConversations.ts — CRUD for the agentic conversation-tracking
* tables: `agentic_conversations` (one row per conversation tree root) and
* `conversation_turn_nodes` (one row per distinct turn instance, chained to
* its predecessor — see open-sse/services/conversationTracker.ts for how the
* chain hash is computed and walked to detect continuations/forks).
*
* `conversation_turn_nodes` is identity-only (id/parent/content_hash) — no
* turn text/tool-call content lives on these rows. Display content is
* resolved on demand from the call-log pipeline artifact each node's
* `last_correlation_id` points at (see
* open-sse/services/conversationTurnContent.ts), reusing the same full,
* untruncated payloads call_logs already persists instead of storing a
* second, truncated copy of conversation content here.
*
* `last_message_count`/`last_messages_hash` on `agentic_conversations` are
* dead columns kept only for backward on-disk compatibility (superseded by
* `conversation_turn_nodes`, migration 156) — never read, written as
* placeholders.
*/
import { v4 as uuidv4 } from "uuid";
import { getDbInstance } from "./core";
export interface AgenticConversationRow {
id: string;
apiKeyId: string | null;
fingerprintHash: string;
turnCount: number;
firstSeenAt: string;
lastSeenAt: string;
}
type JsonRecord = Record<string, unknown>;
function asRecord(value: unknown): JsonRecord {
return value && typeof value === "object" ? (value as JsonRecord) : {};
}
function toRow(value: unknown): AgenticConversationRow {
const r = asRecord(value);
return {
id: String(r.id ?? ""),
apiKeyId: typeof r.api_key_id === "string" ? r.api_key_id : null,
fingerprintHash: String(r.fingerprint_hash ?? ""),
turnCount: Number(r.turn_count ?? 1),
firstSeenAt: String(r.first_seen_at ?? ""),
lastSeenAt: String(r.last_seen_at ?? ""),
};
}
export function createAgenticConversation(input: {
id?: string;
apiKeyId: string | null;
fingerprintHash: string;
}): AgenticConversationRow {
const db = getDbInstance();
const now = new Date().toISOString();
const id = input.id || `conv_${uuidv4()}`;
// last_message_count/last_messages_hash are dead columns (superseded by
// conversation_turn_nodes, migration 156) — 0/'' placeholders only.
db.prepare(
`INSERT INTO agentic_conversations
(id, api_key_id, fingerprint_hash, last_message_count, last_messages_hash, turn_count, first_seen_at, last_seen_at)
VALUES (?, ?, ?, 0, '', 1, ?, ?)`
).run(id, input.apiKeyId, input.fingerprintHash, now, now);
return {
id,
apiKeyId: input.apiKeyId,
fingerprintHash: input.fingerprintHash,
turnCount: 1,
firstSeenAt: now,
lastSeenAt: now,
};
}
export function findAgenticConversationsByFingerprint(
fingerprintHash: string
): AgenticConversationRow[] {
const db = getDbInstance();
const rows = db
.prepare(
`SELECT * FROM agentic_conversations WHERE fingerprint_hash = ? ORDER BY last_seen_at DESC LIMIT 20`
)
.all(fingerprintHash);
return rows.map(toRow);
}
export function updateAgenticConversation(id: string, patch: { turnCount: number }): void {
const db = getDbInstance();
db.prepare(`UPDATE agentic_conversations SET turn_count = ?, last_seen_at = ? WHERE id = ?`).run(
patch.turnCount,
new Date().toISOString(),
id
);
}
// ── Turn-node tree (migration 156) ───────────────────────────────────────
export interface ConversationTurnNode {
id: string;
conversationId: string;
parentId: string | null;
role: string;
/** sha256(role+text) — reconnect-anchor lookup key, and the key
* conversationTurnContent.ts resolves this node's actual display text/
* tool-call shape by, from the call-log artifact its lastCorrelationId
* points at (no display content is stored on this row itself). */
contentHash: string;
lastCorrelationId: string | null;
firstSeenAt: string;
lastSeenAt: string;
}
function toTurnNode(value: unknown): ConversationTurnNode {
const r = asRecord(value);
return {
id: String(r.id ?? ""),
conversationId: String(r.conversation_id ?? ""),
parentId: typeof r.parent_id === "string" ? r.parent_id : null,
role: String(r.role ?? ""),
contentHash: String(r.content_hash ?? ""),
lastCorrelationId: typeof r.last_correlation_id === "string" ? r.last_correlation_id : null,
firstSeenAt: String(r.first_seen_at ?? ""),
lastSeenAt: String(r.last_seen_at ?? ""),
};
}
export interface ConversationTurnIndex {
/** Every existing node id for the chain — O(1) forward-walk membership checks. */
nodeIds: Set<string>;
/**
* contentHash (sha256 of just a turn's own role+text, independent of
* parent) -> node ids sharing that content. Lets resolveConversationId
* find a reconnection point ANYWHERE in the chain, not only at its start —
* real OpenClaw traffic drops/summarizes the earliest turns as a session
* grows, so a new request's turn 0 is often not the chain's own first turn.
*/
byContentHash: Map<string, string[]>;
/**
* Node ids that already have at least one recorded child. Lets
* resolveConversationId distinguish "this turn is genuinely new" (the
* reconnect anchor has no child yet — safe to extend this SAME
* conversation) from "a turn already exists at this position and this
* request's turn differs from it" (an edit — becomes its own independent
* conversation as of the 2026-08-06 redesign; see resolveConversationId's
* doc comment for why conversations no longer fork in place).
*/
parentsWithChildren: Set<string>;
}
/**
* Bulk-load a conversation chain's node ids and content-hash index in one
* query, for the reconnect-anchor search in resolveConversationId
* (conversationTracker.ts). Chains are small in practice (tens to low
* hundreds of turns), so one bulk load per candidate is cheap.
*/
export function getConversationTurnIndex(conversationId: string): ConversationTurnIndex {
const db = getDbInstance();
const rows = db
.prepare(
`SELECT id, parent_id, content_hash FROM conversation_turn_nodes WHERE conversation_id = ?`
)
.all(conversationId);
const nodeIds = new Set<string>();
const byContentHash = new Map<string, string[]>();
const parentsWithChildren = new Set<string>();
for (const r of rows) {
const rec = asRecord(r);
const id = String(rec.id ?? "");
const parentId = typeof rec.parent_id === "string" ? rec.parent_id : null;
const contentHash = String(rec.content_hash ?? "");
nodeIds.add(id);
if (parentId) parentsWithChildren.add(parentId);
if (!contentHash) continue;
const bucket = byContentHash.get(contentHash);
if (bucket) bucket.push(id);
else byContentHash.set(contentHash, [id]);
}
return { nodeIds, byContentHash, parentsWithChildren };
}
/**
* Insert a run of new turn nodes (a fresh branch, or the whole chain for a
* brand-new conversation). Nodes already existing on this chain are never
* re-inserted or touched here — only the newly-diverging tail from the
* fork/reconnect point onward reaches this function (see conversationTracker.ts).
*/
export function insertConversationTurnNodes(
conversationId: string,
correlationId: string | null,
nodes: Array<{
id: string;
parentId: string | null;
role: string;
contentHash: string;
}>
): void {
if (nodes.length === 0) return;
const db = getDbInstance();
const now = new Date().toISOString();
const insert = db.prepare(
`INSERT OR IGNORE INTO conversation_turn_nodes
(id, conversation_id, parent_id, role, content_hash, last_correlation_id, first_seen_at, last_seen_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
);
const insertMany = db.transaction((rows: typeof nodes) => {
for (const node of rows) {
insert.run(
node.id,
conversationId,
node.parentId,
node.role,
node.contentHash,
correlationId,
now,
now
);
}
});
insertMany(nodes);
}
export interface ConversationTurnNodeWithSeq extends ConversationTurnNode {
/** SQLite rowid — a stable, monotonically-increasing insertion-order
* cursor for pagination (first_seen_at can tie within the same request's
* batch insert; rowid never does). */
seq: number;
}
export interface ConversationTurnPage {
/** Ascending order (oldest first) within the page. */
nodes: ConversationTurnNodeWithSeq[];
/** True when older turns exist beyond this page (only meaningful for the
* initial load / beforeSeq cases — always false for afterSeq/poll). */
hasMore: boolean;
}
/**
* Paginated turn fetch for the /dashboard/conversations view: a real
* OpenClaw conversation can run to hundreds of turns, so the page always
* loads the most recent `limit` (default 20) rather than everything.
* - No cursor: initial load — the LAST `limit` turns.
* - `beforeSeq`: "load more" (older) — the `limit` turns immediately before it.
* - `afterSeq`: poll for new turns since the last load — everything newer,
* uncapped (a handful of turns in practice).
* Only one of beforeSeq/afterSeq is meaningful per call; afterSeq wins if
* both are somehow given.
*/
export function getConversationTurnPage(
conversationId: string,
opts: { limit?: number; beforeSeq?: number; afterSeq?: number } = {}
): ConversationTurnPage {
const db = getDbInstance();
const limit = Math.max(1, Math.min(opts.limit ?? 20, 500));
if (opts.afterSeq != null) {
const rows = db
.prepare(
`SELECT rowid as seq, * FROM conversation_turn_nodes
WHERE conversation_id = ? AND rowid > ? ORDER BY rowid ASC`
)
.all(conversationId, opts.afterSeq);
return { nodes: rows.map(toTurnNodeWithSeq), hasMore: false };
}
const rows =
opts.beforeSeq != null
? db
.prepare(
`SELECT rowid as seq, * FROM conversation_turn_nodes
WHERE conversation_id = ? AND rowid < ? ORDER BY rowid DESC LIMIT ?`
)
.all(conversationId, opts.beforeSeq, limit + 1)
: db
.prepare(
`SELECT rowid as seq, * FROM conversation_turn_nodes
WHERE conversation_id = ? ORDER BY rowid DESC LIMIT ?`
)
.all(conversationId, limit + 1);
const hasMore = rows.length > limit;
const page = (hasMore ? rows.slice(0, limit) : rows).reverse();
return { nodes: page.map(toTurnNodeWithSeq), hasMore };
}
function toTurnNodeWithSeq(value: unknown): ConversationTurnNodeWithSeq {
const rec = asRecord(value);
return { ...toTurnNode(value), seq: Number(rec.seq ?? 0) };
}
/**
* Turn nodes are tagged with `last_correlation_id` (see
* conversationTracker.ts's doc comment for why — the request's own
* call_logs.id doesn't exist yet when a node is created), not a call_logs.id
* directly. Resolves the set in one bulk query (not one lookup per node) to
* a `correlation_id -> call_logs.id` map so the tree view can link each node
* to a navigable request.
*/
export function resolveCallLogIdsByCorrelationIds(correlationIds: string[]): Map<string, string> {
const unique = [...new Set(correlationIds.filter(Boolean))];
const result = new Map<string, string>();
if (unique.length === 0) return result;
const db = getDbInstance();
const placeholders = unique.map(() => "?").join(",");
const rows = db
.prepare(`SELECT id, correlation_id FROM call_logs WHERE correlation_id IN (${placeholders})`)
.all(...unique);
for (const r of rows) {
const rec = asRecord(r);
const correlationId = typeof rec.correlation_id === "string" ? rec.correlation_id : null;
const callLogId = typeof rec.id === "string" ? rec.id : null;
// Keep the first match per correlation_id — a retry/combo-fallback can
// theoretically share one correlation_id across a couple of call_logs
// rows; any of them is a valid navigation target.
if (correlationId && callLogId && !result.has(correlationId)) {
result.set(correlationId, callLogId);
}
}
return result;
}
/**
* Upsert for the client-supplied `x-omniroute-session-id` path: the header
* value is used directly as the conversation id, so this only needs to keep
* `turn_count`/`last_seen_at` moving — the fingerprint/prefix-hash fields are
* unused for header-pinned conversations (continuation is guaranteed by the
* client, not detected heuristically).
*/
export function touchOrCreateExternalConversation(
id: string,
ctx: { apiKeyId: string | null }
): void {
const db = getDbInstance();
const now = new Date().toISOString();
const existing = db.prepare(`SELECT id FROM agentic_conversations WHERE id = ?`).get(id);
if (existing) {
db.prepare(
`UPDATE agentic_conversations SET turn_count = turn_count + 1, last_seen_at = ? WHERE id = ?`
).run(now, id);
return;
}
db.prepare(
`INSERT INTO agentic_conversations
(id, api_key_id, fingerprint_hash, last_message_count, last_messages_hash, turn_count, first_seen_at, last_seen_at)
VALUES (?, ?, '', 0, '', 1, ?, ?)`
).run(id, ctx.apiKeyId, now, now);
}
export interface MultiTurnConversationRow extends AgenticConversationRow {
lastCallLogId: string | null;
lastModel: string | null;
lastProvider: string | null;
lastStatus: number | null;
}
/**
* Conversations with >= 2 actual turn nodes — filters out one-shot,
* non-agentic traffic for the /dashboard/conversations list page.
*
* Deliberately filters on conversation_turn_nodes COUNT, not `turn_count`:
* `turn_count` tracks how many separate REQUESTS have touched this
* conversation (see createAgenticConversation/updateAgenticConversation),
* not how many turns it contains. A brand-new conversation minted by
* resolveConversationId's divergence path (see conversationTracker.ts)
* starts at turn_count=1 even though its first insert can carry the
* conversation's entire prior history (hundreds of nodes) — real OpenClaw
* traffic diverges/edits turns often enough that most conversations never
* accumulate a second touching request, so a turn_count-based filter left
* them permanently invisible despite having a rich multi-turn transcript
* (2026-08-06, request 1785975096139-6627d2 / conv_36fff6fa...: turn_count=1,
* 398 real conversation_turn_nodes rows). Joined to each
* conversation's most recent call_logs row (by MAX(timestamp) per
* session_tag) in a single query rather than one lookup per row, since this
* is a list view that can have many conversations.
*/
export function listMultiTurnConversations(
filter: {
limit?: number;
offset?: number;
} = {}
): { rows: MultiTurnConversationRow[]; total: number } {
const db = getDbInstance();
const limit = Math.max(1, Math.min(filter.limit ?? 50, 200));
const offset = Math.max(0, filter.offset ?? 0);
const total = asRecord(
db
.prepare(
`SELECT COUNT(*) as c FROM agentic_conversations ac
WHERE (SELECT COUNT(*) FROM conversation_turn_nodes n WHERE n.conversation_id = ac.id) >= 2`
)
.get()
).c as number;
const rows = db
.prepare(
`SELECT ac.*, latest.id as last_call_log_id, latest.model as last_model,
latest.provider as last_provider, latest.status as last_status
FROM agentic_conversations ac
LEFT JOIN (
SELECT cl1.id, cl1.session_tag, cl1.model, cl1.provider, cl1.status
FROM call_logs cl1
WHERE cl1.timestamp = (
SELECT MAX(cl2.timestamp) FROM call_logs cl2 WHERE cl2.session_tag = cl1.session_tag
)
) latest ON latest.session_tag = ac.id
WHERE (SELECT COUNT(*) FROM conversation_turn_nodes n WHERE n.conversation_id = ac.id) >= 2
ORDER BY ac.last_seen_at DESC
LIMIT ? OFFSET ?`
)
.all(limit, offset);
return {
total: Number(total ?? 0),
rows: rows.map((r) => {
const rec = asRecord(r);
return {
...toRow(rec),
lastCallLogId: typeof rec.last_call_log_id === "string" ? rec.last_call_log_id : null,
lastModel: typeof rec.last_model === "string" ? rec.last_model : null,
lastProvider: typeof rec.last_provider === "string" ? rec.last_provider : null,
lastStatus: typeof rec.last_status === "number" ? rec.last_status : null,
};
}),
};
}