()
| 312 | } |
| 313 | |
| 314 | function startTailing() { |
| 315 | state.tailRemainder = Buffer.alloc(0); |
| 316 | state.tailTimer = setInterval(() => { |
| 317 | if (maybeAttachPendingSwitchTarget('tail_pending_target')) return; |
| 318 | if (!state.transcriptPath) return; |
| 319 | try { |
| 320 | const stat = fs.statSync(state.transcriptPath); |
| 321 | if (stat.size <= state.transcriptOffset) { |
| 322 | if (state.tailCatchingUp) { |
| 323 | state.tailCatchingUp = false; |
| 324 | log('Tail catch-up complete, live mode'); |
| 325 | } |
| 326 | return; |
| 327 | } |
| 328 | |
| 329 | const fd = fs.openSync(state.transcriptPath, 'r'); |
| 330 | const buf = Buffer.alloc(stat.size - state.transcriptOffset); |
| 331 | fs.readSync(fd, buf, 0, buf.length, state.transcriptOffset); |
| 332 | fs.closeSync(fd); |
| 333 | state.transcriptOffset = stat.size; |
| 334 | |
| 335 | const data = state.tailRemainder.length > 0 ? Buffer.concat([state.tailRemainder, buf]) : buf; |
| 336 | let start = 0; |
| 337 | for (let i = 0; i < data.length; i++) { |
| 338 | if (data[i] !== 0x0A) continue; |
| 339 | const line = data.slice(start, i).toString('utf8').trim(); |
| 340 | start = i + 1; |
| 341 | if (!line) continue; |
| 342 | try { |
| 343 | const event = JSON.parse(line); |
| 344 | if (event.type === 'user' || (event.message && event.message.role === 'user')) { |
| 345 | const content = event.message && event.message.content; |
| 346 | const slashCommand = extractSlashCommand(content); |
| 347 | const isInterruptedUserEvent = isUserInterruptEvent(content); |
| 348 | const isPassiveUserEvent = isNonAiUserEvent(event, content); |
| 349 | const ignoreInitialClear = ( |
| 350 | slashCommand === '/clear' && |
| 351 | state.pendingInitialClearTranscript && |
| 352 | state.pendingInitialClearTranscript.sessionId === state.currentSessionId |
| 353 | ); |
| 354 | if (!state.tailCatchingUp && isInterruptedUserEvent) { |
| 355 | setTurnState('idle', { sessionId: state.currentSessionId, reason: 'transcript_user_interrupt' }); |
| 356 | } |
| 357 | if (!state.tailCatchingUp && !slashCommand && !isPassiveUserEvent) { |
| 358 | setTurnState('running', { sessionId: state.currentSessionId, reason: 'transcript_user_event' }); |
| 359 | } |
| 360 | if (slashCommand === '/clear') { |
| 361 | if (ignoreInitialClear) { |
| 362 | state.pendingInitialClearTranscript = null; |
| 363 | log(`Ignored bootstrap /clear transcript event for session ${state.currentSessionId}`); |
| 364 | } else { |
| 365 | markExpectingSwitch(); |
| 366 | } |
| 367 | } else if ( |
| 368 | state.pendingInitialClearTranscript && |
| 369 | state.pendingInitialClearTranscript.sessionId === state.currentSessionId && |
| 370 | !isPassiveUserEvent && |
| 371 | !event.isMeta && |
no test coverage detected