Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(agent-platform): persisted search_text digest for scalable session search (#65764)

Ben Whited3caa86b732c
diff --git a/products/agent_platform/backend/migrations/0012_agentsession_search_text_turn_count.py b/products/agent_platform/backend/migrations/0012_agentsession_search_text_turn_count.py
new file mode 100644
index 000000000000..68a0af5e8905
--- /dev/null
+++ b/products/agent_platform/backend/migrations/0012_agentsession_search_text_turn_count.py
@@ -0,0 +1,20 @@
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("agent_platform", "0011_agentrevision_skill_refs"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="agentsession",
+ name="search_text",
+ field=models.TextField(blank=True, null=True),
+ ),
+ migrations.AddField(
+ model_name="agentsession",
+ name="turn_count",
+ field=models.IntegerField(db_default=0, default=0),
+ ),
+ ]
diff --git a/products/agent_platform/backend/migrations/max_migration.txt b/products/agent_platform/backend/migrations/max_migration.txt
index 16ae82e58b3d..c48d57f0cd82 100644
--- a/products/agent_platform/backend/migrations/max_migration.txt
+++ b/products/agent_platform/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0011_agentrevision_skill_refs
+0012_agentsession_search_text_turn_count
diff --git a/products/agent_platform/backend/models.py b/products/agent_platform/backend/models.py
index a01661c709ca..8b0bec8f6d42 100644
--- a/products/agent_platform/backend/models.py
+++ b/products/agent_platform/backend/models.py
@@ -192,6 +192,11 @@ class AgentSession(ProductTeamModel, UUIDModel):
'{"tokens_in": 0, "tokens_out": 0, "cache_read": 0, "cache_write": 0, "cost_input": 0, "cost_output": 0, "cost_cache_read": 0, "cost_cache_write": 0, "cost_total": 0}'
),
)
+ # Derived on every conversation write by the node SessionQueue so the list
+ # view + search never read the full `conversation` JSONB. search_text is a
+ # truncated user+assistant text digest; turn_count is len(conversation).
+ search_text = models.TextField(null=True, blank=True)
+ turn_count = models.IntegerField(default=0, db_default=0)
created_at = models.DateTimeField(auto_now_add=True, db_default=Now())
updated_at = models.DateTimeField(auto_now=True, db_default=Now())
diff --git a/products/agent_platform/services/agent-janitor/src/server.test.ts b/products/agent_platform/services/agent-janitor/src/server.test.ts
index 32d327969c4f..c91093f76493 100644
--- a/products/agent_platform/services/agent-janitor/src/server.test.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.test.ts
@@ -265,31 +265,47 @@ describe('janitor HTTP', () => {
)
})
- it('GET /sessions?search matches external_key case-insensitively, not the transcript', async () => {
+ it('GET /sessions?search matches transcript text, external_key and id', async () => {
const { queue, app } = mk()
await queue.enqueue({
...session('s-deploy'),
application_id: uuidFor('app-1'),
- external_key: 'slack:CWIDGET',
- conversation: [{ role: 'user', content: 'can you deploy the gadget service?', timestamp: 1 }],
+ external_key: 'slack:C123',
+ conversation: [
+ { role: 'user', content: 'can you deploy the WIDGET service?', timestamp: 1 },
+ {
+ role: 'assistant',
+ content: [{ type: 'text', text: 'Deploying now.' }],
+ api: 'a',
+ provider: 'a',
+ model: 'm',
+ usage: { input: 1, output: 1, cost: { input: 0, output: 0, total: 0 } },
+ timestamp: 2,
+ },
+ ],
})
await queue.enqueue({
...session('s-unrelated'),
application_id: uuidFor('app-1'),
external_key: 'slack:C999',
- conversation: [{ role: 'user', content: 'mentions WIDGET in the transcript only', timestamp: 1 }],
+ conversation: [{ role: 'user', content: 'what is the weather', timestamp: 1 }],
})
- // external_key match, case-insensitive.
- const byKey = await request(app)
+ // Transcript-text match via the persisted search_text digest, case-insensitive.
+ const byText = await request(app)
.get('/sessions')
.query({ application_id: uuidFor('app-1'), search: 'widget' })
- expect((byKey.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-deploy')])
- expect(byKey.body.count).toBe(1)
+ expect((byText.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-deploy')])
+ expect(byText.body.count).toBe(1)
+ // external_key match.
+ const byKey = await request(app)
+ .get('/sessions')
+ .query({ application_id: uuidFor('app-1'), search: 'C999' })
+ expect((byKey.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-unrelated')])
// id match.
const byId = await request(app)
.get('/sessions')
- .query({ application_id: uuidFor('app-1'), search: uuidFor('s-unrelated') })
- expect((byId.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-unrelated')])
+ .query({ application_id: uuidFor('app-1'), search: uuidFor('s-deploy') })
+ expect((byId.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-deploy')])
// No match → empty, not an error.
const none = await request(app)
.get('/sessions')
@@ -308,7 +324,7 @@ describe('janitor HTTP', () => {
expect((res.body.results as Array<{ id: string }>).map((s) => s.id)).toEqual([uuidFor('s-pct')])
})
- it('GET /sessions summaries include preview + usage_total off the persisted column', async () => {
+ it('GET /sessions summaries derive preview from search_text + usage_total off the persisted columns', async () => {
const { queue, app } = mk()
await queue.enqueue({
...session('s-rich'),
@@ -339,7 +355,9 @@ describe('janitor HTTP', () => {
const res = await request(app)
.get('/sessions')
.query({ application_id: uuidFor('app-1') })
- expect(res.body.results[0].preview).toBe('hello back!')
+ // Preview is the conversation digest (user + assistant text), not just
+ // the last assistant line — it comes off the persisted search_text.
+ expect(res.body.results[0].preview).toBe('hi hello back!')
expect(res.body.results[0].usage_total).toMatchObject({
tokens_in: 50,
tokens_out: 10,
diff --git a/products/agent_platform/services/agent-janitor/src/server.ts b/products/agent_platform/services/agent-janitor/src/server.ts
index 592552739497..948ba6952133 100644
--- a/products/agent_platform/services/agent-janitor/src/server.ts
+++ b/products/agent_platform/services/agent-janitor/src/server.ts
@@ -73,6 +73,7 @@ import {
MemoryStore,
MODEL_POLICY_LEVELS,
PgIdentityAdminStore,
+ previewText,
readTypedBundle,
RevisionStore,
SessionQueue,
@@ -472,12 +473,15 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
search: q.search,
}
const [sessions, count] = await Promise.all([
- opts.queue.listByApplication(q.application_id, { ...filter, limit: q.limit, offset: q.offset }),
+ opts.queue.listSummariesByApplication(q.application_id, {
+ ...filter,
+ limit: q.limit,
+ offset: q.offset,
+ }),
opts.queue.countByApplication(q.application_id, filter),
])
- // Conversation can be large; strip it from the list view but derive a
- // preview so a single tool call still tells you what the agent said.
- // usage_total reads off the persisted column — no JSONB walk.
+ // `turns` + `preview` come off the persisted `turn_count` /
+ // `search_text` columns, so listing never detoasts a transcript.
const summaries = sessions.map((s) => ({
id: s.id,
application_id: s.application_id,
@@ -487,8 +491,8 @@ export function buildJanitorApp(opts: JanitorServerOpts): Express {
idempotency_key: s.idempotency_key,
trigger_metadata: s.trigger_metadata,
principal: s.principal,
- turns: s.conversation.length,
- preview: lastAssistantTextPreview(s.conversation),
+ turns: s.turns,
+ preview: previewText(s.search_text),
usage_total: s.usage_total,
retry_count: s.retry_count,
created_at: s.created_at,
diff --git a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
index 825befccfa4b..1ef50c4d6f7c 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/pg-queue.ts
@@ -20,6 +20,7 @@ import {
SessionAclEntry,
SessionUsageTotal,
} from '../spec/spec'
+import { buildSearchText, SEARCH_TEXT_MAX } from '../spec/summarize-conversation'
import {
AggregateStats,
DecideElevationInput,
@@ -27,6 +28,7 @@ import {
LIVE_SESSION_STATES,
ListSessionsOpts,
SessionQueue,
+ SessionSummary,
} from './queue'
const SELECT_COLS = `id, application_id, revision_id, team_id, external_key,
@@ -35,6 +37,14 @@ const SELECT_COLS = `id, application_id, revision_id, team_id, external_key,
usage_total, acl, pending_elevation_requests,
created_at, updated_at`
+// List view: every summary column except the heavy conversation/JSONB blobs.
+// `turn_count` + `search_text` stand in for the transcript so a page never
+// detoasts it.
+const SUMMARY_COLS = `id, application_id, revision_id, team_id, external_key,
+ idempotency_key, trigger_metadata, state, principal,
+ usage_total, retry_count, turn_count, search_text,
+ created_at, updated_at`
+
const log = createLogger('pg-queue')
export class PgSessionQueue implements SessionQueue {
@@ -47,9 +57,10 @@ export class PgSessionQueue implements SessionQueue {
idempotency_key, trigger_metadata, state,
conversation, pending_inputs, principal, retry_count,
usage_total, acl, pending_elevation_requests,
+ search_text, turn_count,
created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7::jsonb, $8, $9::jsonb, $10::jsonb,
- $11::jsonb, $12, $13::jsonb, $14::jsonb, $15::jsonb, $16, $17)
+ $11::jsonb, $12, $13::jsonb, $14::jsonb, $15::jsonb, $16, $17, $18, $19)
ON CONFLICT (id) DO UPDATE SET
state = EXCLUDED.state,
conversation = EXCLUDED.conversation,
@@ -57,6 +68,8 @@ export class PgSessionQueue implements SessionQueue {
usage_total = EXCLUDED.usage_total,
acl = EXCLUDED.acl,
pending_elevation_requests = EXCLUDED.pending_elevation_requests,
+ search_text = EXCLUDED.search_text,
+ turn_count = EXCLUDED.turn_count,
updated_at = EXCLUDED.updated_at`,
[
session.id,
@@ -74,6 +87,8 @@ export class PgSessionQueue implements SessionQueue {
JSON.stringify(session.usage_total ?? EMPTY_USAGE_TOTAL),
JSON.stringify(session.acl ?? []),
JSON.stringify(session.pending_elevation_requests ?? []),
+ buildSearchText(session.conversation),
+ session.conversation.length,
session.created_at,
session.updated_at,
]
@@ -148,6 +163,10 @@ export class PgSessionQueue implements SessionQueue {
if (patch.conversation !== undefined) {
sets.push(`conversation = $${i++}::jsonb`)
params.push(JSON.stringify(patch.conversation))
+ sets.push(`search_text = $${i++}`)
+ params.push(buildSearchText(patch.conversation))
+ sets.push(`turn_count = $${i++}`)
+ params.push(patch.conversation.length)
}
if (patch.pending_inputs !== undefined) {
sets.push(`pending_inputs = $${i++}::jsonb`)
@@ -224,12 +243,22 @@ export class PgSessionQueue implements SessionQueue {
}
async appendConversation(sessionId: string, msg: ConversationMessage): Promise<void> {
+ // Keep turn_count + search_text current without re-reading the whole
+ // transcript: bump the count and append this message's text (capped).
+ const text = buildSearchText([msg])
await this.pool.query(
`UPDATE agent_session
SET conversation = conversation || $2::jsonb,
+ turn_count = turn_count + 1,
+ search_text = LEFT(
+ CASE
+ WHEN $3 = '' THEN COALESCE(search_text, '')
+ WHEN COALESCE(search_text, '') = '' THEN $3
+ ELSE search_text || ' ' || $3
+ END, $4),
updated_at = NOW()
WHERE id = $1`,
- [sessionId, JSON.stringify([msg])]
+ [sessionId, JSON.stringify([msg]), text, SEARCH_TEXT_MAX]
)
}
@@ -437,6 +466,22 @@ export class PgSessionQueue implements SessionQueue {
return Number(r.rows[0]?.count ?? 0)
}
+ async listSummariesByApplication(applicationId: string, opts: ListSessionsOpts = {}): Promise<SessionSummary[]> {
+ const limit = Math.max(1, Math.min(opts.limit ?? 100, 500))
+ const offset = Math.max(0, opts.offset ?? 0)
+ const { where, params } = buildSessionFilter(applicationId, opts)
+ params.push(limit, offset)
+ const r = await this.pool.query<SummaryDbRow>(
+ `SELECT ${SUMMARY_COLS}
+ FROM agent_session
+ WHERE ${where.join(' AND ')}
+ ORDER BY created_at DESC
+ LIMIT $${params.length - 1} OFFSET $${params.length}`,
+ params
+ )
+ return r.rows.map(rowToSummary)
+ }
+
async listIdleCompleted(floorMaxAgeMs: number, limit = 200): Promise<AgentSession[]> {
const r = await this.pool.query<DbRow>(
`SELECT ${SELECT_COLS}
@@ -607,13 +652,12 @@ function buildSessionFilter(
where.push(`created_at <= $${params.length}`)
}
if (opts.search?.trim()) {
- // id + external_key only — transcript search would scan/detoast every
- // session's JSONB; it lands on a persisted, indexed column instead.
- // LIKE wildcards escaped so the term matches literally.
+ // id + external_key + the conversation digest (search_text) — never the
+ // raw conversation JSONB. LIKE wildcards escaped so the term is literal.
const term = `%${opts.search.trim().replace(/[\\%_]/g, '\\$&')}%`
params.push(term)
const idx = params.length
- where.push(`(id::text ILIKE $${idx} OR external_key ILIKE $${idx})`)
+ where.push(`(id::text ILIKE $${idx} OR external_key ILIKE $${idx} OR search_text ILIKE $${idx})`)
}
return { where, params }
}
@@ -665,3 +709,44 @@ function parseUsageTotal(raw: unknown): SessionUsageTotal {
}
return { ...EMPTY_USAGE_TOTAL, ...(raw as Partial<SessionUsageTotal>) }
}
+
+interface SummaryDbRow {
+ id: string
+ application_id: string
+ revision_id: string
+ team_id: number
+ external_key: string | null
+ idempotency_key: string | null
+ trigger_metadata: unknown
+ state: string
+ principal: unknown
+ usage_total: unknown
+ retry_count: number
+ turn_count: number | null
+ search_text: string | null
+ created_at: Date
+ updated_at: Date
+}
+
+function rowToSummary(row: SummaryDbRow): SessionSummary {
+ return {
+ id: row.id,
+ application_id: row.application_id,
+ revision_id: row.revision_id,
+ team_id: row.team_id,
+ external_key: row.external_key,
+ idempotency_key: row.idempotency_key,
+ trigger_metadata:
+ row.trigger_metadata && typeof row.trigger_metadata === 'object'
+ ? (row.trigger_metadata as Record<string, unknown>)
+ : null,
+ state: row.state as AgentSession['state'],
+ principal: (row.principal as AgentSession['principal']) ?? null,
+ usage_total: parseUsageTotal(row.usage_total),
+ retry_count: row.retry_count,
+ turns: row.turn_count ?? 0,
+ search_text: row.search_text ?? null,
+ created_at: row.created_at.toISOString(),
+ updated_at: row.updated_at.toISOString(),
+ }
+}
diff --git a/products/agent_platform/services/agent-shared/src/persistence/queue.ts b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
index a19296c329c0..223fc589917d 100644
--- a/products/agent_platform/services/agent-shared/src/persistence/queue.ts
+++ b/products/agent_platform/services/agent-shared/src/persistence/queue.ts
@@ -11,6 +11,7 @@ import {
PendingElevationRequest,
SessionAclEntry,
SessionPrincipal,
+ SessionUsageTotal,
} from '../spec/spec'
/** Input to the atomic elevation-decision transition (`decideElevationRequest`). */
@@ -70,10 +71,33 @@ export interface ListSessionsOpts {
createdAfter?: string
/** ISO datetime — only return sessions with created_at <= this. */
createdBefore?: string
- /** Case-insensitive substring over the session id and external_key. */
+ /** Case-insensitive substring over id, external_key, and the conversation digest. */
search?: string
}
+/**
+ * Lightweight list row — every summary column except the heavy `conversation`
+ * JSONB. `turns` and `search_text` come off persisted columns, so listing never
+ * detoasts a transcript.
+ */
+export interface SessionSummary {
+ id: string
+ application_id: string
+ revision_id: string
+ team_id: number
+ external_key: string | null
+ idempotency_key: string | null
+ trigger_metadata: Record<string, unknown> | null
+ state: AgentSession['state']
+ principal: AgentSession['principal']
+ usage_total: SessionUsageTotal
+ retry_count: number
+ turns: number
+ search_text: string | null
+ created_at: string
+ updated_at: string
+}
+
/**
* Narrow capability the runner needs to read + grow `pending_inputs` mid-loop
* without taking the whole `SessionQueue` dependency (and without the runner
@@ -169,6 +193,12 @@ export interface SessionQueue extends SessionInputsStore {
* and `offset` are ignored — the count is over the full filtered set.
*/
countByApplication(applicationId: string, opts?: Omit<ListSessionsOpts, 'limit' | 'offset'>): Promise<number>
+ /**
+ * Like `listByApplication` but returns {@link SessionSummary} rows (no
+ * conversation transcript) for the list view — `turns` + `search_text` read
+ * off persisted columns instead of detoasting JSONB.
+ */
+ listSummariesByApplication(applicationId: string, opts?: ListSessionsOpts): Promise<SessionSummary[]>
/**
* Roll up summary stats for an agent — drives the agent-detail
* overview tiles. `since` filters cost + sessions count to a
diff --git a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts
index ac22f4c9c7bd..95984e40724b 100644
--- a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.test.ts
@@ -1,5 +1,11 @@
-import { AssistantMessageRecord, ConversationMessage, EMPTY_USAGE_TOTAL, UserMessage } from './spec'
-import { accumulateUsage, lastAssistantTextPreview, totalConversationUsage } from './summarize-conversation'
+import { AssistantMessageRecord, ConversationMessage, EMPTY_USAGE_TOTAL, ToolResultMessage, UserMessage } from './spec'
+import {
+ accumulateUsage,
+ buildSearchText,
+ lastAssistantTextPreview,
+ previewText,
+ totalConversationUsage,
+} from './summarize-conversation'
function user(content: string): UserMessage {
return { role: 'user', content, timestamp: Date.now() }
@@ -84,6 +90,89 @@ describe('lastAssistantTextPreview', () => {
})
})
+describe('buildSearchText', () => {
+ function toolResult(text: string): ToolResultMessage {
+ return {
+ role: 'toolResult',
+ toolCallId: 'tc1',
+ toolName: 'bash',
+ content: [{ type: 'text', text }],
+ isError: false,
+ timestamp: Date.now(),
+ }
+ }
+
+ it('joins user + assistant text in order, collapsing whitespace', () => {
+ const c: ConversationMessage[] = [user('deploy the widget'), assistant({ text: 'on\n it' }), user('thanks')]
+ expect(buildSearchText(c)).toBe('deploy the widget on it thanks')
+ })
+
+ it('skips tool results and text-less assistant turns', () => {
+ const c: ConversationMessage[] = [
+ user('run it'),
+ toolResult('SECRET_TOKEN=abc noise that should not be searchable'),
+ { ...assistant({}), content: [] },
+ assistant({ text: 'done' }),
+ ]
+ expect(buildSearchText(c)).toBe('run it done')
+ })
+
+ it('truncates to the max code points without an ellipsis', () => {
+ const out = buildSearchText([user('a'.repeat(50))], 10)
+ expect(out).toBe('a'.repeat(10))
+ })
+
+ it('handles array-form user content', () => {
+ const c: ConversationMessage[] = [
+ { role: 'user', content: [{ type: 'text', text: 'hello' }], timestamp: Date.now() },
+ ]
+ expect(buildSearchText(c)).toBe('hello')
+ })
+
+ it('strips the slack envelope + mention, keeping the real message', () => {
+ const slack = user(
+ [
+ '[slack]',
+ 'channel: C0BA3AC9TT2',
+ 'ts: 1782215525.31',
+ 'thread_ts: 1782215525.31',
+ 'user: U03DCBD92JX',
+ 'mention: true',
+ 'dm: false',
+ '',
+ '<@U0BCBQVL62G> what happened today?',
+ ].join('\n')
+ )
+ expect(buildSearchText([slack, assistant({ text: 'A few things.' })])).toBe(
+ 'what happened today? A few things.'
+ )
+ })
+
+ it('strips the [console-context] block, keeping the real message', () => {
+ const consoleMsg = user(
+ '[console-context]\n{"page":"agent","project_id":1}\n[/console-context]\n\ncan you test out this agent'
+ )
+ expect(buildSearchText([consoleMsg])).toBe('can you test out this agent')
+ })
+
+ it('leaves cron / plain messages untouched', () => {
+ expect(buildSearchText([user('Build the morning briefing for 2026-06-23.')])).toBe(
+ 'Build the morning briefing for 2026-06-23.'
+ )
+ })
+})
+
+describe('previewText', () => {
+ it('returns null for null/empty', () => {
+ expect(previewText(null)).toBeNull()
+ expect(previewText(' ')).toBeNull()
+ })
+
+ it('collapses and truncates with an ellipsis', () => {
+ expect(previewText('hi there', 4)).toBe('hi …')
+ })
+})
+
describe('totalConversationUsage', () => {
it('returns all zeros for an empty conversation', () => {
expect(totalConversationUsage([])).toEqual({
diff --git a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts
index 8584aa816bcb..f03e36b755ee 100644
--- a/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts
+++ b/products/agent_platform/services/agent-shared/src/spec/summarize-conversation.ts
@@ -41,6 +41,72 @@ export function lastAssistantTextPreview(
return null
}
+/** Cap for the persisted `search_text` digest — bounds the column + the scan. */
+export const SEARCH_TEXT_MAX = 10_000
+
+/**
+ * Strip the routing/context envelopes the triggers prepend to a user message so
+ * the digest captures what was actually said, not channel ids / page JSON:
+ * - `[slack]` + `key: value` lines, ended by a blank line (ingress slack trigger)
+ * - `[console-context] … [/console-context]` JSON block (the console chat client)
+ * - `<@U…>` Slack mention tokens
+ */
+function stripInjectedContext(text: string): string {
+ return text
+ .replace(/^\s*\[([a-z][a-z0-9-]*)\][\s\S]*?\[\/\1\]\s*/i, '')
+ .replace(/^\s*\[slack\][\s\S]*?\n[ \t]*\n/i, '')
+ .replace(/<@[A-Z0-9]+>/g, ' ')
+ .trim()
+}
+
+/**
+ * Plain-text digest of a conversation (user + assistant text, in order,
+ * whitespace-collapsed and truncated): the value persisted to `search_text` so
+ * search + the list preview never touch the full JSONB transcript. User
+ * messages have their injected context envelope stripped; tool results and
+ * thinking are skipped — noisy and unbounded.
+ */
+export function buildSearchText(conversation: ConversationMessage[], max: number = SEARCH_TEXT_MAX): string {
+ const parts: string[] = []
+ for (const m of conversation) {
+ if (m.role === 'user') {
+ const raw =
+ typeof m.content === 'string'
+ ? m.content
+ : m.content
+ .filter((c) => c.type === 'text')
+ .map((c) => c.text)
+ .join(' ')
+ const cleaned = stripInjectedContext(raw)
+ if (cleaned) {
+ parts.push(cleaned)
+ }
+ } else if (m.role === 'assistant') {
+ for (const c of m.content) {
+ if (c.type === 'text') {
+ parts.push(c.text)
+ }
+ }
+ }
+ }
+ const collapsed = parts.join(' ').replace(/\s+/g, ' ').trim()
+ const chars = Array.from(collapsed)
+ return chars.length > max ? chars.slice(0, max).join('') : collapsed
+}
+
+/** Trim a stored `search_text` to a list-row preview (code-point-safe). */
+export function previewText(searchText: string | null, max: number = PREVIEW_MAX): string | null {
+ if (!searchText) {
+ return null
+ }
+ const collapsed = searchText.replace(/\s+/g, ' ').trim()
+ if (!collapsed) {
+ return null
+ }
+ const chars = Array.from(collapsed)
+ return chars.length > max ? `${chars.slice(0, max - 1).join('')}…` : collapsed
+}
+
/**
* Aggregate token + cost numbers across every assistant message in the
* conversation. Returns all-zeroes when no assistant has run yet (or when the