chatCache.ts 86 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. import { projectChatEvent } from './chatEventProjection.js'
  2. import { HttpError } from './errors.js'
  3. import { createHash, randomUUID } from 'node:crypto'
  4. import { chmodSync, createReadStream, existsSync, mkdirSync, renameSync, statSync, unlinkSync, writeFileSync } from 'node:fs'
  5. import { join } from 'node:path'
  6. import { DatabaseSync } from 'node:sqlite'
  7. import type { UpstreamResponse } from './upstream.js'
  8. import type { UpstreamServiceSession } from './localAuth.js'
  9. export type ChatCacheMode = 'upstream-only' | 'shadow' | 'prefer-local'
  10. export type ChatCacheState = 'current' | 'stale' | 'syncing' | 'gap'
  11. export type ChatCacheSource = 'local' | 'upstream'
  12. interface StoredSnapshot {
  13. response: UpstreamResponse
  14. state: ChatCacheState
  15. }
  16. interface MessagePage {
  17. response: UpstreamResponse
  18. state: ChatCacheState
  19. }
  20. function object(value: unknown): Record<string, unknown> | undefined {
  21. return value && typeof value === 'object' && !Array.isArray(value)
  22. ? value as Record<string, unknown> : undefined
  23. }
  24. function parseResponse(response: UpstreamResponse): Record<string, unknown> | undefined {
  25. if (response.status < 200 || response.status >= 300) return undefined
  26. try { return object(JSON.parse(response.body.toString('utf8'))) } catch { return undefined }
  27. }
  28. function headerRecord(headers: Headers): string {
  29. return JSON.stringify(Object.fromEntries([...headers.entries()].filter(([name]) => name.toLowerCase() !== 'set-cookie')))
  30. }
  31. function responseFromRow(row: Record<string, unknown>): UpstreamResponse {
  32. return {
  33. status: Number(row.status),
  34. headers: new Headers(JSON.parse(String(row.headers)) as Record<string, string>),
  35. body: Buffer.from(String(row.body), 'base64'),
  36. }
  37. }
  38. function profileOf(value: Record<string, unknown>, fallback = ''): string {
  39. return String(value.profile ?? value.profile_name ?? fallback).trim()
  40. }
  41. function sessionIDOf(value: Record<string, unknown>): string {
  42. return String(value.id ?? value.session_id ?? value.sessionId ?? '').trim()
  43. }
  44. function sessionSource(value: Record<string, unknown>): string {
  45. return String(value.source ?? '').trim()
  46. }
  47. function sessionTitle(value: Record<string, unknown>): string {
  48. return String(value.title ?? '').trim()
  49. }
  50. // Hermes uses Unix seconds; local route registration uses milliseconds. Keep
  51. // the public summary in seconds so Web and iOS compare the same activity time.
  52. function timestampSeconds(value: unknown): number | undefined {
  53. if (typeof value !== 'number' && typeof value !== 'string') return undefined
  54. const numeric = Number(value)
  55. const seconds = Number.isFinite(numeric)
  56. ? numeric > 10_000_000_000 ? numeric / 1_000 : numeric
  57. : typeof value === 'string' ? Date.parse(value) / 1_000 : NaN
  58. return Number.isFinite(seconds) && seconds > 0 ? seconds : undefined
  59. }
  60. function firstTimestamp(value: Record<string, unknown>, keys: string[]): number | undefined {
  61. for (const key of keys) {
  62. const timestamp = timestampSeconds(value[key])
  63. if (timestamp !== undefined) return timestamp
  64. }
  65. return undefined
  66. }
  67. const START_TIME_KEYS = ['started_at', 'startedAt', 'session_started', 'created_at', 'createdAt']
  68. const ACTIVITY_TIME_KEYS = ['last_active', 'last_active_at', 'last_activity_at', 'lastActive', 'updated_at', 'updatedAt']
  69. function mergeSessionMetadata(previous: Record<string, unknown>, incoming: Record<string, unknown>): Record<string, unknown> {
  70. const summary = { ...previous, ...incoming }
  71. // A messages response can carry title/model metadata, but its envelope is
  72. // not a replacement for the session detail.
  73. delete summary.messages
  74. delete summary.pagination
  75. const started = firstTimestamp(incoming, START_TIME_KEYS) ?? firstTimestamp(previous, START_TIME_KEYS)
  76. const activity = firstTimestamp(incoming, ACTIVITY_TIME_KEYS) ?? firstTimestamp(previous, ACTIVITY_TIME_KEYS)
  77. if (started !== undefined) summary.started_at = started
  78. if (activity !== undefined) summary.last_active = activity
  79. return summary
  80. }
  81. function messageTimeBounds(messages: Record<string, unknown>[]): { first?: number; last?: number } {
  82. let first: number | undefined
  83. let last: number | undefined
  84. for (const message of messages) {
  85. const time = firstTimestamp(message, ['timestamp', 'created_at', 'createdAt'])
  86. if (time === undefined) continue
  87. first = Math.min(first ?? time, time)
  88. last = Math.max(last ?? time, time)
  89. }
  90. return { first, last }
  91. }
  92. function isPlaceholderTitle(value: string): boolean {
  93. return new Set([
  94. '', '新对话', '新会话', '未命名对话', '未命名会话', 'new conversation', 'new session', 'untitled',
  95. ]).has(value.trim().toLowerCase())
  96. }
  97. function messageID(value: Record<string, unknown>, fallback: string): string {
  98. const id = String(value.id ?? value.row_id ?? value.message_id ?? value.messageId ?? '').trim()
  99. return id || createHash('sha256').update(JSON.stringify(value) + fallback).digest('hex')
  100. }
  101. function bool(value: unknown): boolean {
  102. return value === true || value === 1 || value === '1' || value === 'true'
  103. }
  104. const PATH_PATTERN = /(?:file:\/\/)?(\/(?:Users|private|var|tmp)\/[^\s<>'"`)\]}]+\.[A-Za-z0-9]{1,12})/g
  105. function referencedPaths(value: unknown, output = new Set<string>()): Set<string> {
  106. if (typeof value === 'string') {
  107. for (const match of value.matchAll(PATH_PATTERN)) output.add(match[1]!)
  108. } else if (Array.isArray(value)) {
  109. for (const child of value) referencedPaths(child, output)
  110. } else {
  111. const record = object(value)
  112. if (record) for (const child of Object.values(record)) referencedPaths(child, output)
  113. }
  114. return output
  115. }
  116. export class ChatCacheStore {
  117. readonly db: DatabaseSync
  118. readonly assetsRoot: string
  119. private closed = false
  120. get isClosed(): boolean { return this.closed }
  121. constructor(home: string, legacySingleUserID?: string) {
  122. mkdirSync(home, { recursive: true, mode: 0o700 })
  123. const path = join(home, 'chat-cache.sqlite3')
  124. this.db = new DatabaseSync(path)
  125. chmodSync(path, 0o600)
  126. this.assetsRoot = join(home, 'chat-cache-assets')
  127. mkdirSync(this.assetsRoot, { recursive: true, mode: 0o700 })
  128. this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;
  129. CREATE TABLE IF NOT EXISTS chat_sessions(
  130. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  131. runtime_id TEXT, source TEXT NOT NULL, data TEXT NOT NULL, authoritative_title TEXT,
  132. authoritative_title_at INTEGER NOT NULL DEFAULT 0,
  133. owned_at INTEGER, ownership_evidence TEXT,
  134. sync_state TEXT NOT NULL DEFAULT 'stale', complete INTEGER NOT NULL DEFAULT 0,
  135. last_event_seq INTEGER NOT NULL DEFAULT 0, last_synced_at INTEGER NOT NULL,
  136. PRIMARY KEY(owner,profile,session_id));
  137. CREATE TABLE IF NOT EXISTS chat_messages(
  138. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  139. message_id TEXT NOT NULL, position INTEGER NOT NULL, data TEXT NOT NULL,
  140. content_hash TEXT NOT NULL, PRIMARY KEY(owner,profile,session_id,message_id));
  141. CREATE INDEX IF NOT EXISTS chat_messages_position ON chat_messages(owner,profile,session_id,position);
  142. CREATE TABLE IF NOT EXISTS chat_events(
  143. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  144. event_seq INTEGER NOT NULL, event_type TEXT NOT NULL, payload TEXT NOT NULL,
  145. received_at INTEGER NOT NULL, PRIMARY KEY(owner,profile,session_id,event_seq,event_type));
  146. CREATE TABLE IF NOT EXISTS chat_attachments(
  147. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  148. source_path TEXT NOT NULL, sha256 TEXT, mime_type TEXT, size INTEGER,
  149. local_path TEXT, state TEXT NOT NULL DEFAULT 'pending', updated_at INTEGER NOT NULL,
  150. PRIMARY KEY(owner,profile,session_id,source_path));
  151. CREATE INDEX IF NOT EXISTS chat_attachments_source ON chat_attachments(owner,source_path);
  152. CREATE TABLE IF NOT EXISTS chat_sync_cursors(
  153. owner TEXT NOT NULL, profile TEXT NOT NULL, generation TEXT,
  154. event_cursor INTEGER NOT NULL DEFAULT 0, sync_state TEXT NOT NULL DEFAULT 'stale',
  155. last_synced_at INTEGER NOT NULL, PRIMARY KEY(owner,profile));
  156. CREATE TABLE IF NOT EXISTS chat_snapshots(
  157. owner TEXT NOT NULL, cache_key TEXT NOT NULL, kind TEXT NOT NULL,
  158. profile TEXT NOT NULL, session_id TEXT, status INTEGER NOT NULL,
  159. headers TEXT NOT NULL, body TEXT NOT NULL, sync_state TEXT NOT NULL,
  160. saved_at INTEGER NOT NULL, PRIMARY KEY(owner,cache_key));
  161. CREATE TABLE IF NOT EXISTS chat_meta(
  162. key TEXT PRIMARY KEY, value TEXT NOT NULL);`)
  163. this.db.exec(`CREATE TABLE IF NOT EXISTS chat_local_state(
  164. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL,
  165. pinned INTEGER, read_count INTEGER NOT NULL DEFAULT 0,
  166. assistant_id TEXT, PRIMARY KEY(owner,profile,session_id));
  167. CREATE TABLE IF NOT EXISTS chat_session_aliases(owner TEXT NOT NULL,profile TEXT NOT NULL,alias_id TEXT NOT NULL,session_id TEXT NOT NULL,PRIMARY KEY(owner,profile,alias_id));
  168. CREATE TABLE IF NOT EXISTS chat_recovery_jobs(owner TEXT NOT NULL,profile TEXT NOT NULL,session_id TEXT NOT NULL,force INTEGER NOT NULL DEFAULT 0,PRIMARY KEY(owner,profile,session_id));
  169. CREATE TABLE IF NOT EXISTS chat_event_receipts(
  170. owner TEXT NOT NULL, profile TEXT NOT NULL, session_id TEXT NOT NULL, event_id TEXT NOT NULL,
  171. PRIMARY KEY(owner,profile,session_id,event_id));`)
  172. const localColumns=this.db.prepare('PRAGMA table_info(chat_local_state)').all() as {name:string}[]
  173. for(const [name,type] of [['title','TEXT'],['archived','INTEGER'],['read_initialized','INTEGER NOT NULL DEFAULT 0']]){
  174. if(!localColumns.some(c=>c.name===name))this.db.exec(`ALTER TABLE chat_local_state ADD COLUMN ${name} ${type}`)
  175. }
  176. const sessionColumns = this.db.prepare('PRAGMA table_info(chat_sessions)').all() as Array<{ name: string }>
  177. this.db.exec('BEGIN IMMEDIATE')
  178. try {
  179. if (!sessionColumns.some(column => column.name === 'sync_revision')) {
  180. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN sync_revision INTEGER NOT NULL DEFAULT 0')
  181. }
  182. if (!sessionColumns.some(column => column.name === 'message_total')) {
  183. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN message_total INTEGER')
  184. }
  185. if (!sessionColumns.some(column => column.name === 'metadata_complete')) {
  186. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN metadata_complete INTEGER NOT NULL DEFAULT 0')
  187. this.db.exec("UPDATE chat_sessions SET metadata_complete=1 WHERE json_valid(data) AND (json_type(data,'$.message_count') IS NOT NULL OR json_type(data,'$.model') IS NOT NULL)")
  188. }
  189. if (!sessionColumns.some(column => column.name === 'authoritative_title')) {
  190. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN authoritative_title TEXT')
  191. }
  192. if (!sessionColumns.some(column => column.name === 'authoritative_title_at')) {
  193. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN authoritative_title_at INTEGER NOT NULL DEFAULT 0')
  194. }
  195. if (!sessionColumns.some(column => column.name === 'owned_at')) {
  196. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN owned_at INTEGER')
  197. }
  198. if (!sessionColumns.some(column => column.name === 'ownership_evidence')) {
  199. this.db.exec('ALTER TABLE chat_sessions ADD COLUMN ownership_evidence TEXT')
  200. }
  201. this.db.exec(`CREATE INDEX IF NOT EXISTS chat_sessions_owned
  202. ON chat_sessions(owner,profile,owned_at,last_synced_at)`)
  203. const ownershipMigration = this.db.prepare(
  204. "SELECT value FROM chat_meta WHERE key='ownership-registry-v1'",
  205. ).get() as { value?: string } | undefined
  206. if (!ownershipMigration) {
  207. // A single cached owner is trusted only when the persisted local user
  208. // database independently confirms the same sole identity.
  209. const legacyOwners = this.db.prepare(
  210. 'SELECT DISTINCT owner FROM chat_sessions ORDER BY owner',
  211. ).all() as Array<{ owner: string }>
  212. if (legacyOwners.length === 1 && legacyOwners[0]!.owner === legacySingleUserID) {
  213. this.db.exec(`UPDATE chat_sessions SET
  214. owned_at=COALESCE(owned_at,last_synced_at),
  215. ownership_evidence=COALESCE(ownership_evidence,'legacy-single-user')`)
  216. }
  217. }
  218. // Recover interrupted/new-schema writes only from explicit command proof.
  219. this.db.exec(`UPDATE chat_sessions SET
  220. owned_at=COALESCE(owned_at,(
  221. SELECT MIN(chat_events.received_at) FROM chat_events
  222. WHERE chat_events.owner=chat_sessions.owner
  223. AND chat_events.profile=chat_sessions.profile
  224. AND chat_events.session_id=chat_sessions.session_id
  225. AND chat_events.event_type IN ('command:session.create','command:session.branch')
  226. )),
  227. ownership_evidence=COALESCE(ownership_evidence,'command-migration')
  228. WHERE EXISTS (
  229. SELECT 1 FROM chat_events
  230. WHERE chat_events.owner=chat_sessions.owner
  231. AND chat_events.profile=chat_sessions.profile
  232. AND chat_events.session_id=chat_sessions.session_id
  233. AND chat_events.event_type IN ('command:session.create','command:session.branch')
  234. )`)
  235. const legacyTitles = this.db.prepare(`SELECT owner,profile,session_id,data FROM chat_sessions
  236. WHERE authoritative_title IS NULL`).all() as Array<{
  237. owner: string; profile: string; session_id: string; data: string
  238. }>
  239. const backfillTitle = this.db.prepare(`UPDATE chat_sessions SET authoritative_title=?
  240. WHERE owner=? AND profile=? AND session_id=? AND authoritative_title IS NULL`)
  241. for (const row of legacyTitles) {
  242. let summary: Record<string, unknown> = {}
  243. try { summary = object(JSON.parse(row.data)) ?? {} } catch { continue }
  244. const title = sessionTitle(summary)
  245. if (!isPlaceholderTitle(title)) backfillTitle.run(title, row.owner, row.profile, row.session_id)
  246. }
  247. if (!this.db.prepare("SELECT 1 FROM chat_meta WHERE key='session-activity-v1'").get()) {
  248. const rows = this.db.prepare(`SELECT owner,profile,session_id,source,data,owned_at,message_total
  249. FROM chat_sessions WHERE owned_at IS NOT NULL`).all() as Array<{
  250. owner: string; profile: string; session_id: string; source: string; data: string
  251. owned_at: number; message_total: number | null
  252. }>
  253. const update = this.db.prepare(`UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?`)
  254. for (const row of rows) {
  255. let stored: Record<string, unknown>
  256. try { stored = object(JSON.parse(row.data)) ?? {} } catch { continue }
  257. const summary = mergeSessionMetadata({}, stored)
  258. if (Array.isArray(stored.messages) || !firstTimestamp(summary, START_TIME_KEYS)
  259. || !firstTimestamp(summary, ACTIVITY_TIME_KEYS)) {
  260. const messages = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?`)
  261. .all(row.owner, row.profile, row.session_id) as Array<{ data: string }>
  262. const bounds = messageTimeBounds(messages.flatMap(message => {
  263. try { return [object(JSON.parse(message.data)) ?? {}] } catch { return [] }
  264. }))
  265. summary.started_at = firstTimestamp(summary, START_TIME_KEYS) ?? bounds.first ?? timestampSeconds(row.owned_at)
  266. summary.last_active = Math.max(firstTimestamp(summary, ACTIVITY_TIME_KEYS) ?? 0,
  267. bounds.last ?? 0) || summary.started_at
  268. if (row.message_total !== null) summary.message_count = row.message_total
  269. }
  270. summary.id = row.session_id
  271. summary.profile = row.profile
  272. summary.source = sessionSource(summary) || row.source
  273. update.run(JSON.stringify(summary), row.owner, row.profile, row.session_id)
  274. }
  275. this.db.prepare("INSERT INTO chat_meta(key,value) VALUES('session-activity-v1','complete')").run()
  276. }
  277. // List bodies written before ownership became an explicit projection do
  278. // not carry `owned` and may have been filtered by `source`. Rebuild them on
  279. // first use after every restart instead of serving a semantically old page.
  280. this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE kind='list'").run()
  281. this.db.prepare(`INSERT INTO chat_meta(key,value) VALUES('ownership-registry-v1','complete')
  282. ON CONFLICT(key) DO UPDATE SET value=excluded.value`).run()
  283. this.db.prepare(`INSERT OR IGNORE INTO chat_local_state(owner,profile,session_id)
  284. SELECT owner,profile,session_id FROM chat_sessions WHERE owned_at IS NOT NULL`).run()
  285. this.db.exec('COMMIT')
  286. } catch (error) {
  287. this.db.exec('ROLLBACK')
  288. throw error
  289. }
  290. }
  291. close(): void { this.closed = true; this.db.close() }
  292. stats(): Record<string, number> {
  293. const count = (table: string) => Number((this.db.prepare(`SELECT COUNT(*) count FROM ${table}`).get() as { count: number }).count)
  294. const bytes = Number((this.db.prepare(`SELECT COALESCE(SUM(size),0) bytes FROM chat_attachments WHERE state='cached'`).get() as { bytes: number }).bytes)
  295. return {
  296. sessions: Number((this.db.prepare(`SELECT COUNT(*) count FROM chat_sessions
  297. WHERE owned_at IS NOT NULL`).get() as { count: number }).count),
  298. messages: count('chat_messages'),
  299. events: count('chat_events'),
  300. attachments: count('chat_attachments'),
  301. attachmentBytes: bytes,
  302. }
  303. }
  304. snapshot(owner: string, key: string): StoredSnapshot | undefined {
  305. const row = this.db.prepare('SELECT status,headers,body,sync_state FROM chat_snapshots WHERE owner=? AND cache_key=?')
  306. .get(owner, key) as Record<string, unknown> | undefined
  307. return row ? { response: responseFromRow(row), state: String(row.sync_state) as ChatCacheState } : undefined
  308. }
  309. localList(owner: string, profile: string, page: { offset?: number; limit?: number; archived?: string }): UpstreamResponse {
  310. const offset = Math.max(0, Math.trunc(page.offset ?? 0)), limit = Math.max(1, Math.min(200, Math.trunc(page.limit ?? 100)))
  311. const where = `s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)
  312. AND s.source NOT IN ('cron','ios_group','yaoyao_workspace')
  313. AND (?='include' OR COALESCE(l.archived,json_extract(s.data,'$.archived'),json_extract(s.data,'$.is_archived'),0)=CASE WHEN ?='only' THEN 1 ELSE 0 END)`
  314. const args = [owner, profile, profile, page.archived ?? 'exclude', page.archived ?? 'exclude']
  315. const total = Number((this.db.prepare(`SELECT count(*) n FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE ${where}`).get(...args) as {n:number}).n)
  316. const rows = this.db.prepare(`SELECT s.profile,s.session_id,s.data,s.sync_state,s.complete,l.title local_title,
  317. COALESCE(l.pinned,json_extract(s.data,'$.pinned'),json_extract(s.data,'$.is_pinned'),0) pin
  318. FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id) WHERE ${where}
  319. ORDER BY pin DESC, COALESCE(json_extract(s.data,'$.last_active'),0) DESC, s.session_id
  320. LIMIT ? OFFSET ?`).all(...args, limit, offset) as Array<Record<string,any>>
  321. return {status:200,headers:new Headers({'content-type':'application/json'}),body:Buffer.from(JSON.stringify({
  322. sessions:rows.map(r=>({...JSON.parse(r.data),...(r.local_title!=null?{title:r.local_title}:{}),id:r.session_id,profile:r.profile,owned:true,pinned:!!r.pin,
  323. sync_state:r.sync_state,history_complete:!!r.complete})), total,offset,limit,
  324. sync_state:this.needsListMetadata(owner,profile)?'syncing':'current'
  325. }))}
  326. }
  327. missingSessions(owner: string, profile: string): Array<{profile:string;session_id:string}> {
  328. return (this.db.prepare(`SELECT profile,session_id FROM chat_sessions WHERE owner=? AND owned_at IS NOT NULL
  329. AND (?='' OR profile=?) AND (metadata_complete=0 OR complete=0) LIMIT 100`)
  330. .all(owner,profile,profile) as {profile:string;session_id:string}[])
  331. }
  332. pins(owner: string, profile: string): string[] {
  333. return (this.db.prepare(`SELECT s.session_id FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id)
  334. WHERE s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)
  335. AND COALESCE(l.pinned,json_extract(s.data,'$.pinned'),json_extract(s.data,'$.is_pinned'),0)=1 ORDER BY s.last_synced_at DESC`)
  336. .all(owner,profile,profile) as {session_id:string}[]).map(r=>r.session_id)
  337. }
  338. unread(owner: string, profile: string) {
  339. const sessions = (this.db.prepare(`SELECT s.profile,s.session_id,COALESCE(s.message_total,0) message_count,
  340. CASE WHEN COALESCE(l.read_initialized,0)=1 THEN l.read_count ELSE COALESCE(s.message_total,0) END read_message_count FROM chat_sessions s LEFT JOIN chat_local_state l USING(owner,profile,session_id)
  341. WHERE s.owner=? AND s.owned_at IS NOT NULL AND (?='' OR s.profile=?)`).all(owner,profile,profile) as any[])
  342. .map(r=>({...r,updated_at:Date.now(),unread_count:Math.max(0,r.message_count-r.read_message_count)}))
  343. return {profile,supported:true,total_unread:sessions.reduce((n,r)=>n+r.unread_count,0),sessions}
  344. }
  345. markRead(owner: string, profile: string, id: string, count?: number) {
  346. id=this.canonicalSessionID(owner,profile,id)
  347. this.requireOwned(owner,profile,id)
  348. const total = Number((this.db.prepare('SELECT message_total FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
  349. .get(owner,profile,id) as any).message_total ?? 0)
  350. const read = Math.max(0,Math.min(total, count ?? total))
  351. this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,read_count,read_initialized) VALUES(?,?,?,?,1)
  352. ON CONFLICT(owner,profile,session_id) DO UPDATE SET read_count=MAX(read_count,excluded.read_count),read_initialized=1`).run(owner,profile,id,read)
  353. return this.unread(owner,profile).sessions.find(r=>r.session_id===id)!
  354. }
  355. requireOwned(owner: string, profile: string, id: string): void {
  356. if (!this.ownsSession(owner,profile,id)) throw new HttpError(404,'会话不存在','session_not_found')
  357. }
  358. patchLocal(owner: string, profile: string, id: string, patch: Record<string,unknown>): void {
  359. id=this.canonicalSessionID(owner,profile,id)
  360. this.requireOwned(owner,profile,id)
  361. this.db.exec('SAVEPOINT local_chat_patch')
  362. try {
  363. if (typeof patch.pinned==='boolean') this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,pinned) VALUES(?,?,?,?)
  364. ON CONFLICT(owner,profile,session_id) DO UPDATE SET pinned=excluded.pinned`).run(owner,profile,id,patch.pinned?1:0)
  365. const row = this.localDetail(owner,profile,id)!
  366. const data = {...JSON.parse(row.response.body.toString()),...patch}
  367. this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?').run(JSON.stringify(data),owner,profile,id)
  368. for(const key of ['title','archived'] as const)if(patch[key]!==undefined){
  369. const value=key==='archived'?(patch[key]?1:0):String(patch[key])
  370. this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,${key}) VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET ${key}=excluded.${key}`).run(owner,profile,id,value)
  371. }
  372. if(typeof patch.title==='string') this.recordAuthoritativeTitle(owner,profile,id,patch.title)
  373. this.db.prepare("UPDATE chat_sessions SET sync_state=CASE WHEN complete=1 THEN 'current' ELSE sync_state END WHERE owner=? AND profile=? AND session_id=?").run(owner,profile,id)
  374. this.db.exec('RELEASE local_chat_patch')
  375. } catch(e) {this.db.exec('ROLLBACK TO local_chat_patch; RELEASE local_chat_patch');throw e}
  376. }
  377. private writeLiveMessage(owner:string,profile:string,id:string,message:Record<string,any>): void {
  378. const prior = this.db.prepare('SELECT position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').get(owner,profile,id,message.id) as {position:number}|undefined
  379. const row = this.db.prepare('SELECT message_total,complete,data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id) as any
  380. const extent = Number((this.db.prepare('SELECT COALESCE(MAX(position)+1,0) n FROM chat_messages WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id) as any).n)
  381. const position = prior?.position ?? Math.max(extent,Number(row.message_total??0))
  382. const data=JSON.stringify(message)
  383. this.db.prepare(`INSERT INTO chat_messages(owner,profile,session_id,message_id,position,data,content_hash) VALUES(?,?,?,?,?,?,?)
  384. ON CONFLICT(owner,profile,session_id,message_id) DO UPDATE SET data=excluded.data,content_hash=excluded.content_hash`).run(owner,profile,id,message.id,position,data,createHash('sha256').update(data).digest('hex'))
  385. const total=Math.max(Number(row.message_total??0),position+1), summary=JSON.parse(row.data)
  386. const now=Date.now()
  387. summary.message_count=total; summary.last_active=now/1000
  388. if (typeof message.content==='string' && message.content.trim()) summary.preview=message.content.slice(0,160)
  389. this.db.prepare('UPDATE chat_sessions SET data=?,message_total=?,last_synced_at=? WHERE owner=? AND profile=? AND session_id=?').run(JSON.stringify(summary),total,now,owner,profile,id)
  390. for(const path of referencedPaths(message)) this.db.prepare(`INSERT OR IGNORE INTO chat_attachments(owner,profile,session_id,source_path,state,updated_at) VALUES(?,?,?,?,'pending',?)`).run(owner,profile,id,path,now)
  391. }
  392. projectedMessageID(owner:string,profile:string,id:string):string|undefined {
  393. return (this.db.prepare(`SELECT message_id FROM chat_messages WHERE owner=? AND profile=? AND session_id=?
  394. AND json_extract(data,'$.role')='assistant' ORDER BY position DESC LIMIT 1`).get(owner,profile,id) as {message_id:string}|undefined)?.message_id
  395. }
  396. private projectEvent(owner:string,profile:string,id:string,type:string,p:Record<string,any>,eventID:string): void {
  397. if(!this.ownsSession(owner,profile,id))return
  398. if(type==='command.confirmed'||type==='command.rejected'){
  399. const userID=`user:${p.delivery_id}`
  400. const row=this.db.prepare('SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').get(owner,profile,id,userID) as any
  401. if(row)this.writeLiveMessage(owner,profile,id,{...JSON.parse(row.data),status:type==='command.confirmed'?'complete':'failed',...(p.error?{error:p.error}:{})})
  402. this.db.prepare("UPDATE chat_sessions SET sync_state=CASE WHEN sync_state='gap' THEN 'gap' WHEN complete=1 THEN 'current' ELSE 'stale' END WHERE owner=? AND profile=? AND session_id=?").run(owner,profile,id)
  403. return
  404. }
  405. if (type==='message.user' || type==='peer_user_message') {
  406. this.writeLiveMessage(owner,profile,id,{...p,id:String(p.message_id??p.id??eventID),role:'user',content:p.text??p.content??'',timestamp:Date.now()/1000});return
  407. }
  408. const state=this.db.prepare('SELECT assistant_id FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id) as any
  409. const last=state?.assistant_id?this.db.prepare('SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').get(owner,profile,id,state.assistant_id) as any:undefined
  410. const previous=last?JSON.parse(last.data):undefined
  411. // A new run must never append to the assistant row from the preceding turn.
  412. if(['message.complete','run.completed'].includes(type) && !previous && !p.text && !p.content && !p.message){
  413. this.db.prepare("UPDATE chat_sessions SET sync_state='gap' WHERE owner=? AND profile=? AND session_id=?").run(owner,profile,id);return
  414. }
  415. const startsNew=type==='message.start' && previous?.status!=='streaming'
  416. const message=projectChatEvent(type,p,startsNew?undefined:previous,`event:${eventID}`,Date.now())
  417. if(message){
  418. if(previous && previous.id !== message.id && !startsNew){
  419. const exists=this.db.prepare('SELECT 1 FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').get(owner,profile,id,message.id)
  420. if(!exists)this.db.prepare('UPDATE chat_messages SET message_id=? WHERE owner=? AND profile=? AND session_id=? AND message_id=?').run(message.id,owner,profile,id,previous.id)
  421. else {this.db.prepare("UPDATE chat_sessions SET sync_state='gap' WHERE owner=? AND profile=? AND session_id=?").run(owner,profile,id);return}
  422. }
  423. this.writeLiveMessage(owner,profile,id,message)
  424. this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,assistant_id) VALUES(?,?,?,?)
  425. ON CONFLICT(owner,profile,session_id) DO UPDATE SET assistant_id=excluded.assistant_id`).run(owner,profile,id,type==='message.interim'?null:message.id)
  426. this.db.prepare(`UPDATE chat_sessions SET sync_state=CASE WHEN sync_state='gap' THEN 'gap' WHEN complete=1 THEN 'current' ELSE 'stale' END
  427. WHERE owner=? AND profile=? AND session_id=?`).run(owner,profile,id)
  428. }
  429. }
  430. needsListMetadata(owner: string, profile: string): boolean {
  431. return Boolean(this.db.prepare(`SELECT 1 FROM chat_sessions WHERE owner=? AND owned_at IS NOT NULL
  432. AND (?='' OR profile=?) AND metadata_complete=0 LIMIT 1`).get(owner, profile, profile))
  433. }
  434. localDetail(owner: string, profile: string, sessionID: string): StoredSnapshot | undefined {
  435. const row = this.db.prepare(`SELECT data,sync_state FROM chat_sessions
  436. WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`)
  437. .get(owner, profile, sessionID) as { data: string; sync_state: ChatCacheState } | undefined
  438. if (!row) return undefined
  439. const local=this.db.prepare('SELECT title,archived,pinned FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionID) as any
  440. return { response: { status: 200, headers: new Headers({ 'content-type': 'application/json' }),
  441. body: Buffer.from(JSON.stringify({...JSON.parse(row.data),...(local?.title!=null?{title:local.title}:{}),...(local?.archived!=null?{archived:!!local.archived}:{}),owned:true,pinned:local?.pinned!=null?!!local.pinned:bool(JSON.parse(row.data).pinned),sync_state:row.sync_state})) }, state: row.sync_state }
  442. }
  443. revision(owner: string, profile: string, sessionID: string): number {
  444. return Number((this.db.prepare('SELECT sync_revision FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
  445. .get(owner, profile, sessionID) as { sync_revision?: number } | undefined)?.sync_revision ?? 0)
  446. }
  447. hasMessage(owner: string, profile: string, sessionID: string, message: Record<string, unknown>, position: number): boolean {
  448. const id = messageID(message, String(position))
  449. const row = this.db.prepare('SELECT position FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?')
  450. .get(owner, profile, sessionID, id) as { position: number } | undefined
  451. if (row && row.position !== position) throw new Error('Stored history changed; explicit refresh is required')
  452. return Boolean(row)
  453. }
  454. putSnapshot(owner: string, key: string, kind: string, profile: string, sessionID: string | undefined,
  455. response: UpstreamResponse, ownedList = false, requestStartedAt = Date.now(),
  456. metadataResponse: UpstreamResponse = response): boolean {
  457. const payload = parseResponse(response)
  458. if (!payload) return false
  459. if (kind === 'list' && !ownedList) return false
  460. const isOwnedChat = ownedList || this.payloadBelongsToOwnedChat(owner, profile, sessionID, payload)
  461. if (!isOwnedChat) return false
  462. const now = Date.now()
  463. this.db.exec('SAVEPOINT chat_snapshot')
  464. try {
  465. // Hydrate all registered sessions from the unsliced upstream list, while
  466. // persisting only the owner-filtered page as the public response snapshot.
  467. this.ingestPayload(owner, profile, sessionID, parseResponse(metadataResponse) ?? payload, now, kind, requestStartedAt)
  468. this.db.prepare(`INSERT INTO chat_snapshots(owner,cache_key,kind,profile,session_id,status,headers,body,sync_state,saved_at)
  469. VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,cache_key) DO UPDATE SET status=excluded.status,headers=excluded.headers,
  470. body=excluded.body,sync_state='current',saved_at=excluded.saved_at`)
  471. .run(owner, key, kind, profile, sessionID ?? null, response.status, headerRecord(response.headers),
  472. response.body.toString('base64'), 'current', now)
  473. this.db.exec('RELEASE chat_snapshot')
  474. return true
  475. } catch (error) {
  476. this.db.exec('ROLLBACK TO chat_snapshot; RELEASE chat_snapshot')
  477. throw error
  478. }
  479. }
  480. applySync(owner: string, profile: string, sessionID: string, revision: number,
  481. pages: Array<{ key: string; kind: string; response: UpstreamResponse; startedAt: number }>, force: boolean): boolean {
  482. if (this.revision(owner, profile, sessionID) !== revision) return false
  483. this.db.exec('SAVEPOINT history_sync')
  484. try {
  485. if (force) this.db.prepare('DELETE FROM chat_messages WHERE owner=? AND profile=? AND session_id=?').run(owner, profile, sessionID)
  486. // Recovery promotes locally generated stream identities to upstream row IDs.
  487. // Remove only replaced rows inside the verified window; keep older coverage.
  488. if(!force){
  489. const windows=pages.filter(p=>p.kind==='messages').map(p=>parseResponse(p.response)).filter(Boolean) as Record<string,any>[]
  490. for(const window of windows){
  491. const pagination=window.pagination??{},messages=window.messages as Record<string,any>[]
  492. if(!Array.isArray(messages)||!Number.isSafeInteger(pagination.total))continue
  493. const end=pagination.total-Number(pagination.offset??0),start=end-messages.length
  494. const ids=new Set(messages.map((m,index)=>messageID(m,String(start+index))))
  495. const existing=this.db.prepare('SELECT message_id,data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND position>=? AND position<?').all(owner,profile,sessionID,start,end) as {message_id:string;data:string}[]
  496. for(const row of existing){
  497. if(ids.has(row.message_id))continue
  498. const value=JSON.parse(row.data)
  499. if(value.role==='user'&&value.status==='pending'&&!messages.some(m=>m.role==='user'&&m.content===value.content))
  500. throw new Error('Unconfirmed submission must be reconciled before history replacement')
  501. this.db.prepare('DELETE FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?').run(owner,profile,sessionID,row.message_id)
  502. }
  503. }
  504. }
  505. this.db.prepare("DELETE FROM chat_snapshots WHERE owner=? AND profile=? AND session_id=? AND kind='messages'").run(owner, profile, sessionID)
  506. for (const page of pages) this.putSnapshot(owner, page.key, page.kind, profile, sessionID, page.response, false, page.startedAt)
  507. const latest=this.db.prepare("SELECT message_id FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND json_extract(data,'$.role')='assistant' ORDER BY position DESC LIMIT 1").get(owner,profile,sessionID) as {message_id:string}|undefined
  508. if(latest)this.db.prepare('UPDATE chat_local_state SET assistant_id=? WHERE owner=? AND profile=? AND session_id=?').run(latest.message_id,owner,profile,sessionID)
  509. this.db.exec('RELEASE history_sync')
  510. return true
  511. } catch (error) {
  512. this.db.exec('ROLLBACK TO history_sync; RELEASE history_sync')
  513. throw error
  514. }
  515. }
  516. messagePage(owner: string, profile: string, sessionID: string, offset: number, limit: number): MessagePage | undefined {
  517. const session = this.db.prepare(`SELECT data,sync_state,complete,message_total FROM chat_sessions
  518. WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as Record<string, unknown> | undefined
  519. if (!session) return undefined
  520. const totalRow = this.db.prepare('SELECT COUNT(*) count, MAX(position)+1 extent FROM chat_messages WHERE owner=? AND profile=? AND session_id=?')
  521. .get(owner, profile, sessionID) as { count: number; extent: number | null }
  522. if (session.message_total == null && !bool(session.complete)) return undefined
  523. const total = Number(session.message_total ?? totalRow.extent ?? 0)
  524. const end = Math.max(0, total - offset)
  525. const start = Math.max(0, end - limit)
  526. const rows = this.db.prepare(`SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=?
  527. AND position>=? AND position<? ORDER BY position`).all(owner, profile, sessionID, start, end) as Array<{ data: string }>
  528. const messages = rows.map(row => JSON.parse(row.data))
  529. if (messages.length !== end - start) return undefined // Fetch only an actually missing page.
  530. const body = Buffer.from(JSON.stringify({
  531. session_id: sessionID,
  532. session: JSON.parse(this.localDetail(owner,profile,sessionID)!.response.body.toString()),
  533. messages,
  534. pagination: {
  535. total,
  536. returned: messages.length,
  537. offset,
  538. limit,
  539. has_more: start > 0,
  540. },
  541. }))
  542. return {
  543. response: { status: 200, headers: new Headers({ 'content-type': 'application/json; charset=utf-8' }), body },
  544. state: String(session.sync_state) as ChatCacheState,
  545. }
  546. }
  547. recordEvent(owner: string, profile: string, sessionID: string, frame: Record<string, unknown>): boolean {
  548. const rawSeq = Number(frame.seq ?? frame.sequence ?? 0)
  549. const type = String(frame.type ?? 'unknown')
  550. const payload = JSON.stringify(frame.payload ?? {})
  551. const eventID = String(frame.delivery_id ?? (rawSeq > 0 ? `${frame.epoch ?? ''}:${rawSeq}:${type}` : randomUUID()))
  552. const seq = Number.parseInt(createHash('sha256').update(eventID).digest('hex').slice(0,12),16)
  553. const now = Date.now()
  554. this.db.exec('SAVEPOINT live_event')
  555. try {
  556. const receipt=this.db.prepare('INSERT OR IGNORE INTO chat_event_receipts VALUES(?,?,?,?)').run(owner,profile,sessionID,eventID)
  557. if(!receipt.changes){this.db.exec('RELEASE live_event');return false}
  558. const previous = this.db.prepare(`SELECT last_event_seq FROM chat_sessions
  559. WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as { last_event_seq?: number } | undefined
  560. const lastSeen = Number(previous?.last_event_seq ?? 0)
  561. const inserted = this.db.prepare(`INSERT OR IGNORE INTO chat_events(owner,profile,session_id,event_seq,event_type,payload,received_at)
  562. VALUES(?,?,?,?,?,?,?)`).run(owner, profile, sessionID, Number.isSafeInteger(seq) ? seq : 0, type, payload, now)
  563. if (!inserted.changes) {this.db.exec('RELEASE live_event');return false}
  564. const state: ChatCacheState = type === 'gateway.reset' || type.includes('reset')
  565. || (!frame.epoch && rawSeq > 0 && lastSeen > 0 && rawSeq > lastSeen + 1) ? 'gap' : 'stale'
  566. const metadataOnly = ['session.info', 'session.title', 'session.title.updated', 'session.usage', 'gateway.ready'].includes(type) && state !== 'gap'
  567. this.db.prepare(`UPDATE chat_sessions SET sync_state=CASE WHEN ? THEN sync_state WHEN sync_state='gap' THEN 'gap' ELSE ? END,
  568. sync_revision=sync_revision+?,last_event_seq=MAX(last_event_seq,?),last_synced_at=?
  569. WHERE owner=? AND profile=? AND session_id=?`).run(metadataOnly ? 1 : 0, state, metadataOnly ? 0 : 1, rawSeq > 0 ? rawSeq : lastSeen, now, owner, profile, sessionID)
  570. if (type === 'session.info') {
  571. const payload = object(frame.payload) ?? {}
  572. const info = object(payload.info) ?? payload
  573. const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
  574. .get(owner, profile, sessionID) as { data: string } | undefined
  575. if (row) {
  576. const summary = object(JSON.parse(row.data)) ?? {}
  577. for (const field of ['model', 'provider', 'fast']) if (info[field] !== undefined) summary[field] = info[field]
  578. this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?')
  579. .run(JSON.stringify(summary), owner, profile, sessionID)
  580. }
  581. }
  582. if (type === 'session.title' || type === 'session.title.updated') {
  583. const title = String(object(frame.payload)?.title ?? frame.title ?? '').trim()
  584. if (title) this.updateOwnedSessionTitle(owner, profile, sessionID, title, now)
  585. }
  586. this.db.prepare(`UPDATE chat_snapshots SET sync_state=? WHERE owner=? AND (session_id=? OR kind='list')
  587. AND (?=0 OR kind<>'messages')`).run(state, owner, sessionID, metadataOnly ? 1 : 0)
  588. this.db.prepare(`INSERT INTO chat_sync_cursors(owner,profile,event_cursor,sync_state,last_synced_at)
  589. VALUES(?,?,?,?,?) ON CONFLICT(owner,profile) DO UPDATE SET event_cursor=MAX(event_cursor,excluded.event_cursor),
  590. sync_state=excluded.sync_state,last_synced_at=excluded.last_synced_at`)
  591. .run(owner, profile, rawSeq > 0 ? rawSeq : lastSeen, state, now)
  592. this.projectEvent(owner,profile,sessionID,type,object(frame.payload)??{},eventID)
  593. this.db.exec('RELEASE live_event')
  594. return true
  595. }catch(e){this.db.exec('ROLLBACK TO live_event; RELEASE live_event');throw e}
  596. }
  597. canonicalSessionID(owner:string,profile:string,id:string):string {
  598. let current=id
  599. const seen=new Set<string>()
  600. for(let n=0;n<32&&!seen.has(current);n++){
  601. seen.add(current)
  602. const row=this.db.prepare('SELECT session_id FROM chat_session_aliases WHERE owner=? AND profile=? AND alias_id=?').get(owner,profile,current) as {session_id:string}|undefined
  603. if(!row)break
  604. current=row.session_id
  605. }
  606. return current
  607. }
  608. private migrateRuntimeSession(owner:string,profile:string,id:string,runtime:string):void {
  609. const old=this.db.prepare('SELECT session_id FROM chat_sessions WHERE owner=? AND profile=? AND runtime_id=? AND session_id<>? AND owned_at IS NOT NULL').get(owner,profile,runtime,id) as {session_id:string}|undefined
  610. if(!old||this.ownsSession(owner,profile,id))return
  611. this.db.exec('SAVEPOINT migrate_live_route')
  612. try{
  613. for(const table of ['chat_sessions','chat_messages','chat_events','chat_snapshots','chat_attachments','chat_local_state','chat_event_receipts','chat_recovery_jobs'])
  614. this.db.prepare(`UPDATE ${table} SET session_id=? WHERE owner=? AND profile=? AND session_id=?`).run(id,owner,profile,old.session_id)
  615. this.db.prepare('INSERT OR REPLACE INTO chat_session_aliases VALUES(?,?,?,?)').run(owner,profile,old.session_id,id)
  616. this.db.prepare('UPDATE chat_session_aliases SET session_id=? WHERE owner=? AND profile=? AND session_id=?').run(id,owner,profile,old.session_id)
  617. this.db.prepare("UPDATE chat_sessions SET data=json_set(data,'$.id',?) WHERE owner=? AND profile=? AND session_id=?").run(id,owner,profile,id)
  618. this.db.exec('RELEASE migrate_live_route')
  619. }catch(e){this.db.exec('ROLLBACK TO migrate_live_route; RELEASE migrate_live_route');throw e}
  620. }
  621. recordRoute(owner: string, profile: string, sessionID: string, runtimeID: string): void {
  622. this.migrateRuntimeSession(owner,profile,sessionID,runtimeID)
  623. const now = Date.now()
  624. const summary = { id: sessionID, profile, source: 'unknown', title: '新对话', started_at: now, last_active: now }
  625. this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_synced_at,owned_at,ownership_evidence)
  626. VALUES(?,?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET runtime_id=excluded.runtime_id,
  627. last_synced_at=excluded.last_synced_at,owned_at=COALESCE(chat_sessions.owned_at,excluded.owned_at),
  628. ownership_evidence=COALESCE(chat_sessions.ownership_evidence,excluded.ownership_evidence)`)
  629. .run(owner, profile, sessionID, runtimeID, 'unknown', JSON.stringify(summary), 'stale', 0, now, now, 'route-confirmed')
  630. this.markListsStale(owner)
  631. }
  632. recordCommand(owner: string, profile: string, sessionID: string, method: string,
  633. params: Record<string, unknown>): void {
  634. const now = Date.now()
  635. const source = sessionSource(params) || 'unknown'
  636. const establishesOwnership = method === 'session.create' || method === 'session.branch'
  637. const summary = { id: sessionID, profile, source, title: '新对话', started_at: now, last_active: now }
  638. this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,source,data,sync_state,complete,last_synced_at,owned_at,ownership_evidence)
  639. VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET
  640. source=CASE WHEN excluded.source='unknown' THEN chat_sessions.source ELSE excluded.source END,
  641. sync_state=CASE WHEN chat_sessions.sync_state='gap' THEN 'gap' ELSE 'stale' END,sync_revision=chat_sessions.sync_revision+1,last_synced_at=excluded.last_synced_at,
  642. owned_at=COALESCE(chat_sessions.owned_at,excluded.owned_at),
  643. ownership_evidence=COALESCE(chat_sessions.ownership_evidence,excluded.ownership_evidence)`)
  644. .run(owner, profile, sessionID, source, JSON.stringify(summary), 'stale', 0, now,
  645. establishesOwnership ? now : null, establishesOwnership ? `command:${method}` : null)
  646. if(method==='session.create') this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,read_initialized) VALUES(?,?,?,1) ON CONFLICT(owner,profile,session_id) DO UPDATE SET read_initialized=1`).run(owner,profile,sessionID)
  647. if(method==='session.create') this.db.prepare(`UPDATE chat_sessions SET complete=1,metadata_complete=1,message_total=0,sync_state='current' WHERE owner=? AND profile=? AND session_id=? AND message_total IS NULL`).run(owner,profile,sessionID)
  648. if((method==='prompt.submit'||method==='session.steer') && params._delivery_id){
  649. const userID=`user:${params._delivery_id}`
  650. this.writeLiveMessage(owner,profile,sessionID,{id:userID,role:'user',content:params.text??params.input??'',timestamp:now/1000,status:'pending',client_message_id:String(params._delivery_id).replace(/^(web|ios):prompt:/,'')})
  651. this.db.prepare(`INSERT INTO chat_local_state(owner,profile,session_id,assistant_id) VALUES(?,?,?,NULL) ON CONFLICT(owner,profile,session_id) DO UPDATE SET assistant_id=NULL`).run(owner,profile,sessionID)
  652. }
  653. const payload = JSON.stringify(params)
  654. const seq = Number.parseInt(createHash('sha256').update(`${method}:${payload}`).digest('hex').slice(0, 12), 16)
  655. this.db.prepare(`INSERT OR IGNORE INTO chat_events(owner,profile,session_id,event_seq,event_type,payload,received_at)
  656. VALUES(?,?,?,?,?,?,?)`).run(owner, profile, sessionID, seq, `command:${method}`, payload, now)
  657. this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE owner=? AND (session_id=? OR kind='list')")
  658. .run(owner, sessionID)
  659. }
  660. fileSourceMessage(owner: string, profile: string, sessionID: string, messageID: string): Record<string, unknown> | undefined {
  661. const row = this.db.prepare('SELECT data FROM chat_messages WHERE owner=? AND profile=? AND session_id=? AND message_id=?')
  662. .get(owner, profile, sessionID, messageID)
  663. return row ? JSON.parse(String(row.data)) : undefined
  664. }
  665. markListsStale(owner: string): void {
  666. this.db.prepare("UPDATE chat_snapshots SET sync_state='stale' WHERE owner=? AND kind='list'").run(owner)
  667. }
  668. invalidateOwnedMetadata(owner: string): Array<{profile:string;session_id:string}> {
  669. return this.db.prepare(`UPDATE chat_sessions SET metadata_complete=0,sync_revision=sync_revision+1
  670. WHERE owner=? AND owned_at IS NOT NULL AND source NOT IN ('cron','ios_group','yaoyao_workspace')
  671. RETURNING profile,session_id`).all(owner) as Array<{profile:string;session_id:string}>
  672. }
  673. refreshMetadata(owner:string,profile:string,id:string,revision:number,response:UpstreamResponse,startedAt:number):boolean {
  674. const payload=parseResponse(response),summary=object(payload?.session)??payload
  675. const total=summary?.message_count??summary?.messageCount
  676. const row=this.db.prepare('SELECT metadata_complete,complete,message_total,sync_state FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
  677. .get(owner,profile,id) as {metadata_complete:number;complete:number;message_total:number;sync_state:string}|undefined
  678. if(!row||row.metadata_complete||!row.complete||total==null||Number(total)!==row.message_total||this.revision(owner,profile,id)!==revision)return false
  679. this.db.exec('SAVEPOINT metadata_refresh')
  680. try {
  681. const metadata={...summary};delete metadata.messages
  682. const headers=new Headers(response.headers);headers.delete('content-length')
  683. const metadataResponse={...response,headers,body:Buffer.from(JSON.stringify(metadata))}
  684. if(!this.putSnapshot(owner,`detail:${profile}:${id}`,'detail',profile,id,metadataResponse,false,startedAt))throw new Error('Invalid conversation metadata')
  685. // A metadata invalidation must not replace or downgrade the durable live tail.
  686. this.db.prepare('UPDATE chat_sessions SET sync_state=? WHERE owner=? AND profile=? AND session_id=?').run(row.sync_state,owner,profile,id)
  687. this.db.exec('RELEASE metadata_refresh');return true
  688. }catch(error){this.db.exec('ROLLBACK TO metadata_refresh; RELEASE metadata_refresh');throw error}
  689. }
  690. recordAuthoritativeTitle(owner: string, profile: string, sessionID: string, title: string): void {
  691. const normalized = title.trim()
  692. if (!normalized) return
  693. this.updateOwnedSessionTitle(owner, profile, sessionID, normalized, Date.now())
  694. this.db.prepare(`UPDATE chat_snapshots SET sync_state='stale'
  695. WHERE owner=? AND (session_id=? OR kind='list')`).run(owner, sessionID)
  696. }
  697. deleteSession(owner: string, profile: string, sessionID: string): void {
  698. const assets = this.db.prepare(`SELECT DISTINCT local_path FROM chat_attachments
  699. WHERE owner=? AND profile=? AND session_id=? AND local_path IS NOT NULL`)
  700. .all(owner, profile, sessionID) as Array<{ local_path: string }>
  701. this.db.exec('BEGIN IMMEDIATE')
  702. try {
  703. for (const table of ['chat_messages', 'chat_events', 'chat_attachments', 'chat_local_state', 'chat_event_receipts', 'chat_recovery_jobs', 'chat_session_aliases', 'chat_sessions']) {
  704. this.db.prepare(`DELETE FROM ${table} WHERE owner=? AND profile=? AND session_id=?`).run(owner, profile, sessionID)
  705. }
  706. this.db.prepare("DELETE FROM chat_snapshots WHERE owner=? AND ((profile=? AND session_id=?) OR kind='list')")
  707. .run(owner, profile, sessionID)
  708. this.db.exec('COMMIT')
  709. for (const asset of assets) {
  710. const referenced = this.db.prepare('SELECT 1 ok FROM chat_attachments WHERE local_path=? LIMIT 1').get(asset.local_path)
  711. if (!referenced) try { unlinkSync(asset.local_path) } catch { /* Already absent. */ }
  712. }
  713. } catch (error) { this.db.exec('ROLLBACK'); throw error }
  714. }
  715. attachment(owner: string, sourcePath: string): { localPath: string; mimeType?: string } | undefined {
  716. const row = this.db.prepare(`SELECT local_path,mime_type FROM chat_attachments
  717. WHERE owner=? AND source_path=? AND state='cached' ORDER BY updated_at DESC LIMIT 1`).get(owner, sourcePath) as Record<string, unknown> | undefined
  718. const localPath = row?.local_path ? String(row.local_path) : ''
  719. return localPath && existsSync(localPath) ? { localPath, ...(row?.mime_type ? { mimeType: String(row.mime_type) } : {}) } : undefined
  720. }
  721. knowsAttachment(owner: string, sourcePath: string): boolean {
  722. return Boolean(this.db.prepare('SELECT 1 ok FROM chat_attachments WHERE owner=? AND source_path=? LIMIT 1').get(owner, sourcePath))
  723. }
  724. ownsSession(owner: string, profile: string, sessionID: string): boolean {
  725. sessionID=this.canonicalSessionID(owner,profile,sessionID)
  726. return Boolean(this.db.prepare(
  727. 'SELECT 1 ok FROM chat_sessions WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL',
  728. ).get(owner, profile, sessionID))
  729. }
  730. ownedSessionMetadata(owner: string, profile: string, sessionID: string): {
  731. owned: boolean
  732. authoritativeTitle?: string
  733. } {
  734. const row = this.db.prepare(`SELECT authoritative_title FROM chat_sessions
  735. WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`)
  736. .get(owner, profile, sessionID) as { authoritative_title?: string | null } | undefined
  737. const local=this.db.prepare('SELECT title FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,sessionID) as {title?:string}|undefined
  738. const authoritativeTitle = String(local?.title ?? row?.authoritative_title ?? '').trim()
  739. return {
  740. owned: Boolean(row),
  741. ...(authoritativeTitle ? { authoritativeTitle } : {}),
  742. }
  743. }
  744. mergeOwnedSessionsIntoList(
  745. owner: string,
  746. fallbackProfile: string,
  747. response: UpstreamResponse,
  748. page: { offset?: number; limit?: number; archived?: string } = {},
  749. ): UpstreamResponse {
  750. const payload = parseResponse(response)
  751. if (!payload) return response
  752. const collectionKey = Array.isArray(payload.items)
  753. ? 'items'
  754. : Array.isArray(payload.sessions) ? 'sessions' : undefined
  755. if (!collectionKey) return response
  756. const rows = (fallbackProfile
  757. ? this.db.prepare(`SELECT profile,session_id,source,data,authoritative_title,last_synced_at FROM chat_sessions
  758. WHERE owner=? AND profile=? AND owned_at IS NOT NULL`)
  759. .all(owner, fallbackProfile)
  760. : this.db.prepare(`SELECT profile,session_id,source,data,authoritative_title,last_synced_at FROM chat_sessions
  761. WHERE owner=? AND owned_at IS NOT NULL`).all(owner)) as Array<{
  762. profile: string
  763. session_id: string
  764. source: string
  765. data: string
  766. authoritative_title: string | null
  767. last_synced_at: number
  768. }>
  769. const owned = new Map(rows.map(row => [
  770. `${row.profile}\u0000${row.session_id}`,
  771. row,
  772. ]))
  773. const merged = new Map<string, Record<string, unknown>>()
  774. for (const [key, row] of owned) {
  775. let stored: Record<string, unknown> = {}
  776. try { stored = object(JSON.parse(row.data)) ?? {} } catch { /* Ignore damaged display metadata. */ }
  777. const storedSource = sessionSource(stored)
  778. merged.set(key, {
  779. ...stored,
  780. id: row.session_id,
  781. profile: row.profile,
  782. source: storedSource && storedSource !== 'unknown' ? storedSource : row.source,
  783. ...(row.authoritative_title?.trim() ? { title: row.authoritative_title.trim() } : {}),
  784. _yaoyao_registry_activity: row.last_synced_at,
  785. owned: true,
  786. })
  787. }
  788. for (const value of payload[collectionKey] as unknown[]) {
  789. const session = object(value)
  790. if (!session) continue
  791. const id = sessionIDOf(session)
  792. const profile = profileOf(session, fallbackProfile) || 'default'
  793. if (!id) continue
  794. const key = `${profile}\u0000${id}`
  795. const row = owned.get(key)
  796. if (row) {
  797. const title = row.authoritative_title?.trim()
  798. merged.set(key, {
  799. ...mergeSessionMetadata(merged.get(key) ?? {}, session),
  800. ...(title ? { title } : {}),
  801. _yaoyao_registry_activity: row.last_synced_at,
  802. owned: true,
  803. })
  804. }
  805. }
  806. const activity = (session: Record<string, unknown>): number =>
  807. firstTimestamp(session, ACTIVITY_TIME_KEYS) ?? firstTimestamp(session, START_TIME_KEYS) ?? 0
  808. const archived = (session: Record<string, unknown>): boolean => bool(
  809. session.is_archived ?? session.isArchived ?? session.archived,
  810. )
  811. const pinned = (session: Record<string, unknown>): boolean => bool(
  812. session.is_pinned ?? session.isPinned ?? session.pinned,
  813. )
  814. const archivedMode = page.archived ?? 'exclude'
  815. const allSessions = [...merged.values()]
  816. .filter(session => archivedMode === 'include'
  817. || (archivedMode === 'only' ? archived(session) : !archived(session)))
  818. .sort((left, right) => Number(pinned(right)) - Number(pinned(left))
  819. || activity(right) - activity(left))
  820. const offset = Math.max(0, Math.trunc(page.offset ?? 0))
  821. const limit = Math.max(1, Math.min(500, Math.trunc(page.limit ?? 100)))
  822. const sessions = allSessions.slice(offset, offset + limit).map((session) => {
  823. const publicSession = mergeSessionMetadata({}, session)
  824. delete publicSession._yaoyao_registry_activity
  825. return publicSession
  826. })
  827. const body = Buffer.from(JSON.stringify({
  828. ...payload,
  829. [collectionKey]: sessions,
  830. total: allSessions.length,
  831. offset,
  832. limit,
  833. }))
  834. const headers = new Headers(response.headers)
  835. headers.delete('content-length')
  836. return { ...response, headers, body }
  837. }
  838. excludeOwnedSessionsFromList(
  839. owner: string,
  840. fallbackProfile: string,
  841. response: UpstreamResponse,
  842. page: { offset?: number; limit?: number } = {},
  843. ): UpstreamResponse {
  844. const payload = parseResponse(response)
  845. if (!payload) return response
  846. const collectionKey = Array.isArray(payload.items)
  847. ? 'items'
  848. : Array.isArray(payload.sessions) ? 'sessions' : undefined
  849. if (!collectionKey) return response
  850. const allSessions = (payload[collectionKey] as unknown[]).filter((value) => {
  851. const session = object(value)
  852. if (!session) return true
  853. const id = sessionIDOf(session)
  854. const profile = profileOf(session, fallbackProfile) || 'default'
  855. return !id || !this.ownsSession(owner, profile, id)
  856. })
  857. const offset = Math.max(0, Math.trunc(page.offset ?? 0))
  858. const limit = Math.max(1, Math.min(500, Math.trunc(page.limit ?? 100)))
  859. const sessions = allSessions.slice(offset, offset + limit)
  860. const headers = new Headers(response.headers)
  861. headers.delete('content-length')
  862. return {
  863. ...response,
  864. headers,
  865. body: Buffer.from(JSON.stringify({
  866. ...payload,
  867. [collectionKey]: sessions,
  868. total: allSessions.length,
  869. offset,
  870. limit,
  871. })),
  872. }
  873. }
  874. markSessionOwnership(
  875. owner: string,
  876. fallbackProfile: string,
  877. sessionID: string,
  878. response: UpstreamResponse,
  879. ): UpstreamResponse {
  880. const payload = parseResponse(response)
  881. if (!payload) return response
  882. const session = object(payload.session)
  883. const candidate = session ?? payload
  884. const id = sessionIDOf(candidate) || sessionID
  885. const profile = profileOf(candidate, fallbackProfile) || fallbackProfile || 'default'
  886. const row = this.db.prepare(`SELECT authoritative_title FROM chat_sessions
  887. WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`).get(owner, profile, id) as { authoritative_title?: string | null } | undefined
  888. const owned = Boolean(row)
  889. const local=this.db.prepare('SELECT title FROM chat_local_state WHERE owner=? AND profile=? AND session_id=?').get(owner,profile,id) as {title?:string}|undefined
  890. const title = String(local?.title ?? row?.authoritative_title ?? '').trim()
  891. const body = session
  892. ? Buffer.from(JSON.stringify({
  893. ...payload,
  894. session: { ...session, ...(title ? { title } : {}), owned },
  895. owned,
  896. }))
  897. : Buffer.from(JSON.stringify({ ...payload, ...(title ? { title } : {}), owned }))
  898. const headers = new Headers(response.headers)
  899. headers.delete('content-length')
  900. return { ...response, headers, body }
  901. }
  902. markOwnedSearchResults(
  903. owner: string,
  904. fallbackProfile: string,
  905. response: UpstreamResponse,
  906. view?: 'chat' | 'history',
  907. limit = 100,
  908. ): UpstreamResponse {
  909. const payload = parseResponse(response)
  910. if (!payload || !Array.isArray(payload.results)) return response
  911. const marked = payload.results.map((value) => {
  912. const session = object(value)
  913. if (!session) return value
  914. const id = sessionIDOf(session)
  915. const profile = profileOf(session, fallbackProfile) || fallbackProfile || 'default'
  916. const metadata = id
  917. ? this.ownedSessionMetadata(owner, profile, id)
  918. : { owned: false }
  919. return {
  920. ...session,
  921. ...(metadata.authoritativeTitle ? { title: metadata.authoritativeTitle } : {}),
  922. owned: metadata.owned,
  923. }
  924. })
  925. const projected = marked.filter((value) => {
  926. if (!view) return true
  927. const session = object(value)
  928. if (!session) return false
  929. return view === 'chat' ? session.owned === true : session.owned !== true
  930. })
  931. const results = projected.slice(0, Math.max(1, Math.min(100, Math.trunc(limit))))
  932. const headers = new Headers(response.headers)
  933. headers.delete('content-length')
  934. return {
  935. ...response,
  936. headers,
  937. body: Buffer.from(JSON.stringify({ ...payload, results, total: projected.length })),
  938. }
  939. }
  940. storeAttachment(owner: string, sourcePath: string, response: UpstreamResponse): string | undefined {
  941. if (response.status !== 200 || !response.body.length) return undefined
  942. const sha256 = createHash('sha256').update(response.body).digest('hex')
  943. const directory = join(this.assetsRoot, sha256.slice(0, 2))
  944. mkdirSync(directory, { recursive: true, mode: 0o700 })
  945. const target = join(directory, sha256)
  946. if (!existsSync(target)) {
  947. const temporary = `${target}.${process.pid}.tmp`
  948. writeFileSync(temporary, response.body, { mode: 0o600 })
  949. renameSync(temporary, target)
  950. }
  951. const mimeType = response.headers.get('content-type')?.split(';', 1)[0]
  952. this.db.prepare(`UPDATE chat_attachments SET sha256=?,mime_type=?,size=?,local_path=?,state='cached',updated_at=?
  953. WHERE owner=? AND source_path=?`).run(sha256, mimeType ?? null, response.body.length, target, Date.now(), owner, sourcePath)
  954. return target
  955. }
  956. assetStream(path: string): { stream: ReturnType<typeof createReadStream>; size: number } {
  957. return { stream: createReadStream(path), size: statSync(path).size }
  958. }
  959. private payloadBelongsToOwnedChat(owner: string, profile: string, sessionID: string | undefined,
  960. payload: Record<string, unknown>): boolean {
  961. const session = object(payload.session) ?? (sessionID ? payload : undefined)
  962. if (session) {
  963. const id = sessionIDOf(session) || sessionID || ''
  964. const sessionProfile = profileOf(session, profile) || profile || 'default'
  965. if (id && this.ownsSession(owner, sessionProfile, id)) return true
  966. }
  967. const sessions = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.sessions) ? payload.sessions : []
  968. if (sessions.some(value => {
  969. const candidate = object(value)
  970. if (!candidate) return false
  971. const id = sessionIDOf(candidate)
  972. const sessionProfile = profileOf(candidate, profile) || profile || 'default'
  973. return Boolean(id && this.ownsSession(owner, sessionProfile, id))
  974. })) return true
  975. return Boolean(sessionID && this.ownsSession(owner, profile || 'default', sessionID))
  976. }
  977. private ingestPayload(owner: string, fallbackProfile: string, sessionID: string | undefined,
  978. payload: Record<string, unknown>, now: number, kind: string, requestStartedAt: number): void {
  979. const candidates: Record<string, unknown>[] = []
  980. const direct = object(payload.session)
  981. if (direct) candidates.push(direct)
  982. const listed = Array.isArray(payload.items) ? payload.items : Array.isArray(payload.sessions) ? payload.sessions : []
  983. for (const value of listed) if (object(value)) candidates.push(object(value)!)
  984. if (sessionID && !direct && (sessionIDOf(payload) || sessionSource(payload) || typeof payload.title === 'string')) {
  985. candidates.push(payload)
  986. }
  987. for (const session of candidates) {
  988. const id = sessionIDOf(session) || sessionID || ''
  989. if (!id) continue
  990. const profile = profileOf(session, fallbackProfile) || fallbackProfile || 'default'
  991. const registered = this.ownsSession(owner, profile, id)
  992. const source = sessionSource(session)
  993. if (!registered) continue
  994. const titleRow = this.db.prepare(`SELECT data,authoritative_title,authoritative_title_at FROM chat_sessions
  995. WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, id) as {
  996. data: string; authoritative_title?: string | null; authoritative_title_at?: number
  997. } | undefined
  998. const authoritativeTitle = String(titleRow?.authoritative_title ?? '').trim()
  999. const authoritativeTitleAt = Number(titleRow?.authoritative_title_at ?? 0)
  1000. const incomingTitle = sessionTitle(session)
  1001. const preservesAuthoritativeTitle = Boolean(authoritativeTitle)
  1002. && (kind !== 'detail' || isPlaceholderTitle(incomingTitle)
  1003. || requestStartedAt <= authoritativeTitleAt)
  1004. let previous: Record<string, unknown> = {}
  1005. try { previous = object(JSON.parse(titleRow?.data ?? '{}')) ?? {} } catch { /* Recover from incoming metadata. */ }
  1006. const storedSession = mergeSessionMetadata(previous, session)
  1007. if (preservesAuthoritativeTitle) storedSession.title = authoritativeTitle
  1008. const metadataComplete = kind !== 'messages' || direct ? 1 : 0
  1009. this.db.prepare(`INSERT INTO chat_sessions(owner,profile,session_id,runtime_id,source,data,sync_state,complete,last_synced_at,metadata_complete)
  1010. VALUES(?,?,?,?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET data=excluded.data,
  1011. metadata_complete=MAX(chat_sessions.metadata_complete,excluded.metadata_complete),
  1012. source=CASE WHEN excluded.source='unknown' THEN chat_sessions.source ELSE excluded.source END,
  1013. sync_state='current',last_synced_at=excluded.last_synced_at`)
  1014. .run(owner, profile, id, null, source || 'unknown', JSON.stringify(storedSession), 'current', 0, now, metadataComplete)
  1015. const acceptedTitle = sessionTitle(storedSession)
  1016. if (acceptedTitle && !isPlaceholderTitle(acceptedTitle)
  1017. && (!authoritativeTitle || kind === 'detail')) {
  1018. this.db.prepare(`UPDATE chat_sessions SET authoritative_title=?,authoritative_title_at=?
  1019. WHERE owner=? AND profile=? AND session_id=?`).run(
  1020. acceptedTitle,
  1021. Math.max(requestStartedAt, authoritativeTitleAt),
  1022. owner,
  1023. profile,
  1024. id,
  1025. )
  1026. }
  1027. }
  1028. const messages = Array.isArray(payload.messages) ? payload.messages.flatMap(value => object(value) ? [object(value)!] : []) : []
  1029. if (!Array.isArray(payload.messages) || !sessionID) return
  1030. const profile = fallbackProfile || profileOf(direct ?? {}, 'default') || 'default'
  1031. const pagination = object(payload.pagination) ?? {}
  1032. const offset = Math.max(0, Number(pagination.offset ?? payload.offset ?? 0) || 0)
  1033. const storedDetail = this.localDetail(owner, profile, sessionID)
  1034. const storedSummary = storedDetail ? parseResponse(storedDetail.response) ?? {} : {}
  1035. const total = Math.max(offset + messages.length,
  1036. Number(pagination.total ?? payload.total ?? storedSummary.message_count ?? storedSummary.messageCount ?? 0) || 0)
  1037. const start = Math.max(0, total - offset - messages.length)
  1038. messages.forEach((message, index) => {
  1039. const data = JSON.stringify(message)
  1040. this.db.prepare(`INSERT INTO chat_messages(owner,profile,session_id,message_id,position,data,content_hash)
  1041. VALUES(?,?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,message_id) DO UPDATE SET position=excluded.position,
  1042. data=excluded.data,content_hash=excluded.content_hash
  1043. WHERE chat_messages.content_hash<>excluded.content_hash OR chat_messages.position<>excluded.position`)
  1044. .run(owner, profile, sessionID, messageID(message, String(start + index)), start + index, data,
  1045. createHash('sha256').update(data).digest('hex'))
  1046. for (const sourcePath of referencedPaths(message)) {
  1047. this.db.prepare(`INSERT INTO chat_attachments(owner,profile,session_id,source_path,state,updated_at)
  1048. VALUES(?,?,?,?,?,?) ON CONFLICT(owner,profile,session_id,source_path) DO UPDATE SET updated_at=excluded.updated_at`)
  1049. .run(owner, profile, sessionID, sourcePath, 'pending', now)
  1050. }
  1051. })
  1052. const coverage = this.db.prepare(`SELECT COUNT(*) count, COUNT(DISTINCT position) positions, MIN(position) first, MAX(position) last
  1053. FROM chat_messages WHERE owner=? AND profile=? AND session_id=?`).get(owner, profile, sessionID) as Record<string, number>
  1054. const complete = total === 0 ? coverage.count === 0
  1055. : coverage.count === total && coverage.positions === total && coverage.first === 0 && coverage.last === total - 1
  1056. const row = this.db.prepare('SELECT data FROM chat_sessions WHERE owner=? AND profile=? AND session_id=?')
  1057. .get(owner, profile, sessionID) as { data: string }
  1058. const summary = mergeSessionMetadata({}, object(JSON.parse(row.data)) ?? {})
  1059. const bounds = messageTimeBounds(messages)
  1060. if (!firstTimestamp(summary, START_TIME_KEYS) && bounds.first !== undefined) summary.started_at = bounds.first
  1061. if (bounds.last !== undefined) {
  1062. summary.last_active = Math.max(firstTimestamp(summary, ACTIVITY_TIME_KEYS) ?? 0, bounds.last)
  1063. }
  1064. summary.message_count = total
  1065. this.db.prepare('UPDATE chat_sessions SET data=? WHERE owner=? AND profile=? AND session_id=?')
  1066. .run(JSON.stringify(summary), owner, profile, sessionID)
  1067. this.db.prepare(`UPDATE chat_sessions SET complete=?,message_total=?,sync_state='current',last_synced_at=?
  1068. WHERE owner=? AND profile=? AND session_id=?`).run(complete ? 1 : 0, total, now, owner, profile, sessionID)
  1069. }
  1070. private updateOwnedSessionTitle(owner: string, profile: string, sessionID: string, title: string, now: number): void {
  1071. const row = this.db.prepare(`SELECT source,data FROM chat_sessions
  1072. WHERE owner=? AND profile=? AND session_id=? AND owned_at IS NOT NULL`).get(owner, profile, sessionID) as Record<string, unknown> | undefined
  1073. if (!row) return
  1074. let summary: Record<string, unknown> = {}
  1075. try { summary = object(JSON.parse(String(row.data))) ?? {} } catch { /* Rebuild damaged display metadata below. */ }
  1076. const storedSource = sessionSource(summary)
  1077. const source = storedSource && storedSource !== 'unknown'
  1078. ? storedSource
  1079. : String(row.source || 'unknown')
  1080. this.db.prepare(`UPDATE chat_sessions SET data=?,authoritative_title=?,authoritative_title_at=?,sync_state='stale',last_synced_at=?
  1081. WHERE owner=? AND profile=? AND session_id=?`).run(JSON.stringify({
  1082. ...summary,
  1083. id: sessionID,
  1084. profile,
  1085. source,
  1086. title,
  1087. }), title, now, now, owner, profile, sessionID)
  1088. }
  1089. }
  1090. export class ChatCacheCoordinator {
  1091. private reconciling = new Map<string, Promise<void>>()
  1092. onSynchronized: (owner: string, profile: string, sessionID: string) => void = () => {}
  1093. constructor(readonly store: ChatCacheStore, readonly upstream: UpstreamServiceSession,
  1094. readonly mode: ChatCacheMode = 'prefer-local') {
  1095. const timer=setTimeout(()=>{
  1096. this.retryTimers.delete(timer)
  1097. if(this.store.isClosed||this.stopped)return
  1098. void this.restoreReadPositions()
  1099. for(const row of this.store.db.prepare('SELECT * FROM chat_recovery_jobs').all() as any[])this.schedule(row.owner,row.profile,row.session_id,!!row.force)
  1100. },0);timer.unref();this.retryTimers.add(timer)
  1101. }
  1102. readonly diagnostics = {localReads:0, recoveryAttempts:0, recoveryFailures:0, recoveryCompleted:0}
  1103. private async restoreReadPositions():Promise<void>{
  1104. if(this.stopped||this.store.isClosed)return
  1105. const scopes=this.store.db.prepare('SELECT DISTINCT owner,profile FROM chat_local_state WHERE read_initialized=0').all() as {owner:string;profile:string}[]
  1106. let failed=false
  1107. for(let i=0;i<scopes.length;i+=2)await Promise.all(scopes.slice(i,i+2).map(async({owner,profile})=>{
  1108. if(this.stopped||this.store.isClosed)return
  1109. try{
  1110. const response=await this.upstream.request('/api/session-unread',{search:new URLSearchParams({profile})})
  1111. if(this.stopped||this.store.isClosed)return
  1112. if(response.status>=500)throw new Error('Read-position import unavailable')
  1113. const payload=parseResponse(response),rows=Array.isArray(payload?.sessions)?payload.sessions:[]
  1114. this.store.db.exec('SAVEPOINT read_position_import')
  1115. try{
  1116. for(const raw of rows){const r=object(raw);if(!r)continue;const id=String(r.session_id??r.sessionId??'')
  1117. const count=Math.max(0,Number(r.read_message_count??r.readMessageCount??0)||0)
  1118. this.store.db.prepare('UPDATE chat_local_state SET read_count=?,read_initialized=1 WHERE owner=? AND profile=? AND session_id=? AND read_initialized=0').run(count,owner,profile,id)
  1119. }
  1120. this.store.db.prepare(`UPDATE chat_local_state SET read_count=COALESCE((SELECT message_total FROM chat_sessions s WHERE s.owner=chat_local_state.owner AND s.profile=chat_local_state.profile AND s.session_id=chat_local_state.session_id),0),read_initialized=1 WHERE owner=? AND profile=? AND read_initialized=0`).run(owner,profile)
  1121. this.store.db.exec('RELEASE read_position_import')
  1122. }catch(e){this.store.db.exec('ROLLBACK TO read_position_import; RELEASE read_position_import');throw e}
  1123. }catch{failed=true}
  1124. }))
  1125. if(failed&&!this.stopped&&!this.store.isClosed){const timer=setTimeout(()=>{this.retryTimers.delete(timer);void this.restoreReadPositions()},30_000);timer.unref();this.retryTimers.add(timer)}
  1126. }
  1127. private jobs = new Map<string,{owner:string;profile:string;id:string;force:boolean;attempt:number}>()
  1128. private activeJobs = new Set<string>()
  1129. private retryTimers = new Set<ReturnType<typeof setTimeout>>()
  1130. private stopped = false
  1131. close(): void {this.stopped=true;for(const timer of this.retryTimers)clearTimeout(timer);this.retryTimers.clear();this.jobs.clear()}
  1132. schedule(owner:string,profile:string,id:string,force=false): void {
  1133. if(this.stopped||this.store.isClosed||!this.store.ownsSession(owner,profile,id))return
  1134. const key=JSON.stringify([owner,profile,id]),previous=this.jobs.get(key)
  1135. if(previous){previous.force ||= force;if(force)this.store.db.prepare('UPDATE chat_recovery_jobs SET force=1 WHERE owner=? AND profile=? AND session_id=?').run(owner,profile,id);return}
  1136. this.store.db.prepare('INSERT INTO chat_recovery_jobs VALUES(?,?,?,?) ON CONFLICT(owner,profile,session_id) DO UPDATE SET force=MAX(force,excluded.force)').run(owner,profile,id,force?1:0)
  1137. this.jobs.set(key,{owner,profile,id,force,attempt:0})
  1138. const timer=setTimeout(()=>{this.retryTimers.delete(timer);this.drain()},0);timer.unref();this.retryTimers.add(timer)
  1139. }
  1140. private drain(): void {
  1141. if(this.stopped||this.store.isClosed)return
  1142. for(const [key,job] of this.jobs){
  1143. if(this.activeJobs.size>=2)break
  1144. if(this.activeJobs.has(key)||job.attempt<0)continue
  1145. this.activeJobs.add(key)
  1146. this.diagnostics.recoveryAttempts++
  1147. const force=job.force;job.force=false
  1148. void this.reconcile(job.owner,job.profile,job.id,force).then(()=>{
  1149. if(this.stopped||this.store.isClosed)return
  1150. if(job.force){job.attempt=0;return}
  1151. this.diagnostics.recoveryCompleted++
  1152. this.jobs.delete(key)
  1153. this.store.db.prepare('DELETE FROM chat_recovery_jobs WHERE owner=? AND profile=? AND session_id=?').run(job.owner,job.profile,job.id)
  1154. }).catch(()=>{
  1155. if(this.stopped||this.store.isClosed)return
  1156. this.diagnostics.recoveryFailures++
  1157. job.force ||= force
  1158. const attempt=Math.abs(job.attempt)+1;job.attempt=-attempt
  1159. const timer=setTimeout(()=>{this.retryTimers.delete(timer);job.attempt=attempt;this.drain()},Math.min(30_000,1000*2**Math.min(attempt-1,5)))
  1160. timer.unref();this.retryTimers.add(timer)
  1161. }).finally(()=>{this.activeJobs.delete(key);this.drain()})
  1162. }
  1163. }
  1164. readLocal(owner:string,kind:'list'|'detail'|'messages',profile:string,id:string|undefined,
  1165. page:{offset?:number;limit?:number;archived?:string},force=false): {response:UpstreamResponse;source:ChatCacheSource;state:ChatCacheState} {
  1166. this.diagnostics.localReads++
  1167. if(id)id=this.store.canonicalSessionID(owner,profile,id)
  1168. if(kind==='list'){
  1169. for(const row of this.store.missingSessions(owner,profile)) this.schedule(owner,row.profile,row.session_id,force)
  1170. return {response:this.store.localList(owner,profile,page),source:'local',state:this.store.needsListMetadata(owner,profile)?'syncing':'current'}
  1171. }
  1172. this.store.requireOwned(owner,profile,id!)
  1173. const local=kind==='detail'?this.store.localDetail(owner,profile,id!):this.store.messagePage(owner,profile,id!,page.offset??0,page.limit??100)
  1174. if(force||!local||local.state==='gap')this.schedule(owner,profile,id!,force)
  1175. if(!local)throw new HttpError(409,'历史正在后台补齐,请稍后重试','CHAT_HISTORY_SYNC_PENDING')
  1176. return {response:local.response,source:'local',state:this.jobs.has(JSON.stringify([owner,profile,id]))?'syncing':local.state}
  1177. }
  1178. async read(owner: string, key: string, kind: string, profile: string, sessionID: string | undefined,
  1179. load: () => Promise<UpstreamResponse>, ownedList = false,
  1180. listPage: { offset?: number; limit?: number; archived?: string } = {}): Promise<{ response: UpstreamResponse; source: ChatCacheSource; state: ChatCacheState }> {
  1181. if (this.mode === 'upstream-only') {
  1182. const upstreamResponse = await load()
  1183. return {
  1184. response: kind === 'list' && ownedList
  1185. ? this.store.mergeOwnedSessionsIntoList(owner, profile, upstreamResponse, listPage)
  1186. : upstreamResponse,
  1187. source: 'upstream',
  1188. state: 'current',
  1189. }
  1190. }
  1191. if (this.mode === 'prefer-local' && kind === 'list' && ownedList && !this.store.needsListMetadata(owner, profile)) {
  1192. return { response: this.store.localList(owner, profile, listPage), source: 'local', state: 'current' }
  1193. }
  1194. const local = kind === 'list' && ownedList && this.store.needsListMetadata(owner, profile) ? undefined : kind === 'detail' && sessionID
  1195. ? this.store.localDetail(owner, profile, sessionID) ?? this.store.snapshot(owner, key)
  1196. : this.store.snapshot(owner, key)
  1197. const projectedLocal = local && kind === 'list' && ownedList
  1198. ? {
  1199. ...local,
  1200. response: this.store.mergeOwnedSessionsIntoList(owner, profile, local.response, listPage),
  1201. }
  1202. : local
  1203. if (this.mode === 'prefer-local' && local) {
  1204. return { response: projectedLocal!.response, source: 'local', state: local.state }
  1205. }
  1206. try {
  1207. const requestStartedAt = Date.now()
  1208. const upstreamResponse = await load()
  1209. if (this.mode === 'prefer-local' && local && upstreamResponse.status >= 500) {
  1210. return { response: projectedLocal!.response, source: 'local', state: 'stale' }
  1211. }
  1212. const response = kind === 'list' && ownedList
  1213. ? this.store.mergeOwnedSessionsIntoList(
  1214. owner,
  1215. profile,
  1216. upstreamResponse,
  1217. listPage,
  1218. )
  1219. : upstreamResponse
  1220. this.store.putSnapshot(owner, key, kind, profile, sessionID, response, ownedList, requestStartedAt, upstreamResponse)
  1221. return { response, source: 'upstream', state: 'current' }
  1222. } catch (error) {
  1223. if (this.mode === 'prefer-local' && local) return { response: projectedLocal!.response, source: 'local', state: 'stale' }
  1224. throw error
  1225. }
  1226. }
  1227. async messages(owner: string, key: string, profile: string, sessionID: string, offset: number, limit: number,
  1228. load: () => Promise<UpstreamResponse>): Promise<{ response: UpstreamResponse; source: ChatCacheSource; state: ChatCacheState }> {
  1229. if (this.mode === 'prefer-local') {
  1230. // A completion may still be committing its authoritative tail. Join it for
  1231. // the latest page; older, already stored pages never wait for the network.
  1232. if (offset === 0) await this.reconciling.get(JSON.stringify([owner, profile, sessionID]))?.catch(() => {})
  1233. const page = this.store.messagePage(owner, profile, sessionID, offset, limit)
  1234. if (page) return { response: page.response, source: 'local', state: page.state }
  1235. }
  1236. return this.read(owner, key, 'messages', profile, sessionID, load)
  1237. }
  1238. observe(owner: string, profile: string, sessionID: string, frame: Record<string, unknown>): void {
  1239. if (!this.store.recordEvent(owner, profile, sessionID, frame)) return
  1240. if (String(frame.type).includes('reset') || this.store.localDetail(owner,profile,sessionID)?.state==='gap'
  1241. || (['message.complete','run.completed'].includes(String(frame.type)) && this.store.localDetail(owner,profile,sessionID)?.state!=='current')) {
  1242. this.schedule(owner, profile, sessionID)
  1243. }
  1244. }
  1245. observeGlobal(owner: string, type: string, upstreamInvalidation=false): void {
  1246. if (type !== 'sessions.changed' || this.stopped || this.store.isClosed) return
  1247. this.store.markListsStale(owner)
  1248. if(upstreamInvalidation)for(const row of this.store.invalidateOwnedMetadata(owner))this.schedule(owner,row.profile,row.session_id)
  1249. }
  1250. command(owner: string, profile: string, sessionID: string, method: string,
  1251. params: Record<string, unknown>): void {
  1252. this.store.recordCommand(owner, profile, sessionID, method, params)
  1253. }
  1254. route(owner: string, profile: string, sessionID: string, runtimeID: string): void {
  1255. this.store.recordRoute(owner, profile, sessionID, runtimeID)
  1256. }
  1257. async reconcile(owner: string, profile: string, sessionID: string, force = false): Promise<void> {
  1258. if(this.store.isClosed)return
  1259. sessionID=this.store.canonicalSessionID(owner,profile,sessionID)
  1260. if (this.stopped || this.store.isClosed || !this.store.ownsSession(owner, profile, sessionID)) return
  1261. const key = JSON.stringify([owner, profile, sessionID])
  1262. const pending = this.reconciling.get(key)
  1263. if (pending) {
  1264. await pending.catch(() => {})
  1265. if (force || this.store.localDetail(owner, profile, sessionID)?.state !== 'current') {
  1266. return this.reconcile(owner, profile, sessionID, force)
  1267. }
  1268. return
  1269. }
  1270. const task = (async () => {
  1271. const revision = this.store.revision(owner, profile, sessionID)
  1272. const previous = this.store.messagePage(owner, profile, sessionID, 0, 1)
  1273. const previousTotal = previous ? Number(object(parseResponse(previous.response)?.pagination)?.total ?? 0) : 0
  1274. const detailPath = `/api/sessions/${encodeURIComponent(sessionID)}`
  1275. const detailStartedAt = Date.now()
  1276. const detail = await this.upstream.request(detailPath, { search: new URLSearchParams({ profile }), cache: 'reload' })
  1277. if (this.stopped || this.store.isClosed) return
  1278. if (detail.status !== 200) throw new Error('Unable to synchronize conversation metadata')
  1279. if(!force&&this.store.refreshMetadata(owner,profile,sessionID,revision,detail,detailStartedAt)) {
  1280. this.onSynchronized(owner,profile,sessionID)
  1281. return
  1282. }
  1283. const detailPayload = parseResponse(detail) ?? {}
  1284. const detailSummary = object(detailPayload.session) ?? detailPayload
  1285. const summaryTotal = Math.max(0, Number(detailSummary.message_count ?? detailSummary.messageCount ?? previousTotal) || 0)
  1286. const pages = [{ key: `detail:${profile}:${sessionID}`, kind: 'detail', response: detail, startedAt: detailStartedAt, offset: 0 }]
  1287. let offset = 0
  1288. let done = false
  1289. let expectedTotal: number | undefined
  1290. let resolvedTotal = summaryTotal
  1291. // Stop as soon as the authoritative tail overlaps durable messages. Only
  1292. // explicit refresh (or uncached history) walks all the way to the beginning.
  1293. for (let page = 0; page < 1_000; page++) {
  1294. const search = new URLSearchParams({ profile, offset: String(offset), limit: '100', order: 'latest', include_compacted: 'true' })
  1295. const startedAt = Date.now()
  1296. const response = await this.upstream.request(`${detailPath}/messages`, { search, cache: 'reload' })
  1297. if (this.stopped || this.store.isClosed) return
  1298. const payload = parseResponse(response)
  1299. if (response.status !== 200 || !Array.isArray(payload?.messages)) throw new Error('Unable to synchronize conversation messages')
  1300. const messages = payload.messages.flatMap(value => object(value) ? [object(value)!] : [])
  1301. const pagination = object(payload.pagination) ?? {}
  1302. const explicitTotal = pagination.total ?? payload.total
  1303. const total = Math.max(offset + messages.length, Number(explicitTotal ?? summaryTotal) || 0)
  1304. if (!force && total < previousTotal) throw new Error('Stored history changed; explicit refresh is required')
  1305. if (explicitTotal !== undefined) {
  1306. if (expectedTotal !== undefined && expectedTotal !== total) throw new Error('Conversation changed during synchronization')
  1307. expectedTotal = total
  1308. }
  1309. const anchors = !force ? messages.map((message, index) =>
  1310. this.store.hasMessage(owner, profile, sessionID, message, total - offset - messages.length + index)) : []
  1311. const overlap = anchors.some(Boolean)
  1312. pages.push({ key: `messages:${profile}:${sessionID}:${offset}:100`, kind: 'messages', response, startedAt, offset })
  1313. const more = pagination.hasMore ?? pagination.has_more ?? payload.hasMore ?? payload.has_more
  1314. const hasMore = more === undefined ? messages.length >= 100 : bool(more)
  1315. if (overlap || !hasMore) {
  1316. if (!overlap && expectedTotal !== undefined && expectedTotal !== offset + messages.length) throw new Error('Conversation pagination ended before its declared total')
  1317. resolvedTotal = overlap ? total : offset + messages.length
  1318. done = true
  1319. break
  1320. }
  1321. if (!messages.length) break
  1322. offset += messages.length
  1323. }
  1324. if (!done) throw new Error('Conversation synchronization is incomplete')
  1325. // Newer Hermes omits total/has_more. Once the end is known, project the
  1326. // same verified total onto every page before assigning absolute positions.
  1327. for (let index = 0; index < pages.length; index++) {
  1328. const entry = pages[index]!
  1329. const payload = parseResponse(entry.response)!
  1330. if (entry.kind === 'detail') {
  1331. const summary = object(payload.session) ?? payload
  1332. summary.message_count = resolvedTotal
  1333. } else {
  1334. const pagination = object(payload.pagination) ?? {}
  1335. const pageOffset = entry.offset
  1336. payload.pagination = { ...pagination, total: resolvedTotal, offset: pageOffset,
  1337. has_more: pageOffset + (payload.messages as unknown[]).length < resolvedTotal }
  1338. }
  1339. const headers = new Headers(entry.response.headers)
  1340. headers.delete('content-length')
  1341. entry.response = { ...entry.response, headers, body: Buffer.from(JSON.stringify(payload)) }
  1342. }
  1343. if (!this.store.applySync(owner, profile, sessionID, revision, pages, force)) {
  1344. // Preserve the invalidation when a newer event arrived during the read.
  1345. // Its completion joins this flight and schedules the next tail read.
  1346. throw new Error('Conversation changed during refresh; retry after the reply completes')
  1347. } else {
  1348. this.onSynchronized(owner, profile, sessionID)
  1349. }
  1350. })().finally(() => { if (this.reconciling.get(key) === task) this.reconciling.delete(key) })
  1351. this.reconciling.set(key, task)
  1352. return task
  1353. }
  1354. async cacheAttachment(owner: string, sourcePath: string): Promise<void> {
  1355. if (this.mode === 'upstream-only' || !this.store.knowsAttachment(owner, sourcePath) || this.store.attachment(owner, sourcePath)) return
  1356. try {
  1357. const response = await this.upstream.request('/api/files/download', {
  1358. search: new URLSearchParams({ path: sourcePath }), maxResponseBytes: 100 * 1_024 * 1_024,
  1359. })
  1360. this.store.storeAttachment(owner, sourcePath, response)
  1361. } catch { /* The next authorized request can retry. */ }
  1362. }
  1363. }
  1364. export function chatCacheKey(kind: string, profile: string, sessionID: string | undefined, search: URLSearchParams): string {
  1365. const normalized = new URLSearchParams(search)
  1366. normalized.sort()
  1367. return [kind, profile, sessionID ?? '', normalized.toString()].join(':')
  1368. }