@@ -254,4 +254,66 @@ describe('CodexAdapter', () => {
254254 expect ( agents ) . toHaveLength ( 1 ) ;
255255 expect ( agents [ 0 ] . sessionId ) . toBe ( 'near-session' ) ;
256256 } ) ;
257+
258+ it ( 'should prefer missing-cwd session before any-session fallback for unmatched process' , async ( ) => {
259+ mockedListProcesses . mockReturnValue ( [
260+ { pid : 108 , command : 'codex' , cwd : '/repo-missing-cwd' , tty : 'ttys015' } ,
261+ ] as ProcessInfo [ ] ) ;
262+
263+ jest . spyOn ( adapter as any , 'readSessions' ) . mockReturnValue ( [
264+ {
265+ sessionId : 'any-session' ,
266+ projectPath : '/another-repo' ,
267+ summary : 'Any session fallback' ,
268+ sessionStart : new Date ( '2026-02-26T15:00:00.000Z' ) ,
269+ lastActive : new Date ( '2026-02-26T15:12:00.000Z' ) ,
270+ lastPayloadType : 'agent_message' ,
271+ } as MockSession ,
272+ {
273+ sessionId : 'missing-cwd-session' ,
274+ projectPath : '' ,
275+ summary : 'Missing cwd session' ,
276+ sessionStart : new Date ( '2026-02-26T15:00:10.000Z' ) ,
277+ lastActive : new Date ( '2026-02-26T15:11:00.000Z' ) ,
278+ lastPayloadType : 'agent_message' ,
279+ } as MockSession ,
280+ ] ) ;
281+ jest . spyOn ( adapter as any , 'getProcessStartTimes' ) . mockReturnValue (
282+ new Map ( [ [ 108 , new Date ( '2026-02-26T15:00:00.000Z' ) ] ] ) ,
283+ ) ;
284+
285+ const agents = await adapter . detectAgents ( ) ;
286+ expect ( agents ) . toHaveLength ( 1 ) ;
287+ expect ( agents [ 0 ] . sessionId ) . toBe ( 'missing-cwd-session' ) ;
288+ } ) ;
289+
290+ it ( 'should not reuse the same session for multiple running processes' , async ( ) => {
291+ mockedListProcesses . mockReturnValue ( [
292+ { pid : 109 , command : 'codex' , cwd : '/repo-shared' , tty : 'ttys016' } ,
293+ { pid : 110 , command : 'codex' , cwd : '/repo-shared' , tty : 'ttys017' } ,
294+ ] as ProcessInfo [ ] ) ;
295+
296+ jest . spyOn ( adapter as any , 'readSessions' ) . mockReturnValue ( [
297+ {
298+ sessionId : 'shared-session' ,
299+ projectPath : '/repo-shared' ,
300+ summary : 'Only one session exists' ,
301+ sessionStart : new Date ( '2026-02-26T15:00:00.000Z' ) ,
302+ lastActive : new Date ( '2026-02-26T15:11:00.000Z' ) ,
303+ lastPayloadType : 'agent_message' ,
304+ } as MockSession ,
305+ ] ) ;
306+ jest . spyOn ( adapter as any , 'getProcessStartTimes' ) . mockReturnValue (
307+ new Map ( [
308+ [ 109 , new Date ( '2026-02-26T15:00:00.000Z' ) ] ,
309+ [ 110 , new Date ( '2026-02-26T15:00:30.000Z' ) ] ,
310+ ] ) ,
311+ ) ;
312+
313+ const agents = await adapter . detectAgents ( ) ;
314+ expect ( agents ) . toHaveLength ( 2 ) ;
315+ const mappedAgents = agents . filter ( ( agent ) => agent . sessionId === 'shared-session' ) ;
316+ expect ( mappedAgents ) . toHaveLength ( 1 ) ;
317+ expect ( agents . some ( ( agent ) => agent . sessionId . startsWith ( 'pid-' ) ) ) . toBe ( true ) ;
318+ } ) ;
257319} ) ;
0 commit comments