Skip to content

Commit f12abca

Browse files
authored
fix(app): sync the event stream only when live and keep the newest endpoint (#61765)
1 parent e4e55bd commit f12abca

21 files changed

Lines changed: 426 additions & 60 deletions

File tree

‎packages/app/src/composer/attachments/destination.ts‎

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -28,19 +28,25 @@ export function useAttachmentDestination(controls: Accessor<ComposerControls>) {
2828
const info = await sdk.api.server.info({ signal })
2929
// One directory per upload keeps the original filename without collisions; the server
3030
// normalizes the separators and returns the resolved path.
31-
const url = new URL("/api/experimental/fs/write", server.conn.http.url)
31+
const url = new URL("/api/experimental/fs/write", sdk.http.url)
3232
url.searchParams.set("location[directory]", location().directory)
3333
url.searchParams.set("path", `${info.paths.tmp}/uploads/${uuid()}/${file.name}`)
3434

35-
return write(url, file, server.conn.http.password, report, signal)
35+
return write(url, file, sdk.http.password, report, signal)
3636
},
3737
})
3838
}
3939

4040
// fetch cannot report upload progress and Chromium only streams request bodies over HTTP/2, so
4141
// the one request that needs both goes through XMLHttpRequest. The browser streams the File
4242
// from disk; nothing is buffered in the renderer.
43-
function write(url: URL, file: File, password: string | undefined, report: (loaded: number) => void, signal: AbortSignal) {
43+
function write(
44+
url: URL,
45+
file: File,
46+
password: string | undefined,
47+
report: (loaded: number) => void,
48+
signal: AbortSignal,
49+
) {
4450
return new Promise<string>((resolve, reject) => {
4551
if (signal.aborted) return reject(new DOMException("Upload aborted", "AbortError"))
4652
const xhr = new XMLHttpRequest()

‎packages/app/src/providers/connect/remote.test.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@ const contributed = {
88
status: { type: "ready", http: { url: "http://127.0.0.1:4096" } },
99
authenticate: () => false,
1010
managed: true,
11-
http: { url: "http://127.0.0.1:4096" },
1211
} as const
1312

1413
test("SSH disclosure uses the remote identity even with a loopback proxy", () => {

‎packages/app/src/runtime/plugin/host-apis.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -526,7 +526,7 @@ export function createPluginAttachment(apis: HostApis) {
526526
return live().sdk.url
527527
},
528528
get password() {
529-
return live().sdk.server.http.password
529+
return live().sdk.http.password
530530
},
531531
get client() {
532532
return live().sdk.api

‎packages/app/src/runtime/plugin/mounted-session.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export function createMountedSession(session: SessionModel) {
6969
return server.ctx.sdk.url
7070
},
7171
get password() {
72-
return server.conn.http.password
72+
return server.ctx.sdk.http.password
7373
},
7474
get client() {
7575
return server.ctx.sdk.api

‎packages/app/src/runtime/plugin/servers.tsx‎

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -30,9 +30,6 @@ import { renamedFrom } from "./stores"
3030
/** A server a plugin contributes. `key` is `${plugin}:${entry.id}`. */
3131
export type PluginServer = { readonly key: string; readonly plugin: string; readonly entry: ServerEntry }
3232

33-
// Where a contributed server's event stream starts before its plugin reports an endpoint; it never answers.
34-
const offline = { url: "http://127.0.0.1:0" }
35-
3633
// The last complete inventory of each plugin that contributes servers, without endpoints or credentials.
3734
const Inventories = Schema.Record(
3835
Schema.String,
@@ -211,14 +208,18 @@ function connection(initial: PluginServer) {
211208
get managed() {
212209
return !!entry().reconnect
213210
},
214-
get http() {
215-
return entry().http ?? offline
216-
},
217211
// Resolved per call: the connection outlives a reload of the plugin that provides it.
218212
get reconnect() {
219213
if (!entry().reconnect) return undefined
220214

221-
return (signal: AbortSignal) => entry().reconnect?.(signal) ?? Promise.resolve(entry().http ?? offline)
215+
return (signal: AbortSignal) => {
216+
const status = selectPluginStatus(untrack(machine))
217+
218+
return (
219+
entry().reconnect?.(signal) ??
220+
(status.type === "ready" ? Promise.resolve(status.http) : Promise.reject(new Error("Server is not ready")))
221+
)
222+
}
222223
},
223224
authenticate: (onConnected) => {
224225
if (!canAuthenticatePluginServer(untrack(machine))) return false

‎packages/app/src/runtime/server/client.tsx‎

Lines changed: 59 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { createRefCountMap } from "@/runtime/server/refcount"
1111
import { createRequestQueue } from "@/runtime/server/request-queue"
1212
import { ServerScope } from "@/runtime/server/scope"
1313
import { useServer } from "./current"
14+
import { createEndpointSyncState, transitionEndpointSync, type EndpointSyncEvent } from "./server-sync/endpoint-machine"
1415

1516
type OpenCodeEventMap = { [Type in OpenCodeEvent["type"]]: Extract<OpenCodeEvent, { type: Type }> }
1617

@@ -76,9 +77,13 @@ type ServerSDKBase = {
7677
event: OpenCodeEventSource
7778
}
7879

80+
// Where a plugin server's transport points until the plugin reports the server ready; it never answers. The server has
81+
// a controller, and so a transport, from the moment it is listed.
82+
const unready = { url: "http://127.0.0.1:0" }
83+
7984
function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerScope): ServerSDKBase {
8085
const platform = usePlatform()
81-
const transport = createServerTransport({ http: server.http, fetch: platform.fetch })
86+
const transport = createServerTransport({ http: ServerConnection.http(server) ?? unready, fetch: platform.fetch })
8287
const media = createMediaCache(() => transport.api)
8388
const serverKey = ServerConnection.key(server)
8489
setMediaBlobLoader(serverKey, (uri) => media.load(uri))
@@ -89,9 +94,38 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
8994

9095
const events = createOpenCodeEventSource()
9196
const reconnect = resolveEndpoint(server)
97+
// Read only by `dispatchEndpoint`, the transport's only writer.
98+
let endpoint = createEndpointSyncState(transport.http)
99+
100+
function dispatchEndpoint(event: EndpointSyncEvent) {
101+
const result = transitionEndpointSync(endpoint, event)
102+
endpoint = result.state
103+
result.effects.forEach((effect) => {
104+
if (effect.type === "transport.update") return void transport.update(effect.http)
105+
connection.internal.resync("Server endpoint changed")
106+
})
107+
}
92108

93109
const connection = createClientConnection(transport.api, {
94-
reconnect: reconnect ? async (signal) => transport.update(await reconnect(signal)) : undefined,
110+
// Returns the transport's client rather than the resolved one: when the plugin reported a newer endpoint while
111+
// this resolution ran, the stream connects to that one.
112+
reconnect: reconnect
113+
? async (signal) => {
114+
dispatchEndpoint({ type: "resolve.started" })
115+
116+
if (endpoint.type !== "resolving") return transport.api
117+
const attempt = endpoint.attempt
118+
const resolution = reconnect(signal)
119+
120+
void resolution.catch(() => dispatchEndpoint({ type: "resolve.failed", attempt }))
121+
122+
return resolution.then((http) => {
123+
dispatchEndpoint({ type: "resolve.succeeded", attempt, http })
124+
125+
return transport.api
126+
})
127+
}
128+
: undefined,
95129
flushInterval: 16,
96130
pageLifecycle: true,
97131
onEvent(event) {
@@ -111,17 +145,24 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
111145
if (server.type === "plugin" || server.type === "sidecar") {
112146
createEffect(
113147
on(
114-
() => `${server.http.url}\0${server.http.password ?? ""}`,
115148
() => {
116-
if (sameEndpoint(transport.http, server.http)) return
117-
transport.update(server.http)
118-
connection.internal.resync("Server endpoint changed")
149+
const http = ServerConnection.http(server)
150+
151+
return http && `${http.url}\0${http.password ?? ""}`
152+
},
153+
() => {
154+
const http = ServerConnection.http(server)
155+
156+
// A plugin server that stops being ready keeps its last endpoint until the plugin reports it ready again.
157+
if (http) dispatchEndpoint({ type: "endpoint.reported", http })
119158
},
120159
{ defer: true },
121160
),
122161
)
123162
}
124163

164+
onCleanup(() => dispatchEndpoint({ type: "disposed" }))
165+
125166
return {
126167
server,
127168
scope,
@@ -141,14 +182,22 @@ function createServerSdkContextBase(server: ServerConnection.Any, scope: ServerS
141182
}
142183

143184
/**
144-
* Where the event stream connects after a disconnect. A plugin's server can exist before the plugin reports its
145-
* endpoint (a server restored from the plugin's last inventory starts on a placeholder) and can move at any time, so
146-
* its stream always resolves the plugin's current endpoint, through the plugin's `reconnect` when it has one then.
185+
* Where the event stream connects after a disconnect. A plugin's server can exist before it is ready (a server restored
186+
* from the plugin's last inventory starts on `unready`) and can move at any time, so its stream always resolves the
187+
* plugin's current endpoint, through the plugin's `reconnect` when it has one then. A server that is not ready has none
188+
* to resolve, so the stream keeps retrying where it is.
147189
*/
148190
function resolveEndpoint(
149191
server: ServerConnection.Any,
150192
): ((signal: AbortSignal) => Promise<ServerConnection.HttpBase>) | undefined {
151-
if (server.type === "plugin") return (signal) => server.reconnect?.(signal) ?? Promise.resolve(server.http)
193+
if (server.type === "plugin")
194+
return (signal) => {
195+
const http = ServerConnection.http(server)
196+
197+
return (
198+
server.reconnect?.(signal) ?? (http ? Promise.resolve(http) : Promise.reject(new Error("Server is not ready")))
199+
)
200+
}
152201

153202
if (server.type === "sidecar") return server.reconnect
154203

‎packages/app/src/runtime/server/machine.test.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -113,14 +113,13 @@ test("a rejection of credentials the server has since replaced changes nothing",
113113
expect(selectServerCtx(late.state, key)?.name).toBe("ctx2")
114114
})
115115

116-
test("a contributed server has credentials to check only while it is ready, never its placeholder endpoint", () => {
116+
test("a contributed server has credentials to check only while it is ready", () => {
117117
const plugin = (status: ServerConnection.Plugin["status"]): ServerConnection.Plugin => ({
118118
type: "plugin",
119119
key: "ssh:box",
120120
plugin: "ssh",
121121
status,
122122
managed: true,
123-
http: { url: "http://127.0.0.1:0" },
124123
authenticate: () => false,
125124
})
126125

‎packages/app/src/runtime/server/registry.test.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ test("startup auth_token credentials override a persisted same-url server; witho
5555
})
5656

5757
expect(kept).toHaveLength(1)
58-
expect(kept[0]?.http).toEqual({ url, password: "saved" })
58+
expect(kept[0] && ServerConnection.http(kept[0])).toEqual({ url, password: "saved" })
5959
expect(kept[0]?.type === "http" ? kept[0].authToken : true).toBeUndefined()
6060
})
6161

@@ -71,14 +71,11 @@ test("treats WSL and mismatched-port loopback servers as remote connections", ()
7171
status: { type: "ready", http: { url: "http://127.0.0.1:4097" } },
7272
authenticate: () => false,
7373
managed: false,
74-
http: { url: "http://127.0.0.1:4097" },
7574
},
7675
windowsSidecar,
7776
),
7877
).toBe(false)
79-
expect(
80-
ServerConnection.local({ type: "sidecar", variant: "base", http: { url: windowsSidecar } }),
81-
).toBe(true)
78+
expect(ServerConnection.local({ type: "sidecar", variant: "base", http: { url: windowsSidecar } })).toBe(true)
8279
expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:28894" } }, windowsSidecar)).toBe(true)
8380
expect(ServerConnection.local({ type: "http", http: { url: "http://[::1]:28894" } }, windowsSidecar)).toBe(true)
8481
expect(ServerConnection.local({ type: "http", http: { url: "http://localhost:4096" } }, windowsSidecar)).toBe(false)

‎packages/app/src/runtime/server/registry.tsx‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ export function resolveServerList(input: {
115115
deduped.set(key, {
116116
...existing,
117117
...conn,
118-
http: { ...existing.http, ...conn.http },
118+
http: { ...ServerConnection.http(existing), ...conn.http },
119119
})
120120
else deduped.set(key, conn)
121121
}
@@ -172,11 +172,6 @@ export namespace ServerConnection {
172172
status: PluginServerStatus
173173
/** The plugin re-resolves the endpoint (e.g. a tunnel), so the connection can drop and come back. */
174174
managed: boolean
175-
/**
176-
* Where the event stream starts and follows: the plugin's last endpoint, or an unroutable placeholder before it
177-
* reports one. Everything else reads `ServerConnection.http`, which has an endpoint only while the server is ready.
178-
*/
179-
http: HttpBase
180175
reconnect?: (signal: AbortSignal) => Promise<HttpBase>
181176
/**
182177
* Starts sign-in while the server waits for it, or joins the one in progress; false when the server does not
@@ -319,7 +314,12 @@ export const { use: useServers, provider: ServersProvider } = createSimpleContex
319314
const current = (conn: ServerConnection.Any) =>
320315
ServerConnection.builtin(conn) || ServerConnection.key(conn) === props.canonicalLocalServer
321316

322-
const ownUrl = () => props.servers?.find(ServerConnection.builtin)?.http.url ?? props.canonicalLocalServer
317+
const ownUrl = () => {
318+
const builtin = props.servers?.find(ServerConnection.builtin)
319+
320+
return (builtin && ServerConnection.http(builtin)?.url) ?? props.canonicalLocalServer
321+
}
322+
323323
const local = (conn?: ServerConnection.Any) => ServerConnection.local(conn, ownUrl())
324324

325325
const label = (conn: ServerConnection.Any) =>

‎packages/app/src/runtime/server/server-sync/connection.ts‎

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,33 @@
1-
import { createEffect, type Accessor } from "solid-js"
1+
import { createEffect, onCleanup, untrack, type Accessor } from "solid-js"
22
import type { ServerConnectionStatus } from "../client"
3+
import { transitionConnectionSync, type ConnectionSyncEvent, type ConnectionSyncState } from "./machine"
34

45
export function createConnectionSync(input: {
56
status: Accessor<ServerConnectionStatus>
67
invalidate: () => void
7-
connected: (info: { reconnect: boolean }) => void
8+
connected: (info: { restart: boolean }) => void
89
}) {
10+
// Read only by `dispatch`; the effects run untracked, so their reads never re-run the status effect.
11+
let connection: ConnectionSyncState = { type: "idle" }
12+
13+
function dispatch(event: ConnectionSyncEvent) {
14+
const result = transitionConnectionSync(connection, event)
15+
connection = result.state
16+
result.effects.forEach((effect) => {
17+
if (effect.type === "invalidate") return input.invalidate()
18+
input.connected({ restart: effect.restart })
19+
})
20+
}
21+
922
createEffect(() => {
10-
if (input.status() === "connected") return
11-
input.invalidate()
23+
const status = input.status()
24+
untrack(() => dispatch({ type: "status.changed", status }))
1225
})
13-
14-
let connectedOnce = false
26+
onCleanup(() => dispatch({ type: "disposed" }))
1527

1628
function handleEvent(event: { type: string }) {
1729
if (event.type !== "server.connected") return
18-
input.connected({ reconnect: connectedOnce })
19-
connectedOnce = true
30+
dispatch({ type: "handshake.received" })
2031
}
2132

2233
return { handleEvent }

0 commit comments

Comments
 (0)