Skip to content

Commit 7fe85a1

Browse files
committed
fix(session-recovery): handle API/storage index mismatch in empty message recovery
- Try both targetIndex and targetIndex-1 to handle system message offset - Remove 'last assistant message' skip logic (API error means it's not final) 🤖 GENERATED WITH ASSISTANCE OF [OhMyOpenCode](https://github.com/code-yeongyu/oh-my-opencode)
1 parent 8e62514 commit 7fe85a1

File tree

1 file changed

+18
-17
lines changed

1 file changed

+18
-17
lines changed

src/hooks/session-recovery/storage.ts

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -122,13 +122,7 @@ export function findEmptyMessages(sessionID: string): string[] {
122122
const messages = readMessages(sessionID)
123123
const emptyIds: string[] = []
124124

125-
for (let i = 0; i < messages.length; i++) {
126-
const msg = messages[i]
127-
128-
// API rule: only the final assistant message may have empty content
129-
const isLastMessage = i === messages.length - 1
130-
if (isLastMessage && msg.role === "assistant") continue
131-
125+
for (const msg of messages) {
132126
if (!messageHasContent(msg.id)) {
133127
emptyIds.push(msg.id)
134128
}
@@ -140,18 +134,25 @@ export function findEmptyMessages(sessionID: string): string[] {
140134
export function findEmptyMessageByIndex(sessionID: string, targetIndex: number): string | null {
141135
const messages = readMessages(sessionID)
142136

143-
if (targetIndex < 0 || targetIndex >= messages.length) return null
144-
145-
const targetMsg = messages[targetIndex]
137+
// Try multiple indices to handle system message offset
138+
// API includes system message at index 0, storage may not
139+
const indicesToTry = [targetIndex, targetIndex - 1]
146140

147-
// API rule: only the final assistant message may have empty content
148-
// All other messages (user AND assistant) must have non-empty content
149-
const isLastMessage = targetIndex === messages.length - 1
150-
if (isLastMessage && targetMsg.role === "assistant") return null
151-
152-
if (messageHasContent(targetMsg.id)) return null
141+
for (const idx of indicesToTry) {
142+
if (idx < 0 || idx >= messages.length) continue
153143

154-
return targetMsg.id
144+
const targetMsg = messages[idx]
145+
146+
// NOTE: Do NOT skip last assistant message here
147+
// If API returned an error, this message is NOT the final assistant message
148+
// (the API only allows empty content for the ACTUAL final assistant message)
149+
150+
if (!messageHasContent(targetMsg.id)) {
151+
return targetMsg.id
152+
}
153+
}
154+
155+
return null
155156
}
156157

157158
export function findFirstEmptyMessage(sessionID: string): string | null {

0 commit comments

Comments
 (0)