@@ -17,7 +17,7 @@ import {
1717} from '@sim/db/schema'
1818import { createLogger } from '@sim/logger'
1919import { toError } from '@sim/utils/errors'
20- import { and , desc , eq , isNotNull , isNull , ne } from 'drizzle-orm'
20+ import { and , desc , eq , isNotNull , isNull , ne , sql } from 'drizzle-orm'
2121import { listApiKeys } from '@/lib/api-key/service'
2222import { buildWorkspaceMd , type WorkspaceMdData } from '@/lib/copilot/chat/workspace-context'
2323import { extractDocumentStyle } from '@/lib/copilot/vfs/document-style'
@@ -1157,7 +1157,22 @@ export class WorkspaceVFS {
11571157 . select ( {
11581158 id : copilotChats . id ,
11591159 title : copilotChats . title ,
1160- messages : copilotChats . messages ,
1160+ messageCount : sql < number > `COALESCE(jsonb_array_length(${ copilotChats . messages } ), 0)` ,
1161+ messages : sql < unknown [ ] > `COALESCE((
1162+ SELECT jsonb_agg(
1163+ jsonb_build_object(
1164+ 'role', m->>'role',
1165+ 'content', m->>'content',
1166+ 'contentBlocks', COALESCE((
1167+ SELECT jsonb_agg(jsonb_build_object('type', 'text', 'content', b->>'content'))
1168+ FROM jsonb_array_elements(COALESCE(m->'contentBlocks', '[]'::jsonb)) AS b
1169+ WHERE b->>'type' = 'text'
1170+ ), '[]'::jsonb)
1171+ )
1172+ )
1173+ FROM jsonb_array_elements(${ copilotChats . messages } ) AS m
1174+ WHERE m->>'role' IN ('user', 'assistant')
1175+ ), '[]'::jsonb)` ,
11611176 createdAt : copilotChats . createdAt ,
11621177 updatedAt : copilotChats . updatedAt ,
11631178 } )
@@ -1177,13 +1192,14 @@ export class WorkspaceVFS {
11771192 const safeName = sanitizeName ( title )
11781193 const prefix = `tasks/${ safeName } /`
11791194 const messages = Array . isArray ( task . messages ) ? task . messages : [ ]
1195+ const messageCount = Number ( task . messageCount ) || 0
11801196
11811197 this . files . set (
11821198 `${ prefix } session.md` ,
11831199 serializeTaskSession ( {
11841200 id : task . id ,
11851201 title,
1186- messageCount : messages . length ,
1202+ messageCount,
11871203 createdAt : task . createdAt ,
11881204 updatedAt : task . updatedAt ,
11891205 } )
0 commit comments