| 20 | export type RevertInput = z.infer<typeof RevertInput> |
| 21 | |
| 22 | export async function revert(input: RevertInput) { |
| 23 | SessionPrompt.assertNotBusy(input.sessionID) |
| 24 | const all = await Session.messages({ sessionID: input.sessionID }) |
| 25 | let lastUser: MessageV2.User | undefined |
| 26 | const session = await Session.get(input.sessionID) |
| 27 | |
| 28 | let revert: Session.Info["revert"] |
| 29 | const patches: Snapshot.Patch[] = [] |
| 30 | for (const msg of all) { |
| 31 | if (msg.info.role === "user") lastUser = msg.info |
| 32 | const remaining = [] |
| 33 | for (const part of msg.parts) { |
| 34 | if (revert) { |
| 35 | if (part.type === "patch") { |
| 36 | patches.push(part) |
| 37 | } |
| 38 | continue |
| 39 | } |
| 40 | |
| 41 | if (!revert) { |
| 42 | if ((msg.info.id === input.messageID && !input.partID) || part.id === input.partID) { |
| 43 | // if no useful parts left in message, same as reverting whole message |
| 44 | const partID = remaining.some((item) => ["text", "tool"].includes(item.type)) ? input.partID : undefined |
| 45 | revert = { |
| 46 | messageID: !partID && lastUser ? lastUser.id : msg.info.id, |
| 47 | partID, |
| 48 | } |
| 49 | } |
| 50 | remaining.push(part) |
| 51 | } |
| 52 | } |
| 53 | } |
| 54 | |
| 55 | if (revert) { |
| 56 | const session = await Session.get(input.sessionID) |
| 57 | revert.snapshot = session.revert?.snapshot ?? (await Snapshot.track()) |
| 58 | await Snapshot.revert(patches) |
| 59 | if (revert.snapshot) revert.diff = await Snapshot.diff(revert.snapshot) |
| 60 | return Session.update(input.sessionID, (draft) => { |
| 61 | draft.revert = revert |
| 62 | }) |
| 63 | } |
| 64 | return session |
| 65 | } |
| 66 | |
| 67 | export async function unrevert(input: { sessionID: string }) { |
| 68 | log.info("unreverting", input) |