GeezerVison is showing github.com — fix(app): order stored messages by creation time (#41001) · Ichinose-Kazuki/opencode@79effe8
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: packages/app/src/context/global-sync/event-reducer.test.ts +11-11Lines changed: 11 additions & 11 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -15,12 +15,12 @@ const rootSession = (input: { id: string; parentID?: string; archived?: number } | 15 | 15 | }, | 16 | 16 | }) as Session | 17 | 17 |
| 18 | | -const userMessage = (id: string, sessionID: string) => | | 18 | +const userMessage = (id: string, sessionID: string, created = 1) => | 19 | 19 | ({ | 20 | 20 | id, | 21 | 21 | sessionID, | 22 | 22 | role: "user", | 23 | | - time: { created: 1 }, | | 23 | + time: { created }, | 24 | 24 | agent: "assistant", | 25 | 25 | model: { providerID: "openai", modelID: "gpt" }, | 26 | 26 | }) as Message | @@ -370,28 +370,28 @@ describe("applyDirectoryEvent", () => { | 370 | 370 | const sessionID = "ses_1" | 371 | 371 | const [store, setStore] = createStore( | 372 | 372 | baseState({ | 373 | | - message: { [sessionID]: [userMessage("msg_1", sessionID), userMessage("msg_3", sessionID)] }, | 374 | | - part: { msg_2: [textPart("prt_1", sessionID, "msg_2")] }, | | 373 | + message: { [sessionID]: [userMessage("msg_z", sessionID, 1), userMessage("msg_b", sessionID, 3)] }, | | 374 | + part: { msg_a: [textPart("prt_1", sessionID, "msg_a")] }, | 375 | 375 | }), | 376 | 376 | ) | 377 | 377 |
| 378 | 378 | applyDirectoryEvent({ | 379 | | - event: { type: "message.updated", properties: { info: userMessage("msg_2", sessionID) } }, | | 379 | + event: { type: "message.updated", properties: { info: userMessage("msg_a", sessionID, 2) } }, | 380 | 380 | store, | 381 | 381 | setStore, | 382 | 382 | push() {}, | 383 | 383 | directory: "/tmp", | 384 | 384 | loadLsp() {}, | 385 | 385 | }) | 386 | 386 |
| 387 | | - expect(store.message[sessionID]?.map((x) => x.id)).toEqual(["msg_1", "msg_2", "msg_3"]) | | 387 | + expect(store.message[sessionID]?.map((x) => x.id)).toEqual(["msg_z", "msg_a", "msg_b"]) | 388 | 388 |
| 389 | 389 | applyDirectoryEvent({ | 390 | 390 | event: { | 391 | 391 | type: "message.updated", | 392 | 392 | properties: { | 393 | 393 | info: { | 394 | | - ...userMessage("msg_2", sessionID), | | 394 | + ...userMessage("msg_a", sessionID, 2), | 395 | 395 | role: "assistant", | 396 | 396 | } as Message, | 397 | 397 | }, | @@ -403,19 +403,19 @@ describe("applyDirectoryEvent", () => { | 403 | 403 | loadLsp() {}, | 404 | 404 | }) | 405 | 405 |
| 406 | | - expect(store.message[sessionID]?.find((x) => x.id === "msg_2")?.role).toBe("assistant") | | 406 | + expect(store.message[sessionID]?.find((x) => x.id === "msg_a")?.role).toBe("assistant") | 407 | 407 |
| 408 | 408 | applyDirectoryEvent({ | 409 | | - event: { type: "message.removed", properties: { sessionID, messageID: "msg_2" } }, | | 409 | + event: { type: "message.removed", properties: { sessionID, messageID: "msg_a" } }, | 410 | 410 | store, | 411 | 411 | setStore, | 412 | 412 | push() {}, | 413 | 413 | directory: "/tmp", | 414 | 414 | loadLsp() {}, | 415 | 415 | }) | 416 | 416 |
| 417 | | - expect(store.message[sessionID]?.map((x) => x.id)).toEqual(["msg_1", "msg_3"]) | 418 | | - expect(store.part.msg_2).toBeUndefined() | | 417 | + expect(store.message[sessionID]?.map((x) => x.id)).toEqual(["msg_z", "msg_b"]) | | 418 | + expect(store.part.msg_a).toBeUndefined() | 419 | 419 | }) | 420 | 420 |
| 421 | 421 | test("upserts and prunes message parts", () => { | |
Collapse file Copy file name to clipboardExpand all lines: packages/app/src/context/global-sync/event-reducer.ts +8-7Lines changed: 8 additions & 7 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -15,6 +15,7 @@ import type { State, VcsCache } from "./types" | 15 | 15 | import { trimSessions } from "./session-trim" | 16 | 16 | import { dropSessionCaches } from "./session-cache" | 17 | 17 | import { diffs as list, message as clean } from "@/utils/diffs" | | 18 | +import { messageKey } from "@/utils/session-message" | 18 | 19 |
| 19 | 20 | const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"]) | 20 | 21 | const SESSION_CONTENT_EVENTS = new Set([ | @@ -275,7 +276,7 @@ export function applyDirectoryEvent(input: { | 275 | 276 | input.setStore("message", info.sessionID, [info]) | 276 | 277 | break | 277 | 278 | } | 278 | | - const result = Binary.search(messages, info.id, (m) => m.id) | | 279 | + const result = Binary.search(messages, messageKey(info), messageKey) | 279 | 280 | if (result.found) { | 280 | 281 | input.setStore("message", info.sessionID, result.index, reconcile(info)) | 281 | 282 | break | @@ -295,8 +296,8 @@ export function applyDirectoryEvent(input: { | 295 | 296 | produce((draft) => { | 296 | 297 | const messages = draft.message[props.sessionID] | 297 | 298 | if (messages) { | 298 | | - const result = Binary.search(messages, props.messageID, (m) => m.id) | 299 | | - if (result.found) messages.splice(result.index, 1) | | 299 | + const index = messages.findIndex((message) => message.id === props.messageID) | | 300 | + if (index >= 0) messages.splice(index, 1) | 300 | 301 | } | 301 | 302 | const parts = draft.part[props.messageID] | 302 | 303 | if (parts) { | @@ -322,7 +323,7 @@ export function applyDirectoryEvent(input: { | 322 | 323 | input.setStore("part", part.messageID, [part]) | 323 | 324 | break | 324 | 325 | } | 325 | | - const result = Binary.search(parts, part.id, (p) => p.id) | | 326 | + const result = Binary.search(parts, part.id, (item) => item.id) | 326 | 327 | if (result.found) { | 327 | 328 | input.setStore("part", part.messageID, result.index, reconcile(part)) | 328 | 329 | break | @@ -345,13 +346,13 @@ export function applyDirectoryEvent(input: { | 345 | 346 | ) | 346 | 347 | const parts = input.store.part[props.messageID] | 347 | 348 | if (!parts) break | 348 | | - const result = Binary.search(parts, props.partID, (p) => p.id) | | 349 | + const result = Binary.search(parts, props.partID, (part) => part.id) | 349 | 350 | if (result.found) { | 350 | 351 | input.setStore( | 351 | 352 | produce((draft) => { | 352 | 353 | const list = draft.part[props.messageID] | 353 | 354 | if (!list) return | 354 | | - const next = Binary.search(list, props.partID, (p) => p.id) | | 355 | + const next = Binary.search(list, props.partID, (part) => part.id) | 355 | 356 | if (!next.found) return | 356 | 357 | list.splice(next.index, 1) | 357 | 358 | if (list.length === 0) delete draft.part[props.messageID] | @@ -364,7 +365,7 @@ export function applyDirectoryEvent(input: { | 364 | 365 | const props = event.properties as { messageID: string; partID: string; field: string; delta: string } | 365 | 366 | const parts = input.store.part[props.messageID] | 366 | 367 | if (!parts) break | 367 | | - const result = Binary.search(parts, props.partID, (p) => p.id) | | 368 | + const result = Binary.search(parts, props.partID, (part) => part.id) | 368 | 369 | if (!result.found) break | 369 | 370 | const field = props.field as keyof (typeof parts)[number] | 370 | 371 | const current = parts[result.index]?.[field] | |
Collapse file Copy file name to clipboardExpand all lines: packages/app/src/context/server-session.test.ts +2-1Lines changed: 2 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -264,6 +264,7 @@ describe("server session", () => { | 264 | 264 |
| 265 | 265 | expect(requests).toEqual([{ sessionID: "root", limit: 20, order: "desc" }]) | 266 | 266 | expect(store.data.session_message.root.map((message) => message.id)).toEqual([user.id, assistant.id]) | | 267 | + expect(store.data.message.root.map((message) => message.id)).toEqual([user.id, assistant.id]) | 267 | 268 | }) | 268 | 269 |
| 269 | 270 | test("extends a current page to include the user for split assistant turns", async () => { | @@ -1497,7 +1498,7 @@ describe("server session", () => { | 1497 | 1498 |
| 1498 | 1499 | await store.sync("child", { force: true }) | 1499 | 1500 |
| 1500 | | - expect(store.data.message.child).toEqual([boundary, older]) | | 1501 | + expect(store.data.message.child).toEqual([older, boundary]) | 1501 | 1502 | }) | 1502 | 1503 |
| 1503 | 1504 | test("preserves a part update for a message being loaded from history", async () => { | |
Collapse file Copy file name to clipboardExpand all lines: packages/app/src/context/server-session.ts +28-29Lines changed: 28 additions & 29 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -18,15 +18,14 @@ import { message as cleanMessage } from "@/utils/diffs" | 18 | 18 | import { sessionNotFoundError } from "@/utils/server-errors" | 19 | 19 | import { rootSession } from "@/utils/session-route" | 20 | 20 | import { normalizeSessionInfo } from "@/utils/session" | 21 | | -import { normalizeSessionMessages } from "@/utils/session-message" | | 21 | +import { compareMessages, messageKey, normalizeSessionMessages } from "@/utils/session-message" | 22 | 22 | import { dropSessionCaches, pickSessionCacheEvictions, SESSION_CACHE_LIMIT } from "./global-sync/session-cache" | 23 | 23 | import { createV2SessionReducer, type V2SessionReduction } from "./server-session-v2-reducer" | 24 | 24 | import type { ServerApi } from "@/utils/server" | 25 | 25 |
| 26 | 26 | type MessageApi = ServerApi["message"] | 27 | 27 |
| 28 | 28 | const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0) | 29 | | -const cmpMessage = (a: Message, b: Message) => a.time.created - b.time.created || cmp(a.id, b.id) | 30 | 29 | const SKIP_PARTS = new Set(["patch", "step-start", "step-finish"]) | 31 | 30 | const initialMessagePageSize = 20 | 32 | 31 | const historyMessagePageSize = 200 | @@ -64,7 +63,7 @@ type MessagePage = { | 64 | 63 | function legacyMessageSource(items: { info: Message; parts: Part[] }[]): SessionMessageInfo[] { | 65 | 64 | return items | 66 | 65 | .slice() | 67 | | - .sort((a, b) => cmp(a.info.id, b.info.id)) | | 66 | + .sort((a, b) => compareMessages(a.info, b.info)) | 68 | 67 | .map((item) => { | 69 | 68 | if (item.info.role === "user") { | 70 | 69 | return { | @@ -111,17 +110,16 @@ function mergeOptimisticPage(page: MessagePage, items: OptimisticItem[]) { | 111 | 110 | const part = new Map(page.part.map((item) => [item.id, item.part])) | 112 | 111 | const observed: { messageID: string; parts: Part[] }[] = [] | 113 | 112 | for (const item of items) { | 114 | | - const result = Binary.search(session, item.message.id, (message) => message.id) | 115 | | - if (!result.found) session.splice(result.index, 0, item.message) | | 113 | + const result = Binary.search(session, messageKey(item.message), messageKey) | | 114 | + const found = result.found | | 115 | + if (!found) session.splice(result.index, 0, item.message) | 116 | 116 | const current = part.get(item.message.id) | 117 | | - const confirmed = result.found | 118 | | - ? item.parts.filter((part) => Binary.search(current ?? [], part.id, (value) => value.id).found) | 119 | | - : [] | 120 | | - if (result.found) observed.push({ messageID: item.message.id, parts: confirmed }) | | 117 | + const confirmed = found ? item.parts.filter((part) => current?.some((value) => value.id === part.id)) : [] | | 118 | + if (found) observed.push({ messageID: item.message.id, parts: confirmed }) | 121 | 119 | part.set( | 122 | 120 | item.message.id, | 123 | 121 | merge( | 124 | | - result.found ? (current ?? []) : merge(item.confirmedParts ?? [], current ?? []), | | 122 | + found ? (current ?? []) : merge(item.confirmedParts ?? [], current ?? []), | 125 | 123 | item.parts.filter((part) => !confirmed.includes(part)), | 126 | 124 | ), | 127 | 125 | ) | @@ -158,6 +156,7 @@ function reconcileFetched<T extends { id: string }>( | 158 | 156 | retained?: ReadonlySet<string> | 159 | 157 | removed?: ReadonlySet<string> | 160 | 158 | preserveUnfetched?: boolean | ((item: T) => boolean) | | 159 | + compare?: (a: T, b: T) => number | 161 | 160 | } = {}, | 162 | 161 | ) { | 163 | 162 | const result = new Map(fetched.map((item) => [item.id, item])) | @@ -180,7 +179,8 @@ function reconcileFetched<T extends { id: string }>( | 180 | 179 | if (!item) result.delete(id) | 181 | 180 | } | 182 | 181 | for (const id of options.removed ?? emptyIDs) result.delete(id) | 183 | | - return [...result.values()].sort((a, b) => cmp(a.id, b.id)) | | 182 | + const items = [...result.values()] | | 183 | + return options.compare ? items.sort(options.compare) : items | 184 | 184 | } | 185 | 185 |
| 186 | 186 | type ServerSessionOptions = { retry?: typeof retry; protocol?: Promise<"v1" | "v2"> } | @@ -413,8 +413,7 @@ export function createServerSession( | 413 | 413 | if (!load) return | 414 | 414 | // A part event keeps an existing parent when the fetched page omits it without overriding fetched metadata. | 415 | 415 | const messages = data.message[sessionID] | 416 | | - if (messages && Binary.search(messages, messageID, (message) => message.id).found) | 417 | | - load.retainedMessages.add(messageID) | | 416 | + if (messages?.some((message) => message.id === messageID)) load.retainedMessages.add(messageID) | 418 | 417 | const parts = load.touchedParts.get(messageID) | 419 | 418 | if (parts) { | 420 | 419 | parts.add(partID) | @@ -437,16 +436,14 @@ export function createServerSession( | 437 | 436 | load.touchedParts.set(messageID, new Set(parts)) | 438 | 437 | load.carriedDeltaParts.set(messageID, new Set(parts)) | 439 | 438 | const messages = data.message[sessionID] | 440 | | - if (messages && Binary.search(messages, messageID, (message) => message.id).found) | 441 | | - load.retainedMessages.add(messageID) | | 439 | + if (messages?.some((message) => message.id === messageID)) load.retainedMessages.add(messageID) | 442 | 440 | } | 443 | 441 | for (const [messageID, parts] of load.removedParts) { | 444 | 442 | const touched = load.touchedParts.get(messageID) ?? new Set<string>() | 445 | 443 | parts.forEach((partID) => touched.add(partID)) | 446 | 444 | load.touchedParts.set(messageID, touched) | 447 | 445 | const messages = data.message[sessionID] | 448 | | - if (messages && Binary.search(messages, messageID, (message) => message.id).found) | 449 | | - load.retainedMessages.add(messageID) | | 446 | + if (messages?.some((message) => message.id === messageID)) load.retainedMessages.add(messageID) | 450 | 447 | } | 451 | 448 | for (const [messageID, parts] of load.optimisticParts) { | 452 | 449 | load.removedMessages.delete(messageID) | @@ -555,7 +552,7 @@ export function createServerSession( | 555 | 552 | const source = pages.flatMap((page) => page.data).toReversed() | 556 | 553 | const normalized = normalizeSessionMessages(sessionID, source) | 557 | 554 | return { | 558 | | - session: normalized.messages.sort((a, b) => cmp(a.id, b.id)), | | 555 | + session: normalized.messages.sort(compareMessages), | 559 | 556 | part: [...normalized.parts.entries()] | 560 | 557 | .map(([id, part]) => ({ id, part: part.sort((a, b) => cmp(a.id, b.id)) })) | 561 | 558 | .sort((a, b) => cmp(a.id, b.id)), | @@ -572,7 +569,7 @@ export function createServerSession( | 572 | 569 | }) | 573 | 570 | const items = (response.data ?? []).filter((item) => !!item?.info?.id) | 574 | 571 | return { | 575 | | - session: items.map((item) => cleanMessage(item.info)).sort((a, b) => cmp(a.id, b.id)), | | 572 | + session: items.map((item) => cleanMessage(item.info)).sort(compareMessages), | 576 | 573 | part: items.map((item) => ({ | 577 | 574 | id: item.info.id, | 578 | 575 | part: item.parts.filter((part) => !!part?.id).sort((a, b) => cmp(a.id, b.id)), | @@ -696,7 +693,7 @@ export function createServerSession( | 696 | 693 | const normalized = normalizeSessionMessages(sessionID, source) | 697 | 694 | return { | 698 | 695 | ...page, | 699 | | - session: normalized.messages.sort((a, b) => cmp(a.id, b.id)), | | 696 | + session: normalized.messages.sort(compareMessages), | 700 | 697 | part: [...normalized.parts.entries()] | 701 | 698 | .map(([id, part]) => ({ id, part: part.sort((a, b) => cmp(a.id, b.id)) })) | 702 | 699 | .sort((a, b) => cmp(a.id, b.id)), | @@ -713,6 +710,7 @@ export function createServerSession( | 713 | 710 | retained: load?.retainedMessages, | 714 | 711 | removed: load?.removedMessages, | 715 | 712 | preserveUnfetched, | | 713 | + compare: compareMessages, | 716 | 714 | }) | 717 | 715 | batch(() => { | 718 | 716 | if (source) setData("session_message", sessionID, reconcile(source)) | @@ -754,7 +752,7 @@ export function createServerSession( | 754 | 752 | try { | 755 | 753 | const page = await fetchMessages(sessionID, limit, before, () => resetMessageLoad(sessionID, load)) | 756 | 754 | const first = page.session.reduce<Message | undefined>( | 757 | | - (oldest, message) => (!oldest || cmpMessage(message, oldest) < 0 ? message : oldest), | | 755 | + (oldest, message) => (!oldest || compareMessages(message, oldest) < 0 ? message : oldest), | 758 | 756 | undefined, | 759 | 757 | ) | 760 | 758 | if (generations.get(sessionID) !== active) return | @@ -804,14 +802,15 @@ export function createServerSession( | 804 | 802 | session: merge( | 805 | 803 | page.session, | 806 | 804 | parents.map((parent) => parent.message), | 807 | | - ), | | 805 | + ).sort(compareMessages), | 808 | 806 | part: merge( | 809 | 807 | page.part, | 810 | 808 | parents.map((parent) => ({ id: parent.message.id, part: parent.parts })), | 811 | 809 | ), | 812 | 810 | } | 813 | 811 | const preserveUnfetched = | 814 | | - mode === "prepend" || (!result.complete && (!first || ((message: Message) => cmpMessage(message, first) < 0))) | | 812 | + mode === "prepend" || | | 813 | + (!result.complete && (!first || ((message: Message) => compareMessages(message, first) < 0))) | 815 | 814 | applyMessagePage( | 816 | 815 | sessionID, | 817 | 816 | result, | @@ -928,7 +927,7 @@ export function createServerSession( | 928 | 927 | .message({ sessionID, messageID }) | 929 | 928 | .then((message) => { | 930 | 929 | const current = data.session_message[sessionID] ?? [] | 931 | | - const messages = [...current.filter((item) => item.id !== message.id), message].sort((a, b) => cmp(a.id, b.id)) | | 930 | + const messages = [...current.filter((item) => item.id !== message.id), message].sort(compareMessages) | 932 | 931 | projectV2({ sessionID, messages, touched: [message.id] }) | 933 | 932 | }) | 934 | 933 | .catch(() => {}) | @@ -1051,7 +1050,7 @@ export function createServerSession( | 1051 | 1050 | setData("message", info.sessionID, [info]) | 1052 | 1051 | return | 1053 | 1052 | } | 1054 | | - const result = Binary.search(messages, info.id, (message) => message.id) | | 1053 | + const result = Binary.search(messages, messageKey(info), messageKey) | 1055 | 1054 | if (result.found) setData("message", info.sessionID, result.index, reconcile(info)) | 1056 | 1055 | if (!result.found) | 1057 | 1056 | setData("message", info.sessionID, (value = []) => { | @@ -1084,8 +1083,8 @@ export function createServerSession( | 1084 | 1083 | produce((draft) => { | 1085 | 1084 | const messages = draft.message[props.sessionID] | 1086 | 1085 | if (messages) { | 1087 | | - const result = Binary.search(messages, props.messageID, (message) => message.id) | 1088 | | - if (result.found) messages.splice(result.index, 1) | | 1086 | + const index = messages.findIndex((message) => message.id === props.messageID) | | 1087 | + if (index >= 0) messages.splice(index, 1) | 1089 | 1088 | } | 1090 | 1089 | deleteMessageParts(draft, props.messageID) | 1091 | 1090 | }), | @@ -1097,7 +1096,7 @@ export function createServerSession( | 1097 | 1096 | if (SKIP_PARTS.has(part.type)) return | 1098 | 1097 | const messages = data.message[part.sessionID] | 1099 | 1098 | const load = messageLoads.get(part.sessionID) | 1100 | | - const missing = !messages || !Binary.search(messages, part.messageID, (message) => message.id).found | | 1099 | + const missing = !messages?.some((message) => message.id === part.messageID) | 1101 | 1100 | // Outside a page load, accepting a part without its ordered parent event would create an unbounded orphan. | 1102 | 1101 | if ( | 1103 | 1102 | missing && | @@ -1341,7 +1340,7 @@ export function createServerSession( | 1341 | 1340 | if (items) items.set(input.message.id, { ...input, parts, confirmedParts: [] }) | 1342 | 1341 | if (!items) | 1343 | 1342 | optimistic.set(input.sessionID, new Map([[input.message.id, { ...input, parts, confirmedParts: [] }]])) | 1344 | | - setData("message", input.sessionID, (messages = []) => merge(messages, [input.message])) | | 1343 | + setData("message", input.sessionID, (messages = []) => merge(messages, [input.message]).sort(compareMessages)) | 1345 | 1344 | setData( | 1346 | 1345 | "part_text_accum_delta", | 1347 | 1346 | produce((draft) => { | |
|