1- import { chmodSync , existsSync , mkdirSync , readFileSync , unlinkSync } from "node:fs" ;
1+ import { chmodSync , existsSync , lstatSync , mkdirSync , readFileSync , readdirSync , truncateSync , unlinkSync } from "node:fs" ;
22import { dirname , join } from "node:path" ;
33import { atomicWriteFile , getConfigDir } from "../config" ;
44import type { OcxProviderContinuationState } from "../types" ;
@@ -14,6 +14,10 @@ const MAX_STORED_RESPONSE_BYTES = 64 * 1024 * 1024;
1414 * carry base64 `input_image` data URLs, and one screenshot-heavy thread must not balloon the file. */
1515const SNAPSHOT_ENTRY_MAX_BYTES = 2 * 1024 * 1024 ;
1616const SNAPSHOT_TOTAL_MAX_BYTES = 24 * 1024 * 1024 ;
17+ const STALE_TEMP_GRACE_MS = 15 * 60 * 1_000 ;
18+ const STALE_TEMP_MAX_CANDIDATES = 4_096 ;
19+ const STALE_TEMP_MAX_CLEANUPS = 512 ;
20+ const RESPONSE_STATE_TEMP_NAME = / ^ r e s p o n s e s - s t a t e \. j s o n \. o c x \. ( \d + ) \. ( \d + ) \. t m p $ / ;
1721
1822interface StoredResponseState {
1923 createdAt : number ;
@@ -88,6 +92,102 @@ function snapshotPath(): string {
8892 return join ( getConfigDir ( ) , "responses-state.json" ) ;
8993}
9094
95+ export interface ResponseStateTempRecoveryResult {
96+ matched : number ;
97+ removed : number ;
98+ scrubbed : number ;
99+ failed : number ;
100+ bytesRemoved : number ;
101+ }
102+
103+ interface ResponseStateTempRecoveryIO {
104+ now : ( ) => number ;
105+ list : ( dir : string ) => string [ ] ;
106+ inspect : ( path : string ) => { isFile : boolean ; mtimeMs : number ; size : number } ;
107+ isProcessAlive : ( pid : number ) => boolean ;
108+ truncate : ( path : string ) => void ;
109+ unlink : ( path : string ) => void ;
110+ }
111+
112+ function processIsAlive ( pid : number ) : boolean {
113+ if ( pid === process . pid ) return true ;
114+ try {
115+ process . kill ( pid , 0 ) ;
116+ return true ;
117+ } catch ( error ) {
118+ // EPERM means the process exists but cannot be signalled. Unknown platform errors
119+ // are also protected; cleanup should prefer a false negative over touching a live writer.
120+ return ( error as NodeJS . ErrnoException ) . code !== "ESRCH" ;
121+ }
122+ }
123+
124+ const responseStateTempRecoveryIO : ResponseStateTempRecoveryIO = {
125+ now : Date . now ,
126+ list : dir => readdirSync ( dir ) ,
127+ inspect : path => {
128+ const stat = lstatSync ( path ) ;
129+ return { isFile : stat . isFile ( ) && ! stat . isSymbolicLink ( ) , mtimeMs : stat . mtimeMs , size : stat . size } ;
130+ } ,
131+ isProcessAlive : processIsAlive ,
132+ truncate : path => truncateSync ( path , 0 ) ,
133+ unlink : unlinkSync ,
134+ } ;
135+
136+ /**
137+ * Recover only abandoned response-state atomic-write files. The exact basename,
138+ * regular-file check, age gate, and PID liveness check protect unrelated/active files.
139+ * Cleanup is capped and best-effort because continuation state is only a cache.
140+ */
141+ export function recoverStaleResponseStateTemps (
142+ dir = getConfigDir ( ) ,
143+ overrides : Partial < ResponseStateTempRecoveryIO > = { } ,
144+ ) : ResponseStateTempRecoveryResult {
145+ const io = { ...responseStateTempRecoveryIO , ...overrides } ;
146+ const result : ResponseStateTempRecoveryResult = {
147+ matched : 0 ,
148+ removed : 0 ,
149+ scrubbed : 0 ,
150+ failed : 0 ,
151+ bytesRemoved : 0 ,
152+ } ;
153+ let names : string [ ] ;
154+ try { names = io . list ( dir ) ; } catch { return result ; }
155+ let candidates = 0 ;
156+ for ( const name of names ) {
157+ const match = RESPONSE_STATE_TEMP_NAME . exec ( name ) ;
158+ if ( ! match ) continue ;
159+ candidates += 1 ;
160+ if ( candidates > STALE_TEMP_MAX_CANDIDATES || result . removed + result . failed >= STALE_TEMP_MAX_CLEANUPS ) break ;
161+ result . matched += 1 ;
162+ const pid = Number ( match [ 1 ] ) ;
163+ const sequence = Number ( match [ 2 ] ) ;
164+ if ( ! Number . isSafeInteger ( pid ) || pid <= 0 || ! Number . isSafeInteger ( sequence ) || sequence <= 0 ) continue ;
165+ const path = join ( dir , name ) ;
166+ let file : ReturnType < ResponseStateTempRecoveryIO [ "inspect" ] > ;
167+ try { file = io . inspect ( path ) ; } catch { continue ; }
168+ if ( ! file . isFile || io . now ( ) - file . mtimeMs < STALE_TEMP_GRACE_MS ) continue ;
169+ if ( pid === process . pid || io . isProcessAlive ( pid ) ) continue ;
170+
171+ let scrubbed = false ;
172+ try {
173+ io . truncate ( path ) ;
174+ scrubbed = true ;
175+ result . scrubbed += 1 ;
176+ } catch { /* unlink may still remove the sensitive snapshot */ }
177+ try {
178+ io . unlink ( path ) ;
179+ result . removed += 1 ;
180+ result . bytesRemoved += file . size ;
181+ } catch {
182+ // A zero-byte residual is harmless privacy-wise but should still count as a
183+ // cleanup failure so a later startup can retry its removal.
184+ result . failed += 1 ;
185+ if ( ! scrubbed ) continue ;
186+ }
187+ }
188+ return result ;
189+ }
190+
91191/**
92192 * Best-effort disk snapshot so previous_response_id chains survive a proxy restart (the
93193 * dominant expansion-miss cause: an in-memory-only store dies with the process, and the next
@@ -100,6 +200,7 @@ function ensureLoaded(): void {
100200 loaded = true ;
101201 try {
102202 const path = snapshotPath ( ) ;
203+ recoverStaleResponseStateTemps ( dirname ( path ) ) ;
103204 if ( ! existsSync ( path ) ) return ;
104205 const raw = JSON . parse ( readFileSync ( path , "utf-8" ) ) as { version ?: unknown ; states ?: unknown } ;
105206 if ( ( raw . version !== 1 && raw . version !== 2 ) || ! Array . isArray ( raw . states ) ) return ;
0 commit comments