mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-26 23:28:43 +00:00
feat(app): add question notifications and sounds (#60358)
Co-authored-by: Sayuri Nekomiya <contactme@awsl.rip>
This commit is contained in:
parent
b19d143181
commit
d09e2c6c8d
10 changed files with 524 additions and 15 deletions
|
|
@ -3,6 +3,8 @@ import type { ConfigEntry, OpenCodeEvent, SessionMessageInfo, WorktreeDirectory
|
|||
import { NO_PROVIDER, REMOTE_SERVER, SERVER, holdRoute, project, seed, session } from "../utils/app"
|
||||
import { mockMissingLocation, mockOpenCodeServer } from "../utils/mock-server"
|
||||
import { mockRemoteServer, mockWorkspace, openSession, openSettings, type WorkspaceInput } from "../utils/workspace"
|
||||
import { recordNotifications } from "../utils/notifications"
|
||||
import { installSseTransport } from "../utils/sse-transport"
|
||||
|
||||
const directory = "C:/Projects/settings-demo"
|
||||
|
||||
|
|
@ -94,6 +96,146 @@ test("a settings page survives refresh", async ({ page }) => {
|
|||
await expect(page).toHaveURL("/settings?tab=appearance")
|
||||
})
|
||||
|
||||
test("Questions settings default independently of old Permissions settings and survive reload", async ({ page }) => {
|
||||
const { settings } = await open(page, {
|
||||
seed: {
|
||||
settings: {
|
||||
notifications: { agent: false, permissions: false, errors: true },
|
||||
sounds: { permissionsEnabled: false, permissions: "alert-05" },
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
await settings.getByRole("tab", { name: "Notifications", exact: true }).click()
|
||||
await expect(settings.locator('[data-slot="settings-row-title"]')).toHaveText([
|
||||
"Agent",
|
||||
"Permissions",
|
||||
"Questions",
|
||||
"Errors",
|
||||
"Agent",
|
||||
"Permissions",
|
||||
"Questions",
|
||||
"Errors",
|
||||
"Interface",
|
||||
])
|
||||
const questions = settings.getByRole("switch", { name: "Questions", exact: true })
|
||||
|
||||
const permissions = settings.locator('[data-action="settings-notifications-permissions"]').getByRole("switch")
|
||||
|
||||
const questionSound = settings.locator('[data-action="settings-sounds-questions"]')
|
||||
|
||||
const permissionSound = settings.locator('[data-action="settings-sounds-permissions"]')
|
||||
|
||||
await expect(questions).toBeChecked()
|
||||
await expect(permissions).not.toBeChecked()
|
||||
await expect(questionSound).toHaveText("Staplebops 02")
|
||||
await expect(permissionSound).toHaveText("None")
|
||||
await questions.locator("..").locator('[data-slot="switch-control"]').click()
|
||||
await expect(questions).not.toBeChecked()
|
||||
await questionSound.click()
|
||||
await page.getByRole("option", { name: "Alert 02", exact: true }).click()
|
||||
await expect(questionSound).toHaveText("Alert 02")
|
||||
|
||||
await page.reload()
|
||||
await expect(questions).not.toBeChecked()
|
||||
await expect(questionSound).toHaveText("Alert 02")
|
||||
await expect(permissions).not.toBeChecked()
|
||||
await expect(permissionSound).toHaveText("None")
|
||||
await questions.locator("..").locator('[data-slot="switch-control"]').click()
|
||||
await questionSound.click()
|
||||
await page.getByRole("option", { name: "None", exact: true }).click()
|
||||
await expect(questions).toBeChecked()
|
||||
await expect(questionSound).toHaveText("None")
|
||||
await settings.getByRole("combobox", { name: "Search", exact: true }).fill("Questions")
|
||||
await expect(settings.locator('[data-setting-target="settings-notifications-questions"]')).toBeVisible()
|
||||
await expect(settings.locator('[data-setting-target="settings-sounds-questions"]')).toBeVisible()
|
||||
})
|
||||
|
||||
test("request events use real Questions settings without disabling Permissions alerts", async ({ page }) => {
|
||||
const recorded = await recordNotifications(page)
|
||||
|
||||
const transport = await installSseTransport(page, { server: SERVER })
|
||||
|
||||
const workspace = await openSession(page, {
|
||||
name: "Request notifications",
|
||||
seed: { settings: { sounds: { agentEnabled: false, permissions: "alert-01", questions: "alert-02" } } },
|
||||
})
|
||||
|
||||
await transport.waitForConnection()
|
||||
await page.getByRole("button", { name: "Home", exact: true }).click()
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click()
|
||||
const settings = page.getByTestId("settings-screen")
|
||||
|
||||
await settings.getByRole("tab", { name: "Notifications", exact: true }).click()
|
||||
const questions = settings.getByRole("switch", { name: "Questions", exact: true })
|
||||
|
||||
await expect(questions).toBeChecked()
|
||||
|
||||
const event = (
|
||||
kind: "question" | "mcp-elicitation" | "websearch.provider" | "permission",
|
||||
index: number,
|
||||
): OpenCodeEvent => ({
|
||||
id: `evt_request_${index}`,
|
||||
created: 1700000001000 + index,
|
||||
location: { directory: workspace.directory },
|
||||
...(kind === "permission"
|
||||
? {
|
||||
type: "permission.asked" as const,
|
||||
data: {
|
||||
id: `per_request_${index}`,
|
||||
sessionID: workspace.session.id,
|
||||
action: "shell",
|
||||
resources: ["echo hello"],
|
||||
metadata: {},
|
||||
},
|
||||
}
|
||||
: {
|
||||
type: "form.created" as const,
|
||||
data: {
|
||||
form: {
|
||||
id: `frm_request_${index}`,
|
||||
sessionID: workspace.session.id,
|
||||
title: "Input",
|
||||
metadata: { kind },
|
||||
fields: [{ key: "answer", type: "string" as const, title: "Continue?" }],
|
||||
},
|
||||
},
|
||||
}),
|
||||
})
|
||||
|
||||
await transport.send(event("question", 1))
|
||||
await expect
|
||||
.poll(() => recorded.notifications)
|
||||
.toEqual([{ title: "Question requires an answer", body: "Request notifications" }])
|
||||
await expect.poll(() => recorded.sounds).toEqual([expect.stringContaining("alert-02")])
|
||||
|
||||
// Choosing None leaves system notifications enabled; the next input request proves the settings reach delivery.
|
||||
await settings.locator('[data-action="settings-sounds-questions"]').click()
|
||||
await page.getByRole("option", { name: "None", exact: true }).click()
|
||||
await expect(settings.locator('[data-action="settings-sounds-questions"]')).toHaveText("None")
|
||||
const previews = recorded.sounds.slice()
|
||||
|
||||
await transport.send(event("mcp-elicitation", 2))
|
||||
await expect
|
||||
.poll(() => recorded.notifications.map((item) => item.title))
|
||||
.toEqual(["Question requires an answer", "Input requested"])
|
||||
|
||||
await questions.locator("..").locator('[data-slot="switch-control"]').click()
|
||||
await expect(questions).not.toBeChecked()
|
||||
await transport.send(event("question", 3))
|
||||
await transport.send(event("permission", 4))
|
||||
await expect
|
||||
.poll(() => recorded.notifications.map((item) => item.title))
|
||||
.toEqual(["Question requires an answer", "Input requested", "Permission required"])
|
||||
await transport.send(event("websearch.provider", 5))
|
||||
await expect
|
||||
.poll(() => recorded.notifications.map((item) => item.title))
|
||||
.toEqual(["Question requires an answer", "Input requested", "Permission required", "Permission required"])
|
||||
await expect
|
||||
.poll(() => recorded.sounds)
|
||||
.toEqual([...previews, expect.stringContaining("alert-01"), expect.stringContaining("alert-01")])
|
||||
})
|
||||
|
||||
for (const locale of ["en", "ar"]) {
|
||||
test(`background activity alignment stays physical and persists (${locale})`, async ({ page }) => {
|
||||
const id = "ses_activity_settings"
|
||||
|
|
|
|||
53
packages/app/e2e/utils/notifications.ts
Normal file
53
packages/app/e2e/utils/notifications.ts
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
import type { Page } from "@playwright/test"
|
||||
|
||||
// Only browser APIs are replaced: settings, event delivery, request stores and the coordinator stay real.
|
||||
export async function recordNotifications(page: Page) {
|
||||
const notifications: { title: string; body?: string }[] = []
|
||||
|
||||
const sounds: string[] = []
|
||||
|
||||
await page.exposeBinding("recordNotification", (_source, notification: { title: string; body?: string }) => {
|
||||
notifications.push(notification)
|
||||
})
|
||||
await page.exposeBinding("recordNotificationSound", (_source, src: string) => {
|
||||
sounds.push(src)
|
||||
})
|
||||
await page.addInitScript(() => {
|
||||
// SAFETY: exposeBinding above installs these callbacks before the app starts.
|
||||
const host: Window & {
|
||||
recordNotification?: (notification: { title: string; body?: string }) => Promise<void>
|
||||
recordNotificationSound?: (src: string) => Promise<void>
|
||||
} = window
|
||||
|
||||
// Simulate an unfocused app without changing the user's live desktop window.
|
||||
document.hasFocus = () => false
|
||||
Object.defineProperty(window, "Notification", {
|
||||
value: class extends EventTarget {
|
||||
static permission = "granted"
|
||||
onclick: (() => void) | null = null
|
||||
|
||||
constructor(title: string, options?: NotificationOptions) {
|
||||
super()
|
||||
void host.recordNotification!({ title, body: options?.body })
|
||||
}
|
||||
|
||||
close() {}
|
||||
},
|
||||
})
|
||||
Object.defineProperty(window, "Audio", {
|
||||
value: class {
|
||||
currentTime = 0
|
||||
|
||||
constructor(readonly src: string) {}
|
||||
|
||||
play() {
|
||||
return host.recordNotificationSound!(this.src)
|
||||
}
|
||||
|
||||
pause() {}
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
return { notifications, sounds }
|
||||
}
|
||||
|
|
@ -550,6 +550,8 @@ export const dict = {
|
|||
"error.chain.configInvalidWithMessage": "Config file at {{path}} is invalid: {{message}}",
|
||||
|
||||
"notification.permission.title": "Permission required",
|
||||
"notification.question.title": "Question requires an answer",
|
||||
"notification.elicitation.title": "Input requested",
|
||||
|
||||
"notification.session.responseReady.title": "Response ready",
|
||||
"notification.session.error.title": "Session error",
|
||||
|
|
@ -1055,6 +1057,8 @@ export const dict = {
|
|||
"Show system notification when the agent is complete or needs attention",
|
||||
"settings.general.notifications.permissions.title": "Permissions",
|
||||
"settings.general.notifications.permissions.description": "Show system notification when a permission is required",
|
||||
"settings.general.notifications.questions.title": "Questions",
|
||||
"settings.general.notifications.questions.description": "Show system notification when the agent asks a question",
|
||||
"settings.general.notifications.errors.title": "Errors",
|
||||
"settings.general.notifications.errors.description": "Show system notification when an error occurs",
|
||||
|
||||
|
|
@ -1062,6 +1066,8 @@ export const dict = {
|
|||
"settings.general.sounds.agent.description": "Play sound when the agent is complete or needs attention",
|
||||
"settings.general.sounds.permissions.title": "Permissions",
|
||||
"settings.general.sounds.permissions.description": "Play sound when a permission is required",
|
||||
"settings.general.sounds.questions.title": "Questions",
|
||||
"settings.general.sounds.questions.description": "Play sound when the agent asks a question",
|
||||
"settings.general.sounds.errors.title": "Errors",
|
||||
"settings.general.sounds.errors.description": "Play sound when an error occurs",
|
||||
"settings.general.sounds.interface.title": "Interface",
|
||||
|
|
|
|||
|
|
@ -177,6 +177,12 @@ export function createSoundSettingsController() {
|
|||
(value) => settings.sounds.setPermissionsEnabled(value),
|
||||
(id) => settings.sounds.setPermissions(id),
|
||||
),
|
||||
questions: channel(
|
||||
settings.sounds.questionsEnabled,
|
||||
settings.sounds.questions,
|
||||
(value) => settings.sounds.setQuestionsEnabled(value),
|
||||
(id) => settings.sounds.setQuestions(id),
|
||||
),
|
||||
errors: channel(
|
||||
settings.sounds.errorsEnabled,
|
||||
settings.sounds.errors,
|
||||
|
|
|
|||
|
|
@ -112,12 +112,14 @@ describe("settings schema", () => {
|
|||
keybinds: {},
|
||||
permissions: { autoApprove: false, autoApproveProjects: {} },
|
||||
workspaces: { defaultDestination: "last-used", lastUsed: {} },
|
||||
notifications: { agent: false, permissions: true, errors: false },
|
||||
notifications: { agent: false, permissions: true, questions: true, errors: false },
|
||||
sounds: {
|
||||
agentEnabled: true,
|
||||
agent: "staplebops-01",
|
||||
permissionsEnabled: true,
|
||||
permissions: "staplebops-02",
|
||||
questionsEnabled: true,
|
||||
questions: "staplebops-02",
|
||||
errorsEnabled: true,
|
||||
errors: "nope-03",
|
||||
interfaceEnabled: true,
|
||||
|
|
@ -165,7 +167,7 @@ describe("settings schema", () => {
|
|||
expect(settings.permissions).toEqual({ autoApprove: true, autoApproveProjects: { on: true, off: false } })
|
||||
expect(settings.workspaces).toEqual({ defaultDestination: "new", lastUsed: { good: "workspace" } })
|
||||
expect(settings.keybinds).toEqual({ good: "ctrl+k" })
|
||||
expect(settings.notifications).toEqual({ agent: false, permissions: true, errors: true })
|
||||
expect(settings.notifications).toEqual({ agent: false, permissions: true, questions: true, errors: true })
|
||||
expect(settings.sounds).toMatchObject({ agent: "custom", agentEnabled: false, permissions: "staplebops-02" })
|
||||
expect(decode(encode(settings))).toEqual(settings)
|
||||
})
|
||||
|
|
|
|||
|
|
@ -169,6 +169,7 @@ const workspacesSchema = Persistence.struct({
|
|||
const notificationsSchema = Persistence.struct({
|
||||
agent: Schema.Boolean,
|
||||
permissions: Schema.Boolean,
|
||||
questions: Schema.Boolean,
|
||||
errors: Schema.Boolean,
|
||||
})
|
||||
|
||||
|
|
@ -177,6 +178,8 @@ const soundsSchema = Persistence.struct({
|
|||
agent: Schema.String,
|
||||
permissionsEnabled: Schema.Boolean,
|
||||
permissions: Schema.String,
|
||||
questionsEnabled: Schema.Boolean,
|
||||
questions: Schema.String,
|
||||
errorsEnabled: Schema.Boolean,
|
||||
errors: Schema.String,
|
||||
interfaceEnabled: Schema.optional(Schema.Boolean),
|
||||
|
|
@ -310,12 +313,14 @@ export const defaultSettings: Settings = {
|
|||
keybinds: {},
|
||||
permissions: { autoApprove: false, autoApproveProjects: {} },
|
||||
workspaces: { defaultDestination: "last-used", lastUsed: {} },
|
||||
notifications: { agent: false, permissions: true, errors: false },
|
||||
notifications: { agent: false, permissions: true, questions: true, errors: false },
|
||||
sounds: {
|
||||
agentEnabled: true,
|
||||
agent: "staplebops-01",
|
||||
permissionsEnabled: true,
|
||||
permissions: "staplebops-02",
|
||||
questionsEnabled: true,
|
||||
questions: "staplebops-02",
|
||||
errorsEnabled: true,
|
||||
errors: "nope-03",
|
||||
interfaceEnabled: true,
|
||||
|
|
@ -540,6 +545,10 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
|||
setPermissions(value: boolean) {
|
||||
setStore("notifications", "permissions", value)
|
||||
},
|
||||
questions: withFallback(() => store.notifications?.questions, defaultSettings.notifications.questions),
|
||||
setQuestions(value: boolean) {
|
||||
setStore("notifications", "questions", value)
|
||||
},
|
||||
errors: withFallback(() => store.notifications?.errors, defaultSettings.notifications.errors),
|
||||
setErrors(value: boolean) {
|
||||
setStore("notifications", "errors", value)
|
||||
|
|
@ -565,6 +574,14 @@ export const { use: useSettings, provider: SettingsProvider } = createSimpleCont
|
|||
setPermissions(value: string) {
|
||||
setStore("sounds", "permissions", value)
|
||||
},
|
||||
questionsEnabled: withFallback(() => store.sounds?.questionsEnabled, defaultSettings.sounds.questionsEnabled),
|
||||
setQuestionsEnabled(value: boolean) {
|
||||
setStore("sounds", "questionsEnabled", value)
|
||||
},
|
||||
questions: withFallback(() => store.sounds?.questions, defaultSettings.sounds.questions),
|
||||
setQuestions(value: string) {
|
||||
setStore("sounds", "questions", value)
|
||||
},
|
||||
errorsEnabled: withFallback(() => store.sounds?.errorsEnabled, defaultSettings.sounds.errorsEnabled),
|
||||
setErrorsEnabled(value: boolean) {
|
||||
setStore("sounds", "errorsEnabled", value)
|
||||
|
|
|
|||
|
|
@ -23,6 +23,11 @@ const soundSettings = {
|
|||
title: "settings.general.sounds.permissions.title",
|
||||
description: "settings.general.sounds.permissions.description",
|
||||
},
|
||||
questions: {
|
||||
action: "settings-sounds-questions",
|
||||
title: "settings.general.sounds.questions.title",
|
||||
description: "settings.general.sounds.questions.description",
|
||||
},
|
||||
errors: {
|
||||
action: "settings-sounds-errors",
|
||||
title: "settings.general.sounds.errors.title",
|
||||
|
|
@ -31,7 +36,7 @@ const soundSettings = {
|
|||
} as const
|
||||
|
||||
const SoundSetting: Component<{
|
||||
kind: "agent" | "permissions" | "errors"
|
||||
kind: "agent" | "permissions" | "questions" | "errors"
|
||||
channel: SoundSettingsController["agent"]
|
||||
}> = (props) => {
|
||||
const language = useLanguage()
|
||||
|
|
@ -100,6 +105,21 @@ export const SettingsNotifications: Component = () => {
|
|||
</div>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.notifications.questions.title")}
|
||||
description={language.t("settings.general.notifications.questions.description")}
|
||||
>
|
||||
<div data-action="settings-notifications-questions">
|
||||
<Switch
|
||||
hideLabel
|
||||
checked={settings.notifications.questions()}
|
||||
onChange={(checked) => settings.notifications.setQuestions(checked)}
|
||||
>
|
||||
{language.t("settings.general.notifications.questions.title")}
|
||||
</Switch>
|
||||
</div>
|
||||
</SettingsRow>
|
||||
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.notifications.errors.title")}
|
||||
description={language.t("settings.general.notifications.errors.description")}
|
||||
|
|
@ -119,6 +139,7 @@ export const SettingsNotifications: Component = () => {
|
|||
<SettingsList>
|
||||
<SoundSetting kind="agent" channel={sounds.agent} />
|
||||
<SoundSetting kind="permissions" channel={sounds.permissions} />
|
||||
<SoundSetting kind="questions" channel={sounds.questions} />
|
||||
<SoundSetting kind="errors" channel={sounds.errors} />
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.sounds.interface.title")}
|
||||
|
|
|
|||
|
|
@ -172,6 +172,14 @@ export const clientSettings: Entry<SettingsRootTab>[] = [
|
|||
description: "settings.general.notifications.permissions.description",
|
||||
keywords: "desktop notifications permissions",
|
||||
},
|
||||
{
|
||||
tab: "notifications",
|
||||
label: "settings.general.notifications.questions.title",
|
||||
target: "settings-notifications-questions",
|
||||
section: "settings.general.section.notifications",
|
||||
description: "settings.general.notifications.questions.description",
|
||||
keywords: "desktop notifications questions mcp elicitation input",
|
||||
},
|
||||
{
|
||||
tab: "notifications",
|
||||
label: "settings.general.notifications.errors.title",
|
||||
|
|
@ -196,6 +204,14 @@ export const clientSettings: Entry<SettingsRootTab>[] = [
|
|||
description: "settings.general.sounds.permissions.description",
|
||||
keywords: "sound audio permissions",
|
||||
},
|
||||
{
|
||||
tab: "notifications",
|
||||
label: "settings.general.sounds.questions.title",
|
||||
target: "settings-sounds-questions",
|
||||
section: "settings.general.section.sounds",
|
||||
description: "settings.general.sounds.questions.description",
|
||||
keywords: "sound audio questions mcp elicitation input",
|
||||
},
|
||||
{
|
||||
tab: "notifications",
|
||||
label: "settings.general.sounds.errors.title",
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import type { ServerSDK } from "@/runtime/server/client"
|
|||
import type { Data } from "@opencode/client/solid"
|
||||
import { usePlatform } from "@/runtime/platform/platform"
|
||||
import { useLanguage } from "@/runtime/i18n/language"
|
||||
import { useSettings } from "@/settings/model"
|
||||
import { projectSettingsKey, useSettings } from "@/settings/model"
|
||||
import { Persist, persisted, removePersisted } from "@/runtime/persistence/storage"
|
||||
import { Persistence } from "@/runtime/persistence/schema"
|
||||
import { playSoundById } from "@/shell/notifications/sound"
|
||||
|
|
@ -17,6 +17,13 @@ import { useServer } from "@/runtime/server/current"
|
|||
|
||||
type NotificationTabs = Pick<ReturnType<typeof useTabs>, "addSessionTab" | "rememberSessionRoute" | "select">
|
||||
|
||||
const requestTitles = {
|
||||
permission: "notification.permission.title",
|
||||
question: "notification.question.title",
|
||||
"mcp-elicitation": "notification.elicitation.title",
|
||||
"websearch.provider": "notification.permission.title",
|
||||
} as const
|
||||
|
||||
export function openNotificationSession(tabs: NotificationTabs, server: ServerConnection.Key, sessionID: string) {
|
||||
const tab = tabs.addSessionTab({ server, sessionId: sessionID })
|
||||
|
||||
|
|
@ -280,7 +287,72 @@ export function createServerNotificationState(input: {
|
|||
})
|
||||
}
|
||||
|
||||
const handleRequest = async (
|
||||
kind: "permission" | "question" | "mcp-elicitation" | "websearch.provider",
|
||||
sessionID: string,
|
||||
requestID: string,
|
||||
) => {
|
||||
const session = await lookup(sessionID)
|
||||
|
||||
if (!session || disposed.value) return
|
||||
|
||||
const target = sessionIDHasOpenTab(tabs.store, input.key, sessionID)
|
||||
? sessionID
|
||||
: input.data.session.root(sessionID)
|
||||
|
||||
if (!sessionIDHasOpenTab(tabs.store, input.key, target)) return
|
||||
|
||||
const category = kind === "question" || kind === "mcp-elicitation" ? "questions" : "permissions"
|
||||
|
||||
const pending = () => {
|
||||
if (disposed.value) return false
|
||||
|
||||
if (kind !== "permission") return input.data.session.form.list(sessionID)?.some((form) => form.id === requestID)
|
||||
|
||||
if (settings.permissions.autoApproves(projectSettingsKey(input.sdk.scope, session.projectID))) return false
|
||||
|
||||
return input.data.session.permission.list(sessionID)?.some((request) => request.id === requestID)
|
||||
}
|
||||
|
||||
const key = `${input.key}\0${kind}:${requestID}`
|
||||
|
||||
const soundEnabled =
|
||||
category === "questions" ? settings.sounds.questionsEnabled : settings.sounds.permissionsEnabled
|
||||
|
||||
if (soundEnabled() && pending()) {
|
||||
void input.coordinator.sound(key, () => {
|
||||
if (pending()) return playSoundById(settings.sounds[category]())
|
||||
})
|
||||
}
|
||||
|
||||
if (!settings.notifications[category]() || !pending()) return
|
||||
|
||||
void input.coordinator.system(key, () => {
|
||||
if (!pending()) return
|
||||
|
||||
return platform.notify(language.t(requestTitles[kind]), session.title ?? sessionID, () =>
|
||||
openNotificationSession(tabs, input.key, target),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
const unsub = input.sdk.event.listen((event) => {
|
||||
if (event.type === "permission.asked") {
|
||||
void handleRequest("permission", event.data.sessionID, event.data.id)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (event.type === "form.created") {
|
||||
const kind = event.data.form.metadata?.kind
|
||||
|
||||
if (kind === "question" || kind === "mcp-elicitation" || kind === "websearch.provider") {
|
||||
void handleRequest(kind, event.data.form.sessionID, event.data.form.id)
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if (event.type === "session.execution.failed") {
|
||||
handleSessionError(event.data.sessionID, event.id)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
import { beforeAll, expect, mock, setSystemTime, test, vi } from "bun:test"
|
||||
import { beforeAll, beforeEach, expect, mock, setSystemTime, test, vi } from "bun:test"
|
||||
import { createEffect, createRoot } from "solid-js"
|
||||
import { createStore } from "solid-js/store"
|
||||
import type { OpenCodeEvent } from "@opencode/client/promise"
|
||||
import type { ServerConnection } from "@/runtime/server/registry"
|
||||
import { ServerScope } from "@/runtime/server/scope"
|
||||
import type { Tab } from "@/shell/tabs/tabs"
|
||||
import type { createNotificationCoordinator } from "@/shell/notifications/coordinator"
|
||||
|
||||
type NotificationDelivery = Parameters<ReturnType<typeof createNotificationCoordinator>["system"]>[1]
|
||||
|
||||
// SAFETY: this is the key format `ServerConnection.key` produces for a local server.
|
||||
const server = "local\nhttp://localhost:4096" as ServerConnection.Key
|
||||
|
|
@ -13,10 +16,35 @@ const session = { id: "session-1", title: "Test session", location: { directory:
|
|||
|
||||
const alerts: string[] = []
|
||||
|
||||
const tabs = { store: new Array<Tab>() }
|
||||
const sounds: string[] = []
|
||||
|
||||
const clicks: Array<() => void> = []
|
||||
|
||||
const selected: string[] = []
|
||||
|
||||
const tabs = {
|
||||
store: new Array<Tab>(),
|
||||
addSessionTab: (input: { server: ServerConnection.Key; sessionId: string }) => ({
|
||||
type: "session" as const,
|
||||
...input,
|
||||
}),
|
||||
rememberSessionRoute: () => {},
|
||||
select: (tab: Tab) => {
|
||||
if (tab.type === "session") selected.push(tab.sessionId)
|
||||
},
|
||||
}
|
||||
|
||||
let createServerNotificationState: typeof import("@/shell/notifications/notification").createServerNotificationState
|
||||
|
||||
const preferences = {
|
||||
autoApprove: false,
|
||||
agent: true,
|
||||
permissions: true,
|
||||
questions: true,
|
||||
permissionsSound: true,
|
||||
questionsSound: true,
|
||||
}
|
||||
|
||||
// Each test fakes only the parts of the SDK, data store and coordinator that the notification state reads.
|
||||
const createState = (input: { sdk: object; data: object; coordinator: object }) =>
|
||||
// SAFETY: the fakes cover every member the notification state reaches in that test.
|
||||
|
|
@ -36,26 +64,172 @@ beforeAll(async () => {
|
|||
...real.platform,
|
||||
usePlatform: () => ({
|
||||
platform: "web",
|
||||
notify: async (title: string) => {
|
||||
notify: async (title: string, _description?: string, onClick?: () => void) => {
|
||||
alerts.push(title)
|
||||
|
||||
if (onClick) clicks.push(onClick)
|
||||
},
|
||||
}),
|
||||
}))
|
||||
mock.module("@/settings/model", () => ({
|
||||
...real.settings,
|
||||
useSettings: () => ({
|
||||
sounds: { agentEnabled: () => false, errorsEnabled: () => false },
|
||||
notifications: { agent: () => true, errors: () => true },
|
||||
}),
|
||||
}))
|
||||
mock.module("@/runtime/i18n/language", () => ({
|
||||
...real.language,
|
||||
useLanguage: () => ({ t: (key: string) => key }),
|
||||
}))
|
||||
mock.module("@/settings/model", () => ({
|
||||
...real.settings,
|
||||
useSettings: () => ({
|
||||
sounds: {
|
||||
agentEnabled: () => false,
|
||||
errorsEnabled: () => false,
|
||||
permissionsEnabled: () => preferences.permissionsSound,
|
||||
permissions: () => "alert-01",
|
||||
questionsEnabled: () => preferences.questionsSound,
|
||||
questions: () => "alert-02",
|
||||
},
|
||||
notifications: {
|
||||
agent: () => preferences.agent,
|
||||
errors: () => true,
|
||||
permissions: () => preferences.permissions,
|
||||
questions: () => preferences.questions,
|
||||
},
|
||||
permissions: { autoApproves: () => preferences.autoApprove },
|
||||
}),
|
||||
}))
|
||||
mock.module("@/shell/tabs/tabs", () => ({ ...real.tabs, useTabs: () => tabs }))
|
||||
mock.module("@/shell/notifications/sound", () => ({
|
||||
playSoundById: async (id: string) => {
|
||||
sounds.push(id)
|
||||
},
|
||||
}))
|
||||
createServerNotificationState = (await import("@/shell/notifications/notification")).createServerNotificationState
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
alerts.length = 0
|
||||
sounds.length = 0
|
||||
clicks.length = 0
|
||||
selected.length = 0
|
||||
Object.assign(preferences, {
|
||||
autoApprove: false,
|
||||
agent: true,
|
||||
permissions: true,
|
||||
questions: true,
|
||||
permissionsSound: true,
|
||||
questionsSound: true,
|
||||
})
|
||||
})
|
||||
|
||||
const requests = [
|
||||
{ kind: "permission", category: "permissions", title: "notification.permission.title" },
|
||||
{ kind: "question", category: "questions", title: "notification.question.title" },
|
||||
{ kind: "mcp-elicitation", category: "questions", title: "notification.elicitation.title" },
|
||||
{ kind: "websearch.provider", category: "permissions", title: "notification.permission.title" },
|
||||
] as const
|
||||
|
||||
test.each(
|
||||
requests.flatMap((request) =>
|
||||
[
|
||||
"enabled",
|
||||
"other category disabled",
|
||||
"notifications disabled",
|
||||
"sound disabled",
|
||||
"resolved",
|
||||
"auto approve",
|
||||
"root tab",
|
||||
"no tab",
|
||||
"disposed",
|
||||
].map((scenario) => ({ ...request, scenario })),
|
||||
),
|
||||
)("request alerts: $kind / $scenario", async (options) => {
|
||||
preferences.agent = false
|
||||
preferences.autoApprove = options.scenario === "auto approve"
|
||||
preferences[options.category] = options.scenario !== "notifications disabled"
|
||||
preferences[options.category === "questions" ? "questionsSound" : "permissionsSound"] =
|
||||
options.scenario !== "sound disabled"
|
||||
|
||||
if (options.scenario === "other category disabled") {
|
||||
preferences[options.category === "questions" ? "permissions" : "questions"] = false
|
||||
preferences[options.category === "questions" ? "permissionsSound" : "questionsSound"] = false
|
||||
}
|
||||
|
||||
tabs.store =
|
||||
options.scenario === "no tab"
|
||||
? []
|
||||
: [{ type: "session", server, sessionId: options.scenario === "root tab" ? "root" : session.id }]
|
||||
const listeners = new Array<(event: OpenCodeEvent) => void>()
|
||||
|
||||
const deliveries = new Array<NotificationDelivery>()
|
||||
|
||||
const pending = { value: true }
|
||||
|
||||
const dispose = createRoot((dispose) => {
|
||||
createState({
|
||||
sdk: {
|
||||
scope: ServerScope.local,
|
||||
event: {
|
||||
listen: (listener: (event: OpenCodeEvent) => void) => {
|
||||
listeners.push(listener)
|
||||
|
||||
return () => {}
|
||||
},
|
||||
},
|
||||
},
|
||||
data: {
|
||||
session: {
|
||||
get: () => ({ ...session, parentID: "root", projectID: "project-1" }),
|
||||
root: () => "root",
|
||||
permission: { list: () => (pending.value ? [{ id: "request-1" }] : []) },
|
||||
form: { list: () => (pending.value ? [{ id: "request-1" }] : []) },
|
||||
},
|
||||
},
|
||||
coordinator: {
|
||||
sound: async (_key: string, run: NotificationDelivery) => {
|
||||
deliveries.push(run)
|
||||
},
|
||||
system: async (_key: string, run: NotificationDelivery) => {
|
||||
deliveries.push(run)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return dispose
|
||||
})
|
||||
|
||||
try {
|
||||
listeners.forEach((listener) =>
|
||||
// SAFETY: only the request identity, session and form kind are read by the handler.
|
||||
listener({
|
||||
type: options.kind === "permission" ? "permission.asked" : "form.created",
|
||||
data:
|
||||
options.kind === "permission"
|
||||
? { sessionID: session.id, id: "request-1" }
|
||||
: { form: { sessionID: session.id, id: "request-1", metadata: { kind: options.kind } } },
|
||||
} as never),
|
||||
)
|
||||
await Promise.resolve()
|
||||
|
||||
if (options.scenario === "resolved") pending.value = false
|
||||
|
||||
if (options.scenario === "disposed") dispose()
|
||||
await Promise.all(deliveries.map((run) => run()))
|
||||
|
||||
const suppressed =
|
||||
["resolved", "disposed", "no tab"].includes(options.scenario) ||
|
||||
(options.scenario === "auto approve" && options.kind === "permission")
|
||||
|
||||
expect(alerts).toEqual(!suppressed && options.scenario !== "notifications disabled" ? [options.title] : [])
|
||||
expect(sounds).toEqual(
|
||||
!suppressed && options.scenario !== "sound disabled"
|
||||
? [options.category === "questions" ? "alert-02" : "alert-01"]
|
||||
: [],
|
||||
)
|
||||
clicks.forEach((click) => click())
|
||||
expect(selected).toEqual(alerts.length ? [options.scenario === "root tab" ? "root" : session.id] : [])
|
||||
} finally {
|
||||
dispose()
|
||||
}
|
||||
})
|
||||
|
||||
test.each([
|
||||
["session.execution.succeeded", "notification.session.responseReady.title"],
|
||||
["session.execution.failed", "notification.session.error.title"],
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue