Skip to content

Commit c3ac54e

Browse files
authored
fix(vfs): make copilot message ordering deterministic via WITH ORDINALITY (#4597)
1 parent b1a9443 commit c3ac54e

1 file changed

Lines changed: 10 additions & 9 deletions

File tree

apps/sim/lib/copilot/vfs/workspace-vfs.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1161,22 +1161,23 @@ export class WorkspaceVFS {
11611161
messages: sql<unknown[]>`COALESCE((
11621162
SELECT jsonb_agg(
11631163
jsonb_build_object(
1164-
'role', m->>'role',
1165-
'content', m->'content',
1164+
'role', m.value->>'role',
1165+
'content', m.value->'content',
11661166
'contentBlocks', COALESCE((
1167-
SELECT jsonb_agg(jsonb_build_object('type', 'text', 'content', b->'content'))
1167+
SELECT jsonb_agg(jsonb_build_object('type', 'text', 'content', b.value->'content') ORDER BY b.ord)
11681168
FROM jsonb_array_elements(
1169-
CASE WHEN jsonb_typeof(m->'contentBlocks') = 'array'
1170-
THEN m->'contentBlocks'
1169+
CASE WHEN jsonb_typeof(m.value->'contentBlocks') = 'array'
1170+
THEN m.value->'contentBlocks'
11711171
ELSE '[]'::jsonb
11721172
END
1173-
) AS b
1174-
WHERE b->>'type' = 'text'
1173+
) WITH ORDINALITY AS b(value, ord)
1174+
WHERE b.value->>'type' = 'text'
11751175
), '[]'::jsonb)
11761176
)
1177+
ORDER BY m.ord
11771178
)
1178-
FROM jsonb_array_elements(${copilotChats.messages}) AS m
1179-
WHERE m->>'role' IN ('user', 'assistant')
1179+
FROM jsonb_array_elements(${copilotChats.messages}) WITH ORDINALITY AS m(value, ord)
1180+
WHERE m.value->>'role' IN ('user', 'assistant')
11801181
), '[]'::jsonb)`,
11811182
createdAt: copilotChats.createdAt,
11821183
updatedAt: copilotChats.updatedAt,

0 commit comments

Comments
 (0)