Skip to content
Merged
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
6 changes: 3 additions & 3 deletions apps/desktop/e2e/fixtures/updater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { homedir } from 'node:os'
import { join, relative } from 'node:path'
import type { DesktopUpdateState } from '@sim/desktop-bridge'
import { app, BrowserWindow, autoUpdater as nativeUpdater, net } from 'electron'
import { MacUpdater } from 'electron-updater'
import { CancellationToken, MacUpdater } from 'electron-updater'
import { countWindowsWithUnsavedChanges, describeInFlightWork } from '@/main/in-flight-work'
import { initUpdater } from '@/main/updater'

Expand Down Expand Up @@ -95,8 +95,8 @@ void app.whenReady().then(async () => {
getWindow: () => null,
events: { filePath: '', record: (name, data) => events.push({ name, data }) },
appOrigin: () => origin,
loadAutoUpdater: () => updater,
canSelfUpdate: async () => true,
loadElectronUpdater: () => ({ autoUpdater: updater, CancellationToken }),
canSelfUpdate: async () => 'capable',
probeOriginFeed: async () => false,
installStatePath: join(directory, 'update-install.json'),
describeInFlightWork: async () =>
Expand Down
23 changes: 20 additions & 3 deletions apps/desktop/src/main/atomic-json-file.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import {
closeSync,
fstatSync,
fsyncSync,
mkdirSync,
openSync,
readSync,
renameSync,
writeFileSync,
} from 'node:fs'
import { mkdir, open, rename, unlink, writeFile } from 'node:fs/promises'
import { mkdir, open, rename, unlink } from 'node:fs/promises'
import { dirname } from 'node:path'

/** Owner-only, matching every store that keeps user data in userData. */
Expand Down Expand Up @@ -87,6 +88,10 @@ function temporaryPathFor(filePath: string): string {
/**
* Crash-safe JSON writes for the small encrypted stores in userData.
*
* The temp file is synced before the rename publishes it: without that, a
* power loss can leave the renamed path pointing at a file whose contents
* never reached disk, which reads back as zero bytes.
*
* Every one of them (local-filesystem grants, the credential vault, the site
* directory) had written this same temp-file-then-rename sequence by hand, and
* they had already drifted: two scoped the temporary file by pid and the third
Expand All @@ -96,7 +101,13 @@ function temporaryPathFor(filePath: string): string {
export async function writeJsonFileAtomically(filePath: string, value: unknown): Promise<void> {
await mkdir(dirname(filePath), { recursive: true })
const temporaryPath = temporaryPathFor(filePath)
await writeFile(temporaryPath, JSON.stringify(value), { mode: FILE_MODE })
const handle = await open(temporaryPath, 'w', FILE_MODE)
try {
await handle.writeFile(JSON.stringify(value))
await handle.sync()
Comment thread
waleedlatif1 marked this conversation as resolved.
Resolved
} finally {
await handle.close()
}
await rename(temporaryPath, filePath)
}

Expand All @@ -114,7 +125,13 @@ export function writeJsonFileAtomicallySync(
): void {
mkdirSync(dirname(filePath), { recursive: true })
const temporaryPath = temporaryPathFor(filePath)
writeFileSync(temporaryPath, JSON.stringify(value, null, indent), { mode: FILE_MODE })
const descriptor = openSync(temporaryPath, 'w', FILE_MODE)
try {
writeFileSync(descriptor, JSON.stringify(value, null, indent))
fsyncSync(descriptor)
} finally {
closeSync(descriptor)
}
renameSync(temporaryPath, filePath)
}

Expand Down
9 changes: 9 additions & 0 deletions apps/desktop/src/main/computer-use/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1080,6 +1080,15 @@ describe('native computer use authority and lifecycle', () => {
expect(service.listAppPermissions()).toEqual([])
})

it('lets a server repair clear grants while the rejected settings file cannot be written', async () => {
const { service, config, state } = setup()
await state()
vi.spyOn(config, 'flush').mockReturnValue(false)
expect(() => service.reset({ settingsPersistence: 'server-repair' })).not.toThrow()
expect(service.isEnabled()).toBe(false)
expect(service.listAppPermissions()).toEqual([])
})

it('does not operate an app if persistent approval cannot be saved', async () => {
const { config, state, native, service } = setup()
vi.spyOn(config, 'flush').mockReturnValue(false)
Expand Down
13 changes: 11 additions & 2 deletions apps/desktop/src/main/computer-use/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -396,13 +396,22 @@ export class ComputerUseService {
this.snapshots.clear()
}

reset(): void {
/**
* `server-repair` is for a server change, whose own settings write follows
* at once and refuses the change if it fails, so a settings file that cannot
* be written yet (a rejected one) does not block the change that repairs it.
*/
reset(
options: { settingsPersistence: 'required' | 'server-repair' } = {
settingsPersistence: 'required',
}
): void {
this.cancel()
this.appNames.clear()
this.deps.config.set('computerUseEnabled', false)
this.deps.config.set('computerUseAskForApps', false)
this.deps.config.set('computerUseAllowedApps', [])
if (!this.deps.config.flush())
if (!this.deps.config.flush() && options.settingsPersistence === 'required')
throw new Error('Could not clear saved Computer Use permissions.')
}

Expand Down
78 changes: 77 additions & 1 deletion apps/desktop/src/main/config.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { dirname, join } from 'node:path'
import { describe, expect, it } from 'vitest'
Expand Down Expand Up @@ -90,6 +90,82 @@ describe('createConfigStore', () => {
expect(readFileSync(filePath, 'utf8')).not.toContain('private.example')
})

it('names why a rejected file was not used and keeps a copy when repairing it', () => {
for (const [contents, problem] of [
['{ "origin": "https://sim.example.com", }', 'unparseable'],
['[]', 'unparseable'],
['{ "origin": null }', 'unparseable'],
['{ "origin": "http://192.168.1.20:3000" }', 'invalid-origin'],
] as const) {
const filePath = tempSettingsPath()
writeFileSync(filePath, contents)
const store = createConfigStore(filePath, {})
expect(store.getLoadProblem()?.kind).toBe(problem)

expect(store.setOrigin(DEFAULT_ORIGIN).ok).toBe(true)
expect(store.getLoadProblem()).toBeNull()
const backups = readdirSync(dirname(filePath)).filter((name) =>
name.startsWith('settings.json.bak-')
)
expect(backups).toHaveLength(1)
expect(readFileSync(join(dirname(filePath), backups[0]), 'utf8')).toBe(contents)
}
})

it('reports no problem for a valid or missing file and keeps no copy when changing servers', () => {
const filePath = tempSettingsPath()
expect(createConfigStore(filePath, {}).getLoadProblem()).toBeNull()
writeFileSync(filePath, JSON.stringify({ origin: 'https://sim.example.com' }))
const store = createConfigStore(filePath, {})
expect(store.getLoadProblem()).toBeNull()
expect(store.setOrigin('https://other.example.com').ok).toBe(true)
expect(readdirSync(dirname(filePath))).toEqual(['settings.json'])
})

it('retries a failed write instead of dropping every later change', () => {
const filePath = tempSettingsPath()
const parent = dirname(filePath)
const store = createConfigStore(filePath, {})
rmSync(parent, { recursive: true })
writeFileSync(parent, 'not a directory')

try {
store.set('zoomLevel', 2)
expect(store.flush()).toBe(false)

rmSync(parent)
mkdirSync(parent)
store.set('trayEnabled', false)
expect(store.flush()).toBe(true)
expect(JSON.parse(readFileSync(filePath, 'utf8'))).toMatchObject({
zoomLevel: 2,
trayEnabled: false,
})
} finally {
rmSync(parent, { recursive: true, force: true })
}
})

it('reports a re-confirmed origin as saved only once pending changes reach disk', () => {
const filePath = tempSettingsPath()
const parent = dirname(filePath)
const store = createConfigStore(filePath, {})
rmSync(parent, { recursive: true })
writeFileSync(parent, 'not a directory')

try {
store.set('computerUseAllowedApps', [])
expect(store.setOrigin(DEFAULT_ORIGIN).ok).toBe(false)

rmSync(parent)
mkdirSync(parent)
expect(store.setOrigin(DEFAULT_ORIGIN).ok).toBe(true)
expect(JSON.parse(readFileSync(filePath, 'utf8')).computerUseAllowedApps).toEqual([])
} finally {
rmSync(parent, { recursive: true, force: true })
}
})

it('keeps the active origin unchanged when its immediate write fails', () => {
const filePath = tempSettingsPath()
const parent = dirname(filePath)
Expand Down
Loading
Loading