GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(app): support current event transport · anomalyco/opencode@c5989d7

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • packages/app
    • e2e
      • regression
        • session-timeline-transport.spec.ts
      • utils
        • mock-server.ts
        • sse-transport.ts
    • src/context
      • server-sdk.test.ts
      • server-sdk.tsx
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎packages/app/e2e/regression/session-timeline-transport.spec.ts‎

Copy file name to clipboardExpand all lines: packages/app/e2e/regression/session-timeline-transport.spec.ts
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ test("reconnects after a stream error", async ({ page }) => {
8989
expect((await timeline.transport.connections())[0]?.endedBy).toBe("error")
9090
})
9191

92-
test("records event IDs and reconnect Last-Event-ID headers", async ({ page }) => {
92+
test("does not request replay when reconnecting the volatile V2 event stream", async ({ page }) => {
9393
const timeline = await setupTimeline(page, { eventRetry: 10 })
9494
const first = await timeline.transport.send(partUpdated(textPart("prt_transport_id", "event with id")), {
9595
id: "timeline-event-7",
@@ -100,7 +100,7 @@ test("records event IDs and reconnect Last-Event-ID headers", async ({ page }) =
100100
const connection = await timeline.transport.waitForConnection({ after: first.connectionID })
101101

102102
expect(first.eventID).toBe("timeline-event-7")
103-
expect(connection.headers["last-event-id"]).toBe("timeline-event-7")
103+
expect(connection.headers["last-event-id"]).toBeUndefined()
104104
})
105105

106106
test("passes through non-event fetches", async ({ page }) => {
Collapse file

‎packages/app/e2e/utils/mock-server.ts‎

Copy file name to clipboardExpand all lines: packages/app/e2e/utils/mock-server.ts
+242-9Lines changed: 242 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -54,14 +54,18 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
5454
if (url.port !== targetPort && url.port !== appPort) return route.fallback()
5555

5656
const path = url.pathname
57-
if (path === "/global/event" || path === "/event") return sse(route, config.events?.(), config.eventRetry)
57+
if (path === "/global/event" || path === "/event" || path === "/api/event") {
58+
const events = config.events?.()
59+
return sse(
60+
route,
61+
path === "/api/event"
62+
? [{ id: "evt_mock_connected", type: "server.connected", data: {} }, ...(events?.map(currentEvent) ?? [])]
63+
: events,
64+
config.eventRetry,
65+
)
66+
}
5867
if (path === "/global/health") return json(route, { healthy: true })
59-
if (path === "/api/session")
60-
return json(route, {
61-
data: config.sessions.map((session) => v2Session(session, config.directory)),
62-
cursor: {},
63-
})
64-
if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: false })
68+
if (path === "/experimental/capabilities") return json(route, { backgroundSubagents: true })
6569
if (path === "/permission")
6670
return json(route, typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? []))
6771
if (path === "/question")
@@ -89,10 +93,122 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
8993
},
9094
data: [],
9195
})
96+
if (path === "/api/agent")
97+
return json(route, {
98+
location: location(config),
99+
data: [
100+
{
101+
id: "build",
102+
name: "Build",
103+
mode: "primary",
104+
hidden: false,
105+
request: { settings: {}, headers: {}, body: {} },
106+
permissions: [],
107+
},
108+
],
109+
})
110+
if (path === "/api/command") return json(route, { location: location(config), data: [] })
111+
if (path === "/api/mcp") return json(route, { location: location(config), data: [] })
112+
if (path === "/api/mcp/resource")
113+
return json(route, { location: location(config), data: { resources: [], templates: [] } })
114+
const integration = path.match(/^\/api\/integration\/([^/]+)$/)?.[1]
115+
if (integration && route.request().method() === "GET")
116+
return json(route, {
117+
location: location(config),
118+
data: { id: integration, name: integration, methods: [{ type: "key", label: "API key" }], connections: [] },
119+
})
120+
if (/^\/api\/integration\/[^/]+\/connect\/key$/.test(path) && route.request().method() === "POST")
121+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
122+
if (path === "/api/project") return json(route, [config.project])
123+
if (path === "/api/project/current")
124+
return json(route, { id: (config.project as { id?: string }).id, directory: config.directory })
125+
if (path.startsWith("/api/project/") && route.request().method() === "PATCH") return json(route, config.project)
126+
if (path === "/api/path")
127+
return json(route, {
128+
state: config.directory,
129+
config: config.directory,
130+
worktree: config.directory,
131+
directory: config.directory,
132+
home: "C:/OpenCode",
133+
})
134+
if (path === "/api/permission/request")
135+
return json(route, {
136+
location: location(config),
137+
data: (typeof config.permissions === "function" ? config.permissions() : (config.permissions ?? [])).map(
138+
currentPermission,
139+
),
140+
})
141+
if (path === "/api/question/request")
142+
return json(route, {
143+
location: location(config),
144+
data: typeof config.questions === "function" ? config.questions() : (config.questions ?? []),
145+
})
146+
if (path === "/api/vcs")
147+
return json(route, { location: location(config), data: { branch: "main", defaultBranch: "main" } })
148+
if (path === "/api/vcs/status") return json(route, { location: location(config), data: [] })
149+
if (path === "/api/vcs/diff") return json(route, { location: location(config), data: config.vcsDiff ?? [] })
150+
if (path === "/api/pty/shells") return json(route, { location: location(config), data: [] })
151+
if (/^\/api\/pty\/[^/]+\/connect-token$/.test(path))
152+
return json(route, { location: location(config), data: { ticket: "e2e-ticket", expires_in: 60 } })
92153
if (emptyObject.has(path)) return json(route, {})
93154
if (emptyList.has(path)) return json(route, [])
155+
if (path === "/api/session") {
156+
const directory = url.searchParams.get("directory")
157+
const parentID = url.searchParams.get("parentID")
158+
const limit = Number(url.searchParams.get("limit") ?? 50)
159+
const offset = Number(url.searchParams.get("cursor") ?? 0)
160+
const sessions = config.sessions
161+
.filter((session) => !directory || session.directory === directory)
162+
.filter((session) => parentID !== "null" || session.parentID === undefined)
163+
.filter((session) => {
164+
const search = url.searchParams.get("search")?.toLowerCase()
165+
return !search || String(session.title ?? "").toLowerCase().includes(search)
166+
})
167+
const ordered = url.searchParams.get("order") === "asc" ? sessions.toReversed() : sessions
168+
const data = ordered.slice(offset, offset + limit)
169+
const next = offset + limit < ordered.length ? String(offset + limit) : undefined
170+
return json(route, {
171+
data: data.map((session) => currentSession(session, config.directory)),
172+
cursor: { next },
173+
})
174+
}
175+
if (path === "/api/session/active") {
176+
const statuses = (config.sessionStatus ?? {}) as Record<string, { type?: string }>
177+
return json(route, {
178+
data: Object.fromEntries(
179+
Object.entries(statuses).flatMap(([id, status]) => (status.type === "idle" ? [] : [[id, { type: "running" }]])),
180+
),
181+
})
182+
}
183+
if (/^\/api\/session\/[^/]+\/shell$/.test(path) && route.request().method() === "POST") {
184+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
185+
}
186+
if (/^\/api\/session\/[^/]+\/question\/[^/]+\/(reply|reject)$/.test(path) && route.request().method() === "POST") {
187+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
188+
}
189+
if (/^\/api\/session\/[^/]+\/permission\/[^/]+\/reply$/.test(path) && route.request().method() === "POST") {
190+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
191+
}
192+
if (
193+
/^\/api\/session\/[^/]+\/(archive|rename|interrupt|revert\/clear|revert\/commit)$/.test(path) &&
194+
route.request().method() === "POST"
195+
) {
196+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
197+
}
198+
if (/^\/api\/session\/[^/]+$/.test(path) && route.request().method() === "DELETE") {
199+
return route.fulfill({ status: 204, headers: { "access-control-allow-origin": "*" } })
200+
}
94201
if (path in staticRoutes) return json(route, staticRoutes[path])
95202

203+
const currentSessionMatch = path.match(/^\/api\/session\/([^/]+)$/)
204+
if (currentSessionMatch) {
205+
const session = config.sessions.find((item) => item.id === currentSessionMatch[1])
206+
if (!session) return json(route, { error: "Session not found" }, undefined, 404)
207+
return json(route, {
208+
data: currentSession(session, config.directory),
209+
})
210+
}
211+
96212
const sessionMatch = path.match(/^\/session\/([^/]+)$/)
97213
if (sessionMatch) {
98214
const session = config.sessions.find((s) => s.id === sessionMatch[1])
@@ -115,6 +231,24 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
115231
if (todoMatch) return json(route, config.todos?.(todoMatch[1]!) ?? [])
116232
if (/^\/session\/[^/]+\/(children|diff)$/.test(path)) return json(route, [])
117233

234+
const currentMessagesMatch = path.match(/^\/api\/session\/([^/]+)\/message$/)
235+
if (currentMessagesMatch) {
236+
const token = url.searchParams.get("cursor") ?? undefined
237+
const before = token ? cursors.get(token) : undefined
238+
if (token && !before) return json(route, { error: "Invalid cursor" }, undefined, 400)
239+
config.onMessages?.({ sessionID: currentMessagesMatch[1], before, phase: "start" })
240+
await config.beforeMessagesResponse?.({ sessionID: currentMessagesMatch[1]!, before })
241+
if (config.messageDelay !== undefined) await new Promise((resolve) => setTimeout(resolve, config.messageDelay))
242+
const pageData = config.pageMessages(currentMessagesMatch[1], Number(url.searchParams.get("limit") ?? 50), before)
243+
config.onMessages?.({ sessionID: currentMessagesMatch[1], before, phase: "end" })
244+
const cursor = pageData.cursor ? `cursor_${++nextCursor}` : undefined
245+
if (cursor) cursors.set(cursor, pageData.cursor!)
246+
return json(route, {
247+
data: pageData.items.map(currentMessage).reverse(),
248+
cursor: { next: cursor },
249+
})
250+
}
251+
118252
const messagesMatch = path.match(/^\/session\/([^/]+)\/message$/)
119253
if (messagesMatch) {
120254
const token = url.searchParams.get("before") ?? undefined
@@ -137,12 +271,36 @@ export async function mockOpenCodeServer(page: Page, config: MockServerConfig) {
137271
})
138272
}
139273

140-
function v2Session(session: { id: string } & Record<string, unknown>, fallbackDirectory: string) {
274+
function location(config: MockServerConfig) {
275+
return {
276+
directory: config.directory,
277+
project: { id: (config.project as { id?: string }).id, directory: config.directory },
278+
}
279+
}
280+
281+
function currentPermission(value: unknown) {
282+
const permission = value as Record<string, unknown>
283+
if (permission.action) return permission
284+
const tool = permission.tool as { messageID?: string; callID?: string } | undefined
285+
return {
286+
id: permission.id,
287+
sessionID: permission.sessionID,
288+
action: permission.permission,
289+
resources: permission.patterns ?? [],
290+
save: permission.always,
291+
metadata: permission.metadata,
292+
source: tool?.messageID && tool.callID ? { type: "tool", messageID: tool.messageID, callID: tool.callID } : undefined,
293+
}
294+
}
295+
296+
export function currentSession(session: { id: string } & Record<string, unknown>, fallbackDirectory?: string) {
141297
const time = session.time && typeof session.time === "object" ? session.time : {}
142298
return {
143299
id: session.id,
144300
parentID: session.parentID,
145301
projectID: session.projectID ?? "project",
302+
agent: session.agent ?? "build",
303+
model: session.model ?? { id: "mock-model", providerID: "mock-provider" },
146304
cost: session.cost ?? 0,
147305
tokens: session.tokens ?? { input: 0, output: 0, reasoning: 0, cache: { read: 0, write: 0 } },
148306
time: {
@@ -157,7 +315,67 @@ function v2Session(session: { id: string } & Record<string, unknown>, fallbackDi
157315
directory: typeof session.directory === "string" ? session.directory : fallbackDirectory,
158316
...(typeof session.workspaceID === "string" ? { workspaceID: session.workspaceID } : {}),
159317
},
160-
...(typeof session.path === "string" ? { subpath: session.path } : {}),
318+
subpath: session.path,
319+
revert: session.revert,
320+
}
321+
}
322+
323+
function currentMessage(value: unknown) {
324+
const item = value as {
325+
info: Record<string, unknown> & { id: string; role: "user" | "assistant"; time: { created: number } }
326+
parts: Array<Record<string, unknown> & { type: string }>
327+
}
328+
if (item.info.role === "user") {
329+
return {
330+
id: item.info.id,
331+
type: "user",
332+
time: item.info.time,
333+
text: item.parts
334+
.flatMap((part) => (part.type === "text" && typeof part.text === "string" ? [part.text] : []))
335+
.join("\n"),
336+
}
337+
}
338+
return {
339+
id: item.info.id,
340+
type: "assistant",
341+
time: item.info.time,
342+
agent: item.info.agent ?? "build",
343+
model: { id: item.info.modelID ?? "model", providerID: item.info.providerID ?? "provider" },
344+
cost: item.info.cost,
345+
tokens: item.info.tokens,
346+
error: item.info.error,
347+
content: item.parts.flatMap<unknown>((part) => {
348+
if (part.type === "text" || part.type === "reasoning") return [{ type: part.type, text: part.text ?? "" }]
349+
if (part.type !== "tool") return []
350+
const state = part.state as Record<string, unknown>
351+
return [
352+
{
353+
type: "tool",
354+
id: part.id,
355+
name: part.tool,
356+
time: state.time ?? { created: item.info.time.created },
357+
state:
358+
state.status === "pending"
359+
? { status: "streaming", input: state.raw ?? JSON.stringify(state.input ?? {}) }
360+
: state.status === "completed"
361+
? {
362+
status: "completed",
363+
input: state.input ?? {},
364+
structured: state.metadata ?? {},
365+
content: [{ type: "text", text: state.output ?? "" }],
366+
}
367+
: state.status === "error"
368+
? {
369+
status: "error",
370+
input: state.input ?? {},
371+
structured: state.metadata ?? {},
372+
content: [],
373+
error: { type: "ToolError", message: state.error ?? "Tool failed" },
374+
}
375+
: { status: "running", input: state.input ?? {}, structured: state.metadata ?? {}, content: [] },
376+
},
377+
]
378+
}),
161379
}
162380
}
163381

@@ -181,3 +399,18 @@ function sse(route: Route, events?: unknown[], retry?: number) {
181399
body: `${retry === undefined ? "" : `retry: ${retry}\n\n`}${events?.map((event) => `data: ${JSON.stringify(event)}\n\n`).join("") || ": ok\n\n"}`,
182400
})
183401
}
402+
403+
function currentEvent(input: unknown) {
404+
if (!input || typeof input !== "object" || !("payload" in input)) return input
405+
const envelope = input as { directory?: string; payload?: unknown }
406+
if (!envelope.payload || typeof envelope.payload !== "object") return input
407+
const payload = envelope.payload as { id?: string; type?: string; properties?: unknown }
408+
if (!payload.type) return input
409+
return {
410+
id: payload.id ?? `evt_mock_${Date.now()}`,
411+
created: Date.now(),
412+
type: payload.type,
413+
data: payload.properties ?? {},
414+
location: envelope.directory && envelope.directory !== "global" ? { directory: envelope.directory } : undefined,
415+
}
416+
}
Collapse file

‎packages/app/e2e/utils/sse-transport.ts‎

Copy file name to clipboardExpand all lines: packages/app/e2e/utils/sse-transport.ts
+30-7Lines changed: 30 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import type { Page } from "@playwright/test"
33
export type SseConnectionRecord = {
44
id: number
55
url: string
6-
path: "/global/event" | "/event"
6+
path: "/global/event" | "/event" | "/api/event"
77
headers: Record<string, string>
88
openedAt: number
99
endedAt?: number
@@ -93,6 +93,20 @@ export async function installSseTransport<T>(
9393
eventOptions.retry === undefined ? "" : `retry: ${eventOptions.retry}\n`,
9494
`data: ${JSON.stringify(payload)}\n\n`,
9595
].join("")
96+
const currentEvent = (input: unknown) => {
97+
if (!input || typeof input !== "object" || !("payload" in input)) return input
98+
const envelope = input as { directory?: string; payload?: unknown }
99+
if (!envelope.payload || typeof envelope.payload !== "object") return input
100+
const payload = envelope.payload as { id?: string; type?: string; properties?: unknown }
101+
if (!payload.type) return input
102+
return {
103+
id: payload.id ?? `evt_mock_${Date.now()}`,
104+
created: Date.now(),
105+
type: payload.type,
106+
data: payload.properties ?? {},
107+
location: envelope.directory && envelope.directory !== "global" ? { directory: envelope.directory } : undefined,
108+
}
109+
}
96110
const acknowledge = (
97111
connection: Connection,
98112
bytes: number,
@@ -140,14 +154,14 @@ export async function installSseTransport<T>(
140154
output.forEach((chunk) => connection.controller.enqueue(chunk))
141155
return acknowledge(connection, input.bytes.length, output.length)
142156
}
143-
const encoded = input.deliveries.map((delivery) => ({
144-
delivery,
145-
bytes: encoder.encode(frame(delivery.payload, delivery.options)),
146-
}))
157+
const encoded = input.deliveries.map((delivery) => {
158+
const payload = connection.path === "/api/event" ? currentEvent(delivery.payload) : delivery.payload
159+
return { delivery, payload, bytes: encoder.encode(frame(payload, delivery.options)) }
160+
})
147161
encoded.forEach((item) => marker(item.delivery.options?.marker))
148162
if (input.burst) {
149163
const bytes = encoder.encode(
150-
encoded.map((item) => frame(item.delivery.payload, item.delivery.options)).join(""),
164+
encoded.map((item) => frame(item.payload, item.delivery.options)).join(""),
151165
)
152166
connection.controller.enqueue(bytes)
153167
return encoded.map((item) => acknowledge(connection, item.bytes.byteLength, 1, item.delivery.options?.id))
@@ -161,7 +175,10 @@ export async function installSseTransport<T>(
161175
const fetch = (input: RequestInfo | URL, init?: RequestInit) => {
162176
const request = new Request(input, init)
163177
const url = new URL(request.url)
164-
if (url.origin !== server || (url.pathname !== "/global/event" && url.pathname !== "/event"))
178+
if (
179+
url.origin !== server ||
180+
(url.pathname !== "/global/event" && url.pathname !== "/event" && url.pathname !== "/api/event")
181+
)
165182
return originalFetch(request)
166183

167184
const id = ++nextConnectionID
@@ -177,6 +194,12 @@ export async function installSseTransport<T>(
177194
record.controller = controller
178195
connections.push(record)
179196
if (retry !== undefined) controller.enqueue(encoder.encode(`retry: ${retry}\n\n`))
197+
if (url.pathname === "/api/event")
198+
controller.enqueue(
199+
encoder.encode(
200+
frame({ id: `evt_mock_connected_${id}`, type: "server.connected", data: {} }),
201+
),
202+
)
180203
request.signal.addEventListener(
181204
"abort",
182205
() => {

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.