@@ -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,27 @@ 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(
1169+ CASE WHEN jsonb_typeof(m->'contentBlocks') = 'array'
1170+ THEN m->'contentBlocks'
1171+ ELSE '[]'::jsonb
1172+ END
1173+ ) AS b
1174+ WHERE b->>'type' = 'text'
1175+ ), '[]'::jsonb)
1176+ )
1177+ )
1178+ FROM jsonb_array_elements(${ copilotChats . messages } ) AS m
1179+ WHERE m->>'role' IN ('user', 'assistant')
1180+ ), '[]'::jsonb)` ,
11611181 createdAt : copilotChats . createdAt ,
11621182 updatedAt : copilotChats . updatedAt ,
11631183 } )
@@ -1177,13 +1197,14 @@ export class WorkspaceVFS {
11771197 const safeName = sanitizeName ( title )
11781198 const prefix = `tasks/${ safeName } /`
11791199 const messages = Array . isArray ( task . messages ) ? task . messages : [ ]
1200+ const messageCount = Number ( task . messageCount ) || 0
11801201
11811202 this . files . set (
11821203 `${ prefix } session.md` ,
11831204 serializeTaskSession ( {
11841205 id : task . id ,
11851206 title,
1186- messageCount : messages . length ,
1207+ messageCount,
11871208 createdAt : task . createdAt ,
11881209 updatedAt : task . updatedAt ,
11891210 } )
0 commit comments