mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 17:01:37 +03:00
feat(desktop): choose whether the background service keeps running after quit
This commit is contained in:
committed by
opencode-agent[bot]
Unverified
parent
ec53c3b3cb
commit
aa7336d557
@@ -316,6 +316,12 @@ export const DESKTOP_NATIVE_ENGLISH = {
|
||||
|
||||
"desktop.contextMenu.spellcheck": "Spellcheck",
|
||||
"desktop.contextMenu.spellcheckLanguages": "Spellcheck Languages",
|
||||
|
||||
"desktop.quit.serviceNotice.message": "OpenCode keeps running in the background",
|
||||
"desktop.quit.serviceNotice.detail":
|
||||
"After you quit, the OpenCode server keeps running so agents, terminals, and MCP servers can finish their work. You can change this anytime in Settings.",
|
||||
"desktop.quit.serviceNotice.keepRunning": "Keep Running",
|
||||
"desktop.quit.serviceNotice.stopOnQuit": "Stop When I Quit",
|
||||
} as const
|
||||
|
||||
export type DesktopNativeKey = keyof typeof DESKTOP_NATIVE_ENGLISH
|
||||
|
||||
@@ -1067,6 +1067,9 @@ export const dict = {
|
||||
"settings.general.row.pinchZoom.description": "Allow trackpad pinch and Ctrl-scroll gestures to zoom",
|
||||
"settings.general.row.spellcheck.title": "Spellcheck",
|
||||
"settings.general.row.spellcheck.description": "Underline misspelled words while typing",
|
||||
"settings.general.row.keepServiceRunning.title": "Keep server running after quit",
|
||||
"settings.general.row.keepServiceRunning.description":
|
||||
"Agents, terminals, and MCP servers keep working after you quit. Turning this off also stops sessions started from the CLI",
|
||||
|
||||
"sound.option.none": "None",
|
||||
"sound.option.alert01": "Alert 01",
|
||||
|
||||
@@ -114,6 +114,12 @@ type PlatformBase = {
|
||||
/** Turn the native spellchecker on or off (desktop only) */
|
||||
setSpellcheckEnabled?(enabled: boolean): Promise<void>
|
||||
|
||||
/** Get whether the background server keeps running after the app quits (desktop only) */
|
||||
getKeepServiceRunning?(): Promise<boolean>
|
||||
|
||||
/** Choose whether the background server keeps running after the app quits (desktop only) */
|
||||
setKeepServiceRunning?(enabled: boolean): Promise<void>
|
||||
|
||||
/** Run a desktop-only menu action from the app chrome */
|
||||
runDesktopMenuAction?(action: DesktopMenuAction): Promise<void> | void
|
||||
|
||||
|
||||
@@ -251,6 +251,14 @@ export const SettingsGeneral: Component = () => {
|
||||
write: (checked) => platform.setSpellcheckEnabled?.(checked),
|
||||
})
|
||||
|
||||
const keepServiceRunning = createOptimisticSetting({
|
||||
source: () => (desktop() && "getKeepServiceRunning" in platform) || undefined,
|
||||
initial: true,
|
||||
initialMeta: undefined,
|
||||
load: async () => ({ value: (await platform.getKeepServiceRunning?.()) ?? true, meta: undefined }),
|
||||
write: (checked) => platform.setKeepServiceRunning?.(checked),
|
||||
})
|
||||
|
||||
const GeneralSection = () => (
|
||||
<div class="settings-section">
|
||||
<h3 class="settings-section-title">{language.t("settings.general.section.general")}</h3>
|
||||
@@ -292,6 +300,16 @@ export const SettingsGeneral: Component = () => {
|
||||
<Switch checked={spellcheck.value()} onChange={spellcheck.select} />
|
||||
</div>
|
||||
</SettingsRow>
|
||||
<Show when={"getKeepServiceRunning" in platform}>
|
||||
<SettingsRow
|
||||
title={language.t("settings.general.row.keepServiceRunning.title")}
|
||||
description={language.t("settings.general.row.keepServiceRunning.description")}
|
||||
>
|
||||
<div data-action="settings-keep-service-running">
|
||||
<Switch checked={keepServiceRunning.value()} onChange={keepServiceRunning.select} />
|
||||
</div>
|
||||
</SettingsRow>
|
||||
</Show>
|
||||
</Show>
|
||||
|
||||
<PluginSettingsSections page="general" section="general" />
|
||||
|
||||
@@ -11,6 +11,7 @@ import { IpcPortHandoff } from "../ipc-transport"
|
||||
import { ApplicationLifecycle } from "../lifecycle"
|
||||
import { finishFirstLaunchOnboarding, isFirstLaunchOnboardingPending } from "../lifecycle/onboarding"
|
||||
import { BackgroundService } from "../service/background-service"
|
||||
import { QuitBehavior } from "../service/quit-behavior"
|
||||
import { SidecarCredentials } from "../service/sidecar-credentials"
|
||||
import { getWindowID, setBackgroundColor } from "../windows"
|
||||
import { sender } from "./context"
|
||||
@@ -44,6 +45,8 @@ export const appHandlers = AppRpcs.toLayer(
|
||||
AppSetBackgroundColor: ({ color }) => Effect.sync(() => setBackgroundColor(color)),
|
||||
AppGetSpellcheckEnabled: () => Effect.sync(getSpellcheckEnabled),
|
||||
AppSetSpellcheckEnabled: ({ enabled }) => Effect.sync(() => setSpellcheckEnabled(enabled)),
|
||||
AppGetKeepServiceRunning: () => Effect.sync(QuitBehavior.getKeepServiceRunning),
|
||||
AppSetKeepServiceRunning: ({ enabled }) => Effect.sync(() => QuitBehavior.setKeepServiceRunning(enabled)),
|
||||
AppExportDebugLogs: () => logging.exportDebug,
|
||||
AppSetForceFocus: ({ enabled }, context) => promise(() => setForceFocus(sender(handoff, context), enabled)),
|
||||
AppRecordFatalRendererError: ({ error }) =>
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type Handoff,
|
||||
type State,
|
||||
} from "./machine"
|
||||
import { QuitBehavior } from "../service/quit-behavior"
|
||||
import { initializeFirstLaunchOnboarding } from "./onboarding"
|
||||
import { Shutdown } from "./shutdown"
|
||||
|
||||
@@ -66,6 +67,12 @@ const runtime = Layer.effect(
|
||||
}),
|
||||
),
|
||||
),
|
||||
confirm: () =>
|
||||
runPromise(
|
||||
Effect.tryPromise(QuitBehavior.confirmFirstQuit).pipe(
|
||||
Effect.catch((error) => Effect.logError("first-quit service notice failed", { error })),
|
||||
),
|
||||
),
|
||||
// Electron records a cancelled quit only after `before-quit` returns. A stop with nothing to do finishes in a
|
||||
// microtask, so quitting from it would be overwritten and the app would stay alive with no windows. Quit on the
|
||||
// next tick instead.
|
||||
@@ -121,7 +128,7 @@ const runtime = Layer.effect(
|
||||
|
||||
const beforeQuit = (event: Event) => {
|
||||
if (preventsQuit(driver.state())) event.preventDefault()
|
||||
driver.dispatch({ type: "before.quit" })
|
||||
driver.dispatch({ type: "before.quit", confirm: QuitBehavior.isQuitNoticePending() })
|
||||
}
|
||||
|
||||
const willQuit = () => driver.dispatch({ type: "will.quit" })
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
preventsQuit,
|
||||
quitsWhenAllWindowsClosed,
|
||||
restoresWindows,
|
||||
stopsForQuit,
|
||||
transition,
|
||||
type Event,
|
||||
type Reply,
|
||||
@@ -146,6 +147,70 @@ describe("app lifecycle machine", () => {
|
||||
])
|
||||
})
|
||||
|
||||
test("the first quit holds Electron while the user answers, then stops the plugins exactly once", () => {
|
||||
const asked = transition(initialState(), { type: "before.quit", confirm: true })
|
||||
|
||||
expect(asked).toEqual({
|
||||
state: { status: "confirming", attempt: 1 },
|
||||
commands: [{ type: "confirm-quit", attempt: 1 }],
|
||||
})
|
||||
expect(preventsQuit(asked.state)).toBe(true)
|
||||
expect(isQuitting(asked.state)).toBe(false)
|
||||
|
||||
// Cmd+Q pressed again, or the window closed again, while the dialog is open asks nothing new.
|
||||
expect(transition(asked.state, { type: "before.quit", confirm: true })).toEqual({
|
||||
state: asked.state,
|
||||
commands: [],
|
||||
})
|
||||
expect(transition(asked.state, { type: "quit.confirmed", attempt: 0 })).toEqual({
|
||||
state: asked.state,
|
||||
commands: [],
|
||||
})
|
||||
|
||||
const answered = transition(asked.state, { type: "quit.confirmed", attempt: 1 })
|
||||
expect(answered).toEqual({
|
||||
state: { status: "stopping", attempt: 2, exit: "quit" },
|
||||
commands: [{ type: "stop-plugins", attempt: 2 }],
|
||||
})
|
||||
expect(stopsForQuit(answered.state)).toBe(true)
|
||||
expect(transition(answered.state, { type: "quit.confirmed", attempt: 1 }).state).toBe(answered.state)
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ name: "the OS ends the session", event: { type: "session.ending" } },
|
||||
{ name: "a signal quits", event: { type: "exit.requested", mode: "quit" } },
|
||||
{ name: "Electron quits without before-quit", event: { type: "will.quit" } },
|
||||
] satisfies { name: string; event: Event }[])("$name while the user is answering: the quit goes on", (row) => {
|
||||
const asked = transition(initialState(), { type: "before.quit", confirm: true }).state
|
||||
const next = transition(asked, row.event)
|
||||
|
||||
expect(next.commands).toEqual([{ type: "stop-plugins", attempt: 2 }])
|
||||
expect(stopsForQuit(next.state)).toBe(true)
|
||||
expect(transition(next.state, { type: "quit.confirmed", attempt: 1 }).state).toBe(next.state)
|
||||
})
|
||||
|
||||
test("a restart while the user is answering is rejected as busy", () => {
|
||||
const asked = transition(initialState(), { type: "before.quit", confirm: true }).state
|
||||
const caller = reply()
|
||||
|
||||
expect(transition(asked, { type: "restart.requested", keep, handoff, reply: caller })).toEqual({
|
||||
state: asked,
|
||||
commands: [{ type: "reject", reply: caller, reason: { kind: "busy" } }],
|
||||
})
|
||||
})
|
||||
|
||||
test.each([
|
||||
{ name: "quit", events: [{ type: "before.quit" }], quit: true },
|
||||
{ name: "Electron quit", events: [{ type: "will.quit" }], quit: true },
|
||||
{ name: "relaunch", events: [{ type: "exit.requested", mode: "relaunch" }], quit: false },
|
||||
{ name: "restart handoff", events: [{ type: "restart.requested", keep, handoff, reply: reply() }], quit: false },
|
||||
] satisfies { name: string; events: Event[]; quit: boolean }[])(
|
||||
"only a quit stops the background service, not a $name",
|
||||
(row) => {
|
||||
expect(stopsForQuit(replay(row.events).state)).toBe(row.quit)
|
||||
},
|
||||
)
|
||||
|
||||
const phases = [
|
||||
{ phase: "suspending", events: [], reason: { kind: "quitting" }, stale: { type: "plugins.stopped", attempt: 1 } },
|
||||
{
|
||||
|
||||
@@ -14,6 +14,8 @@ export type Reply = { readonly resolve: () => void; readonly reject: (cause: unk
|
||||
*/
|
||||
export type State =
|
||||
| { readonly status: "running"; readonly attempt: number }
|
||||
/** The user quit for the first time and is choosing whether the background service outlives the app. */
|
||||
| { readonly status: "confirming"; readonly attempt: number }
|
||||
/** Every plugin but `keep` is stopping for a restart handoff; without `handoff` the app relaunches next. */
|
||||
| {
|
||||
readonly status: "suspending"
|
||||
@@ -40,7 +42,9 @@ export type Event =
|
||||
| { readonly type: "exit.requested"; readonly mode: ExitMode }
|
||||
/** Windows logoff or shutdown (`session-end` on each window); Electron emits no `before-quit` for it. */
|
||||
| { readonly type: "session.ending" }
|
||||
| { readonly type: "before.quit" }
|
||||
/** `confirm` asks the user first, once, whether the background service should keep running after quit. */
|
||||
| { readonly type: "before.quit"; readonly confirm?: boolean }
|
||||
| { readonly type: "quit.confirmed"; readonly attempt: number }
|
||||
| { readonly type: "will.quit" }
|
||||
|
||||
export type RejectReason =
|
||||
@@ -49,6 +53,7 @@ export type RejectReason =
|
||||
| { readonly kind: "quitting" }
|
||||
|
||||
export type Command =
|
||||
| { readonly type: "confirm-quit"; readonly attempt: number }
|
||||
| { readonly type: "stop-plugins"; readonly attempt: number }
|
||||
| { readonly type: "run-handoff"; readonly attempt: number; readonly handoff: Handoff }
|
||||
| { readonly type: "resume-plugins"; readonly attempt: number }
|
||||
@@ -75,8 +80,22 @@ export function transition(state: State, event: Event): Transition {
|
||||
|
||||
// A quit that starts while the handoff runs is the handoff's own (quitAndInstall quits before its promise settles),
|
||||
// and the plugins it must not wait for are already stopped.
|
||||
if (event.type === "before.quit")
|
||||
return state.status === "handing-off" ? unchanged(state) : exitRequested(state, "quit")
|
||||
if (event.type === "before.quit") {
|
||||
if (state.status === "handing-off" || state.status === "confirming") return unchanged(state)
|
||||
|
||||
if (state.status === "running" && event.confirm)
|
||||
return {
|
||||
state: { status: "confirming", attempt: state.attempt + 1 },
|
||||
commands: [{ type: "confirm-quit", attempt: state.attempt + 1 }],
|
||||
}
|
||||
|
||||
return exitRequested(state, "quit")
|
||||
}
|
||||
|
||||
if (event.type === "quit.confirmed")
|
||||
return state.status === "confirming" && state.attempt === event.attempt
|
||||
? exitRequested(state, "quit")
|
||||
: unchanged(state)
|
||||
|
||||
if (event.type === "will.quit") return willQuit(state)
|
||||
|
||||
@@ -84,7 +103,8 @@ export function transition(state: State, event: Event): Transition {
|
||||
}
|
||||
|
||||
/** The app starts no plugin, and the windows that close are restored on the next launch. */
|
||||
export const isQuitting = (state: State) => state.status !== "running" && state.status !== "resuming"
|
||||
export const isQuitting = (state: State) =>
|
||||
state.status !== "running" && state.status !== "resuming" && state.status !== "confirming"
|
||||
|
||||
/** The scope a stop leaves running: the restart caller's, until the handoff settled. */
|
||||
export const keptScope = (state: State) =>
|
||||
@@ -93,7 +113,7 @@ export const keptScope = (state: State) =>
|
||||
/** The macOS dock reopens windows until a real quit starts; a restart handoff can still fail and keep the app. */
|
||||
export const restoresWindows = (state: State) => state.status !== "stopping" && state.status !== "quitting"
|
||||
|
||||
/** Electron's `before-quit` waits for the plugins to stop first. */
|
||||
/** Electron's `before-quit` waits for the user's answer and for the plugins to stop first. */
|
||||
export const preventsQuit = (state: State) => state.status !== "handing-off" && state.status !== "quitting"
|
||||
|
||||
/**
|
||||
@@ -103,6 +123,10 @@ export const preventsQuit = (state: State) => state.status !== "handing-off" &&
|
||||
export const quitsWhenAllWindowsClosed = (state: State, platform: NodeJS.Platform) =>
|
||||
platform !== "darwin" || state.status === "stopping" || state.status === "quitting"
|
||||
|
||||
/** Whether this stop ends in a quit, as opposed to a restart handoff or a relaunch. */
|
||||
export const stopsForQuit = (state: State) =>
|
||||
state.status === "quitting" || (state.status === "stopping" && state.exit === "quit")
|
||||
|
||||
function restartRequested(state: State, event: Extract<Event, { type: "restart.requested" }>): Transition {
|
||||
if (state.status === "running")
|
||||
return {
|
||||
@@ -149,7 +173,10 @@ function willQuit(state: State): Transition {
|
||||
}
|
||||
}
|
||||
|
||||
function stepSettled(state: State, event: Extract<Event, { readonly attempt: number }>): Transition {
|
||||
function stepSettled(
|
||||
state: State,
|
||||
event: Exclude<Extract<Event, { readonly attempt: number }>, { type: "quit.confirmed" }>,
|
||||
): Transition {
|
||||
if (state.status === "quitting" || state.attempt !== event.attempt) return unchanged(state)
|
||||
|
||||
if (event.type === "plugins.stopped" && state.status === "suspending") {
|
||||
@@ -213,6 +240,8 @@ export function createDriver(input: {
|
||||
readonly stop: () => Promise<void>
|
||||
/** Starts the plugins a handoff stopped again; never rejects. */
|
||||
readonly resume: () => Promise<void>
|
||||
/** Asks the user the first-quit question and stores the answer; never rejects. */
|
||||
readonly confirm: () => Promise<void>
|
||||
readonly exit: (mode: ExitMode) => void
|
||||
}) {
|
||||
const current = { state: initialState() }
|
||||
@@ -230,6 +259,12 @@ export function createDriver(input: {
|
||||
return void input.stop().then(done, done)
|
||||
}
|
||||
|
||||
if (command.type === "confirm-quit") {
|
||||
const done = () => dispatch({ type: "quit.confirmed", attempt: command.attempt })
|
||||
|
||||
return void input.confirm().then(done, done)
|
||||
}
|
||||
|
||||
if (command.type === "run-handoff")
|
||||
return void Promise.resolve()
|
||||
.then(command.handoff)
|
||||
|
||||
@@ -304,6 +304,46 @@ describe("background service driver", () => {
|
||||
expect(result).toEqual(A)
|
||||
})
|
||||
|
||||
test("disposing before the app stops the service on quit interrupts a reconnect and starts no replacement", async () => {
|
||||
const result = await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const attempts: string[] = []
|
||||
const finished: string[] = []
|
||||
|
||||
const machine = yield* BackgroundServiceMachine.make({
|
||||
probe: Effect.succeed(undefined),
|
||||
ensure: (mode) =>
|
||||
Effect.suspend(() => {
|
||||
attempts.push(mode)
|
||||
|
||||
return mode === "initial"
|
||||
? Effect.succeed(A)
|
||||
: Effect.never.pipe(Effect.onExit(() => Effect.sync(() => finished.push(mode))))
|
||||
}),
|
||||
publish: () => undefined,
|
||||
})
|
||||
|
||||
yield* machine.connection
|
||||
const pending = yield* Effect.forkChild(machine.reconnect.pipe(Effect.exit), { startImmediately: true })
|
||||
yield* Effect.yieldNow
|
||||
yield* machine.dispose
|
||||
const reconnect = yield* Fiber.join(pending)
|
||||
const later = yield* machine.reconnect.pipe(Effect.exit)
|
||||
|
||||
return { reconnect: reconnect._tag, later: later._tag, attempts, finished }
|
||||
}),
|
||||
),
|
||||
)
|
||||
|
||||
expect(result).toEqual({
|
||||
reconnect: "Failure",
|
||||
later: "Failure",
|
||||
attempts: ["initial", "reconnect"],
|
||||
finished: ["reconnect"],
|
||||
})
|
||||
})
|
||||
|
||||
test("a connect that dies fails its callers, and the next caller connects again", async () => {
|
||||
const result = await Effect.runPromise(
|
||||
Effect.scoped(
|
||||
|
||||
@@ -347,5 +347,14 @@ export const make = Effect.fn("BackgroundServiceMachine.make")(function* (input:
|
||||
return {
|
||||
connection: request("connection.requested"),
|
||||
reconnect: request("reconnect.requested"),
|
||||
/**
|
||||
* Ends the connection before the app stops the service on quit: a window that loses the service then cannot
|
||||
* start a replacement that would outlive the app, and an attempt still running is interrupted.
|
||||
*/
|
||||
dispose: Effect.suspend(() => {
|
||||
dispatch({ type: "disposed" })
|
||||
|
||||
return FiberSet.clear(fibers)
|
||||
}),
|
||||
}
|
||||
})
|
||||
|
||||
@@ -4,11 +4,15 @@ import { Context, Effect, FileSystem, Layer, Option, Path, Schema } from "effect
|
||||
import { SidecarChanged } from "../../shared/ipc-rpc/events"
|
||||
import { CHANNEL } from "../constants"
|
||||
import { emitIpcEvent } from "../ipc-events"
|
||||
import { ApplicationLifecycle } from "../lifecycle"
|
||||
import { stopsForQuit } from "../lifecycle/machine"
|
||||
import { Shutdown } from "../lifecycle/shutdown"
|
||||
import { getMainWindows } from "../windows"
|
||||
import { BackgroundServiceMachine } from "./background-service-machine"
|
||||
import { cleanStages } from "./cli-stages"
|
||||
import { keptStages, serviceVersion, shouldRetryEnsure } from "./cli-version"
|
||||
import { DesktopCli } from "./desktop-cli"
|
||||
import { QuitBehavior } from "./quit-behavior"
|
||||
import { SidecarCredentials } from "./sidecar-credentials"
|
||||
import { takeSidecarProbe } from "./sidecar-probe"
|
||||
|
||||
@@ -27,22 +31,57 @@ export const layer = Layer.effect(
|
||||
Service,
|
||||
Effect.gen(function* () {
|
||||
const context = yield* Effect.context<FileSystem.FileSystem | Path.Path | DesktopCli.Service>()
|
||||
const lifecycle = yield* ApplicationLifecycle.Service
|
||||
const shutdown = yield* Shutdown.Service
|
||||
|
||||
return Service.of(
|
||||
yield* BackgroundServiceMachine.make({
|
||||
probe: probe().pipe(Effect.provide(context)),
|
||||
ensure: (mode) => ensure(mode).pipe(Effect.provide(context)),
|
||||
publish: (data) => {
|
||||
SidecarCredentials.set(data)
|
||||
// Every window moves its requests and event stream to the new origin, not only the one that reconnected.
|
||||
const event = new SidecarChanged({ url: data.url })
|
||||
getMainWindows().forEach((win) => emitIpcEvent(win.webContents, event))
|
||||
},
|
||||
}),
|
||||
)
|
||||
const machine = yield* BackgroundServiceMachine.make({
|
||||
probe: probe().pipe(Effect.provide(context)),
|
||||
ensure: (mode) => ensure(mode).pipe(Effect.provide(context)),
|
||||
publish: (data) => {
|
||||
SidecarCredentials.set(data)
|
||||
// Every window moves its requests and event stream to the new origin, not only the one that reconnected.
|
||||
const event = new SidecarChanged({ url: data.url })
|
||||
getMainWindows().forEach((win) => emitIpcEvent(win.webContents, event))
|
||||
},
|
||||
})
|
||||
|
||||
// The service outlives the app by default, so agents keep working after quit. A restart handoff or a relaunch
|
||||
// keeps it either way.
|
||||
const remove = yield* shutdown.add({
|
||||
stop: Effect.suspend(() =>
|
||||
stopsForQuit(lifecycle.state()) && !QuitBehavior.getKeepServiceRunning()
|
||||
? machine.dispose.pipe(Effect.andThen(stop().pipe(Effect.provide(context))))
|
||||
: Effect.void,
|
||||
),
|
||||
resume: Effect.void,
|
||||
})
|
||||
|
||||
yield* Effect.addFinalizer(() => Effect.sync(remove))
|
||||
|
||||
return Service.of({ connection: machine.connection, reconnect: machine.reconnect })
|
||||
}),
|
||||
)
|
||||
|
||||
const stop = Effect.fn("BackgroundService.stop")(function* () {
|
||||
yield* Effect.logInfo("stopping v2 background service on quit")
|
||||
const path = yield* Path.Path
|
||||
const client = yield* Effect.promise(() => import("@opencode/client/service"))
|
||||
|
||||
yield* Effect.tryPromise(() => client.Service.stop({ file: registrationFile(path) })).pipe(
|
||||
Effect.catch((error) => Effect.logError("failed to stop v2 background service on quit", { error })),
|
||||
)
|
||||
})
|
||||
|
||||
function registrationFile(path: Path.Path) {
|
||||
if (process.env.OPENCODE_DESKTOP_SERVER_CHANNEL !== "local") return undefined
|
||||
|
||||
return path.join(
|
||||
process.env.XDG_STATE_HOME ?? path.join(app.getPath("home"), ".local", "state"),
|
||||
"opencode",
|
||||
"service-local.json",
|
||||
)
|
||||
}
|
||||
|
||||
// A compatible service the entry module already found is adopted at once; the machine still verifies it with
|
||||
// `ensure("initial")` (which also completes a terminal handoff), off the renderer's path.
|
||||
const probe = Effect.fn("BackgroundService.probe")(function* () {
|
||||
@@ -108,14 +147,7 @@ const prepare = Effect.fn("BackgroundService.prepare")(function* (mode: Backgrou
|
||||
if (isolated) process.env.XDG_STATE_HOME = app.getPath("userData")
|
||||
const client = yield* Effect.promise(() => import("@opencode/client/service"))
|
||||
|
||||
const file =
|
||||
process.env.OPENCODE_DESKTOP_SERVER_CHANNEL === "local"
|
||||
? path.join(
|
||||
process.env.XDG_STATE_HOME ?? path.join(app.getPath("home"), ".local", "state"),
|
||||
"opencode",
|
||||
"service-local.json",
|
||||
)
|
||||
: undefined
|
||||
const file = registrationFile(path)
|
||||
|
||||
return { cli, client, file, isolated, version }
|
||||
})
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
export * as QuitBehavior from "./quit-behavior"
|
||||
|
||||
import { dialog } from "electron"
|
||||
import { KEEP_SERVICE_RUNNING_KEY, SERVICE_QUIT_NOTICE_SHOWN_KEY } from "../storage/keys"
|
||||
import { getStore } from "../storage/store"
|
||||
import { nativeT } from "../native/translations"
|
||||
import { getLastFocusedWindow } from "../windows"
|
||||
|
||||
/** The background service outlives the app unless the user turned that off. */
|
||||
export function getKeepServiceRunning() {
|
||||
return getStore().get(KEEP_SERVICE_RUNNING_KEY) !== false
|
||||
}
|
||||
|
||||
export function setKeepServiceRunning(enabled: boolean) {
|
||||
getStore().set(KEEP_SERVICE_RUNNING_KEY, enabled)
|
||||
// Choosing in Settings answers the first-quit question too.
|
||||
getStore().set(SERVICE_QUIT_NOTICE_SHOWN_KEY, true)
|
||||
}
|
||||
|
||||
/** The first quit explains that the service keeps running, and offers to stop it instead. */
|
||||
export function isQuitNoticePending() {
|
||||
return getStore().get(SERVICE_QUIT_NOTICE_SHOWN_KEY) !== true
|
||||
}
|
||||
|
||||
const KEEP = 0
|
||||
|
||||
const STOP = 1
|
||||
|
||||
/** Asks once and stores the answer. Dismissing the dialog keeps the default: the service keeps running. */
|
||||
export async function confirmFirstQuit() {
|
||||
const win = getLastFocusedWindow()
|
||||
|
||||
const options: Electron.MessageBoxOptions = {
|
||||
type: "info",
|
||||
buttons: [nativeT("desktop.quit.serviceNotice.keepRunning"), nativeT("desktop.quit.serviceNotice.stopOnQuit")],
|
||||
defaultId: KEEP,
|
||||
cancelId: KEEP,
|
||||
message: nativeT("desktop.quit.serviceNotice.message"),
|
||||
detail: nativeT("desktop.quit.serviceNotice.detail"),
|
||||
}
|
||||
|
||||
// The last window is already closed when closing it quits the app (Windows, Linux), so the dialog may have no parent.
|
||||
const { response } = await (win && win.isVisible()
|
||||
? dialog.showMessageBox(win, options)
|
||||
: dialog.showMessageBox(options))
|
||||
|
||||
setKeepServiceRunning(response !== STOP)
|
||||
}
|
||||
@@ -15,3 +15,7 @@ export const BACKGROUND_COLOR_KEY = "backgroundColor"
|
||||
export const WINDOW_IDS_KEY = "windowIds"
|
||||
|
||||
export const BUNDLED_CLI_VERSION_KEY = "bundledCliVersion"
|
||||
|
||||
export const KEEP_SERVICE_RUNNING_KEY = "keepServiceRunning"
|
||||
|
||||
export const SERVICE_QUIT_NOTICE_SHOWN_KEY = "serviceQuitNoticeShown"
|
||||
|
||||
@@ -78,6 +78,8 @@ export type ElectronAPI = {
|
||||
setForceFocus(enabled: boolean): Promise<void>
|
||||
getSpellcheckEnabled(): Promise<boolean>
|
||||
setSpellcheckEnabled(enabled: boolean): Promise<void>
|
||||
getKeepServiceRunning(): Promise<boolean>
|
||||
setKeepServiceRunning(enabled: boolean): Promise<void>
|
||||
recordFatalRendererError(error: FatalRendererError): Promise<void>
|
||||
setNativeTranslations(bundle: DesktopNativeBundle): Promise<void>
|
||||
}
|
||||
|
||||
@@ -86,6 +86,8 @@ export const api: ElectronAPI = {
|
||||
setForceFocus: (enabled) => invoke("AppSetForceFocus", { enabled }),
|
||||
getSpellcheckEnabled: () => invoke("AppGetSpellcheckEnabled"),
|
||||
setSpellcheckEnabled: (enabled) => invoke("AppSetSpellcheckEnabled", { enabled }),
|
||||
getKeepServiceRunning: () => invoke("AppGetKeepServiceRunning"),
|
||||
setKeepServiceRunning: (enabled) => invoke("AppSetKeepServiceRunning", { enabled }),
|
||||
recordFatalRendererError: (error) => invoke("AppRecordFatalRendererError", { error }),
|
||||
setNativeTranslations: (bundle) => invoke("AppSetNativeTranslations", { value: bundle }),
|
||||
}
|
||||
|
||||
@@ -45,6 +45,8 @@ export function createDesktopPlatform(api: ElectronAPI, windowState: DesktopWind
|
||||
setPinchZoomEnabled,
|
||||
getSpellcheckEnabled: () => api.getSpellcheckEnabled(),
|
||||
setSpellcheckEnabled: (enabled) => api.setSpellcheckEnabled(enabled),
|
||||
getKeepServiceRunning: () => api.getKeepServiceRunning(),
|
||||
setKeepServiceRunning: (enabled) => api.setKeepServiceRunning(enabled),
|
||||
onDragCancel: (callback) => {
|
||||
window.addEventListener(DragCancelEvent, callback)
|
||||
|
||||
|
||||
@@ -63,6 +63,12 @@ export const AppSetSpellcheckEnabled = Rpc.make("AppSetSpellcheckEnabled", {
|
||||
payload: { enabled: Schema.Boolean },
|
||||
})
|
||||
|
||||
export const AppGetKeepServiceRunning = Rpc.make("AppGetKeepServiceRunning", { success: Schema.Boolean })
|
||||
|
||||
export const AppSetKeepServiceRunning = Rpc.make("AppSetKeepServiceRunning", {
|
||||
payload: { enabled: Schema.Boolean },
|
||||
})
|
||||
|
||||
export const AppSetNativeTranslations = Rpc.make("AppSetNativeTranslations", {
|
||||
payload: { value: Schema.Unknown },
|
||||
})
|
||||
@@ -83,6 +89,8 @@ export const AppRpcs = RpcGroup.make(
|
||||
AppSetForceFocus,
|
||||
AppGetSpellcheckEnabled,
|
||||
AppSetSpellcheckEnabled,
|
||||
AppGetKeepServiceRunning,
|
||||
AppSetKeepServiceRunning,
|
||||
AppRecordFatalRendererError,
|
||||
AppSetNativeTranslations,
|
||||
AppRelaunch,
|
||||
|
||||
Reference in New Issue
Block a user