fix(app): settle permission replies and the session header fit through state machines (#61942)

This commit is contained in:
Luke Parker
2026-11-04 23:06:16 -06:00
committed by GitHub
Unverified
parent 5e76d6a9b1
commit 2b9216a002
8 changed files with 701 additions and 79 deletions
@@ -290,6 +290,20 @@ test.describe("location", () => {
await header.screenshot({ path: test.info().outputPath(`location-${state.width}.png`) })
}
// Find takes room from the title, so the usage details give way, and come back once Find closes.
const search = header.locator('[data-component="timeline-search-bar"] input')
await row.evaluate((element) => (element.style.inlineSize = "680px"))
await expect(usage).toBeVisible()
await page.keyboard.press("ControlOrMeta+f")
await expect(search).toBeFocused()
await expect(usageMenu).toBeVisible()
await header.screenshot({ path: test.info().outputPath("location-find-open.png") })
await search.press("Escape")
await expect(search).toHaveCount(0)
await expect(project).toBeVisible()
await expect(usage).toBeVisible()
await header.screenshot({ path: test.info().outputPath("location-find-closed.png") })
await row.evaluate((element) => element.style.removeProperty("inline-size"))
await review.click()
await expect(review).toHaveAttribute("aria-expanded", "true")
@@ -210,6 +210,49 @@ test("shows a pending permission dock", async ({ page }) => {
await expect(page.locator('[data-component="composer"]')).toBeVisible()
})
test("sends one permission reply and closes the dock when it lands, before permission.replied", async ({ page }) => {
await mockServer(page, {
sessionPermissions: {
[sessionID]: [
{
id: "permission-request",
sessionID,
permission: "shell",
patterns: ["git status"],
metadata: {},
always: [],
},
],
},
})
const replies: unknown[] = []
const released = Promise.withResolvers<void>()
// Answers without the `permission.replied` event the server also publishes, so only the reply can close the dock.
await page.route(/\/api\/session\/ses_request_docks\/permission\/permission-request\/reply/, async (route) => {
if (route.request().method() !== "POST") return route.fallback()
replies.push(route.request().postDataJSON())
await released.promise
await route.fulfill({ status: 204 })
})
await page.goto(sessionHref(sessionID))
await expectSessionTitle(page, title)
const permission = page.locator('[data-component="dock-prompt"][data-kind="permission"]')
const actions = permission.locator('[data-slot="permission-footer-actions"]')
await permission.getByRole("button", { name: "Allow once" }).dblclick()
await expect.poll(() => replies.length).toBe(1)
for (const name of ["Deny", "Allow always", "Allow once"])
await expect(actions.getByRole("button", { name, exact: true })).toBeDisabled()
released.resolve()
await expect(permission).toHaveCount(0)
await expect(page.locator('[data-component="composer"]')).toBeVisible()
await expect(page.getByText("Request failed", { exact: true })).toHaveCount(0)
expect(replies).toEqual([{ decision: "once" }])
})
test("names the MCP tool, the hook's message and the full input in the permission dock", async ({ page }) => {
const body = "x".repeat(3000)
await mockServer(page, {
@@ -0,0 +1,143 @@
import { describe, expect, test } from "bun:test"
import {
headerFitCollapse,
headerFitCompact,
INITIAL_HEADER_FIT_STATE,
transitionHeaderFit,
type HeaderFitMeasuredEvent,
type HeaderFitState,
} from "./fit-machine"
// A header laid out like the real one: the location takes its rendered width, the actions theirs, and the title box
// fills the rest of the row. The project name takes 80px and the worktree name 100px, each with its gap.
const title = 300
const usage = 146
const usageSaved = 82
const find = 208
function actions(compact: boolean, search = false) {
return usage - (compact ? usageSaved : 0) + (search ? find : 0)
}
function measured(
state: HeaderFitState,
row: number,
input: { search?: boolean; worktree?: boolean; actions?: boolean; limit?: number } = {},
): HeaderFitMeasuredEvent {
const worktree = input.worktree ?? true
const collapse = headerFitCollapse(state)
const location = 40 + (collapse < 2 ? 80 : 0) + (worktree && collapse < 1 ? 100 : 0)
const width = input.actions === false ? 0 : actions(headerFitCompact(state), input.search)
return {
type: "measured",
locationWidth: location,
titleBoxWidth: row - location - width,
titleWidth: title,
projectWidth: 80,
worktreeWidth: worktree ? 100 : 0,
hasWorktree: worktree,
limit: input.limit ?? Number.POSITIVE_INFINITY,
hasActions: input.actions !== false,
actionsWidth: width,
}
}
// Fits like the driver: a pass that enters compact measures the actions once they render compact.
function fit(state: HeaderFitState, row: number, input: Parameters<typeof measured>[2] = {}) {
const next = transitionHeaderFit(state, measured(state, row, input))
if (next.status !== "compact" || next.expandedWidth === undefined) return next
return transitionHeaderFit(next, {
type: "compact.settled",
actionsWidth: input.actions === false ? 0 : actions(true, input.search),
})
}
// Fits until the header stops changing, as the observers do after each render.
function settle(state: HeaderFitState, row: number, input: Parameters<typeof measured>[2] = {}) {
const seen: HeaderFitState[] = [state]
for (let pass = 0; pass < 4; pass++) {
const next = fit(seen.at(-1) ?? state, row, input)
if (next === seen.at(-1)) return { state: next, passes: seen.slice(1) }
seen.push(next)
}
throw new Error(`header kept changing: ${seen.map((item) => item.status).join(" -> ")}`)
}
describe("transitionHeaderFit", () => {
test("closing Find while compact expands the actions again", () => {
const opened = settle(INITIAL_HEADER_FIT_STATE, 680, { search: true }).state
expect(opened).toEqual({ status: "compact", expandedWidth: undefined, saved: usageSaved })
// The old fit subtracted the 354px the actions took with Find open, not the 82px compacting freed.
expect(fit(opened, 680)).toBe(INITIAL_HEADER_FIT_STATE)
})
test("opening Find while compact keeps the room the details take, so the header does not flip back and forth", () => {
const compact = settle(INITIAL_HEADER_FIT_STATE, 480).state
expect(compact).toEqual({ status: "compact", expandedWidth: undefined, saved: usageSaved })
// 40px to spare beside the compact actions, less than their details take back.
const searching = settle(compact, 652, { search: true })
expect(searching.state).toBe(compact)
expect(searching.passes).toEqual([])
// Once the details fit, they expand and stay.
const expanded = settle(compact, 694, { search: true })
expect(expanded.passes.map((state) => state.status)).toEqual(["project-hidden"])
})
test("hides the worktree name, then the project name, then the details, and restores them in reverse", () => {
const states = [700, 600, 500, 480, 500, 600, 700].reduce<HeaderFitState[]>((list, row) => {
list.push(settle(list.at(-1) ?? INITIAL_HEADER_FIT_STATE, row).state)
return list
}, [])
expect(states.map((state) => [headerFitCollapse(state), headerFitCompact(state)])).toEqual([
[0, false],
[1, false],
[2, false],
[2, true],
[2, false],
[1, false],
[0, false],
])
})
test("skips the worktree step without a worktree and never compacts without actions", () => {
expect(settle(INITIAL_HEADER_FIT_STATE, 550, { worktree: false }).state.status).toBe("project-hidden")
expect(settle(INITIAL_HEADER_FIT_STATE, 300, { actions: false }).state.status).toBe("project-hidden")
})
test("fits each candidate against the location's maximum width", () => {
// 154px is free: the full 220px location does not fit, but its 100px cap does.
expect(settle(INITIAL_HEADER_FIT_STATE, 600).state.status).toBe("worktree-hidden")
expect(settle(INITIAL_HEADER_FIT_STATE, 600, { limit: 100 }).state).toBe(INITIAL_HEADER_FIT_STATE)
})
test("returns the same state while the header keeps fitting the same way", () => {
for (const row of [700, 600, 500, 480]) {
const state = settle(INITIAL_HEADER_FIT_STATE, row).state
expect(transitionHeaderFit(state, measured(state, row))).toBe(state)
expect(transitionHeaderFit(state, measured(state, row - 2))).toBe(state)
}
})
test("ignores a compact measurement outside the compact entry", () => {
const settled = { type: "compact.settled", actionsWidth: 64 } as const
expect(transitionHeaderFit(INITIAL_HEADER_FIT_STATE, settled)).toBe(INITIAL_HEADER_FIT_STATE)
const compact = settle(INITIAL_HEADER_FIT_STATE, 480).state
expect(transitionHeaderFit(compact, settled)).toBe(compact)
})
})
@@ -0,0 +1,95 @@
// How far the session header gave way so the title fits: the worktree name hides first, then the project name, then the
// actions drop their details (`compact`). Runs on every header resize, so it returns the same object when nothing
// changes and the steady states are frozen singletons. Keep it in a signal, never a Solid store.
export type HeaderFitState =
| { readonly status: "full" }
| { readonly status: "worktree-hidden" }
| { readonly status: "project-hidden" }
| {
readonly status: "compact"
/** The actions' expanded width on entry, until the compact width is measured. */
readonly expandedWidth: number | undefined
/** The width compacting freed. Expanding takes it back, whatever the actions beside the details do meanwhile. */
readonly saved: number
}
export type HeaderFitMeasuredEvent = {
readonly type: "measured"
readonly locationWidth: number
readonly titleBoxWidth: number
/** What the title section's content needs. */
readonly titleWidth: number
readonly projectWidth: number
readonly worktreeWidth: number
readonly hasWorktree: boolean
/** The location's maximum width. */
readonly limit: number
readonly hasActions: boolean
readonly actionsWidth: number
}
/** The actions were measured right after they rendered compact. */
export type HeaderFitCompactSettledEvent = {
readonly type: "compact.settled"
readonly actionsWidth: number
}
export type HeaderFitEvent = HeaderFitMeasuredEvent | HeaderFitCompactSettledEvent
export const INITIAL_HEADER_FIT_STATE: HeaderFitState = Object.freeze({ status: "full" })
const WORKTREE_HIDDEN: HeaderFitState = Object.freeze({ status: "worktree-hidden" })
const PROJECT_HIDDEN: HeaderFitState = Object.freeze({ status: "project-hidden" })
export function transitionHeaderFit(state: HeaderFitState, event: HeaderFitEvent): HeaderFitState {
if (event.type === "compact.settled") {
if (state.status !== "compact" || state.expandedWidth === undefined) return state
return { status: "compact", expandedWidth: undefined, saved: Math.max(0, state.expandedWidth - event.actionsWidth) }
}
// Hidden labels keep their intrinsic width, so fitting never depends on a previous truncation.
const collapse = headerFitCollapse(state)
const expanded =
event.locationWidth + (collapse >= 1 ? event.worktreeWidth : 0) + (collapse >= 2 ? event.projectWidth : 0)
const saved =
state.status !== "compact"
? 0
: state.expandedWidth === undefined
? state.saved
: Math.max(0, state.expandedWidth - event.actionsWidth)
// Everything outside the location and title sections is reserved for the actions, so candidates are fitted against
// expanded actions: compact actions expand again once the title fits beside them.
const available = event.locationWidth + event.titleBoxWidth - event.titleWidth - saved
if (Math.min(expanded, event.limit) <= available) return INITIAL_HEADER_FIT_STATE
if (event.hasWorktree && Math.min(expanded - event.worktreeWidth, event.limit) <= available) return WORKTREE_HIDDEN
if (!event.hasActions || Math.min(expanded - event.worktreeWidth - event.projectWidth, event.limit) <= available)
return PROJECT_HIDDEN
if (state.status !== "compact") return { status: "compact", expandedWidth: event.actionsWidth, saved: 0 }
if (state.expandedWidth === undefined) return state
return { status: "compact", expandedWidth: undefined, saved }
}
/** 0 shows the whole location, 1 hides the worktree name, 2 also hides the project name. */
export function headerFitCollapse(state: HeaderFitState) {
if (state.status === "full") return 0
if (state.status === "worktree-hidden") return 1
return 2
}
/** The title does not fit even with the location collapsed, so the actions show without their details. */
export function headerFitCompact(state: HeaderFitState) {
return state.status === "compact"
}
+73 -55
View File
@@ -1,14 +1,34 @@
import { onCleanup, onMount } from "solid-js"
import { createStore } from "solid-js/store"
import { createSignal, onCleanup, onMount, untrack } from "solid-js"
import {
headerFitCollapse,
headerFitCompact,
INITIAL_HEADER_FIT_STATE,
transitionHeaderFit,
type HeaderFitState,
} from "./fit-machine"
/** Fits the location names, then the actions' details, before allowing the session title to truncate. */
export function createSessionHeaderFit() {
const [store, setStore] = createStore({ collapse: 0, compact: false })
const [state, setState] = createSignal<HeaderFitState>(INITIAL_HEADER_FIT_STATE)
let root!: HTMLDivElement
// Compact actions drop their details, so their last expanded width is what expanding them again takes back.
let expandedActions = 0
onMount(() => {
// Reused on every pass: fitting runs on each resize of the header.
const measured = {
type: "measured" as const,
locationWidth: 0,
titleBoxWidth: 0,
titleWidth: 0,
projectWidth: 0,
worktreeWidth: 0,
hasWorktree: false,
limit: 0,
hasActions: false,
actionsWidth: 0,
}
const settled = { type: "compact.settled" as const, actionsWidth: 0 }
const fit = () => {
const location = root.querySelector<HTMLElement>(".session-header-location")
const title = root.querySelector<HTMLElement>(".session-header-title")
@@ -21,63 +41,33 @@ export function createSessionHeaderFit() {
if (!location || !title || !measure || !trigger || !project || !root.clientWidth) return
const gap = Number.parseFloat(getComputedStyle(trigger).columnGap)
const projectWidth = project.getBoundingClientRect().width + gap
const worktreeWidth = worktree ? worktree.getBoundingClientRect().width + gap : 0
// Hidden labels retain their intrinsic width, so fitting never depends on a previous truncation.
const expanded =
location.getBoundingClientRect().width +
(store.collapse >= 1 ? worktreeWidth : 0) +
(store.collapse >= 2 ? projectWidth : 0)
// Ancestors can fill the space a hidden name freed. Apply their cap to each reconstructed candidate.
const max = getComputedStyle(location).maxInlineSize
const limit =
measured.locationWidth = location.getBoundingClientRect().width
measured.titleBoxWidth = title.getBoundingClientRect().width
measured.titleWidth = measureTitleWidth(title, measure)
measured.projectWidth = project.getBoundingClientRect().width + gap
measured.worktreeWidth = worktree ? worktree.getBoundingClientRect().width + gap : 0
measured.hasWorktree = !!worktree
measured.limit =
max === "none"
? Number.POSITIVE_INFINITY
: Number.parseFloat(max) * (max.endsWith("%") ? root.getBoundingClientRect().width / 100 : 1)
measured.hasActions = !!actions
measured.actionsWidth = actions?.getBoundingClientRect().width ?? 0
const children = [...title.children].filter(
(element) => !element.matches(".session-header-title-measure") && getComputedStyle(element).display !== "none",
)
const current = untrack(state)
const next = transitionHeaderFit(current, measured)
const titleWidth = children.reduce(
(width, element) => {
if (element.matches('[data-slot="session-header-gap"]')) return width
if (next === current) return
// Compact actions render synchronously, so measuring them now records what compacting freed, even when no
// observer would fire again.
setState(next)
if (element.matches("h1, input")) return width + measure.getBoundingClientRect().width
const style = getComputedStyle(element)
return (
width +
element.getBoundingClientRect().width +
Number.parseFloat(style.marginInlineStart) +
Number.parseFloat(style.marginInlineEnd)
)
},
Math.max(0, children.length - 1) * Number.parseFloat(getComputedStyle(title).columnGap),
)
const actionsWidth = actions?.getBoundingClientRect().width ?? 0
if (!store.compact) expandedActions = actionsWidth
// Everything outside these two sections is reserved for actions, separators and their spacing. Candidates are
// fitted against expanded actions, so compact actions expand again once the title fits beside them.
const available =
location.getBoundingClientRect().width +
title.getBoundingClientRect().width -
titleWidth -
(store.compact ? Math.max(0, expandedActions - actionsWidth) : 0)
const fits = (width: number) => Math.min(width, limit) <= available
const collapse = fits(expanded) ? 0 : worktree && fits(expanded - worktreeWidth) ? 1 : 2
setStore({
collapse,
compact: !!actions && collapse === 2 && !fits(expanded - worktreeWidth - projectWidth),
})
if (next.status !== "compact" || next.expandedWidth === undefined) return
settled.actionsWidth = actions?.getBoundingClientRect().width ?? 0
setState(transitionHeaderFit(next, settled))
}
const resize = new ResizeObserver(fit)
@@ -106,11 +96,39 @@ export function createSessionHeaderFit() {
return {
ref: (element: HTMLDivElement) => (root = element),
get collapse() {
return store.collapse
return headerFitCollapse(state())
},
/** The title does not fit even with the location collapsed, so the actions show without their details. */
get compact() {
return store.compact
return headerFitCompact(state())
},
}
}
// What the title section's visible content needs, with the title at its full width.
function measureTitleWidth(title: HTMLElement, measure: HTMLElement) {
let width = 0
let count = 0
for (let element = title.firstElementChild; element; element = element.nextElementSibling) {
if (element.matches(".session-header-title-measure")) continue
const style = getComputedStyle(element)
if (style.display === "none") continue
count++
if (element.matches('[data-slot="session-header-gap"]')) continue
if (element.matches("h1, input")) {
width += measure.getBoundingClientRect().width
continue
}
width +=
element.getBoundingClientRect().width +
Number.parseFloat(style.marginInlineStart) +
Number.parseFloat(style.marginInlineEnd)
}
return width + Math.max(0, count - 1) * Number.parseFloat(getComputedStyle(title).columnGap)
}
+98 -24
View File
@@ -1,6 +1,6 @@
import { createEffect, createMemo } from "solid-js"
import { createStore } from "solid-js/store"
import type { FormInfo, PermissionRequest } from "@opencode/client/promise"
import { createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js"
import { isPermissionNotFoundError, type FormInfo, type PermissionRequest } from "@opencode/client/promise"
import { abort } from "@opencode/util/abort"
import { useParams } from "@solidjs/router"
import { showToast } from "@/shell/notifications/toast"
import { useServerSDK } from "@/runtime/server/client"
@@ -13,6 +13,17 @@ import { createSessionBackground } from "@/session/requests/background"
import { createSteerBackground } from "@/session/requests/steer-background"
import { useData, useServer } from "@/runtime/server/current"
import { needsUser } from "./auto-approve-machine"
import {
INITIAL_PERMISSION_REPLY_STATE,
isPermissionReplied,
isPermissionResponding,
PERMISSION_REPLIED_LIMIT,
transitionPermissionReply,
type PermissionDecision,
type PermissionReplyEffect,
type PermissionReplyEvent,
type PermissionReplyState,
} from "./permission-machine"
export function createSessionRequestModel() {
const params = useParams()
@@ -22,6 +33,18 @@ export function createSessionRequestModel() {
const autoApprove = useServer().ctx.autoApprove
const language = useLanguage()
const settings = useSettings()
// Manual replies from the dock, by request. Requests nobody answered from this dock have no entry.
const [replies, setReplies] = createSignal<Readonly<Record<string, PermissionReplyState>>>({})
const runs = new Map<string, { controller: AbortController; timer: ReturnType<typeof setTimeout> }>()
const replyState = (requestID: string) => replies()[requestID] ?? INITIAL_PERMISSION_REPLY_STATE
const stop = serverSDK.event.on("permission.replied", (event) => dispatch(event.data.requestID, { type: "resolved" }))
onCleanup(() => {
stop()
Object.keys(untrack(replies)).forEach((id) => dispatch(id, { type: "disposed" }))
})
createEffect(() => {
const id = params.id
@@ -113,8 +136,11 @@ export function createSessionRequestModel() {
projectSettingsKey(serverSDK.scope, id ? data.session.get(id)?.projectID : undefined),
)
return sessionPermissionRequest(data.session.list(), data.session.permission.list, id, (item) =>
needsUser(autoApprove.state(item.id), enabled),
return sessionPermissionRequest(
data.session.list(),
data.session.permission.list,
id,
(item) => needsUser(autoApprove.state(item.id), enabled) && !isPermissionReplied(replyState(item.id)),
)
})
@@ -164,35 +190,73 @@ export function createSessionRequestModel() {
move: (sessionID) => serverSDK.api.session.background({ sessionID }),
})
const [store, setStore] = createStore<{ responding: string | undefined }>({ responding: undefined })
// The dock keeps the last request mounted while it closes, so its buttons follow that request's reply.
const lastPermissionID = createMemo<string | undefined>((previous) => permissionRequest()?.id ?? previous)
const permissionResponding = createMemo(() => {
const perm = permissionRequest()
const id = lastPermissionID()
if (!perm) return false
return store.responding === perm.id
return !!id && isPermissionResponding(replyState(id))
})
const decide = (response: "once" | "always" | "reject") => {
const decide = (decision: PermissionDecision) => {
const perm = permissionRequest()
if (!perm) return
dispatch(perm.id, { type: "decide", sessionID: perm.sessionID, decision })
}
if (store.responding === perm.id) return
function dispatch(requestID: string, event: PermissionReplyEvent) {
const state = untrack(() => replyState(requestID))
const result = transitionPermissionReply(state, event)
setStore("responding", perm.id)
serverSDK.api.permission
.reply({ sessionID: perm.sessionID, requestID: perm.id, decision: response })
.catch((error) => {
showToast({
title: language.t("common.requestFailed"),
description: error instanceof Error ? error.message : String(error),
})
})
.finally(() => {
setStore("responding", (id) => (id === perm.id ? undefined : id))
})
if (result.state !== state) setReplies((current) => pruneReplied({ ...current, [requestID]: result.state }))
result.effects.forEach((effect) => execute(requestID, effect))
}
function execute(requestID: string, effect: PermissionReplyEffect) {
if (effect.type === "toast-failed") {
showToast({ title: language.t("common.requestFailed"), description: effect.error })
return
}
if (effect.type === "abort") {
const run = runs.get(requestID)
runs.delete(requestID)
clearTimeout(run?.timer)
abort(run?.controller)
return
}
const controller = new AbortController()
runs.set(requestID, {
controller,
timer: setTimeout(
() => dispatch(requestID, { type: "reply.timed-out", attempt: effect.attempt }),
effect.timeoutMs,
),
})
// A request another client or the TUI already answered counts as replied.
void serverSDK.api.permission
.reply({ sessionID: effect.sessionID, requestID, decision: effect.decision }, { signal: controller.signal })
.then(
() => dispatch(requestID, { type: "reply.succeeded", attempt: effect.attempt }),
(error) =>
dispatch(
requestID,
isPermissionNotFoundError(error)
? { type: "reply.succeeded", attempt: effect.attempt }
: {
type: "reply.failed",
attempt: effect.attempt,
error: error instanceof Error ? error.message : String(error),
},
),
)
}
return {
@@ -214,3 +278,13 @@ export function createSessionRequestModel() {
}
export type SessionRequestModel = ReturnType<typeof createSessionRequestModel>
// Replied entries only hide requests until `permission.replied` removes them, so the oldest can go.
function pruneReplied(replies: Readonly<Record<string, PermissionReplyState>>) {
const replied = Object.entries(replies).flatMap(([id, state]) => (isPermissionReplied(state) ? [id] : []))
if (replied.length <= PERMISSION_REPLIED_LIMIT) return replies
const drop = new Set(replied.slice(0, replied.length - PERMISSION_REPLIED_LIMIT))
return Object.fromEntries(Object.entries(replies).filter(([id]) => !drop.has(id)))
}
@@ -0,0 +1,130 @@
import { describe, expect, test } from "bun:test"
import {
INITIAL_PERMISSION_REPLY_STATE,
isPermissionReplied,
isPermissionResponding,
PERMISSION_REPLY_TIMEOUT_MS,
transitionPermissionReply,
type PermissionReplyEvent,
type PermissionReplyState,
type PermissionReplyTransition,
} from "./permission-machine"
const decide = (decision: "once" | "always" | "reject" = "once"): PermissionReplyEvent => ({
type: "decide",
sessionID: "ses_1",
decision,
})
const responding = (attempt: number): PermissionReplyState => ({
status: "responding",
attempt,
sessionID: "ses_1",
decision: "once",
})
function replay(events: PermissionReplyEvent[], from = INITIAL_PERMISSION_REPLY_STATE) {
return events.reduce<PermissionReplyTransition[]>((steps, event) => {
steps.push(transitionPermissionReply(steps.at(-1)?.state ?? from, event))
return steps
}, [])
}
describe("transitionPermissionReply", () => {
test("a reply that lands before permission.replied keeps the dock answered and ignores another click", () => {
const steps = replay([decide("once"), { type: "reply.succeeded", attempt: 1 }])
const replied = steps[1].state
expect(steps[0]).toEqual({
state: responding(1),
effects: [
{ type: "reply", attempt: 1, sessionID: "ses_1", decision: "once", timeoutMs: PERMISSION_REPLY_TIMEOUT_MS },
],
})
expect(steps[1].effects).toEqual([{ type: "abort" }])
expect(isPermissionResponding(replied)).toBe(true)
expect(isPermissionReplied(replied)).toBe(true)
const again = transitionPermissionReply(replied, decide("once"))
expect(again.state).toBe(replied)
expect(again.effects).toEqual([])
})
test("a second click while the reply is in flight sends nothing", () => {
const state = responding(1)
const result = transitionPermissionReply(state, decide("always"))
expect(result.state).toBe(state)
expect(result.effects).toEqual([])
})
test("a failed reply re-enables the dock with a toast, and the retry is a new attempt", () => {
const steps = replay([decide("always"), { type: "reply.failed", attempt: 1, error: "boom" }, decide("once")])
expect(steps[1]).toEqual({
state: { status: "idle", attempt: 1 },
effects: [{ type: "abort" }, { type: "toast-failed", error: "boom" }],
})
expect(isPermissionResponding(steps[1].state)).toBe(false)
expect(steps[2].state).toEqual({ status: "responding", attempt: 2, sessionID: "ses_1", decision: "once" })
})
test("a hung reply times out, and the aborted request's failure is ignored", () => {
const steps = replay([
decide("reject"),
{ type: "reply.timed-out", attempt: 1 },
{ type: "reply.failed", attempt: 1, error: "aborted" },
])
expect(steps[1]).toEqual({
state: { status: "idle", attempt: 1 },
effects: [{ type: "abort" }, { type: "toast-failed", error: undefined }],
})
expect(steps[2].state).toBe(steps[1].state)
expect(steps[2].effects).toEqual([])
})
test("results of an earlier attempt cannot move the current one", () => {
const state = responding(2)
for (const event of [
{ type: "reply.succeeded", attempt: 1 },
{ type: "reply.failed", attempt: 1, error: "aborted" },
{ type: "reply.timed-out", attempt: 1 },
] satisfies PermissionReplyEvent[]) {
const result = transitionPermissionReply(state, event)
expect(result.state).toBe(state)
expect(result.effects).toEqual([])
}
})
test("permission.replied settles an in-flight reply and is a no-op otherwise", () => {
expect(transitionPermissionReply(responding(1), { type: "resolved" })).toEqual({
state: { status: "replied" },
effects: [{ type: "abort" }],
})
for (const state of [INITIAL_PERMISSION_REPLY_STATE, { status: "replied" } satisfies PermissionReplyState]) {
const result = transitionPermissionReply(state, { type: "resolved" })
expect(result.state).toBe(state)
expect(result.effects).toEqual([])
}
})
test("disposal aborts an in-flight reply and is a no-op otherwise", () => {
expect(transitionPermissionReply(responding(3), { type: "disposed" })).toEqual({
state: { status: "idle", attempt: 3 },
effects: [{ type: "abort" }],
})
for (const state of [INITIAL_PERMISSION_REPLY_STATE, { status: "replied" } satisfies PermissionReplyState]) {
const result = transitionPermissionReply(state, { type: "disposed" })
expect(result.state).toBe(state)
expect(result.effects).toEqual([])
}
})
})
@@ -0,0 +1,105 @@
export const PERMISSION_REPLY_TIMEOUT_MS = 15_000
export const PERMISSION_REPLIED_LIMIT = 256
export type PermissionDecision = "once" | "always" | "reject"
// One permission request's manual reply from the dock. `attempt` advances on each try, so a late failure or timeout
// from an earlier click cannot move a newer one. `replied` is terminal: an answered request never re-enables or
// resurfaces before `permission.replied` removes it from the store.
export type PermissionReplyState =
| { readonly status: "idle"; readonly attempt: number }
| {
readonly status: "responding"
readonly attempt: number
readonly sessionID: string
readonly decision: PermissionDecision
}
| { readonly status: "replied" }
export type PermissionReplyEvent =
| { readonly type: "decide"; readonly sessionID: string; readonly decision: PermissionDecision }
| { readonly type: "reply.succeeded"; readonly attempt: number }
| { readonly type: "reply.failed"; readonly attempt: number; readonly error: string }
| { readonly type: "reply.timed-out"; readonly attempt: number }
// `permission.replied` arrived on the event stream, from this or another client.
| { readonly type: "resolved" }
| { readonly type: "disposed" }
export type PermissionReplyEffect =
| {
readonly type: "reply"
readonly attempt: number
readonly sessionID: string
readonly decision: PermissionDecision
readonly timeoutMs: number
}
| { readonly type: "abort" }
| { readonly type: "toast-failed"; readonly error?: string }
export type PermissionReplyTransition = {
readonly state: PermissionReplyState
readonly effects: readonly PermissionReplyEffect[]
}
export const INITIAL_PERMISSION_REPLY_STATE: PermissionReplyState = Object.freeze({ status: "idle", attempt: 0 })
const NONE: readonly PermissionReplyEffect[] = []
const ABORT: readonly PermissionReplyEffect[] = [{ type: "abort" }]
export function transitionPermissionReply(
state: PermissionReplyState,
event: PermissionReplyEvent,
): PermissionReplyTransition {
// The first click claims the request; later clicks, including a second click of a double-click, do nothing.
if (event.type === "decide") {
if (state.status !== "idle") return unchanged(state)
const attempt = state.attempt + 1
return {
state: { status: "responding", attempt, sessionID: event.sessionID, decision: event.decision },
effects: [
{
type: "reply",
attempt,
sessionID: event.sessionID,
decision: event.decision,
timeoutMs: PERMISSION_REPLY_TIMEOUT_MS,
},
],
}
}
if (state.status !== "responding") return unchanged(state)
if (event.type === "resolved") return { state: { status: "replied" }, effects: ABORT }
if (event.type === "disposed") return { state: { status: "idle", attempt: state.attempt }, effects: ABORT }
if (event.attempt !== state.attempt) return unchanged(state)
if (event.type === "reply.succeeded") return { state: { status: "replied" }, effects: ABORT }
return {
state: { status: "idle", attempt: state.attempt },
effects: [
{ type: "abort" },
{ type: "toast-failed", error: event.type === "reply.failed" ? event.error : undefined },
],
}
}
/** The dock's buttons stay disabled while a reply is in flight and after it lands, through the dock's close motion. */
export function isPermissionResponding(state: PermissionReplyState) {
return state.status !== "idle"
}
/** An answered request leaves the dock at once, without waiting for `permission.replied`. */
export function isPermissionReplied(state: PermissionReplyState) {
return state.status === "replied"
}
function unchanged(state: PermissionReplyState): PermissionReplyTransition {
return { state, effects: NONE }
}