mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-17 23:24:00 +03:00
fix(desktop): model migration poll, picked files, plugin host follow and zoom as state machines (#61926)
This commit is contained in:
committed by
GitHub
Unverified
parent
c3f9fbbce3
commit
0d18f558b0
@@ -0,0 +1,137 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createPickedFileState,
|
||||
transitionPickedFiles,
|
||||
type PickedFileCommand,
|
||||
type PickedFileEvent,
|
||||
type PickedFileState,
|
||||
} from "./attachment-picker-machine"
|
||||
|
||||
// Folds events through the machine and keeps the commands of each step.
|
||||
function replay(events: readonly PickedFileEvent[], from = createPickedFileState()) {
|
||||
return events.reduce<{ state: PickedFileState; commands: (readonly PickedFileCommand[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionPickedFiles(result.state, event)
|
||||
|
||||
return { state: next.state, commands: [...result.commands, next.commands] }
|
||||
},
|
||||
{ state: from, commands: [] },
|
||||
)
|
||||
}
|
||||
|
||||
// Sender 1 opens dialog 1 and is granted `paths` under token "t" with a 10 byte budget.
|
||||
const granted = (paths: readonly string[]): PickedFileEvent[] => [
|
||||
{ type: "picker.opened", sender: 1 },
|
||||
{ type: "selection.granted", picker: 1, token: "t", paths, budget: 10 },
|
||||
]
|
||||
|
||||
const bytes = (length: number) => new ArrayBuffer(length)
|
||||
|
||||
describe("picked file authorizations", () => {
|
||||
test("claims a file while it reads and refuses a second read of it", () => {
|
||||
const run = replay([
|
||||
...granted(["a.txt"]),
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(2)).toEqual([
|
||||
[{ type: "read", attempt: 2, maxBytes: 10 }],
|
||||
[{ type: "reject", reason: "not-selected" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("gives a file back without charging the budget when its read fails or is cancelled", () => {
|
||||
const run = replay([
|
||||
...granted(["a.txt"]),
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "read.failed", attempt: 2, token: "t", path: "a.txt" },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "read.cancelled", attempt: 3, token: "t", path: "a.txt" },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "read.succeeded", attempt: 4, token: "t", path: "a.txt", bytes: bytes(10) },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(2)).toEqual([
|
||||
[{ type: "read", attempt: 2, maxBytes: 10 }],
|
||||
[{ type: "reject", reason: "read-failed" }],
|
||||
[{ type: "read", attempt: 3, maxBytes: 10 }],
|
||||
[],
|
||||
[{ type: "read", attempt: 4, maxBytes: 10 }],
|
||||
[{ type: "unwatch-sender", sender: 1 }, { type: "resolve" }],
|
||||
[{ type: "reject", reason: "not-selected" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("keeps concurrent reads of one selection within its budget", () => {
|
||||
const run = replay([
|
||||
...granted(["a.txt", "b.txt"]),
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "b.txt" },
|
||||
{ type: "read.succeeded", attempt: 2, token: "t", path: "a.txt", bytes: bytes(6) },
|
||||
{ type: "read.succeeded", attempt: 3, token: "t", path: "b.txt", bytes: bytes(6) },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "b.txt" },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(2)).toEqual([
|
||||
[{ type: "read", attempt: 2, maxBytes: 10 }],
|
||||
[{ type: "read", attempt: 3, maxBytes: 10 }],
|
||||
[{ type: "resolve" }],
|
||||
[{ type: "reject", reason: "size-limit" }],
|
||||
[{ type: "read", attempt: 4, maxBytes: 4 }],
|
||||
])
|
||||
})
|
||||
|
||||
test("drops a reloaded renderer's selections and dialogs and keeps other renderers'", () => {
|
||||
const run = replay([
|
||||
...granted(["a.txt"]),
|
||||
{ type: "picker.opened", sender: 1 },
|
||||
{ type: "picker.opened", sender: 2 },
|
||||
{ type: "selection.granted", picker: 3, token: "u", paths: ["b.txt"], budget: 10 },
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "sender.cleared", sender: 1 },
|
||||
{ type: "read.succeeded", attempt: 4, token: "t", path: "a.txt", bytes: bytes(1) },
|
||||
{ type: "selection.granted", picker: 2, token: "v", paths: ["c.txt"], budget: 10 },
|
||||
{ type: "read.requested", sender: 2, token: "u", path: "b.txt" },
|
||||
])
|
||||
|
||||
expect(run.commands[0]).toEqual([
|
||||
{ type: "watch-sender", sender: 1 },
|
||||
{ type: "picker-opened", picker: 1 },
|
||||
])
|
||||
expect(run.commands.slice(6)).toEqual([
|
||||
[{ type: "unwatch-sender", sender: 1 }],
|
||||
[{ type: "reject", reason: "not-selected" }],
|
||||
[],
|
||||
[{ type: "read", attempt: 5, maxBytes: 10 }],
|
||||
])
|
||||
})
|
||||
|
||||
test("unwatches every renderer and refuses late results once disposed", () => {
|
||||
const run = replay([
|
||||
...granted(["a.txt"]),
|
||||
{ type: "read.requested", sender: 1, token: "t", path: "a.txt" },
|
||||
{ type: "picker.opened", sender: 2 },
|
||||
{ type: "disposed" },
|
||||
{ type: "read.succeeded", attempt: 2, token: "t", path: "a.txt", bytes: bytes(1) },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(4)).toEqual([
|
||||
[
|
||||
{ type: "unwatch-sender", sender: 2 },
|
||||
{ type: "unwatch-sender", sender: 1 },
|
||||
],
|
||||
[{ type: "reject", reason: "not-selected" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("ignores a release from another renderer and stale results", () => {
|
||||
const start = replay([...granted(["a.txt"])]).state
|
||||
|
||||
expect(transitionPickedFiles(start, { type: "selection.released", sender: 2, token: "t" }).state).toBe(start)
|
||||
expect(transitionPickedFiles(start, { type: "read.cancelled", attempt: 9, token: "t", path: "a.txt" }).state).toBe(
|
||||
start,
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
// A renderer may read each file it picked once, within the selection's byte budget. A read claims its file until it
|
||||
// settles: a failed or cancelled read gives the file back, so the renderer can retry it.
|
||||
export type PickedPath = { readonly status: "unread" } | { readonly status: "reading"; readonly attempt: number }
|
||||
|
||||
export type PickedSelection = {
|
||||
readonly sender: number
|
||||
readonly remaining: number
|
||||
readonly files: ReadonlyMap<string, PickedPath>
|
||||
}
|
||||
|
||||
// `pickers` are native file dialogs still open, by id, with the renderer that opened them. A renderer that reloads or
|
||||
// closes loses its open dialogs and selections.
|
||||
export type PickedFileState =
|
||||
| {
|
||||
readonly status: "open"
|
||||
readonly nextAttempt: number
|
||||
readonly pickers: ReadonlyMap<number, number>
|
||||
readonly selections: ReadonlyMap<string, PickedSelection>
|
||||
}
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type PickedFileEvent =
|
||||
| { readonly type: "picker.opened"; readonly sender: number }
|
||||
| { readonly type: "picker.closed"; readonly picker: number }
|
||||
| {
|
||||
readonly type: "selection.granted"
|
||||
readonly picker: number
|
||||
readonly token: string
|
||||
readonly paths: readonly string[]
|
||||
readonly budget: number
|
||||
}
|
||||
| { readonly type: "read.requested"; readonly sender: number; readonly token: string; readonly path: string }
|
||||
| {
|
||||
readonly type: "read.succeeded"
|
||||
readonly attempt: number
|
||||
readonly token: string
|
||||
readonly path: string
|
||||
readonly bytes: ArrayBuffer
|
||||
}
|
||||
| { readonly type: "read.failed"; readonly attempt: number; readonly token: string; readonly path: string }
|
||||
| { readonly type: "read.cancelled"; readonly attempt: number; readonly token: string; readonly path: string }
|
||||
| { readonly type: "selection.released"; readonly sender: number; readonly token: string }
|
||||
| { readonly type: "sender.cleared"; readonly sender: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type PickedRejectReason = "not-selected" | "size-limit" | "read-failed"
|
||||
|
||||
// `watch-sender` and `unwatch-sender` follow a renderer while it holds a dialog or a selection; the rest answer the
|
||||
// request event that produced them.
|
||||
export type PickedFileCommand =
|
||||
| { readonly type: "watch-sender"; readonly sender: number }
|
||||
| { readonly type: "unwatch-sender"; readonly sender: number }
|
||||
| { readonly type: "picker-opened"; readonly picker: number }
|
||||
| { readonly type: "granted"; readonly token: string }
|
||||
| { readonly type: "read"; readonly attempt: number; readonly maxBytes: number }
|
||||
| { readonly type: "resolve" }
|
||||
| { readonly type: "reject"; readonly reason: PickedRejectReason }
|
||||
|
||||
export type PickedFileTransition = {
|
||||
readonly state: PickedFileState
|
||||
readonly commands: readonly PickedFileCommand[]
|
||||
}
|
||||
|
||||
export function createPickedFileState(): PickedFileState {
|
||||
return { status: "open", nextAttempt: 1, pickers: new Map(), selections: new Map() }
|
||||
}
|
||||
|
||||
export function transitionPickedFiles(state: PickedFileState, event: PickedFileEvent): PickedFileTransition {
|
||||
if (state.status === "disposed") {
|
||||
if (event.type === "read.requested" || event.type === "read.succeeded" || event.type === "read.failed")
|
||||
return reject(state, "not-selected")
|
||||
|
||||
return { state, commands: [] }
|
||||
}
|
||||
|
||||
switch (event.type) {
|
||||
case "picker.opened": {
|
||||
const picker = state.nextAttempt
|
||||
const next = { ...state, nextAttempt: picker + 1, pickers: new Map(state.pickers).set(picker, event.sender) }
|
||||
|
||||
return watched(state, next, [event.sender], [{ type: "picker-opened", picker }])
|
||||
}
|
||||
|
||||
case "picker.closed": {
|
||||
const sender = state.pickers.get(event.picker)
|
||||
|
||||
if (sender === undefined) return { state, commands: [] }
|
||||
|
||||
return watched(state, { ...state, pickers: without(state.pickers, event.picker) }, [sender], [])
|
||||
}
|
||||
|
||||
case "selection.granted": {
|
||||
const sender = state.pickers.get(event.picker)
|
||||
|
||||
// The renderer that opened the dialog reloaded or closed while it was open: nothing is granted.
|
||||
if (sender === undefined) return { state, commands: [] }
|
||||
const pickers = without(state.pickers, event.picker)
|
||||
const paths = [...new Set(event.paths)]
|
||||
|
||||
if (paths.length === 0) return watched(state, { ...state, pickers }, [sender], [])
|
||||
|
||||
const selection: PickedSelection = {
|
||||
sender,
|
||||
remaining: event.budget,
|
||||
files: new Map(paths.map((path) => [path, UNREAD])),
|
||||
}
|
||||
|
||||
return watched(
|
||||
state,
|
||||
{ ...state, pickers, selections: new Map(state.selections).set(event.token, selection) },
|
||||
[sender],
|
||||
[{ type: "granted", token: event.token }],
|
||||
)
|
||||
}
|
||||
|
||||
case "read.requested": {
|
||||
const selection = state.selections.get(event.token)
|
||||
|
||||
if (selection?.sender !== event.sender || selection.files.get(event.path)?.status !== "unread")
|
||||
return reject(state, "not-selected")
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
nextAttempt: attempt + 1,
|
||||
selections: withFile(state.selections, event.token, selection, event.path, { status: "reading", attempt }),
|
||||
},
|
||||
commands: [{ type: "read", attempt, maxBytes: selection.remaining }],
|
||||
}
|
||||
}
|
||||
|
||||
case "read.succeeded": {
|
||||
const selection = current(state, event)
|
||||
|
||||
if (!selection) return reject(state, "not-selected")
|
||||
|
||||
// Reads of other files in the same selection may have spent the budget since this one started.
|
||||
if (event.bytes.byteLength > selection.remaining)
|
||||
return reject(
|
||||
{ ...state, selections: withFile(state.selections, event.token, selection, event.path, UNREAD) },
|
||||
"size-limit",
|
||||
)
|
||||
const files = without(selection.files, event.path)
|
||||
|
||||
const selections =
|
||||
files.size === 0
|
||||
? without(state.selections, event.token)
|
||||
: new Map(state.selections).set(event.token, {
|
||||
...selection,
|
||||
remaining: selection.remaining - event.bytes.byteLength,
|
||||
files,
|
||||
})
|
||||
|
||||
return watched(state, { ...state, selections }, [selection.sender], [{ type: "resolve" }])
|
||||
}
|
||||
|
||||
case "read.failed": {
|
||||
const selection = current(state, event)
|
||||
|
||||
if (!selection) return reject(state, "not-selected")
|
||||
|
||||
return reject(
|
||||
{ ...state, selections: withFile(state.selections, event.token, selection, event.path, UNREAD) },
|
||||
"read-failed",
|
||||
)
|
||||
}
|
||||
|
||||
case "read.cancelled": {
|
||||
const selection = current(state, event)
|
||||
|
||||
if (!selection) return { state, commands: [] }
|
||||
|
||||
return {
|
||||
state: { ...state, selections: withFile(state.selections, event.token, selection, event.path, UNREAD) },
|
||||
commands: [],
|
||||
}
|
||||
}
|
||||
|
||||
case "selection.released": {
|
||||
if (state.selections.get(event.token)?.sender !== event.sender) return { state, commands: [] }
|
||||
|
||||
return watched(state, { ...state, selections: without(state.selections, event.token) }, [event.sender], [])
|
||||
}
|
||||
|
||||
case "sender.cleared": {
|
||||
if (!senderLive(state, event.sender)) return { state, commands: [] }
|
||||
|
||||
return watched(
|
||||
state,
|
||||
{
|
||||
...state,
|
||||
pickers: new Map([...state.pickers].filter((entry) => entry[1] !== event.sender)),
|
||||
selections: new Map([...state.selections].filter((entry) => entry[1].sender !== event.sender)),
|
||||
},
|
||||
[event.sender],
|
||||
[],
|
||||
)
|
||||
}
|
||||
|
||||
case "disposed":
|
||||
return {
|
||||
state: { status: "disposed" },
|
||||
commands: liveSenders(state).map((sender) => ({ type: "unwatch-sender", sender })),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const UNREAD: PickedPath = Object.freeze({ status: "unread" })
|
||||
|
||||
type OpenState = Extract<PickedFileState, { status: "open" }>
|
||||
|
||||
// The selection whose file this result's attempt still claims.
|
||||
function current(state: OpenState, event: { attempt: number; token: string; path: string }) {
|
||||
const selection = state.selections.get(event.token)
|
||||
const file = selection?.files.get(event.path)
|
||||
|
||||
if (file?.status !== "reading" || file.attempt !== event.attempt) return undefined
|
||||
|
||||
return selection
|
||||
}
|
||||
|
||||
function senderLive(state: OpenState, sender: number) {
|
||||
return (
|
||||
[...state.pickers.values()].includes(sender) ||
|
||||
[...state.selections.values()].some((selection) => selection.sender === sender)
|
||||
)
|
||||
}
|
||||
|
||||
function liveSenders(state: OpenState) {
|
||||
return [...new Set([...state.pickers.values(), ...[...state.selections.values()].map((item) => item.sender)])]
|
||||
}
|
||||
|
||||
// Follows a renderer from its first dialog or selection until its last is gone.
|
||||
function watched(
|
||||
previous: OpenState,
|
||||
next: OpenState,
|
||||
senders: readonly number[],
|
||||
commands: readonly PickedFileCommand[],
|
||||
): PickedFileTransition {
|
||||
const changes = senders.flatMap((sender): PickedFileCommand[] => {
|
||||
const before = senderLive(previous, sender)
|
||||
const after = senderLive(next, sender)
|
||||
|
||||
if (before === after) return []
|
||||
|
||||
return [after ? { type: "watch-sender", sender } : { type: "unwatch-sender", sender }]
|
||||
})
|
||||
|
||||
return { state: next, commands: [...changes, ...commands] }
|
||||
}
|
||||
|
||||
function withFile(
|
||||
selections: ReadonlyMap<string, PickedSelection>,
|
||||
token: string,
|
||||
selection: PickedSelection,
|
||||
path: string,
|
||||
file: PickedPath,
|
||||
) {
|
||||
return new Map(selections).set(token, { ...selection, files: new Map(selection.files).set(path, file) })
|
||||
}
|
||||
|
||||
function without<K, V>(map: ReadonlyMap<K, V>, key: K) {
|
||||
const next = new Map(map)
|
||||
next.delete(key)
|
||||
|
||||
return next
|
||||
}
|
||||
|
||||
function reject(state: PickedFileState, reason: PickedRejectReason): PickedFileTransition {
|
||||
return { state, commands: [{ type: "reject", reason }] }
|
||||
}
|
||||
@@ -42,10 +42,24 @@ describe("attachment size limit", () => {
|
||||
describe("picked file authorizations", () => {
|
||||
const read = (path: string) => Effect.sync(() => new TextEncoder().encode(path).buffer)
|
||||
|
||||
// Opens a dialog for `sender` and grants it `paths`, as `openFilePicker` does.
|
||||
const pick = (
|
||||
authorizations: ReturnType<typeof createPickedFileAuthorizations>,
|
||||
sender: number,
|
||||
paths: readonly string[],
|
||||
) => {
|
||||
const picker = authorizations.open(sender)
|
||||
const token = picker === undefined ? undefined : authorizations.grant(picker, paths)
|
||||
|
||||
if (token === undefined) throw new Error("nothing granted")
|
||||
|
||||
return token
|
||||
}
|
||||
|
||||
test("keeps concurrent picker selections isolated", async () => {
|
||||
const authorizations = createPickedFileAuthorizations(read)
|
||||
const first = authorizations.add(1, ["a.txt", "b.txt"])
|
||||
const second = authorizations.add(1, ["c.txt"])
|
||||
const first = pick(authorizations, 1, ["a.txt", "b.txt"])
|
||||
const second = pick(authorizations, 1, ["c.txt"])
|
||||
|
||||
expect(new TextDecoder().decode(await run(authorizations.read(1, first, "a.txt")))).toBe("a.txt")
|
||||
expect(new TextDecoder().decode(await run(authorizations.read(1, second, "c.txt")))).toBe("c.txt")
|
||||
@@ -54,8 +68,8 @@ describe("picked file authorizations", () => {
|
||||
|
||||
test("releases unread files for one picker without affecting another", async () => {
|
||||
const authorizations = createPickedFileAuthorizations(read)
|
||||
const first = authorizations.add(1, ["a.txt"])
|
||||
const second = authorizations.add(1, ["b.txt"])
|
||||
const first = pick(authorizations, 1, ["a.txt"])
|
||||
const second = pick(authorizations, 1, ["b.txt"])
|
||||
authorizations.release(1, first)
|
||||
|
||||
await expect(run(authorizations.read(1, first, "a.txt"))).rejects.toThrow("not selected")
|
||||
@@ -64,11 +78,56 @@ describe("picked file authorizations", () => {
|
||||
|
||||
test("keeps picker tokens scoped to their renderer", async () => {
|
||||
const authorizations = createPickedFileAuthorizations(read)
|
||||
const token = authorizations.add(1, ["a.txt"])
|
||||
const token = pick(authorizations, 1, ["a.txt"])
|
||||
|
||||
await expect(run(authorizations.read(2, token, "a.txt"))).rejects.toThrow("not selected")
|
||||
})
|
||||
|
||||
test("lets the renderer retry a file whose read failed, then reads it only once", async () => {
|
||||
const reads: string[] = []
|
||||
|
||||
const authorizations = createPickedFileAuthorizations((path) =>
|
||||
Effect.suspend(() => {
|
||||
reads.push(path)
|
||||
|
||||
// On dev the first failure consumed the file, so the retry was refused as not selected.
|
||||
if (reads.length === 1) return Effect.fail(new Error("EBUSY: resource busy or locked"))
|
||||
|
||||
return Effect.succeed(new TextEncoder().encode(path).buffer)
|
||||
}),
|
||||
)
|
||||
|
||||
const token = pick(authorizations, 1, ["a.txt"])
|
||||
|
||||
await expect(run(authorizations.read(1, token, "a.txt"))).rejects.toThrow("EBUSY")
|
||||
expect(new TextDecoder().decode(await run(authorizations.read(1, token, "a.txt")))).toBe("a.txt")
|
||||
await expect(run(authorizations.read(1, token, "a.txt"))).rejects.toThrow("not selected")
|
||||
})
|
||||
|
||||
test("drops a renderer's selections and open dialogs once it reloads or closes", async () => {
|
||||
const watched = new Map<number, () => void>()
|
||||
|
||||
const authorizations = createPickedFileAuthorizations(read, (sender, clear) => {
|
||||
watched.set(sender, clear)
|
||||
|
||||
return () => watched.delete(sender)
|
||||
})
|
||||
|
||||
const kept = pick(authorizations, 2, ["b.txt"])
|
||||
const token = pick(authorizations, 1, ["a.txt"])
|
||||
const picker = authorizations.open(1)
|
||||
|
||||
expect([...watched.keys()]).toEqual([2, 1])
|
||||
watched.get(1)?.()
|
||||
|
||||
expect([...watched.keys()]).toEqual([2])
|
||||
await expect(run(authorizations.read(1, token, "a.txt"))).rejects.toThrow("not selected")
|
||||
// The dialog the old document opened grants nothing to the new one.
|
||||
expect(picker === undefined ? "unopened" : authorizations.grant(picker, ["c.txt"])).toBeUndefined()
|
||||
expect(new TextDecoder().decode(await run(authorizations.read(2, kept, "b.txt")))).toBe("b.txt")
|
||||
expect([...watched.keys()]).toEqual([])
|
||||
})
|
||||
|
||||
test("charges actual reads against the selection budget", async () => {
|
||||
const size = MAX_ATTACHMENT_BYTES / 2 + 1
|
||||
|
||||
@@ -80,7 +139,7 @@ describe("picked file authorizations", () => {
|
||||
}),
|
||||
)
|
||||
|
||||
const token = authorizations.add(1, ["a.txt", "b.txt"])
|
||||
const token = pick(authorizations, 1, ["a.txt", "b.txt"])
|
||||
|
||||
await run(authorizations.read(1, token, "a.txt"))
|
||||
await expect(run(authorizations.read(1, token, "b.txt"))).rejects.toThrow("budget exceeded")
|
||||
|
||||
@@ -1,39 +1,110 @@
|
||||
import { randomUUID } from "node:crypto"
|
||||
import { ByteSize, Effect, FileSystem } from "effect"
|
||||
import { ByteSize, Effect, Exit, FileSystem } from "effect"
|
||||
import { nativeT } from "../native/translations"
|
||||
import {
|
||||
createPickedFileState,
|
||||
transitionPickedFiles,
|
||||
type PickedFileCommand,
|
||||
type PickedFileEvent,
|
||||
type PickedRejectReason,
|
||||
} from "./attachment-picker-machine"
|
||||
|
||||
export const MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024
|
||||
|
||||
/**
|
||||
* The files each renderer picked and may read. `watch` follows a renderer while it holds an open dialog or a selection,
|
||||
* and calls `clear` once that renderer reloads or closes; it returns a function that stops following.
|
||||
*/
|
||||
export function createPickedFileAuthorizations(
|
||||
read: (path: string, maxBytes: number) => Effect.Effect<ArrayBuffer, unknown>,
|
||||
watch?: (sender: number, clear: () => void) => () => void,
|
||||
) {
|
||||
const selections = new Map<string, { sender: number; paths: Set<string>; remaining: number }>()
|
||||
let state = createPickedFileState()
|
||||
const watchers = new Map<number, () => void>()
|
||||
|
||||
// Returns the command that answers the event, if any.
|
||||
const dispatch = (event: PickedFileEvent) => {
|
||||
const next = transitionPickedFiles(state, event)
|
||||
state = next.state
|
||||
next.commands.forEach((command) => {
|
||||
if (command.type === "watch-sender" && watch)
|
||||
watchers.set(
|
||||
command.sender,
|
||||
watch(command.sender, () => dispatch({ type: "sender.cleared", sender: command.sender })),
|
||||
)
|
||||
|
||||
if (command.type !== "unwatch-sender") return
|
||||
watchers.get(command.sender)?.()
|
||||
watchers.delete(command.sender)
|
||||
})
|
||||
|
||||
return next.commands.find((command) => command.type !== "watch-sender" && command.type !== "unwatch-sender")
|
||||
}
|
||||
|
||||
return {
|
||||
add(sender: number, paths: string[]) {
|
||||
const token = randomUUID()
|
||||
selections.set(token, { sender, paths: new Set(paths), remaining: MAX_ATTACHMENT_BYTES })
|
||||
/** Starts a native file dialog for `sender`; returns its id, or undefined once disposed. */
|
||||
open(sender: number) {
|
||||
const reply = dispatch({ type: "picker.opened", sender })
|
||||
|
||||
return token
|
||||
return reply?.type === "picker-opened" ? reply.picker : undefined
|
||||
},
|
||||
/** Grants the dialog's files; undefined when its renderer reloaded or closed while the dialog was open. */
|
||||
grant(picker: number, paths: readonly string[]) {
|
||||
const reply = dispatch({
|
||||
type: "selection.granted",
|
||||
picker,
|
||||
token: randomUUID(),
|
||||
paths,
|
||||
budget: MAX_ATTACHMENT_BYTES,
|
||||
})
|
||||
|
||||
return reply?.type === "granted" ? reply.token : undefined
|
||||
},
|
||||
/** Ends a dialog that granted nothing. */
|
||||
close(picker: number) {
|
||||
dispatch({ type: "picker.closed", picker })
|
||||
},
|
||||
read: Effect.fn("DesktopFiles.readPickedFile")(function* (sender: number, token: string, path: string) {
|
||||
const selection = selections.get(token)
|
||||
const claim = dispatch({ type: "read.requested", sender, token, path })
|
||||
|
||||
if (selection?.sender !== sender || !selection.paths.delete(path))
|
||||
throw new Error(nativeT("desktop.picker.error.notSelected"))
|
||||
const bytes = yield* read(path, selection.remaining)
|
||||
selection.remaining -= bytes.byteLength
|
||||
if (claim?.type !== "read") throw rejection(claim)
|
||||
|
||||
if (selection.paths.size === 0) selections.delete(token)
|
||||
const exit = yield* read(path, claim.maxBytes).pipe(
|
||||
Effect.onInterrupt(() =>
|
||||
Effect.sync(() => dispatch({ type: "read.cancelled", attempt: claim.attempt, token, path })),
|
||||
),
|
||||
Effect.exit,
|
||||
)
|
||||
|
||||
return bytes
|
||||
const settled = dispatch(
|
||||
Exit.isSuccess(exit)
|
||||
? { type: "read.succeeded", attempt: claim.attempt, token, path, bytes: exit.value }
|
||||
: { type: "read.failed", attempt: claim.attempt, token, path },
|
||||
)
|
||||
|
||||
if (settled?.type === "resolve" || (settled?.type === "reject" && settled.reason === "read-failed"))
|
||||
return yield* exit
|
||||
|
||||
throw rejection(settled)
|
||||
}),
|
||||
release(sender: number, token: string) {
|
||||
if (selections.get(token)?.sender === sender) selections.delete(token)
|
||||
dispatch({ type: "selection.released", sender, token })
|
||||
},
|
||||
dispose() {
|
||||
dispatch({ type: "disposed" })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function rejection(reply: PickedFileCommand | undefined) {
|
||||
const reason: PickedRejectReason = reply?.type === "reject" ? reply.reason : "not-selected"
|
||||
|
||||
if (reason === "size-limit")
|
||||
return new Error(nativeT("desktop.picker.error.sizeLimit", { limit: MAX_ATTACHMENT_BYTES / 1024 / 1024 }))
|
||||
|
||||
return new Error(nativeT("desktop.picker.error.notSelected"))
|
||||
}
|
||||
|
||||
export function assertAttachmentBudget(files: { size: number }[]) {
|
||||
const total = files.reduce((sum, file) => sum + file.size, 0)
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
export * as DesktopFiles from "./index"
|
||||
|
||||
import { execFile, spawn } from "node:child_process"
|
||||
import { clipboard, dialog, nativeImage, shell } from "electron"
|
||||
import { clipboard, dialog, nativeImage, shell, webContents } from "electron"
|
||||
import { Context, Effect, FileSystem, Layer, Path } from "effect"
|
||||
import type { DirectoryPickerOptions, FilePickerOptions, SaveFilePickerOptions } from "../../shared/ipc-contract"
|
||||
import { scoped } from "../native/logging"
|
||||
@@ -19,15 +19,46 @@ export const layer = Layer.effect(
|
||||
const fs = yield* FileSystem.FileSystem
|
||||
const path = yield* Path.Path
|
||||
|
||||
return Service.of(make(fs, path))
|
||||
const pickedFiles = createPickedFileAuthorizations(
|
||||
(file, maxBytes) => readAttachment(file, maxBytes).pipe(Effect.provideService(FileSystem.FileSystem, fs)),
|
||||
watchRenderer,
|
||||
)
|
||||
|
||||
yield* Effect.addFinalizer(() => Effect.sync(pickedFiles.dispose))
|
||||
|
||||
return Service.of(make(fs, path, pickedFiles))
|
||||
}),
|
||||
)
|
||||
|
||||
function make(fs: FileSystem.FileSystem, path: Path.Path) {
|
||||
const pickedFiles = createPickedFileAuthorizations((file, maxBytes) =>
|
||||
readAttachment(file, maxBytes).pipe(Effect.provideService(FileSystem.FileSystem, fs)),
|
||||
)
|
||||
// A renderer that reloads or closes drops its picked files: the next document never asked for them.
|
||||
function watchRenderer(sender: number, clear: () => void) {
|
||||
const contents = webContents.fromId(sender)
|
||||
|
||||
if (!contents || contents.isDestroyed()) {
|
||||
queueMicrotask(clear)
|
||||
|
||||
return () => {}
|
||||
}
|
||||
|
||||
const navigated = (event: Electron.Event<{ isMainFrame: boolean; isSameDocument: boolean }>) => {
|
||||
if (event.isMainFrame && !event.isSameDocument) clear()
|
||||
}
|
||||
|
||||
contents.on("did-start-navigation", navigated)
|
||||
contents.once("destroyed", clear)
|
||||
|
||||
return () => {
|
||||
if (contents.isDestroyed()) return
|
||||
contents.off("did-start-navigation", navigated)
|
||||
contents.off("destroyed", clear)
|
||||
}
|
||||
}
|
||||
|
||||
function make(
|
||||
fs: FileSystem.FileSystem,
|
||||
path: Path.Path,
|
||||
pickedFiles: ReturnType<typeof createPickedFileAuthorizations>,
|
||||
) {
|
||||
return {
|
||||
openDirectoryPicker: Effect.fn("DesktopFiles.openDirectoryPicker")(function* (options?: DirectoryPickerOptions) {
|
||||
const result = yield* Effect.promise(() =>
|
||||
@@ -43,30 +74,37 @@ function make(fs: FileSystem.FileSystem, path: Path.Path) {
|
||||
return options?.multiple ? result.filePaths : result.filePaths[0]
|
||||
}),
|
||||
openFilePicker: Effect.fn("DesktopFiles.openFilePicker")(function* (sender: number, options?: FilePickerOptions) {
|
||||
const result = yield* Effect.promise(() =>
|
||||
dialog.showOpenDialog({
|
||||
properties: ["openFile", ...(options?.multiple ? ["multiSelections" as const] : [])],
|
||||
title: options?.title ?? nativeT("desktop.dialog.chooseFile"),
|
||||
defaultPath: options?.defaultPath,
|
||||
filters: pickerFilters(options?.extensions),
|
||||
}),
|
||||
)
|
||||
const picker = pickedFiles.open(sender)
|
||||
|
||||
if (result.canceled) return null
|
||||
if (picker === undefined) return null
|
||||
|
||||
const files = yield* Effect.forEach(
|
||||
result.filePaths,
|
||||
Effect.fnUntraced(function* (file) {
|
||||
const info = yield* fs.stat(file)
|
||||
return yield* Effect.gen(function* () {
|
||||
const result = yield* Effect.promise(() =>
|
||||
dialog.showOpenDialog({
|
||||
properties: ["openFile", ...(options?.multiple ? ["multiSelections" as const] : [])],
|
||||
title: options?.title ?? nativeT("desktop.dialog.chooseFile"),
|
||||
defaultPath: options?.defaultPath,
|
||||
filters: pickerFilters(options?.extensions),
|
||||
}),
|
||||
)
|
||||
|
||||
return { path: file, name: path.basename(file), size: Number(info.size) }
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
)
|
||||
if (result.canceled) return null
|
||||
|
||||
assertAttachmentBudget(files)
|
||||
const files = yield* Effect.forEach(
|
||||
result.filePaths,
|
||||
Effect.fnUntraced(function* (file) {
|
||||
const info = yield* fs.stat(file)
|
||||
|
||||
return { token: pickedFiles.add(sender, result.filePaths), files }
|
||||
return { path: file, name: path.basename(file), size: Number(info.size) }
|
||||
}),
|
||||
{ concurrency: "unbounded" },
|
||||
)
|
||||
|
||||
assertAttachmentBudget(files)
|
||||
const token = pickedFiles.grant(picker, result.filePaths)
|
||||
|
||||
return token === undefined ? null : { token, files }
|
||||
}).pipe(Effect.ensuring(Effect.sync(() => pickedFiles.close(picker))))
|
||||
}),
|
||||
readPickedFile: pickedFiles.read,
|
||||
releasePickedFiles: pickedFiles.release,
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import {
|
||||
createHostState,
|
||||
transitionHost,
|
||||
type HostCommand,
|
||||
type HostEndpoint,
|
||||
type HostEvent,
|
||||
type HostState,
|
||||
} from "./host-machine"
|
||||
|
||||
const a: HostEndpoint = { url: "http://127.0.0.1:4096", authorization: "Basic a" }
|
||||
|
||||
const b: HostEndpoint = { url: "http://127.0.0.1:4097", authorization: "Basic b" }
|
||||
|
||||
// Folds events through the machine and keeps the commands of each step.
|
||||
function replay(events: readonly HostEvent<string>[], from: HostState = createHostState()) {
|
||||
return events.reduce<{ state: HostState; commands: (readonly HostCommand<string>[])[] }>(
|
||||
(result, event) => {
|
||||
const next = transitionHost(result.state, event)
|
||||
|
||||
return { state: next.state, commands: [...result.commands, next.commands] }
|
||||
},
|
||||
{ state: from, commands: [] },
|
||||
)
|
||||
}
|
||||
|
||||
const live = { quitting: false }
|
||||
|
||||
describe("plugin host follow", () => {
|
||||
test("never applies a listing from an endpoint the server already left", () => {
|
||||
const run = replay([
|
||||
{ type: "started", endpoint: a, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
{ type: "endpoint.changed", endpoint: b, ...live },
|
||||
// On dev endpoint A's listing finished later and reloaded plugins against the old server.
|
||||
{ type: "list.succeeded", attempt: 2, listing: "from a", ...live },
|
||||
])
|
||||
|
||||
expect(run.commands).toEqual([
|
||||
[{ type: "subscribe-credentials" }, { type: "start-watch", attempt: 1, endpoint: a }],
|
||||
[{ type: "start-list", attempt: 2, endpoint: a, timeoutMs: 30_000 }],
|
||||
[{ type: "cancel-watch" }, { type: "cancel-list" }, { type: "start-watch", attempt: 3, endpoint: b }],
|
||||
[],
|
||||
])
|
||||
})
|
||||
|
||||
test("coalesces changes during a listing into one more listing", () => {
|
||||
const listing = replay([
|
||||
{ type: "started", endpoint: a, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
]).state
|
||||
|
||||
expect(transitionHost(listing, { type: "relist.requested", watchAttempt: 1, ...live }).state).toBe(listing)
|
||||
|
||||
const ends: HostEvent<string>[] = [
|
||||
{ type: "list.succeeded", attempt: 2, listing: "plugins", ...live },
|
||||
{ type: "list.failed", attempt: 2, cause: "offline", ...live },
|
||||
{ type: "list.timed-out", attempt: 2, ...live },
|
||||
]
|
||||
|
||||
expect(ends.map((event) => transitionHost(listing, event).commands)).toEqual([
|
||||
[
|
||||
{ type: "apply-listing", listing: "plugins" },
|
||||
{ type: "start-list", attempt: 3, endpoint: a, timeoutMs: 30_000 },
|
||||
],
|
||||
[
|
||||
{ type: "log-list-error", cause: "offline" },
|
||||
{ type: "start-list", attempt: 3, endpoint: a, timeoutMs: 30_000 },
|
||||
],
|
||||
[
|
||||
{ type: "cancel-list" },
|
||||
{ type: "log-list-error", cause: expect.any(Error) },
|
||||
{ type: "start-list", attempt: 3, endpoint: a, timeoutMs: 30_000 },
|
||||
],
|
||||
])
|
||||
})
|
||||
|
||||
test("retries an ended stream after a pause and ignores events from the old one", () => {
|
||||
const run = replay([
|
||||
{ type: "started", endpoint: a, ...live },
|
||||
{ type: "watch.ended", attempt: 1, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
{ type: "watch.retry-due", attempt: 2, ...live },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(1)).toEqual([
|
||||
[{ type: "schedule-watch-retry", attempt: 2, delayMs: 1_000 }],
|
||||
[],
|
||||
[{ type: "start-watch", attempt: 3, endpoint: a }],
|
||||
])
|
||||
})
|
||||
|
||||
test("a reconnect on the same endpoint follows anew and keeps the running listing", () => {
|
||||
const run = replay([
|
||||
{ type: "started", endpoint: a, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
{ type: "endpoint.changed", endpoint: { ...a }, ...live },
|
||||
{ type: "list.succeeded", attempt: 2, listing: "plugins", ...live },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(2)).toEqual([
|
||||
[{ type: "cancel-watch" }, { type: "start-watch", attempt: 3, endpoint: a }],
|
||||
[{ type: "apply-listing", listing: "plugins" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("stops following on stop and starts again on resume", () => {
|
||||
const run = replay([
|
||||
{ type: "started", endpoint: a, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
{ type: "stopped" },
|
||||
{ type: "list.succeeded", attempt: 2, listing: "late", ...live },
|
||||
{ type: "resumed", endpoint: a, ...live },
|
||||
])
|
||||
|
||||
expect(run.commands.slice(2)).toEqual([
|
||||
[{ type: "unsubscribe-credentials" }, { type: "cancel-watch" }, { type: "cancel-list" }],
|
||||
[],
|
||||
[{ type: "queue-menubar" }, { type: "subscribe-credentials" }, { type: "start-watch", attempt: 3, endpoint: a }],
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("plugin host menubar", () => {
|
||||
test("publishes once per queued flush and keeps the menu while quitting", () => {
|
||||
const run = replay([
|
||||
{ type: "menubar.scheduled" },
|
||||
{ type: "menubar.scheduled" },
|
||||
{ type: "menubar.flushed", quitting: false },
|
||||
{ type: "menubar.scheduled" },
|
||||
{ type: "menubar.flushed", quitting: true },
|
||||
{ type: "menubar.flushed", quitting: false },
|
||||
])
|
||||
|
||||
expect(run.commands).toEqual([
|
||||
[{ type: "queue-menubar" }],
|
||||
[],
|
||||
[{ type: "publish-menubar" }],
|
||||
[{ type: "queue-menubar" }],
|
||||
[],
|
||||
[],
|
||||
])
|
||||
})
|
||||
|
||||
test("does not start following while the app quits, and drops a listing that lands during the quit", () => {
|
||||
const stopped = createHostState()
|
||||
|
||||
expect(transitionHost(stopped, { type: "started", endpoint: a, quitting: true }).state).toBe(stopped)
|
||||
|
||||
const listing = replay([
|
||||
{ type: "started", endpoint: a, ...live },
|
||||
{ type: "relist.requested", watchAttempt: 1, ...live },
|
||||
]).state
|
||||
|
||||
expect(
|
||||
transitionHost(listing, { type: "list.succeeded", attempt: 2, listing: "plugins", quitting: true }).commands,
|
||||
).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,280 @@
|
||||
export const WATCH_RETRY_MS = 1_000
|
||||
|
||||
export const LIST_TIMEOUT_MS = 30_000
|
||||
|
||||
/** The app's own server as main reaches it. */
|
||||
export type HostEndpoint = {
|
||||
readonly url: string
|
||||
readonly authorization: string | undefined
|
||||
}
|
||||
|
||||
// The event stream of the app's own server: a stream that ends while its endpoint stays retries after a pause.
|
||||
export type HostWatch =
|
||||
| { readonly status: "idle" }
|
||||
| { readonly status: "streaming"; readonly attempt: number }
|
||||
| { readonly status: "retrying"; readonly attempt: number }
|
||||
|
||||
// One listing of the server's plugins at a time; a change during a listing lists once more (`queued`).
|
||||
export type HostList =
|
||||
| { readonly status: "idle" }
|
||||
| { readonly status: "listing"; readonly attempt: number; readonly queued: boolean }
|
||||
|
||||
// `menubarQueued` is a menubar publish waiting for its microtask, in either phase: quitting keeps the menu as it is.
|
||||
export type HostState =
|
||||
| { readonly status: "stopped"; readonly nextAttempt: number; readonly menubarQueued: boolean }
|
||||
| {
|
||||
readonly status: "following"
|
||||
readonly nextAttempt: number
|
||||
readonly menubarQueued: boolean
|
||||
readonly endpoint: HostEndpoint | undefined
|
||||
readonly watch: HostWatch
|
||||
readonly list: HostList
|
||||
}
|
||||
|
||||
// `quitting` is the app lifecycle's answer when the event happened.
|
||||
export type HostEvent<Listing> =
|
||||
| { readonly type: "started"; readonly endpoint: HostEndpoint | undefined; readonly quitting: boolean }
|
||||
| { readonly type: "resumed"; readonly endpoint: HostEndpoint | undefined; readonly quitting: boolean }
|
||||
| { readonly type: "stopped" }
|
||||
| { readonly type: "endpoint.changed"; readonly endpoint: HostEndpoint | undefined; readonly quitting: boolean }
|
||||
| { readonly type: "watch.ended"; readonly attempt: number; readonly quitting: boolean }
|
||||
| { readonly type: "watch.retry-due"; readonly attempt: number; readonly quitting: boolean }
|
||||
| { readonly type: "relist.requested"; readonly watchAttempt: number; readonly quitting: boolean }
|
||||
| { readonly type: "list.succeeded"; readonly attempt: number; readonly listing: Listing; readonly quitting: boolean }
|
||||
| { readonly type: "list.failed"; readonly attempt: number; readonly cause: unknown; readonly quitting: boolean }
|
||||
| { readonly type: "list.timed-out"; readonly attempt: number; readonly quitting: boolean }
|
||||
| { readonly type: "menubar.scheduled" }
|
||||
| { readonly type: "menubar.flushed"; readonly quitting: boolean }
|
||||
|
||||
export type HostCommand<Listing> =
|
||||
| { readonly type: "subscribe-credentials" }
|
||||
| { readonly type: "unsubscribe-credentials" }
|
||||
| { readonly type: "start-watch"; readonly attempt: number; readonly endpoint: HostEndpoint }
|
||||
| { readonly type: "schedule-watch-retry"; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "cancel-watch" }
|
||||
| {
|
||||
readonly type: "start-list"
|
||||
readonly attempt: number
|
||||
readonly endpoint: HostEndpoint
|
||||
readonly timeoutMs: number
|
||||
}
|
||||
| { readonly type: "cancel-list" }
|
||||
| { readonly type: "apply-listing"; readonly listing: Listing }
|
||||
| { readonly type: "log-list-error"; readonly cause: unknown }
|
||||
| { readonly type: "queue-menubar" }
|
||||
| { readonly type: "publish-menubar" }
|
||||
|
||||
export type HostTransition<Listing> = {
|
||||
readonly state: HostState
|
||||
readonly commands: readonly HostCommand<Listing>[]
|
||||
}
|
||||
|
||||
type Following = Extract<HostState, { status: "following" }>
|
||||
|
||||
export function createHostState(): HostState {
|
||||
return { status: "stopped", nextAttempt: 1, menubarQueued: false }
|
||||
}
|
||||
|
||||
export function transitionHost<Listing>(state: HostState, event: HostEvent<Listing>): HostTransition<Listing> {
|
||||
switch (event.type) {
|
||||
case "menubar.scheduled":
|
||||
if (state.menubarQueued) return unchanged(state)
|
||||
|
||||
return { state: { ...state, menubarQueued: true }, commands: [{ type: "queue-menubar" }] }
|
||||
|
||||
case "menubar.flushed":
|
||||
if (!state.menubarQueued) return unchanged(state)
|
||||
|
||||
// While quitting the menu keeps its items, a kept plugin's among them; resuming publishes it again.
|
||||
return {
|
||||
state: { ...state, menubarQueued: false },
|
||||
commands: event.quitting ? [] : [{ type: "publish-menubar" }],
|
||||
}
|
||||
|
||||
case "resumed": {
|
||||
const queued = transitionHost<Listing>(state, { type: "menubar.scheduled" })
|
||||
const started = transitionHost<Listing>(queued.state, { ...event, type: "started" })
|
||||
|
||||
return { state: started.state, commands: [...queued.commands, ...started.commands] }
|
||||
}
|
||||
|
||||
case "started":
|
||||
if (state.status === "following") return follow(state, event.endpoint, event.quitting)
|
||||
|
||||
if (event.quitting) return unchanged(state)
|
||||
|
||||
return follow(
|
||||
{
|
||||
status: "following",
|
||||
nextAttempt: state.nextAttempt,
|
||||
menubarQueued: state.menubarQueued,
|
||||
endpoint: undefined,
|
||||
watch: IDLE_WATCH,
|
||||
list: IDLE_LIST,
|
||||
},
|
||||
event.endpoint,
|
||||
false,
|
||||
[{ type: "subscribe-credentials" }],
|
||||
)
|
||||
|
||||
case "stopped":
|
||||
if (state.status === "stopped") return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { status: "stopped", nextAttempt: state.nextAttempt, menubarQueued: state.menubarQueued },
|
||||
commands: [{ type: "unsubscribe-credentials" }, ...cancelled<Listing>(state)],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "following") return unchanged(state)
|
||||
|
||||
switch (event.type) {
|
||||
case "endpoint.changed":
|
||||
return follow(state, event.endpoint, event.quitting)
|
||||
|
||||
case "watch.ended": {
|
||||
if (state.watch.status !== "streaming" || state.watch.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
if (event.quitting) return { state: { ...state, watch: IDLE_WATCH }, commands: [] }
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: { ...state, nextAttempt: attempt + 1, watch: { status: "retrying", attempt } },
|
||||
commands: [{ type: "schedule-watch-retry", attempt, delayMs: WATCH_RETRY_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
case "watch.retry-due": {
|
||||
if (state.watch.status !== "retrying" || state.watch.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
if (event.quitting || !state.endpoint) return { state: { ...state, watch: IDLE_WATCH }, commands: [] }
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: { ...state, nextAttempt: attempt + 1, watch: { status: "streaming", attempt } },
|
||||
commands: [{ type: "start-watch", attempt, endpoint: state.endpoint }],
|
||||
}
|
||||
}
|
||||
|
||||
case "relist.requested": {
|
||||
if (event.quitting || !state.endpoint) return unchanged(state)
|
||||
|
||||
if (state.watch.status !== "streaming" || state.watch.attempt !== event.watchAttempt) return unchanged(state)
|
||||
|
||||
if (state.list.status === "listing")
|
||||
return state.list.queued
|
||||
? unchanged(state)
|
||||
: { state: { ...state, list: { ...state.list, queued: true } }, commands: [] }
|
||||
|
||||
return list(state, state.endpoint, [])
|
||||
}
|
||||
|
||||
case "list.succeeded":
|
||||
if (!currentList(state, event.attempt)) return unchanged(state)
|
||||
|
||||
if (event.quitting) return settleList(state, [], true)
|
||||
|
||||
return settleList(state, [{ type: "apply-listing", listing: event.listing }], false)
|
||||
|
||||
case "list.failed":
|
||||
if (!currentList(state, event.attempt)) return unchanged(state)
|
||||
|
||||
return settleList(state, [{ type: "log-list-error", cause: event.cause }], event.quitting)
|
||||
|
||||
case "list.timed-out":
|
||||
if (!currentList(state, event.attempt)) return unchanged(state)
|
||||
|
||||
return settleList(
|
||||
state,
|
||||
[
|
||||
{ type: "cancel-list" },
|
||||
{ type: "log-list-error", cause: new Error(`Plugin listing timed out after ${LIST_TIMEOUT_MS} ms`) },
|
||||
],
|
||||
event.quitting,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a watch started with `attempt` is still the one to run. */
|
||||
export function isCurrentHostWatch(state: HostState, attempt: number) {
|
||||
return state.status === "following" && state.watch.status === "streaming" && state.watch.attempt === attempt
|
||||
}
|
||||
|
||||
export function sameHostEndpoint(a: HostEndpoint | undefined, b: HostEndpoint | undefined) {
|
||||
return a?.url === b?.url && a?.authorization === b?.authorization
|
||||
}
|
||||
|
||||
const IDLE_WATCH: HostWatch = Object.freeze({ status: "idle" })
|
||||
|
||||
const IDLE_LIST: HostList = Object.freeze({ status: "idle" })
|
||||
|
||||
function currentList(state: Following, attempt: number) {
|
||||
return state.list.status === "listing" && state.list.attempt === attempt
|
||||
}
|
||||
|
||||
// Every credential change follows the server anew, as each connection and reconnect publishes one. A listing keeps
|
||||
// running only while the endpoint stays the same; one from a superseded endpoint never applies.
|
||||
function follow<Listing>(
|
||||
state: Following,
|
||||
endpoint: HostEndpoint | undefined,
|
||||
quitting: boolean,
|
||||
before: readonly HostCommand<Listing>[] = [],
|
||||
): HostTransition<Listing> {
|
||||
const same = sameHostEndpoint(state.endpoint, endpoint)
|
||||
|
||||
if (quitting && same && state.watch.status === "idle" && state.list.status === "idle" && before.length === 0)
|
||||
return unchanged(state)
|
||||
const stopsList = quitting || !same
|
||||
|
||||
const commands: HostCommand<Listing>[] = [
|
||||
...before,
|
||||
...(state.watch.status === "idle" ? [] : [{ type: "cancel-watch" as const }]),
|
||||
...(stopsList && state.list.status !== "idle" ? [{ type: "cancel-list" as const }] : []),
|
||||
]
|
||||
|
||||
const listing = stopsList ? IDLE_LIST : state.list
|
||||
|
||||
if (quitting || !endpoint) return { state: { ...state, endpoint, watch: IDLE_WATCH, list: listing }, commands }
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: { ...state, endpoint, nextAttempt: attempt + 1, watch: { status: "streaming", attempt }, list: listing },
|
||||
commands: [...commands, { type: "start-watch", attempt, endpoint }],
|
||||
}
|
||||
}
|
||||
|
||||
function list<Listing>(
|
||||
state: Following,
|
||||
endpoint: HostEndpoint,
|
||||
before: readonly HostCommand<Listing>[],
|
||||
): HostTransition<Listing> {
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: { ...state, nextAttempt: attempt + 1, list: { status: "listing", attempt, queued: false } },
|
||||
commands: [...before, { type: "start-list", attempt, endpoint, timeoutMs: LIST_TIMEOUT_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
// Ends the current listing and starts the queued one, if a change arrived meanwhile and the app is not quitting.
|
||||
function settleList<Listing>(
|
||||
state: Following,
|
||||
commands: readonly HostCommand<Listing>[],
|
||||
quitting: boolean,
|
||||
): HostTransition<Listing> {
|
||||
if (!quitting && state.list.status === "listing" && state.list.queued && state.endpoint)
|
||||
return list(state, state.endpoint, commands)
|
||||
|
||||
return { state: { ...state, list: IDLE_LIST }, commands }
|
||||
}
|
||||
|
||||
function cancelled<Listing>(state: Following): HostCommand<Listing>[] {
|
||||
return [
|
||||
...(state.watch.status === "idle" ? [] : [{ type: "cancel-watch" as const }]),
|
||||
...(state.list.status === "idle" ? [] : [{ type: "cancel-list" as const }]),
|
||||
]
|
||||
}
|
||||
|
||||
function unchanged<Listing>(state: HostState): HostTransition<Listing> {
|
||||
return { state, commands: [] }
|
||||
}
|
||||
@@ -64,6 +64,15 @@ import { getLastFocusedWindow, getMainWindows, onMainWindow } from "../windows"
|
||||
import { PluginError } from "./error"
|
||||
import { createLifecycle, type ErrorLog, type Instance, type Revision } from "./lifecycle"
|
||||
import { createManager } from "./manager"
|
||||
import {
|
||||
createHostState,
|
||||
isCurrentHostWatch,
|
||||
sameHostEndpoint,
|
||||
transitionHost,
|
||||
type HostCommand,
|
||||
type HostEndpoint,
|
||||
type HostEvent,
|
||||
} from "./host-machine"
|
||||
import { evaluateMain } from "./module"
|
||||
import { getStore } from "../storage/store"
|
||||
import { createStorage } from "./storage"
|
||||
@@ -92,8 +101,8 @@ type ListedPlugin = {
|
||||
}
|
||||
|
||||
/**
|
||||
* What main keeps of the plugin listing besides the plugins: the ids a built-in claims, the plugins with a server
|
||||
* part and those that export `./tui` (Extensions › Plugins tags those parts), and the follow of the server.
|
||||
* What main keeps of the plugin listing besides the plugins: the ids a built-in claims, and the plugins with a server
|
||||
* part and those that export `./tui` (Extensions › Plugins tags those parts).
|
||||
*/
|
||||
type Inventory = {
|
||||
reserved: readonly string[]
|
||||
@@ -105,10 +114,15 @@ type Inventory = {
|
||||
* New plugins whose bundle main could not read, with why: listed in Extensions › Plugins until a listing reads them.
|
||||
*/
|
||||
unreadable: ReadonlyMap<string, string>
|
||||
/** Aborts the current follow of the app's own server. */
|
||||
watch?: AbortController
|
||||
/** Stops following the server's connections. */
|
||||
stop?: () => void
|
||||
}
|
||||
|
||||
/** One listing of the app's own server, applied only while it is the current one. */
|
||||
type Listing = {
|
||||
readonly plugins: ReadonlyMap<string, ListedPlugin>
|
||||
readonly reserved: readonly string[]
|
||||
readonly parts: Pick<Inventory, "server" | "tui" | "unsupported" | "unreadable">
|
||||
/** Bundles this listing found to run only on other systems, by id, at their revision. */
|
||||
readonly skipped: ReadonlyMap<string, string>
|
||||
}
|
||||
|
||||
const loadClient = () => import("@opencode/client")
|
||||
@@ -116,12 +130,20 @@ const loadClient = () => import("@opencode/client")
|
||||
/** The client of the app's own server, made once the client module loaded and again when the endpoint changes. */
|
||||
type SidecarClient = {
|
||||
module?: Awaited<ReturnType<typeof loadClient>>
|
||||
key?: string
|
||||
client?: OpenCodeClient
|
||||
active?: { readonly endpoint: HostEndpoint; readonly client: OpenCodeClient }
|
||||
/** The client plugins read while the server is unreachable. */
|
||||
unavailable?: OpenCodeClient
|
||||
}
|
||||
|
||||
/** What following the app's own server holds open: its credential subscription, stream, listing and timers. */
|
||||
type HostResources = {
|
||||
unfollow?: () => void
|
||||
watch?: AbortController
|
||||
watchTimer?: ReturnType<typeof setTimeout>
|
||||
list?: AbortController
|
||||
listTimer?: ReturnType<typeof setTimeout>
|
||||
}
|
||||
|
||||
/** An Ipc method with its spec erased: Ipcs of every spec share one table, and `call` runs the spec's codecs. */
|
||||
type Method = IpcImpl<IpcSpec>[string]
|
||||
|
||||
@@ -209,7 +231,7 @@ export function createHost(input: {
|
||||
// Each live instance's catalog and messages, so a locale change reaches them.
|
||||
const translations = new Set<Translation>()
|
||||
const closed = new Set<(win: BrowserWindow) => void>()
|
||||
const status = { sequence: 0, menubarQueued: false, listing: false, relist: false }
|
||||
let nextEntry = 0
|
||||
|
||||
const broadcast = (event: DesktopEvent) => getMainWindows().forEach((win) => emitIpcEvent(win.webContents, event))
|
||||
const changed = () => broadcast(new PluginsChanged({ list: installed() }))
|
||||
@@ -264,20 +286,7 @@ export function createHost(input: {
|
||||
})
|
||||
}
|
||||
|
||||
const publishMenubar = () => {
|
||||
status.menubarQueued = false
|
||||
|
||||
// While quitting the menu keeps its items, a kept plugin's among them; resuming publishes it again.
|
||||
if (isQuitting(input.appState())) return
|
||||
refreshMenu()
|
||||
broadcast(new PluginMenubarItemsChanged({ items: listMenubarItems() }))
|
||||
}
|
||||
|
||||
const scheduleMenubar = () => {
|
||||
if (status.menubarQueued) return
|
||||
status.menubarQueued = true
|
||||
queueMicrotask(publishMenubar)
|
||||
}
|
||||
const scheduleMenubar = () => dispatch({ type: "menubar.scheduled" })
|
||||
|
||||
const listMenubarItems = (): BridgeMenubarItem[] =>
|
||||
menubarItems().map((entry) => {
|
||||
@@ -391,66 +400,156 @@ export function createHost(input: {
|
||||
}))
|
||||
}
|
||||
|
||||
const loadModule = async () => (sidecar.module ??= await loadClient())
|
||||
|
||||
const sidecarEndpoint = (): HostEndpoint | undefined => {
|
||||
const credentials = SidecarCredentials.get()
|
||||
|
||||
if (!credentials) return undefined
|
||||
|
||||
return { url: credentials.url, authorization: SidecarCredentials.authorization(credentials, credentials.url) }
|
||||
}
|
||||
|
||||
const clientFor = (module: NonNullable<SidecarClient["module"]>, endpoint: HostEndpoint) => {
|
||||
if (sidecar.active && sameHostEndpoint(sidecar.active.endpoint, endpoint)) return sidecar.active.client
|
||||
const headers: Record<string, string> = endpoint.authorization ? { authorization: endpoint.authorization } : {}
|
||||
const client = module.OpenCode.make({ baseUrl: endpoint.url, headers })
|
||||
sidecar.active = { endpoint, client }
|
||||
|
||||
return client
|
||||
}
|
||||
|
||||
const sidecarClient = () => {
|
||||
const endpoint = server("sidecar")
|
||||
const endpoint = sidecarEndpoint()
|
||||
|
||||
if (!endpoint || !sidecar.module) return undefined
|
||||
const key = JSON.stringify([endpoint.url, endpoint.headers])
|
||||
|
||||
if (sidecar.key !== key)
|
||||
Object.assign(sidecar, {
|
||||
key,
|
||||
client: sidecar.module.OpenCode.make({ baseUrl: endpoint.url, headers: { ...endpoint.headers } }),
|
||||
})
|
||||
|
||||
return sidecar.client
|
||||
return clientFor(sidecar.module, endpoint)
|
||||
}
|
||||
|
||||
// Follows the app's own server, as the TUI does: lists its plugins on each connection and each `plugin.updated`.
|
||||
// Every connection and reconnect of the server starts a new follow, so a new endpoint is followed at once.
|
||||
const watchPlugins = async () => {
|
||||
sidecar.module ??= await loadClient()
|
||||
const client = sidecarClient()
|
||||
let following = createHostState()
|
||||
const resources: HostResources = {}
|
||||
|
||||
if (!client || isQuitting(input.appState())) return
|
||||
inventory.watch?.abort()
|
||||
const watch = new AbortController()
|
||||
inventory.watch = watch
|
||||
void followPlugins(client, watch.signal)
|
||||
const quitting = () => isQuitting(input.appState())
|
||||
|
||||
const dispatch = (event: HostEvent<Listing>) => {
|
||||
const next = transitionHost(following, event)
|
||||
following = next.state
|
||||
// Each command runs on its own, so one that throws cannot keep the rest from running.
|
||||
next.commands.forEach((command) =>
|
||||
Promise.try(() => perform(command)).catch((cause: unknown) =>
|
||||
input.log("plugin host command failed", { command: command.type, cause: String(cause) }),
|
||||
),
|
||||
)
|
||||
}
|
||||
|
||||
const follow = () =>
|
||||
void watchPlugins().catch((cause: unknown) => input.log("plugin watch failed", { cause: String(cause) }))
|
||||
const perform = (command: HostCommand<Listing>) => {
|
||||
switch (command.type) {
|
||||
case "subscribe-credentials":
|
||||
resources.unfollow = SidecarCredentials.onChange(() =>
|
||||
dispatch({ type: "endpoint.changed", endpoint: sidecarEndpoint(), quitting: quitting() }),
|
||||
)
|
||||
|
||||
const followPlugins = async (client: OpenCodeClient, signal: AbortSignal) => {
|
||||
while (!signal.aborted) {
|
||||
await readEvents(client, signal).catch(() => undefined)
|
||||
return
|
||||
case "unsubscribe-credentials":
|
||||
resources.unfollow?.()
|
||||
resources.unfollow = undefined
|
||||
|
||||
if (signal.aborted) return
|
||||
// The stream ended while the endpoint stayed the same; subscribe again after a pause.
|
||||
await new Promise((resolve) => setTimeout(resolve, 1_000))
|
||||
return
|
||||
case "start-watch":
|
||||
return void watchPlugins(command.attempt, command.endpoint)
|
||||
case "schedule-watch-retry":
|
||||
clearTimeout(resources.watchTimer)
|
||||
resources.watchTimer = setTimeout(
|
||||
() => dispatch({ type: "watch.retry-due", attempt: command.attempt, quitting: quitting() }),
|
||||
command.delayMs,
|
||||
)
|
||||
|
||||
return
|
||||
case "cancel-watch":
|
||||
resources.watch?.abort()
|
||||
resources.watch = undefined
|
||||
clearTimeout(resources.watchTimer)
|
||||
resources.watchTimer = undefined
|
||||
|
||||
return
|
||||
case "start-list":
|
||||
return void listPlugins(command.attempt, command.endpoint, command.timeoutMs)
|
||||
case "cancel-list":
|
||||
resources.list?.abort()
|
||||
resources.list = undefined
|
||||
clearTimeout(resources.listTimer)
|
||||
resources.listTimer = undefined
|
||||
|
||||
return
|
||||
case "apply-listing":
|
||||
command.listing.skipped.forEach((revision, id) => skipped.set(id, revision))
|
||||
|
||||
return applyPlugins(command.listing.plugins, command.listing.reserved, command.listing.parts)
|
||||
case "log-list-error":
|
||||
return input.log("plugin listing failed", { cause: String(command.cause) })
|
||||
case "queue-menubar":
|
||||
return queueMicrotask(() => dispatch({ type: "menubar.flushed", quitting: quitting() }))
|
||||
case "publish-menubar":
|
||||
refreshMenu()
|
||||
|
||||
return broadcast(new PluginMenubarItemsChanged({ items: listMenubarItems() }))
|
||||
}
|
||||
}
|
||||
|
||||
const readEvents = async (client: OpenCodeClient, signal: AbortSignal) => {
|
||||
// Reads the server's event stream until it ends or the machine cancels it; an ended stream retries after a pause.
|
||||
const watchPlugins = async (attempt: number, endpoint: HostEndpoint) => {
|
||||
resources.watch?.abort()
|
||||
const controller = new AbortController()
|
||||
resources.watch = controller
|
||||
|
||||
const module = await loadModule().catch((cause: unknown) => {
|
||||
input.log("plugin watch failed", { cause: String(cause) })
|
||||
})
|
||||
|
||||
if (module && !controller.signal.aborted && isCurrentHostWatch(following, attempt))
|
||||
await readEvents(clientFor(module, endpoint), attempt, controller.signal).catch(() => undefined)
|
||||
|
||||
if (!controller.signal.aborted) dispatch({ type: "watch.ended", attempt, quitting: quitting() })
|
||||
}
|
||||
|
||||
const readEvents = async (client: OpenCodeClient, attempt: number, signal: AbortSignal) => {
|
||||
for await (const event of client.event.subscribe({ signal }))
|
||||
if (event.type === "plugin.updated" || event.type === "server.connected") relistPlugins()
|
||||
if (event.type === "plugin.updated" || event.type === "server.connected")
|
||||
dispatch({ type: "relist.requested", watchAttempt: attempt, quitting: quitting() })
|
||||
}
|
||||
|
||||
// Lists the plugins once, bounded by a timeout; the machine applies the result only while this listing is current.
|
||||
const listPlugins = async (attempt: number, endpoint: HostEndpoint, timeoutMs: number) => {
|
||||
resources.list?.abort()
|
||||
clearTimeout(resources.listTimer)
|
||||
const controller = new AbortController()
|
||||
resources.list = controller
|
||||
resources.listTimer = setTimeout(
|
||||
() => dispatch({ type: "list.timed-out", attempt, quitting: quitting() }),
|
||||
timeoutMs,
|
||||
)
|
||||
|
||||
const event = await readListing(endpoint, controller.signal).then(
|
||||
(listing): HostEvent<Listing> => ({ type: "list.succeeded", attempt, listing, quitting: quitting() }),
|
||||
(cause: unknown): HostEvent<Listing> => ({ type: "list.failed", attempt, cause, quitting: quitting() }),
|
||||
)
|
||||
|
||||
// Cancelled or timed out: the machine already moved on.
|
||||
if (controller.signal.aborted) return
|
||||
clearTimeout(resources.listTimer)
|
||||
resources.list = undefined
|
||||
resources.listTimer = undefined
|
||||
dispatch(event)
|
||||
}
|
||||
|
||||
// Lists the plugins on the app's own server that ship a `./gui-experimental` bundle and reads each bundle there. A
|
||||
// listing that fails is logged and keeps what main runs.
|
||||
const listPlugins = async () => {
|
||||
sidecar.module ??= await loadClient()
|
||||
const client = sidecarClient()
|
||||
|
||||
if (!client || isQuitting(input.appState())) return
|
||||
|
||||
const listed = await client.plugin.list().then(
|
||||
(result) => result.data,
|
||||
(cause: unknown) => void input.log("plugin listing failed", { cause: String(cause) }),
|
||||
)
|
||||
|
||||
if (!listed) return
|
||||
const readListing = async (endpoint: HostEndpoint, signal: AbortSignal): Promise<Listing> => {
|
||||
const client = clientFor(await loadModule(), endpoint)
|
||||
const listed = (await client.plugin.list(undefined, { signal })).data
|
||||
|
||||
const shipped = listed.filter(shipsPluginGui)
|
||||
const reserved = shipped.flatMap((plugin) => (pluginIdAvailable(plugin.id, definitions) ? [] : [plugin.id]))
|
||||
@@ -462,12 +561,15 @@ export function createHost(input: {
|
||||
unreadable: new Map<string, string>(),
|
||||
}
|
||||
|
||||
const found = new Map<string, string>()
|
||||
|
||||
const read = await Promise.all(
|
||||
shipped.filter((plugin) => !reserved.includes(plugin.id)).map((plugin) => readPlugin(client, plugin.id, parts)),
|
||||
shipped
|
||||
.filter((plugin) => !reserved.includes(plugin.id))
|
||||
.map((plugin) => readPlugin(client, plugin.id, { ...parts, skipped: found }, signal)),
|
||||
)
|
||||
|
||||
if (isQuitting(input.appState())) return
|
||||
applyPlugins(new Map(read.flatMap((entry) => (entry ? [entry] : []))), reserved, parts)
|
||||
return { plugins: new Map(read.flatMap((entry) => (entry ? [entry] : []))), reserved, parts, skipped: found }
|
||||
}
|
||||
|
||||
// Reads a plugin's bundle and evaluates each new revision once. A read that fails is logged and keeps the bundle
|
||||
@@ -476,13 +578,19 @@ export function createHost(input: {
|
||||
const readPlugin = async (
|
||||
client: OpenCodeClient,
|
||||
id: string,
|
||||
parts: { readonly unsupported: Set<string>; readonly unreadable: Map<string, string> },
|
||||
parts: {
|
||||
readonly unsupported: Set<string>
|
||||
readonly unreadable: Map<string, string>
|
||||
readonly skipped: Map<string, string>
|
||||
},
|
||||
signal: AbortSignal,
|
||||
) => {
|
||||
const previous = plugins.get(id)
|
||||
|
||||
const bundle = await client.plugin.gui({ id }).then(
|
||||
const bundle = await client.plugin.gui({ id }, { signal }).then(
|
||||
(result) => result.data,
|
||||
(cause: unknown) => {
|
||||
if (signal.aborted) return
|
||||
input.log("plugin bundle read failed", { id, cause: String(cause) })
|
||||
|
||||
if (!previous) parts.unreadable.set(id, cause instanceof Error ? cause.message : String(cause))
|
||||
@@ -495,7 +603,8 @@ export function createHost(input: {
|
||||
|
||||
if (skipped.get(id) === bundle.revision) return void parts.unsupported.add(id)
|
||||
|
||||
if (isQuitting(input.appState())) return undefined
|
||||
// A listing that was cancelled, timed out or outlived the app evaluates nothing more.
|
||||
if (signal.aborted || quitting()) return undefined
|
||||
|
||||
const loaded = await evaluateMain(bundle.code).then(
|
||||
(value) => ({ ok: true as const, value }),
|
||||
@@ -503,7 +612,7 @@ export function createHost(input: {
|
||||
)
|
||||
|
||||
if (!loaded.ok || runsOn(loaded.value, os)) return [id, { bundle, loaded }] as const
|
||||
skipped.set(id, bundle.revision)
|
||||
parts.skipped.set(id, bundle.revision)
|
||||
|
||||
return void parts.unsupported.add(id)
|
||||
}
|
||||
@@ -552,21 +661,6 @@ export function createHost(input: {
|
||||
})
|
||||
}
|
||||
|
||||
// One listing at a time; a change during a listing lists once more.
|
||||
const relistPlugins = () => {
|
||||
if (status.listing) return void (status.relist = true)
|
||||
status.listing = true
|
||||
void listPlugins()
|
||||
.catch((cause: unknown) => input.log("plugin listing failed", { cause: String(cause) }))
|
||||
.finally(() => {
|
||||
status.listing = false
|
||||
|
||||
if (!status.relist) return
|
||||
status.relist = false
|
||||
relistPlugins()
|
||||
})
|
||||
}
|
||||
|
||||
// What every window loads: the plugins main runs, and the ids a built-in claims.
|
||||
const pluginGuis = () => ({
|
||||
plugins: [...plugins].map(([id, plugin]) => ({
|
||||
@@ -612,7 +706,7 @@ export function createHost(input: {
|
||||
function add<T>(registry: Registry<T>, item: T | (() => T | undefined)): Cleanup {
|
||||
if (signal.aborted) return () => {}
|
||||
|
||||
const key = `${id}/${++status.sequence}`
|
||||
const key = `${id}/${++nextEntry}`
|
||||
entries.set(key, { registry: registry.id, plugin: id, value: item })
|
||||
|
||||
if (registry.id === MenubarItem.id) scheduleMenubar()
|
||||
@@ -882,31 +976,26 @@ export function createHost(input: {
|
||||
)
|
||||
|
||||
// Plugins listed from the server before a stop are known already; the listing that follows reconciles the rest.
|
||||
const start = async () => {
|
||||
inventory.stop ??= SidecarCredentials.onChange(follow)
|
||||
follow()
|
||||
await Promise.all(
|
||||
[...local.map((definition) => definition.id), ...plugins.keys()].map((id) => lifecycle.activate(id)),
|
||||
)
|
||||
}
|
||||
const activateAll = () =>
|
||||
Promise.all([...local.map((definition) => definition.id), ...plugins.keys()].map((id) => lifecycle.activate(id)))
|
||||
|
||||
return {
|
||||
/**
|
||||
* Activates every enabled main plugin, then follows the app's own server for plugin GUIs. The app calls this once
|
||||
* its first window is up.
|
||||
*/
|
||||
start,
|
||||
async start() {
|
||||
dispatch({ type: "started", endpoint: sidecarEndpoint(), quitting: quitting() })
|
||||
await activateAll()
|
||||
},
|
||||
/** Starts again what `stop` stopped, once a restart handoff failed. */
|
||||
async resume() {
|
||||
scheduleMenubar()
|
||||
await start()
|
||||
dispatch({ type: "resumed", endpoint: sidecarEndpoint(), quitting: quitting() })
|
||||
await activateAll()
|
||||
},
|
||||
/** Stops every main plugin but one a restart handoff keeps, and the follow of the server; awaits their cleanups. */
|
||||
async stop() {
|
||||
inventory.stop?.()
|
||||
inventory.stop = undefined
|
||||
inventory.watch?.abort()
|
||||
inventory.watch = undefined
|
||||
dispatch({ type: "stopped" })
|
||||
await lifecycle.stop()
|
||||
},
|
||||
/** Activates the plugin whose id the Ipc's id names, ahead of `start`. */
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import type { ExperimentalMigrationV1StatusOutput } from "@opencode/client/promise"
|
||||
import {
|
||||
createMigrationState,
|
||||
selectMigrationProgress,
|
||||
selectMigrationToastVisible,
|
||||
transitionMigration,
|
||||
type MigrationEvent,
|
||||
type MigrationState,
|
||||
} from "./migration-status-machine"
|
||||
|
||||
const progress = { label: "Migrating sessions", numerator: 3, denominator: 10 }
|
||||
|
||||
const running: ExperimentalMigrationV1StatusOutput = { status: "running", progress }
|
||||
|
||||
// Polls once: the due wait, then the request's answer for the attempt it started.
|
||||
function poll(state: MigrationState, answer: (attempt: number) => MigrationEvent) {
|
||||
if (state.status !== "waiting") throw new Error(`expected waiting, got ${state.status}`)
|
||||
const polling = transitionMigration(state, { type: "poll.due", attempt: state.attempt }).state
|
||||
|
||||
if (polling.status !== "polling") throw new Error(`expected polling, got ${polling.status}`)
|
||||
|
||||
return transitionMigration(polling, answer(polling.attempt))
|
||||
}
|
||||
|
||||
describe("migration status poll", () => {
|
||||
test("keeps the running toast and retries with backoff after a transport failure", () => {
|
||||
const first = poll(createMigrationState().state, (attempt) => ({
|
||||
type: "poll.succeeded",
|
||||
attempt,
|
||||
output: running,
|
||||
}))
|
||||
|
||||
expect(selectMigrationToastVisible(first.state)).toBe(true)
|
||||
|
||||
// On dev a single `Failed to fetch` stopped polling and showed "migration failed" while it was still running.
|
||||
const delays = [1, 2, 3, 4, 5, 6, 7].reduce<{ state: MigrationState; delays: number[] }>(
|
||||
(result) => {
|
||||
const next = poll(result.state, (attempt) => ({ type: "poll.failed", attempt }))
|
||||
const wait = next.effects.find((effect) => effect.type === "start-wait")
|
||||
|
||||
expect(next.effects.some((effect) => effect.type === "show-error")).toBe(false)
|
||||
expect(selectMigrationProgress(next.state)).toEqual(progress)
|
||||
|
||||
return { state: next.state, delays: [...result.delays, wait?.delayMs ?? 0] }
|
||||
},
|
||||
{ state: first.state, delays: [] },
|
||||
)
|
||||
|
||||
expect(delays.delays).toEqual([1_000, 2_000, 4_000, 8_000, 16_000, 32_000, 32_000])
|
||||
|
||||
const recovered = poll(delays.state, (attempt) => ({
|
||||
type: "poll.succeeded",
|
||||
attempt,
|
||||
output: { status: "required" },
|
||||
}))
|
||||
|
||||
expect(recovered.effects).toContainEqual({ type: "start-wait", attempt: expect.any(Number), delayMs: 1_000 })
|
||||
expect(selectMigrationToastVisible(recovered.state)).toBe(false)
|
||||
|
||||
const done = poll(recovered.state, (attempt) => ({
|
||||
type: "poll.succeeded",
|
||||
attempt,
|
||||
output: { status: "completed" },
|
||||
}))
|
||||
|
||||
expect(done.state).toEqual({ status: "completed" })
|
||||
expect(done.effects).toEqual([{ type: "cancel-timer" }])
|
||||
})
|
||||
|
||||
test("reports a migration error answer and stops", () => {
|
||||
const failed = poll(createMigrationState().state, (attempt) => ({
|
||||
type: "poll.succeeded",
|
||||
attempt,
|
||||
output: { status: "error", error: "corrupt db" },
|
||||
}))
|
||||
|
||||
expect(failed.state).toEqual({ status: "failed", error: "corrupt db" })
|
||||
expect(failed.effects).toEqual([{ type: "cancel-timer" }, { type: "show-error", error: "corrupt db" }])
|
||||
expect(selectMigrationToastVisible(failed.state)).toBe(false)
|
||||
})
|
||||
|
||||
test("aborts a hung request and ignores its late answer", () => {
|
||||
const start = createMigrationState().state
|
||||
const polling = transitionMigration(start, { type: "poll.due", attempt: 1 }).state
|
||||
const timedOut = transitionMigration(polling, { type: "poll.timed-out", attempt: 2 })
|
||||
|
||||
expect(timedOut.effects).toEqual([{ type: "abort-poll" }, { type: "start-wait", attempt: 3, delayMs: 1_000 }])
|
||||
expect(transitionMigration(timedOut.state, { type: "poll.failed", attempt: 2 }).state).toBe(timedOut.state)
|
||||
expect(
|
||||
transitionMigration(timedOut.state, { type: "poll.succeeded", attempt: 2, output: { status: "completed" } })
|
||||
.state,
|
||||
).toBe(timedOut.state)
|
||||
})
|
||||
|
||||
test("ignores stale timers and cancels work when disposed", () => {
|
||||
const start = createMigrationState().state
|
||||
|
||||
expect(transitionMigration(start, { type: "poll.due", attempt: 7 }).state).toBe(start)
|
||||
|
||||
const polling = transitionMigration(start, { type: "poll.due", attempt: 1 }).state
|
||||
|
||||
expect(transitionMigration(polling, { type: "disposed" })).toEqual({
|
||||
state: { status: "disposed" },
|
||||
effects: [{ type: "cancel-timer" }, { type: "abort-poll" }],
|
||||
})
|
||||
expect(transitionMigration(start, { type: "disposed" }).effects).toEqual([{ type: "cancel-timer" }])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,123 @@
|
||||
import type { ExperimentalMigrationV1StatusOutput } from "@opencode/client/promise"
|
||||
|
||||
export const MIGRATION_POLL_MS = 1_000
|
||||
|
||||
export const MIGRATION_POLL_TIMEOUT_MS = 10_000
|
||||
|
||||
const MAX_RETRY_EXPONENT = 5
|
||||
|
||||
export type MigrationProgress = Extract<ExperimentalMigrationV1StatusOutput, { status: "running" }>["progress"]
|
||||
|
||||
// `progress` is the last running answer: a transport failure keeps it, so the toast does not flicker.
|
||||
export type MigrationState =
|
||||
| {
|
||||
readonly status: "waiting" | "polling"
|
||||
readonly attempt: number
|
||||
readonly failures: number
|
||||
readonly progress: MigrationProgress | undefined
|
||||
}
|
||||
| { readonly status: "completed" }
|
||||
| { readonly status: "failed"; readonly error: string }
|
||||
| { readonly status: "disposed" }
|
||||
|
||||
export type MigrationEvent =
|
||||
| { readonly type: "poll.due"; readonly attempt: number }
|
||||
| { readonly type: "poll.succeeded"; readonly attempt: number; readonly output: ExperimentalMigrationV1StatusOutput }
|
||||
| { readonly type: "poll.failed"; readonly attempt: number }
|
||||
| { readonly type: "poll.timed-out"; readonly attempt: number }
|
||||
| { readonly type: "disposed" }
|
||||
|
||||
export type MigrationEffect =
|
||||
| { readonly type: "start-wait"; readonly attempt: number; readonly delayMs: number }
|
||||
| { readonly type: "start-poll"; readonly attempt: number; readonly timeoutMs: number }
|
||||
| { readonly type: "cancel-timer" }
|
||||
| { readonly type: "abort-poll" }
|
||||
| { readonly type: "show-error"; readonly error: string }
|
||||
|
||||
export type MigrationTransition = {
|
||||
readonly state: MigrationState
|
||||
readonly effects: readonly MigrationEffect[]
|
||||
}
|
||||
|
||||
export function createMigrationState(): MigrationTransition {
|
||||
return {
|
||||
state: { status: "waiting", attempt: 1, failures: 0, progress: undefined },
|
||||
effects: [{ type: "start-wait", attempt: 1, delayMs: MIGRATION_POLL_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
export function transitionMigration(state: MigrationState, event: MigrationEvent): MigrationTransition {
|
||||
if (event.type === "disposed") {
|
||||
if (state.status === "disposed") return unchanged(state)
|
||||
|
||||
if (state.status === "waiting") return { state: { status: "disposed" }, effects: [{ type: "cancel-timer" }] }
|
||||
|
||||
if (state.status === "polling")
|
||||
return { state: { status: "disposed" }, effects: [{ type: "cancel-timer" }, { type: "abort-poll" }] }
|
||||
|
||||
return { state: { status: "disposed" }, effects: [] }
|
||||
}
|
||||
|
||||
if (event.type === "poll.due") {
|
||||
if (state.status !== "waiting" || state.attempt !== event.attempt) return unchanged(state)
|
||||
const attempt = state.attempt + 1
|
||||
|
||||
return {
|
||||
state: { ...state, status: "polling", attempt },
|
||||
effects: [{ type: "start-poll", attempt, timeoutMs: MIGRATION_POLL_TIMEOUT_MS }],
|
||||
}
|
||||
}
|
||||
|
||||
if (state.status !== "polling" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
if (event.type === "poll.succeeded") {
|
||||
const output = event.output
|
||||
|
||||
if (output.status === "completed") return { state: { status: "completed" }, effects: [{ type: "cancel-timer" }] }
|
||||
|
||||
if (output.status === "error")
|
||||
return {
|
||||
state: { status: "failed", error: output.error },
|
||||
effects: [{ type: "cancel-timer" }, { type: "show-error", error: output.error }],
|
||||
}
|
||||
|
||||
return wait(state.attempt + 1, 0, output.status === "running" ? output.progress : undefined, [
|
||||
{ type: "cancel-timer" },
|
||||
])
|
||||
}
|
||||
|
||||
// A transport failure or a hung request says nothing about the migration: keep the toast and retry with backoff.
|
||||
const delay = MIGRATION_POLL_MS * 2 ** Math.min(state.failures, MAX_RETRY_EXPONENT)
|
||||
|
||||
const before: MigrationEffect[] =
|
||||
event.type === "poll.timed-out" ? [{ type: "abort-poll" }] : [{ type: "cancel-timer" }]
|
||||
|
||||
return wait(state.attempt + 1, state.failures + 1, state.progress, before, delay)
|
||||
}
|
||||
|
||||
export function selectMigrationProgress(state: MigrationState) {
|
||||
if (state.status === "waiting" || state.status === "polling") return state.progress
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function selectMigrationToastVisible(state: MigrationState) {
|
||||
return selectMigrationProgress(state) !== undefined
|
||||
}
|
||||
|
||||
function wait(
|
||||
attempt: number,
|
||||
failures: number,
|
||||
progress: MigrationProgress | undefined,
|
||||
before: readonly MigrationEffect[],
|
||||
delayMs = MIGRATION_POLL_MS,
|
||||
): MigrationTransition {
|
||||
return {
|
||||
state: { status: "waiting", attempt, failures, progress },
|
||||
effects: [...before, { type: "start-wait", attempt, delayMs }],
|
||||
}
|
||||
}
|
||||
|
||||
function unchanged(state: MigrationState): MigrationTransition {
|
||||
return { state, effects: [] }
|
||||
}
|
||||
@@ -1,20 +1,33 @@
|
||||
import { OpenCode, type ExperimentalMigrationV1StatusOutput } from "@opencode/client/promise"
|
||||
import { OpenCode } from "@opencode/client/promise"
|
||||
import { useLanguage } from "@opencode/app/desktop"
|
||||
import { Loader } from "@opencode/ui/loader"
|
||||
import { showToast, toaster, Toast } from "@opencode/ui/toast"
|
||||
import { createRoot, createSignal, onCleanup, onMount } from "solid-js"
|
||||
import { createEffect, createRoot, createSignal, onCleanup, onMount } from "solid-js"
|
||||
import type { ServerReadyData } from "../shared/ipc-contract"
|
||||
import {
|
||||
createMigrationState,
|
||||
selectMigrationProgress,
|
||||
selectMigrationToastVisible,
|
||||
transitionMigration,
|
||||
type MigrationEffect,
|
||||
type MigrationEvent,
|
||||
type MigrationProgress,
|
||||
} from "./migration-status-machine"
|
||||
|
||||
type Progress = Extract<ExperimentalMigrationV1StatusOutput, { status: "running" }>["progress"]
|
||||
type ToastHandle = { id: number; closed: boolean; dispose: (() => void) | undefined }
|
||||
|
||||
export function MigrationStatus(props: { server: ServerReadyData }) {
|
||||
const language = useLanguage()
|
||||
const [progress, setProgress] = createSignal<Progress>()
|
||||
const abort = new AbortController()
|
||||
let toastID: number | undefined
|
||||
let disposeToast: (() => void) | undefined
|
||||
const initial = createMigrationState()
|
||||
const [state, setState] = createSignal(initial.state)
|
||||
// The main process credentials sidecar requests; see `wireRendererHeaders`.
|
||||
const client = OpenCode.make({ baseUrl: props.server.url })
|
||||
let timer: ReturnType<typeof setTimeout> | undefined
|
||||
let controller: AbortController | undefined
|
||||
// One handle per shown toast: a render that lands after the dismissal disposes its own root at once.
|
||||
let toast: ToastHandle | undefined
|
||||
|
||||
const format = (progress: Progress | undefined) => {
|
||||
const format = (progress: MigrationProgress | undefined) => {
|
||||
if (!progress) return ""
|
||||
|
||||
if (progress.label === "Clearing old events") return language.t("toast.migration.progress.clearingOldEvents")
|
||||
@@ -46,19 +59,22 @@ export function MigrationStatus(props: { server: ServerReadyData }) {
|
||||
}
|
||||
|
||||
const hide = () => {
|
||||
if (toastID !== undefined) toaster.dismiss(toastID)
|
||||
toastID = undefined
|
||||
disposeToast?.()
|
||||
disposeToast = undefined
|
||||
if (!toast) return
|
||||
toast.closed = true
|
||||
toaster.dismiss(toast.id)
|
||||
toast.dispose?.()
|
||||
toast = undefined
|
||||
}
|
||||
|
||||
const show = () => {
|
||||
if (toastID !== undefined) return
|
||||
toastID = toaster.show(
|
||||
({ toastId }) =>
|
||||
createRoot((dispose) => {
|
||||
disposeToast?.()
|
||||
disposeToast = dispose
|
||||
if (toast) return
|
||||
const handle: ToastHandle = { id: 0, closed: false, dispose: undefined }
|
||||
toast = handle
|
||||
handle.id = toaster.show(
|
||||
({ toastId }) => {
|
||||
const view = createRoot((dispose) => {
|
||||
handle.dispose?.()
|
||||
handle.dispose = dispose
|
||||
|
||||
return (
|
||||
<Toast toastId={toastId}>
|
||||
@@ -67,66 +83,81 @@ export function MigrationStatus(props: { server: ServerReadyData }) {
|
||||
<Loader />
|
||||
</Toast.Icon>
|
||||
<Toast.Content>
|
||||
<Toast.Title dir="auto">{format(progress())}</Toast.Title>
|
||||
<Toast.Title dir="auto">{format(selectMigrationProgress(state()))}</Toast.Title>
|
||||
</Toast.Content>
|
||||
</div>
|
||||
</Toast>
|
||||
)
|
||||
}),
|
||||
})
|
||||
|
||||
if (handle.closed) handle.dispose?.()
|
||||
|
||||
return view
|
||||
},
|
||||
{ persistent: true },
|
||||
)
|
||||
}
|
||||
|
||||
onMount(async () => {
|
||||
await wait(1_000, abort.signal)
|
||||
const run = (effect: MigrationEffect) => {
|
||||
if (effect.type === "start-wait") {
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => dispatch({ type: "poll.due", attempt: effect.attempt }), effect.delayMs)
|
||||
|
||||
if (abort.signal.aborted) return
|
||||
return
|
||||
}
|
||||
|
||||
// The main process credentials sidecar requests; see `wireRendererHeaders`.
|
||||
const client = OpenCode.make({ baseUrl: props.server.url })
|
||||
if (effect.type === "start-poll") {
|
||||
controller?.abort()
|
||||
const current = new AbortController()
|
||||
controller = current
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => dispatch({ type: "poll.timed-out", attempt: effect.attempt }), effect.timeoutMs)
|
||||
void client.experimental.migration.v1.status({ signal: current.signal }).then(
|
||||
(output) => dispatch({ type: "poll.succeeded", attempt: effect.attempt, output }),
|
||||
() => dispatch({ type: "poll.failed", attempt: effect.attempt }),
|
||||
)
|
||||
|
||||
void (async () => {
|
||||
while (true) {
|
||||
const status = await client.experimental.migration.v1.status({ signal: abort.signal })
|
||||
setProgress(status.status === "running" ? status.progress : undefined)
|
||||
return
|
||||
}
|
||||
|
||||
if (status.status === "running") show()
|
||||
else hide()
|
||||
if (effect.type === "cancel-timer") {
|
||||
clearTimeout(timer)
|
||||
timer = undefined
|
||||
|
||||
if (status.status === "completed") return
|
||||
return
|
||||
}
|
||||
|
||||
if (status.status === "error") throw new Error(status.error)
|
||||
await wait(1_000, abort.signal)
|
||||
}
|
||||
})().catch((error) => {
|
||||
if (abort.signal.aborted) return
|
||||
hide()
|
||||
showToast({
|
||||
variant: "error",
|
||||
title: language.t("toast.migration.failed.title"),
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
duration: 10_000,
|
||||
})
|
||||
if (effect.type === "abort-poll") {
|
||||
controller?.abort()
|
||||
controller = undefined
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
showToast({
|
||||
variant: "error",
|
||||
title: language.t("toast.migration.failed.title"),
|
||||
description: effect.error,
|
||||
duration: 10_000,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const dispatch = (event: MigrationEvent) => {
|
||||
const next = transitionMigration(state(), event)
|
||||
|
||||
if (next.state === state()) return
|
||||
setState(next.state)
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
createEffect(() => (selectMigrationToastVisible(state()) ? show() : hide()))
|
||||
|
||||
onMount(() => initial.effects.forEach(run))
|
||||
|
||||
onCleanup(() => {
|
||||
abort.abort()
|
||||
dispatch({ type: "disposed" })
|
||||
hide()
|
||||
})
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
function wait(delay: number, signal: AbortSignal) {
|
||||
return new Promise<void>((resolve) => {
|
||||
const timer = setTimeout(done, delay)
|
||||
signal.addEventListener("abort", done, { once: true })
|
||||
|
||||
function done() {
|
||||
clearTimeout(timer)
|
||||
signal.removeEventListener("abort", done)
|
||||
resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { nextDesktopZoomLevel } from "@opencode/app/desktop-menu"
|
||||
import {
|
||||
createZoomState,
|
||||
selectRequestedZoom,
|
||||
selectWebviewZoom,
|
||||
transitionZoom,
|
||||
type ZoomEvent,
|
||||
type ZoomState,
|
||||
} from "./zoom-machine"
|
||||
|
||||
const reply = Promise.withResolvers<void>()
|
||||
|
||||
function replay(events: readonly ZoomEvent[], from = createZoomState()) {
|
||||
return events.reduce((state, event) => transitionZoom(state, event).state, from)
|
||||
}
|
||||
|
||||
const pinchOn = replay([{ type: "pinch.seeded", enabled: true }])
|
||||
|
||||
describe("zoom requests", () => {
|
||||
test("rolls a refused level back so the next step starts from the real zoom", () => {
|
||||
const refused = replay([
|
||||
{ type: "factor.seeded", factor: 1 },
|
||||
{ type: "level.requested", level: 1.1, reply },
|
||||
{ type: "level.failed", attempt: 1 },
|
||||
])
|
||||
|
||||
// On dev the refused 1.1 stuck as the requested zoom and the next Zoom In jumped to 1.25.
|
||||
expect(selectRequestedZoom(refused)).toBe(1)
|
||||
expect(nextDesktopZoomLevel(selectRequestedZoom(refused), "in")).toBe(1.1)
|
||||
})
|
||||
|
||||
test("keeps a reset to 1 when the boot read of the reloaded window's zoom lands later", () => {
|
||||
const state = replay([
|
||||
{ type: "level.requested", level: 1, reply },
|
||||
{ type: "factor.seeded", factor: 1.5 },
|
||||
{ type: "level.seeded", level: 1.5 },
|
||||
])
|
||||
|
||||
expect(selectWebviewZoom(state)).toBe(1)
|
||||
expect(selectRequestedZoom(state)).toBe(1)
|
||||
expect(state.level).toBe(1)
|
||||
})
|
||||
|
||||
test("keeps the newest step pending while main reports an earlier one", () => {
|
||||
const stepped = replay([
|
||||
{ type: "level.requested", level: 1.1, reply },
|
||||
{ type: "level.requested", level: 1.25, reply },
|
||||
{ type: "zoom.changed", factor: 1.1000000001, level: 1.1 },
|
||||
])
|
||||
|
||||
expect(selectRequestedZoom(stepped)).toBe(1.25)
|
||||
expect(replay([{ type: "level.succeeded", attempt: 1 }], stepped)).toBe(stepped)
|
||||
expect(selectRequestedZoom(replay([{ type: "level.failed", attempt: 2 }], stepped))).toBe(1.1000000001)
|
||||
expect(selectWebviewZoom(replay([{ type: "zoom.changed", factor: 1.25, level: 1.25 }], stepped))).toBe(1.25)
|
||||
})
|
||||
|
||||
test("restores the pinch setting and wheel listener when main refuses it", () => {
|
||||
const requested = transitionZoom(pinchOn, { type: "pinch.requested", enabled: false, reply })
|
||||
|
||||
expect(requested.effects).toEqual([
|
||||
{ type: "sync-wheel-listener", enabled: false },
|
||||
{ type: "set-pinch-zoom", attempt: 1, enabled: false, reply },
|
||||
])
|
||||
expect(transitionZoom(requested.state, { type: "pinch.failed", attempt: 1 }).effects).toEqual([
|
||||
{ type: "sync-wheel-listener", enabled: true },
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("wheel pinch", () => {
|
||||
const wheel = (delta: number): ZoomEvent => ({ type: "wheel.pinched", delta })
|
||||
|
||||
test("waits for the threshold, then zooms from the zoom at that point", () => {
|
||||
const small = transitionZoom(pinchOn, wheel(10))
|
||||
|
||||
expect(small.state.status).toBe("accumulating")
|
||||
expect(small.effects).toEqual([{ type: "arm-pinch-timer" }])
|
||||
|
||||
const started = replay([wheel(10)], small.state)
|
||||
|
||||
expect(started).toMatchObject({ status: "pinching", startZoom: 1, totalDelta: 0 })
|
||||
|
||||
const zoomed = transitionZoom(started, wheel(-20))
|
||||
|
||||
expect(zoomed.effects).toEqual([{ type: "arm-pinch-timer" }, { type: "set-zoom-factor", attempt: 1, factor: 1.2 }])
|
||||
expect(replay([{ type: "pinch.ended" }], zoomed.state).status).toBe("idle")
|
||||
})
|
||||
|
||||
test("ends the gesture when a keyboard step or another window changes the zoom", () => {
|
||||
const pinching = replay([wheel(-20), wheel(-20)], pinchOn)
|
||||
|
||||
// On dev the next wheel frame zoomed from the gesture's stale start zoom and undid the reset.
|
||||
const reset = transitionZoom(pinching, { type: "level.requested", level: 1, reply })
|
||||
|
||||
expect(reset.state.status).toBe("idle")
|
||||
expect(reset.effects[0]).toEqual({ type: "cancel-pinch-timer" })
|
||||
expect(transitionZoom(pinching, { type: "zoom.changed", factor: 2, level: 2 }).state.status).toBe("idle")
|
||||
|
||||
const next = replay([wheel(-20), wheel(-20)], replay([{ type: "level.succeeded", attempt: 2 }], reset.state))
|
||||
|
||||
expect(next).toMatchObject({ status: "pinching", startZoom: 1 })
|
||||
})
|
||||
|
||||
test("returns the same state for a zero delta or while pinch zoom is off", () => {
|
||||
const pinching = replay([wheel(-20)], pinchOn)
|
||||
const off: ZoomState = createZoomState()
|
||||
|
||||
expect(transitionZoom(pinching, wheel(0)).state).toBe(pinching)
|
||||
expect(transitionZoom(off, wheel(-40)).state).toBe(off)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,325 @@
|
||||
import type { DesktopZoomLevel } from "@opencode/app/desktop-menu"
|
||||
|
||||
const MAX_ZOOM_LEVEL = 10
|
||||
|
||||
const MIN_ZOOM_LEVEL = 0.2
|
||||
|
||||
const WHEEL_PINCH_THRESHOLD = 20
|
||||
|
||||
const WHEEL_PINCH_STEP = 0.2
|
||||
|
||||
export const WHEEL_PINCH_END_DELAY = 160
|
||||
|
||||
/** Settles the caller's promise once main answers. */
|
||||
export type ZoomReply = PromiseWithResolvers<void>
|
||||
|
||||
// Whether a Ctrl+wheel gesture zooms the page. `updating` keeps the previous value to restore if main refuses it.
|
||||
export type PinchSetting =
|
||||
| { readonly status: "unseeded" }
|
||||
| { readonly status: "settled"; readonly enabled: boolean }
|
||||
| { readonly status: "updating"; readonly attempt: number; readonly enabled: boolean; readonly previous: boolean }
|
||||
|
||||
// The zoom this renderer asked main for and has not seen land yet.
|
||||
export type ZoomRequest =
|
||||
| { readonly kind: "factor"; readonly attempt: number; readonly target: number }
|
||||
| { readonly kind: "level"; readonly attempt: number; readonly target: DesktopZoomLevel }
|
||||
|
||||
// `factorSeeded` and `levelSeeded` turn true on the first answer, user action or main event, so a late boot read
|
||||
// cannot overwrite a newer value.
|
||||
type ZoomBase = {
|
||||
readonly factor: number
|
||||
readonly factorSeeded: boolean
|
||||
readonly level: DesktopZoomLevel
|
||||
readonly levelSeeded: boolean
|
||||
readonly pinch: PinchSetting
|
||||
readonly nextAttempt: number
|
||||
readonly request: ZoomRequest | undefined
|
||||
}
|
||||
|
||||
// The wheel gesture: `accumulating` until the deltas cross the threshold, then `pinching` from the zoom at that point.
|
||||
export type ZoomState =
|
||||
| (ZoomBase & { readonly status: "idle" })
|
||||
| (ZoomBase & { readonly status: "accumulating"; readonly totalDelta: number })
|
||||
| (ZoomBase & { readonly status: "pinching"; readonly startZoom: number; readonly totalDelta: number })
|
||||
|
||||
export type ZoomEvent =
|
||||
| { readonly type: "factor.seeded"; readonly factor: number }
|
||||
| { readonly type: "factor.seed-failed" }
|
||||
| { readonly type: "level.seeded"; readonly level: DesktopZoomLevel }
|
||||
| { readonly type: "level.seed-failed" }
|
||||
| { readonly type: "pinch.seeded"; readonly enabled: boolean }
|
||||
| { readonly type: "pinch.changed"; readonly enabled: boolean }
|
||||
| { readonly type: "pinch.requested"; readonly enabled: boolean; readonly reply: ZoomReply }
|
||||
| { readonly type: "pinch.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "pinch.failed"; readonly attempt: number }
|
||||
| { readonly type: "zoom.changed"; readonly factor: number; readonly level: DesktopZoomLevel }
|
||||
| { readonly type: "level.requested"; readonly level: DesktopZoomLevel; readonly reply: ZoomReply }
|
||||
| { readonly type: "level.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "level.failed"; readonly attempt: number }
|
||||
| { readonly type: "factor.succeeded"; readonly attempt: number }
|
||||
| { readonly type: "factor.failed"; readonly attempt: number }
|
||||
// `delta` is writable so the wheel listener reuses one event object across frames.
|
||||
| { readonly type: "wheel.pinched"; delta: number }
|
||||
| { readonly type: "pinch.ended" }
|
||||
|
||||
export type ZoomEffect =
|
||||
| { readonly type: "sync-wheel-listener"; readonly enabled: boolean }
|
||||
| { readonly type: "arm-pinch-timer" }
|
||||
| { readonly type: "cancel-pinch-timer" }
|
||||
| { readonly type: "set-zoom-factor"; readonly attempt: number; readonly factor: number }
|
||||
| {
|
||||
readonly type: "set-zoom-level"
|
||||
readonly attempt: number
|
||||
readonly level: DesktopZoomLevel
|
||||
readonly reply: ZoomReply
|
||||
}
|
||||
| { readonly type: "set-pinch-zoom"; readonly attempt: number; readonly enabled: boolean; readonly reply: ZoomReply }
|
||||
|
||||
export type ZoomTransition = {
|
||||
readonly state: ZoomState
|
||||
readonly effects: readonly ZoomEffect[]
|
||||
}
|
||||
|
||||
type IdleZoom = Extract<ZoomState, { status: "idle" }>
|
||||
|
||||
export function createZoomState(): ZoomState {
|
||||
return {
|
||||
status: "idle",
|
||||
factor: 1,
|
||||
factorSeeded: false,
|
||||
level: 1,
|
||||
levelSeeded: false,
|
||||
pinch: { status: "unseeded" },
|
||||
nextAttempt: 1,
|
||||
request: undefined,
|
||||
}
|
||||
}
|
||||
|
||||
export function transitionZoom(state: ZoomState, event: ZoomEvent): ZoomTransition {
|
||||
switch (event.type) {
|
||||
case "wheel.pinched":
|
||||
return wheel(state, event.delta)
|
||||
|
||||
case "pinch.ended":
|
||||
if (state.status === "idle") return unchanged(state)
|
||||
|
||||
return { state: idle(state), effects: CANCEL_TIMER }
|
||||
|
||||
case "factor.seeded":
|
||||
if (state.factorSeeded) return unchanged(state)
|
||||
|
||||
return { state: { ...state, factor: clampZoom(event.factor), factorSeeded: true }, effects: NO_EFFECTS }
|
||||
|
||||
case "factor.seed-failed":
|
||||
if (state.factorSeeded) return unchanged(state)
|
||||
|
||||
return { state: { ...state, factorSeeded: true }, effects: NO_EFFECTS }
|
||||
|
||||
case "level.seeded":
|
||||
if (state.levelSeeded) return unchanged(state)
|
||||
|
||||
return { state: { ...state, level: event.level, levelSeeded: true }, effects: NO_EFFECTS }
|
||||
|
||||
case "level.seed-failed":
|
||||
if (state.levelSeeded) return unchanged(state)
|
||||
|
||||
return { state: { ...state, levelSeeded: true }, effects: NO_EFFECTS }
|
||||
|
||||
case "pinch.seeded":
|
||||
if (state.pinch.status !== "unseeded") return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { ...state, pinch: { status: "settled", enabled: event.enabled } },
|
||||
effects: event.enabled ? [{ type: "sync-wheel-listener", enabled: true }] : NO_EFFECTS,
|
||||
}
|
||||
|
||||
case "pinch.changed":
|
||||
return setPinch(state, { status: "settled", enabled: event.enabled }, NO_EFFECTS)
|
||||
|
||||
case "pinch.requested": {
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return setPinch(
|
||||
{ ...state, nextAttempt: attempt + 1 },
|
||||
{ status: "updating", attempt, enabled: event.enabled, previous: selectPinchEnabled(state) },
|
||||
[{ type: "set-pinch-zoom", attempt, enabled: event.enabled, reply: event.reply }],
|
||||
)
|
||||
}
|
||||
|
||||
case "pinch.succeeded":
|
||||
if (state.pinch.status !== "updating" || state.pinch.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { ...state, pinch: { status: "settled", enabled: state.pinch.enabled } }, effects: NO_EFFECTS }
|
||||
|
||||
case "pinch.failed":
|
||||
if (state.pinch.status !== "updating" || state.pinch.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return setPinch(state, { status: "settled", enabled: state.pinch.previous }, NO_EFFECTS)
|
||||
|
||||
case "zoom.changed": {
|
||||
// Main reports each level it applies; a newer level this renderer asked for may still be on its way.
|
||||
const pending = state.request?.kind === "level" && state.request.target !== event.level
|
||||
|
||||
const next: IdleZoom = {
|
||||
...idle(state),
|
||||
factor: clampZoom(event.factor),
|
||||
factorSeeded: true,
|
||||
level: event.level,
|
||||
levelSeeded: true,
|
||||
request: pending ? state.request : undefined,
|
||||
}
|
||||
|
||||
return { state: next, effects: state.status === "idle" ? NO_EFFECTS : CANCEL_TIMER }
|
||||
}
|
||||
|
||||
case "level.requested": {
|
||||
const attempt = state.nextAttempt
|
||||
const effect: ZoomEffect = { type: "set-zoom-level", attempt, level: event.level, reply: event.reply }
|
||||
|
||||
const next: IdleZoom = {
|
||||
...idle(state),
|
||||
factorSeeded: true,
|
||||
levelSeeded: true,
|
||||
nextAttempt: attempt + 1,
|
||||
request: { kind: "level", attempt, target: event.level },
|
||||
}
|
||||
|
||||
return { state: next, effects: state.status === "idle" ? [effect] : [CANCEL_PINCH_TIMER, effect] }
|
||||
}
|
||||
|
||||
case "level.succeeded":
|
||||
if (state.request?.kind !== "level" || state.request.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return {
|
||||
state: { ...state, factor: state.request.target, level: state.request.target, request: undefined },
|
||||
effects: NO_EFFECTS,
|
||||
}
|
||||
|
||||
case "level.failed":
|
||||
if (state.request?.kind !== "level" || state.request.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { ...state, request: undefined }, effects: NO_EFFECTS }
|
||||
|
||||
case "factor.succeeded":
|
||||
if (state.request?.kind !== "factor" || state.request.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { ...state, factor: state.request.target, request: undefined }, effects: NO_EFFECTS }
|
||||
|
||||
case "factor.failed":
|
||||
if (state.request?.kind !== "factor" || state.request.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
return { state: { ...state, request: undefined }, effects: NO_EFFECTS }
|
||||
}
|
||||
}
|
||||
|
||||
/** The zoom the window shows, as main last confirmed it. */
|
||||
export function selectWebviewZoom(state: ZoomState) {
|
||||
return state.factor
|
||||
}
|
||||
|
||||
export function selectZoomLevel(state: ZoomState) {
|
||||
return state.level
|
||||
}
|
||||
|
||||
/** The zoom the next step starts from: the pending request's target, else the confirmed zoom. */
|
||||
export function selectRequestedZoom(state: ZoomState) {
|
||||
return state.request?.target ?? state.factor
|
||||
}
|
||||
|
||||
export function selectPinchEnabled(state: ZoomState) {
|
||||
return state.pinch.status !== "unseeded" && state.pinch.enabled
|
||||
}
|
||||
|
||||
function clampZoom(value: number) {
|
||||
return Math.min(Math.max(value, MIN_ZOOM_LEVEL), MAX_ZOOM_LEVEL)
|
||||
}
|
||||
|
||||
// Frozen effect lists keep wheel frames free of allocations beyond the next state.
|
||||
const NO_EFFECTS: readonly ZoomEffect[] = Object.freeze([])
|
||||
|
||||
const ARM_PINCH_TIMER: ZoomEffect = Object.freeze({ type: "arm-pinch-timer" })
|
||||
|
||||
const CANCEL_PINCH_TIMER: ZoomEffect = Object.freeze({ type: "cancel-pinch-timer" })
|
||||
|
||||
const ARM_TIMER: readonly ZoomEffect[] = Object.freeze([ARM_PINCH_TIMER])
|
||||
|
||||
const CANCEL_TIMER: readonly ZoomEffect[] = Object.freeze([CANCEL_PINCH_TIMER])
|
||||
|
||||
function wheel(state: ZoomState, delta: number): ZoomTransition {
|
||||
if (!selectPinchEnabled(state)) return unchanged(state)
|
||||
|
||||
if (state.status === "idle") {
|
||||
if (Math.abs(delta) < WHEEL_PINCH_THRESHOLD)
|
||||
return { state: { ...state, status: "accumulating", totalDelta: delta }, effects: ARM_TIMER }
|
||||
|
||||
return {
|
||||
state: { ...state, status: "pinching", startZoom: selectRequestedZoom(state), totalDelta: 0 },
|
||||
effects: ARM_TIMER,
|
||||
}
|
||||
}
|
||||
|
||||
if (delta === 0) return { state, effects: ARM_TIMER }
|
||||
const totalDelta = state.totalDelta + delta
|
||||
|
||||
if (state.status === "accumulating") {
|
||||
if (Math.abs(totalDelta) < WHEEL_PINCH_THRESHOLD) return { state: { ...state, totalDelta }, effects: ARM_TIMER }
|
||||
|
||||
// The gesture starts from the zoom at the moment it crossed the threshold.
|
||||
return {
|
||||
state: { ...state, status: "pinching", startZoom: selectRequestedZoom(state), totalDelta: 0 },
|
||||
effects: ARM_TIMER,
|
||||
}
|
||||
}
|
||||
|
||||
const target = clampZoom(state.startZoom - (totalDelta / WHEEL_PINCH_THRESHOLD) * WHEEL_PINCH_STEP)
|
||||
|
||||
if (target === selectRequestedZoom(state)) return { state: { ...state, totalDelta }, effects: ARM_TIMER }
|
||||
const attempt = state.nextAttempt
|
||||
|
||||
return {
|
||||
state: {
|
||||
...state,
|
||||
totalDelta,
|
||||
factorSeeded: true,
|
||||
nextAttempt: attempt + 1,
|
||||
request: { kind: "factor", attempt, target },
|
||||
},
|
||||
effects: [ARM_PINCH_TIMER, { type: "set-zoom-factor", attempt, factor: target }],
|
||||
}
|
||||
}
|
||||
|
||||
// Turning pinch zoom off ends a gesture; the wheel listener follows the effective setting.
|
||||
function setPinch(state: ZoomState, setting: PinchSetting, after: readonly ZoomEffect[]): ZoomTransition {
|
||||
const before = selectPinchEnabled(state)
|
||||
const next: ZoomState = { ...state, pinch: setting }
|
||||
const enabled = selectPinchEnabled(next)
|
||||
const ends = !enabled && next.status !== "idle"
|
||||
|
||||
return {
|
||||
state: ends ? idle(next) : next,
|
||||
effects: [
|
||||
...(ends ? CANCEL_TIMER : NO_EFFECTS),
|
||||
...(before === enabled ? NO_EFFECTS : [{ type: "sync-wheel-listener" as const, enabled }]),
|
||||
...after,
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
function idle(state: ZoomState): IdleZoom {
|
||||
if (state.status === "idle") return state
|
||||
|
||||
return {
|
||||
status: "idle",
|
||||
factor: state.factor,
|
||||
factorSeeded: state.factorSeeded,
|
||||
level: state.level,
|
||||
levelSeeded: state.levelSeeded,
|
||||
pinch: state.pinch,
|
||||
nextAttempt: state.nextAttempt,
|
||||
request: state.request,
|
||||
}
|
||||
}
|
||||
|
||||
function unchanged(state: ZoomState): ZoomTransition {
|
||||
return { state, effects: NO_EFFECTS }
|
||||
}
|
||||
@@ -5,6 +5,16 @@
|
||||
import { nextDesktopZoomLevel, type DesktopZoomLevel } from "@opencode/app/desktop-menu"
|
||||
import { createSignal } from "solid-js"
|
||||
import { api } from "../api"
|
||||
import {
|
||||
createZoomState,
|
||||
selectRequestedZoom,
|
||||
selectWebviewZoom,
|
||||
selectZoomLevel,
|
||||
transitionZoom,
|
||||
WHEEL_PINCH_END_DELAY,
|
||||
type ZoomEffect,
|
||||
type ZoomEvent,
|
||||
} from "./zoom-machine"
|
||||
|
||||
const OS_NAME = (() => {
|
||||
if (navigator.userAgent.includes("Mac")) return "macos"
|
||||
@@ -20,96 +30,122 @@ const [webviewZoom, setWebviewZoom] = createSignal(1)
|
||||
|
||||
const [zoomLevel, setZoomLevelSignal] = createSignal<DesktopZoomLevel>(1)
|
||||
|
||||
let requestedZoom = 1
|
||||
let state = createZoomState()
|
||||
|
||||
let pinchZoomEnabled = false
|
||||
let pinchTimer: ReturnType<typeof setTimeout> | undefined
|
||||
|
||||
let wheelPinch:
|
||||
| {
|
||||
active: boolean
|
||||
startZoom: number
|
||||
totalDelta: number
|
||||
timeout: ReturnType<typeof setTimeout> | undefined
|
||||
}
|
||||
| undefined
|
||||
// Reused for every wheel frame, so a pinch gesture allocates no event objects.
|
||||
const wheelEvent: Extract<ZoomEvent, { type: "wheel.pinched" }> = { type: "wheel.pinched", delta: 0 }
|
||||
|
||||
const MAX_ZOOM_LEVEL = 10
|
||||
const endPinch: ZoomEvent = { type: "pinch.ended" }
|
||||
|
||||
const MIN_ZOOM_LEVEL = 0.2
|
||||
const dispatch = (event: ZoomEvent) => {
|
||||
const next = transitionZoom(state, event)
|
||||
|
||||
const WHEEL_PINCH_THRESHOLD = 20
|
||||
if (next.state !== state) {
|
||||
state = next.state
|
||||
setWebviewZoom(selectWebviewZoom(state))
|
||||
setZoomLevelSignal(selectZoomLevel(state))
|
||||
}
|
||||
|
||||
const WHEEL_PINCH_STEP = 0.2
|
||||
|
||||
const WHEEL_PINCH_END_DELAY = 160
|
||||
|
||||
const clamp = (value: number) => Math.min(Math.max(value, MIN_ZOOM_LEVEL), MAX_ZOOM_LEVEL)
|
||||
|
||||
const applyZoom = (next: number) => {
|
||||
requestedZoom = next
|
||||
void api
|
||||
.setZoomFactor(next)
|
||||
.then(() => {
|
||||
if (requestedZoom !== next) return
|
||||
setWebviewZoom(next)
|
||||
})
|
||||
.catch(() => {
|
||||
if (requestedZoom !== next) return
|
||||
requestedZoom = webviewZoom()
|
||||
})
|
||||
next.effects.forEach(run)
|
||||
}
|
||||
|
||||
// A renderer reload keeps the window's zoom, so seed the signal from main.
|
||||
void api.getZoomFactor().then((factor) => {
|
||||
if (requestedZoom !== 1) return
|
||||
requestedZoom = clamp(factor)
|
||||
setWebviewZoom(requestedZoom)
|
||||
})
|
||||
const run = (effect: ZoomEffect) => {
|
||||
if (effect.type === "arm-pinch-timer") {
|
||||
clearTimeout(pinchTimer)
|
||||
pinchTimer = setTimeout(() => dispatch(endPinch), WHEEL_PINCH_END_DELAY)
|
||||
|
||||
void api.getZoomLevel().then(setZoomLevelSignal)
|
||||
return
|
||||
}
|
||||
|
||||
api.onZoomChanged((zoom) => {
|
||||
requestedZoom = clamp(zoom.factor)
|
||||
setWebviewZoom(requestedZoom)
|
||||
setZoomLevelSignal(zoom.level)
|
||||
})
|
||||
if (effect.type === "cancel-pinch-timer") {
|
||||
clearTimeout(pinchTimer)
|
||||
pinchTimer = undefined
|
||||
|
||||
void api.getPinchZoomEnabled().then((enabled) => {
|
||||
pinchZoomEnabled = enabled
|
||||
syncWheelPinchListener()
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
api.onPinchZoomEnabledChanged((enabled) => {
|
||||
pinchZoomEnabled = enabled
|
||||
resetWheelPinch()
|
||||
syncWheelPinchListener()
|
||||
})
|
||||
// A cancelable window wheel listener makes every scroll gesture wait for the main thread, so it
|
||||
// is only attached while pinch zoom is on. Main's zoom-changed handler covers Ctrl+wheel otherwise.
|
||||
if (effect.type === "sync-wheel-listener") {
|
||||
if (!effect.enabled) return window.removeEventListener("wheel", onWheelPinch)
|
||||
window.addEventListener("wheel", onWheelPinch, { passive: false })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (effect.type === "set-zoom-factor") {
|
||||
void api.setZoomFactor(effect.factor).then(
|
||||
() => dispatch({ type: "factor.succeeded", attempt: effect.attempt }),
|
||||
() => dispatch({ type: "factor.failed", attempt: effect.attempt }),
|
||||
)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// The caller's promise follows main's answer, after the machine has seen it.
|
||||
if (effect.type === "set-zoom-level") {
|
||||
const call = api.setZoomLevel(effect.level)
|
||||
void call.then(
|
||||
() => dispatch({ type: "level.succeeded", attempt: effect.attempt }),
|
||||
() => dispatch({ type: "level.failed", attempt: effect.attempt }),
|
||||
)
|
||||
|
||||
return effect.reply.resolve(call)
|
||||
}
|
||||
|
||||
const call = api.setPinchZoomEnabled(effect.enabled)
|
||||
void call.then(
|
||||
() => dispatch({ type: "pinch.succeeded", attempt: effect.attempt }),
|
||||
() => dispatch({ type: "pinch.failed", attempt: effect.attempt }),
|
||||
)
|
||||
effect.reply.resolve(call)
|
||||
}
|
||||
|
||||
// A renderer reload keeps the window's zoom, so seed it from main unless something newer already set it.
|
||||
void api.getZoomFactor().then(
|
||||
(factor) => dispatch({ type: "factor.seeded", factor }),
|
||||
() => dispatch({ type: "factor.seed-failed" }),
|
||||
)
|
||||
|
||||
void api.getZoomLevel().then(
|
||||
(level) => dispatch({ type: "level.seeded", level }),
|
||||
() => dispatch({ type: "level.seed-failed" }),
|
||||
)
|
||||
|
||||
api.onZoomChanged((zoom) => dispatch({ type: "zoom.changed", factor: zoom.factor, level: zoom.level }))
|
||||
|
||||
void api.getPinchZoomEnabled().then(
|
||||
(enabled) => dispatch({ type: "pinch.seeded", enabled }),
|
||||
() => undefined,
|
||||
)
|
||||
|
||||
api.onPinchZoomEnabledChanged((enabled) => dispatch({ type: "pinch.changed", enabled }))
|
||||
|
||||
const setPinchZoomEnabled = (enabled: boolean) => {
|
||||
pinchZoomEnabled = enabled
|
||||
resetWheelPinch()
|
||||
syncWheelPinchListener()
|
||||
const reply = Promise.withResolvers<void>()
|
||||
dispatch({ type: "pinch.requested", enabled, reply })
|
||||
|
||||
return api.setPinchZoomEnabled(enabled)
|
||||
return reply.promise
|
||||
}
|
||||
|
||||
// Main saves the level and applies it to every window, then reports the new zoom back.
|
||||
const setZoomLevel = (level: DesktopZoomLevel) => {
|
||||
requestedZoom = level
|
||||
const reply = Promise.withResolvers<void>()
|
||||
dispatch({ type: "level.requested", level, reply })
|
||||
|
||||
return api.setZoomLevel(level)
|
||||
return reply.promise
|
||||
}
|
||||
|
||||
const resetZoom = () => void setZoomLevel(1)
|
||||
// A refused step was already rolled back by the machine; the keyboard shortcuts have no caller to report it to.
|
||||
const stepZoom = (level: DesktopZoomLevel) => void setZoomLevel(level).catch(() => undefined)
|
||||
|
||||
const zoomIn = () => void setZoomLevel(nextDesktopZoomLevel(requestedZoom, "in"))
|
||||
const resetZoom = () => stepZoom(1)
|
||||
|
||||
const zoomOut = () => void setZoomLevel(nextDesktopZoomLevel(requestedZoom, "out"))
|
||||
const zoomIn = () => stepZoom(nextDesktopZoomLevel(selectRequestedZoom(state), "in"))
|
||||
|
||||
const resetWheelPinch = () => {
|
||||
clearTimeout(wheelPinch?.timeout)
|
||||
wheelPinch = undefined
|
||||
}
|
||||
const zoomOut = () => stepZoom(nextDesktopZoomLevel(selectRequestedZoom(state), "out"))
|
||||
|
||||
const normalizeWheelDelta = (event: WheelEvent) => {
|
||||
if (event.deltaMode === WheelEvent.DOM_DELTA_LINE) return event.deltaY * 16
|
||||
@@ -119,49 +155,12 @@ const normalizeWheelDelta = (event: WheelEvent) => {
|
||||
return event.deltaY
|
||||
}
|
||||
|
||||
const updateWheelPinch = (event: WheelEvent) => {
|
||||
wheelPinch ??= {
|
||||
active: false,
|
||||
startZoom: requestedZoom,
|
||||
totalDelta: 0,
|
||||
timeout: undefined,
|
||||
}
|
||||
|
||||
clearTimeout(wheelPinch.timeout)
|
||||
wheelPinch.timeout = setTimeout(resetWheelPinch, WHEEL_PINCH_END_DELAY)
|
||||
wheelPinch.totalDelta += normalizeWheelDelta(event)
|
||||
|
||||
if (!wheelPinch.active && Math.abs(wheelPinch.totalDelta) < WHEEL_PINCH_THRESHOLD) return
|
||||
|
||||
if (!wheelPinch.active) {
|
||||
wheelPinch.active = true
|
||||
wheelPinch.startZoom = requestedZoom
|
||||
wheelPinch.totalDelta = 0
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
wheelPinch.active = true
|
||||
applyZoom(clamp(wheelPinch.startZoom - (wheelPinch.totalDelta / WHEEL_PINCH_THRESHOLD) * WHEEL_PINCH_STEP))
|
||||
}
|
||||
|
||||
const onWheelPinch = (event: WheelEvent) => {
|
||||
if (!event.ctrlKey) return
|
||||
|
||||
event.preventDefault()
|
||||
updateWheelPinch(event)
|
||||
}
|
||||
|
||||
// A cancelable window wheel listener makes every scroll gesture wait for the main thread, so it
|
||||
// is only attached while pinch zoom is on. Main's zoom-changed handler covers Ctrl+wheel otherwise.
|
||||
const syncWheelPinchListener = () => {
|
||||
if (pinchZoomEnabled) {
|
||||
window.addEventListener("wheel", onWheelPinch, { passive: false })
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
window.removeEventListener("wheel", onWheelPinch)
|
||||
wheelEvent.delta = normalizeWheelDelta(event)
|
||||
dispatch(wheelEvent)
|
||||
}
|
||||
|
||||
window.addEventListener("keydown", (event) => {
|
||||
|
||||
Reference in New Issue
Block a user