-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathglance.test.ts
More file actions
281 lines (228 loc) · 7.8 KB
/
glance.test.ts
File metadata and controls
281 lines (228 loc) · 7.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import { describe, it, expect, vi, afterEach } from "vitest"
// Mock @opencode-ai/plugin — `tool()` is a passthrough that returns the config
vi.mock("@opencode-ai/plugin", () => ({
tool: (config: any) => config,
}))
// Helper: dynamically import the plugin to get fresh module-level state
async function loadPlugin() {
vi.resetModules()
vi.doMock("@opencode-ai/plugin", () => ({
tool: (config: any) => config,
}))
const mod = await import("./glance.js")
return mod.GlancePlugin
}
function mockClient() {
return { client: {} }
}
function mockContext(abort?: AbortSignal) {
return {
metadata: vi.fn(),
abort,
}
}
/**
* Build a ReadableStream that emits the given SSE chunks, then hangs forever.
* The hang prevents the background loop from spinning in a tight reconnect cycle.
*/
function sseStream(events: string[]) {
const encoder = new TextEncoder()
let i = 0
return new ReadableStream({
pull(controller) {
if (i < events.length) {
controller.enqueue(encoder.encode(events[i]))
i++
return
}
// Hang forever after all events are emitted
return new Promise(() => {})
},
})
}
function cleanupWaiters() {
for (const key of Object.keys(globalThis)) {
if (key.startsWith("__glance_waiter_")) {
delete (globalThis as any)[key]
}
}
}
function getOpenCodeWaiterKeys(): string[] {
return Object.keys(globalThis).filter((key) =>
key.startsWith("__glance_waiter_opencode_"),
)
}
/**
* URL-aware fetch mock. Routes by URL so both the background loop and
* tool calls get correct responses regardless of call order.
*/
function routedFetch(opts: {
session?: { id: string; url: string }
sessionError?: number
sseEvents?: string[]
}) {
return vi.fn(async (url: string, _init?: any) => {
if (url === "https://glance.sh/api/session") {
if (opts.sessionError) {
return { ok: false, status: opts.sessionError }
}
return {
ok: true,
json: async () => opts.session ?? { id: "test-id", url: "/s/test-id" },
}
}
if (typeof url === "string" && url.includes("/events")) {
return {
ok: true,
body: sseStream(opts.sseEvents ?? []),
}
}
return { ok: false, status: 404 }
})
}
describe("opencode glance plugin", () => {
afterEach(() => {
vi.restoreAllMocks()
cleanupWaiters()
})
describe("glance tool", () => {
it("creates a session and returns the URL", async () => {
vi.stubGlobal(
"fetch",
routedFetch({ session: { id: "abc123", url: "/s/abc123" } }),
)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
const result = await plugin.tool.glance.execute({})
expect(result).toContain("https://glance.sh/s/abc123")
expect(result).toContain("Session ready")
})
it("reuses an existing session on second call", async () => {
const fetchFn = routedFetch({
session: { id: "abc123", url: "/s/abc123" },
})
vi.stubGlobal("fetch", fetchFn)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
// Let background loop create its session
await new Promise((r) => setTimeout(r, 20))
const r1 = await plugin.tool.glance.execute({})
const r2 = await plugin.tool.glance.execute({})
expect(r1).toContain("/s/abc123")
expect(r2).toContain("/s/abc123")
})
it("returns error when session creation fails", async () => {
vi.stubGlobal("fetch", routedFetch({ sessionError: 500 }))
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
// Wait for background loop to fail
await new Promise((r) => setTimeout(r, 50))
const result = await plugin.tool.glance.execute({})
expect(result).toContain("Failed to create session")
})
})
describe("glance_wait tool", () => {
it("returns error when no session exists", async () => {
vi.stubGlobal(
"fetch",
vi.fn().mockRejectedValue(new Error("no network")),
)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
// Give background loop time to fail
await new Promise((r) => setTimeout(r, 50))
const ctx = mockContext()
const result = await plugin.tool.glance_wait.execute({}, ctx)
expect(result).toContain("No active session")
})
it("returns image URL when image is dispatched", async () => {
const imagePayload = JSON.stringify({
url: "https://glance.sh/tok123.png",
expiresAt: Date.now() + 60_000,
})
vi.stubGlobal(
"fetch",
routedFetch({
session: { id: "sess1", url: "/s/sess1" },
sseEvents: [
`event: connected\ndata: {}\n\n`,
`event: image\ndata: ${imagePayload}\n\n`,
],
}),
)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
// Ensure session exists
await plugin.tool.glance.execute({})
const ctx = mockContext()
const result = await plugin.tool.glance_wait.execute({}, ctx)
expect(result).toContain("https://glance.sh/tok123.png")
expect(ctx.metadata).toHaveBeenCalledWith(
expect.objectContaining({
title: expect.stringContaining("Waiting for paste"),
}),
)
})
it("parses image events split across SSE chunks", async () => {
const expiresAt = Date.now() + 60_000
vi.stubGlobal(
"fetch",
routedFetch({
session: { id: "sess-chunked", url: "/s/sess-chunked" },
sseEvents: [
'event: image\ndata: {"url":"https://glance.sh/chunked.png",',
`"expiresAt":${expiresAt}}\n\n`,
],
}),
)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
await plugin.tool.glance.execute({})
const ctx = mockContext()
const result = await plugin.tool.glance_wait.execute({}, ctx)
expect(result).toContain("https://glance.sh/chunked.png")
})
it("registers distinct waiters even within the same millisecond", async () => {
vi.stubGlobal(
"fetch",
routedFetch({
session: { id: "sess-waiters", url: "/s/sess-waiters" },
}),
)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
await plugin.tool.glance.execute({})
const dateNowSpy = vi.spyOn(Date, "now").mockReturnValue(123)
const ac1 = new AbortController()
const ac2 = new AbortController()
const wait1 = plugin.tool.glance_wait.execute({}, mockContext(ac1.signal))
const wait2 = plugin.tool.glance_wait.execute({}, mockContext(ac2.signal))
expect(getOpenCodeWaiterKeys()).toHaveLength(2)
ac1.abort()
ac2.abort()
await expect(Promise.all([wait1, wait2])).resolves.toEqual([
"Session timed out. Ask the user to paste an image at https://glance.sh/s/sess-waiters",
"Session timed out. Ask the user to paste an image at https://glance.sh/s/sess-waiters",
])
dateNowSpy.mockRestore()
})
it("returns timeout message when aborted", async () => {
vi.stubGlobal(
"fetch",
routedFetch({
session: { id: "sess2", url: "/s/sess2" },
}),
)
const GlancePlugin = await loadPlugin()
const plugin = await GlancePlugin(mockClient())
await plugin.tool.glance.execute({})
const ac = new AbortController()
const ctx = mockContext(ac.signal)
const waitPromise = plugin.tool.glance_wait.execute({}, ctx)
await new Promise((r) => setTimeout(r, 50))
ac.abort()
const result = await waitPromise
expect(result).toContain("timed out")
})
})
})