| 1 | import type { ControlResult, SessionMeta } from "./types"; |
| 2 | |
| 3 | export interface TaskMonitorNavigationDeps { |
| 4 | tabID: string; |
| 5 | taskID: string; |
| 6 | intentSeq: number; |
| 7 | isIntentCurrent: (intentSeq: number) => boolean; |
| 8 | openTaskSessionForTab: (tabID: string, taskID: string) => Promise<ControlResult>; |
| 9 | listSessionsForTab: (tabID: string) => Promise<SessionMeta[]>; |
| 10 | sessionIDFromPath: (path: string) => string; |
| 11 | } |
| 12 | |
| 13 | // resolveTaskMonitorSession keeps every asynchronous lookup bound to the tab |
| 14 | // that rendered the task row. A newer navigation intent makes late successes |
| 15 | // and late failures inert, preserving last-click-wins behavior. |
| 16 | export async function resolveTaskMonitorSession({ |
| 17 | tabID, |
| 18 | taskID, |
| 19 | intentSeq, |
| 20 | isIntentCurrent, |
| 21 | openTaskSessionForTab, |
| 22 | listSessionsForTab, |
| 23 | sessionIDFromPath, |
| 24 | }: TaskMonitorNavigationDeps): Promise<SessionMeta | null> { |
| 25 | let result: ControlResult; |
| 26 | try { |
| 27 | result = await openTaskSessionForTab(tabID, taskID); |
| 28 | } catch (error) { |
| 29 | if (!isIntentCurrent(intentSeq)) return null; |
| 30 | throw error; |
| 31 | } |
| 32 | if (!isIntentCurrent(intentSeq)) return null; |
| 33 | if (result.error) { |
| 34 | throw new Error(`${result.error.code}: ${result.error.message}`); |
| 35 | } |
| 36 | |
| 37 | const sessionID = result.session_id?.trim(); |
| 38 | if (!sessionID) throw new Error("Task session is unavailable"); |
| 39 | |
| 40 | let sessions: SessionMeta[]; |
| 41 | try { |
| 42 | sessions = await listSessionsForTab(tabID); |
| 43 | } catch (error) { |
| 44 | if (!isIntentCurrent(intentSeq)) return null; |
| 45 | throw error; |
| 46 | } |
| 47 | if (!isIntentCurrent(intentSeq)) return null; |
| 48 | |
| 49 | const session = sessions.find((candidate) => sessionIDFromPath(candidate.path) === sessionID); |
| 50 | if (!session) throw new Error("Task session is unavailable"); |
| 51 | return session; |
| 52 | } |
| 53 |