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