Skip to content

Commit cfb7fe5

Browse files
merge(Zoo-Code-Org#1918 u148): refresh fws/u7-tool-wiring onto the trunk tip f98fcf7
One collision, in src/utils/__tests__/jsonFileRecovery.test.ts, at the import of ../jsonFileRecovery. The three stages of that path were base 1bd90d8, trunk ce33e73 and head c2dc472. Hunk 1, the only conflicted hunk: the trunk side was kept. Its spelling import { recoverInterruptedReplacement, deleteJsonFile, recoverMissingJsonFile } was taken as-is, and this branch's own import of LockKeyWalkIncompleteError and resolveLockKey from services/file-safety/safeWriteText was re-landed below it, because the three delete-side rows this lane added assert the fail-closed key resolution that the merged module still has. The branch's spelling of the shared import line, which named two exports rather than three, was dropped; nothing else of either side was dropped. The trunk version of the file is a verbatim subsequence of the result, and every line of the branch version survives except that one import line. src/utils/jsonFileRecovery.ts auto-merged: the branch's key resolution in deleteJsonFile and the trunk's AmbiguousBackupRecencyError tie refusal in recoverInterruptedReplacement sit in disjoint regions, 45 added and 2 removed lines against the pre-refresh head. No suppression added and no suppression count raised.
2 parents 9b957e9 + f98fcf7 commit cfb7fe5

114 files changed

Lines changed: 1981 additions & 760 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎.roo/rules-translate/001-general-rules.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,10 @@
3030
# 4. WEBVIEW UI LOCALIZATION (webview-ui/src/)
3131

3232
- Located in webview-ui/src/i18n/locales/
33-
- Uses standard React i18next patterns with the useTranslation hook
33+
- Use `useAppTranslation` from `@src/i18n/TranslationContext`, not react-i18next's `useTranslation` (ESLint enforces this). It returns `{ t, language }`; switching languages belongs to the provider, so the i18next instance is not exposed:
34+
- Always write fully qualified keys (`t("chat:about")`)
35+
- Always pass that `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
36+
- Never use the global `t` from `i18next` (`i18next.t`); memoized output would keep showing the previous language after a switch (ESLint enforces this). Pass `t` (and `language` for dates) to helpers instead, as `utils/format.ts` and `utils/validate.ts` do
3437
- All user interface strings should be internationalized
3538
- Always use the Trans component with named components for text with embedded components
3639

@@ -40,6 +43,7 @@
4043

4144
```
4245
<Trans
46+
t={t}
4347
i18nKey="welcome:telemetry.changeSettings"
4448
components={{
4549
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />

‎.roo/skills/roo-translation/SKILL.md‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,10 @@ This guidance file is loaded at runtime and should be consulted for the latest b
7070
## WebView UI Localization (webview-ui/src/)
7171

7272
- Located in `webview-ui/src/i18n/locales/`
73-
- Uses standard React i18next patterns with the `useTranslation` hook
73+
- Use `useAppTranslation` from `@src/i18n/TranslationContext`, not react-i18next's `useTranslation` (ESLint enforces this). It returns `{ t, language }`; switching languages belongs to the provider, so the i18next instance is not exposed:
74+
- Always write fully qualified keys (`t("chat:about")`)
75+
- Always pass that `t` to `Trans` (`<Trans t={t} i18nKey="..." />`); `Trans` does not follow language changes on its own (ESLint enforces this)
76+
- Never use the global `t` from `i18next` (`i18next.t`); memoized output would keep showing the previous language after a switch (ESLint enforces this). Pass `t` (and `language` for dates) to helpers instead, as `utils/format.ts` and `utils/validate.ts` do
7477
- All user interface strings should be internationalized
7578
- Always use the `Trans` component with named components for text with embedded components
7679

@@ -86,6 +89,7 @@ React component usage:
8689

8790
```tsx
8891
<Trans
92+
t={t}
8993
i18nKey="welcome:telemetry.changeSettings"
9094
components={{
9195
settingsLink: <VSCodeLink href="#" onClick={handleOpenSettings} />,
Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
// Guards that keep translated output in step with a language switch. Built-in no-restricted-syntax only.
2+
// Translations must come from the component's `t` (webview-ui's `useAppTranslation`), which changes identity
3+
// on a language switch; the global instance's `t` gives React (and React Compiler caches) nothing to
4+
// invalidate on, so memoized output would keep the previous language.
5+
6+
// Selectors cannot follow bindings, so the instance is recognised by name: a default import or
7+
// `useTranslation().i18n` held as `i18n`/`i18next`. The aliasing selectors below keep it under those names.
8+
// Passing the instance as an argument and reading `.t` from the parameter is not caught.
9+
const i18nInstanceName = "/^(i18n|i18next)$/"
10+
const i18nInstance = `:matches([name=${i18nInstanceName}], MemberExpression[property.name=${i18nInstanceName}])`
11+
12+
// i18next itself and modules that re-export its instance as their default (webview-ui's i18n/setup).
13+
const i18nInstanceSource = "/^(i18next|(.*\\/)?i18n\\/setup|\\.\\.?\\/setup)$/"
14+
15+
const globalTMessage = "Use t from useAppTranslation so memoized output follows language changes."
16+
const aliasMessage =
17+
"Keep the i18next instance named i18n or i18next: the global-t check recognises it by name, so an alias hides i18n.t."
18+
19+
export const i18nLanguageSwitchSelectors = [
20+
{
21+
// Global t read off the instance: i18next.t(...), i18n?.t(...), i18next["t"], useTranslation().i18n.t.
22+
selector: `MemberExpression:matches([property.name='t'][computed=false], [property.value='t']):has(> ${i18nInstance}.object)`,
23+
message: globalTMessage,
24+
},
25+
{
26+
// Global t destructured from the instance: const { t } = i18next, const { t: translate } = i18n.
27+
// Other properties stay allowed: const { language } = i18next.
28+
selector: `VariableDeclarator:has(> ${i18nInstance}.init) > ObjectPattern > Property[key.name='t']`,
29+
message: globalTMessage,
30+
},
31+
{
32+
// Default import under another name: import lang from "i18next", import { default as lang } from "@/i18n/setup".
33+
// Named imports such as initReactI18next or `type TFunction` are other specifiers and are not matched.
34+
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > :matches(ImportDefaultSpecifier, ImportSpecifier[imported.name='default']):not([local.name=${i18nInstanceName}])`,
35+
message: aliasMessage,
36+
},
37+
{
38+
// Namespace import: import * as lang from "i18next" exposes the instance's t as lang.t whatever lang is called.
39+
selector: `ImportDeclaration[source.value=${i18nInstanceSource}] > ImportNamespaceSpecifier`,
40+
message: aliasMessage,
41+
},
42+
{
43+
// Re-export under another name: export { default as lang } from "i18next" lets importers alias it unseen.
44+
selector: `ExportNamedDeclaration[source.value=${i18nInstanceSource}] > ExportSpecifier[local.name='default']:not([exported.name=${i18nInstanceName}])`,
45+
message: aliasMessage,
46+
},
47+
{
48+
// Variable alias: const lang = i18next, const lang = useTranslation().i18n.
49+
// Keeping the name is fine (const i18n = useTranslation().i18n); calls such as i18next.createInstance() are not
50+
// the instance itself and are not matched.
51+
selector: `VariableDeclarator[id.type='Identifier']:not([id.name=${i18nInstanceName}]):has(> ${i18nInstance}.init)`,
52+
message: aliasMessage,
53+
},
54+
{
55+
// Assignment alias to an existing variable: lang = i18n.
56+
selector: `AssignmentExpression:not([left.name=${i18nInstanceName}]):has(> ${i18nInstance}.right)`,
57+
message: aliasMessage,
58+
},
59+
{
60+
// Destructuring rename, in declarations and parameters: const { i18n: lang } = useTranslation(),
61+
// ({ i18n: lang }) => ..., and a nested pattern such as const { i18n: { t } } = useTranslation().
62+
// The shorthand const { i18n } = useTranslation() keeps the name and is allowed.
63+
selector: `ObjectPattern > Property[key.name=${i18nInstanceName}]:not([value.name=${i18nInstanceName}])`,
64+
message: aliasMessage,
65+
},
66+
{
67+
// <Trans> without its own t={t}: it reads the global instance, so a memoized element keeps the old language.
68+
// Direct child only: <Trans components={{ b: <Foo t={1} /> }} /> is allowed.
69+
selector: "JSXOpeningElement[name.name='Trans']:not(:has(> JSXAttribute[name.name='t']))",
70+
message:
71+
"Pass t={t} from useAppTranslation: Trans does not subscribe to language changes, so a cached <Trans> keeps the previous language.",
72+
},
73+
]
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
import assert from "node:assert/strict"
2+
import { describe, it } from "node:test"
3+
4+
import { Linter } from "eslint"
5+
import typescriptEslint from "typescript-eslint"
6+
7+
import { i18nLanguageSwitchSelectors } from "./i18n-language-switch.js"
8+
9+
const linter = new Linter({ configType: "flat" })
10+
const config = [
11+
{
12+
files: ["**/*.tsx"],
13+
languageOptions: { parser: typescriptEslint.parser, parserOptions: { ecmaFeatures: { jsx: true } } },
14+
rules: { "no-restricted-syntax": ["error", ...i18nLanguageSwitchSelectors] },
15+
},
16+
]
17+
18+
const lint = (code) => linter.verify(code, config, { filename: "example.tsx" }).map((message) => message.message)
19+
20+
describe("i18n language switch: global t", () => {
21+
for (const code of [
22+
'i18next.t("chat:about")',
23+
'import i18n from "i18next"\ni18n.t("chat:about")',
24+
'i18n?.t("chat:about")',
25+
'i18next["t"]("chat:about")',
26+
'useTranslation().i18n.t("chat:about")',
27+
"const { t } = i18next",
28+
"const { t: translate } = i18n",
29+
"const { t } = useTranslation().i18n",
30+
]) {
31+
it(`flags: ${code}`, () => {
32+
assert.equal(lint(code).length, 1)
33+
})
34+
}
35+
36+
for (const code of [
37+
'const { t } = useTranslation()\nt("chat:about")',
38+
'i18next.changeLanguage("es")',
39+
"i18n.language",
40+
"i18next[t]",
41+
"const { language } = i18n",
42+
'other.t("chat:about")',
43+
]) {
44+
it(`allows: ${code}`, () => {
45+
assert.deepEqual(lint(code), [])
46+
})
47+
}
48+
})
49+
50+
describe("i18n language switch: aliasing the instance", () => {
51+
for (const code of [
52+
'import lang from "i18next"',
53+
'import { default as lang } from "i18next"',
54+
'import * as lang from "i18next"',
55+
'import lang from "@src/i18n/setup"',
56+
'import lang from "@/i18n/setup"',
57+
'import lang from "../setup"',
58+
'export { default as lang } from "i18next"',
59+
"const lang = i18next",
60+
"const lang = useTranslation().i18n",
61+
"lang = i18n",
62+
"const { i18n: lang } = useTranslation()",
63+
"const { i18n: { t } } = useTranslation()",
64+
"function Foo({ i18n: lang }) {}",
65+
]) {
66+
it(`flags: ${code}`, () => {
67+
assert.equal(lint(code).length, 1)
68+
})
69+
}
70+
71+
for (const code of [
72+
'import i18next from "i18next"',
73+
'import i18n from "i18next"',
74+
'import i18next, { type TFunction } from "i18next"',
75+
'import { initReactI18next } from "react-i18next"',
76+
'import i18next from "@src/i18n/setup"',
77+
'import { default as i18next } from "i18next"',
78+
'import config from "./config"',
79+
"const i18n = useTranslation().i18n",
80+
"const { i18n } = useTranslation()",
81+
"const { language } = i18next",
82+
"const instance = i18next.createInstance()",
83+
"changeLanguage(i18next)",
84+
]) {
85+
it(`allows: ${code}`, () => {
86+
assert.deepEqual(lint(code), [])
87+
})
88+
}
89+
})
90+
91+
describe("i18n language switch: Trans", () => {
92+
for (const code of [
93+
'<Trans i18nKey="chat:about" />',
94+
"<Trans components={{ b: <Foo t={1} /> }} />",
95+
"<Trans {...props} />",
96+
]) {
97+
it(`flags a Trans without its own t: ${code}`, () => {
98+
assert.equal(lint(code).length, 1)
99+
})
100+
}
101+
102+
for (const code of [
103+
'<Trans t={t} i18nKey="chat:about" />',
104+
"<Trans t={t} components={{ b: <Foo t={1} /> }} />",
105+
'<Other i18nKey="chat:about" />',
106+
]) {
107+
it(`allows: ${code}`, () => {
108+
assert.deepEqual(lint(code), [])
109+
})
110+
}
111+
})

‎packages/config-eslint/package.json‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,12 @@
88
"./next-js": "./next.js",
99
"./provider-identifiers": "./provider-identifiers.js",
1010
"./api-provider-hygiene": "./api-provider-hygiene.js",
11-
"./i18n-keys": "./i18n-keys.js"
11+
"./i18n-keys": "./i18n-keys.js",
12+
"./i18n-language-switch": "./i18n-language-switch.js"
1213
},
1314
"scripts": {
1415
"lint": "eslint . --max-warnings=0",
15-
"test": "node --test provider-identifiers.test.js api-provider-hygiene.test.js i18n-keys.test.js"
16+
"test": "node --test *.test.js"
1617
},
1718
"devDependencies": {
1819
"@eslint/js": "9.39.5",

‎src/utils/__tests__/jsonFileRecovery.test.ts‎

Lines changed: 131 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import * as fsSync from "fs"
55

66
import { acquireFileLock } from "../fileLock"
77
import { setPersistenceTraceSink } from "../../core/task-persistence/persistenceTrace"
8-
import { deleteJsonFile, recoverMissingJsonFile } from "../jsonFileRecovery"
8+
import { recoverInterruptedReplacement, deleteJsonFile, recoverMissingJsonFile } from "../jsonFileRecovery"
99
import { LockKeyWalkIncompleteError, resolveLockKey } from "../../services/file-safety/safeWriteText"
1010
import { readFileWithMissingRetry } from "../../core/task-persistence/readFileWithMissingRetry"
1111

@@ -59,6 +59,57 @@ describe("reader recovery", () => {
5959
await expect(fs.readFile(backup)).rejects.toMatchObject({ code: "ENOENT" })
6060
})
6161

62+
// The recency choice is `sort((a, b) => b.mtimeMs - a.mtimeMs)` followed by renaming
63+
// the head of that list. mtime is the only signal recovery has, so an exact tie says
64+
// nothing about which backup holds the committed content - the winner would be readdir
65+
// order, and the loser is unlinked. The tie is set with utimes rather than raced
66+
// against the clock, so the row does not depend on how fast two writes land; the
67+
// second row is the control that keeps this from being a test which merely asserts
68+
// "two backups means reject".
69+
it("refuses an exact mtime tie between two backups instead of picking by directory order", async () => {
70+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
71+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
72+
const shared = new Date(1_700_000_000_000)
73+
await fs.utimes(backup, shared, shared)
74+
await fs.utimes(otherBackup, shared, shared)
75+
76+
const error = await recoverInterruptedReplacement(target).then(
77+
() => undefined,
78+
(reason: unknown) => reason,
79+
)
80+
expect(error).toMatchObject({
81+
name: "AmbiguousBackupRecencyError",
82+
code: "AMBIGUOUS_BACKUP_RECENCY",
83+
mtimeMs: 1_700_000_000_000,
84+
})
85+
// The diagnostic has to name the magnitude it refused to guess about.
86+
expect(String((error as Error).message)).toContain("share mtime 1700000000000")
87+
88+
// Fail closed: nothing restored, nothing deleted, so both copies survive for a
89+
// human to read.
90+
await expect(fs.access(target)).rejects.toMatchObject({ code: "ENOENT" })
91+
expect(JSON.parse(await fs.readFile(backup, "utf8"))).toEqual({ committed: true })
92+
expect(JSON.parse(await fs.readFile(otherBackup, "utf8"))).toEqual({ other: true })
93+
})
94+
95+
it("restores the newer backup when two backups have different mtimes", async () => {
96+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
97+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
98+
const older = new Date(1_700_000_000_000)
99+
const newer = new Date(1_700_000_000_001)
100+
await fs.utimes(otherBackup, older, older)
101+
await fs.utimes(backup, newer, newer)
102+
103+
const recovery = await recoverInterruptedReplacement(target)
104+
105+
expect(recovery.foundLeftovers).toBe(true)
106+
expect(recovery.restoredFrom).toBe(backup)
107+
expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ committed: true })
108+
// The loser of a decided race is still garbage-collected, which is the contract the
109+
// tie row must not break.
110+
await expect(fs.access(otherBackup)).rejects.toMatchObject({ code: "ENOENT" })
111+
})
112+
62113
it("traces reader restoration and lock waiting", async () => {
63114
const sink = vi.fn()
64115
setPersistenceTraceSink(sink)
@@ -274,4 +325,83 @@ describe("reader recovery", () => {
274325
await expect(recoverMissingJsonFile(target)).resolves.toBe(false)
275326
await expect(fs.stat(dir)).rejects.toMatchObject({ code: "ENOENT" })
276327
})
328+
329+
it("restores the newest backup when two OLDER backups share a tie", async () => {
330+
// Three backups: 200, 100, 100. The tie sits BELOW the winner, so recency is decidable
331+
// and recovery must restore the newest copy and remove both losers. A guard that refused
332+
// every duplicate mtime - not just a tie for the newest slot - would fail this row, which
333+
// is what stops the two tie rows above from standing in for "any duplicate means refuse".
334+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
335+
const thirdBackup = path.join(dir, ".history_item.json.bak_3_third.tmp")
336+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
337+
await fs.writeFile(thirdBackup, JSON.stringify({ third: true }))
338+
const older = new Date(1_700_000_000_100)
339+
const newest = new Date(1_700_000_000_200)
340+
await fs.utimes(otherBackup, older, older)
341+
await fs.utimes(thirdBackup, older, older)
342+
await fs.utimes(backup, newest, newest)
343+
344+
const recovery = await recoverInterruptedReplacement(target)
345+
346+
expect(recovery.foundLeftovers).toBe(true)
347+
expect(recovery.restoredFrom).toBe(backup)
348+
expect(JSON.parse(await fs.readFile(target, "utf8"))).toEqual({ committed: true })
349+
await expect(fs.access(otherBackup)).rejects.toMatchObject({ code: "ENOENT" })
350+
await expect(fs.access(thirdBackup)).rejects.toMatchObject({ code: "ENOENT" })
351+
})
352+
353+
it("refuses a tie through the reader entry point and keeps both copies", async () => {
354+
// The refusal has to survive the path a reader actually takes: recoverMissingJsonFile runs
355+
// recovery under the lock and reports the failure through the persistence trace. Asserting
356+
// it here as well keeps a propagation or trace regression from passing while the internal
357+
// helper row still goes green.
358+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
359+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
360+
const shared = new Date(1_700_000_000_000)
361+
await fs.utimes(backup, shared, shared)
362+
await fs.utimes(otherBackup, shared, shared)
363+
const sink = vi.fn()
364+
setPersistenceTraceSink(sink)
365+
366+
await expect(recoverMissingJsonFile(target)).rejects.toMatchObject({
367+
name: "AmbiguousBackupRecencyError",
368+
code: "AMBIGUOUS_BACKUP_RECENCY",
369+
})
370+
371+
expect(sink).toHaveBeenCalledWith(expect.stringContaining('"stage":"json-recovery"'))
372+
expect(sink).toHaveBeenCalledWith(expect.stringContaining('"result":"failed"'))
373+
// Fail closed: the tie is still there for a human to decide about.
374+
await expect(fs.access(target)).rejects.toMatchObject({ code: "ENOENT" })
375+
expect(JSON.parse(await fs.readFile(backup, "utf8"))).toEqual({ committed: true })
376+
expect(JSON.parse(await fs.readFile(otherBackup, "utf8"))).toEqual({ other: true })
377+
})
378+
379+
it("keeps the tied paths out of the tie error message and on the error properties", async () => {
380+
// Error telemetry captures message and stack, and a workspace path carries the local
381+
// username into that capture. The message names the basenames it refused to choose between;
382+
// the full paths stay on the properties, which is where a human acts on them.
383+
const otherBackup = path.join(dir, ".history_item.json.bak_2_other.tmp")
384+
await fs.writeFile(otherBackup, JSON.stringify({ other: true }))
385+
const shared = new Date(1_700_000_000_000)
386+
await fs.utimes(backup, shared, shared)
387+
await fs.utimes(otherBackup, shared, shared)
388+
389+
const error = await recoverInterruptedReplacement(target).then(
390+
() => undefined,
391+
(reason: unknown) => reason,
392+
)
393+
const tie = error as Error & { targetPath: string; firstBackupPath: string; secondBackupPath: string }
394+
395+
expect(tie.name).toBe("AmbiguousBackupRecencyError")
396+
expect(tie.message).not.toContain(path.sep)
397+
expect(tie.message).not.toContain(dir)
398+
expect(tie.message).toContain("history_item.json")
399+
expect(tie.message).toContain("share mtime 1700000000000")
400+
expect(tie.targetPath).toBe(target)
401+
// The two tied files, whatever order readdir handed them in: the guard reports both,
402+
// and which one lands on which property is not something the caller can rely on.
403+
expect([tie.firstBackupPath, tie.secondBackupPath].sort()).toEqual([backup, otherBackup].sort())
404+
expect(tie.message).toContain(path.basename(backup))
405+
expect(tie.message).toContain(path.basename(otherBackup))
406+
})
277407
})

0 commit comments

Comments
 (0)