Merge remote-tracking branch 'origin/main' into brennanb2025/mobile-ask-preview-sheet

This commit is contained in:
Brennan Benson
2026-11-09 21:01:36 -08:00
1044 changed files with 11120 additions and 20196 deletions
+4
View File
@@ -512,6 +512,10 @@ jobs:
if: needs.code_paths.outputs.static_analysis == 'true'
run: bun config/scripts/localization/source-extraction/audit-localization-coverage.mjs --check
- name: Verify startup and worktree localization coverage
if: needs.code_paths.outputs.static_analysis == 'true'
run: bun run verify:startup-worktree-localization-coverage
- name: Verify mobile localization
if: needs.code_paths.outputs.static_analysis == 'true'
run: bun config/scripts/localization/catalog-validation/verify-mobile-localization.mjs
+3
View File
@@ -121,6 +121,9 @@ validation-screenshots/
test-results/
playwright-report/
# Claude Code settings are machine-local.
**/.claude/settings.local.json
# Agent skills are installed per machine.
/.claude/skills/
/.agents/skills/
+2 -4
View File
@@ -292,11 +292,9 @@ Pair with your desktop app to monitor and steer your agents from your phone.
- **Discord:** Join the community on **[Discord](https://discord.gg/fzjDKHxv8Q)**.
- **Twitter / X:** Follow **[@orca_build](https://x.com/orca_build)** for updates and announcements.
- **WeChat:** Scan to join an Orca community WeChat group. If one group is full, join another.
- **WeChat:** Scan to join an Orca community WeChat group.
<img src="docs/assets/wechat-qr-group14.jpg" alt="WeChat QR code for the Orca community" width="160" />
<img src="docs/assets/wechat-qr-group15.jpg" alt="WeChat QR code for the Orca community" width="160" />
<img src="docs/assets/wechat-qr-group16.jpg" alt="WeChat QR code for the Orca community" width="160" />
<img src="docs/assets/wechat-qr.jpg" alt="WeChat QR code for the Orca community" width="160" />
- **Feedback &amp; Ideas:** We ship fast. Missing something? [Request a new feature](https://github.com/stablyai/orca/issues).
- **Privacy:** See the [privacy &amp; telemetry docs](https://www.onorca.dev/docs/telemetry) for what anonymous usage data Orca collects and how to opt out.
@@ -1,5 +1,5 @@
// Later run-all.ts checks against the same host: rebind, orphan grace, silence,
// forced resets and pre-upgrade refusals.
// forced resets.
import WebSocket from 'ws'
import { GRACE_MS, ORIGIN, PING_MS, PORT, SILENCE_MS, makeControl, openPhone, record, sleep, waitFor, type Ctx, type Control } from './run-all-harness'
@@ -89,12 +89,4 @@ export async function runLifecycleChecks(ctx: Ctx, main: Control, mainAck: Ack):
back.client.closeNow()
}
// Bad JWT -> 401 before upgrade; malformed host id -> 429.
{
const bad = new WebSocket(`ws://127.0.0.1:${PORT}/v1/host/control`, { headers: { authorization: 'Bearer nope' } })
const status = await new Promise<number>((res) => bad.on('unexpected-response', (_q, r) => res(r.statusCode ?? 0)))
const badHost = new WebSocket(`ws://127.0.0.1:${PORT}/v1/connect/short`)
const s2 = await new Promise<number>((res) => badHost.on('unexpected-response', (_q, r) => res(r.statusCode ?? 0)))
record('R11/R5 ES256 JWKS rejects bad token (401); malformed host id 429', status === 401 && s2 === 429, `${status},${s2}`)
}
}
-5
View File
@@ -100,11 +100,6 @@ async function runTests(ctx: Ctx): Promise<void> {
const mainAck = await main.client.connect()
const transport = main.bindTransport(mainAck.generation)
// Alarm-driven app ping, answered by the shipped client's pong handler.
await sleep(PING_MS * 3 + 300)
record('R2/R5 alarm-driven JSON ping parsed by shipped client, pong keeps control alive',
main.events.pings >= 2 && main.client.isLive(), `pings=${main.events.pings} live=${main.client.isLive()}`)
// Phone connect -> conn-open (strict, shipped parser) -> host data -> relay-hello (shipped parser).
const phone = openPhone(ctx)
const helloOk = await waitFor(() => phone.hello !== null, 5000)
@@ -0,0 +1,36 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
// Why: import.meta.url, not dirname — electron-vite's config bundle rewrites only the former.
const REPO_ROOT = fileURLToPath(new URL('../..', import.meta.url))
export const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt'
// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently.
export const UNCOMPILED_FILE_LISTS = [
UNCOMPILED_LIST,
'config/render-path-translate-baseline.txt',
'config/react-compiler-hazard-baseline.txt'
]
/** Repo-relative paths from a list or count baseline: `[count ]path[#detail][ # note]`. */
export function parseListedFiles(text) {
return text
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
.map((line) =>
line
.replace(/^\d+\s+/, '')
.split('#')[0]
.trim()
)
}
export function readListedFiles(list, root = REPO_ROOT) {
return parseListedFiles(readFileSync(resolve(root, list), 'utf8'))
}
export function reactCompilerExcludedFiles(root = REPO_ROOT) {
return [...new Set(UNCOMPILED_FILE_LISTS.flatMap((list) => readListedFiles(list, root)))]
}
+1 -21
View File
@@ -1,25 +1,5 @@
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import type { Options } from '@vitejs/plugin-react'
// Hand-kept list plus every file still in a hazard ratchet; compiled, these would run differently.
const UNCOMPILED_FILE_LISTS = [
'config/react-compiler-uncompiled-files.txt',
'config/render-path-translate-baseline.txt',
'config/react-compiler-hazard-baseline.txt'
]
function listedFiles(list: string): string[] {
return readFileSync(resolve(list), 'utf8')
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
.map((line) => line.replace(/^\d+\s+/, '').split('#')[0])
}
export function reactCompilerExcludedFiles(): string[] {
return [...new Set(UNCOMPILED_FILE_LISTS.flatMap(listedFiles))]
}
import { reactCompilerExcludedFiles } from './react-compiler-uncompiled-files.mjs'
export function isReactCompilerEnabled(): boolean {
return process.env.ORCA_REACT_COMPILER !== '0'
+7 -7
View File
@@ -12,17 +12,17 @@
3 src/renderer/src/components/LinearIssueTextEditor.tsx
3 src/renderer/src/components/LinearIssueWorkspace.tsx
5 src/renderer/src/components/LinearItemDrawer.tsx
1 src/renderer/src/components/NativeChatResumeOnRestartGroups.tsx
1 src/renderer/src/components/native-chat-recovery/tree/NativeChatResumeOnRestartGroups.tsx
1 src/renderer/src/components/activity/ActivityPrototypePage.tsx
1 src/renderer/src/components/activity/activity-scope-filter-controls.tsx
2 src/renderer/src/components/activity/activity-thread-actions.ts
1 src/renderer/src/components/activity/use-agent-pane-thread-store-data.ts
1 src/renderer/src/components/activity/use-agent-pane-threads.ts
4 src/renderer/src/components/agent/AgentSettingsDialog.tsx
1 src/renderer/src/components/automations/automation-host-client.ts
1 src/renderer/src/components/automations/hosts/automation-host-client.ts
1 src/renderer/src/components/automations/automations-page-fixtures.ts
1 src/renderer/src/components/automations/use-automations-page-controller.ts
1 src/renderer/src/components/automations/use-automations-page-destination-form.ts
1 src/renderer/src/components/automations/authoring/use-automations-page-destination-form.ts
1 src/renderer/src/components/browser-pane/ReopenBrowserPageOnServerButton.tsx
1 src/renderer/src/components/browser-pane/browser-reopen-on-server.ts
1 src/renderer/src/components/browser-pane/stream-remote/use-remote-browser-page-stream.ts
@@ -204,11 +204,11 @@
1 src/renderer/src/hooks/ipc-events/runtime-environment-subscription-selection.ts
1 src/renderer/src/hooks/ipc-events/settings-sidebar-ipc-bridge.ts
1 src/renderer/src/hooks/ipc-events/terminal-request-ipc-bridge.ts
1 src/renderer/src/hooks/use-active-skill-discovery-runtime-target.ts
1 src/renderer/src/hooks/skills/discovery/use-active-skill-discovery-runtime-target.ts
2 src/renderer/src/hooks/use-integration-provider-status-refresh.ts
1 src/renderer/src/hooks/useActiveProjectSkillRuntime.ts
1 src/renderer/src/hooks/skills/runtime/useActiveProjectSkillRuntime.ts
1 src/renderer/src/hooks/useEditorExternalWatch.ts
1 src/renderer/src/hooks/useInstalledAgentSkills.ts
1 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts
1 src/renderer/src/hooks/useIpcEvents.ts
4 src/renderer/src/hooks/useIssueMetadata.ts
2 src/renderer/src/hooks/useLinearIssuePublication.ts
@@ -230,7 +230,7 @@
1 src/renderer/src/lib/workspace/ownership/runtime-session-mirror-owners.ts
1 src/renderer/src/lib/runtime-session-mirror-targets.ts
1 src/renderer/src/lib/workspace/ownership/single-runtime-legacy-owner.ts
1 src/renderer/src/lib/skill-runtime-command.ts
1 src/renderer/src/lib/skills/runtime/skill-runtime-command.ts
1 src/renderer/src/lib/terminal-close-route.ts
4 src/renderer/src/lib/terminal-worktree-route.ts # resolveTerminalPtyOwner: teardown, close and PTY identity read spawn's attribution (round 3 F8), which retired the deprecated resolver's readers
3 src/renderer/src/lib/unread-badge-count-selector.ts
+1 -1
View File
@@ -1,7 +1,7 @@
# JSX mapped straight over a host collection, per file, outside components/host-picker.
# This is a RATCHET: counts may only go DOWN. Draw host lists with HostCombobox or
# useBoundedHostRows. Prune after a fix: pnpm check:host-list-render-ratchet --prune
1 src/renderer/src/components/automations/AutomationRunsDashboard.tsx
1 src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx
1 src/renderer/src/components/right-sidebar/ai-vault/panel/AiVaultPanelControls.tsx
1 src/renderer/src/components/right-sidebar/source-control/ai/SourceControlAgentActionDialogForm.tsx
1 src/renderer/src/components/settings/browser/profiles/BrowserSessionCookiesSection.tsx
+29 -29
View File
@@ -28,27 +28,27 @@
1 src/renderer/src/components/artifacts/ArtifactPublishButton.tsx
2 src/renderer/src/components/artifacts/ArtifactsPage.tsx
2 src/renderer/src/components/artifacts/useArtifactPagination.ts
2 src/renderer/src/components/automations/AutomationEditorPromptEditor.tsx
1 src/renderer/src/components/automations/AutomationHostFilterNotice.tsx
1 src/renderer/src/components/automations/AutomationProjectCombobox.tsx
1 src/renderer/src/components/automations/AutomationRunHistory.tsx
1 src/renderer/src/components/automations/AutomationRunsDashboard.tsx
1 src/renderer/src/components/automations/AutomationRunsTable.tsx
2 src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.tsx
1 src/renderer/src/components/automations/hosts/AutomationHostFilterNotice.tsx
1 src/renderer/src/components/automations/authoring/AutomationProjectCombobox.tsx
1 src/renderer/src/components/automations/runs/AutomationRunHistory.tsx
1 src/renderer/src/components/automations/runs/AutomationRunsDashboard.tsx
1 src/renderer/src/components/automations/runs/AutomationRunsTable.tsx
1 src/renderer/src/components/automations/AutomationsPageSurface.tsx
1 src/renderer/src/components/automations/use-automation-agent-picker-entries.ts
2 src/renderer/src/components/automations/use-automation-create-destination.ts
4 src/renderer/src/components/automations/use-automation-host-catalog.ts
4 src/renderer/src/components/automations/use-automation-list-search.ts
2 src/renderer/src/components/automations/use-automation-migrate-action.ts
1 src/renderer/src/components/automations/use-automation-runs-dashboard.ts
1 src/renderer/src/components/automations/use-automations-page-list-state.ts
1 src/renderer/src/components/automations/authoring/use-automation-agent-picker-entries.ts
2 src/renderer/src/components/automations/authoring/use-automation-create-destination.ts
4 src/renderer/src/components/automations/hosts/use-automation-host-catalog.ts
4 src/renderer/src/components/automations/listing/use-automation-list-search.ts
2 src/renderer/src/components/automations/authoring/use-automation-migrate-action.ts
1 src/renderer/src/components/automations/runs/use-automation-runs-dashboard.ts
1 src/renderer/src/components/automations/listing/use-automations-page-list-state.ts
1 src/renderer/src/components/automations/use-automations-page-local-state.ts
1 src/renderer/src/components/automations/use-automations-page-refresh.ts
1 src/renderer/src/components/automations/use-automations-page-setup-state.ts
1 src/renderer/src/components/automations/authoring/use-automations-page-setup-state.ts
1 src/renderer/src/components/automations/use-automations-page-store-state.ts
1 src/renderer/src/components/automations/use-external-automation-scope-retention.ts
2 src/renderer/src/components/automations/use-scoped-external-automations.ts
16 src/renderer/src/components/automations/use-selected-automation-run-history.ts
1 src/renderer/src/components/automations/external/use-external-automation-scope-retention.ts
2 src/renderer/src/components/automations/external/use-scoped-external-automations.ts
16 src/renderer/src/components/automations/runs/use-selected-automation-run-history.ts
7 src/renderer/src/components/browser-extension-install-dialog.tsx
1 src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.tsx
2 src/renderer/src/components/browser-pane/annotate/MarkupOverlay.tsx
@@ -206,7 +206,7 @@
1 src/renderer/src/components/mobile/WindowsFirewallNotice.tsx
2 src/renderer/src/components/mobile/use-mobile-page-paired-devices.ts
1 src/renderer/src/components/mobile/use-mobile-pairing-generation.ts
1 src/renderer/src/components/native-chat-restart-runtimes.ts
1 src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts
1 src/renderer/src/components/native-chat/NativeChatStructuredSession.tsx
8 src/renderer/src/components/native-chat/attachments/chips/use-native-chat-composer-attachments.ts
2 src/renderer/src/components/native-chat/attachments/intake/use-native-chat-resolved-path-attachments.ts
@@ -542,16 +542,16 @@
4 src/renderer/src/components/sidebar/worktree-list/viewport/use-row-measurement.ts
1 src/renderer/src/components/sidebar/worktree-list/viewport/use-scroll-to-top.ts
1 src/renderer/src/components/sidebar/worktree-list/viewport/use-virtualizer.ts
1 src/renderer/src/components/skills/SkillBundleInstallFlow.tsx
2 src/renderer/src/components/skills/SkillInstallDialog.tsx
4 src/renderer/src/components/skills/SkillInstallManagementDialog.tsx
1 src/renderer/src/components/skills/SkillShareDialog.tsx
1 src/renderer/src/components/skills/SkillSharedLinkRow.tsx
1 src/renderer/src/components/skills/installation/SkillBundleInstallFlow.tsx
2 src/renderer/src/components/skills/installation/SkillInstallDialog.tsx
4 src/renderer/src/components/skills/installation/SkillInstallManagementDialog.tsx
1 src/renderer/src/components/skills/sharing/SkillShareDialog.tsx
1 src/renderer/src/components/skills/sharing/SkillSharedLinkRow.tsx
1 src/renderer/src/components/skills/SkillsPage.tsx
1 src/renderer/src/components/skills/setup/WslAgentSkillSetupPanel.tsx
2 src/renderer/src/components/skills/use-owned-skill-shares.ts
1 src/renderer/src/components/skills/use-reviewed-skill-plan.ts
1 src/renderer/src/components/skills/use-skill-delete-flow.ts
2 src/renderer/src/components/skills/sharing/use-owned-skill-shares.ts
1 src/renderer/src/components/skills/freshness/use-reviewed-skill-plan.ts
1 src/renderer/src/components/skills/deletion/use-skill-delete-flow.ts
1 src/renderer/src/components/sparse/SparseCheckoutPresetSelect.tsx
1 src/renderer/src/components/ssh-host-recovery/SshHostMoveAnywayAction.tsx
2 src/renderer/src/components/star-nag/StarNagAgentValueMomentObserver.tsx
@@ -693,16 +693,16 @@
1 src/renderer/src/hooks/composer-state/workspace-identity-state.ts
3 src/renderer/src/hooks/linear-issue-committed-state.ts
1 src/renderer/src/hooks/use-audio-capture.ts
1 src/renderer/src/hooks/use-bundled-skill-install.ts
1 src/renderer/src/hooks/skills/installation/use-bundled-skill-install.ts
2 src/renderer/src/hooks/useDetectedAgents.ts
2 src/renderer/src/hooks/useGitHubTaskItems.ts
2 src/renderer/src/hooks/useImmediateMutation.ts
6 src/renderer/src/hooks/useInstalledAgentSkills.ts
6 src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.ts
1 src/renderer/src/hooks/useIssueMetadata.ts
3 src/renderer/src/hooks/useLinearIssuePublication.ts
1 src/renderer/src/hooks/useMacTccAttributionSeveredNotice.ts
1 src/renderer/src/hooks/useSettingsNavigationMetadata.ts
4 src/renderer/src/hooks/useSkillFreshness.ts
4 src/renderer/src/hooks/skills/freshness/useSkillFreshness.ts
1 src/renderer/src/hooks/useTaskPageGitHubWorkItemMutation.ts
6 src/renderer/src/hooks/useVirtualizedScrollAnchor.ts
1 src/renderer/src/lib/host-chat-program-acquisition.ts
+1 -1
View File
@@ -1,5 +1,5 @@
# Grandfathered code React Compiler would run differently (<file>#<function>:<hazard>).
# Generated; never hand-edit. Lower after a fix: pnpm check:react-compiler-compat-ratchet --prune
1 src/renderer/src/components/agent/agent-launch-picker-drafts.ts#useAgentPickerSetup:discarded-subscription
1 src/renderer/src/components/native-chat-restart-runtimes.ts#useNativeChatRestartRuntimes:discarded-subscription
1 src/renderer/src/components/native-chat-recovery/offers/native-chat-restart-runtimes.ts#useNativeChatRestartRuntimes:discarded-subscription
1 src/renderer/src/components/right-sidebar/source-control/ai/use-source-control-action-agent-choice.ts#useSourceControlActionAgentChoice:store-read-in-memo-block
File diff suppressed because one or more lines are too long
+1 -1
View File
@@ -2,7 +2,7 @@
# This is a RATCHET: counts may only go DOWN. Use useTranslate()/useIntlLocale() from
# @/i18n/use-translate. Prune after a fix: pnpm check:render-path-translate-ratchet --prune
2 src/renderer/src/components/agent/AgentLaunchPromptComposer.tsx
5 src/renderer/src/components/automations/use-external-automation-actions.ts
5 src/renderer/src/components/automations/external/use-external-automation-actions.ts
1 src/renderer/src/components/diff-comments/useDiffCommentDecorator.tsx
2 src/renderer/src/components/editor/markdown-preview/render-tree/use-markdown-preview-components.tsx
1 src/renderer/src/components/tab-group/useTabGroupCreationCommands.ts
@@ -1,4 +1,4 @@
import { readFile } from 'node:fs/promises'
import { readFile, readdir } from 'node:fs/promises'
import { readRouteSnapshot } from '../../mobile-web-app/mobile-web-app-route-snapshot.mjs'
import { MOBILE_WEB_APP_DEPENDENCY_PATH } from '../../mobile-web-app/mobile-web-app-bundle-dependencies.mjs'
import { existsSync, realpathSync } from 'node:fs'
@@ -457,6 +457,32 @@ export async function mobileWebAppModuleClosure(entryModules, { absWorkingDir }
// One lazily imported chunk per UI language; the page fetches only the active one after init.
const LOCALE_CATALOG_INPUT = /(^|\/)src\/i18n\/locales\/[^/]+\.json$/
const localeCatalogDir = join(mobileDir, 'src', 'i18n', 'locales')
// The same catalogs as JSON for the host to serve one at a time, to shells that skip the chunks;
// English is the page's inline fallback, so it has none.
export async function readLocaleCatalogs(directory = localeCatalogDir) {
const names = (await readdir(directory))
.filter((name) => name.endsWith('.json') && name !== 'en.json')
.sort()
return Promise.all(
names.map(async (name) => {
// Minify: the host sends and the phone keeps the parsed object, not the source layout.
const bytes = Buffer.from(
JSON.stringify(JSON.parse(await readFile(join(directory, name), 'utf8'))),
'utf8'
)
const sha256 = sha256Hex(bytes)
return {
locale: name.slice(0, -'.json'.length),
bytes,
path: `catalogs/${sha256}.json`,
sha256,
byteLength: bytes.byteLength
}
})
)
}
function localeCatalogOutputs(metafile) {
return new Set(
@@ -586,11 +612,13 @@ export async function buildMobileWebAppBundle({
desktopVersion,
protocolWindow,
{ script, chunks, images, catalogChunks, entryStaticBytes, chunkCount, routeChunks, routeKeys },
catalogs,
scrollbarStyle
] = await Promise.all([
readDesktopVersion(),
readProtocolWindow(),
bundleMobileWebApp({ appDir }),
readLocaleCatalogs(),
readFile(join(projectDir, 'src/shared/styles/scrollbar-sleek.css'), 'utf8').then((style) =>
// The shared desktop stylesheet can be checked out as CRLF on Windows.
style.replace(/\r\n/g, '\n')
@@ -598,9 +626,14 @@ export async function buildMobileWebAppBundle({
])
// Names already hash final bytes, so hashedAsset must reproduce them.
const scriptAsset = hashedAsset(script, 'js')
const catalogChunkSet = new Set(catalogChunks)
const written = [
scriptAsset,
...[...chunks, ...images].map(({ name, bytes }) => hashedAsset(bytes, extname(name).slice(1)))
...[...chunks, ...images].map((output) => ({
...hashedAsset(output.bytes, extname(output.name).slice(1)),
// Shells that read catalogs from the host skip these; older shells download them as before.
...(catalogChunkSet.has(output) ? { kind: 'catalog' } : {})
}))
]
// Root-absolute URLs survive nested routes; CSP allows only about: base. ESM entry/chunks load under existing self policy.
@@ -624,6 +657,7 @@ export async function buildMobileWebAppBundle({
const { manifest } = await writeMobileWebBundleTree({
outDir,
written: [indexAsset, ...written],
catalogs,
desktopVersion,
protocolWindow,
routes: resolveMobileWebPageRoutes(routeKeys, pageRoutes),
@@ -133,6 +133,8 @@ async function compressWithBrotli(written) {
export async function writeMobileWebBundleTree({
outDir,
written,
// Host-only JSON outside `assets` and buildId, served one at a time over RPC.
catalogs = [],
desktopVersion,
protocolWindow,
// Empty route list makes shell render every screen natively.
@@ -143,14 +145,15 @@ export async function writeMobileWebBundleTree({
}) {
const brotliCopies = brotli ? await compressWithBrotli(written) : new Map()
const assets = written
.map(({ path, sha256, byteLength, contentType }) => {
.map(({ path, sha256, byteLength, contentType, kind }) => {
const copy = brotliCopies.get(path)
return {
path,
sha256,
byteLength,
contentType,
...(copy === undefined ? {} : { brotliByteLength: copy.byteLength })
...(copy === undefined ? {} : { brotliByteLength: copy.byteLength }),
...(kind === undefined ? {} : { kind })
}
})
.sort((left, right) => (left.path < right.path ? -1 : left.path > right.path ? 1 : 0))
@@ -164,14 +167,27 @@ export async function writeMobileWebBundleTree({
entrypoint: MOBILE_WEB_BUNDLE_ENTRYPOINT,
totalBytes: assets.reduce((total, asset) => total + asset.byteLength, 0),
assets,
routes
routes,
...(catalogs.length === 0
? {}
: {
catalogs: catalogs.map(({ locale, path, sha256, byteLength }) => ({
locale,
path,
sha256,
byteLength
}))
})
}
// Clear entire output or stale unreferenced assets ship inside asar.
await rm(outDir, { recursive: true, force: true })
await mkdir(join(outDir, 'assets'), { recursive: true })
for (const asset of written) {
await writeFile(join(outDir, asset.path), asset.bytes)
if (catalogs.length > 0) {
await mkdir(join(outDir, 'catalogs'), { recursive: true })
}
for (const file of [...written, ...catalogs]) {
await writeFile(join(outDir, file.path), file.bytes)
}
for (const [path, copy] of brotliCopies) {
await writeFile(join(outDir, mobileWebBundleBrotliPath(path)), copy)
@@ -29,6 +29,8 @@ export function mobileWebAppBundleMaxAssets(routeCount, imageCount, catalogChunk
// fetched only for the active language, never before the first route. Code keeps its own fence.
export const MOBILE_WEB_APP_BUNDLE_MAX_CATALOG_CHUNKS = 10
export const MOBILE_WEB_APP_BUNDLE_MAX_CATALOG_BYTES = 3 * 1024 * 1024
// The host sends a catalog's JSON in one reply, which must fit a 1 MiB relay frame once encrypted.
export const MOBILE_WEB_APP_HOST_CATALOG_MAX_BYTES = 384 * 1024
// Our own fence on the page's code, well inside the phone contract (32 MiB total, 10 MiB per asset in
// manifest-contract.ts); it fails the build before the code weighs more than any one asset may.
@@ -185,6 +187,23 @@ export async function verifyMobileWebAppBundle({ bundleDir = defaultBundleDir }
`${String(MOBILE_WEB_APP_BUNDLE_MAX_CATALOG_BYTES)} bytes`
)
}
// buildId leaves the host's JSON catalogs out, so a stale copy shows only here.
const hostCatalogsOf = (built) => JSON.stringify(built.catalogs ?? [])
if (hostCatalogsOf(first.manifest) !== hostCatalogsOf(second.manifest)) {
fail('host language catalogs are not reproducible')
}
if (hostCatalogsOf(first.manifest) !== hostCatalogsOf(manifest)) {
fail(`${bundleDir} is stale: its host language catalogs differ from a fresh build's`)
}
const oversized = (manifest.catalogs ?? []).find(
(catalog) => catalog.byteLength > MOBILE_WEB_APP_HOST_CATALOG_MAX_BYTES
)
if (oversized) {
fail(
`the ${oversized.locale} host catalog is ${String(oversized.byteLength)} bytes, over the ` +
`${String(MOBILE_WEB_APP_HOST_CATALOG_MAX_BYTES)} one reply carries`
)
}
const budgetBytes = mobileWebAppBundleBudgetBytes(manifest) - first.catalogBytes
if (budgetBytes > MOBILE_WEB_APP_BUNDLE_MAX_TOTAL_BYTES) {
fail(
@@ -4641,9 +4641,6 @@
"src/renderer/src/components/JiraIssueWorkspace.optimistic-edit.test.tsx": 2340,
"src/renderer/src/components/JiraIssueWorkspace.status-queue.test.tsx": 1852,
"src/renderer/src/components/JiraIssueWorkspace.transition-source.test.tsx": 1843,
"src/renderer/src/components/NativeChatRemoteResume.test.tsx": 8774,
"src/renderer/src/components/NativeChatResumeOnRestartGroups.selection.test.tsx": 2633,
"src/renderer/src/components/NativeChatResumeOnRestartGroups.test.tsx": 3472,
"src/renderer/src/components/NewWorkspaceComposerCard.quick-file-drop.test.tsx": 4557,
"src/renderer/src/components/NewWorkspaceComposerCard.set-location.test.tsx": 1301,
"src/renderer/src/components/QuickOpen.selection.test.tsx": 1046,
@@ -4675,53 +4672,44 @@
"src/renderer/src/components/artifacts/ArtifactPublishButton.test.tsx": 706,
"src/renderer/src/components/artifacts/ArtifactsPage.test.tsx": 2052,
"src/renderer/src/components/artifacts/artifact-publish-flow.test.ts": 114,
"src/renderer/src/components/automations/AutomationEditorPromptEditor.test.tsx": 396,
"src/renderer/src/components/automations/authoring/AutomationEditorPromptEditor.test.tsx": 396,
"src/renderer/src/components/automations/AutomationPromptDisclosure.test.tsx": 893,
"src/renderer/src/components/automations/AutomationRunsTable.test.tsx": 668,
"src/renderer/src/components/automations/AutomationSchedulePicker.test.ts": 431,
"src/renderer/src/components/automations/AutomationTimeField.test.tsx": 654,
"src/renderer/src/components/automations/authoring/AutomationSchedulePicker.test.ts": 431,
"src/renderer/src/components/automations/AutomationsPage.behavior.test.tsx": 3389,
"src/renderer/src/components/automations/AutomationsPage.edit-destination.test.tsx": 2932,
"src/renderer/src/components/automations/AutomationsPage.run-navigation.test.tsx": 3056,
"src/renderer/src/components/automations/ExternalAutomationManagers.test.tsx": 852,
"src/renderer/src/components/automations/automation-captured-owner.test.ts": 379,
"src/renderer/src/components/automations/automation-create-projects.test.ts": 42,
"src/renderer/src/components/automations/hosts/automation-captured-owner.test.ts": 379,
"src/renderer/src/components/automations/automation-host-cache-controller.test.ts": 411,
"src/renderer/src/components/automations/automation-host-cache-error.test.ts": 391,
"src/renderer/src/components/automations/automation-host-cache-health.test.ts": 52,
"src/renderer/src/components/automations/automation-host-cache.test.ts": 79,
"src/renderer/src/components/automations/automation-host-catalog-generation.test.ts": 258,
"src/renderer/src/components/automations/automation-host-client.test.ts": 374,
"src/renderer/src/components/automations/hosts/automation-host-cache.test.ts": 79,
"src/renderer/src/components/automations/automation-host-diagnostics.test.ts": 460,
"src/renderer/src/components/automations/automation-host-filter-resolution.test.ts": 256,
"src/renderer/src/components/automations/automation-host-health.test.ts": 47,
"src/renderer/src/components/automations/automation-host-invalidation-window-events.test.ts": 83,
"src/renderer/src/components/automations/automation-host-invalidation.test.ts": 85,
"src/renderer/src/components/automations/automation-host-list-rows.test.ts": 419,
"src/renderer/src/components/automations/automation-host-recovery.test.ts": 51,
"src/renderer/src/components/automations/hosts/automation-host-list-rows.test.ts": 419,
"src/renderer/src/components/automations/automation-host-scale-gates.test.ts": 638,
"src/renderer/src/components/automations/automation-host-scheduler.test.ts": 439,
"src/renderer/src/components/automations/automation-legacy-schedule-editing.test.ts": 449,
"src/renderer/src/components/automations/automation-list-focus-recovery.test.ts": 48,
"src/renderer/src/components/automations/automation-list-row-identity.test.ts": 626,
"src/renderer/src/components/automations/automation-list-search.test.ts": 75,
"src/renderer/src/components/automations/hosts/automation-host-scheduler.test.ts": 439,
"src/renderer/src/components/automations/authoring/automation-legacy-schedule-editing.test.ts": 449,
"src/renderer/src/components/automations/automation-list-view.test.ts": 257,
"src/renderer/src/components/automations/automation-run-context.test.ts": 58,
"src/renderer/src/components/automations/automation-run-history-keyboard-navigation.test.ts": 434,
"src/renderer/src/components/automations/automation-run-open-target.test.ts": 442,
"src/renderer/src/components/automations/runs/automation-run-history-keyboard-navigation.test.ts": 434,
"src/renderer/src/components/automations/runs/automation-run-open-target.test.ts": 442,
"src/renderer/src/components/automations/automation-run-output-snapshot-equivalence.test.ts": 158,
"src/renderer/src/components/automations/automation-run-output-snapshot.test.ts": 96,
"src/renderer/src/components/automations/automation-setup-decision.test.ts": 58,
"src/renderer/src/components/automations/authoring/automation-setup-decision.test.ts": 58,
"src/renderer/src/components/automations/automation-usage-model.test.ts": 200,
"src/renderer/src/components/automations/external-automation-list-entries.test.ts": 57,
"src/renderer/src/components/automations/external-automation-scope-gating.test.ts": 67,
"src/renderer/src/components/automations/external/external-automation-scope-gating.test.ts": 67,
"src/renderer/src/components/automations/external-automation-scope-keys.test.ts": 53,
"src/renderer/src/components/automations/use-automation-host-catalog-readoption.test.tsx": 802,
"src/renderer/src/components/automations/use-automation-host-catalog.test.tsx": 920,
"src/renderer/src/components/automations/use-automation-list-focus-recovery.test.tsx": 229,
"src/renderer/src/components/automations/use-automation-list-search.test.tsx": 679,
"src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx": 6692,
"src/renderer/src/components/automations/use-automation-runs-dashboard.test.tsx": 854,
"src/renderer/src/components/automations/hosts/use-automation-host-catalog-readoption.test.tsx": 802,
"src/renderer/src/components/automations/hosts/use-automation-host-catalog.test.tsx": 920,
"src/renderer/src/components/automations/listing/use-automation-list-search.test.tsx": 679,
"src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx": 6692,
"src/renderer/src/components/automations/runs/use-automation-runs-dashboard.test.tsx": 854,
"src/renderer/src/components/automations/use-selected-automation-run-history.test.tsx": 2104,
"src/renderer/src/components/browser-favicon.test.tsx": 333,
"src/renderer/src/components/browser-pane/ClientHostedBrowserPagePane.dead-guest.test.tsx": 6219,
@@ -5135,15 +5123,9 @@
"src/renderer/src/components/mobile/WindowsFirewallNotice.test.tsx": 691,
"src/renderer/src/components/mobile/paired-mobile-devices.test.ts": 192,
"src/renderer/src/components/mobile/use-mobile-page-paired-devices.test.ts": 475,
"src/renderer/src/components/native-chat-launch-resume-decision.test.tsx": 1844,
"src/renderer/src/components/native-chat-resume-bulk-progress.test.tsx": 3261,
"src/renderer/src/components/native-chat-resume-failed-chat-watch.test.ts": 1954,
"src/renderer/src/components/native-chat-resume-failure-guidance.test.ts": 240,
"src/renderer/src/components/native-chat-resume-finished-run.test.tsx": 4173,
"src/renderer/src/components/native-chat-resume-on-restart-grouping.test.ts": 117,
"src/renderer/src/components/native-chat-resume-result-view.test.tsx": 2723,
"src/renderer/src/components/native-chat-resume-run.test.ts": 65,
"src/renderer/src/components/native-chat-resume-skipped-progress.test.tsx": 3009,
"src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-bulk-progress.test.tsx": 3261,
"src/renderer/src/components/native-chat-recovery/offers/native-chat-resume-failed-chat-watch.test.ts": 1954,
"src/renderer/src/components/native-chat-recovery/integration/native-chat-resume-finished-run.test.tsx": 4173,
"src/renderer/src/components/native-chat/messages/rows/NativeChatAgentMessageCard.test.tsx": 3700,
"src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTaskRun.test.tsx": 242,
"src/renderer/src/components/native-chat/tools/tasks/NativeChatBackgroundTasksStatus.test.tsx": 782,
@@ -5155,7 +5137,7 @@
"src/renderer/src/components/native-chat/attachments/chips/NativeChatImageAttachmentPreview.test.tsx": 2818,
"src/renderer/src/components/native-chat/media/visuals/NativeChatInlineVisual.link-placement.test.tsx": 2477,
"src/renderer/src/components/native-chat/prompts/NativeChatInteractiveCard.test.tsx": 2881,
"src/renderer/src/components/native-chat/usage/NativeChatInterruptedContinue.test.tsx": 2719,
"src/renderer/src/components/native-chat/viewport/scroll/NativeChatJumpToLatest.test.tsx": 477,
"src/renderer/src/components/native-chat/markdown/code/NativeChatMarkdown.code-wrap.test.tsx": 3123,
"src/renderer/src/components/native-chat/media/images/NativeChatMarkdown.image-preview.test.tsx": 4346,
@@ -5195,9 +5177,7 @@
"src/renderer/src/components/native-chat/selection-quotes/NativeChatSelectionQuote.test.tsx": 2370,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.approval-and-start-failure.test.tsx": 2922,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.availability-notice.test.tsx": 2764,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.history-read-state.test.tsx": 4919,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.host-outage.test.tsx": 3552,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.notice-card.test.tsx": 2911,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.refusal-notices.test.tsx": 3014,
"src/renderer/src/components/native-chat/surfaces/integration/NativeChatStructuredSession.test.tsx": 4459,
"src/renderer/src/components/native-chat/tools/tasks/NativeChatStructuredSessionStatus.test.tsx": 583,
@@ -5241,7 +5221,6 @@
"src/renderer/src/components/native-chat/composer/focus/native-chat-composer-reveal-focus.test.tsx": 526,
"src/renderer/src/components/native-chat/attachments/intake/native-chat-composer-workspace-file-drop.test.tsx": 1166,
"src/renderer/src/components/native-chat/drafts/native-chat-draft-retention.test.ts": 1415,
"src/renderer/src/components/native-chat/attachments/intake/native-chat-element-file-drop.test.tsx": 2057,
"src/renderer/src/components/native-chat/attachments/intake/native-chat-external-attachments-destination.test.tsx": 951,
"src/renderer/src/components/native-chat/links/actions/native-chat-file-link-existence.test.ts": 1937,
"src/renderer/src/components/native-chat/pane/actions/native-chat-header-ownership.test.tsx": 2796,
@@ -5256,7 +5235,6 @@
"src/renderer/src/components/native-chat/native-chat-new-rows-marker.test.tsx": 581,
"src/renderer/src/components/native-chat/pane/routing/native-chat-open-wake.test.ts": 1807,
"src/renderer/src/components/native-chat/pane/ownership/native-chat-owner-selectors.test.tsx": 525,
"src/renderer/src/components/native-chat/attachments/intake/native-chat-pane-file-drop.test.tsx": 439,
"src/renderer/src/components/native-chat/paste/native-chat-paste-routing.test.tsx": 2417,
"src/renderer/src/components/native-chat/session/terminal/delivery/native-chat-pending.test.ts": 273,
"src/renderer/src/components/native-chat/composer/editor/native-chat-prompt-document-text.test.ts": 219,
@@ -5495,10 +5473,7 @@
"src/renderer/src/components/right-sidebar/hosted-review/provider-actions/useHostedReviewStackParent.test.tsx": 288,
"src/renderer/src/components/right-sidebar/source-control/listing/useSourceControlSubmoduleStatus.test.tsx": 2076,
"src/renderer/src/components/settings/accounts/AccountsPane.owner-scope.test.tsx": 4057,
"src/renderer/src/components/skills/setup/AgentSkillSetupPanel.freshness.test.tsx": 15418,
"src/renderer/src/components/skills/setup/AgentSkillSetupPanel.plan-status.test.tsx": 23334,
"src/renderer/src/components/skills/setup/AgentSkillSetupPanel.remote-availability.test.tsx": 5937,
"src/renderer/src/components/skills/setup/AgentSkillSetupPanel.test.tsx": 2315,
"src/renderer/src/components/settings/agents/AgentsPane.test.tsx": 3230,
"src/renderer/src/components/settings/accounts/providers/AntigravityAccountsSection.test.tsx": 2722,
"src/renderer/src/components/settings/appearance/chat/AppearanceChatContrastControls.draft.test.tsx": 795,
@@ -5509,7 +5484,7 @@
"src/renderer/src/components/settings/chat/ChatPermissionSetting.test.tsx": 834,
"src/renderer/src/components/settings/chat/ChatSettingsSection.navigation.test.tsx": 2540,
"src/renderer/src/components/settings/chat/ChatSettingsSection.test.tsx": 2718,
"src/renderer/src/lib/skill-runtime-command.test.ts": 1670,
"src/renderer/src/lib/skills/runtime/skill-runtime-command.test.ts": 1670,
"src/renderer/src/components/settings/virtual-machines/recipes/EphemeralVmsPane.test.tsx": 1025,
"src/renderer/src/components/settings/accounts/sign-in/HostAccountSignInPrompt.test.tsx": 309,
"src/renderer/src/components/settings/agents/launch/HostAgentLaunchSettings.test.tsx": 7498,
@@ -5540,7 +5515,6 @@
"src/renderer/src/components/settings/developer-permissions/TerminalTccAttributionNotice.test.tsx": 401,
"src/renderer/src/components/settings/voice/VoiceMicrophoneSetting.test.tsx": 957,
"src/renderer/src/components/settings/voice/VoicePane.test.tsx": 1042,
"src/renderer/src/components/settings/voice/VoiceSpeechModelSection.test.tsx": 503,
"src/renderer/src/components/settings/accounts/sign-in/account-add-cancel-target.test.ts": 217,
"src/renderer/src/components/settings/accounts/usage/accounts-pane-opencode-credentials.test.ts": 519,
"src/renderer/src/lib/agent-session/launch/agent-settings-update-queue.test.ts": 249,
@@ -5690,22 +5664,18 @@
"src/renderer/src/components/sidebar/workspace-actions/parenting/worktree-parent-eligibility.test.ts": 68,
"src/renderer/src/components/sidebar/worktree-list/listing/worktree-sort-label-ordering.test.ts": 114,
"src/renderer/src/components/sidebar/wsl-host-offer-move.test.ts": 227,
"src/renderer/src/components/skills/SkillFreshnessUpdateDialog.test.tsx": 913,
"src/renderer/src/components/skills/SkillInstallDialog.test.tsx": 4429,
"src/renderer/src/components/skills/SkillInstallManagementDialog.test.tsx": 3300,
"src/renderer/src/components/skills/SkillSharedLinkRow.test.tsx": 817,
"src/renderer/src/components/skills/installation/SkillInstallManagementDialog.test.tsx": 3300,
"src/renderer/src/components/skills/sharing/SkillSharedLinkRow.test.tsx": 817,
"src/renderer/src/components/skills/SkillsPage.test.tsx": 3822,
"src/renderer/src/components/skills/skill-agent-filter.test.ts": 274,
"src/renderer/src/components/skills/skill-share-link.test.ts": 55,
"src/renderer/src/components/skills/skill-share-package-selection.test.ts": 49,
"src/renderer/src/components/skills/skills-filter.test.ts": 204,
"src/renderer/src/components/skills/catalog/skill-agent-filter.test.ts": 274,
"src/renderer/src/components/sparse/sparse-directory-entry-input.test.ts": 207,
"src/renderer/src/components/stats/usage-daily-chart.test.tsx": 333,
"src/renderer/src/components/stats/usage-overview-model.test.ts": 364,
"src/renderer/src/components/status-bar/ClaudeSwitcherMenu.owner-lifetime.test.tsx": 2317,
"src/renderer/src/components/status-bar/NativeChatResumeStatusSegment.test.tsx": 2452,
"src/renderer/src/components/status-bar/PortsStatusSegment.render-stability.test.tsx": 2161,
"src/renderer/src/components/status-bar/SkillUpdateStatusSegment.test.tsx": 594,
"src/renderer/src/components/status-bar/SshStatusSegment.large-host-list.test.tsx": 1838,
"src/renderer/src/components/status-bar/StatusBarUsageChangeNotices.test.tsx": 785,
"src/renderer/src/components/status-bar/UpdateStatusSegment.test.tsx": 2484,
@@ -6172,8 +6142,7 @@
"src/renderer/src/hooks/editor-external-watch-overflow.test.ts": 1023,
"src/renderer/src/hooks/editor-external-watch-selected-host.test.ts": 1988,
"src/renderer/src/hooks/editor-runtime-file-watch.test.ts": 58,
"src/renderer/src/hooks/installed-agent-skill-discovery-cache.test.ts": 53,
"src/renderer/src/hooks/installed-agent-skill-discovery.test.ts": 74,
"src/renderer/src/hooks/ipc-events/agent-status-pane-routing-index-retention.test.ts": 4878,
"src/renderer/src/hooks/ipc-events/agent-status-pending-retry-gate.test.ts": 466,
"src/renderer/src/hooks/ipc-events/agent-status-terminal-title-tab-write.test.ts": 2247,
@@ -6210,7 +6179,7 @@
"src/renderer/src/hooks/runtime-project-refresh-scheduler.test.ts": 65,
"src/renderer/src/hooks/shortcut-label-cache.test.tsx": 2021,
"src/renderer/src/hooks/unpaired-device-auth-notification.test.ts": 41,
"src/renderer/src/hooks/use-bundled-skill-install.test.tsx": 553,
"src/renderer/src/hooks/use-document-dark-theme.test.tsx": 350,
"src/renderer/src/hooks/use-list-multi-selection.test.tsx": 545,
"src/renderer/src/hooks/use-monaco-theme.test.tsx": 323,
@@ -6236,7 +6205,7 @@
"src/renderer/src/hooks/useEphemeralVmRecipeOptions.test.tsx": 415,
"src/renderer/src/hooks/useGitHubSlugMetadata.assignee-reuse.test.tsx": 233,
"src/renderer/src/hooks/useImmediateMutation.test.ts": 618,
"src/renderer/src/hooks/useInstalledAgentSkills.react.test.tsx": 2093,
"src/renderer/src/hooks/skills/discovery/useInstalledAgentSkills.react.test.tsx": 2093,
"src/renderer/src/hooks/useIpcEvents-agent-status-connection-attribution.test.ts": 5510,
"src/renderer/src/hooks/useIpcEvents-agent-status-hook-titles.test.ts": 5621,
"src/renderer/src/hooks/useIpcEvents-agent-status-pane-teardown.test.ts": 5268,
@@ -6268,7 +6237,7 @@
"src/renderer/src/hooks/useReadOnScreenAttention.mixed-workspace.test.ts": 1725,
"src/renderer/src/hooks/useReadOnScreenAttention.test.ts": 1915,
"src/renderer/src/hooks/useRetiredWorktreeNames.test.ts": 593,
"src/renderer/src/hooks/useSkillFreshness.test.tsx": 554,
"src/renderer/src/hooks/useUnreadDockBadge.test.ts": 2126,
"src/renderer/src/hooks/virtualized-hidden-row-measurement.test.ts": 199,
"src/renderer/src/hooks/worktree-change-refresh-queue.test.ts": 59,
@@ -6347,7 +6316,7 @@
"src/renderer/src/lib/browser/navigation/browser-link-profile-isolation.test.ts": 2511,
"src/renderer/src/lib/browser/palette/browser-page-palette-activation.test.ts": 1983,
"src/renderer/src/lib/browser/palette/browser-palette-page-entries.test.ts": 480,
"src/renderer/src/lib/bundled-skill-target.test.ts": 54,
"src/renderer/src/lib/skills/runtime/bundled-skill-target.test.ts": 54,
"src/renderer/src/lib/source-control/checks/check-run-details-log-normalization-performance.test.ts": 846,
"src/renderer/src/lib/source-control/checks/check-run-details-log-normalization.test.ts": 75,
"src/renderer/src/lib/claude-account-switch-sessions.test.ts": 782,
@@ -6378,15 +6347,12 @@
"src/renderer/src/runtime/hosts/platform/execution-host-facts.test.ts": 1796,
"src/renderer/src/lib/feature-education-telemetry.test.ts": 52,
"src/renderer/src/lib/feedback-image-attachments.test.ts": 557,
"src/renderer/src/lib/browser/documents/file-preview-link-open.test.ts": 2311,
"src/renderer/src/lib/file-search-selection.test.ts": 51,
"src/renderer/src/lib/find-query-bounds.test.ts": 45,
"src/renderer/src/lib/finished-agent-resume-resurrection.test.ts": 1872,
"src/renderer/src/lib/focus-terminal-tab-surface.split-focus.test.ts": 331,
"src/renderer/src/lib/foreground-terminal-tabs.test.ts": 55,
"src/shared/new-workspace/github-links.test.ts": 76,
"src/renderer/src/lib/work-items/github/github-source-runtime-context.test.ts": 62,
"src/shared/new-workspace/gitlab-links.test.ts": 56,
"src/renderer/src/lib/hook-command-delayed-delivery.test.ts": 1904,
"src/renderer/src/lib/host-chat-program.test.ts": 2419,
"src/renderer/src/lib/host-mirror-handle-gap-drain.test.ts": 1706,
@@ -6827,7 +6793,6 @@
"src/renderer/src/store/slices/editor/git/editor-git-status-reconciliation.test.ts": 870,
"src/renderer/src/store/slices/editor/tabs/editor-layout-owner-records.test.ts": 2006,
"src/renderer/src/store/slices/editor/markdown/editor-markdown-link-activation.test.ts": 953,
"src/renderer/src/store/slices/editor/markdown/editor-markdown-view-state.test.ts": 801,
"src/renderer/src/store/slices/editor/git/editor-open-diff.test.ts": 1987,
"src/renderer/src/store/slices/editor/tabs/editor-open-link-placement.test.ts": 1987,
"src/renderer/src/store/slices/editor/tabs/editor-preview-tab-setting.test.ts": 1952,
@@ -7996,7 +7961,7 @@
"tests/e2e/ai-vault-account-stream.unit.test.ts": 4506,
"tests/e2e/ai-vault-manual-name-clear.unit.test.ts": 21206,
"tests/e2e/automation-chat-reopen.unit.test.ts": 6262,
"tests/e2e/automation-save-fallback.unit.test.ts": 9065,
"tests/e2e/claude-agent-row-view.unit.test.ts": 1491,
"tests/e2e/codex-child-approval-activity-row.unit.test.ts": 14886,
"tests/e2e/completed-worker-retirement-resume.unit.test.ts": 38857,
@@ -8032,7 +7997,7 @@
"tests/e2e/host-agent-launch-preferences-work.unit.test.ts": 3882,
"tests/e2e/host-agent-launch-settings-hook-bookkeeping.unit.test.ts": 21972,
"tests/e2e/host-cold-park-remote-subscriber.unit.test.ts": 5314,
"tests/e2e/journal-restored-consumers.unit.test.ts": 33933,
"tests/e2e/launch-agent-background-session-remote.unit.test.ts": 1016,
"tests/e2e/launch-agent-in-new-tab-web-runtime.unit.test.ts": 14288,
"tests/e2e/linear-cli-recovery.unit.test.ts": 7592,
@@ -8044,7 +8009,7 @@
"tests/e2e/native-chat-rewind-boundary.unit.test.ts": 2977,
"tests/e2e/native-chat-ssh-transcript.unit.test.ts": 1166,
"tests/e2e/native-chat-startup-option-pickers.unit.test.ts": 9377,
"tests/e2e/native-chat-transcript-file-order.unit.test.ts": 1066,
"tests/e2e/native-chat-transcript-reasoning.unit.test.ts": 3341,
"tests/e2e/nested-agent-idle-owner.unit.test.ts": 2469,
"tests/e2e/omp-child-session-recovery.unit.test.ts": 2205,
@@ -106,6 +106,19 @@ function parseManifest(bundleDir) {
}
}
}
if (manifest.catalogs !== undefined && !Array.isArray(manifest.catalogs)) {
throw failure('manifest catalogs is not a list')
}
for (const catalog of manifest.catalogs ?? []) {
if (typeof catalog !== 'object' || catalog === null || typeof catalog.locale !== 'string') {
throw failure('manifest catalog entry has no locale')
}
assertSafeRelativePath(catalog.path)
if (typeof catalog.sha256 !== 'string' || !SHA256_PATTERN.test(catalog.sha256)) {
throw failure(`manifest catalog ${catalog.path} has no sha256 digest`)
}
assertInteger(catalog.byteLength, `catalogs[${catalog.path}].byteLength`)
}
if (!manifest.assets.some((asset) => asset.path === manifest.entrypoint)) {
throw failure(`manifest entrypoint ${manifest.entrypoint} is not one of its assets`)
}
@@ -126,6 +139,11 @@ function parseManifest(bundleDir) {
return manifest
}
// Assets go to the phone; catalogs stay on the host, which serves one on request.
function servedFiles(manifest) {
return [...manifest.assets, ...(manifest.catalogs ?? [])]
}
function listBundleFiles(directory, prefix = '') {
const found = []
for (const entry of readdirSync(directory, { withFileTypes: true })) {
@@ -164,7 +182,7 @@ function assertNoUnlistedFiles(bundleDir, manifest) {
const listed = new Set([
'manifest.json',
...darkBuildMarkerFileNames(),
...manifest.assets.map((asset) => asset.path),
...servedFiles(manifest).map((file) => file.path),
...brotliCopies(manifest).map((asset) => brotliPath(asset))
])
const strays = listBundleFiles(bundleDir).filter((path) => !listed.has(path))
@@ -180,7 +198,7 @@ function assertNoUnlistedFiles(bundleDir, manifest) {
function assertMobileWebBundleBuilt(bundleDir = MOBILE_WEB_BUNDLE_DIR) {
const manifest = parseManifest(bundleDir)
assertNoUnlistedFiles(bundleDir, manifest)
for (const asset of manifest.assets) {
for (const asset of servedFiles(manifest)) {
const assetPath = join(bundleDir, asset.path)
const size = statSize(bundleDir, asset.path)
if (size !== asset.byteLength) {
@@ -6,10 +6,11 @@ import process from 'node:process'
// TypeScript 7 is a native CLI; AST consumers still need the legacy JavaScript API.
import ts from 'typescript-api'
import { isTestOnlySourcePath } from '../../static-analysis/process-boundaries/test-only-source-path.mjs'
import { isVisibleObjectKey } from './localization-visible-object-keys.mjs'
const SOURCE_EXTENSIONS = new Set(['.ts', '.tsx', '.js', '.jsx', '.mts', '.cts'])
const SKIP_PATH_PARTS = new Set(['.git', 'dist', 'node_modules', 'out', '__snapshots__', 'assets'])
const LOCALIZATION_CALL_NAMES = new Set(['t', 'translate'])
const LOCALIZATION_CALL_NAMES = new Set(['t', 'translate', 'translateMain'])
const CLASS_PROPERTY_NAMES = new Set(['className', 'classNames'])
// Why: the children of these elements are CSS or code, never copy a translator should see.
const NON_COPY_JSX_ELEMENTS = new Set(['style', 'script'])
@@ -35,25 +36,6 @@ const USER_VISIBLE_JSX_ATTRIBUTES = new Set([
'toggleDescription',
'tooltip'
])
const USER_VISIBLE_OBJECT_KEYS = new Set([
'accessibilityHint',
'accessibilityLabel',
'ariaLabel',
'badge',
'description',
'emptyText',
'error',
'headerTitle',
'helperText',
'keywords',
'label',
'message',
'placeholder',
'subtitle',
'title',
'toggleDescription',
'tooltip'
])
const USER_VISIBLE_FUNCTION_NAMES = new Set([
'alert',
'confirm',
@@ -331,7 +313,7 @@ function isInsideNonCopyJsxElement(node) {
return Boolean(element && NON_COPY_JSX_ELEMENTS.has(element.openingElement.tagName.getText()))
}
function classifyStringNode(node) {
function classifyStringNode(node, includeNativeDialogFields = false) {
if (
hasAncestorObjectPropertyName(node, CLASS_PROPERTY_NAMES) ||
isInsideNonCopyJsxElement(node)
@@ -369,12 +351,15 @@ function classifyStringNode(node) {
}
const objectPropertyName = nearestObjectPropertyName(node)
if (objectPropertyName && !USER_VISIBLE_OBJECT_KEYS.has(objectPropertyName)) {
if (objectPropertyName && !isVisibleObjectKey(objectPropertyName, includeNativeDialogFields)) {
return undefined
}
const ancestorObjectPropertyName = nearestAncestorObjectPropertyName(node)
if (ancestorObjectPropertyName && !USER_VISIBLE_OBJECT_KEYS.has(ancestorObjectPropertyName)) {
if (
ancestorObjectPropertyName &&
!isVisibleObjectKey(ancestorObjectPropertyName, includeNativeDialogFields)
) {
return undefined
}
@@ -407,7 +392,12 @@ function areaForFile(relativePath) {
return `renderer/${parts[0] ?? 'root'}`
}
export function collectLocalizationCandidates(filePath, sourceText, root = process.cwd()) {
export function collectLocalizationCandidates(
filePath,
sourceText,
root = process.cwd(),
options = {}
) {
const sourceKind =
filePath.endsWith('.tsx') || filePath.endsWith('.jsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS
const sourceFile = ts.createSourceFile(
@@ -450,7 +440,7 @@ export function collectLocalizationCandidates(filePath, sourceText, root = proce
ts.isNoSubstitutionTemplateLiteral(node) ||
ts.isTemplateExpression(node)
) {
const kind = classifyStringNode(node)
const kind = classifyStringNode(node, options.includeNativeDialogFields)
if (kind) {
for (const part of stringParts(node)) {
pushReport(node, kind, part.text, part.dynamic)
@@ -521,6 +511,7 @@ function parseArgs(argv) {
allowlistPath: path.join('config', 'localization-coverage-allowlist.json'),
check: false,
format: 'summary',
includeNativeDialogFields: false,
outputPath: null,
sourceRoots: []
}
@@ -531,6 +522,8 @@ function parseArgs(argv) {
options.format = 'json'
} else if (arg === '--markdown') {
options.format = 'markdown'
} else if (arg === '--native-dialog-fields') {
options.includeNativeDialogFields = true
} else if (arg === '--check') {
options.check = true
} else if (arg === '--allowlist') {
@@ -616,7 +609,7 @@ export async function main(root = process.cwd(), argv = process.argv.slice(2)) {
for (const filePath of files) {
const sourceText = await fs.readFile(filePath, 'utf8')
reports.push(...collectLocalizationCandidates(filePath, sourceText, root))
reports.push(...collectLocalizationCandidates(filePath, sourceText, root, options))
}
if (options.check) {
@@ -0,0 +1,59 @@
import { describe, expect, it, vi } from 'vitest'
import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { collectLocalizationCandidates, main } from './audit-localization-coverage.mjs'
const path = '/repo/src/main/startup/dialog.ts'
const source = `
const options = {
message: translateMain('message', 'Translated message'),
detail: 'Untranslated detail',
buttons: ['Proceed', translateMain('cancel', 'Cancel')],
body: 'Untranslated body',
buttonLabel: 'Retry',
checkboxLabel: 'Remember choice'
}
`
describe('native dialog localization coverage', () => {
it('finds untranslated native dialog fields while ignoring translated copy', () => {
const candidates = collectLocalizationCandidates(path, source, '/repo', {
includeNativeDialogFields: true
})
expect(candidates.map(({ kind, text }) => [kind, text])).toEqual([
['object-property:detail', 'Untranslated detail'],
['object-property:buttons', 'Proceed'],
['object-property:body', 'Untranslated body'],
['object-property:buttonLabel', 'Retry'],
['object-property:checkboxLabel', 'Remember choice']
])
})
it('does not change the existing renderer scan by default', () => {
expect(collectLocalizationCandidates(path, source, '/repo')).toEqual([])
})
it('fails the opt-in check for a new native dialog literal', async () => {
const root = await mkdtemp(join(tmpdir(), 'orca-native-localization-'))
const report = vi.spyOn(console, 'error').mockImplementation(() => {})
try {
await mkdir(join(root, 'src'))
await writeFile(join(root, 'src', 'dialog.ts'), "const options = { detail: 'Raw detail' }")
await writeFile(join(root, 'allowlist.json'), '[]')
await expect(
main(root, [
'--check',
'--native-dialog-fields',
'--source-root',
'src',
'--allowlist',
'allowlist.json'
])
).resolves.toBe(1)
} finally {
report.mockRestore()
await rm(root, { recursive: true, force: true })
}
})
})
@@ -0,0 +1,33 @@
const USER_VISIBLE_OBJECT_KEYS = new Set([
'accessibilityHint',
'accessibilityLabel',
'ariaLabel',
'badge',
'description',
'emptyText',
'error',
'headerTitle',
'helperText',
'keywords',
'label',
'message',
'placeholder',
'subtitle',
'title',
'toggleDescription',
'tooltip'
])
const NATIVE_DIALOG_OBJECT_KEYS = new Set([
'detail',
'buttons',
'body',
'buttonLabel',
'checkboxLabel'
])
export function isVisibleObjectKey(name, includeNativeDialogFields) {
return (
USER_VISIBLE_OBJECT_KEYS.has(name) ||
(includeNativeDialogFields && NATIVE_DIALOG_OBJECT_KEYS.has(name))
)
}
@@ -32,7 +32,7 @@ import { View } from 'react-native'
import { GestureHandlerRootView } from 'react-native-gesture-handler'
import { MobileNativeChatQueuedMessages } from './src/session/native-chat/input/MobileNativeChatQueuedMessages'
import { MobileNativeChatComposer } from './src/session/native-chat/composer/MobileNativeChatComposer'
import { mobileQueuedMessageCards } from './src/session/mobile-structured-queued-message-cards'
import { mobileQueuedMessageCards } from './src/session/native-chat/input/mobile-structured-queued-message-cards'
import { activateMobileUiLocale, translate } from './src/i18n/mobile-i18n'
const [mode, locale] = location.hash.slice(1).split(':')
@@ -19,7 +19,7 @@ export function stageOrcadMobileWebBundle(outputDir, bundleDir = MOBILE_WEB_BUND
// The release template refuses the variable itself.
assertNoDarkOutputOfOffSwitches([bundleDir])
assertMobileWebBundleBuilt(bundleDir)
// The guard refuses unlisted files, so the tree is the manifest, its assets and a dark marker.
// The guard refuses unlisted files, so the tree is the manifest, its assets and catalogs, and a dark marker.
cpSync(bundleDir, join(outputDir, ...ORCAD_MOBILE_WEB_DIR.split('/')), { recursive: true })
}
@@ -18,7 +18,7 @@ const { sortJiraIssues } = await jiti.import(
'../../../../src/renderer/src/components/jira-issue-sorter.ts'
)
const { sortAutomationListViewItems } = await jiti.import(
'../../../../src/renderer/src/components/automations/automation-list-view.ts'
'../../../../src/renderer/src/components/automations/listing/automation-list-view.ts'
)
const automationLocale = 'en-US'
@@ -4,7 +4,7 @@ import { performance } from 'node:perf_hooks'
import { transform } from 'esbuild'
import { buildCounterbalancedSchedule } from '../measurement/counterbalanced-benchmark-schedule.mjs'
const path = 'src/renderer/src/components/skills/skill-source-inventory.ts'
const path = 'src/renderer/src/components/skills/catalog/skill-source-inventory.ts'
const arms = {}
for (const [name, source] of [
['baseline', readFileSync(0, 'utf8')],
@@ -102,7 +102,33 @@ export const VERIFY_CHECKS = [
'config/scripts/localization/source-extraction/audit-localization-coverage.mjs',
'--check'
],
inputs: ['src/renderer/src/', LOCALES]
inputs: [
'src/renderer/src/',
LOCALES,
'config/scripts/localization/source-extraction/audit-localization-coverage',
'config/scripts/localization/source-extraction/localization-visible-object-keys'
]
},
{
name: 'startup and worktree localization coverage',
args: [
'config/scripts/localization/source-extraction/audit-localization-coverage.mjs',
'--check',
'--native-dialog-fields',
'--source-root',
'src/main/startup',
'--source-root',
'src/shared/worktree',
'--allowlist',
'config/startup-worktree-localization-allowlist.json'
],
inputs: [
'src/main/startup/',
'src/shared/worktree/',
'config/scripts/localization/source-extraction/audit-localization-coverage',
'config/scripts/localization/source-extraction/localization-visible-object-keys',
'config/startup-worktree-localization-allowlist.json'
]
},
{
name: 'mobile localization',
@@ -145,7 +171,8 @@ export const VERIFY_CHECKS = [
'mobile/web-entry/',
'config/mobile-localization-coverage-allowlist.json',
'config/scripts/audit-localization-coverage',
'config/scripts/localization/source-extraction/audit-localization-coverage'
'config/scripts/localization/source-extraction/audit-localization-coverage',
'config/scripts/localization/source-extraction/localization-visible-object-keys'
]
},
{
@@ -18,6 +18,7 @@ export const LINT_STEPS = [
'check:test-file-runners',
'verify:localization-catalogs',
'verify:localization-coverage',
'verify:startup-worktree-localization-coverage',
'verify:mobile-localization',
'verify:mobile-localization-coverage',
'lint:ast-grep-gates',
@@ -27,6 +27,10 @@ import {
renderLiveReadLines,
renderStoreReadLines
} from './react-compiler-hazards.mjs'
import {
UNCOMPILED_LIST,
readListedFiles
} from '../../../../build-plugins/react-compiler-uncompiled-files.mjs'
// Runs React Compiler (analysis only, nothing is written) over the renderer so code that compiles
// today keeps compiling, and code that would change behavior once compiled can't be added.
@@ -34,8 +38,6 @@ import {
const SCAN_ROOT = 'src/renderer/src'
const BAILOUT_BASELINE = 'config/react-compiler-bailout-baseline.txt'
const HAZARD_BASELINE = 'config/react-compiler-hazard-baseline.txt'
// The build leaves these files uncompiled, so their hazards cannot run.
const UNCOMPILED_LIST = 'config/react-compiler-uncompiled-files.txt'
const COMMAND = 'pnpm check:react-compiler-compat-ratchet'
const NOT_SHIPPED =
/(?:^|\/)__(?:mocks|fixtures|tests)__\/|\.(?:test|spec|bench)\.[cm]?tsx?$|[.-]test-|[.-]fixtures?\.tsx?$/
@@ -101,18 +103,31 @@ function addTo(map, key, value) {
map.set(key, [...(map.get(key) ?? []), value])
}
// The build leaves these files uncompiled, so their hazards cannot run.
function readUncompiledFiles(root) {
const file = path.join(root, UNCOMPILED_LIST)
if (!fs.existsSync(file)) {
return new Set()
return fs.existsSync(path.join(root, UNCOMPILED_LIST))
? new Set(readListedFiles(UNCOMPILED_LIST, root))
: new Set()
}
// Why: the build matches the exact id, so `\`, `../`, a directory or another case would silently compile.
function isCanonicalFile(root, rel) {
try {
const file = path.join(root, rel)
return (
!rel.includes('\\') &&
path.posix.normalize(rel) === rel &&
fs.statSync(file).isFile() &&
fs.realpathSync.native(file) === path.join(fs.realpathSync.native(root), rel)
)
} catch {
return false
}
return new Set(
fs
.readFileSync(file, 'utf8')
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'))
)
}
/** Listed paths that name no renderer file; a renamed file would silently compile. */
export function findStaleUncompiledFiles(uncompiled, exists) {
return [...uncompiled].filter((rel) => !rel.startsWith(`${SCAN_ROOT}/`) || !exists(rel))
}
/** Virtualizer hooks plus every hook that returns one, followed through wrappers of wrappers. */
@@ -210,12 +225,14 @@ async function scanFile(rel, text, result) {
export async function scanRenderer(root = process.cwd()) {
const sources = [...readTrackedSources(root, [SCAN_ROOT], isScannedPath)]
const uncompiled = readUncompiledFiles(root)
const result = {
files: 0,
compiled: 0,
diagnostics: new Map(),
hazards: new Map(),
uncompiled: readUncompiledFiles(root),
uncompiled,
staleUncompiled: findStaleUncompiledFiles(uncompiled, (rel) => isCanonicalFile(root, rel)),
virtualizerHooks: collectVirtualizerHooks(sources),
liveReaders: collectLiveReaders(sources)
}
@@ -341,8 +358,15 @@ export async function main(root = process.cwd(), arg = undefined) {
)
return 0
}
for (const rel of scan.staleUncompiled) {
console.error(
`::error::${UNCOMPILED_LIST}: ${rel} is not a renderer file. ` +
'Point it at the renamed file, or remove it once the file is gone.'
)
}
const touched = listTouchedFiles(root)
const ok = [
scan.staleUncompiled.length === 0,
check(root, 'bailout(s)', BAILOUT_BASELINE, bailouts, scan.diagnostics, touched),
check(root, 'hazard(s)', HAZARD_BASELINE, hazards, scan.hazards, touched)
].every(Boolean)
@@ -36,6 +36,7 @@ const NODE_RUNTIME_INCLUDE = [
// Asserts an observer survives a forced collection; conservative retention would hide a lost one.
'config/scripts/test-runtime/dom/happy-dom-mutation-observer-retention.test.ts',
// These reach Node SQLite through a shared helper or a dynamic import, which the scan skips.
'src/main/agent-hooks/server/testing/providers/codex/server-codex-session-start.test.ts',
'src/main/claude/claude-transcript-catch-up.test.ts',
'src/main/claude/claude-transcript-duration.test.ts',
'tests/e2e/native-chat-startup-option-pickers.unit.test.ts',
@@ -136,7 +137,7 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/gitlab/gitlab-known-host-retirement.test.ts',
'src/main/window/main-window-updater-deferred-setup.test.ts',
'src/renderer/src/components/terminal-pane/host-state/terminal-pane-host-state-memo.test.ts',
'src/renderer/src/components/automations/use-automation-runs-dashboard-payload.test.tsx',
'src/renderer/src/components/automations/runs/use-automation-runs-dashboard-payload.test.tsx',
'src/main/native-chat/agent-session-journal/**/*.test.ts',
'src/main/native-chat/agent-session-wire/host/testing/structured-agent-session-terminal-writer-acquire.test.ts',
'src/main/runtime/agent-session/records/agent-session-conversation-name-store.test.ts',
@@ -168,7 +169,12 @@ const NODE_RUNTIME_INCLUDE = [
'src/main/claude/claude-agent-sdk-contract-pins.test.ts',
'config/scripts/orcad-distribution/server-bundle/profile-state-worker-smoke.test.mjs',
'config/scripts/desktop-distribution/runtime-verification/process-host-dev-rebuild.test.ts',
'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts'
'config/scripts/test-runtime/node-worker/vitest-node-runtime-pool.test.ts',
// Reopen the WAL-backed dismissal cache read-only through the row cache, which Bun on macOS cannot.
'src/main/runtime/push/notifications/mobile-notification-dismissal-store.test.ts',
'src/main/runtime/push/notifications/mobile-notification-dismissal-read-failure.test.ts',
'src/main/ipc/notifications-subject-retirement.test.ts',
'src/main/ipc/notifications-external-acknowledgement.test.ts'
]
/** `filters` limits the SQLite import scan to the tests a filtered CLI run can select. */
@@ -0,0 +1,26 @@
[
{
"filePath": "src/main/startup/main-process-quit.ts",
"kind": "object-property:message",
"text": "before-quit allowed for update install",
"dynamic": false,
"count": 1,
"reason": "Updater lifecycle diagnostics are not displayed as UI copy."
},
{
"filePath": "src/main/startup/main-process-quit.ts",
"kind": "object-property:message",
"text": "will-quit cleanup for update install; daemonTeardown=disconnect",
"dynamic": false,
"count": 1,
"reason": "Updater lifecycle diagnostics are not displayed as UI copy."
},
{
"filePath": "src/main/startup/profile-state-recovery-preflight.ts",
"kind": "object-property:message",
"text": "Invalid profile-state recovery launch.",
"dynamic": false,
"count": 1,
"reason": "Existing recovery detail is user-visible and remains untranslated; tracked in issue 32207."
}
]
+3 -1
View File
@@ -126,10 +126,12 @@ const bunProject = {
}
// Files whose state the per-file reset can undo share one worker's module cache instead of
// re-importing thousands of modules each. ORCA_VITEST_ISOLATE_EVERY_FILE=1 turns it off.
// Windows workers that keep native addons (process tree, ConPTY) across files die of heap
// corruption (0xC0000374); production code loads them lazily, so the file scan can't see them.
const runtimeProject = process.versions.bun ? bunProject : nodeProject
const nodeRuntimeFiles = new Set(nodeRuntimeInclude.map((file) => file.replaceAll('\\', '/')))
const sharedWorkerFiles =
process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1'
process.env.ORCA_VITEST_ISOLATE_EVERY_FILE === '1' || process.platform === 'win32'
? []
: filesSafeToShareWorker(
process.cwd(),
+1 -1
View File
@@ -22,7 +22,7 @@
1 src/renderer/src/components/sidebar/worktree-list/navigation/pending-reveal-inputs.ts # reads a passed-in copy
1 src/renderer/src/components/sidebar/worktree-list/navigation/use-pending-reveal.ts # reads a passed-in copy
2 src/renderer/src/components/sidebar/worktree-list/viewport/VirtualizedWorktreeViewport.tsx # reads a passed-in copy
2 src/renderer/src/components/skills/skill-install-workspace-choices.ts # reads a passed-in copy
2 src/renderer/src/components/skills/installation/skill-install-workspace-choices.ts # reads a passed-in copy
1 src/renderer/src/components/terminal-pane/links/files/terminal-worktree-path-link.ts # P5b-2 must clear: loosely typed state param
1 src/renderer/src/components/workspace-space/space-window-state.ts # reads a passed-in copy
1 src/renderer/src/hooks/composer-state/composer-source-state.ts # P5b-2 must clear: composer store snapshot
Binary file not shown.

Before

Width:  |  Height:  |  Size: 392 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 400 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 391 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 385 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 381 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 386 KiB

After

Width:  |  Height:  |  Size: 395 KiB

+1 -1
View File
@@ -53,5 +53,5 @@ pnpm dev:fresh [--keep] [--seed-from[=<profile dir>]] # temporary profile, rem
- Slow main-process rebuilds: set `ORCA_DEV_MAIN_SOURCEMAPS=0` before `pnpm dev` when you don't need main-process source maps.
- Renderer misbehaving in dev: set `ORCA_DEV_BUNDLED=0` to turn off bundled dev mode, and report it.
- Test passes alone but fails after others: add `// @orca-isolated-worker` to the file; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak.
- Test passes alone but fails after others: add `// @orca-isolated-worker` to the file; `ORCA_VITEST_ISOLATE_EVERY_FILE=1` isolates every file to confirm a leak. Windows always isolates every file, because native addons kept across files corrupt the heap.
- Slow typechecks: where supported, `pnpm tc` keeps incremental caches in `.cache/typecheck/`; delete it to force a fresh check.
+2 -4
View File
@@ -249,11 +249,9 @@ Associez-la à l'app de bureau pour surveiller et piloter vos agents depuis votr
- **Discord :** Rejoignez la communauté sur **[Discord](https://discord.gg/fzjDKHxv8Q)**.
- **Twitter / X :** Suivez **[@orca_build](https://x.com/orca_build)** pour les news et annonces.
- **WeChat :** Scannez pour rejoindre un groupe WeChat de la communauté Orca. Si un groupe est complet, rejoignez-en un autre.
- **WeChat :** Scannez pour rejoindre un groupe WeChat de la communauté Orca.
<img src="../assets/wechat-qr-group14.jpg" alt="QR code du groupe WeChat de la communauté Orca" width="160" />
<img src="../assets/wechat-qr-group15.jpg" alt="QR code du groupe WeChat de la communauté Orca" width="160" />
<img src="../assets/wechat-qr-group16.jpg" alt="QR code du groupe WeChat de la communauté Orca" width="160" />
<img src="../assets/wechat-qr.jpg" alt="QR code du groupe WeChat de la communauté Orca" width="160" />
- **Feedback &amp; idées :** On ship vite. Il manque quelque chose ? [Demandez une feature](https://github.com/stablyai/orca/issues).
- **Confidentialité :** Voir la [doc confidentialité &amp; télémétrie](https://www.onorca.dev/docs/telemetry) pour ce qu'Orca collecte en anonyme et comment désactiver la télémétrie.
+2 -4
View File
@@ -244,11 +244,9 @@ yay -S stably-orca-bin
- **Discord:** **[Discord](https://discord.gg/fzjDKHxv8Q)** 커뮤니티에 참여하세요.
- **Twitter / X:** 업데이트와 공지는 **[@orca_build](https://x.com/orca_build)** 를 팔로우하세요.
- **WeChat:** QR 코드를 스캔해 Orca 커뮤니티 WeChat 그룹에 참여하세요. 한 그룹이 가득 찼다면 다른 그룹에 참여하세요.
- **WeChat:** QR 코드를 스캔해 Orca 커뮤니티 WeChat 그룹에 참여하세요.
<img src="../assets/wechat-qr-group14.jpg" alt="Orca 커뮤니티 WeChat 그룹 QR 코드" width="160" />
<img src="../assets/wechat-qr-group15.jpg" alt="Orca 커뮤니티 WeChat 그룹 QR 코드" width="160" />
<img src="../assets/wechat-qr-group16.jpg" alt="Orca 커뮤니티 WeChat 그룹 QR 코드" width="160" />
<img src="../assets/wechat-qr.jpg" alt="Orca 커뮤니티 WeChat 그룹 QR 코드" width="160" />
- **피드백과 아이디어:** 우리는 빠르게 출시합니다. 필요한 기능이 있나요? [새 기능을 요청](https://github.com/stablyai/orca/issues)하세요.
- **개인정보 보호:** Orca가 수집하는 익명 사용 데이터와 수집 거부 방법은 [개인정보 및 텔레메트리 문서](https://www.onorca.dev/docs/telemetry)를 참고하세요.
+2 -4
View File
@@ -245,11 +245,9 @@ yay -S stably-orca-bin
- **Discord:** Присоединяйтесь к сообществу в **[Discord](https://discord.gg/fzjDKHxv8Q)**.
- **Twitter / X:** Подпишитесь на **[@orca_build](https://x.com/orca_build)**, чтобы узнавать об обновлениях и анонсах.
- **WeChat:** Отсканируйте QR-код, чтобы присоединиться к группе сообщества Orca в WeChat. Если одна группа заполнена, присоединяйтесь к другой.
- **WeChat:** Отсканируйте QR-код, чтобы присоединиться к группе сообщества Orca в WeChat.
<img src="../assets/wechat-qr-group14.jpg" alt="QR-код группы сообщества Orca в WeChat" width="160" />
<img src="../assets/wechat-qr-group15.jpg" alt="QR-код группы сообщества Orca в WeChat" width="160" />
<img src="../assets/wechat-qr-group16.jpg" alt="QR-код группы сообщества Orca в WeChat" width="160" />
<img src="../assets/wechat-qr.jpg" alt="QR-код группы сообщества Orca в WeChat" width="160" />
- **Отзывы и идеи:** Мы быстро выпускаем обновления. Чего-то не хватает? [Предложите новую возможность](https://github.com/stablyai/orca/issues).
- **Конфиденциальность:** В [документации о конфиденциальности и телеметрии](https://www.onorca.dev/docs/telemetry) описано, какие анонимные данные об использовании собирает Orca и как отказаться от их сбора.
+2 -4
View File
@@ -242,11 +242,9 @@ Ajanlarınızı telefonunuzdan izlemek ve yönlendirmek için masaüstü uygulam
- **Discord:** Topluluğa **[Discord](https://discord.gg/fzjDKHxv8Q)** üzerinden katılın.
- **Twitter / X:** Güncellemeler ve duyurular için **[@orca_build](https://x.com/orca_build)** hesabını takip edin.
- **WeChat:** Orca topluluğunun bir WeChat grubuna katılmak için karekodu okutun. Bir grup doluysa başka bir gruba katılabilirsiniz.
- **WeChat:** Orca topluluğunun bir WeChat grubuna katılmak için karekodu okutun.
<img src="../assets/wechat-qr-group14.jpg" alt="Orca topluluğunun WeChat grubu karekodu" width="160" />
<img src="../assets/wechat-qr-group15.jpg" alt="Orca topluluğunun WeChat grubu karekodu" width="160" />
<img src="../assets/wechat-qr-group16.jpg" alt="Orca topluluğunun WeChat grubu karekodu" width="160" />
<img src="../assets/wechat-qr.jpg" alt="Orca topluluğunun WeChat grubu karekodu" width="160" />
- **Geri bildirim ve fikirler:** Hızlı sürüm çıkarıyoruz. Eksik bulduğunuz bir şey mi var? [Yeni bir özellik isteyin](https://github.com/stablyai/orca/issues).
- **Gizlilik:** Orca'nın hangi anonim kullanım verisini topladığını ve bunu nasıl kapatacağınızı [gizlilik ve telemetri dokümanlarında](https://www.onorca.dev/docs/telemetry) bulabilirsiniz.
+2 -4
View File
@@ -242,11 +242,9 @@ yay -S stably-orca-bin
- **Discord:** 加入 **[Discord](https://discord.gg/fzjDKHxv8Q)** 社区。
- **Twitter / X:** 关注 **[@orca_build](https://x.com/orca_build)** 获取更新和公告。
- **微信:** 扫码加入 Orca 社区微信群。如果一个群已满,可以加入其他群。
- **微信:** 扫码加入 Orca 社区微信群。
<img src="../assets/wechat-qr-group14.jpg" alt="Orca 社区微信群二维码" width="160" />
<img src="../assets/wechat-qr-group15.jpg" alt="Orca 社区微信群二维码" width="160" />
<img src="../assets/wechat-qr-group16.jpg" alt="Orca 社区微信群二维码" width="160" />
<img src="../assets/wechat-qr.jpg" alt="Orca 社区微信群二维码" width="160" />
- **反馈与想法:** 我们发布很快。缺少什么功能?[提交功能请求](https://github.com/stablyai/orca/issues)。
- **隐私:** 查看[隐私与遥测文档](https://www.onorca.dev/docs/telemetry),了解 Orca 收集哪些匿名使用数据以及如何退出。
+35 -23
View File
@@ -18029,7 +18029,7 @@
"id": "native-chat-write-accepted",
"operation": "nativeChat.terminal-write",
"family": "nativeChat.terminal-write",
"sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"],
"sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"],
"schedules": [],
"steps": [
{
@@ -18065,7 +18065,7 @@
"id": "native-chat-write-rejected",
"operation": "nativeChat.terminal-write",
"family": "nativeChat.terminal-write",
"sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"],
"sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"],
"schedules": [],
"steps": [
{
@@ -18101,7 +18101,7 @@
"id": "native-chat-write-delivery-unknown",
"operation": "nativeChat.terminal-write",
"family": "nativeChat.terminal-write",
"sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"],
"sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"],
"schedules": [],
"steps": [
{
@@ -18133,7 +18133,7 @@
"id": "native-chat-write-clear-line",
"operation": "nativeChat.terminal-write",
"family": "nativeChat.terminal-write",
"sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"],
"sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"],
"schedules": [],
"steps": [
{
@@ -18169,7 +18169,7 @@
"id": "native-chat-write-typed-command",
"operation": "nativeChat.terminal-write",
"family": "nativeChat.terminal-write",
"sites": ["mobile/src/session/native-chat/mobile-native-chat-send.ts"],
"sites": ["mobile/src/session/native-chat/composer/mobile-native-chat-send.ts"],
"schedules": [],
"steps": [
{
@@ -18840,7 +18840,9 @@
"id": "structured-launch-unsupported",
"operation": "agentSession.structured-launch",
"family": "agentSession.structured-launch",
"sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"],
"sites": [
"mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts"
],
"schedules": [],
"steps": [
{
@@ -18870,7 +18872,9 @@
"id": "structured-launch-support-refused",
"operation": "agentSession.structured-launch",
"family": "agentSession.structured-launch",
"sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"],
"sites": [
"mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts"
],
"schedules": [],
"steps": [
{
@@ -18900,7 +18904,9 @@
"id": "structured-launch-created",
"operation": "agentSession.structured-launch",
"family": "agentSession.structured-launch",
"sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"],
"sites": [
"mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts"
],
"schedules": [],
"steps": [
{
@@ -18951,7 +18957,9 @@
"id": "structured-launch-definitive-refusal",
"operation": "agentSession.structured-launch",
"family": "agentSession.structured-launch",
"sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"],
"sites": [
"mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts"
],
"schedules": [],
"steps": [
{
@@ -19003,7 +19011,9 @@
"id": "structured-launch-replays-dropped-create",
"operation": "agentSession.structured-launch",
"family": "agentSession.structured-launch",
"sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"],
"sites": [
"mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts"
],
"schedules": [],
"steps": [
{
@@ -19443,7 +19453,7 @@
"id": "native-chat-stop-accepted",
"operation": "session.native-chat-stop",
"family": "session.native-chat-stop",
"sites": ["mobile/src/session/native-chat/use-mobile-native-chat-stop.ts"],
"sites": ["mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts"],
"schedules": [],
"steps": [
{
@@ -19504,7 +19514,7 @@
"id": "native-chat-stop-both-rejected",
"operation": "session.native-chat-stop",
"family": "session.native-chat-stop",
"sites": ["mobile/src/session/native-chat/use-mobile-native-chat-stop.ts"],
"sites": ["mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts"],
"schedules": [],
"steps": [
{
@@ -19562,7 +19572,7 @@
"id": "native-chat-stop-delivery-unknown",
"operation": "session.native-chat-stop",
"family": "session.native-chat-stop",
"sites": ["mobile/src/session/native-chat/use-mobile-native-chat-stop.ts"],
"sites": ["mobile/src/session/native-chat/composer/use-mobile-native-chat-stop.ts"],
"schedules": [],
"steps": [
{
@@ -19962,7 +19972,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -20039,7 +20049,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -20117,7 +20127,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -20152,7 +20162,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -20188,7 +20198,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -20224,7 +20234,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -20280,7 +20290,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -24889,7 +24899,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -24944,7 +24954,7 @@
"mobile/src/source-control/review/use-mobile-diff-review-comment-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-git-actions.ts",
"mobile/src/source-control/review/use-mobile-diff-review-send-actions.ts",
"mobile/src/session/native-chat/mobile-native-chat-stale-input.ts"
"mobile/src/session/native-chat/composer/mobile-native-chat-stale-input.ts"
],
"schedules": [],
"steps": [
@@ -25018,7 +25028,9 @@
"id": "structured-agent-session-created",
"operation": "agentSession.structured-launch",
"family": "agentSession.structured-create",
"sites": ["mobile/src/session/mobile-structured-agent-session-launch.ts"],
"sites": [
"mobile/src/session/native-chat/agent-session/mobile-structured-agent-session-launch.ts"
],
"schedules": [],
"steps": [
{
@@ -1,5 +1,5 @@
import { openMobileAgentHistoryChat } from './open-mobile-agent-history-chat'
import { mobileStructuredSessionOpenMessage } from '../session/mobile-structured-session-open-message'
import { mobileStructuredSessionOpenMessage } from '../session/native-chat/agent-session/mobile-structured-session-open-message'
import { prepareMobileHistoryResumeTarget } from './mobile-history-resume-target-preparation'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { View } from 'react-native'
@@ -4,7 +4,7 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import {
openMobileStructuredSession,
mobileStructuredSessionHref
} from '../session/open-mobile-structured-session'
} from '../session/native-chat/agent-session/open-mobile-structured-session'
/** Consume native opens and ambiguous failures; only an explicit pre-effect refusal resumes in a terminal. */
export async function openMobileAgentHistoryChat(args: {
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import { mobileStructuredSessionStatusFeed } from '../session/mobile-structured-session-status-feed'
import { mobileStructuredSessionStatusFeed } from '../session/native-chat/agent-session/mobile-structured-session-status-feed'
import type { AgentSessionConversationNames } from '../../../src/shared/agent-session/agent-session-conversation-names'
import { useForceReconnect } from '../transport/connection/host-client-hooks'
import { useWorkspaceClient } from '../worktree/use-workspace-client'
+17 -17
View File
@@ -4,6 +4,7 @@ import type { ConnectionState } from '../transport/connection/connection-state'
import type { HostWorktreeInfo } from '../worktree/home-worktree-info'
import { buildAgentList, type AgentListSection } from './agent-list-model'
import {
selectActiveAgents,
selectAgentsNeedingYou,
type AgentListInput,
type AgentListRow,
@@ -79,24 +80,22 @@ const statusView = (showWorkers: boolean, unreadOnly = false) => ({
describe('buildAgentList by status', () => {
it('buckets agents by what they ask of the user, newest first, and folds idle ones', () => {
const list = buildAgentList(
input({
mac: {
state: 'connected',
info: {
agents: entries([
agent('asking', 'waiting'),
agent('older-run', 'working', { stateStartedAt: NOW - 5 * MINUTE }),
agent('newer-run', 'working', { stateStartedAt: NOW - 2 * MINUTE }),
agent('finished', 'done'),
// Silent past the 30-minute freshness window.
agent('quiet', 'working', { updatedAt: NOW - 31 * MINUTE })
])
}
const host = input({
mac: {
state: 'connected',
info: {
agents: entries([
agent('asking', 'waiting'),
agent('older-run', 'working', { stateStartedAt: NOW - 5 * MINUTE }),
agent('newer-run', 'working', { stateStartedAt: NOW - 2 * MINUTE }),
agent('finished', 'done'),
// Silent past the 30-minute freshness window.
agent('quiet', 'working', { updatedAt: NOW - 31 * MINUTE })
])
}
}),
statusView(true)
)
}
})
const list = buildAgentList(host, statusView(true))
expect(shape(list.sections)).toEqual([
{ kind: 'needs-you', rows: ['asking'], workers: [[]], idle: undefined },
{
@@ -107,6 +106,7 @@ describe('buildAgentList by status', () => {
},
{ kind: 'done', rows: ['finished'], workers: [[]], idle: ['quiet'] }
])
expect(panes(selectActiveAgents(host))).toEqual(['asking', 'newer-run', 'older-run'])
})
it('nests workers under their coordinator and still lists the one that needs the user', () => {
+12
View File
@@ -159,6 +159,18 @@ export function selectAgentsNeedingYou(input: AgentListInput): AgentListRow[] {
.sort(byStatusThenRecent)
}
/** Live agents that need the user or are working, workers included: Feed's Active rows. */
export function selectActiveAgents(input: AgentListInput): AgentListRow[] {
return input.hosts
.flatMap((host) => everyRow(hostAgents(input, host.id).roots))
.filter((row) => {
const group = agentStatusGroup(row.dotState)
return !row.stale && (group === 'needs-you' || group === 'working')
})
.map(asTopLevel)
.sort(byStatusThenRecent)
}
export function countAgentsNeedingYouByHost(
rows: readonly AgentListRow[]
): Readonly<Record<string, number>> {
+9 -1
View File
@@ -22,6 +22,8 @@ type MobileStateViewProps = {
loading?: boolean
/** Keeps the content centred above a floating bottom bar. */
bottomInset?: number
/** Full-width content under the message, such as a list of choices. */
children?: ReactNode
}
/** Every screen's loading, empty, no-match, error and offline state: icon, title, one sentence, one action. */
@@ -33,7 +35,8 @@ export function MobileStateView({
details,
action,
loading = false,
bottomInset = 0
bottomInset = 0,
children
}: MobileStateViewProps) {
useMobileColorScheme()
return (
@@ -49,6 +52,7 @@ export function MobileStateView({
{message ? <Text style={styles.message}>{message}</Text> : null}
{details ? <MobileStateDetails details={details} /> : null}
{action ? <MobileStateButton label={action.label} onPress={action.onPress} /> : null}
{children ? <View style={styles.children}>{children}</View> : null}
</View>
)
}
@@ -187,6 +191,10 @@ export function MobileNoMatchState({
}
const styles = themedStyleSheet(() => ({
children: {
alignSelf: 'stretch',
marginTop: spacing.md
},
state: {
flex: 1,
alignItems: 'center',
@@ -64,6 +64,7 @@ vi.mock('../host-screen/host-list-queries', () => ({
import '../transport/hosts/host-descriptor-store'
import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes'
import { markRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity'
import '../../../src/shared/execution-host'
import type { ExecutionHostId } from '../../../src/shared/execution-host'
@@ -194,6 +195,108 @@ describe('NewWorktreeModal project targets', () => {
).toBe('/srv/orca')
})
it("offers only the folder host's copy of a repo when opened from a folder", async () => {
const serverRepo = { ...repos[0]!, path: '/srv/orca' }
const listing = (listed: unknown[]) =>
vi.fn((method: string) =>
method === 'repo.list' ? replied({ repos: listed }) : new Promise<never>(() => {})
)
await act(async () => {
renderer = create(
createElement(NewWorktreeModal, {
visible: true,
client: requestsOnly(listing(repos)),
serverClients: new Map<ExecutionHostId, RpcClient>([
['runtime:env-1', requestsOnly(listing([serverRepo]))]
]),
hostId: 'host-1',
onCreated: () => {},
onClose: () => {},
openExternalUrl: () => {},
folderLaunch: {
repoId: 'repo-1',
executionHostId: 'runtime:env-1',
name: 'payments',
parentWorkspace: 'folder:f-1',
submit: { begin: () => null, presenting: () => true }
}
})
)
})
await flushUpdates()
// The desktop's same-id repo is not offered: its store doesn't hold this folder.
expect(pickerItems(renderer, 'Run on').map((item) => item.detail)).toEqual(['/srv/orca'])
expect(runTargetPicker(renderer).props.selectedId).toBe('runtime:env-1')
})
async function submitFromFolder(createReply: () => Promise<RpcResponse>) {
const serverRepo = { ...repos[0]!, path: '/srv/orca' }
const server = requestsOnly(
vi.fn((method: string) =>
method === 'repo.list'
? replied({ repos: [serverRepo] })
: method === 'worktree.create'
? createReply()
: Promise.reject(new Error(`unexpected ${method}`))
)
)
const settle = vi.fn()
await act(async () => {
renderer = create(
createElement(NewWorktreeModal, {
visible: true,
client: requestsOnly(() => new Promise<never>(() => {})),
serverClients: new Map<ExecutionHostId, RpcClient>([['runtime:env-1', server]]),
hostId: 'host-1',
onCreated: () => {},
onClose: () => {},
openExternalUrl: () => {},
folderLaunch: {
repoId: 'repo-1',
executionHostId: 'runtime:env-1',
name: 'payments',
parentWorkspace: 'folder:f-1',
submit: { begin: () => ({ settle }), presenting: () => true }
}
})
)
})
await flushUpdates()
const form = renderer.root.find((node) => typeof node.props.onCreate === 'function')
await act(async () => form.props.onCreate())
await flushUpdates()
const creates = vi
.mocked(server.sendRequest)
.mock.calls.filter(([method]) => method === 'worktree.create')
return { creates: creates.map(([, params]) => params), settle }
}
it('creates from a folder attached to that folder, on its host', async () => {
const { creates, settle } = await submitFromFolder(() =>
replied({ worktree: { id: 'repo-1::/srv/w/payments', displayName: 'payments' } })
)
expect(creates).toEqual([
expect.objectContaining({
repo: 'id:repo-1',
parentWorkspace: 'folder:f-1',
parentWorkspaceOrigin: 'manual'
})
])
expect(settle).toHaveBeenCalledWith('created')
})
it("doesn't try another name when a folder create's reply is lost", async () => {
const { creates, settle } = await submitFromFolder(() =>
Promise.reject(markRpcDeliveryUnknown(new Error('connection lost')))
)
expect(creates).toHaveLength(1)
expect(settle).toHaveBeenCalledWith('uncertain')
})
it('ignores a stale repo list after the client changes', async () => {
let resolveOldList: ((value: unknown) => void) | undefined
const oldList = new Promise((resolve) => {
+30 -4
View File
@@ -1,4 +1,4 @@
import { useMemo, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { Keyboard } from 'react-native'
import { getComposerRepoWorktreeBranches } from '../../../src/shared/composer-branch-selection'
import { getRepoExecutionHostId, parseExecutionHostId } from '../../../src/shared/execution-host'
@@ -71,14 +71,20 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) {
existingWorktrees,
openExternalUrl,
onCreated,
onClose
onClose,
folderLaunch
} = props
const { repos, allRepos, selectedRepo, setSelectedRepo, loading, loadError, retryLoad } =
useNewWorkspaceRepositories({
client: desktopClient,
serverClients,
hostId,
visible
visible,
...(folderLaunch
? {
initialRepo: { id: folderLaunch.repoId, executionHostId: folderLaunch.executionHostId }
}
: {})
})
// Route picked-repo operations to its host; desktop settings/accounts stay on desktop.
const repoServer = selectedRepo ? serverOf(selectedRepo) : undefined
@@ -126,6 +132,14 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) {
worktreeBranches: selectedRepoWorktreeBranches,
onError: setError
})
// The folder's name, seeded once per opening; the user's edits stand.
const seededFolderName = useRef(false)
useEffect(() => {
if (folderLaunch && !seededFolderName.current) {
seededFolderName.current = true
composer.setName(folderLaunch.name)
}
}, [composer, folderLaunch])
const selectedRepoIsGit = selectedRepo ? selectedRepo.kind !== 'folder' : true
useWorktreeCreateBasePrefetch({
client: visible ? client : null,
@@ -179,7 +193,19 @@ function NewWorktreeModalContent(props: NewWorktreeModalProps) {
setNote((current) => (current === note ? '' : current))
onCreated(worktreeId, name, warning, repoServer)
},
onClose
onClose,
...(folderLaunch
? {
folderLaunch: {
...folderLaunch.submit,
executionHostId: folderLaunch.executionHostId,
parent: {
parentWorkspace: folderLaunch.parentWorkspace,
parentWorkspaceOrigin: 'manual' as const
}
}
}
: {})
})
const sourceAvailability: SmartModeAvailabilityInput = {
@@ -0,0 +1,22 @@
import { translate } from '../i18n/mobile-i18n'
/** A create whose reply was lost, or whose resend was refused: it may exist, so another could be a second one. */
export function uncertainCreateMessage(inFolder: boolean): string {
return inFolder
? translate(
'components.newWorkspaceCreateSubmit.uncertainFolderCreate',
'This worktree may have been created. Check the folder before creating another.'
)
: translate(
'components.newWorkspaceCreateSubmit.uncertainCreate',
'This workspace may have been created. Check your workspaces before creating another.'
)
}
/** The folder screen still owns a create for this repository. */
export function folderCreateBusyMessage(): string {
return translate(
'components.newWorkspaceCreateSubmit.folderCreateBusy',
'A worktree in this repository is still being created or checked. It shows in the folder once it lands.'
)
}
@@ -18,6 +18,30 @@ export type MobileWorkspaceRepo = Pick<SharedRepo, 'id' | 'displayName' | 'path'
>
>
/** Opened from a folder's empty state: that repo and name, created attached to the folder. */
export type NewWorktreeFolderLaunch = {
repoId: string
/** The repo's host, so a same-id copy on another host isn't picked. */
executionHostId: ExecutionHostId
name: string
/** The folder's workspace key, `folder:<id>`. */
parentWorkspace: string
submit: NewWorktreeFolderSubmit
}
/** A folder's create, kept from admission until its outcome is known. */
export type NewWorktreeFolderSubmission = {
settle: (outcome: 'created' | 'uncertain' | 'failed' | 'cancelled') => void
}
/** How the folder screen owns its composer's creates. */
export type NewWorktreeFolderSubmit = {
/** Admits a create for the picked repo before anything is sent; null while another is out for it. */
begin: (repo: MobileWorkspaceRepo) => NewWorktreeFolderSubmission | null
/** False once the folder screen is left: the create runs on, without haptics. */
presenting: () => boolean
}
export type NewWorktreeModalProps = {
visible: boolean
client: RpcClient | null
@@ -37,6 +61,7 @@ export type NewWorktreeModalProps = {
executionHost?: ExecutionHostId
) => void
onClose: () => void
folderLaunch?: NewWorktreeFolderLaunch
}
export type SetupRunPolicy = 'ask' | 'run-by-default' | 'skip-by-default'
@@ -3,7 +3,9 @@ import { useRef, useState, type Dispatch, type SetStateAction } from 'react'
import type { PersistedTrustedOrcaHooks } from '../../../src/shared/orca-yaml-hook-types'
import type { RetiredNameRegistry } from '../../../src/shared/worktree/retired-name-registry'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import { folderCreateBusyMessage, uncertainCreateMessage } from './new-workspace-create-copy'
import { triggerError, triggerSuccess } from '../platform/haptics'
import type { WorktreeCreateParent } from '../tasks/worktree-create-retry'
import { createBlankWorkspace } from '../tasks/blank-workspace-create'
import { isMobileTuiAgentEnabled } from '../tasks/mobile-tui-agents'
import {
@@ -24,7 +26,14 @@ import {
type NewWorktreeAgentOption,
type NewWorktreeRuntimeSettings
} from './new-worktree-agent-selection'
import type { MobileWorkspaceRepo, SetupRunPolicy } from './new-worktree-modal-types'
import type {
MobileWorkspaceRepo,
NewWorktreeFolderSubmission,
NewWorktreeFolderSubmit,
SetupRunPolicy
} from './new-worktree-modal-types'
import { getRepoExecutionHostId, type ExecutionHostId } from '../../../src/shared/execution-host'
import { isRpcDeliveryUnknown } from '../transport/rpc/rpc-delivery-ambiguity'
import type { OrcaHookTrustPrompt } from './OrcaHookTrustDrawer'
import type { NewWorktreeDrawerView } from './use-new-worktree-drawer-navigation'
import { getSuggestedCreatureName } from './worktree-name-suggestion'
@@ -65,6 +74,11 @@ export function useNewWorkspaceCreateSubmit(args: {
setError: Dispatch<SetStateAction<string>>
onCreated: (worktreeId: string, name: string, warning?: string) => void
onClose: () => void
/** Opened from a folder: creates on that folder's host, attached to it, owned by the folder screen. */
folderLaunch?: NewWorktreeFolderSubmit & {
executionHostId: ExecutionHostId
parent: WorktreeCreateParent
}
}): {
creating: boolean
setupTrustPrompt: OrcaHookTrustPrompt | null
@@ -86,7 +100,20 @@ export function useNewWorkspaceCreateSubmit(args: {
createInFlightRef.current = true
setCreating(true)
args.setError('')
const folder = args.folderLaunch
// Admitted for the repo actually picked, before anything is sent; the folder screen owns it until it settles.
const admission = folder
? getRepoExecutionHostId(selectedRepo) === folder.executionHostId
? folder.begin(selectedRepo)
: null
: undefined
const presenting = (): boolean => folder?.presenting() ?? true
let outcome: Parameters<NewWorktreeFolderSubmission['settle']>[0] = 'cancelled'
try {
if (admission === null) {
args.setError(folderCreateBusyMessage())
return
}
if (args.sshGate.requiresConnection) {
args.setError(`Connect ${selectedRepo.displayName} before creating a workspace.`)
return
@@ -178,7 +205,8 @@ export function useNewWorkspaceCreateSubmit(args: {
agentLaunchSupported: args.getAgentLaunchSupport(),
branchIntentSupported: args.getBranchIntentSupport(
selection.kind === 'branch' && selection.reuse ? 'open-existing-v2' : 'create-new'
)
),
parent: folder?.parent
})
: await createBlankWorkspace({
client,
@@ -189,20 +217,43 @@ export function useNewWorkspaceCreateSubmit(args: {
comment: trimmedNote,
setupDecision,
worktreeCreateIdempotency: args.getWorktreeCreateCutoverSupport(),
agentLaunchSupported: args.getAgentLaunchSupport()
agentLaunchSupported: args.getAgentLaunchSupport(),
parent: folder?.parent
})
if ('error' in result) {
triggerError()
// Refused on a resend after a lost reply: the first send may have created it.
outcome = result.replayed ? 'uncertain' : 'failed'
if (outcome === 'uncertain') {
// Not a failure to retry: creating again could make a second one.
args.setError(uncertainCreateMessage(folder !== undefined))
return
}
if (presenting()) {
triggerError()
}
args.setError(result.error)
return
}
triggerSuccess()
outcome = 'created'
if (presenting()) {
triggerSuccess()
}
args.onClose()
args.onCreated(result.worktreeId, result.name, result.warning)
} catch (error) {
triggerError()
// A lost reply may still have created it.
outcome = isRpcDeliveryUnknown(error) ? 'uncertain' : 'failed'
if (folder && outcome === 'uncertain') {
// The folder screen refreshes and holds it until its list shows it; sending again could create a second one.
args.setError(uncertainCreateMessage(true))
return
}
if (presenting()) {
triggerError()
}
args.setError(error instanceof Error ? error.message : 'Failed to create workspace')
} finally {
admission?.settle(outcome)
createInFlightRef.current = false
setCreating(false)
}
@@ -0,0 +1,74 @@
import { act } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { ExecutionHostId } from '../../../src/shared/execution-host'
import { FakeSession } from '../transport/connection/mobile-endpoint-supervisor-test-fakes'
import { hookMount, settleQueryNotifications } from '../test-support/rpc-recording/hook-mount'
import type { MobileWorkspaceRepo } from './new-worktree-modal-types'
import { useNewWorkspaceRepositories } from './use-new-workspace-repositories'
vi.mock('react-native', () => ({ AppState: {} }))
const servers = vi.hoisted(() => {
const state: { repos: ReadonlyMap<string, unknown[]> } = { repos: new Map() }
return state
})
vi.mock('../worktree/use-server-repos', () => ({ useServerRepos: () => servers.repos }))
vi.mock('../worktree/use-last-visited-worktree-repo', () => ({
useLastVisitedWorktreeRepoId: () => ({ loaded: true, repoId: 'api' })
}))
const SERVER: ExecutionHostId = 'runtime:env-1'
const repo = (executionHostId?: ExecutionHostId): MobileWorkspaceRepo => ({
id: 'api',
displayName: 'api',
path: '/src/api',
kind: 'git',
...(executionHostId ? { executionHostId } : {})
})
function desktopListing(repos: MobileWorkspaceRepo[]) {
const client = new FakeSession('connected')
client.sendRequest.mockResolvedValue({
id: '1',
ok: true,
result: { repos },
_meta: { runtimeId: 'r' }
})
return client
}
let mounted: ReturnType<typeof hookMount> | null = null
afterEach(async () => {
await mounted?.unmount()
mounted = null
servers.repos = new Map()
})
describe('useNewWorkspaceRepositories initial repo', () => {
it.each([
{ order: 'desktop first', desktopFirst: true },
{ order: 'server first', desktopFirst: false }
])(
'picks the named host’s copy of a repo id two hosts share ($order)',
async ({ desktopFirst }) => {
const client = desktopListing(desktopFirst ? [repo()] : [])
let picked: MobileWorkspaceRepo | null = null
mounted = hookMount(() => {
picked = useNewWorkspaceRepositories({
client,
hostId: 'host-1',
visible: true,
initialRepo: { id: 'api', executionHostId: SERVER }
}).selectedRepo
})
mounted.mount()
await settleQueryNotifications()
// The desktop's same-id repo must not stand in while the server's listing is on its way.
expect(picked).toBeNull()
servers.repos = new Map([[SERVER, [repo(SERVER)]]])
act(() => mounted?.update())
await settleQueryNotifications()
expect(picked).toMatchObject({ id: 'api', executionHostId: SERVER })
}
)
})
@@ -1,6 +1,6 @@
import { useEffect, useMemo, useState } from 'react'
import { useQueryClient } from '@tanstack/react-query'
import type { ExecutionHostId } from '../../../src/shared/execution-host'
import { getRepoExecutionHostId, type ExecutionHostId } from '../../../src/shared/execution-host'
import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import { cachedHostRepos } from '../host-screen/host-list-queries'
import { listHostRepos } from '../worktree/server-repos'
@@ -21,6 +21,8 @@ export function useNewWorkspaceRepositories(args: {
serverClients?: ReadonlyMap<ExecutionHostId, RpcClient>
hostId?: string
visible: boolean
/** Picked once it is listed, in place of the last visited repo. */
initialRepo?: { id: string; executionHostId: ExecutionHostId }
}): {
repos: MobileWorkspaceRepo[]
allRepos: MobileWorkspaceRepo[]
@@ -31,7 +33,7 @@ export function useNewWorkspaceRepositories(args: {
loadError: string | null
retryLoad: () => void
} {
const { client, serverClients = NO_SERVER_CLIENTS, hostId, visible } = args
const { client, serverClients = NO_SERVER_CLIENTS, hostId, visible, initialRepo } = args
const queryClient = useQueryClient()
// The host list's repos, so the form opens with them while repo.list answers.
const [initialRepos] = useState(() => cachedHostRepos<MobileWorkspaceRepo>(queryClient, hostId))
@@ -51,7 +53,15 @@ export function useNewWorkspaceRepositories(args: {
: [...desktopRepos, ...[...serverRepos.values()].flat()],
[desktopRepos, serverRepos]
)
const repos = useMemo(() => getNewWorkspaceDialogEligibleRepos(allRepos), [allRepos])
const initialRepoId = initialRepo?.id
const initialRepoHost = initialRepo?.executionHostId
// Opened for one host's folder: every picker offers only that host, whose store holds the folder.
const repos = useMemo(() => {
const eligible = getNewWorkspaceDialogEligibleRepos(allRepos)
return initialRepoHost
? eligible.filter((repo) => getRepoExecutionHostId(repo) === initialRepoHost)
: eligible
}, [allRepos, initialRepoHost])
// Derive the pick so it follows updated listings and disappears when its host stops listing it.
const selectedRepo = useMemo(
() => refreshMobileNewWorkspaceDialogSelectedRepo(repos, pickedRepo),
@@ -59,7 +69,26 @@ export function useNewWorkspaceRepositories(args: {
)
useEffect(() => {
if (!visible || !lastVisitedRepo.loaded || selectedRepo || repos.length === 0) {
if (!visible || selectedRepo || !initialRepoId) {
return
}
// Waits for its host's listing: a same-id repo on another host is a different repo.
const initial = repos.find(
(repo) => repo.id === initialRepoId && getRepoExecutionHostId(repo) === initialRepoHost
)
if (initial) {
setSelectedRepo(initial)
}
}, [initialRepoHost, initialRepoId, repos, selectedRepo, visible])
useEffect(() => {
if (
!visible ||
initialRepoId ||
!lastVisitedRepo.loaded ||
selectedRepo ||
repos.length === 0
) {
return
}
const preferredRepoId = resolveNewWorkspaceDialogRepoId({
@@ -70,7 +99,7 @@ export function useNewWorkspaceRepositories(args: {
if (preferredRepo) {
setSelectedRepo(preferredRepo)
}
}, [lastVisitedRepo.loaded, lastVisitedRepo.repoId, repos, selectedRepo, visible])
}, [initialRepoId, lastVisitedRepo.loaded, lastVisitedRepo.repoId, repos, selectedRepo, visible])
useEffect(() => {
if (!visible || !client) {
@@ -37,6 +37,8 @@ export const dictationSetupSchema = z.looseObject({
dictationHoldToRecord: salvagedOptional('dictationHoldToRecord', z.boolean()),
// Absent from older hosts, which remove no fillers either; the phone then keeps them on, the host default.
removeFillerWords: salvagedOptional('removeFillerWords', z.boolean()),
// Absent from older hosts, which stop after a minute; the shared reader maps absent and unknown to that.
stopAfterSilenceSeconds: salvagedOptional('stopAfterSilenceSeconds', z.number().nullable()),
// Absent from older hosts, which spell nothing; malformed entries are dropped.
dictationTerms: salvagedOptional(
'dictationTerms',
@@ -4,6 +4,7 @@ import type { RpcClient } from '../transport/rpc/rpc-client-contract'
import type { MobileDictationAwayTarget } from './mobile-dictation-away-insert'
import type { MobileDictationLiveText } from './use-mobile-dictation-announcements'
import type { DictationTerm } from '../../../src/shared/dictation-dictionary'
import type { StopAfterSilenceSeconds } from '../../../src/shared/dictation-silence-stop'
export type MobileDictationHostToast = { message: string; open?: () => void }
@@ -21,6 +22,7 @@ export type MobileDictationOwner = {
// The target tab's pane key, for a screen still in the stack to switch back to it.
readonly paneKey: string | undefined
readonly dictationMode: string | undefined
readonly silenceSeconds: StopAfterSilenceSeconds
readonly removeFillerWords: boolean
// The computer's terms for this worktree, for words the phone recognizes itself.
readonly dictationTerms: readonly DictationTerm[] | undefined
@@ -7,6 +7,7 @@ import { useClipboardWriter } from '../platform/clipboard'
import { dictationFailureMessage, isDictationSetupRequiredError } from './mobile-dictation-setup'
import { useMobileDictationHaptics } from './use-mobile-dictation-haptics'
import { useMobileDictationSilenceStop } from './use-mobile-dictation-silence-stop'
import { DEFAULT_STOP_AFTER_SILENCE_SECONDS } from '../../../src/shared/dictation-silence-stop'
import { insertMobileDictationAway } from './mobile-dictation-away-insert'
import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-copy'
import { dictationAwayCopy } from './mobile-dictation-away-copy'
@@ -145,7 +146,14 @@ export function MobileDictationHostProvider({ children }: { children: ReactNode
onAudioLimitReached: () => say(nativeChatDictationCopy.stoppedAtCloudLimit())
})
const stop = useMobileDictationHaptics(dictation)
useMobileDictationSilenceStop(dictation, owner?.dictationMode, stop, (message) => say(message))
useMobileDictationSilenceStop(
dictation,
owner?.dictationMode,
// Off is null, so only a missing owner takes the default.
owner ? owner.silenceSeconds : DEFAULT_STOP_AFTER_SILENCE_SECONDS,
stop,
(message) => say(message)
)
// Screens subscribe to the live dictation; the host's context only changes when its owner or pill does.
const liveRef = useRef<UseMobileDictationResult>(dictation)
@@ -14,9 +14,10 @@ export const nativeChatDictationCopy = {
'session.useNativeChatDictation.stoppedAtCloudLimit',
'Dictation stopped at the 10-minute cloud limit.'
),
stoppedAfterSilence: () =>
stoppedAfterSilence: (seconds: number) =>
translate(
'session.useNativeChatDictation.stoppedAfterSilence',
'Stopped after a minute of silence'
'session.useNativeChatDictation.stoppedAfterSilenceSeconds',
'Stopped after {{seconds}} seconds of silence',
{ seconds }
)
}
@@ -1,5 +1,8 @@
import { useEffect, useEffectEvent } from 'react'
import { watchDictationSilence } from '../../../src/shared/dictation-silence-stop'
import {
watchDictationSilence,
type StopAfterSilenceSeconds
} from '../../../src/shared/dictation-silence-stop'
import type { UseMobileDictationResult } from '../hooks/mobile-dictation-session-state'
import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-copy'
@@ -7,20 +10,23 @@ import { nativeChatDictationCopy } from './mobile-session-native-chat-dictation-
export function useMobileDictationSilenceStop(
dictation: Pick<UseMobileDictationResult, 'isRecording' | 'meter'>,
dictationMode: string | undefined,
silenceSeconds: StopAfterSilenceSeconds,
stop: () => void,
showToast: (message: string) => void
): void {
const { meter } = dictation
const watching = dictation.isRecording && dictationMode !== 'hold'
const watching = dictation.isRecording && dictationMode !== 'hold' && silenceSeconds !== null
const stopForSilence = useEffectEvent(() => {
showToast(nativeChatDictationCopy.stoppedAfterSilence())
showToast(nativeChatDictationCopy.stoppedAfterSilence(silenceSeconds ?? 0))
stop()
})
useEffect(() => {
if (!watching) {
if (!watching || silenceSeconds === null) {
return
}
return watchDictationSilence(meter.lastSpeechAt, Date.now, () => stopForSilence())
}, [meter, watching])
return watchDictationSilence(meter.lastSpeechAt, Date.now, silenceSeconds * 1000, () =>
stopForSilence()
)
}, [meter, watching, silenceSeconds])
}
@@ -4,8 +4,8 @@ import type { MobileImageSource } from '../../platform/media-picker-contract'
import type {
MobileNativeChatSendIntent,
MobileNativeChatSendOutcome
} from '../../session/native-chat/mobile-native-chat-send'
import type { StructuredMobileSendAttachment } from '../../session/use-mobile-structured-send-with-outcome'
} from '../../session/native-chat/composer/mobile-native-chat-send'
import type { StructuredMobileSendAttachment } from '../../session/native-chat/composer/use-mobile-structured-send-with-outcome'
import { useMobileImageAttachment } from './use-mobile-image-attachment'
import {
useMobileNativeChatImageAttachments,
@@ -7,10 +7,10 @@ import { areStructurallyEqual } from '../worktree/structural-equality'
import { MobileHomeSectionHeading } from './MobileHomeSectionHeading'
// Enough to act on without pushing Desktops off the first screen; the Agents tab has the rest.
const NEEDS_YOU_ROWS_SHOWN = 3
const ACTIVE_ROWS_SHOWN = 3
/** Feed's short list of agents waiting on the user; hidden when none are. */
export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou(props: {
/** Feed's short list of agents waiting on the user or working, those waiting first; hidden when none are. */
export const MobileHomeActiveAgents = memo(function MobileHomeActiveAgents(props: {
handlers: AgentListRowHandlers
rows: readonly AgentListRow[]
hosts: readonly HostProfile[]
@@ -24,14 +24,14 @@ export const MobileHomeNeedsYou = memo(function MobileHomeNeedsYou(props: {
return (
<>
<MobileHomeSectionHeading
title={t('home.needsYou.heading', 'Needs you')}
title={t('home.activeAgents.heading', 'Active')}
count={props.rows.length}
aside={t('home.needsYou.seeAll', 'See all agents')}
aside={t('home.activeAgents.seeAll', 'See all agents')}
onAsidePress={props.onSeeAll}
first
/>
<MobileAgentListRows
rows={props.rows.slice(0, NEEDS_YOU_ROWS_SHOWN)}
rows={props.rows.slice(0, ACTIVE_ROWS_SHOWN)}
footer="workspace"
nameDesktop={props.hosts.length > 1}
hosts={props.hosts}
+6 -6
View File
@@ -8,12 +8,12 @@ import type { HostCatalogEntry } from '../../transport/hosts/host-profile'
import { MobileHomeAppUpdateCard } from '../MobileHomeAppUpdateCard'
import { MobileHomeEmptyState } from '../MobileHomeEmptyState'
import { MobileHomeHostList } from '../MobileHomeHostList'
import { MobileHomeNeedsYou } from '../MobileHomeNeedsYou'
import { MobileHomeActiveAgents } from '../MobileHomeActiveAgents'
import { MobileHomeTasksSection } from '../MobileHomeTasksSection'
import type { MobileHomeData } from '../use-mobile-home-data'
import { MobileHomeTabHeader } from './MobileHomeTabHeader'
/** Home's first tab: agents that need you, the desktops, and Tasks. */
/** Home's first tab: agents that need you or are working, the desktops, and Tasks. */
export function MobileHomeFeedTab(props: {
data: MobileHomeData
bottomInset: number
@@ -42,7 +42,7 @@ export function MobileHomeFeedTab(props: {
/>
)
}
const needsYou = data.agentsNeedingYou.length > 0
const hasActiveAgents = data.activeAgents.length > 0
return (
<>
{title}
@@ -53,8 +53,8 @@ export function MobileHomeFeedTab(props: {
isWideLayout && { maxWidth: contentMaxWidth, width: '100%', alignSelf: 'center' }
]}
>
<MobileHomeNeedsYou
rows={data.agentsNeedingYou}
<MobileHomeActiveAgents
rows={data.activeAgents}
hosts={data.sortedHosts}
now={data.agentList.now}
handlers={props.agentHandlers}
@@ -62,7 +62,7 @@ export function MobileHomeFeedTab(props: {
/>
<MobileHomeHostList
autoConnectHostIds={data.autoConnectHostIds}
first={!needsYou}
first={!hasActiveAgents}
hostAttempts={data.hostAttempts}
hostLastConnected={data.hostLastConnected}
hostConnections={data.hostConnections}
+3
View File
@@ -10,6 +10,7 @@ import {
import { warmUpWebShell } from '../../modules/orca-mobile-web-shell/src'
import {
countAgentsNeedingYouByHost,
selectActiveAgents,
selectAgentsNeedingYou,
type AgentListInput
} from '../agents/agent-list-rows'
@@ -253,6 +254,7 @@ export function useMobileHomeData() {
[sortedHosts, hostStates, worktreeInfo, now, pendingActivity]
)
const agentsNeedingYou = useMemo(() => selectAgentsNeedingYou(agentList), [agentList])
const activeAgents = useMemo(() => selectActiveAgents(agentList), [agentList])
const needsYouByHost = useMemo(
() => countAgentsNeedingYouByHost(agentsNeedingYou),
[agentsNeedingYou]
@@ -274,6 +276,7 @@ export function useMobileHomeData() {
...connections,
accountsByHost,
applyAgentActivity: agentActivity.apply,
activeAgents,
agentList,
agentsNeedingYou,
connectedHosts,
@@ -0,0 +1,23 @@
import type { SupportedUiLocale } from '../../../src/shared/ui-locale'
export type LocaleCatalog = Readonly<Record<string, unknown>>
// Literal specifiers: Metro evaluates only the chosen module, and the page build splits each into its own chunk.
const CATALOG_IMPORTS: Record<Exclude<SupportedUiLocale, 'en'>, () => Promise<LocaleCatalog>> = {
de: () => import('./locales/de.json').then((module) => module.default),
es: () => import('./locales/es.json').then((module) => module.default),
fr: () => import('./locales/fr.json').then((module) => module.default),
ja: () => import('./locales/ja.json').then((module) => module.default),
ko: () => import('./locales/ko.json').then((module) => module.default),
pt: () => import('./locales/pt.json').then((module) => module.default),
ru: () => import('./locales/ru.json').then((module) => module.default),
tr: () => import('./locales/tr.json').then((module) => module.default),
zh: () => import('./locales/zh.json').then((module) => module.default),
'zh-Hant': () => import('./locales/zh-Hant.json').then((module) => module.default)
}
export function importBundledLocaleCatalog(
locale: Exclude<SupportedUiLocale, 'en'>
): Promise<LocaleCatalog> {
return CATALOG_IMPORTS[locale]()
}
+6 -20
View File
@@ -1,23 +1,9 @@
import type { SupportedUiLocale } from '../../../src/shared/ui-locale'
import type { LocaleCatalog } from './bundled-locale-catalogs'
export type LocaleCatalog = Readonly<Record<string, unknown>>
export { importBundledLocaleCatalog as importLocaleCatalog } from './bundled-locale-catalogs'
// Literal specifiers: Metro evaluates only the chosen module, and the page build splits each into its own chunk.
const CATALOG_IMPORTS: Record<Exclude<SupportedUiLocale, 'en'>, () => Promise<LocaleCatalog>> = {
de: () => import('./locales/de.json').then((module) => module.default),
es: () => import('./locales/es.json').then((module) => module.default),
fr: () => import('./locales/fr.json').then((module) => module.default),
ja: () => import('./locales/ja.json').then((module) => module.default),
ko: () => import('./locales/ko.json').then((module) => module.default),
pt: () => import('./locales/pt.json').then((module) => module.default),
ru: () => import('./locales/ru.json').then((module) => module.default),
tr: () => import('./locales/tr.json').then((module) => module.default),
zh: () => import('./locales/zh.json').then((module) => module.default),
'zh-Hant': () => import('./locales/zh-Hant.json').then((module) => module.default)
}
export function importLocaleCatalog(
locale: Exclude<SupportedUiLocale, 'en'>
): Promise<LocaleCatalog> {
return CATALOG_IMPORTS[locale]()
}
// Bundled catalogs never change after their import, so none arrives later; the page build's .web.ts does.
export const onLocaleCatalogArrival: (
listener: (locale: Exclude<SupportedUiLocale, 'en'>, catalog: LocaleCatalog) => void
) => () => void = () => () => undefined
@@ -0,0 +1,36 @@
import type { SupportedUiLocale } from '../../../src/shared/ui-locale'
import { importBundledLocaleCatalog, type LocaleCatalog } from './bundled-locale-catalogs'
// A shell that skips the catalog chunks has page-locale-catalog-source.ts read them from the desktop
// and the device store; other shells import the chunk as before. No transport here, so pages that
// only translate pull in none.
export type { LocaleCatalog }
type CatalogLocale = Exclude<SupportedUiLocale, 'en'>
type CatalogLoader = (locale: CatalogLocale) => Promise<LocaleCatalog>
type ArrivalListener = (locale: CatalogLocale, catalog: LocaleCatalog) => void
let loader: CatalogLoader | null = null
const arrivalListeners = new Set<ArrivalListener>()
export function publishPageLocaleCatalogLoader(next: CatalogLoader): void {
loader = next
}
// Resolve the catalog or reject so activation falls back to English.
export function importLocaleCatalog(locale: CatalogLocale): Promise<LocaleCatalog> {
return loader === null ? importBundledLocaleCatalog(locale) : loader(locale)
}
// A catalog that arrives after activation settled: a newer copy, or the first one after an offline start.
export function onLocaleCatalogArrival(listener: ArrivalListener): () => void {
arrivalListeners.add(listener)
return () => {
arrivalListeners.delete(listener)
}
}
export function announceLocaleCatalog(locale: CatalogLocale, catalog: LocaleCatalog): void {
for (const listener of arrivalListeners) {
listener(locale, catalog)
}
}
+2 -2
View File
@@ -2568,8 +2568,8 @@
"insertFailed": "Diktat konnte nicht eingefügt werden",
"insertFailedCopied": "Diktat konnte nicht eingefügt werden und wurde daher in die Zwischenablage kopiert",
"inserted": "Diktat eingefügt",
"stoppedAfterSilence": "Nach einer Minute Stille beendet",
"stoppedAtCloudLimit": "Diktat am 10-Minuten-Limit der Cloud gestoppt."
"stoppedAtCloudLimit": "Diktat am 10-Minuten-Limit der Cloud gestoppt.",
"stoppedAfterSilenceSeconds": "Nach {{seconds}} Sekunden Stille gestoppt"
},
"useNativeChatStop": {
"stopNotSent": "Stoppbefehl nicht gesendet",
+20 -5
View File
@@ -661,8 +661,8 @@
"openAccountsHint": "Opens this desktop’s accounts",
"emptyTitle": "No usage yet"
},
"needsYou": {
"heading": "Needs you",
"activeAgents": {
"heading": "Active",
"seeAll": "See all agents"
}
},
@@ -1491,6 +1491,11 @@
"offlineAsOfTime": {
"yesterday": "yesterday, {{time}}"
},
"newWorkspaceCreateSubmit": {
"uncertainFolderCreate": "This worktree may have been created. Check the folder before creating another.",
"uncertainCreate": "This workspace may have been created. Check your workspaces before creating another.",
"folderCreateBusy": "A worktree in this repository is still being created or checked. It shows in the folder once it lands."
},
"smartRailRow": {
"title": "Smart rail",
"subtitle": "Shows keys for what your agent is doing"
@@ -2401,8 +2406,8 @@
"insertFailedCopied": "Couldn't insert dictation, so it was copied to the clipboard",
"insertFailed": "Couldn't insert dictation",
"inserted": "Dictation inserted",
"stoppedAfterSilence": "Stopped after a minute of silence",
"stoppedAtCloudLimit": "Dictation stopped at the 10-minute cloud limit."
"stoppedAtCloudLimit": "Dictation stopped at the 10-minute cloud limit.",
"stoppedAfterSilenceSeconds": "Stopped after {{seconds}} seconds of silence"
},
"quickCommandLaunch": {
"editBeforeRunning": "Edit this quick command before running it",
@@ -3678,7 +3683,17 @@
"emptyTitle": "No attached worktrees yet",
"emptyCopy": "Worktrees created from this workspace will show up here.",
"statusUnavailable": "Unavailable",
"backToFolder": "Back to folder"
"backToFolder": "Back to folder",
"createSection": "Create a worktree",
"createIn": "Create a worktree in {{repo}}",
"created": "Created worktree {{name}} in {{repo}}",
"createdNamed": "Created worktree {{name}}",
"createFailed": "Could not create a worktree in {{repo}}.",
"loadReposRetry": "Load repositories",
"setupChoiceTitle": "Retry without setup?",
"setupChoiceMessage": "Orca couldn't confirm the last create in {{repo}}. Retrying it needs a setup choice; it will be created without running the repository's setup.",
"setupChoiceSkip": "Retry without setup",
"checking": "A worktree from {{repo}} may already have been created. Checking the folder…"
},
"hostedReviewCopy": {
"updatingBranch": "Updating branch...",
+2 -2
View File
@@ -2638,8 +2638,8 @@
"insertFailed": "No se pudo insertar el dictado",
"insertFailedCopied": "No se pudo insertar el dictado, así que se copió al portapapeles.",
"inserted": "Dictado insertado",
"stoppedAfterSilence": "Se detuvo tras un minuto de silencio",
"stoppedAtCloudLimit": "Dictado detenido al llegar al límite de 10 minutos en la nube."
"stoppedAtCloudLimit": "Dictado detenido al llegar al límite de 10 minutos en la nube.",
"stoppedAfterSilenceSeconds": "Detenido tras {{seconds}} segundos de silencio"
},
"useNativeChatStop": {
"stopNotSent": "No se envió la orden de detener",
+2 -2
View File
@@ -2638,8 +2638,8 @@
"insertFailed": "Impossible d'insérer la dictée",
"insertFailedCopied": "Impossible d'insérer la dictée ; elle a été copiée dans le presse-papiers",
"inserted": "Dictée insérée",
"stoppedAfterSilence": "Arrêt après une minute de silence",
"stoppedAtCloudLimit": "Dictée arrêtée à la limite cloud de 10 minutes."
"stoppedAtCloudLimit": "Dictée arrêtée à la limite cloud de 10 minutes.",
"stoppedAfterSilenceSeconds": "Arrêté après {{seconds}} secondes de silence"
},
"useNativeChatStop": {
"stopNotSent": "Commande d'arrêt non envoyée",
+2 -2
View File
@@ -2564,8 +2564,8 @@
"insertFailed": "ディクテーションの結果を挿入できませんでした。",
"insertFailedCopied": "ディクテーションの結果を挿入できず、クリップボードにコピーしました。",
"inserted": "ディクテーションの結果を挿入しました。",
"stoppedAfterSilence": "1分間音声がなかったため停止しました。",
"stoppedAtCloudLimit": "クラウドの10分の上限に達したため、ディクテーションが停止しました。"
"stoppedAtCloudLimit": "クラウドの10分の上限に達したため、ディクテーションが停止しました。",
"stoppedAfterSilenceSeconds": "{{seconds}} 秒間無音だったため停止しました"
},
"useNativeChatStop": {
"stopNotSent": "停止要求を送信できませんでした。",
+2 -2
View File
@@ -2564,8 +2564,8 @@
"insertFailed": "받아쓰기 내용을 삽입하지 못했습니다.",
"insertFailedCopied": "받아쓰기 내용을 삽입하지 못해 클립보드에 복사했습니다.",
"inserted": "받아쓰기 내용 삽입됨",
"stoppedAfterSilence": "1분 동안 말소리가 없어 중지했습니다.",
"stoppedAtCloudLimit": "클라우드 10분 제한에 도달해 받아쓰기가 중지되었습니다."
"stoppedAtCloudLimit": "클라우드 10분 제한에 도달해 받아쓰기가 중지되었습니다.",
"stoppedAfterSilenceSeconds": "{{seconds}}초 동안 조용해서 중지했습니다"
},
"useNativeChatStop": {
"stopNotSent": "중지 요청 전송 안 됨",
+2 -2
View File
@@ -2638,8 +2638,8 @@
"insertFailed": "Não foi possível inserir o ditado",
"insertFailedCopied": "Não foi possível inserir o ditado, então ele foi copiado para a área de transferência",
"inserted": "Ditado inserido",
"stoppedAfterSilence": "Parou após um minuto de silêncio",
"stoppedAtCloudLimit": "O ditado foi interrompido no limite de 10 minutos da nuvem."
"stoppedAtCloudLimit": "O ditado foi interrompido no limite de 10 minutos da nuvem.",
"stoppedAfterSilenceSeconds": "Parado após {{seconds}} segundos de silêncio"
},
"useNativeChatStop": {
"stopNotSent": "Comando de parada não enviado",
+2 -2
View File
@@ -2708,8 +2708,8 @@
"insertFailed": "Не удалось вставить текст диктовки",
"insertFailedCopied": "Не удалось вставить текст диктовки — он скопирован в буфер обмена",
"inserted": "Текст диктовки вставлен",
"stoppedAfterSilence": "Остановлено после минуты тишины",
"stoppedAtCloudLimit": "Диктовка остановлена: достигнут 10-минутный облачный лимит."
"stoppedAtCloudLimit": "Диктовка остановлена: достигнут 10-минутный облачный лимит.",
"stoppedAfterSilenceSeconds": "Остановлено после {{seconds}} с тишины"
},
"useNativeChatStop": {
"stopNotSent": "Команда остановки не отправлена",
+2 -2
View File
@@ -2568,8 +2568,8 @@
"insertFailed": "Dikte metni eklenemedi",
"insertFailedCopied": "Dikte metni eklenemediği için panoya kopyalandı",
"inserted": "Dikte metni eklendi",
"stoppedAfterSilence": "Bir dakika sessizlikten sonra durduruldu",
"stoppedAtCloudLimit": "Dikte, 10 dakikalık bulut sınırında durduruldu."
"stoppedAtCloudLimit": "Dikte, 10 dakikalık bulut sınırında durduruldu.",
"stoppedAfterSilenceSeconds": "{{seconds}} saniyelik sessizlikten sonra durduruldu"
},
"useNativeChatStop": {
"stopNotSent": "Durdurma isteği gönderilemedi",
+2 -2
View File
@@ -2564,8 +2564,8 @@
"insertFailed": "無法插入聽寫內容",
"insertFailedCopied": "無法插入聽寫內容,已複製到剪貼簿",
"inserted": "已插入聽寫內容",
"stoppedAfterSilence": "靜音一分鐘後已停止",
"stoppedAtCloudLimit": "已達 10 分鐘雲端上限。聽寫已停止。"
"stoppedAtCloudLimit": "已達 10 分鐘雲端上限。聽寫已停止。",
"stoppedAfterSilenceSeconds": "靜音 {{seconds}} 秒後已停止"
},
"useNativeChatStop": {
"stopNotSent": "未送出停止命令",
+2 -2
View File
@@ -2564,8 +2564,8 @@
"insertFailed": "无法插入听写文本",
"insertFailedCopied": "无法插入听写文本,已复制到剪贴板",
"inserted": "已插入听写文本",
"stoppedAfterSilence": "静音一分钟后已停止",
"stoppedAtCloudLimit": "已达 10 分钟云端上限。听写已停止。"
"stoppedAtCloudLimit": "已达 10 分钟云端上限。听写已停止。",
"stoppedAfterSilenceSeconds": "静音 {{seconds}} 秒后已停止"
},
"useNativeChatStop": {
"stopNotSent": "停止指令未发送",
+2 -1
View File
@@ -7,7 +7,8 @@ vi.mock('./locale-catalog-imports', () => ({
importLocaleCatalog: (locale: string) =>
failing.has(locale)
? Promise.reject(new Error('missing chunk'))
: new Promise((resolve) => pending.set(locale, resolve))
: new Promise((resolve) => pending.set(locale, resolve)),
onLocaleCatalogArrival: () => () => undefined
}))
const { activateMobileUiLocale, getMobileUiLocale, mobileI18n, translate } =
+13 -1
View File
@@ -3,7 +3,7 @@ import { resolvePluralFamilyKey } from '../../../src/shared/i18n-plural-family'
import { pseudoLocalizeString } from '../../../src/shared/pseudo-localization'
import { DEFAULT_UI_LOCALE, type SupportedUiLocale } from '../../../src/shared/ui-locale'
import enRuntimeRequired from './en-runtime-required.json'
import { importLocaleCatalog } from './locale-catalog-imports'
import { importLocaleCatalog, onLocaleCatalogArrival } from './locale-catalog-imports'
export type Translate = (key: string, fallback: string, options?: TOptions) => string
@@ -83,10 +83,12 @@ export function subscribeMobileUiLanguage(listener: () => void): () => void {
}
let activationRequest = 0
let requestedLocale: SupportedUiLocale = DEFAULT_UI_LOCALE
// Latest request wins: an older catalog import that settles later must not replace a newer choice.
export async function activateMobileUiLocale(locale: SupportedUiLocale): Promise<void> {
const request = ++activationRequest
requestedLocale = locale
try {
if (locale !== 'en' && !mobileI18n.hasResourceBundle(locale, 'translation')) {
const catalog = await importLocaleCatalog(locale)
@@ -115,6 +117,16 @@ export async function activateMobileUiLocale(locale: SupportedUiLocale): Promise
publish()
}
// Switch in place, without a reload: a newer copy replaces the shown one, a first copy replaces the English fallback.
// Install it even when another language is up now, so switching back shows the newer copy.
onLocaleCatalogArrival((locale, catalog) => {
mobileI18n.removeResourceBundle(locale, 'translation')
mobileI18n.addResourceBundle(locale, 'translation', catalog, false, true, { skipCopy: true })
if (locale === requestedLocale) {
void activateMobileUiLocale(locale)
}
})
// Development-only layout check: accents and pads every string so clipping shows on device.
export function setMobilePseudoLocalization(enabled: boolean): void {
if (pseudoLocalization !== enabled) {
@@ -0,0 +1,218 @@
import { describe, expect, it, vi } from 'vitest'
import type { ConnectionState } from '../transport/connection/connection-state'
import type { RpcResponse } from '../transport/rpc/rpc-wire-types'
import {
decodeDeviceStoreValue,
encodeDeviceStoreValue
} from '../device-store/device-store-value-codec'
import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store'
// The page build resolves mobile-i18n's catalog import to the .web module; mirror that here.
vi.mock('./locale-catalog-imports', () => import('./locale-catalog-imports.web'))
// A shell that skipped the catalog chunks: only locales listed here are on disk.
const chunksOnDisk = new Map<string, Record<string, unknown>>()
vi.mock('./bundled-locale-catalogs', () => ({
importBundledLocaleCatalog: async (locale: string) => {
const catalog = chunksOnDisk.get(locale)
if (!catalog) {
throw new Error('not on disk')
}
return catalog
}
}))
const OLD_SHA = 'a'.repeat(64)
const NEW_SHA = 'b'.repeat(64)
type SentRequest = {
method: string
params: unknown
reply: (response: RpcResponse) => void
fail: (error: Error) => void
}
function fakeClient(initial: ConnectionState) {
let state = initial
let generation = 1
const listeners = new Set<(next: ConnectionState) => void>()
const sent: SentRequest[] = []
return {
sent,
getState: () => state,
getGeneration: () => generation,
onStateChange: (listener: (next: ConnectionState) => void) => {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
},
sendRequest: (method: string, params?: unknown) =>
new Promise<RpcResponse>((reply, fail) => sent.push({ method, params, reply, fail })),
moveTo(next: ConnectionState) {
state = next
for (const listener of listeners) {
listener(next)
}
},
// The shell swaps in an already-connected replacement, as on a relay-to-LAN move.
cutover() {
generation += 1
for (const listener of listeners) {
listener('connected')
}
}
}
}
function fakeStore(rows: Record<string, string>): PageDeviceStore & { rows: Map<string, string> } {
const stored = new Map(Object.entries(rows))
return {
rows: stored,
available: () => true,
read: async (_table, keys) => ({
status: 'ok',
values: keys.map((key) => stored.get(key) ?? null)
}),
write: async (_table, ops) => {
for (const op of ops) {
if (op.value !== null) {
stored.set(op.key, op.value)
}
}
return { written: true }
}
}
}
const { startPageLocaleCatalogs } = await import('./page-locale-catalog-source')
const i18n = await import('./mobile-i18n')
// Module state outlives a test, so each test uses its own locale and publishes its own source.
function openPage(client: ReturnType<typeof fakeClient>, store: PageDeviceStore): void {
startPageLocaleCatalogs({ client, store })
}
// Microtasks, then one macrotask, which is when the store write runs.
async function settle(): Promise<void> {
for (let turn = 0; turn < 20; turn++) {
await Promise.resolve()
}
await new Promise((resolve) => setTimeout(resolve, 0))
}
describe('the page language catalog', () => {
it('opens on the stored copy, then switches in place to the desktop newer one', async () => {
const client = fakeClient('connected')
const store = fakeStore({
'i18n-catalog:de': encodeDeviceStoreValue({
v: 1,
sha256: OLD_SHA,
catalog: { greeting: 'Hallo' }
})
})
openPage(client, store)
await i18n.activateMobileUiLocale('de')
expect(i18n.translate('greeting', 'Hello')).toBe('Hallo')
expect(client.sent.map(({ method, params }) => ({ method, params }))).toEqual([
{ method: 'mobileWeb.bundle.localeCatalog', params: { locale: 'de', knownSha256: OLD_SHA } }
])
client.sent[0].reply({
id: 'r1',
ok: true,
result: { locale: 'de', sha256: NEW_SHA, catalog: { greeting: 'Servus' } }
})
await settle()
expect(i18n.getMobileUiLocale()).toBe('de')
expect(i18n.translate('greeting', 'Hello')).toBe('Servus')
expect(decodeDeviceStoreValue(store.rows.get('i18n-catalog:de') ?? '')).toEqual({
v: 1,
sha256: NEW_SHA,
catalog: { greeting: 'Servus' }
})
})
it('shows English offline with nothing stored, then the language once the desktop answers', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const client = fakeClient('reconnecting')
openPage(client, fakeStore({}))
await i18n.activateMobileUiLocale('fr')
expect(i18n.getMobileUiLocale()).toBe('en')
expect(i18n.translate('greeting', 'Hello')).toBe('Hello')
expect(client.sent).toHaveLength(0)
client.moveTo('connected')
await settle()
expect(client.sent.map(({ params }) => params)).toEqual([{ locale: 'fr' }])
client.sent[0].reply({
id: 'r1',
ok: true,
result: { locale: 'fr', sha256: NEW_SHA, catalog: { greeting: 'Bonjour' } }
})
await settle()
expect(i18n.getMobileUiLocale()).toBe('fr')
expect(i18n.translate('greeting', 'Hello')).toBe('Bonjour')
})
it('opens in English when the first request fails on a live link, then switches on the next connection', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const client = fakeClient('connected')
openPage(client, fakeStore({}))
const activation = i18n.activateMobileUiLocale('ja')
await settle()
client.sent[0].fail(new Error('timed out'))
await activation
expect(i18n.getMobileUiLocale()).toBe('en')
client.moveTo('reconnecting')
client.moveTo('connected')
await settle()
client.sent[1].reply({
id: 'r2',
ok: true,
result: { locale: 'ja', sha256: NEW_SHA, catalog: { greeting: 'こんにちは' } }
})
await settle()
expect(i18n.getMobileUiLocale()).toBe('ja')
expect(i18n.translate('greeting', 'Hello')).toBe('こんにちは')
})
it('asks again on the connection a cutover swaps in, without waiting for another reconnect', async () => {
vi.spyOn(console, 'warn').mockImplementation(() => {})
const client = fakeClient('reconnecting')
openPage(client, fakeStore({}))
await i18n.activateMobileUiLocale('ko')
client.moveTo('connected')
await settle()
client.cutover()
client.sent[0].fail(new Error('client cut over'))
await settle()
client.sent[1].reply({
id: 'r2',
ok: true,
result: { locale: 'ko', sha256: NEW_SHA, catalog: { greeting: '안녕하세요' } }
})
await settle()
expect(i18n.getMobileUiLocale()).toBe('ko')
expect(i18n.translate('greeting', 'Hello')).toBe('안녕하세요')
})
it('imports the chunk an older shell left on disk, with no wait and no request', async () => {
chunksOnDisk.set('es', { greeting: 'Hola' })
const client = fakeClient('reconnecting')
openPage(client, fakeStore({}))
await i18n.activateMobileUiLocale('es')
expect(i18n.translate('greeting', 'Hello')).toBe('Hola')
expect(client.sent).toHaveLength(0)
})
})
@@ -0,0 +1,265 @@
import * as z from 'zod'
import type { SupportedUiLocale } from '../../../src/shared/ui-locale'
import { SHA256_PATTERN } from '../../../src/shared/mobile-web-bundle/manifest-contract'
import {
MOBILE_WEB_BUNDLE_LOCALE_CATALOG_METHOD,
MobileWebBundleLocaleCatalogResultSchema
} from '../../../src/shared/mobile-web-bundle/locale-catalog-contract'
import { withTimeoutResult } from '../../../src/shared/promise-timeout-fallback'
import {
decodeDeviceStoreValue,
encodeDeviceStoreValue
} from '../device-store/device-store-value-codec'
import type { BridgeRpcClient } from '../mobile-web-shell/bridge/bridge-rpc-client'
import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store'
import { isMobileMethodUnavailableError } from '../transport/rpc/mobile-method-unavailable'
import { captureRpcOperationSettlement, defineRpcOperation } from '../transport/rpc/rpc-operation'
import { rpcResultVariant } from '../transport/rpc/rpc-operation-result-reader'
import { importBundledLocaleCatalog } from './bundled-locale-catalogs'
import {
announceLocaleCatalog as announce,
publishPageLocaleCatalogLoader,
type LocaleCatalog
} from './locale-catalog-imports.web'
// The desktop serves the active catalog and the phone keeps a copy per host; only the page entry imports this.
type CatalogLocale = Exclude<SupportedUiLocale, 'en'>
type HeldCatalog = { readonly sha256: string; readonly catalog: LocaleCatalog }
type CatalogClient = Pick<
BridgeRpcClient,
'getState' | 'getGeneration' | 'onStateChange' | 'sendRequest'
>
type CatalogSource = { readonly client: CatalogClient; readonly store: PageDeviceStore }
const storedCatalogSchema = z.object({
v: z.literal(1),
sha256: z.string().regex(SHA256_PATTERN),
catalog: z.record(z.string(), z.unknown())
})
const localeCatalogRead = defineRpcOperation({
name: 'mobileWeb.bundle-locale-catalog',
method: MOBILE_WEB_BUNDLE_LOCALE_CATALOG_METHOD,
acceptance: 'require-result-or-throw',
barrier: 'on-settle',
// Loose like every phone reader, so a host may add fields.
read: rpcResultVariant(
'mobile-web-bundle-locale-catalog',
MobileWebBundleLocaleCatalogResultSchema.loose()
)
})
const syncing = new Set<CatalogLocale>()
// The stored read plus a relay round trip with the largest catalog fit well inside; past it the page opens in English.
const FIRST_PAINT_CATALOG_WAIT_MS = 3_000
const storeKey = (locale: CatalogLocale): string => `i18n-catalog:${locale}`
async function readStoredCatalog(
store: PageDeviceStore,
locale: CatalogLocale
): Promise<HeldCatalog | null> {
if (!store.available()) {
return null
}
const read = await store.read('cache', [storeKey(locale)]).catch(() => null)
const raw = read?.status === 'ok' ? read.values[0] : null
if (!raw) {
return null
}
const parsed = storedCatalogSchema.safeParse(decodeDeviceStoreValue(raw))
return parsed.success ? { sha256: parsed.data.sha256, catalog: parsed.data.catalog } : null
}
function writeStoredCatalog(
store: PageDeviceStore,
locale: CatalogLocale,
next: HeldCatalog
): void {
if (store.available()) {
const value = encodeDeviceStoreValue({ v: 1, ...next })
void store.write('cache', [{ key: storeKey(locale), value }]).catch(() => undefined)
}
}
// A send the host never answered, as opposed to a refusal or an unreadable reply.
class CatalogSendFailed extends Error {
constructor(
message: string,
readonly generation: number | null = null
) {
super(message)
}
}
const generationOf = (client: CatalogClient): number | null => client.getGeneration?.() ?? null
// After a failed send, wait for a reconnect or a cutover to another connection, which is often connected already.
// False once pairing is revoked: that connection never comes back.
function whenConnected(client: CatalogClient, failedGeneration: number | null): Promise<boolean> {
let reconnected = failedGeneration === null || client.getState() !== 'connected'
const ready = (): boolean =>
client.getState() === 'connected' && (reconnected || generationOf(client) !== failedGeneration)
if (ready() || client.getState() === 'auth-failed') {
return Promise.resolve(ready())
}
return new Promise((resolve) => {
const stop = client.onStateChange((state) => {
reconnected ||= state !== 'connected'
if (ready() || state === 'auth-failed') {
stop()
resolve(ready())
}
})
})
}
// Rejects when the connection drops first, so a first paint never waits on a reply that can't come.
function beforeConnectionLoss<T>(client: CatalogClient, work: Promise<T>): Promise<T> {
return new Promise((resolve, reject) => {
const stop = client.onStateChange((state) => {
if (state !== 'connected') {
stop()
reject(new CatalogSendFailed('[i18n] connection lost before the catalog arrived'))
}
})
work.then(
(value) => {
stop()
resolve(value)
},
(error: unknown) => {
stop()
reject(error)
}
)
})
}
// One request. On an answer the copy becomes the page's and the store's.
async function askHost(
{ client, store }: CatalogSource,
locale: CatalogLocale,
known: HeldCatalog | undefined
): Promise<HeldCatalog> {
const generation = generationOf(client)
const settled = await captureRpcOperationSettlement(client, localeCatalogRead, {
locale,
...(known ? { knownSha256: known.sha256 } : {})
})
if (settled.status === 'rejected') {
throw new CatalogSendFailed(`[i18n] the ${locale} catalog request got no answer`, generation)
}
const { outcome } = settled
if (outcome.kind === 'decoded') {
const { sha256, catalog } = outcome.value
// A null catalog only confirms the copy the phone named.
const next = catalog !== null ? { sha256, catalog } : known?.sha256 === sha256 ? known : null
if (next) {
if (next !== known) {
// After the first paint: encoding the copy is main-thread work nothing waits on.
setTimeout(() => {
writeStoredCatalog(store, locale, next)
}, 0)
}
return next
}
}
const refusal = outcome.kind === 'outer-refused' ? outcome.error : undefined
throw new Error(
isMobileMethodUnavailableError(refusal?.code, refusal?.message)
? '[i18n] this desktop serves no language catalogs'
: `[i18n] the desktop answered no ${locale} catalog`
)
}
// Asks until the host answers, resending once per new connection; a refusal ends it.
async function syncFromHost(
current: CatalogSource,
locale: CatalogLocale,
known: HeldCatalog | undefined,
failedGeneration: number | null
): Promise<HeldCatalog> {
for (;;) {
if (!(await whenConnected(current.client, failedGeneration))) {
throw new Error('[i18n] this phone is no longer paired with the desktop')
}
try {
return await askHost(current, locale, known)
} catch (error) {
if (!(error instanceof CatalogSendFailed)) {
throw error
}
failedGeneration = error.generation
}
}
}
// One sync per locale, announcing a copy other than the one the page already shows.
function syncOnce(
current: CatalogSource,
locale: CatalogLocale,
known: HeldCatalog | undefined,
failedGeneration: number | null = null
): void {
if (syncing.has(locale)) {
return
}
syncing.add(locale)
syncFromHost(current, locale, known, failedGeneration).then(
(next) => {
syncing.delete(locale)
if (next !== known) {
announce(locale, next.catalog)
}
},
() => {
syncing.delete(locale)
}
)
}
// What a first paint may wait for: the stored copy, else one request while connected.
async function firstCatalog(current: CatalogSource, locale: CatalogLocale): Promise<HeldCatalog> {
// Only a locale with no catalog installed is asked for, so nothing is held in memory here.
const known = await readStoredCatalog(current.store, locale)
if (known) {
// Show the stored copy now; a newer one replaces it when the host answers.
syncOnce(current, locale, known)
return known
}
if (current.client.getState() !== 'connected') {
throw new CatalogSendFailed('[i18n] no connection for the catalog yet')
}
return beforeConnectionLoss(current.client, askHost(current, locale, undefined))
}
async function loadCatalog(current: CatalogSource, locale: CatalogLocale): Promise<LocaleCatalog> {
// A generation an older shell downloaded still holds the chunk: no wait, and this page's own strings.
const bundled = await importBundledLocaleCatalog(locale).catch(() => null)
if (bundled !== null) {
return bundled
}
const first = firstCatalog(current, locale)
const settled = await withTimeoutResult(first, FIRST_PAINT_CATALOG_WAIT_MS)
if (settled.ok) {
return settled.value.catalog
}
// Activation shows English meanwhile; whatever comes later switches the page in place.
first.then(
(late) => {
announce(locale, late.catalog)
},
(failure: unknown) => {
if (failure instanceof CatalogSendFailed) {
syncOnce(current, locale, undefined, failure.generation)
}
}
)
throw new Error(`[i18n] no ${locale} catalog for the first paint`)
}
// Before the first activation, so its catalog comes from the desktop and the store.
export function startPageLocaleCatalogs(current: CatalogSource): void {
publishPageLocaleCatalogLoader((locale) => loadCatalog(current, locale))
}
@@ -48,6 +48,7 @@ describe('init and state', () => {
expect(init.grants.native).toEqual([
BRIDGE_FAULT_GRANT,
BRIDGE_RPC_ENVELOPE_GRANT,
'hostCatalogs',
'navigate',
'storage',
'haptics',
@@ -205,7 +205,7 @@ describe('grants scoped to the route the page was opened for', () => {
const bridge = harness({ routeGrants: navigationOnly, ready: true })
expect(bridge.last()).toMatchObject({
type: 'init',
grants: { native: ['fault', 'rpcEnvelope', 'navigate', 'storage'] }
grants: { native: ['fault', 'rpcEnvelope', 'hostCatalogs', 'navigate', 'storage'] }
})
for (const [method, params] of [
['native.clipboard.read', { mime: 'text' }],
+2 -7
View File
@@ -7,9 +7,8 @@ import { BridgeHostRequests } from './bridge-host-requests'
import { BridgeHostSubscriptions } from './bridge-host-subscriptions'
import { createBridgeHostStreamFrames } from './bridge-host-stream-frames'
import {
BRIDGE_FAULT_GRANT,
BRIDGE_PROTOCOL_VERSION,
BRIDGE_RPC_ENVELOPE_GRANT,
BRIDGE_SHELL_GRANTS,
readBridgeClientMessage,
type BridgeClientMessage
} from './bridge/bridge-envelope'
@@ -30,11 +29,7 @@ export type { BridgeHost, BridgeHostDiagnostic, BridgeHostOptions } from './brid
// Bind the host structurally to one RPC client; the protocol lets pages name no other host. Native origin checks reject expired sessions, and init caps are enforced here.
export function createBridgeHost(options: BridgeHostOptions): BridgeHost {
const { client, buildId, sessionId, pageRoutes, host } = options
const granted: readonly string[] = [
BRIDGE_FAULT_GRANT,
BRIDGE_RPC_ENVELOPE_GRANT,
...options.routeGrants
]
const granted: readonly string[] = [...BRIDGE_SHELL_GRANTS, ...options.routeGrants]
// Validate manifest pairs like the route: a pair refused by the page would invalidate the entire init.
const parsedRouteGrants =
options.pageRouteGrants === undefined
@@ -32,10 +32,12 @@ export {
BRIDGE_EXTERNAL_LINK_GRANT,
BRIDGE_FAULT_GRANT,
BRIDGE_FOREGROUND_NUDGE_REASONS,
BRIDGE_HOST_CATALOGS_GRANT,
BRIDGE_ID_PATTERN,
BRIDGE_NAVIGATE_BACK_NOTIFY,
BRIDGE_PROTOCOL_VERSION,
BRIDGE_RPC_ENVELOPE_GRANT
BRIDGE_RPC_ENVELOPE_GRANT,
BRIDGE_SHELL_GRANTS
} from './bridge-frame-fields'
import {
isPageStorageKey,
@@ -25,3 +25,13 @@ export const BRIDGE_EXTERNAL_LINK_GRANT = 'externalLink'
// Negotiate rpcEnvelope before relying on extra wire fields; older shells drop unknown fields and could execute without caller-required metadata.
export const BRIDGE_RPC_ENVELOPE_GRANT = 'rpcEnvelope'
// The shell skipped the build's language-catalog chunks, so the page reads its catalog from the desktop.
export const BRIDGE_HOST_CATALOGS_GRANT = 'hostCatalogs'
// Granted to every page this shell opens, whatever its route declares.
export const BRIDGE_SHELL_GRANTS: readonly string[] = [
BRIDGE_FAULT_GRANT,
BRIDGE_RPC_ENVELOPE_GRANT,
BRIDGE_HOST_CATALOGS_GRANT
]
@@ -6,9 +6,8 @@ import {
import { BRIDGE_MAX_PENDING_REQUESTS, BRIDGE_MAX_SUBSCRIPTIONS } from './bridge-caps'
import { MOBILE_WEB_SHELL_GRANTS } from '../page-route-policy'
import {
BRIDGE_FAULT_GRANT,
BRIDGE_PROTOCOL_VERSION,
BRIDGE_RPC_ENVELOPE_GRANT,
BRIDGE_SHELL_GRANTS,
type BridgeColorScheme,
type BridgeConnectionSnapshot,
type BridgeHostMessage,
@@ -27,8 +26,7 @@ import type { HostStatusReply } from '../../transport/hosts/host-status-reply-sc
// Grant the intersection of implemented capabilities and route declarations, plus protocol fault. Use the same resolved list for init and enforcement; new names need no version bump.
export const BRIDGE_NATIVE_GRANTS: readonly string[] = [
BRIDGE_FAULT_GRANT,
BRIDGE_RPC_ENVELOPE_GRANT,
...BRIDGE_SHELL_GRANTS,
...MOBILE_WEB_SHELL_GRANTS
]
@@ -1,5 +1,6 @@
import {
MobileWebBundleManifestReadSchema,
shellDownloadedAssets,
type MobileWebBundleManifestRead
} from '../transport/web-bundle/mobile-web-bundle-reply-schemas'
import { MANIFEST_FILE_NAME } from './generation-asset-path'
@@ -33,12 +34,13 @@ export async function readWaitingStage(
}
// Deletes are not atomic, so a kill mid-delete can leave the manifest without its assets; only every byte counts as whole.
const sizes = new Map<string, number>()
for (const folder of new Set(manifest.assets.map((asset) => parentOf(asset.path)))) {
const assets = shellDownloadedAssets(manifest)
for (const folder of new Set(assets.map((asset) => parentOf(asset.path)))) {
for (const file of await fs.listFiles(folder === '' ? directory : joinUri(directory, folder))) {
sizes.set(folder === '' ? file.name : `${folder}/${file.name}`, file.size)
}
}
const whole = manifest.assets.every((asset) => sizes.get(asset.path) === asset.byteLength)
const whole = assets.every((asset) => sizes.get(asset.path) === asset.byteLength)
return whole ? { hostKey, buildId, directory, manifest } : null
}
@@ -1,10 +1,11 @@
import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch'
import { shellDownloadedAssets } from '../transport/web-bundle/mobile-web-bundle-reply-schemas'
import { requireStorablePath } from './generation-asset-path'
import { joinUri } from './generation-cache-uri'
export function stagingAssetsOf(directory: string, result: MobileWebBundleFetchResult) {
const reused = new Set(result.reused)
return result.manifest.assets.map((asset) => ({
return shellDownloadedAssets(result.manifest).map((asset) => ({
asset,
uri: joinUri(directory, requireStorablePath(asset.path)),
bytes: reused.has(asset.path) ? null : requireExactBytes(result.assets.get(asset.path), asset)
@@ -1,5 +1,5 @@
import { describe, expect, it } from 'vitest'
import { createGenerationStore, MAX_CACHED_HOSTS } from './generation-store'
import { createGenerationStore } from './generation-store'
import { deriveHostCacheKey } from './host-cache-key'
import type { MobileWebBundleFetchResult } from '../transport/web-bundle/mobile-web-bundle-fetch'
import { computeMobileWebBundleId } from '../../../src/shared/mobile-web-bundle/manifest-contract'
@@ -13,7 +13,7 @@ const HOST = deriveHostCacheKey('host-a')
function buildResult(options: {
buildId?: string
assets?: readonly { path: string; byteLength: number }[]
assets?: readonly { path: string; byteLength: number; kind?: string }[]
bytes?: ReadonlyMap<string, Uint8Array>
}): MobileWebBundleFetchResult {
const listed = options.assets ?? [
@@ -24,7 +24,8 @@ function buildResult(options: {
path: asset.path,
sha256: String(index).repeat(64).slice(0, 64),
byteLength: asset.byteLength,
contentType: 'text/html; charset=utf-8'
contentType: 'text/html; charset=utf-8',
...(asset.kind === undefined ? {} : { kind: asset.kind })
}))
const totalBytes = assets.reduce((sum, asset) => sum + asset.byteLength, 0)
return {
@@ -59,343 +60,6 @@ async function activate(
await store.commitGeneration(await store.stageGeneration(hostKey, result))
}
function hostKeys(count: number): string[] {
return Array.from({ length: count }, (_, index) => deriveHostCacheKey(`host-${index}`))
}
describe('generation store', () => {
it('refuses an asset that is missing or the wrong length, leaving no generation', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const missing = buildResult({ bytes: new Map([['index.html', new Uint8Array(4)]]) })
const short = buildResult({
bytes: new Map([
['index.html', new Uint8Array(4)],
['assets/app.js', new Uint8Array(1)]
])
})
await expect(store.stageGeneration(HOST, missing)).rejects.toThrow('assets/app.js is absent')
await expect(store.stageGeneration(HOST, short)).rejects.toThrow("not the manifest's 2")
expect(fs.paths()).toEqual([])
expect(await store.readActiveGeneration(HOST)).toBeNull()
})
it('drops the staged tree when a write fails', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
fs.failWritesAt(`${HOST}/tmp/${BUILD}/assets/app.js`)
await expect(store.stageGeneration(HOST, buildResult({}))).rejects.toThrow('disk-full')
expect(fs.paths().some((path) => path.includes(`tmp/${BUILD}`))).toBe(false)
expect(await store.readActiveGeneration(HOST)).toBeNull()
})
it('leaves no generation and no tmp for any host when a download is interrupted', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const other = deriveHostCacheKey('host-b')
// The manifest is written last, so a download cut off mid-stage leaves assets without one.
fs.seed(`${HOST}/tmp/${BUILD}/index.html`, { kind: 'file', bytes: new Uint8Array(4) })
fs.seed(`${other}/tmp/${BUILD}/index.html`, { kind: 'file', bytes: new Uint8Array(4) })
expect(await store.readActiveGeneration(HOST)).toBeNull()
expect(await store.readActiveGeneration(other)).toBeNull()
expect(fs.paths().some((path) => path.includes('/tmp'))).toBe(false)
})
it('reads two generations as no activation and drops the host tree', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
await activate(store, HOST)
fs.seed(`${HOST}/generations/${'c'.repeat(64)}/manifest.json`, {
kind: 'file',
bytes: new TextEncoder().encode('{}')
})
expect(await store.readActiveGeneration(HOST)).toBeNull()
expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false)
})
it('reads an unparseable or mismatched manifest as no activation and drops the host tree', async () => {
for (const body of [
'not json',
JSON.stringify({ ...buildResult({}).manifest, buildId: 'd'.repeat(64) })
]) {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
await activate(store, HOST)
fs.seed(`${HOST}/generations/${BUILD}/manifest.json`, {
kind: 'file',
bytes: new TextEncoder().encode(body)
})
expect(await store.readActiveGeneration(HOST)).toBeNull()
expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false)
}
})
it('evicts the least recently activated host past the ceiling', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const hosts = hostKeys(MAX_CACHED_HOSTS + 1)
for (const host of hosts) {
await activate(store, host)
}
expect(await store.readActiveGeneration(hosts[0])).toBeNull()
expect(fs.paths().some((path) => path.startsWith(hosts[0]))).toBe(false)
for (const host of hosts.slice(1)) {
expect((await store.readActiveGeneration(host))?.buildId).toBe(BUILD)
}
expect(fs.text('hosts.json')).toBe(JSON.stringify(hosts.slice(1)))
})
it('evicts a host with no index entry before the least recently activated one', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const [oldest, ...rest] = hostKeys(MAX_CACHED_HOSTS - 1)
const orphan = deriveHostCacheKey('orphan')
for (const host of [oldest, ...rest]) {
await activate(store, host)
}
await activate(store, orphan)
const order = [oldest, ...rest]
fs.seed('hosts.json', { kind: 'file', bytes: new TextEncoder().encode(JSON.stringify(order)) })
await activate(store, deriveHostCacheKey('one-too-many'))
expect(fs.paths().some((path) => path.startsWith(orphan))).toBe(false)
expect((await store.readActiveGeneration(oldest))?.buildId).toBe(BUILD)
})
it('never counts or evicts a host that is only mid-download', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const hosts = hostKeys(MAX_CACHED_HOSTS)
const oldest = hosts[0]
const downloading = deriveHostCacheKey('downloading')
for (const host of hosts) {
await activate(store, host)
}
const staged = await store.stageGeneration(downloading, buildResult({}))
await activate(store, deriveHostCacheKey('one-too-many'))
// Count activations only; eviction must leave staged downloads intact.
expect(fs.paths().some((path) => path.startsWith(oldest))).toBe(false)
expect(fs.text(`${staged.directory.slice(ROOT.length + 1)}/manifest.json`)).not.toBeNull()
await store.commitGeneration(staged)
expect((await store.readActiveGeneration(downloading))?.buildId).toBe(BUILD)
})
it('serializes two stage calls for one host and build', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
// Give one build id conflicting asset lists to expose interleaved writes into the same staging directory.
const staging = `${HOST}/tmp/${BUILD}`
const earlier = buildResult({
buildId: BUILD,
assets: [{ path: 'assets/earlier.js', byteLength: 2 }]
})
const later = buildResult({
buildId: BUILD,
assets: [{ path: 'assets/later.js', byteLength: 3 }]
})
const [first, second] = await Promise.all([
store.stageGeneration(HOST, earlier),
store.stageGeneration(HOST, later)
])
expect(first.directory).toBe(second.directory)
expect(fs.writes).toEqual([
`${staging}/assets/earlier.js`,
`${staging}/manifest.json`,
`${staging}/assets/later.js`,
`${staging}/manifest.json`
])
expect(fs.paths().filter((path) => path.startsWith(`${staging}/assets/`))).toEqual([
`${staging}/assets/later.js`
])
})
it('refuses a path that escapes the staged tree, and a host key that is not one', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const escapes = [
'../outside.js',
'assets/../../outside.js',
'/etc/passwd',
'assets//app.js',
'manifest.json',
'Manifest.JSON'
]
for (const path of escapes) {
const result = buildResult({ assets: [{ path, byteLength: 1 }] })
await expect(store.stageGeneration(HOST, result)).rejects.toThrow('refuses to stage')
}
await expect(store.stageGeneration('host-a', buildResult({}))).rejects.toThrow(
'not a host cache key'
)
expect(fs.paths()).toEqual([])
})
it('refuses a rename that did not carry the tree, as Android below API 26 can', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
fs.loseContentsOnMove()
const staged = await store.stageGeneration(HOST, buildResult({}))
await expect(store.commitGeneration(staged)).rejects.toThrow('did not carry its manifest')
expect(await store.readActiveGeneration(HOST)).toBeNull()
expect(fs.paths().some((path) => path.includes('generations/'))).toBe(false)
})
it('keeps the host tree when the manifest read fails, and drops it when it is missing', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
const manifest = `${HOST}/generations/${BUILD}/manifest.json`
await activate(store, HOST)
const before = fs.paths().filter((path) => !path.endsWith('/tmp'))
fs.failReadsAt(manifest)
expect(await store.readActiveGeneration(HOST)).toBeNull()
expect(fs.paths()).toEqual(before)
fs.failReadsAt(null)
await fs.delete(`${ROOT}/${manifest}`)
expect(await store.readActiveGeneration(HOST)).toBeNull()
expect(fs.paths().some((path) => path.startsWith(HOST))).toBe(false)
})
it('replaces an entry named for the build id that is not a readable generation', async () => {
const build = BUILD
// Model a crash between rename and the post-rename manifest check.
for (const seeded of [
{ kind: 'directory' },
{ kind: 'file', bytes: new Uint8Array(1) }
] as const) {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
fs.seed(`${HOST}/generations/${build}`, seeded)
await activate(store, HOST)
expect((await store.readActiveGeneration(HOST))?.buildId).toBe(build)
expect(fs.text(`${HOST}/generations/${build}/index.html`)).not.toBeNull()
}
})
it('refuses a handle whose staged tree is gone without touching the activation', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
await activate(store, HOST)
const staged = await store.stageGeneration(HOST, buildResult(SECOND))
await store.abortStagedGeneration(staged)
await expect(store.commitGeneration(staged)).rejects.toThrow('no longer on disk')
expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD)
})
it('refuses a staged handle it did not issue', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
await activate(store, HOST)
const before = fs.paths()
const forged = {
hostKey: HOST,
buildId: SECOND_BUILD,
directory: `${ROOT}/${HOST}/generations/${BUILD}`,
manifest: buildResult({}).manifest
}
await expect(store.commitGeneration(forged)).rejects.toThrow('did not issue')
await expect(store.abortStagedGeneration(forged)).rejects.toThrow('did not issue')
expect(fs.paths()).toEqual(before)
expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD)
})
it('opens builds kept under the old root without a download once the root moves', async () => {
const fs = createFakeFileSystem()
const legacyRootUri = 'file:///caches/mobile-web'
await activate(createGenerationStore({ fileSystem: { ...fs, rootUri: legacyRootUri } }), HOST)
const store = createGenerationStore({ fileSystem: fs, legacyRootUri })
expect((await store.readActiveGeneration(HOST))?.buildId).toBe(BUILD)
expect(await fs.list(legacyRootUri)).toEqual([])
})
})
describe('reusable assets for the next download', () => {
const NEXT = buildResult({
assets: [
{ path: 'index.html', byteLength: 8 },
{ path: 'assets/app-2.js', byteLength: 2 }
]
})
const NEXT_BUILD = NEXT.manifest.buildId
const [PAGE, SCRIPT] = NEXT.manifest.assets
const DOWNLOADED = new Map([['index.html', new Uint8Array(8).fill(9)]])
const LEFT_TO_STAGE = { ...NEXT, assets: DOWNLOADED, reused: ['assets/app-2.js'] }
it.each([HOST, deriveHostCacheKey('second-host')])(
'matches cached assets by content for %s',
async (opened) => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
expect((await store.openReusableAssets(HOST)).has(SCRIPT!)).toBe(false)
await activate(store, HOST)
const reusable = await store.openReusableAssets(opened)
expect(reusable.has(SCRIPT!)).toBe(true)
expect(reusable.has(PAGE!)).toBe(false)
expect(reusable.has({ ...SCRIPT!, sha256: 'f'.repeat(64) })).toBe(false)
expect(await reusable.check(SCRIPT!)).toBe(true)
fs.seed(`${HOST}/generations/${BUILD}/assets/app.js`, {
kind: 'file',
bytes: new Uint8Array(1)
})
expect(await reusable.check(SCRIPT!)).toBe(false)
}
)
it('copies the reused assets beside the downloaded ones and commits the whole build', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
await activate(store, HOST)
await activate(store, HOST, LEFT_TO_STAGE)
const generation = `${HOST}/generations/${NEXT_BUILD}`
expect(fs.bytes(`${generation}/index.html`)).toEqual(new Uint8Array(8).fill(9))
expect(fs.bytes(`${generation}/assets/app-2.js`)).toEqual(new Uint8Array(2).fill(7))
expect((await store.readActiveGeneration(HOST))?.buildId).toBe(NEXT_BUILD)
})
it('refuses to stage a reused asset the active generation no longer holds', async () => {
const fs = createFakeFileSystem()
const store = createGenerationStore({ fileSystem: fs })
await activate(store, HOST)
fs.failReadsAt(`${HOST}/generations/${BUILD}/assets/app.js`)
await expect(store.stageGeneration(HOST, LEFT_TO_STAGE)).rejects.toThrow('unreadable')
await store.deleteHostCache(HOST)
fs.failReadsAt(null)
await expect(store.stageGeneration(HOST, LEFT_TO_STAGE)).rejects.toThrow(
'no longer holds the reused asset assets/app-2.js'
)
expect(fs.paths().some((path) => path.includes(`tmp/${NEXT_BUILD}`))).toBe(false)
})
})
// Commit deletes the old build first, so it must not run under a page still loading that build's chunks.
describe('an update staged behind a live page', () => {
it('stays staged while a page reads the old build, and the next read after it commits', async () => {
@@ -413,44 +77,24 @@ describe('an update staged behind a live page', () => {
expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${BUILD}/index.html`)).toBe(false)
})
it('lets a page that waited on another page fetch the build itself when that page gives up', async () => {
const store = createGenerationStore({ fileSystem: createFakeFileSystem() })
const first = await store.claimUpdate(HOST, SECOND_BUILD)
const second = store.claimUpdate(HOST, SECOND_BUILD)
first?.()
expect(await second).not.toBeNull()
})
it('commits at the next launch when the app ends while the page still reads the old build', async () => {
it('stages a build without its language-catalog chunks and still commits it at the next launch', async () => {
const fs = createFakeFileSystem()
const first = createGenerationStore({ fileSystem: fs })
await activate(first, HOST)
first.holdGeneration(HOST)
first.deferCommit(await first.stageGeneration(HOST, buildResult(SECOND)))
const withCatalog = buildResult({
assets: [
{ path: 'index.html', byteLength: 8 },
{ path: 'assets/de.js', byteLength: 3, kind: 'catalog' }
],
bytes: new Map([['index.html', new Uint8Array(8)]])
})
first.deferCommit(await first.stageGeneration(HOST, withCatalog))
const relaunched = createGenerationStore({ fileSystem: fs })
expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(SECOND_BUILD)
expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${SECOND_BUILD}/index.html`)).toBe(true)
})
it('lets a reader of a host’s build go before a commit or a removal deletes it', async () => {
const fs = createFakeFileSystem()
const onDisk: boolean[] = []
let reading = BUILD
const store = createGenerationStore({
fileSystem: fs,
beforeHostFilesDeleted: async (hostKey) => {
onDisk.push(await fs.fileExists(`${ROOT}/${hostKey}/generations/${reading}/manifest.json`))
}
})
await activate(store, HOST)
onDisk.length = 0
await activate(store, HOST, buildResult(SECOND))
reading = SECOND_BUILD
await store.deleteHostCache(HOST)
expect(onDisk).toEqual([true, true])
const build = withCatalog.manifest.buildId
expect((await relaunched.readActiveGeneration(HOST))?.buildId).toBe(build)
expect(await fs.fileExists(`${ROOT}/${HOST}/generations/${build}/assets/de.js`)).toBe(false)
})
})
@@ -25,6 +25,7 @@ export type MobileWebShellGates = {
export type MobileWebShellManifestFacts = MobileWebBundleCompatManifest & {
readonly buildId: string
// A download with nothing to reuse, in fetch progress's unit (each brotli copy where read, else asset bytes).
readonly totalBytes: number
readonly totalAssets: number
// Older desktops omit routes and serve none.
@@ -1,8 +1,10 @@
import { fetchMobileWebBundle } from '../transport/web-bundle/mobile-web-bundle-fetch'
import { mobileWebBundleStreamBytes } from '../transport/web-bundle/mobile-web-bundle-window-reader'
import { mobileWebBundleManifestRead } from '../transport/web-bundle/mobile-web-bundle-operations'
import type {
MobileWebBundleManifestRead,
MobileWebBundleManifestReply
import {
shellDownloadedAssets,
type MobileWebBundleManifestRead,
type MobileWebBundleManifestReply
} from '../transport/web-bundle/mobile-web-bundle-reply-schemas'
import type { MobileWebBundleCompatManifest } from '../transport/web-bundle/mobile-web-bundle-compat'
import { runRpcOperation } from '../transport/rpc/rpc-operation'
@@ -87,8 +89,9 @@ export async function readManifest(
manifest: {
...compatOf(manifest),
buildId: manifest.buildId,
totalBytes: manifest.totalBytes,
totalAssets: manifest.assets.length,
// What this shell downloads: wire bytes, without the catalog chunks it skips.
totalBytes: mobileWebBundleStreamBytes(opened),
totalAssets: shellDownloadedAssets(manifest).length,
routes: manifest.routes
}
})
@@ -1,56 +0,0 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('expo-file-system', () => ({ Directory: class {}, File: class {}, Paths: { cache: '' } }))
vi.mock('./generation-store-file-system', async () => {
const { createFakeGenerationFileSystem } = await import('./generation-file-system-fake')
const fileSystem = createFakeGenerationFileSystem()
return { createExpoGenerationFileSystem: () => fileSystem }
})
import { createGenerationStore } from './generation-store'
import { createExpoGenerationFileSystem } from './generation-store-file-system'
import { forgetHostUpdateFailures } from './removed-host-shell-cache'
function store() {
return createGenerationStore({ fileSystem: createExpoGenerationFileSystem('') })
}
async function seed(hostId: string): Promise<void> {
await store().recordUpdateFailure({
hostId,
at: 1,
reason: 'connection-lost',
hostCode: null,
offeredBuildId: null,
cachedBuildId: null,
outcome: 'opened-cached',
wall: null
})
}
describe('forgetHostUpdateFailures', () => {
beforeEach(async () => {
await store().forgetHostUpdateFailures('host-1')
await store().forgetHostUpdateFailures('host-2')
})
it("drops the removed host's records and keeps the rest", async () => {
await seed('host-1')
await seed('host-2')
await forgetHostUpdateFailures('host-1')
expect((await store().readUpdateFailures()).map((entry) => entry.hostId)).toEqual(['host-2'])
})
it('writes nothing when nothing was recorded', async () => {
const fileSystem = createExpoGenerationFileSystem('')
expect(await fileSystem.readText(`${fileSystem.rootUri}/update-failures.json`)).toBeNull()
const write = vi.spyOn(fileSystem, 'writeText')
try {
await forgetHostUpdateFailures('host-1')
expect(write).not.toHaveBeenCalled()
expect(await fileSystem.readText(`${fileSystem.rootUri}/update-failures.json`)).toBeNull()
} finally {
write.mockRestore()
}
})
})
@@ -1,5 +1,5 @@
import { useEffect, useLayoutEffect, useRef } from 'react'
import { AppState } from 'react-native'
import { AppState, Platform } from 'react-native'
/**
* Calls `onLeave` once each time the app leaves the foreground, before the system can kill it from the app
@@ -29,13 +29,17 @@ export function useAppLeavesForeground(onLeave: () => void): void {
const change = AppState.addEventListener('change', (next) =>
next === 'active' ? back() : leave()
)
// Window focus events come from Android only.
const blur = AppState.addEventListener('blur', leave)
const focus = AppState.addEventListener('focus', back)
// Window focus events come from Android only; iOS's RCTAppState rejects the subscription outright
// (a red screen in development), so it is never made there.
const windowFocus =
Platform.OS === 'android'
? [AppState.addEventListener('blur', leave), AppState.addEventListener('focus', back)]
: []
return () => {
change.remove()
blur.remove()
focus.remove()
for (const subscription of windowFocus) {
subscription.remove()
}
}
}, [])
}
+1 -1
View File
@@ -16,7 +16,7 @@ import { hostProjectSectionsQuery } from '../host-screen/use-host-project-sectio
import { sessionTabsFamily, sessionTabsKey } from '../session/tabs/mobile-session-last-tabs'
import type { MobileSessionTab } from '../session/tabs/mobile-session-tabs'
import { activeSessionTabOf } from '../session/tabs/active-session-tab'
import { storedTabChatTranscriptIdentity } from '../session/native-chat/mobile-native-chat-transcript-store'
import { storedTabChatTranscriptIdentity } from '../session/native-chat/transcript/mobile-native-chat-transcript-store'
import { gitStatusQuery } from '../source-control/mobile-git-status-query'
import { firstPaintTaskKeys } from '../tasks/task-query-storage'
import { hostQueryKey } from './host-query-key'
+1 -1
View File
@@ -1,6 +1,6 @@
import type { QueryClient } from '@tanstack/react-query'
import type { PageDeviceStore } from '../mobile-web-shell/bridge/page-device-store'
import { primeStoredChatTranscripts } from '../session/native-chat/mobile-native-chat-transcript-store'
import { primeStoredChatTranscripts } from '../session/native-chat/transcript/mobile-native-chat-transcript-store'
import { firstPaintChatTranscriptIdentity, firstPaintQueryKeys } from './first-paint-query-keys'
import { createHostQueryPersistence } from './host-query-persistence'

Some files were not shown because too many files have changed in this diff Show More