Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions PLANS.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ the durable truth after it changes. Git history is the archive.

- [[plans/windows-signpath.md]] — SignPath Foundation self-signed onboarding,
public signing policy, and production Windows release integration.
- [[plans/news-event-reading.md]] — Readiness candidate for existing Draft PR #1767: current dev integrated; source/filter persistence, RSS provenance/time handling and collected-country identities fixed. Frozen source b49e45eae passed the complete suite (7978/0/152), all 15 critical requirements, typechecks and builds; actual desktop/narrow/history/filter and new-report labels accepted. Original archive/human state preserved; 12-source collection and native five-minute preparation continue. #17 cleanup, 24-hour completion, broader semantic and final artifact/remote acceptance remain open. New source channels are deferred; no merge or release.

- [[plans/news-module-injection-research.md]] — Approved News Modules and RSSHub key work on Draft PR #1767; current remote acceptance is incomplete, no merge or release.
- [[plans/news-management-experiment.md]] — Local source-editing and shared RSSHub endpoint experiment, isolated user home, real collector/UI acceptance; no PR or publishing.

- [[plans/settings-machines-dialog.md]] — Move machine management into General / Machines and replace inline SSH setup with a reviewed dialog; Draft PR only.

- [[plans/review-updates-shared-plan.md]] — Share automatic/manual update review
Expand Down
9 changes: 5 additions & 4 deletions apps/desktop/src/activity-announcements.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { AgentActivitySignal } from './activity-projection.js'
import type { NotificationInput } from './notification-queue.js'
import type { ActivityContext } from './activity-policy.js'
function operationId(signal: AgentActivitySignal): string {
return signal.operationId ?? (signal.taskId ? `task:${signal.taskId}`
: signal.workspaceId && signal.resumeId ? `session:${signal.workspaceId}:${signal.resumeId}` : `event:${signal.revision}`)
Expand All @@ -10,7 +11,7 @@ export interface AnnouncementContext {
agent(signal: AgentActivitySignal): string
action(signal: AgentActivitySignal): NotificationInput['action']
t(key: string, values?: { agent?: string }): string
open(context: 'office' | 'inbox' | 'news'): void
open(context: ActivityContext): void
}
export class ActivityAnnouncements {
private announcedThrough: number | null = null
Expand Down Expand Up @@ -74,10 +75,10 @@ export class ActivityAnnouncements {
}
case 'news':
input = { status: 'info', title: signal.source ?? context.t('activityToast.newsSource'),
description: signal.detail, articleId: signal.newsItemId, image: signal.image,
group: `news:${(signal.source ?? '').trim().toLowerCase()}`, windowMs: 4_000,
description: signal.detail, articleId: signal.newsItemId, image: signal.image, newsStoryId: signal.storyId,
group: signal.storyId ? `news:story:${signal.storyId}` : `news:${(signal.source ?? '').trim().toLowerCase()}`, windowMs: 4_000,
revision: signal.revision, duration: 6_000,
action: { label: context.t('activityToast.viewNews'), onClick: () => context.open('news') },
action: { label: context.t('activityToast.viewNews'), onClick: () => context.open(signal.storyId ? `news:${signal.storyId}` : 'news') },
}
break
default:
Expand Down
15 changes: 15 additions & 0 deletions apps/desktop/src/activity-controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,21 @@ function setup() {
beforeEach(() => { vi.useFakeTimers(); vi.setSystemTime(new Date('2026-09-30T12:00:00Z')) })
afterEach(() => { vi.useRealTimers() })
describe('desktop Journal arbitration', () => {
it('routes one followed-event update to its exact News event and obeys the existing News preference', async () => {
const s = setup()
await s.page([])
await s.page([event(1, 'news.story.updated', { storyId: 'port-closure', revision: 2, title: 'Port update', developmentIds: ['reopening'] })])
const display = s.controller.snapshot()[0]
expect(display?.input.context).toBe('news:port-closure')
expect(s.controller.open(display.displayId, 'main')).toBe(true)
expect(s.open).toHaveBeenCalledWith('news:port-closure')
await s.page([event(1, 'news.story.updated', { storyId: 'port-closure', revision: 2, title: 'Port update', developmentIds: ['reopening'] })])
expect(s.controller.snapshot()).toEqual([])
s.controller.setPreferences({ ...structuredClone(defaults), events: { ...defaults.events, news: false } })
await s.page([event(2, 'news.story.updated', { storyId: 'port-closure', revision: 3, title: 'Port update', developmentIds: ['other'] })])
expect(s.controller.snapshot()).toEqual([])
s.controller.stop()
})
it('stops without querying a destroyed surface or restarting after late work', async () => {
let destroyed = false
let identity = 'project-a'
Expand Down
3 changes: 2 additions & 1 deletion apps/desktop/src/activity-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ const text = z.string().max(16_384).optional()
const payloadSchema = z.object({
workspaceId: text, resumeId: text, agent: text, sessionRecordId: text, taskId: text,
inboxEntryId: text, newsItemId: z.number().int().nonnegative().optional(), source: text,
storyId: z.string().regex(/^[a-z0-9][a-z0-9-]{0,79}$/).optional(), revision: z.number().int().positive().optional(), developmentIds: z.array(z.string().max(80)).max(100).optional(),
title: text, image: text, summary: text, error: text, reason: text, launchErrorCode: text,
message: text, originKind: z.string().optional(), testState: z.enum(['running', 'success', 'error']).optional(),
status: z.enum(['done', 'failed', 'interrupted', 'paused']).optional(),
Expand Down Expand Up @@ -57,7 +58,7 @@ export class ActivityController {
: this.surface.petVisible() && this.prefs.pet ? 'pet' : null)
if (!chosen || !this.identity) { close(); return }
// Functions remain in main. Only the safe context and display token cross IPC.
const context: ActivityContext = input.group?.startsWith('news:') ? 'news'
const context: ActivityContext = input.newsStoryId && /^[a-z0-9][a-z0-9-]{0,79}$/.test(input.newsStoryId) ? `news:${input.newsStoryId}` : input.group?.startsWith('news:') ? 'news'
: input.group?.startsWith('inbox:') ? 'inbox' : 'office'
const { action: _action, image: _image, onDismiss: _onDismiss, ...content } = input
let serialized: SerializedNotification = { ...content, duration: Number.isFinite(input.duration) ? input.duration : null, context }
Expand Down
4 changes: 4 additions & 0 deletions apps/desktop/src/activity-journal-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export type AgentRuntimeEventType =
| 'dev.sonner_test'
| 'inbox.received'
| 'news.ingested'
| 'news.story.updated'

export type AgentRuntimeSurface = 'terminal' | 'webpi' | 'headless'

Expand Down Expand Up @@ -60,6 +61,9 @@ export interface AgentRuntimePayload {
summary?: string
documentCount?: number
newsItemId?: number
storyId?: string
revision?: number
developmentIds?: string[]
dedupKey?: string
title?: string
source?: string
Expand Down
4 changes: 2 additions & 2 deletions apps/desktop/src/activity-policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ export function allowsActivity(prefs: ActivityPreferences, signal: AgentActivity
if (!kind || !prefs.enabled || prefs.pausedUntil > now) return false
return prefs.events[kind]
}
export type ActivityContext = 'office' | 'inbox' | 'news'
export type ActivityContext = 'office' | 'inbox' | 'news' | `news:${string}`
export type SerializedNotification = Omit<NotificationInput, 'action' | 'duration' | 'onDismiss'> & {
duration: number | null
context: ActivityContext
}
export function briefNotification(input: SerializedNotification): SerializedNotification {
const title = input.status === 'error' ? 'Work failed' : input.status === 'warning' ? 'Action needed'
: input.context === 'news' ? 'News updated' : input.context === 'inbox' ? 'Report ready'
: input.context === 'news' || input.context.startsWith('news:') ? 'News updated' : input.context === 'inbox' ? 'Report ready'
: input.status === 'running' ? 'Work in progress' : input.status === 'success' ? 'Work completed' : 'Activity updated'
// No names, raw details, article images or source labels reach the pet in brief mode.
return { id: input.id, status: input.status, title, duration: input.duration, context: input.context,
Expand Down
8 changes: 6 additions & 2 deletions apps/desktop/src/activity-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ export interface AgentActivitySignal {
readonly taskId?: string
readonly inboxEntryId?: string
readonly newsItemId?: number
readonly storyId?: string
readonly source?: string
readonly image?: string
readonly operationId?: string
Expand Down Expand Up @@ -221,12 +222,15 @@ export const newsActivityFilter: GlobalActivityFilter = {
id: 'product-news',
project({ runtimeEvents }, now) {
return runtimeEvents.flatMap((event): AgentActivitySignal[] => {
if (event.type !== 'news.ingested' || event.payload.newsItemId === undefined) return []
if (event.type !== 'news.ingested' && event.type !== 'news.story.updated') return []
if (event.type === 'news.ingested' && event.payload.newsItemId === undefined) return []
if (event.type === 'news.story.updated' && (!event.payload.storyId || !/^[a-z0-9][a-z0-9-]{0,79}$/.test(event.payload.storyId))) return []
if (Math.max(0, now - event.ts) > RECENT_SIGNAL_MS) return []
return [{
id: `news:${event.payload.newsItemId}`,
id: event.type === 'news.story.updated' ? `news:story:${event.payload.storyId}:${event.payload.revision}` : `news:${event.payload.newsItemId}`,
kind: 'news',
newsItemId: event.payload.newsItemId,
...(event.type === 'news.story.updated' ? { storyId: event.payload.storyId } : {}),
source: event.payload.source,
detail: event.payload.title,
image: event.payload.image,
Expand Down
223 changes: 223 additions & 0 deletions apps/desktop/src/alice-ipc-shutdown.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
import { EventEmitter, once } from 'node:events'
import type { ChildProcess, spawn as Spawn } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'

const previousHome = process.env.OPENALICE_HOME
const previousRuntimeProfile = process.env.OPENALICE_RUNTIME_PROFILE

const state = vi.hoisted(() => {
const listeners = new Map<string, (...args: unknown[]) => void>()
return {
child: null as ChildProcess | null,
home: '',
spawned: () => {},
listeners,
app: {
isPackaged: false,
whenReady: () => Promise.resolve(),
getPath: (): string => state.home,
commandLine: { removeSwitch: vi.fn(), appendSwitch: vi.fn() },
disableHardwareAcceleration: vi.fn(),
setPath: vi.fn(),
on: vi.fn((name: string, listener: (...args: unknown[]) => void) => listeners.set(name, listener)),
exit: vi.fn(),
quit: vi.fn(),
},
taskkill: vi.fn(),
}
})

vi.mock('electron', () => ({
app: state.app,
protocol: { registerSchemesAsPrivileged: vi.fn(), handle: vi.fn() },
session: { defaultSession: { resolveProxy: async () => '' } },
dialog: { showErrorBox: vi.fn() },
ipcMain: { handle: vi.fn(), on: vi.fn() },
BrowserWindow: vi.fn(), Menu: { setApplicationMenu: vi.fn() },
nativeImage: {}, Notification: vi.fn(), shell: {}, Tray: vi.fn(),
}))
vi.mock('electron-updater', () => ({ default: { autoUpdater: {} } }))
vi.mock('./web-relay.js', () => ({
CLI_VERSION: 'test', UpdateControlService: class {}, ClientUpdateService: class {},
WebRelay: class {}, readStartupTarget: async () => null, writeStartupTarget: async () => {},
resolveLocalStartupHome: async () => null, inspectLocalMachine: async () => ({}),
}))
vi.mock('node:child_process', async (importOriginal) => ({
...await importOriginal<Record<string, unknown>>(),
spawn: vi.fn(() => {
queueMicrotask(state.spawned)
return state.child
}),
spawnSync: state.taskkill,
}))
vi.mock('@traderalice/guardian-runtime', async (importOriginal) => ({
...await importOriginal<Record<string, unknown>>(),
acquireGuardianRuntime: async () => ({ release: async () => {} }),
resolveGuardianTradingMode: async () => ({ mode: 'lite', source: 'env', envLocked: true }),
takeoverRequested: () => false,
proxyEnvFromRules: () => ({}),
}))
vi.mock('./desktop-diagnostics.js', () => ({
DesktopDiagnostics: class { path = 'test.log'; write() {} },
BoundedTextTail: class { append() {}; text() { return '' } },
conciseDiagnosticTail: () => '',
}))
vi.mock('./data-home-desktop.js', () => ({
resolveDesktopDataHome: async () => ({
home: state.home, source: 'explicit', preferences: {},
selectedDefault: false, selectionLock: 'explicit',
}),
createDesktopDataHomeController: () => ({}), dataHomeErrorDetail: String,
}))
vi.mock('./existing-owner-startup.js', () => ({
existingOwnerSmokeMode: () => false,
resolveExistingOwnerStartup: async () => ({ action: 'continue', takeover: false }),
}))
vi.mock('./update-attempt.js', () => ({ inspectPreviousUpdateAttempt: async () => ({ kind: 'none' }) }))
vi.mock('./managed-runtime.js', () => ({ resolveManagedRuntimeEnv: () => ({}) }))
vi.mock('./probe-port.js', () => ({ probeFreePort: async () => 47334 }))
vi.mock('./ipc.js', () => ({
registerOpenAliceIpc: () => {}, handleOpenAliceIpcMessage: () => false,
cancelOpenAliceWebRequests: () => {},
fetchAliceWebRequest: () => new Promise(() => {}),
}))
vi.mock('./app-exit.js', () => ({
exitDesktopProcess: (code: number, options: { appExit: (code: number) => void }) => options.appExit(code),
}))

class AliceChild extends EventEmitter {
pid = 12345
connected = true
exitCode: number | null = null
signalCode: NodeJS.Signals | null = null
stderr = new EventEmitter()
signals: NodeJS.Signals[] = []
send = vi.fn((_message: unknown, callback: (error?: Error) => void) => {
queueMicrotask(() => callback(new Error('IPC channel closed')))
return true
})
kill(signal: NodeJS.Signals) {
this.signals.push(signal)
if (signal === 'SIGKILL') this.finishForced()
return true
}
finishForced() {
this.signalCode = 'SIGKILL'
this.connected = false
this.emit('exit', null, 'SIGKILL')
}
}

beforeEach(() => {
state.home = mkdtempSync(join(tmpdir(), 'desktop-ipc-shutdown-'))
process.env.OPENALICE_HOME = state.home
})

afterEach(() => {
vi.useRealTimers()
state.listeners.clear()
state.child = null
state.spawned = () => {}
state.taskkill.mockReset()
state.app.exit.mockReset()
if (previousHome === undefined) delete process.env.OPENALICE_HOME
else process.env.OPENALICE_HOME = previousHome
if (previousRuntimeProfile === undefined) delete process.env.OPENALICE_RUNTIME_PROFILE
else process.env.OPENALICE_RUNTIME_PROFILE = previousRuntimeProfile
vi.resetModules()
rmSync(state.home, { recursive: true, force: true })
})

async function launch(child: ChildProcess) {
state.child = child
const spawned = new Promise<void>((resolve) => { state.spawned = resolve })
// Loading desktop main is startup work, separate from child shutdown deadlines.
await import('./main.js')
await spawned
}

describe('desktop main Alice IPC shutdown', () => {
it('lets its IPC child finish asynchronous cleanup and exit naturally on before-quit', async () => {
const { spawn: realSpawn } = await vi.importActual<{ spawn: typeof Spawn }>('node:child_process')
const marker = join(state.home, 'cleanup.marker')
const program = `
const { writeFileSync } = require('node:fs')
process.on('SIGTERM', () => {})
const keepAlive = setInterval(() => {}, 1000)
process.on('message', async (message) => {
if (message?.type !== 'openalice:shutdown') return
await new Promise((resolve) => setTimeout(resolve, 20))
writeFileSync(process.argv[1], 'cleaned')
clearInterval(keepAlive)
process.disconnect()
})
process.send('ready')
`
const child = realSpawn(process.execPath, ['-e', program, marker], {
stdio: ['ignore', 'ignore', 'pipe', 'ipc'],
})
const closed = once(child, 'close', { signal: AbortSignal.timeout(20_000) })
void closed.catch(() => {})
try {
const [ready] = await once(child, 'message', { signal: AbortSignal.timeout(3000) })
expect(ready).toBe('ready')
await launch(child)
const exited = once(child, 'exit', { signal: AbortSignal.timeout(3000) })
const preventDefault = vi.fn()
state.listeners.get('before-quit')?.({ preventDefault })
expect(preventDefault).toHaveBeenCalledOnce()
expect(await exited).toEqual([0, null])
await closed
expect(readFileSync(marker, 'utf8')).toBe('cleaned')
expect(child.signalCode).toBeNull()
expect(state.taskkill).not.toHaveBeenCalled()
await vi.waitFor(() => expect(state.app.exit).toHaveBeenCalledWith(0))
} finally {
if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL')
await closed
}
}, 30_000)

for (const failure of ['disconnected', 'send callback error'] as const) {
it(`keeps Alice alive until the 10-second force deadline after ${failure}`, async () => {
const child = new AliceChild()
child.connected = failure !== 'disconnected'
state.taskkill.mockImplementation(() => { child.finishForced(); return { status: 0 } })
await launch(child as unknown as ChildProcess)
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
try {
const preventDefault = vi.fn()
state.listeners.get('before-quit')?.({ preventDefault })
expect(preventDefault).toHaveBeenCalledOnce()
await vi.advanceTimersByTimeAsync(0)
expect(child.exitCode).toBeNull()
expect(child.signalCode).toBeNull()
expect(state.taskkill).not.toHaveBeenCalled()
expect(child.signals).not.toContain('SIGKILL')
expect(state.app.exit).not.toHaveBeenCalled()

await vi.advanceTimersByTimeAsync(9_999)
expect(child.exitCode).toBeNull()
expect(child.signalCode).toBeNull()
expect(state.taskkill).not.toHaveBeenCalled()
expect(child.signals).not.toContain('SIGKILL')
expect(state.app.exit).not.toHaveBeenCalled()

await vi.advanceTimersByTimeAsync(1)
expect(child.signalCode).toBe('SIGKILL')
if (process.platform === 'win32') {
expect(child.signals).toEqual([])
} else {
expect(child.signals).toEqual(['SIGTERM', 'SIGKILL'])
}
expect(state.app.exit).toHaveBeenCalledWith(0)
} finally {
vi.useRealTimers()
if (child.exitCode === null && child.signalCode === null) child.finishForced()
}
}, 30_000)
}
})
Loading
Loading