(
updateFileHistoryState: (
updater: (prev: FileHistoryState) => FileHistoryState,
) => void,
messageId: UUID,
)
| 345 | * Rewinds the file system to a previous snapshot. |
| 346 | */ |
| 347 | export async function fileHistoryRewind( |
| 348 | updateFileHistoryState: ( |
| 349 | updater: (prev: FileHistoryState) => FileHistoryState, |
| 350 | ) => void, |
| 351 | messageId: UUID, |
| 352 | ): Promise<void> { |
| 353 | if (!fileHistoryEnabled()) { |
| 354 | return |
| 355 | } |
| 356 | |
| 357 | // Rewind is a pure filesystem side-effect and does not mutate |
| 358 | // FileHistoryState. Capture state with a no-op updater, then do IO async. |
| 359 | let captured: FileHistoryState | undefined |
| 360 | updateFileHistoryState(state => { |
| 361 | captured = state |
| 362 | return state |
| 363 | }) |
| 364 | if (!captured) return |
| 365 | |
| 366 | const targetSnapshot = captured.snapshots.findLast( |
| 367 | snapshot => snapshot.messageId === messageId, |
| 368 | ) |
| 369 | if (!targetSnapshot) { |
| 370 | logError(new Error(`FileHistory: Snapshot for ${messageId} not found`)) |
| 371 | logEvent('tengu_file_history_rewind_failed', { |
| 372 | trackedFilesCount: captured.trackedFiles.size, |
| 373 | snapshotFound: false, |
| 374 | }) |
| 375 | throw new Error('The selected snapshot was not found') |
| 376 | } |
| 377 | |
| 378 | try { |
| 379 | logForDebugging( |
| 380 | `FileHistory: [Rewind] Rewinding to snapshot for ${messageId}`, |
| 381 | ) |
| 382 | const filesChanged = await applySnapshot(captured, targetSnapshot) |
| 383 | |
| 384 | logForDebugging(`FileHistory: [Rewind] Finished rewinding to ${messageId}`) |
| 385 | logEvent('tengu_file_history_rewind_success', { |
| 386 | trackedFilesCount: captured.trackedFiles.size, |
| 387 | filesChangedCount: filesChanged.length, |
| 388 | }) |
| 389 | } catch (error) { |
| 390 | logError(error) |
| 391 | logEvent('tengu_file_history_rewind_failed', { |
| 392 | trackedFilesCount: captured.trackedFiles.size, |
| 393 | snapshotFound: true, |
| 394 | }) |
| 395 | throw error |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | export function fileHistoryCanRestore( |
| 400 | state: FileHistoryState, |
no test coverage detected