@@ -7,7 +7,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
77import fs from 'fs-extra' ;
88import path from 'node:path' ;
99import os from 'node:os' ;
10- import { Session } from '../../src/session/SessionManager.js' ;
10+ import { Session , SessionManager } from '../../src/session/SessionManager.js' ;
1111import type { SessionMetadata } from '../../src/session/types.js' ;
1212
1313describe ( 'Session' , ( ) => {
@@ -50,3 +50,45 @@ describe('Session', () => {
5050 expect ( session . metadata . messageCount ) . toBe ( 1 ) ;
5151 } ) ;
5252} ) ;
53+
54+ describe ( 'SessionManager' , ( ) => {
55+ let tmpDir : string ;
56+
57+ beforeEach ( async ( ) => {
58+ tmpDir = await fs . mkdtemp ( path . join ( os . tmpdir ( ) , 'autohand-session-manager-test-' ) ) ;
59+ } ) ;
60+
61+ afterEach ( async ( ) => {
62+ await fs . remove ( tmpDir ) ;
63+ } ) ;
64+
65+ it ( 'recovers from a corrupt session index and initializes empty' , async ( ) => {
66+ const indexPath = path . join ( tmpDir , 'index.json' ) ;
67+ const corruptContent = '{ "sessions": [\n { "id": "broken\x00"' ;
68+ await fs . writeFile ( indexPath , corruptContent ) ;
69+
70+ const manager = new SessionManager ( tmpDir ) ;
71+ await expect ( manager . initialize ( ) ) . resolves . toBeUndefined ( ) ;
72+
73+ const sessions = await manager . listSessions ( ) ;
74+ expect ( sessions ) . toEqual ( [ ] ) ;
75+
76+ const backupFiles = ( await fs . readdir ( tmpDir ) ) . filter ( ( f ) => f . startsWith ( 'index.json.corrupt-' ) ) ;
77+ expect ( backupFiles ) . toHaveLength ( 1 ) ;
78+ expect ( await fs . readFile ( path . join ( tmpDir , backupFiles [ 0 ] ) , 'utf-8' ) ) . toBe ( corruptContent ) ;
79+ } ) ;
80+
81+ it ( 'recovers from an empty session index file' , async ( ) => {
82+ const indexPath = path . join ( tmpDir , 'index.json' ) ;
83+ await fs . writeFile ( indexPath , '' ) ;
84+
85+ const manager = new SessionManager ( tmpDir ) ;
86+ await expect ( manager . initialize ( ) ) . resolves . toBeUndefined ( ) ;
87+
88+ const sessions = await manager . listSessions ( ) ;
89+ expect ( sessions ) . toEqual ( [ ] ) ;
90+
91+ const backupFiles = ( await fs . readdir ( tmpDir ) ) . filter ( ( f ) => f . startsWith ( 'index.json.corrupt-' ) ) ;
92+ expect ( backupFiles ) . toHaveLength ( 1 ) ;
93+ } ) ;
94+ } ) ;
0 commit comments