Line data Source code
1 : import { computed, effectScope, watch } from 'vue'
2 :
3 : import { api } from '@/scripts/api'
4 : import { assert } from '@/base/assert'
5 :
6 : import type { AgentDocFrameTransport } from './crdt/agentDocFrameTransport'
7 : import { createAgentDocFrameTransport } from './crdt/agentDocFrameTransport'
8 : import { agentSocketAuthParams } from './services/agent/agentAuth'
9 : import type { AgentEventSocket } from './services/agent/agentEventSource'
10 : import { createAgentEventSource } from './services/agent/agentEventSource'
11 :
12 : /** Agent transport resources whose lifetime is the page, not the Agent panel. */
13 : export interface AgentPageSession {
14 : /** The shared agent websocket. Reference-counts its own connection. */
15 : readonly events: AgentEventSocket
16 : /** The doc-frame tap over {@link events}, for the CRDT follower seam. */
17 : readonly docTransport: AgentDocFrameTransport
18 : /** Observe the signed-in identity changing, after the socket reconnects. */
19 : onIdentityChange(listener: () => void): () => void
20 : }
21 :
22 : export type SocketIdentity = readonly [
23 : account: string | null,
24 : workspace: string | null,
25 : hostWorkspace: string | null
26 : ]
27 :
28 : /** Reads the signed-in identity the socket authenticates as. */
29 : export type SocketIdentitySource = () => SocketIdentity
30 :
31 : /** Normalise the identity the socket authenticates as, collapsing absent to null. */
32 1 : export function toSocketIdentity(
33 : accountId: string | null | undefined,
34 : apiKeyUserId: string | null | undefined,
35 : workspaceId: string | null | undefined,
36 : hostWorkspaceId: string | null | undefined
37 : ): SocketIdentity {
38 1 : return [
39 : accountId ?? apiKeyUserId ?? null,
40 : workspaceId ?? null,
41 : hostWorkspaceId ?? null
42 : ]
43 : }
44 :
45 : /** Whether an identity tuple change should re-authenticate the socket. */
46 0 : export function needsReauthentication(
47 : [account, workspace, hostWorkspace]: SocketIdentity,
48 : [wasAccount, wasWorkspace, wasHostWorkspace]: SocketIdentity
49 : ): boolean {
50 0 : if (
51 : account === wasAccount &&
52 : workspace === wasWorkspace &&
53 : hostWorkspace === wasHostWorkspace
54 : )
55 0 : return false
56 0 : return !(
57 : workspace === null &&
58 : account === wasAccount &&
59 : account !== null &&
60 : hostWorkspace === null
61 : )
62 : }
63 :
64 : interface PageSessionInternals extends AgentPageSession {
65 : readonly stop: () => void
66 : }
67 :
68 1 : let session: PageSessionInternals | null = null
69 :
70 1 : function create(readIdentity: SocketIdentitySource): PageSessionInternals {
71 1 : assert(
72 : session === null,
73 : 'minted a second agent event source while one already exists for this page — the page session owns exactly one event source and one doc-frame transport for the page lifetime, see docs/adr/CRDT-FOLLOWER-0052-the-workflow-document-owns-the-follower-session.md Decision 2'
74 : )
75 1 : const listeners = new Set<() => void>()
76 :
77 1 : const pageScope = effectScope(true)
78 1 : const built = pageScope.run(() => {
79 1 : const events = createAgentEventSource({
80 : endpoint: api.apiURL('/agent/events'),
81 : getAuthParams: agentSocketAuthParams
82 : })
83 1 : const docTransport = createAgentDocFrameTransport(events)
84 :
85 1 : const identity = computed<SocketIdentity>(() => readIdentity())
86 1 : watch(identity, (next, previous) => {
87 0 : if (!needsReauthentication(next, previous)) return
88 0 : events.reconnect()
89 0 : listeners.forEach((listener) => listener())
90 : })
91 1 : return { events, docTransport }
92 : })
93 1 : assert(
94 : built !== undefined,
95 : 'the agent page session scope was already stopped before it built the transport — see docs/adr/CRDT-FOLLOWER-0052-the-workflow-document-owns-the-follower-session.md Stage 1a'
96 : )
97 1 : const { events, docTransport } = built
98 :
99 1 : return {
100 : events,
101 : docTransport,
102 : onIdentityChange(listener) {
103 1 : listeners.add(listener)
104 1 : return () => listeners.delete(listener)
105 : },
106 : stop() {
107 0 : pageScope.stop()
108 0 : listeners.clear()
109 0 : docTransport.destroy()
110 : }
111 : }
112 : }
113 :
114 : /** Resolve the page's agent transport, creating it on first use. Only the first call's `readIdentity` is installed. */
115 1 : export function useAgentPageSession(
116 : readIdentity: SocketIdentitySource
117 : ): AgentPageSession {
118 1 : session ??= create(readIdentity)
119 1 : return session
120 : }
121 :
122 : /** Tear down the page's agent transport. Never call this on panel close. */
123 : export function destroyAgentPageSession(): void {
124 : session?.stop()
125 : session = null
126 : }
|