Skip to content

Commit 118b2af

Browse files
authored
fix(desktop): recover from bad settings files and stuck or looping updates (#10666)
1 parent f3ddb5c commit 118b2af

15 files changed

Lines changed: 909 additions & 96 deletions

‎apps/desktop/e2e/fixtures/updater.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { homedir } from 'node:os'
33
import { join, relative } from 'node:path'
44
import type { DesktopUpdateState } from '@sim/desktop-bridge'
55
import { app, BrowserWindow, autoUpdater as nativeUpdater, net } from 'electron'
6-
import { MacUpdater } from 'electron-updater'
6+
import { CancellationToken, MacUpdater } from 'electron-updater'
77
import { countWindowsWithUnsavedChanges, describeInFlightWork } from '@/main/in-flight-work'
88
import { initUpdater } from '@/main/updater'
99

@@ -95,8 +95,8 @@ void app.whenReady().then(async () => {
9595
getWindow: () => null,
9696
events: { filePath: '', record: (name, data) => events.push({ name, data }) },
9797
appOrigin: () => origin,
98-
loadAutoUpdater: () => updater,
99-
canSelfUpdate: async () => true,
98+
loadElectronUpdater: () => ({ autoUpdater: updater, CancellationToken }),
99+
canSelfUpdate: async () => 'capable',
100100
probeOriginFeed: async () => false,
101101
installStatePath: join(directory, 'update-install.json'),
102102
describeInFlightWork: async () =>

‎apps/desktop/src/main/atomic-json-file.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
import {
22
closeSync,
33
fstatSync,
4+
fsyncSync,
45
mkdirSync,
56
openSync,
67
readSync,
78
renameSync,
89
writeFileSync,
910
} from 'node:fs'
10-
import { mkdir, open, rename, unlink, writeFile } from 'node:fs/promises'
11+
import { mkdir, open, rename, unlink } from 'node:fs/promises'
1112
import { dirname } from 'node:path'
1213

1314
/** Owner-only, matching every store that keeps user data in userData. */
@@ -87,6 +88,10 @@ function temporaryPathFor(filePath: string): string {
8788
/**
8889
* Crash-safe JSON writes for the small encrypted stores in userData.
8990
*
91+
* The temp file is synced before the rename publishes it: without that, a
92+
* power loss can leave the renamed path pointing at a file whose contents
93+
* never reached disk, which reads back as zero bytes.
94+
*
9095
* Every one of them (local-filesystem grants, the credential vault, the site
9196
* directory) had written this same temp-file-then-rename sequence by hand, and
9297
* they had already drifted: two scoped the temporary file by pid and the third
@@ -96,7 +101,13 @@ function temporaryPathFor(filePath: string): string {
96101
export async function writeJsonFileAtomically(filePath: string, value: unknown): Promise<void> {
97102
await mkdir(dirname(filePath), { recursive: true })
98103
const temporaryPath = temporaryPathFor(filePath)
99-
await writeFile(temporaryPath, JSON.stringify(value), { mode: FILE_MODE })
104+
const handle = await open(temporaryPath, 'w', FILE_MODE)
105+
try {
106+
await handle.writeFile(JSON.stringify(value))
107+
await handle.sync()
108+
} finally {
109+
await handle.close()
110+
}
100111
await rename(temporaryPath, filePath)
101112
}
102113

@@ -114,7 +125,13 @@ export function writeJsonFileAtomicallySync(
114125
): void {
115126
mkdirSync(dirname(filePath), { recursive: true })
116127
const temporaryPath = temporaryPathFor(filePath)
117-
writeFileSync(temporaryPath, JSON.stringify(value, null, indent), { mode: FILE_MODE })
128+
const descriptor = openSync(temporaryPath, 'w', FILE_MODE)
129+
try {
130+
writeFileSync(descriptor, JSON.stringify(value, null, indent))
131+
fsyncSync(descriptor)
132+
} finally {
133+
closeSync(descriptor)
134+
}
118135
renameSync(temporaryPath, filePath)
119136
}
120137

‎apps/desktop/src/main/computer-use/service.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,6 +1080,15 @@ describe('native computer use authority and lifecycle', () => {
10801080
expect(service.listAppPermissions()).toEqual([])
10811081
})
10821082

1083+
it('lets a server repair clear grants while the rejected settings file cannot be written', async () => {
1084+
const { service, config, state } = setup()
1085+
await state()
1086+
vi.spyOn(config, 'flush').mockReturnValue(false)
1087+
expect(() => service.reset({ settingsPersistence: 'server-repair' })).not.toThrow()
1088+
expect(service.isEnabled()).toBe(false)
1089+
expect(service.listAppPermissions()).toEqual([])
1090+
})
1091+
10831092
it('does not operate an app if persistent approval cannot be saved', async () => {
10841093
const { config, state, native, service } = setup()
10851094
vi.spyOn(config, 'flush').mockReturnValue(false)

‎apps/desktop/src/main/computer-use/service.ts‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -396,13 +396,22 @@ export class ComputerUseService {
396396
this.snapshots.clear()
397397
}
398398

399-
reset(): void {
399+
/**
400+
* `server-repair` is for a server change, whose own settings write follows
401+
* at once and refuses the change if it fails, so a settings file that cannot
402+
* be written yet (a rejected one) does not block the change that repairs it.
403+
*/
404+
reset(
405+
options: { settingsPersistence: 'required' | 'server-repair' } = {
406+
settingsPersistence: 'required',
407+
}
408+
): void {
400409
this.cancel()
401410
this.appNames.clear()
402411
this.deps.config.set('computerUseEnabled', false)
403412
this.deps.config.set('computerUseAskForApps', false)
404413
this.deps.config.set('computerUseAllowedApps', [])
405-
if (!this.deps.config.flush())
414+
if (!this.deps.config.flush() && options.settingsPersistence === 'required')
406415
throw new Error('Could not clear saved Computer Use permissions.')
407416
}
408417

‎apps/desktop/src/main/config.test.ts‎

Lines changed: 77 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
1+
import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
22
import { tmpdir } from 'node:os'
33
import { dirname, join } from 'node:path'
44
import { describe, expect, it } from 'vitest'
@@ -90,6 +90,82 @@ describe('createConfigStore', () => {
9090
expect(readFileSync(filePath, 'utf8')).not.toContain('private.example')
9191
})
9292

93+
it('names why a rejected file was not used and keeps a copy when repairing it', () => {
94+
for (const [contents, problem] of [
95+
['{ "origin": "https://sim.example.com", }', 'unparseable'],
96+
['[]', 'unparseable'],
97+
['{ "origin": null }', 'unparseable'],
98+
['{ "origin": "http://192.168.1.20:3000" }', 'invalid-origin'],
99+
] as const) {
100+
const filePath = tempSettingsPath()
101+
writeFileSync(filePath, contents)
102+
const store = createConfigStore(filePath, {})
103+
expect(store.getLoadProblem()?.kind).toBe(problem)
104+
105+
expect(store.setOrigin(DEFAULT_ORIGIN).ok).toBe(true)
106+
expect(store.getLoadProblem()).toBeNull()
107+
const backups = readdirSync(dirname(filePath)).filter((name) =>
108+
name.startsWith('settings.json.bak-')
109+
)
110+
expect(backups).toHaveLength(1)
111+
expect(readFileSync(join(dirname(filePath), backups[0]), 'utf8')).toBe(contents)
112+
}
113+
})
114+
115+
it('reports no problem for a valid or missing file and keeps no copy when changing servers', () => {
116+
const filePath = tempSettingsPath()
117+
expect(createConfigStore(filePath, {}).getLoadProblem()).toBeNull()
118+
writeFileSync(filePath, JSON.stringify({ origin: 'https://sim.example.com' }))
119+
const store = createConfigStore(filePath, {})
120+
expect(store.getLoadProblem()).toBeNull()
121+
expect(store.setOrigin('https://other.example.com').ok).toBe(true)
122+
expect(readdirSync(dirname(filePath))).toEqual(['settings.json'])
123+
})
124+
125+
it('retries a failed write instead of dropping every later change', () => {
126+
const filePath = tempSettingsPath()
127+
const parent = dirname(filePath)
128+
const store = createConfigStore(filePath, {})
129+
rmSync(parent, { recursive: true })
130+
writeFileSync(parent, 'not a directory')
131+
132+
try {
133+
store.set('zoomLevel', 2)
134+
expect(store.flush()).toBe(false)
135+
136+
rmSync(parent)
137+
mkdirSync(parent)
138+
store.set('trayEnabled', false)
139+
expect(store.flush()).toBe(true)
140+
expect(JSON.parse(readFileSync(filePath, 'utf8'))).toMatchObject({
141+
zoomLevel: 2,
142+
trayEnabled: false,
143+
})
144+
} finally {
145+
rmSync(parent, { recursive: true, force: true })
146+
}
147+
})
148+
149+
it('reports a re-confirmed origin as saved only once pending changes reach disk', () => {
150+
const filePath = tempSettingsPath()
151+
const parent = dirname(filePath)
152+
const store = createConfigStore(filePath, {})
153+
rmSync(parent, { recursive: true })
154+
writeFileSync(parent, 'not a directory')
155+
156+
try {
157+
store.set('computerUseAllowedApps', [])
158+
expect(store.setOrigin(DEFAULT_ORIGIN).ok).toBe(false)
159+
160+
rmSync(parent)
161+
mkdirSync(parent)
162+
expect(store.setOrigin(DEFAULT_ORIGIN).ok).toBe(true)
163+
expect(JSON.parse(readFileSync(filePath, 'utf8')).computerUseAllowedApps).toEqual([])
164+
} finally {
165+
rmSync(parent, { recursive: true, force: true })
166+
}
167+
})
168+
93169
it('keeps the active origin unchanged when its immediate write fails', () => {
94170
const filePath = tempSettingsPath()
95171
const parent = dirname(filePath)

0 commit comments

Comments
 (0)