Merge remote-tracking branch 'origin/main' into orch-one-step-dispatch

This commit is contained in:
Jinwoo-H
2026-10-28 13:27:15 -04:00
1153 changed files with 67756 additions and 7697 deletions
+10 -3
View File
@@ -53,6 +53,15 @@ pnpm install
pnpm dev
```
`mobile/` is a separate pnpm project with its own lockfile, so the root `pnpm install` leaves its
dependencies uninstalled. `pnpm build` (`build:mobile-web` fails without them) and the lint
passes that cover `mobile/` need them. Install them before building or linting, and again
when `mobile/pnpm-lock.yaml` changes:
```bash
pnpm -C mobile install --frozen-lockfile
```
### Dev Profiles and Parallel Instances
`pnpm dev` in a linked Git worktree uses its own userData profile, renderer port, and remote
@@ -170,7 +179,7 @@ Avoid vague names like `test`, `misc`, or `changes`.
## Before Opening a PR
Run the same checks that CI runs:
Run the same checks that CI runs, after the `mobile/` install from [Local Setup](#local-setup):
```bash
pnpm lint
@@ -261,8 +270,6 @@ All stable kinds (`patch`, `minor`, `major`) are computed off the latest _stable
- **One-off RC for a feature branch:** `kind=rc`, `ref=<branch-or-sha>`. Produces an RC tag that does not touch `main`.
- **Minor or major bump:** `kind=minor` or `kind=major`.
The scheduled 2x/day RC cron in [`release-rc.yml`](../../actions/workflows/release-rc.yml) is independent and continues to run automatically from `main`.
## Release Channels
The public Homebrew cask tracks stable desktop releases:
+1
View File
@@ -81,6 +81,7 @@ jobs:
/config/scripts/pr-layout-oracle-route.mjs
/config/scripts/pr-e2e-source-routing.mjs
/config/scripts/pr-browser-e2e-source-routes.mjs
/config/scripts/pr-editor-preview-e2e-source-routes.mjs
/config/scripts/ci-e2e-job-selection.mjs
/config/scripts/pr-ready-check-reuse.mjs
sparse-checkout-cone-mode: false
+4 -4
View File
@@ -151,8 +151,8 @@ jobs:
name: WSL2 distro (${{ matrix.family }})
needs: [template, container-rootfs]
runs-on: windows-2025
# Healthy runs take 4-11 min; a runner frozen during WSL2 setup is only reaped here (retried by wsl-orcad-e2e-frozen-runner-retry.yml).
timeout-minutes: 30
# Healthy runs take 4-11 min plus the phase 3 restart baseline; a runner frozen during WSL2 setup is only reaped here (retried by wsl-orcad-e2e-frozen-runner-retry.yml).
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
@@ -355,8 +355,8 @@ jobs:
if ($global:LASTEXITCODE -ne 0) { throw "WSL move real pause failed: $global:LASTEXITCODE" }
wsl.exe --terminate $env:PLAIN_DISTRO
# R40: with no terminal left, orcad idle-exits and the holder lets the distro stop on its own.
- name: 'Phase 3: idle orcad releases the distro'
timeout-minutes: 15
- name: 'Phase 3: idle orcad releases the distro; distro restart to first output baseline'
timeout-minutes: 30
env:
ORCA_RUN_WSL_ORCAD_LANE: '1'
ORCA_WSL_ORCAD_LANE_PHASE: idle-release
+2 -2
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="docs/readme/README.zh-CN.md">中文</a> · <a href="docs/readme/README.ja.md">日本語</a> · <a href="docs/readme/README.ko.md">한국어</a> · <a href="docs/readme/README.es.md">Español</a> · <a href="docs/readme/README.fr.md">Français</a> · <a href="docs/readme/README.pt.md">Português</a> · <a href="docs/readme/README.tr.md">Türkçe</a></sub>
<sub><a href="docs/readme/README.zh-CN.md">中文</a> · <a href="docs/readme/README.ja.md">日本語</a> · <a href="docs/readme/README.ko.md">한국어</a> · <a href="docs/readme/README.es.md">Español</a> · <a href="docs/readme/README.fr.md">Français</a> · <a href="docs/readme/README.pt.md">Português</a> · <a href="docs/readme/README.tr.md">Türkçe</a> · <a href="docs/readme/README.ru.md">Русский</a></sub>
</p>
<p align="center">
@@ -272,7 +272,7 @@ The relay that pairs the mobile app with a desktop host is also in this reposito
## Signed Builds
Windows code signing sponored/provided by [SignPath.io](https://signpath.io), certificate by [SignPath Foundation](https://signpath.org).
Windows code signing sponsored/provided by [SignPath.io](https://signpath.io), certificate by [SignPath Foundation](https://signpath.org).
## License
-1
View File
@@ -3,7 +3,6 @@
# This is a RATCHET: counts may only go DOWN.
# Prune after removing calls: pnpm check:daemon-blocking-call-ratchet --prune
2 src/main/daemon/daemon-cgroup-scope.ts
1 src/main/daemon/daemon-file-log.ts
1 src/main/daemon/daemon-process-identity-query.ts
1 src/main/daemon/daemon-process-start-time.ts
2 src/main/daemon/daemon-stream-backlog-probe.ts
+2 -1
View File
@@ -3,7 +3,8 @@
# This is a RATCHET: counts may only go DOWN. Only creation flows with no source row may read
# the default host, through defaultCreationHost. Everything else routes by the owner.
# Prune after removing reads: pnpm check:focus-read-ratchet --prune
3 src/renderer/src/app-shell/use-app-shell-services.ts
1 src/renderer/src/app-shell/ActiveWorkspaceSyncGate.tsx
2 src/renderer/src/app-shell/use-app-shell-services.ts
2 src/renderer/src/App.tsx
1 src/renderer/src/component-fixtures/component-fixture-explorer.tsx # dev-only fixture page seeds default settings
1 src/renderer/src/components/activity/activity-scope-filter-controls.tsx
+71
View File
@@ -0,0 +1,71 @@
# German (de) UI Glossary and Style
Catalog: `src/renderer/src/i18n/locales/de.json`. Missing keys fall back to English at runtime. System detection maps `de`, `de-DE`, `de-AT`, `de-CH` and POSIX tags such as `de_DE.UTF-8` to `de`.
## Voice
- Avoid addressing the user. Prefer neutral phrasing: `Branch auswählen`, `Keine Worktrees gefunden`, `Datei konnte nicht gespeichert werden.`
- When a sentence must address the user, use informal `du` consistently (`dein`, `dir`), lowercase. Never use `Sie`.
- Buttons, menu items and commands use the infinitive: `Öffnen`, `Speichern`, `Löschen`, `Entfernen`, `Erneut versuchen`, `Abbrechen`.
- Failures: `… konnte nicht geladen werden.` in sentences, `Laden fehlgeschlagen` in short labels.
- Confirmations are impersonal questions: `Fenster schließen?`, `Worktree löschen?`
- German has no title case. Capitalize nouns and the first word only, even when the English label uses title case. Keep brand names and acronyms as written.
- Labels have no final period. Use `…`, not `...`. Use German quotes `„…“` in prose; keep backticks and code quoting as in the source.
- Join English terms to German words with a hyphen: `Worktree-Name`, `Branch-Name`, `SSH-Verbindung`, `PR-Titel`, `Git-Repository`.
- German strings run about 30% longer than English. Prefer the shorter natural wording for buttons, tabs and badges, but never drop meaning.
- Plurals follow English (`_one` / `_other`). Keep `{{count}}` wherever the English form has it.
## Terms
Keep Git and developer terms that German developers use in English. Use the noun genders below for articles and adjective endings.
| English | German | Note |
| ---------------------------- | --------------------------------------------- | ---------------------------------------------------------- |
| worktree | der Worktree, die Worktrees | Distinct from workspace. |
| workspace | der Arbeitsbereich | |
| repository / repo | das Repository (die Repositorys) / das Repo | |
| branch / base branch | der Branch (die Branches) / Basis-Branch | |
| commit | der Commit; verb `committen` | |
| pull request / PR | der Pull Request / PR | `merge request` stays `Merge Request` (GitLab). |
| merge, rebase, diff, stash | Merge, Rebase, Diff, Stash | Verbs: `mergen`, `rebasen`, `stashen`. |
| checkout | Checkout; verb `auschecken` | |
| push / pull / fetch | Push / Pull / Fetch | Verbs: `pushen`, `pullen`, `fetchen`. |
| remote (Git) / remote host | das Remote / Remote-Host | `remote` as an adjective: `entfernt`. |
| issue | das Issue | |
| review / code review | das Review / Code-Review | |
| check (CI) | der Check | |
| label (issue/PR) | das Label, die Labels | |
| approve / comment | genehmigen / der Kommentar | |
| source control | Quellcodeverwaltung | |
| agent | der Agent, die Agenten | |
| chat / prompt | der Chat / der Prompt | |
| skill / plugin / hook | der Skill / das Plugin / der Hook | |
| session | die Sitzung | |
| terminal / shell | das Terminal / die Shell | |
| tab | der Tab | The keyboard key stays `Tab`. |
| pane / panel | der Bereich / das Panel | Split pane: `Bereich teilen`. Keep the two terms distinct. |
| sidebar / status bar | die Seitenleiste / die Statusleiste | |
| editor / browser | der Editor / der Browser | |
| command palette / quick open | Befehlspalette / Schnellöffnen | |
| file / folder / directory | Datei / Ordner / Verzeichnis | |
| project | das Projekt | |
| host / server / SSH host | der Host / der Server / der SSH-Host | |
| automation / task | die Automatisierung / die Aufgabe | |
| dashboard | das Dashboard | |
| settings | die Einstellungen | |
| shortcut / keybinding | das Tastenkürzel / die Tastenbelegung | |
| sign in / sign out | anmelden / abmelden | |
| account / provider / model | das Konto / der Anbieter / das Modell | |
| token (LLM or auth) | der Token | |
| usage / quota / rate limit | die Nutzung / das Kontingent / das Ratenlimit | |
| credits / balance | Credits / das Guthaben | |
| notification | die Benachrichtigung | |
| delete / remove | löschen / entfernen | Keep the two terms distinct. |
| enable / disable / default | aktivieren / deaktivieren / Standard | |
| pin / unread / archive | anheften / ungelesen / archivieren | |
| environment / sandbox | die Umgebung / die Sandbox | |
| dictation | das Diktat; verb `diktieren` | |
| clipboard | die Zwischenablage | |
| port forwarding | die Portweiterleitung | |
Do not translate placeholders (`{{value0}}`), markup, commands, paths, keyboard keys, or labels that belong to another product's UI.
@@ -20,6 +20,13 @@
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/components/settings/appearance-search.ts",
"kind": "object-property:keywords",
"text": "Sprache",
"dynamic": false,
"count": 1
},
{
"filePath": "src/renderer/src/components/settings/appearance-search.ts",
"kind": "object-property:keywords",
-13
View File
@@ -1,13 +0,0 @@
diff --git a/dist/chunks/cli-api.De07GUeT.js b/dist/chunks/cli-api.De07GUeT.js
--- a/dist/chunks/cli-api.De07GUeT.js
+++ b/dist/chunks/cli-api.De07GUeT.js
@@ -11817,7 +11817,8 @@ class TestRun {
else error.stacks = parseErrorStacktrace(error, {
frameFilter: project.config.onStackTrace,
getSourceMap(file) {
- if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && existsSync(file)) {
+ // Orca: stack frames can name a directory; existsSync accepts it and readFileSync then throws EISDIR, failing a green run.
+ if (!project.vite.moduleGraph.getModuleById(file)?.transformResult && statSync(file, { throwIfNoEntry: false })?.isFile()) {
const code = readFileSync(file, "utf-8");
return extractSourcemapFromFile(code, file)?.map;
}
+1 -1
View File
@@ -5,7 +5,7 @@ import process from 'node:process'
import { repairTranslatedValue } from './locale-translation-policy.mjs'
const LOCALES_DIR = path.join('src', 'renderer', 'src', 'i18n', 'locales')
const SUPPORTED_LOCALES = new Set(['es', 'fr', 'ja', 'ko', 'ru', 'zh'])
const SUPPORTED_LOCALES = new Set(['de', 'es', 'fr', 'ja', 'ko', 'ru', 'zh'])
const PLACEHOLDER_RE = /\{\{[^}]+\}\}/g
function placeholders(value) {
@@ -0,0 +1,167 @@
import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { createRequire } from 'node:module'
import { tmpdir } from 'node:os'
import { dirname, join, resolve } from 'node:path'
import { performance } from 'node:perf_hooks'
const root = resolve(import.meta.dirname, '../..')
const baseline = process.argv[2] ?? 'HEAD^'
const require = createRequire(join(root, 'package.json'))
const { build } = require('esbuild')
const relative = 'src/main/browser/browser-session-registry.ts'
const target = join(root, relative)
const scratch = mkdtempSync(join(tmpdir(), 'orca-browser-meta-bench-'))
const previousSource = execFileSync('git', ['show', `${baseline}:${relative}`], {
cwd: root,
encoding: 'utf8'
})
const sources = { before: previousSource, after: readFileSync(target, 'utf8') }
const stubs = new Map([
[
'electron',
'export const app={getPath:()=>globalThis.__metaBench.directory}; export const session={fromPartition:()=>({})};'
],
[
'./browser-session-cookie-staging',
'export function applyPendingBrowserCookieImports(){} export function clearPendingBrowserCookieImport(){}'
],
[
'./browser-session-partition-policies',
'export async function installBrowserSessionPartitionPolicies(){}'
],
[
'./browser-session-route-policies',
'export function clearBrowserRoutePartitionPolicies(){} export async function installBrowserRoutePartitionPolicies(){}'
],
[
'./browser-session-profile-retirement',
'export async function retireDeletedBrowserSessionProfile(){} export async function retireFailedBrowserSessionProfile(){}'
],
[
'../persistence/loading-store/user-data-path',
'export function getCanonicalUserDataPath(){return globalThis.__metaBench.directory}'
],
[
'./browser-identity-mode-store',
'export async function markBrowserIdentityMigrationNoticePending(){}'
],
['./browser-site-permission-store', 'export function forgetBrowserSitePermissions(){}'],
['./browser-site-display-store', 'export function forgetBrowserSiteDisplay(){}'],
[
'./extensions/browser-extension-session-loader',
'export function attachBrowserExtensionsToProfileSession(profile,ids){globalThis.__metaBench.assignments.push([profile.id,ids])}'
]
])
const registryByVersion = {}
try {
for (const [version, source] of Object.entries(sources)) {
const output = join(scratch, `${version}.cjs`)
await build({
stdin: { contents: source, sourcefile: target, resolveDir: dirname(target), loader: 'ts' },
bundle: true,
platform: 'node',
format: 'cjs',
outfile: output,
plugins: [
{
name: 'isolate-startup-metadata',
setup(builder) {
builder.onResolve({ filter: /.*/ }, (args) => {
if (args.importer === target && stubs.has(args.path)) {
return { path: args.path, namespace: 'startup-stub' }
}
if (
args.path === 'node:fs' &&
args.importer.endsWith('/browser-session-meta-store.ts')
) {
return { path: 'fs-probe', namespace: 'startup-stub' }
}
})
builder.onLoad({ filter: /.*/, namespace: 'startup-stub' }, (args) => ({
contents:
args.path === 'fs-probe'
? `import * as fs from 'node:fs'; export const {mkdirSync,renameSync,writeFileSync}=fs; export function readFileSync(...args){const result=fs.readFileSync(...args);globalThis.__metaBench.reads++;globalThis.__metaBench.bytes+=Buffer.byteLength(result);return result}`
: stubs.get(args.path),
loader: 'js'
}))
}
}
]
})
globalThis.__metaBench = { directory: scratch, reads: 0, bytes: 0, assignments: [] }
registryByVersion[version] = require(output).browserSessionRegistry
}
const rows = []
for (const count of [10, 100, 1000]) {
const profiles = Array.from({ length: count }, (_, index) => {
const id = `00000000-0000-4000-8000-${index.toString(16).padStart(12, '0')}`
return {
id,
scope: 'isolated',
partition: `persist:orca-browser-session-${id}`,
label: `Browser ${index}`,
source: null
}
})
const enabledExtensionIdsByProfileId = Object.fromEntries([
['default', ['default-extension']],
...profiles.map((profile, index) => [profile.id, [`extension-${index}`]])
])
const json = JSON.stringify({ profiles, enabledExtensionIdsByProfileId })
writeFileSync(join(scratch, 'browser-session-meta.json'), json)
const row = { profiles: count, metadataBytes: Buffer.byteLength(json) }
let beforeAssignments
for (const [version, registry] of Object.entries(registryByVersion)) {
const timings = []
for (let iteration = 0; iteration < 4; iteration++) {
globalThis.__metaBench = { directory: scratch, reads: 0, bytes: 0, assignments: [] }
registry.configureForOrcaProfile({
orcaProfileId: 'local-default',
profileDirectory: scratch
})
globalThis.__metaBench.reads = 0
globalThis.__metaBench.bytes = 0
const start = performance.now()
registry.initializeBrowserSessionsFromPersistedState()
const durationMs = performance.now() - start
const probe = globalThis.__metaBench
assert.equal(probe.reads, version === 'before' ? count + 2 : 1)
assert.equal(registry.listProfiles().length, count + 1)
assert.equal(probe.assignments.length, count + 1)
if (version === 'before') {
beforeAssignments = probe.assignments
} else {
assert.deepEqual(probe.assignments, beforeAssignments)
}
if (iteration > 0) {
timings.push(durationMs)
}
row[version] = { reads: probe.reads, bytes: probe.bytes }
await Promise.resolve()
}
timings.sort((left, right) => left - right)
row[version].medianSynchronousMs = Number(timings[1].toFixed(3))
}
rows.push(row)
}
console.log(
JSON.stringify(
{
node: process.version,
platform: process.platform,
baseline,
productionSeam: 'initializeBrowserSessionsFromPersistedState',
limitations:
'Warm local filesystem; actual registry, JSON parser, profile validation and disk reads. Electron policy installation and extension loading stubbed. Synchronous hydration only; excludes process startup and guest creation.',
rows
},
null,
2
)
)
} finally {
rmSync(scratch, { recursive: true, force: true })
delete globalThis.__metaBench
}
+9 -4
View File
@@ -2,12 +2,13 @@ import { availableParallelism } from 'node:os'
import { createRequire } from 'node:module'
import { dirname, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { runProcess, runProcessSync } from '@orca/process-host'
import { resolvePinnedBunExecutable } from './pinned-bun-executable.mjs'
import { runProcess } from '@orca/process-host'
import { describeProcessFailure } from './process-failure-message.mjs'
import { isDirectInvocation } from './script-entry-detection.mjs'
import { supportsTsrs } from './tsrs-typecheck-compiler.mjs'
import {
resolveProjectCompiler,
resolveTypecheckBunExecutable,
runTypecheckProjects,
selectTypecheckCompiler
} from './run-typecheck-projects-in-parallel.mjs'
@@ -21,7 +22,7 @@ export async function buildCli({
check = runTypecheckProjects,
execute = runProcess,
compiler = process.env.ORCA_CLI_BUILD_COMPILER ?? 'bun',
resolveBunExecutable = (directory) => resolvePinnedBunExecutable(directory, runProcessSync)
resolveBunExecutable = resolveTypecheckBunExecutable
} = {}) {
if (compiler !== 'bun' && compiler !== 'tsrs') {
throw new Error(`Invalid ORCA_CLI_BUILD_COMPILER: ${compiler}`)
@@ -50,7 +51,11 @@ export async function buildCli({
}
return
}
const selection = selectTypecheckCompiler('bun', { root, resolveBunExecutable })
const selection = selectTypecheckCompiler('bun', {
root,
resolveBunExecutable,
fallbackHint: supportsTsrs() ? 'set ORCA_CLI_BUILD_COMPILER=tsrs' : null
})
const failures = await check({
...selection,
root,
@@ -1,6 +1,7 @@
import { readFile } from 'node:fs/promises'
import { readRouteSnapshot } from './mobile-web-app/mobile-web-app-route-snapshot.mjs'
import { realpathSync } from 'node:fs'
import { MOBILE_WEB_APP_DEPENDENCY_PATH } from './mobile-web-app/mobile-web-app-bundle-dependencies.mjs'
import { existsSync, realpathSync } from 'node:fs'
import { basename, extname, join, resolve } from 'node:path'
import { createRequire } from 'node:module'
import { fileURLToPath } from 'node:url'
@@ -503,6 +504,12 @@ export async function buildMobileWebAppBundle({
}
if (isDirectInvocation(import.meta.url, process.argv[1])) {
if (!existsSync(MOBILE_WEB_APP_DEPENDENCY_PATH)) {
console.error(
'[build-mobile-web-app-bundle] mobile/ dependencies are not installed; run `pnpm -C mobile install --frozen-lockfile`'
)
process.exit(1)
}
try {
const { manifest, outDir, routeKeys, entryStaticBytes, chunkCount } =
await buildMobileWebAppBundle()
@@ -193,6 +193,7 @@ export function collectAddedLineRanges(
const source = renamedSources.get(file)
const paths = source ? [source, file] : [file]
const diff = runGit(root, [
'--literal-pathspecs',
'diff',
'--find-renames',
'--unified=0',
@@ -70,6 +70,42 @@ describe('changed-code quality line matching', () => {
).toBe(true)
})
it.each(['edit', 'rename'])('treats bracketed filenames literally after %s', (change) => {
const repo = mkdtempSync(path.join(tmpdir(), 'changed-code-quality-literal-'))
try {
const hooks = `core.hooksPath=${path.join(repo, '.git', 'no-hooks')}`
const git = (...args) => {
const result = runProcessSync({
program: 'git',
args: ['-c', 'commit.gpgsign=false', '-c', hooks, ...args],
cwd: repo
})
expect(result.code, result.stderr).toBe(0)
return result.stdout.trim()
}
git('init', '--quiet')
const file = '[cd].ts'
const source = change === 'rename' ? '[ab].ts' : file
const content = 'export const first = 1\n\nexport const legacy = 3\n'
writeFileSync(path.join(repo, source), content)
writeFileSync(path.join(repo, 'c.ts'), content)
git('add', '.')
git('-c', 'user.name=t', '-c', 'user.email=t@example.invalid', 'commit', '-qm', 'base')
const base = git('rev-parse', 'HEAD')
if (change === 'rename') {
git('mv', source, file)
}
writeFileSync(path.join(repo, file), content.replace('first = 1', 'first = 2'))
writeFileSync(path.join(repo, 'c.ts'), content.replace('legacy = 3', 'legacy = 4'))
const { rangesByFile } = collectAddedLineRanges(repo, base)
expect(rangesByFile.get(file)).toEqual([{ start: 1, end: 1 }])
expect(rangesByFile.get('c.ts')).toEqual([{ start: 3, end: 3 }])
} finally {
rmSync(repo, { recursive: true, force: true })
}
})
it('discovers nested rule overrides while retaining root diagnostics', () => {
const root = path.resolve(import.meta.dirname, '..', '..')
const directory = mkdtempSync(path.join(root, 'config', 'changed-code-quality-nested-'))
+9 -5
View File
@@ -7,7 +7,7 @@ import { pathToFileURL } from 'node:url'
// Docs-only CI skips some media owners; check index paths because GitHub cannot render uncommitted docs-site/feature-wall assets.
const TRANSLATED_README_DIR = path.join('docs', 'readme')
const EXTERNAL_TARGET = /^(?:[a-z][a-z0-9+.-]*:|#|\/\/)/i
const HTML_ATTRIBUTE = /\b(?:src|srcset|href)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
const HTML_ATTRIBUTE = /\b(src|srcset|href)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
const MARKDOWN_LINK = /!?\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g
function readmeFiles(root) {
@@ -32,10 +32,14 @@ function trackedFiles(root, candidates) {
}
function* localTargets(markdown) {
for (const match of markdown.matchAll(HTML_ATTRIBUTE)) {
// srcset lists candidates; each begins with its URL.
for (const candidate of (match[1] ?? match[2]).split(',')) {
const target = candidate.trim().split(/\s+/)[0]
for (const [, attribute, doubleQuoted, singleQuoted] of markdown.matchAll(HTML_ATTRIBUTE)) {
const value = doubleQuoted ?? singleQuoted
// Only srcset lists candidates; each begins with its URL. src/href hold one whole URL.
const targets =
attribute === 'srcset'
? value.split(',').map((candidate) => candidate.trim().split(/\s+/)[0])
: [value.trim()]
for (const target of targets) {
if (target) {
yield target
}
@@ -44,7 +44,9 @@ const validReadmes = {
"<img src='resources/build/icon.png' />",
'<img src="https://img.shields.io/badge/x-y-z" />',
'[Contributing](.github/CONTRIBUTING.md) [Docs](https://example.com/docs) [Top](#top)',
'![hero](docs/assets/hero%20image.jpg "Hero")'
'![hero](docs/assets/hero%20image.jpg "Hero")',
// src/href hold one URL; only srcset is a comma-separated list.
'<img src="docs/assets/hero image,wide.jpg" /> <a href=\'https://example.com/docs?pages=one,two\'>Docs</a>'
].join('\n'),
'docs/readme/README.ja.md': [
'<img src="../../resources/build/icon.png" />',
@@ -56,6 +58,7 @@ const validReadmes = {
'resources/onboarding/feature-wall/tile-01.poster.jpg': 'jpg',
'docs/site/public/docs/tab-split.gif': 'gif',
'docs/assets/hero image.jpg': 'jpg',
'docs/assets/hero image,wide.jpg': 'jpg',
'.github/CONTRIBUTING.md': 'contributing',
LICENSE: 'mit'
}
@@ -77,6 +80,38 @@ describe('README local link check', () => {
expect(findBrokenReadmeLinks(makeFixture(validReadmes))).toEqual([])
})
it('rejects a missing full URL even when its split fragments are tracked', () => {
const root = makeFixture({
...validReadmes,
'README.md': '<img src="docs/assets/missing image,wide.jpg" />',
'docs/assets/missing': 'fragment',
'wide.jpg': 'fragment'
})
expect(findBrokenReadmeLinks(root)).toEqual([
{
readme: 'README.md',
target: 'docs/assets/missing image,wide.jpg',
resolved: 'docs/assets/missing image,wide.jpg'
}
])
})
it('continues checking each srcset candidate without its descriptor', () => {
const root = makeFixture({
...validReadmes,
'README.md': '<source srcset="resources/build/icon.png 1x, docs/assets/missing.png 2x">'
})
expect(findBrokenReadmeLinks(root)).toEqual([
{
readme: 'README.md',
target: 'docs/assets/missing.png',
resolved: 'docs/assets/missing.png'
}
])
})
it('checks tracked media outside the detector sparse checkout', () => {
const root = makeFixture(validReadmes)
const workflow = parse(readFileSync(path.join(projectDir, '.github/workflows/pr.yml'), 'utf8'))
+3 -4
View File
@@ -6213,7 +6213,6 @@
"src/main/skills/skill-remote-install-service.test.ts": 120,
"src/main/skills/skill-remove-transaction.test.ts": 439,
"src/main/skills/skill-root-file-walk.test.ts": 46,
"src/main/skills/skill-runtime-capability.test.ts": 76,
"src/main/skills/skill-scan-coalescer.test.ts": 58,
"src/main/skills/skill-share-package-name.test.ts": 358,
"src/main/skills/skill-share-preparation-service.test.ts": 343,
@@ -12496,14 +12495,14 @@
"src/shared/native-chat/input/native-chat-slash-commands.omp.test.ts": 54,
"src/shared/native-chat/input/native-chat-slash-commands.test.ts": 52,
"src/shared/native-chat-stopped-send-turn.test.ts": 278,
"src/shared/native-chat-subagent-items.test.ts": 167,
"src/shared/native-chat-subagent-summary.test.ts": 45,
"src/shared/native-chat/transcript/native-chat-subagent-items.test.ts": 167,
"src/shared/native-chat/transcript/native-chat-subagent-summary.test.ts": 45,
"src/shared/native-chat/input/native-chat-task-list-history.test.ts": 58,
"src/shared/native-chat/input/native-chat-task-list.test.ts": 41,
"src/shared/native-chat/transcript/native-chat-text-reveal.test.ts": 27,
"src/shared/native-chat-transcript-contracts.test.ts": 591,
"src/shared/native-chat-transcript-projection.test.ts": 134,
"src/shared/native-chat-transcript-retention.test.ts": 55,
"src/shared/native-chat/transcript/native-chat-transcript-retention.test.ts": 55,
"src/shared/native-chat/transcript/native-chat-turn-activity.test.ts": 137,
"src/shared/native-chat/transcript/native-chat-turn-fold.test.ts": 120,
"src/shared/native-chat-turn-membership.test.ts": 174,
@@ -4337,9 +4337,6 @@
"dashboardPopout.card.you": {
"ko": "나"
},
"dashboardPopout.terminal.closed": {
"ko": "실시간 터미널이 없습니다 — 이 에이전트의 창이 닫혔습니다."
},
"dashboardPopout.terminal.focusWorktree": {
"ko": "워크트리 열기"
},
@@ -7,14 +7,19 @@ const projectDir = fileURLToPath(new URL('../../..', import.meta.url))
// Mobile CI requires dependencies so broken installs fail instead of silently skipping their tests.
export const MOBILE_WEB_APP_DEPENDENCIES_REQUIRED_ENV = 'ORCA_MOBILE_WEB_APP_DEPS_REQUIRED'
export const MOBILE_WEB_APP_DEPENDENCY_PATH = join(
projectDir,
'mobile',
'node_modules',
'react-native-web'
)
const SKIP_NOTICE =
'[mobile-web-app] skipping the bundling tests: mobile/node_modules/react-native-web is absent. ' +
'They run for real in pr.yml, in the mobile_web_app job, which installs mobile dependencies.'
// Sharded root tests omit mobile/node_modules; check availability before bundling react-native-web pages.
export function mobileWebAppDependenciesPresent(
modulePath = join(projectDir, 'mobile', 'node_modules', 'react-native-web')
) {
export function mobileWebAppDependenciesPresent(modulePath = MOBILE_WEB_APP_DEPENDENCY_PATH) {
if (existsSync(modulePath)) {
return true
}
@@ -388,6 +388,7 @@ function createMobileCiScopeRepository(
'config/scripts/git-pull-request-diff-base.mjs',
'config/scripts/pr-e2e-source-routing.mjs',
'config/scripts/pr-browser-e2e-source-routes.mjs',
'config/scripts/pr-editor-preview-e2e-source-routes.mjs',
'config/scripts/ci-e2e-job-selection.mjs'
]) {
mkdirSync(dirname(join(directory, file)), { recursive: true })
@@ -503,6 +503,21 @@ function selectsManagedSshLane(file) {
return selectPrE2eSpecs([file]).some((spec) => spec.startsWith(MANAGED_SSH_E2E_SPEC_PREFIX))
}
describe('wsl-host remove routing', () => {
it('runs the fake transport spec, which covers Remove, for a remove-path change', () => {
for (const file of [
'src/main/wsl/wsl-host-server-stop.ts',
'src/main/wsl/wsl-host-peer-desktops.ts',
'src/main/wsl/wsl-host-removal.ts'
]) {
expect(selectPrE2eSpecs([file]), file).toContain('tests/e2e/wsl-host-fake-transport.spec.ts')
}
expect(selectPrE2eSpecs(['src/main/wsl/wsl-host-server-stop.test.ts'])).not.toContain(
'tests/e2e/wsl-host-fake-transport.spec.ts'
)
})
})
describe('wsl-host fake connector routing', () => {
it('runs both WSL host specs for a fake connector change', () => {
const specs = selectPrE2eSpecs(['src/main/wsl/wsl-host-e2e-fake-connector.ts'])
+11
View File
@@ -8,6 +8,7 @@ import {
import { MANAGED_SSH_E2E_SPEC_PREFIX } from './ci-e2e-job-selection.mjs'
import { LAYOUT_ORACLE_E2E_SPECS } from './pr-layout-oracle-route.mjs'
import { PR_BROWSER_E2E_SOURCE_ROUTES } from './pr-browser-e2e-source-routes.mjs'
import { PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES } from './pr-editor-preview-e2e-source-routes.mjs'
const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupportSource(file)
@@ -35,6 +36,7 @@ const ENABLED_AUTOMATION_MOVE =
export const PR_E2E_SOURCE_ROUTES = [
...PR_BROWSER_E2E_SOURCE_ROUTES,
...PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES,
{
id: 'ssh.orcad-editor-ownership',
specs: ['tests/e2e/ssh-orcad-editor-ownership.spec.ts'],
@@ -397,6 +399,15 @@ export const PR_E2E_SOURCE_ROUTES = [
specs: ['tests/e2e/wsl-host-fake-transport.spec.ts', 'tests/e2e/wsl-host-chat.spec.ts'],
matches: (file) => file === 'src/main/wsl/wsl-host-e2e-fake-connector.ts'
},
{
// Remove runs through the fake transport spec; its peer check asks the server who else uses it.
id: 'wsl-host.remove',
specs: ['tests/e2e/wsl-host-fake-transport.spec.ts'],
matches: (file) =>
/^src\/main\/wsl\/(?:wsl-host-server-stop|wsl-host-peer-desktops|wsl-host-removal)\.ts$/.test(
file
)
},
{
id: 'terminal.windows-wsl-launch-and-paste',
specs: [
@@ -0,0 +1,35 @@
import { isUnitTestSupportSource } from './pr-code-change-scope.mjs'
const isProductSource = (file) => !/\.test\.tsx?$/.test(file) && !isUnitTestSupportSource(file)
export const PR_EDITOR_PREVIEW_E2E_SOURCE_ROUTES = [
{
// Image, PDF and media viewers read orca-media grants; the PDF reloads exercise remint and range reads.
id: 'editor.byte-range-preview',
specs: [
'tests/e2e/editor-media-playback-position.spec.ts',
'tests/e2e/media-preview-partition-isolation.spec.ts',
'tests/e2e/paired-remote-large-file-open.spec.ts',
'tests/e2e/pdf-find-counter.spec.ts',
'tests/e2e/pdf-viewer-rebuild-recovery.spec.ts',
'tests/e2e/pdf-viewer-reload-cleanup.spec.ts'
],
matches: (file) =>
isProductSource(file) &&
(/^src\/main\/media\/[^/]+\.ts$/.test(file) ||
/^src\/renderer\/src\/components\/editor\/(?:ImageViewer|PdfViewer|pdf-document-loader|pdf-js-document-options|pdf-orca-media-range-transport)\.tsx?$/.test(
file
) ||
/^src\/renderer\/src\/components\/editor\/(?:EditorEditFileSurface|EditorConflictReviewSurface)\.tsx$/.test(
file
) ||
[
'src/main/ipc/filesystem/filesystem-read-handlers.ts',
'src/main/startup/privileged-custom-schemes.ts',
'src/preload/api/fs-bridge.ts',
'src/renderer/src/runtime/runtime-file-range-preview.ts',
'src/renderer/src/runtime/runtime-file-read-client.ts',
'src/shared/file-preview-kind.ts'
].includes(file))
}
]
+2 -2
View File
@@ -1,9 +1,9 @@
import { availableParallelism } from 'node:os'
import { runProcessSync } from '@orca/process-host'
import { resolvePinnedBunExecutable } from './pinned-bun-executable.mjs'
import { describeProcessFailure } from './process-failure-message.mjs'
import { isDirectInvocation } from './script-entry-detection.mjs'
import {
resolveTypecheckBunExecutable,
resolveTypecheckCommand,
selectTypecheckCompiler
} from './run-typecheck-projects-in-parallel.mjs'
@@ -14,7 +14,7 @@ export function runE2eTypecheck({
root = process.cwd(),
compiler = 'bun',
execute = runProcessSync,
resolveBunExecutable = (directory) => resolvePinnedBunExecutable(directory, runProcessSync)
resolveBunExecutable = resolveTypecheckBunExecutable
} = {}) {
const selection = selectTypecheckCompiler(compiler, { root, resolveBunExecutable })
const command = resolveTypecheckCommand(CONFIG, {
@@ -119,9 +119,36 @@ export function parseTypecheckOptions(args) {
return options
}
const NATIVE_COMPILER_HINT = 'pass --compiler=native'
const recoveryAdvice = (action, fallbackHint) =>
fallbackHint ? `${action}, or ${fallbackHint}.` : `${action}.`
export function resolveTypecheckBunExecutable(root, fallbackHint, execute = runProcessSync) {
let timeoutMessage
const executable = resolvePinnedBunExecutable(root, (options) => {
const result = execute(options)
if (result.timedOut) {
timeoutMessage = `Bun version probe timed out after ${options.timeoutMs} ms: ${options.program}. ${recoveryAdvice('Retry when the host is less busy', fallbackHint)}`
}
return result
})
// Optional Bun callers still fall back; required typechecks must explain a timeout.
if (timeoutMessage) {
throw new Error(timeoutMessage)
}
return executable
}
export function selectTypecheckCompiler(
compiler,
{ root, resolveBunExecutable, platform = process.platform, arch = process.arch }
{
root,
resolveBunExecutable,
fallbackHint = NATIVE_COMPILER_HINT,
platform = process.platform,
arch = process.arch
}
) {
if (compiler === 'auto') {
compiler = supportsTsrs(platform, arch) ? 'tsrs' : 'bun'
@@ -132,10 +159,10 @@ export function selectTypecheckCompiler(
if (compiler === 'native' || compiler === 'tsrs') {
return { compiler }
}
const bunExecutable = resolveBunExecutable(root)
const bunExecutable = resolveBunExecutable(root, fallbackHint)
if (!bunExecutable) {
throw new Error(
`Bun ${readPinnedBunVersion(root)} from devDependencies is missing; run pnpm install, or pass --compiler=native.`
`Bun ${readPinnedBunVersion(root)} from devDependencies is missing; ${recoveryAdvice('run pnpm install', fallbackHint)}`
)
}
return { compiler, bunExecutable }
@@ -283,7 +310,7 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href)
const options = parseTypecheckOptions(process.argv.slice(2))
const selection = selectTypecheckCompiler(options.compiler, {
root: repoRoot,
resolveBunExecutable: (root) => resolvePinnedBunExecutable(root, runProcessSync)
resolveBunExecutable: resolveTypecheckBunExecutable
})
const failures = await runTypecheckProjects({ ...options, ...selection })
if (failures.length > 0) {
@@ -12,12 +12,14 @@ import { tmpdir } from 'node:os'
import { join, relative, sep } from 'node:path'
import { fileURLToPath } from 'node:url'
import { describe, expect, it } from 'vitest'
import { resolvePinnedBunExecutable } from './pinned-bun-executable.mjs'
import {
MOBILE_TYPECHECK_PROJECTS,
TYPECHECK_PROJECTS,
admissibleHeapGib,
planTypecheckBatches,
resolveProjectCompiler,
resolveTypecheckBunExecutable,
resolveTypecheckCommand,
parseTypecheckOptions,
selectTypecheckCompiler,
@@ -215,6 +217,38 @@ describe('local and CI compiler selection', () => {
).toThrow('run pnpm install')
})
it('reports a timed-out installed Bun probe without changing optional fallback', () => {
const root = realpathSync(mkdtempSync(join(tmpdir(), 'orca-bun-probe-')))
try {
const manifest = join(root, 'node_modules', 'bun')
mkdirSync(manifest, { recursive: true })
mkdirSync(join(root, 'config'))
writeFileSync(join(root, 'package.json'), '{}')
writeFileSync(join(root, 'config', '.bun-version'), '1.4.4')
writeFileSync(join(manifest, 'package.json'), JSON.stringify({ bin: { bun: 'bin/bun' } }))
const execute = () => ({ code: null, signal: 'SIGTERM', stdout: '', timedOut: true })
expect(resolvePinnedBunExecutable(root, execute)).toBeNull()
expect(() =>
selectTypecheckCompiler('bun', {
root,
resolveBunExecutable: (directory, hint) =>
resolveTypecheckBunExecutable(directory, hint, execute)
})
).toThrow(/Bun version probe timed out after 2000 ms: .*or pass --compiler=native\./)
expect(() => resolveTypecheckBunExecutable(root, null, execute)).toThrow(
/Retry when the host is less busy\.$/
)
expect(
resolveTypecheckBunExecutable(root, null, () => ({ code: 0, stdout: '1.4.4\n' }))
).toBe(join(manifest, 'bin/bun'))
expect(
resolveTypecheckBunExecutable(root, null, () => ({ code: 0, stdout: '1.4.3\n' }))
).toBeNull()
} finally {
rmSync(root, { recursive: true, force: true })
}
})
it('never probes Bun when tsc is requested', () => {
expect(
selectTypecheckCompiler('native', {
@@ -94,6 +94,10 @@ const NODE_RUNTIME_INCLUDE = [
'src/**/*.node-pty.test.ts',
'src/**/node-pty-*.test.ts',
'src/**/*.live-shell.test.ts',
// These drive live zsh through node-pty and rely on Node's native PTY stream delivery.
'src/main/shell-startup-feature-channel.test.ts',
'src/main/daemon/shell-ready.test.ts',
'src/main/daemon/repro-13767-shell-ready-marker-lost-to-exec.test.ts',
'src/**/*real-pty*.test.ts',
'src/**/*-native.test.ts',
'src/**/*retention*.test.ts',
+1 -1
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
+1 -1
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
+1 -1
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
+1 -1
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
+1 -1
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.tr.md">Türkçe</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
+279
View File
@@ -0,0 +1,279 @@
<h1 align="center">
<a href="https://onOrca.dev"><img src="../../resources/build/icon.png" alt="Orca" width="64" valign="middle" /></a> Orca
</h1>
<p align="center">
<a href="https://github.com/stablyai/orca"><img src="https://img.shields.io/github/stars/stablyai/orca?style=flat&amp;label=%E2%98%85&amp;color=08C" alt="Звёзды на GitHub" /></a>
<a href="https://github.com/stablyai/orca/releases"><img src="../assets/readme-downloads.svg" alt="Общее число скачиваний всех выпусков" /></a>
<img src="https://img.shields.io/badge/license-MIT-08C?style=flat" alt="Лицензия: MIT" />
<a href="https://discord.gg/fzjDKHxv8Q"><img src="https://img.shields.io/badge/Discord-5865F2?logo=discord&logoColor=white" alt="Присоединяйтесь к сообществу Orca в Discord" /></a>
<a href="https://x.com/orca_build"><img src="https://img.shields.io/badge/X-000000?logo=x&logoColor=white" alt="Подпишитесь на Orca в X" /></a>
<img src="https://img.shields.io/badge/macOS%20%7C%20Windows%20%7C%20Linux-4493F8?style=flat-square" alt="Поддерживаемые платформы: macOS, Windows и Linux" />
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a></sub>
</p>
<p align="center">
<strong>Оркестратор ИИ для тех, кто создаёт в 100 раз больше.</strong><br/>
Запускайте Codex, ClaudeCode, OpenCode или Pi параллельно — каждый в своём рабочем дереве, все под контролем в одном месте.
</p>
<h3 align="center"><a href="https://onorca.dev/download"><ins>Скачать Orca</ins></a></h3>
<p align="center">
<img src="../assets/readme-hero.jpg" alt="Настольное приложение Orca с агентами в параллельных рабочих деревьях и мобильным приложением Orca в углу" width="960" />
</p>
## Возможности
<table>
<tr>
<td width="50%" valign="middle">
### Мобильное приложение
Следите за агентами и направляйте их работу с телефона — получайте уведомления о завершении задач и отправляйте дополнительные указания откуда угодно.
[App Store для iOS](https://apps.apple.com/us/app/orca-ide/id6766130217) · [APK для Android](https://www.onorca.dev/download/android) · [Документация →](https://www.onorca.dev/docs/mobile)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/mobile"><picture><source srcset="../assets/feature-wall/mobile-companion-app-showcase.gif" type="image/gif"><img src="../assets/feature-wall/mobile-companion-app-showcase.jpg" alt="Настольное и мобильное приложения Orca" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Параллельные рабочие деревья
Отправьте один запрос пяти агентам, каждый из которых работает в своём изолированном рабочем дереве Git, — сравните результаты и слейте лучший вариант.
[Документация →](https://www.onorca.dev/docs/model/worktrees)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/model/worktrees"><picture><source srcset="../site/public/docs/tab-split.gif" type="image/gif"><img src="../site/public/docs/posters/tab-split.jpg" alt="Управление параллельными рабочими деревьями" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Разделение терминала
Терминалы уровня Ghostty с отрисовкой через WebGL, неограниченным разделением на панели и историей вывода, которая сохраняется после перезапуска.
[Документация →](https://www.onorca.dev/docs/terminal)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/terminal"><picture><source srcset="../../resources/onboarding/feature-wall/tile-02.webp" type="image/webp"><img src="../../resources/onboarding/feature-wall/tile-02.poster.jpg" alt="Разделение терминала на панели" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Режим дизайна
Нажмите на любой элемент интерфейса в настоящем окне Chromium, чтобы отправить его HTML, CSS и снимок соответствующей области экрана прямо в запрос агенту.
[Документация →](https://www.onorca.dev/docs/browser/design-mode)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/browser/design-mode"><picture><source srcset="../site/public/docs/orca-design-mode.gif" type="image/gif"><img src="../../resources/onboarding/feature-wall/tile-05.poster.jpg" alt="Встроенный браузер и режим дизайна" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Встроенная поддержка GitHub и Linear
Просматривайте пул-реквесты, задачи и доски проектов прямо в приложении — открывайте рабочее дерево из любой задачи и проверяйте код, не переключая контекст.
[Документация →](https://www.onorca.dev/docs/review/linear)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/review/linear"><picture><source srcset="../../resources/onboarding/feature-wall/tile-03.webp" type="image/webp"><img src="../../resources/onboarding/feature-wall/tile-03.poster.jpg" alt="Работа с задачами GitHub и Linear в Orca" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Рабочие деревья по SSH
Запускайте агентов на мощном удалённом сервере с полноценным редактированием файлов, работой с Git и терминалами — автоматическое переподключение и перенаправление портов уже предусмотрены.
[Документация →](https://www.onorca.dev/docs/ssh)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/ssh"><picture><source srcset="../../resources/onboarding/feature-wall/tile-06.webp" type="image/webp"><img src="../../resources/onboarding/feature-wall/tile-06.poster.jpg" alt="Удалённые рабочие деревья по SSH" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Комментарии к изменениям ИИ
Оставляйте комментарии к любой строке в сравнении и отправляйте их агенту — проверяйте и редактируйте код, создавайте коммиты, не выходя из Orca.
[Документация →](https://www.onorca.dev/docs/review/annotate-ai-diff)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/review/annotate-ai-diff"><picture><source srcset="../site/public/docs/annotate-ai-diff.gif" type="image/gif"><img src="../../resources/onboarding/feature-wall/tile-08.poster.jpg" alt="Комментирование изменений, созданных ИИ" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Перетаскивание файлов в запросы агентов
Редактор VS Code с автоматическим сохранением всех изменений — перетаскивайте файлы или изображения прямо в запрос агенту.
[Документация →](https://www.onorca.dev/docs/editing/file-explorer)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/editing/file-explorer"><picture><source srcset="../../resources/onboarding/feature-wall/tile-07.gif" type="image/gif"><img src="../../resources/onboarding/feature-wall/tile-07.poster.jpg" alt="Перетаскивание файлов и изображений в запрос агенту" width="100%" /></picture></a>
</td>
</tr>
<tr>
<td width="50%" valign="middle">
### Orca CLI
Агенты тоже управляют Orca — автоматизируйте любые рабочие процессы с помощью `orca worktree create`, `snapshot`, `click` и `fill`.
[Документация →](https://www.onorca.dev/docs/cli/overview)
</td>
<td width="50%">
<a href="https://www.onorca.dev/docs/cli/overview"><picture><source srcset="../../resources/onboarding/feature-wall/tile-09.webp" type="image/webp"><img src="../../resources/onboarding/feature-wall/tile-09.poster.jpg" alt="Автоматизация Orca через CLI" width="100%" /></picture></a>
</td>
</tr>
</table>
**А ещё:**
- **[Быстрое открытие](https://www.onorca.dev/docs/model/quick-open)** — Ищите рабочие деревья, файлы, агентов, команды и контекст репозитория, не прерывая работу.
- **[Переключение учётных записей и учёт использования](https://www.onorca.dev/docs/agents/usage-tracking)** — Следите за использованием Claude и Codex и временем сброса лимитов, переключайтесь между учётными записями без повторного входа.
- **[Предпросмотр содержимого репозитория](https://www.onorca.dev/docs/editing/markdown)** — Просматривайте Markdown, изображения, PDF и документацию репозитория прямо в рабочем пространстве.
- **[Управление компьютером](https://www.onorca.dev/docs/cli/computer-use)** — Позвольте агентам управлять настольными приложениями и видимым интерфейсом, когда задача требует непосредственного взаимодействия.
- **[Уведомления и статус прочтения](https://www.onorca.dev/docs/notifications)** — Узнавайте, когда агент завершил работу или требует внимания, и отмечайте обсуждения как непрочитанные, чтобы вернуться к ним позже.
- **И многое, многое другое** — мы выпускаем обновления каждый день, поэтому этот список постоянно отстаёт. Актуальный список возможностей — в [журнале изменений](https://github.com/stablyai/orca/releases).
---
## Поддерживаемые агенты
Работает с **любым CLI-агентом** — если он запускается в терминале, то запустится и в Orca.
<p>
<a href="https://docs.anthropic.com/claude/docs/claude-code"><kbd><img src="../assets/claude-logo.svg" alt="Логотип Claude Code" width="16" valign="middle" /> Claude Code</kbd></a> &nbsp;
<a href="https://github.com/openai/codex"><kbd><img src="https://www.google.com/s2/favicons?domain=openai.com&sz=64" alt="Логотип Codex" width="16" valign="middle" /> Codex</kbd></a> &nbsp;
<a href="https://x.ai/cli"><kbd><img src="https://www.google.com/s2/favicons?domain=x.ai&sz=64" alt="Логотип Grok" width="16" valign="middle" /> Grok</kbd></a> &nbsp;
<a href="https://cursor.com/cli"><kbd><img src="https://www.google.com/s2/favicons?domain=cursor.com&sz=64" alt="Логотип Cursor" width="16" valign="middle" /> Cursor</kbd></a> &nbsp;
<a href="https://docs.github.com/en/copilot/how-tos/set-up/install-copilot-cli"><kbd><img src="https://www.google.com/s2/favicons?domain=github.com&sz=64" alt="Логотип GitHub Copilot" width="16" valign="middle" /> GitHub Copilot</kbd></a> &nbsp;
<a href="https://dev.meta.ai/docs/muse-code"><kbd><img src="../../src/shared/agent-icons/muse.png" alt="Логотип Muse" width="16" valign="middle" /> Muse</kbd></a> &nbsp;
<a href="https://deepseek-harness.github.io/deepseek-harness/"><kbd><img src="../../src/shared/agent-icons/dsh.png" alt="Логотип DeepSeek Harness" width="16" valign="middle" /> DeepSeek Harness</kbd></a> &nbsp;
<a href="https://zcode.z.ai/en/docs"><kbd><img src="../../src/shared/agent-icons/zcode.png" alt="Логотип ZCode" width="16" valign="middle" /> ZCode</kbd></a> &nbsp;
<a href="https://opencode.ai/docs/cli/"><kbd><img src="https://www.google.com/s2/favicons?domain=opencode.ai&sz=64" alt="Логотип OpenCode" width="16" valign="middle" /> OpenCode</kbd></a> &nbsp;
<a href="https://mimo.xiaomi.com/coder"><kbd><img src="https://www.google.com/s2/favicons?domain=mimo.xiaomi.com&sz=64" alt="Логотип MiMo Code" width="16" valign="middle" /> MiMo Code</kbd></a> &nbsp;
<a href="https://ampcode.com/manual#install"><kbd><img src="https://www.google.com/s2/favicons?domain=ampcode.com&sz=64" alt="Логотип Amp" width="16" valign="middle" /> Amp</kbd></a> &nbsp;
<a href="https://openclaude.gitlawb.com/"><kbd><img src="../../resources/openclaude-logo.png" alt="Логотип OpenClaude" width="16" valign="middle" /> OpenClaude</kbd></a> &nbsp;
<a href="https://antigravity.google/docs/cli-overview"><kbd><img src="https://www.google.com/s2/favicons?domain=antigravity.google&sz=64" alt="Логотип Antigravity" width="16" valign="middle" /> Antigravity</kbd></a> &nbsp;
<a href="https://pi.dev"><kbd><img src="https://pi.dev/favicon.svg" alt="Логотип Pi" width="16" valign="middle" /> Pi</kbd></a> &nbsp;
<a href="https://omp.sh"><kbd><img src="https://omp.sh/favicon.svg" alt="Логотип oh-my-pi" width="16" valign="middle" /> oh-my-pi</kbd></a> &nbsp;
<a href="https://hermes-agent.nousresearch.com/docs/"><kbd><img src="https://www.google.com/s2/favicons?domain=nousresearch.com&sz=64" alt="Логотип Hermes Agent" width="16" valign="middle" /> Hermes Agent</kbd></a> &nbsp;
<a href="https://devin.ai/cli"><kbd><img src="https://www.google.com/s2/favicons?domain=devin.ai&sz=64" alt="Логотип Devin" width="16" valign="middle" /> Devin</kbd></a> &nbsp;
<a href="https://goose-docs.ai/docs/quickstart/"><kbd><img src="https://www.google.com/s2/favicons?domain=goose-docs.ai&sz=64" alt="Логотип Goose" width="16" valign="middle" /> Goose</kbd></a> &nbsp;
<a href="https://docs.augmentcode.com/cli/overview"><kbd><img src="https://www.google.com/s2/favicons?domain=augmentcode.com&sz=64" alt="Логотип Auggie" width="16" valign="middle" /> Auggie</kbd></a> &nbsp;
<a href="https://github.com/autohandai/code-cli"><kbd><img src="https://www.google.com/s2/favicons?domain=autohand.ai&sz=64" alt="Логотип Autohand Code" width="16" valign="middle" /> Autohand Code</kbd></a> &nbsp;
<a href="https://github.com/charmbracelet/crush"><kbd><img src="https://www.google.com/s2/favicons?domain=charm.sh&sz=64" alt="Логотип Charm" width="16" valign="middle" /> Charm</kbd></a> &nbsp;
<a href="https://docs.cline.bot/cline-cli/overview"><kbd><img src="https://www.google.com/s2/favicons?domain=cline.bot&sz=64" alt="Логотип Cline" width="16" valign="middle" /> Cline</kbd></a> &nbsp;
<a href="https://www.codebuddy.ai/cli"><kbd><img src="https://www.google.com/s2/favicons?domain=codebuddy.ai&sz=64" alt="Логотип CodeBuddy" width="16" valign="middle" /> CodeBuddy</kbd></a> &nbsp;
<a href="https://www.codebuff.com/docs/help/quick-start"><kbd><img src="https://www.google.com/s2/favicons?domain=codebuff.com&sz=64" alt="Логотип Codebuff" width="16" valign="middle" /> Codebuff</kbd></a> &nbsp;
<a href="https://freebuff.com"><kbd><img src="../../src/shared/agent-icons/freebuff.png" alt="Логотип Freebuff" width="16" valign="middle" /> Freebuff</kbd></a> &nbsp;
<a href="https://commandcode.ai/docs/quickstart"><kbd><img src="https://www.google.com/s2/favicons?domain=commandcode.ai&sz=64" alt="Логотип Command Code" width="16" valign="middle" /> Command Code</kbd></a> &nbsp;
<a href="https://docs.continue.dev/cli/quickstart"><kbd><img src="https://www.google.com/s2/favicons?domain=continue.dev&sz=64" alt="Логотип Continue" width="16" valign="middle" /> Continue</kbd></a> &nbsp;
<a href="https://docs.factory.ai/cli/getting-started/quickstart"><kbd><img src="../assets/droid-logo.svg" alt="Логотип Droid" width="16" valign="middle" /> Droid</kbd></a> &nbsp;
<a href="https://kilo.ai/docs/cli"><kbd><img src="https://raw.githubusercontent.com/Kilo-Org/kilocode/main/packages/kilo-vscode/assets/icons/kilo-light.svg" alt="Логотип Kilocode" width="16" valign="middle" /> Kilocode</kbd></a> &nbsp;
<a href="https://www.kimi.com/code/docs/en/kimi-code-cli/getting-started.html"><kbd><img src="https://www.google.com/s2/favicons?domain=moonshot.cn&sz=64" alt="Логотип Kimi" width="16" valign="middle" /> Kimi</kbd></a> &nbsp;
<a href="https://kiro.dev/docs/cli/"><kbd><img src="https://www.google.com/s2/favicons?domain=kiro.dev&sz=64" alt="Логотип Kiro" width="16" valign="middle" /> Kiro</kbd></a> &nbsp;
<a href="https://github.com/mistralai/mistral-vibe"><kbd><img src="https://www.google.com/s2/favicons?domain=mistral.ai&sz=64" alt="Логотип Mistral Vibe" width="16" valign="middle" /> Mistral Vibe</kbd></a> &nbsp;
<a href="https://github.com/QwenLM/qwen-code"><kbd><img src="https://www.google.com/s2/favicons?domain=qwenlm.github.io&sz=64" alt="Логотип Qwen Code" width="16" valign="middle" /> Qwen Code</kbd></a> &nbsp;
<a href="https://support.atlassian.com/rovo/docs/install-and-run-rovo-dev-cli-on-your-device/"><kbd><img src="https://www.google.com/s2/favicons?domain=atlassian.com&sz=64" alt="Логотип Rovo Dev" width="16" valign="middle" /> Rovo Dev</kbd></a> &nbsp;
<kbd>+ любой CLI-агент</kbd>
</p>
---
## Установка
### Настольное приложение — macOS, Windows, Linux
- **[Скачать с onOrca.dev](https://onorca.dev/download)**
- Или скачайте сборку напрямую: [macOS Apple Silicon](https://github.com/stablyai/orca/releases/latest/download/orca-macos-arm64.dmg) · [macOS Intel](https://github.com/stablyai/orca/releases/latest/download/orca-macos-x64.dmg) · [Windows (.exe)](https://github.com/stablyai/orca/releases/latest/download/orca-windows-setup.exe) · [Linux AppImage](https://github.com/stablyai/orca/releases/latest/download/orca-linux.AppImage) · [Все сборки](https://github.com/stablyai/orca/releases/latest)
_Или через менеджер пакетов:_
```bash
# macOS (Homebrew)
# Always use the full name; bare `orca` is an unrelated Plotly cask.
brew install --cask stablyai/orca/orca
# Upgrade an existing install
brew upgrade --cask stablyai/orca/orca
# Arch Linux (AUR) — or stably-orca-git to build from source
yay -S stably-orca-bin
```
### Мобильное приложение — iOS, Android
Подключите его к настольному приложению, чтобы следить за агентами и направлять их работу с телефона.
- **iOS:** [Скачать в App Store](https://apps.apple.com/us/app/orca-ide/id6766130217)
- **Android:** [Скачать APK](https://www.onorca.dev/download/android) · [Руководство по установке](https://www.onorca.dev/docs/android-apk)
---
## Сообщество и поддержка
- **Discord:** Присоединяйтесь к сообществу в **[Discord](https://discord.gg/fzjDKHxv8Q)**.
- **Twitter / X:** Подпишитесь на **[@orca_build](https://x.com/orca_build)**, чтобы узнавать об обновлениях и анонсах.
- **WeChat:** Группа № 12 заполнена. Отсканируйте QR-код, чтобы присоединиться к группе № 13 сообщества Orca в WeChat.
<img src="../assets/wechat-qr-group13.jpg" alt="QR-код группы № 13 сообщества Orca в WeChat" width="160" />
- **Отзывы и идеи:** Мы быстро выпускаем обновления. Чего-то не хватает? [Предложите новую возможность](https://github.com/stablyai/orca/issues).
- **Конфиденциальность:** В [документации о конфиденциальности и телеметрии](https://www.onorca.dev/docs/telemetry) описано, какие анонимные данные об использовании собирает Orca и как отказаться от их сбора.
- **Поддержите проект:** Отметьте этот репозиторий [звездой](https://github.com/stablyai/orca), чтобы следить за нашими ежедневными выпусками.
---
## Разработка
Хотите внести вклад в проект или запустить его локально? Загляните в наше руководство [CONTRIBUTING.md](../../.github/CONTRIBUTING.md).
Сервис-посредник для подключения мобильного приложения к компьютеру тоже находится в этом репозитории —
в [`cloud/`](../../cloud/README.md), с отдельным рабочим пространством pnpm и руководством по настройке.
<a href="https://github.com/stablyai/orca/graphs/contributors">
<img src="https://contrib.rocks/image?repo=stablyai/orca" alt="Участники проекта Orca" />
</a>
<p align="center">
<img src="../assets/star-history.png" alt="График числа звёзд stablyai/orca на GitHub" width="880" />
</p>
## Подписанные сборки
Подписание кода для Windows спонсирует и обеспечивает [SignPath.io](https://signpath.io), сертификат предоставляет [SignPath Foundation](https://signpath.org).
## Лицензия
Orca — бесплатное ПО с открытым исходным кодом под [лицензией MIT](../../LICENSE).
+3 -3
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.zh-CN.md">中文</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
@@ -190,7 +190,7 @@ Orca'yı ajanlar da kullanır - her akışı `orca worktree create`, `snapshot`,
<a href="https://omp.sh"><kbd><img src="https://omp.sh/favicon.svg" alt="oh-my-pi logosu" width="16" valign="middle" /> oh-my-pi</kbd></a> &nbsp;
<a href="https://hermes-agent.nousresearch.com/docs/"><kbd><img src="https://www.google.com/s2/favicons?domain=nousresearch.com&sz=64" alt="Hermes Agent logosu" width="16" valign="middle" /> Hermes Agent</kbd></a> &nbsp;
<a href="https://devin.ai/cli"><kbd><img src="https://www.google.com/s2/favicons?domain=devin.ai&sz=64" alt="Devin logosu" width="16" valign="middle" /> Devin</kbd></a> &nbsp;
<a href="https://block.github.io/goose/docs/quickstart/"><kbd><img src="https://www.google.com/s2/favicons?domain=goose-docs.ai&sz=64" alt="Goose logosu" width="16" valign="middle" /> Goose</kbd></a> &nbsp;
<a href="https://goose-docs.ai/docs/quickstart/"><kbd><img src="https://www.google.com/s2/favicons?domain=goose-docs.ai&sz=64" alt="Goose logosu" width="16" valign="middle" /> Goose</kbd></a> &nbsp;
<a href="https://docs.augmentcode.com/cli/overview"><kbd><img src="https://www.google.com/s2/favicons?domain=augmentcode.com&sz=64" alt="Auggie logosu" width="16" valign="middle" /> Auggie</kbd></a> &nbsp;
<a href="https://github.com/autohandai/code-cli"><kbd><img src="https://www.google.com/s2/favicons?domain=autohand.ai&sz=64" alt="Autohand Code logosu" width="16" valign="middle" /> Autohand Code</kbd></a> &nbsp;
<a href="https://github.com/charmbracelet/crush"><kbd><img src="https://www.google.com/s2/favicons?domain=charm.sh&sz=64" alt="Charm logosu" width="16" valign="middle" /> Charm</kbd></a> &nbsp;
@@ -199,7 +199,7 @@ Orca'yı ajanlar da kullanır - her akışı `orca worktree create`, `snapshot`,
<a href="https://www.codebuff.com/docs/help/quick-start"><kbd><img src="https://www.google.com/s2/favicons?domain=codebuff.com&sz=64" alt="Codebuff logosu" width="16" valign="middle" /> Codebuff</kbd></a> &nbsp;
<a href="https://freebuff.com"><kbd><img src="../../src/shared/agent-icons/freebuff.png" alt="Freebuff logosu" width="16" valign="middle" /> Freebuff</kbd></a> &nbsp;
<a href="https://commandcode.ai/docs/quickstart"><kbd><img src="https://www.google.com/s2/favicons?domain=commandcode.ai&sz=64" alt="Command Code logosu" width="16" valign="middle" /> Command Code</kbd></a> &nbsp;
<a href="https://docs.continue.dev/guides/cli"><kbd><img src="https://www.google.com/s2/favicons?domain=continue.dev&sz=64" alt="Continue logosu" width="16" valign="middle" /> Continue</kbd></a> &nbsp;
<a href="https://docs.continue.dev/cli/quickstart"><kbd><img src="https://www.google.com/s2/favicons?domain=continue.dev&sz=64" alt="Continue logosu" width="16" valign="middle" /> Continue</kbd></a> &nbsp;
<a href="https://docs.factory.ai/cli/getting-started/quickstart"><kbd><img src="../assets/droid-logo.svg" alt="Droid logosu" width="16" valign="middle" /> Droid</kbd></a> &nbsp;
<a href="https://kilo.ai/docs/cli"><kbd><img src="https://raw.githubusercontent.com/Kilo-Org/kilocode/main/packages/kilo-vscode/assets/icons/kilo-light.svg" alt="Kilocode logosu" width="16" valign="middle" /> Kilocode</kbd></a> &nbsp;
<a href="https://www.kimi.com/code/docs/en/kimi-code-cli/getting-started.html"><kbd><img src="https://www.google.com/s2/favicons?domain=moonshot.cn&sz=64" alt="Kimi logosu" width="16" valign="middle" /> Kimi</kbd></a> &nbsp;
+1 -1
View File
@@ -12,7 +12,7 @@
</p>
<p align="center">
<sub><a href="../../README.md">English</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a></sub>
<sub><a href="../../README.md">English</a> · <a href="README.ja.md">日本語</a> · <a href="README.ko.md">한국어</a> · <a href="README.es.md">Español</a> · <a href="README.fr.md">Français</a> · <a href="README.pt.md">Português</a> · <a href="README.tr.md">Türkçe</a> · <a href="README.ru.md">Русский</a></sub>
</p>
<p align="center">
+1 -1
View File
@@ -114,7 +114,7 @@ orca orchestration dispatch --task <taskId> --to <workerHandle> --inject --json
## Messaging notes
- Default `check` is the bound Run's oldest unacked Delivery (FIFO). Replay until `--ack`.
- `--peek` / `--all` do not consume mail.
- `--peek` / `--all` do not consume mail and return no `deliveryId`, so they do not drain a mailbox on their own. `--all` and a Run `--peek` show at most 100 rows. To drain, repeat plain `check --ack <previous deliveryId>` until `deliveryId` is `null`.
- Group addresses: `@all`, `@idle`, `@claude`, `@codex`, `@opencode`, `@gemini`, `@droid`, `@grok`, `@cursor`, `@worktree:<id>` — never for `worker_done` / heartbeat.
- Every group except `@worktree:<id>` means the live Dispatches of the sender's own Run, delivered to their Dispatch mailboxes (or child Run mailboxes for nested coordinators). A sender in no Run is refused; `--run` must match the audience and never grants membership.
- Run groups exclude their owning coordinator. A worker raising a blocker sends to `run:<id>`. `@worktree:<id>` includes coordinators in that workspace.
+2
View File
@@ -105,6 +105,8 @@ orca worktree rm --worktree id:<worktreeId> --force --json
When `worktree create` runs from inside an Orca-managed worktree, Orca records the new worktree as a child when it can infer the relationship. Pass `--parent-worktree active` to be explicit, or `--no-parent` when the new work is independent.
Pass `--branch DAT-111-fix-login` to name the Git branch yourself instead of applying the configured branch prefix. `--name` still sets the workspace name and `--base-branch` the starting ref. If that branch already exists and cannot be reused, or the workspace path is already taken, Orca appends a numeric suffix to both, as it does in the new-workspace composer, so `--name task --branch exact` can produce branch `exact-2` even when `exact` is free.
`worktree set --unread` puts the unread dot on the workspace in the sidebar, the same one Orca shows when an agent finishes; `--read` clears it.
Agent startup flags:
+1 -1
View File
@@ -28,7 +28,7 @@ Settings are grouped into panes. Everything here is searchable with `Cmd-,` then
- Status bar toggles, including **Resource Manager** (CPU/memory/sessions, daemon controls, workspace disk scans).
- **Usage percentages** — show provider limits as **% used** or **% remaining** on the status-bar roster.
- App Icon — cycle between Classic, Watercolor, and Blue for the icon shown in the Dock and window switcher.
- **Language** — primary Interface control. Switch between System (follows the OS), English, 中文(简体), 繁體中文(台灣), 한국어, 日本語, Español, Français, Português (Brasil), Русский, or Türkçe. Settings search also matches native words for “language” (语言 / 語言 / 언어 / 言語 / Idioma / Langue / Язык / Dil) so you can find Language while the UI is still in English.
- **Language** — primary Interface control. Switch between System (follows the OS), English, 中文(简体), 繁體中文(台灣), 한국어, 日本語, Español, Français, Português (Brasil), Русский, Türkçe, or Deutsch. Settings search also matches native words for “language” (语言 / 語言 / 언어 / 言語 / Idioma / Langue / Язык / Dil / Sprache) so you can find Language while the UI is still in English.
## Git
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -63,7 +63,13 @@ class AudioEngine {
}
self.setupAudioSession()
self.setup()
do {
try self.setup()
} catch {
// Hand the session back so a failed initialize leaves no other app's audio ducked.
tearDown()
throw error
}
self.start()
}
@@ -101,14 +107,10 @@ class AudioEngine {
}
}
func setup() {
func setup() throws {
let input = avAudioEngine.inputNode
do {
try input.setVoiceProcessingEnabled(true)
} catch {
print("Could not enable voice processing \(error)")
return
}
// Throw rather than return: an engine with no mic tap would report recording and capture nothing.
try input.setVoiceProcessingEnabled(true)
avAudioEngine.inputNode.isVoiceProcessingInputMuted = !isRecording
@@ -269,7 +271,7 @@ class AudioEngine {
func stopRecordingAndPlayer(clearInterruptionResume: Bool = true){
do {
try AVAudioSession.sharedInstance().setActive(false)
try AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
} catch {
print("Could not set the audio session to inactive: \(error)")
}
@@ -288,8 +290,9 @@ class AudioEngine {
func tearDown() {
guard !isTornDown else { return }
isTornDown = true
stopRecordingAndPlayer()
// Stop I/O first; deactivating a session with running I/O returns a busy error.
avAudioEngine.stop()
stopRecordingAndPlayer()
}
var isPlaying: Bool {
@@ -355,7 +358,14 @@ class AudioEngine {
private func handleMediaServicesWereReset() {
guard !isTornDown else { return }
self.avAudioEngine.stop()
self.setup()
do {
try self.setup()
} catch {
print("Could not rebuild the audio engine: \(error)")
tearDown()
onAudioInterruptionCallback?("blocked")
return
}
self.start()
}
@@ -44,7 +44,7 @@ it.each([
const source = "import type { Shape } from './model'; const shape: Shape = { value: 1 }"
writeFileSync(test, source)
const clean = collectTypecheckPass(root)
expect(clean).toEqual({ failing: [], programTestFiles: ['value.test.ts'] })
expect(clean).toEqual({ failing: [], diagnostics: [], programTestFiles: ['value.test.ts'] })
if (buildInfo) {
expect(existsSync(buildInfo)).toBe(true)
}
@@ -54,6 +54,9 @@ it.each([
writeFileSync(join(root, 'model.ts'), 'export interface Shape { value: string }')
const failed = collectTypecheckPass(root)
expect(failed.failing).toEqual(['value.test.ts'])
expect(failed.diagnostics).toEqual([
expect.stringMatching(/^value\.test\.ts\(1,\d+\): error TS2322:/)
])
expect(collectTypecheckPass(root)).toEqual(failed)
writeFileSync(join(root, 'new.test.ts'), 'export const value: number = 1')
@@ -64,7 +67,11 @@ it.each([
expect(findTsNocheckFiles(root, nocheck.programTestFiles)).toEqual(['value.test.ts'])
unlinkSync(test)
expect(collectTypecheckPass(root)).toEqual({ failing: [], programTestFiles: ['new.test.ts'] })
expect(collectTypecheckPass(root)).toEqual({
failing: [],
diagnostics: [],
programTestFiles: ['new.test.ts']
})
} finally {
vi.unstubAllEnvs()
removeTreeSync(root)
@@ -153,6 +153,7 @@ export function collectTypecheckPass(root = process.cwd()) {
const output = `${result.stdout ?? ''}${result.stderr ?? ''}`
return {
failing: parseFailingFiles(output),
diagnostics: output.split('\n').filter((line) => ERROR_LINE.test(line)),
programTestFiles: parseProgramTestFiles(output, fs.realpathSync(root))
}
}
@@ -277,6 +278,9 @@ export function main(root = process.cwd()) {
if (added.length > 0) {
printAddedFailure(added)
for (const diagnostic of pass.diagnostics) {
console.error(diagnostic)
}
if (stale.length > 0) {
printStaleFailure(stale)
}
@@ -1,17 +1,95 @@
import { runProcessSync } from '@orca/process-host'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
import { describe, expect, it } from 'vitest'
// Only the pure functions are under test; the tsc spawn is proven end to end by CI.
import { describe, expect, it, vi } from 'vitest'
import { removeTreeSync } from '../../src/shared/windows-transient-lock-removal'
import {
diffBaseline,
diffCensus,
hasTsNocheckDirective,
main,
parseBaseline,
parseFailingFiles,
parseProgramTestFiles,
TESTS_OUTSIDE_PROGRAM
} from './check-tests-typecheck-ratchet.mjs'
vi.mock('@orca/process-host', () => ({ runProcessSync: vi.fn() }))
vi.mock('./mobile-typecheck-compiler.mjs', () => ({
resolveMobileTypecheckCommand: (project: string, cwd: string) => ({
program: 'compiler',
args: ['--project', project],
cwd
})
}))
describe('ratchet failure diagnostics', () => {
it.each([
{ name: 'new failure', baseline: '', failed: true, exit: 1, printsDiagnostics: true },
{ name: 'clean pass', baseline: '', failed: false, exit: 0, printsDiagnostics: false },
{
name: 'grandfathered failure',
baseline: 'src/value.test.ts\n',
failed: true,
exit: 0,
printsDiagnostics: false
},
{
name: 'stale baseline',
baseline: 'src/value.test.ts\n',
failed: false,
exit: 1,
printsDiagnostics: false
}
])('preserves $name outcome and baseline', ({ baseline, failed, exit, printsDiagnostics }) => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'orca-pr31180-ratchet-'))
const diagnostic = 'src/value.test.ts(1,2): error TS2322: Type number is not assignable.'
const stderrDiagnostic = 'src/value.test.ts(2,3): error TS2345: Argument type mismatch.'
const detail = ' Type number is not assignable to type string.'
const errors = vi.spyOn(console, 'error').mockImplementation(() => {})
const logs = vi.spyOn(console, 'log').mockImplementation(() => {})
try {
for (const file of [...TESTS_OUTSIDE_PROGRAM.keys(), 'src/value.test.ts']) {
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true })
fs.writeFileSync(path.join(root, file), 'export {}\n')
}
const baselineFile = path.join(root, 'tests-typecheck-baseline.txt')
fs.writeFileSync(baselineFile, baseline)
const programFile = path.join(fs.realpathSync(root), 'src/value.test.ts')
vi.mocked(runProcessSync).mockReturnValue({
code: failed ? 2 : 0,
signal: null,
timedOut: false,
stdout: `${programFile}\n${failed ? `${diagnostic}\n${detail}\n` : ''}`,
stderr: failed ? `${stderrDiagnostic}\n` : ''
})
expect(main(root)).toBe(exit)
expect(runProcessSync).toHaveBeenCalledExactlyOnceWith({
program: 'compiler',
args: ['--project', 'tsconfig.test.json', '--listFiles'],
cwd: root,
timeoutMs: null,
maxOutputBytes: 64 * 1024 * 1024
})
expect(errors.mock.calls.some(([message]) => message === diagnostic)).toBe(printsDiagnostics)
expect(errors.mock.calls.some(([message]) => message === stderrDiagnostic)).toBe(
printsDiagnostics
)
expect(
errors.mock.calls.some(([message]) => message === detail || message === programFile)
).toBe(false)
expect(fs.readFileSync(baselineFile, 'utf8')).toBe(baseline)
} finally {
vi.mocked(runProcessSync).mockReset()
errors.mockRestore()
logs.mockRestore()
removeTreeSync(root)
}
})
})
describe('the failing-file parser', () => {
it('names each file once however many errors it carries', () => {
const output = [
+3 -3
View File
@@ -1,8 +1,7 @@
import { runProcessSync } from '@orca/process-host'
import { resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { resolvePinnedBunExecutable } from '../../config/scripts/pinned-bun-executable.mjs'
import {
resolveTypecheckBunExecutable,
resolveTypecheckCommand,
selectTypecheckCompiler
} from '../../config/scripts/run-typecheck-projects-in-parallel.mjs'
@@ -17,7 +16,8 @@ export function resolveMobileTypecheckCommand(project, cwd = process.cwd()) {
}
const selection = selectTypecheckCompiler(requested, {
root,
resolveBunExecutable: (repoRoot) => resolvePinnedBunExecutable(repoRoot, runProcessSync)
resolveBunExecutable: resolveTypecheckBunExecutable,
fallbackHint: 'set ORCA_MOBILE_TYPECHECK_COMPILER=native'
})
const command = resolveTypecheckCommand(resolve(cwd, project), {
...selection,
@@ -124,7 +124,7 @@ describe('a native start the desktop refuses', () => {
await started
})
expect(device.calls).toContain('initialize')
expect(device.calls).toContain('toggleRecording(false)')
expect(device.calls).toContain('tearDown')
// The open capture owns a wake tag; no outer start catch releases it.
expect(device.screen).toEqual(['+', '-'])
expect(dictation().status).toBe('idle')
+6 -32
View File
@@ -4,7 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'
const engine = vi.hoisted(() => ({
listeners: new Map<string, (event: { data: unknown }) => void>(),
calls: new Array<string>(),
throwOn: new Set<string>(),
tearDownFails: false,
openFails: false,
// Record queued screen-lock calls separately; their microtask order relative to synchronous engine calls is not a contract.
screen: new Array<string>(),
@@ -30,15 +30,12 @@ vi.mock('@orca/expo-two-way-audio', () => ({
},
tearDown: () => {
engine.calls.push('tearDown')
if (engine.throwOn.has('tearDown')) {
if (engine.tearDownFails) {
throw new Error('the audio session would not tear down')
}
},
toggleRecording: (on: boolean) => {
engine.calls.push(`toggleRecording(${String(on)})`)
if (engine.throwOn.has(`toggleRecording(${String(on)})`)) {
throw new Error('the audio engine would not stop')
}
return true
}
}))
@@ -63,7 +60,7 @@ beforeEach(async () => {
await flushScreen()
engine.listeners.clear()
engine.calls.length = 0
engine.throwOn.clear()
engine.tearDownFails = false
engine.openFails = false
engine.screen.length = 0
engine.screenTags.clear()
@@ -100,14 +97,8 @@ describe('the calls the native half makes', () => {
expect(engine.calls).toEqual(['permission', 'initialize'])
expect(capture.begin()).toBe(true)
await capture.end()
capture.release()
expect(engine.calls).toEqual([
'permission',
'initialize',
'toggleRecording(true)',
'toggleRecording(false)',
'tearDown'
])
// Muting alone would keep the session and leave other apps' audio ducked until unmount.
expect(engine.calls).toEqual(['permission', 'initialize', 'toggleRecording(true)', 'tearDown'])
})
it('hands every microphone event over with nothing dropped', () => {
@@ -166,26 +157,9 @@ describe('the screen the native microphone holds awake', () => {
describe('a device whose audio session will not shut down', () => {
it('resolves `end` rather than rejecting it, which the contract promises', async () => {
// Synchronous try cannot catch void end() rejection; swallow/log binding failures inside cleanup to prevent unhandled rejections.
engine.throwOn.add('toggleRecording(false)')
engine.tearDownFails = true
const capture = useDictationCapture()
await expect(capture.end()).resolves.toBeUndefined()
expect(engine.calls).toEqual(['toggleRecording(false)'])
})
it('does not throw out of `release`, which runs bare in the unmount path', async () => {
engine.throwOn.add('tearDown')
const capture = useDictationCapture()
expect(() => capture.release()).not.toThrow()
await Promise.resolve()
expect(engine.calls).toEqual(['tearDown'])
})
it('still stops the engine when the tear-down is the half that fails', async () => {
engine.throwOn.add('tearDown')
const capture = useDictationCapture()
await capture.end()
capture.release()
await Promise.resolve()
expect(engine.calls).toEqual(['toggleRecording(false)', 'tearDown'])
})
})
+13 -18
View File
@@ -11,6 +11,16 @@ import type { DictationCapture } from './dictation-capture-contract'
const screen = nativeMicrophoneScreenLock
// Never throw: unmount calls this bare and `end` must not reject, so wake-tag release and desktop cancel still run.
function releaseMicrophone(): void {
screen.release()
try {
tearDown()
} catch (error) {
console.error('Failed to tear down the audio session', error)
}
}
const nativeDictationCapture: DictationCapture = {
open: async () => {
const permission = await requestMicrophonePermissionsAsync()
@@ -25,24 +35,9 @@ const nativeDictationCapture: DictationCapture = {
return { ok: true }
},
begin: () => toggleRecording(true),
// Native events already delivered the tail. Catch binding throws inside this async cleanup because void callers’ synchronous try cannot catch rejections.
end: async () => {
screen.release()
try {
toggleRecording(false)
} catch (error) {
console.error('Failed to stop microphone recording', error)
}
},
// Unmount calls release bare; catch failures so wake-tag release and desktop cancel can still run.
release: () => {
screen.release()
try {
tearDown()
} catch (error) {
console.error('Failed to tear down the audio session', error)
}
},
// Native events already delivered the tail. Tear down, not just mute, so other apps' audio resumes; the next open re-initializes.
end: async () => releaseMicrophone(),
release: releaseMicrophone,
onChunk: (handler) =>
addExpoTwoWayAudioEventListener('onMicrophoneData', (event) => {
const raw = event.data
+122 -88
View File
@@ -1,3 +1,4 @@
import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
import { useCallback, useLayoutEffect, useMemo } from 'react'
import { StyleSheet, View } from 'react-native'
import { MobileNativeChatView, type MobileNativeChatInputLockReason } from './MobileNativeChatView'
@@ -121,6 +122,36 @@ export function MobileNativeChatOverlay({
: null,
[itemSource, fullContent.detail, load]
)
const queuedComposerContext = useMemo(
() => ({
agent,
structured: structuredComposer ?? null,
skillDiscovery: controller.nativeChatSkills,
onNeedSkills: controller.loadNativeChatSkills,
filePaths: controller.nativeChatFilePaths,
onNeedFiles: controller.loadNativeChatFiles,
onError: (message: string) => controller.reportQueuedEditError?.(message),
onMicPress,
micActive,
dictationMode,
onMicPressIn,
onMicPressOut
}),
[
agent,
structuredComposer,
controller.nativeChatSkills,
controller.loadNativeChatSkills,
controller.nativeChatFilePaths,
controller.loadNativeChatFiles,
controller.reportQueuedEditError,
onMicPress,
micActive,
dictationMode,
onMicPressIn,
onMicPressOut
]
)
const noticeNames = useMemo(
() => ({ hostName, ...(agent ? { agentName: tuiAgentDisplayName(agent) ?? agent } : {}) }),
[hostName, agent]
@@ -133,94 +164,97 @@ export function MobileNativeChatOverlay({
conversation={{ surfaceId: sendSurfaceId, sessionId }}
imageClient={controller.nativeChatVisualSource?.client}
>
<View style={styles.overlay}>
<MobileNativeChatVisualContext.Provider value={visuals}>
<MobileNativeChatRootItemSourceContext.Provider value={detailSource}>
<MobileNativeChatReplyRevealsContext.Provider value={replyReveals}>
<MobileNativeChatNoticeContext.Provider value={noticeNames}>
<MobileNativeChatView
messages={session.messages}
folded={folded}
status={session.status}
error={session.error}
readFailedFinally={session.readFailedFinally === true}
agent={controller.nativeChatAgent}
agentWorking={controller.nativeChatTurnActive}
awaitingInput={controller.nativeChatAwaitingInput}
canStop={controller.nativeChatCanStop}
structuredActivityUi={controller.nativeChatStructured}
turnIndicator={controller.nativeChatTurnIndicator}
workingStartedAt={controller.nativeChatWorkingStartedAt}
settledTurns={controller.nativeChatSettledTurns}
turnJournal={controller.nativeChatTurnJournal}
receipts={controller.nativeChatReceipts}
actionablePromptIds={controller.nativeChatActionablePromptIds}
streaming={streaming}
onStop={controller.handleNativeChatStop}
ask={controller.nativeChatAsk}
askKey={controller.nativeChatAskKey}
promptKey={controller.nativeChatPromptKey}
onDismissAsk={controller.dismissNativeChatAsk}
onAnswerAsk={controller.handleNativeChatAnswerAsk}
askRequiresTerminal={
!controller.nativeChatStructured && nativeChatAskRequiresTerminal(agent)
}
onAnswerInTerminal={
activeSessionTabId
? () => controller.setTabView(activeSessionTabId, 'terminal')
: undefined
}
onCancelAsk={controller.handleNativeChatCancelAsk}
onCancelPrompt={controller.handleNativeChatCancelPrompt}
onCollapseAsk={controller.collapseNativeChatAsk}
onCollapsePrompt={controller.collapseNativeChatPrompt}
collapsedPrompt={controller.nativeChatCollapsedPrompt}
question={controller.nativeChatQuestion}
onAnswerQuestion={controller.handleNativeChatQuestionAnswer}
permission={controller.nativeChatPermission}
onRespondPermission={controller.handleNativeChatRespondPermission}
composerTray={composerTray}
onOpenFile={onOpenFile}
hasMore={session.hasMore}
olderPages={session.olderPages}
onLoadEarlier={session.loadEarlier}
onSend={images.sendNativeChat}
sendSurfaceId={sendSurfaceId}
getSendCompletionGeneration={getSendCompletionGeneration}
getComposerEditGeneration={controller.getChatComposerEditGeneration}
pending={controller.chatPending}
imagePreviewsByMessageId={controller.chatImagePreviewsByMessageId}
draftKey={controller.chatDraftKey}
onComposerTextChange={controller.setChatComposerText}
onAttachImage={
controller.nativeChatAcceptsImages
? () => void images.attachImage('library')
: undefined
}
attachments={images.attachments}
onRemoveAttachment={images.removeAttachment}
isAttaching={images.isAttaching}
onMicPress={onMicPress}
micActive={micActive}
dictationMode={dictationMode}
onMicPressIn={onMicPressIn}
onMicPressOut={onMicPressOut}
inputLockReason={inputLockReason}
sendErrorMessage={sendErrorMessage}
onClearSendError={onClearSendError}
filePaths={controller.nativeChatFilePaths}
onNeedFiles={controller.loadNativeChatFiles}
skillDiscovery={controller.nativeChatSkills}
onNeedSkills={controller.loadNativeChatSkills}
sessionOptions={controller.nativeChatSessionOptions}
structuredComposer={structuredComposer}
keyboardInset={keyboardInset}
/>
</MobileNativeChatNoticeContext.Provider>
</MobileNativeChatReplyRevealsContext.Provider>
</MobileNativeChatRootItemSourceContext.Provider>
</MobileNativeChatVisualContext.Provider>
</View>
<MobileQueuedMessageComposerContext.Provider value={queuedComposerContext}>
<View style={styles.overlay}>
<MobileNativeChatVisualContext.Provider value={visuals}>
<MobileNativeChatRootItemSourceContext.Provider value={detailSource}>
<MobileNativeChatReplyRevealsContext.Provider value={replyReveals}>
<MobileNativeChatNoticeContext.Provider value={noticeNames}>
<MobileNativeChatView
messages={session.messages}
folded={folded}
status={session.status}
error={session.error}
readFailedFinally={session.readFailedFinally === true}
agent={controller.nativeChatAgent}
agentWorking={controller.nativeChatTurnActive}
awaitingInput={controller.nativeChatAwaitingInput}
canStop={controller.nativeChatCanStop}
structuredActivityUi={controller.nativeChatStructured}
turnIndicator={controller.nativeChatTurnIndicator}
workingStartedAt={controller.nativeChatWorkingStartedAt}
settledTurns={controller.nativeChatSettledTurns}
turnJournal={controller.nativeChatTurnJournal}
receipts={controller.nativeChatReceipts}
actionablePromptIds={controller.nativeChatActionablePromptIds}
streaming={streaming}
onStop={controller.handleNativeChatStop}
ask={controller.nativeChatAsk}
askKey={controller.nativeChatAskKey}
promptKey={controller.nativeChatPromptKey}
onDismissAsk={controller.dismissNativeChatAsk}
onAnswerAsk={controller.handleNativeChatAnswerAsk}
askRequiresTerminal={
!controller.nativeChatStructured && nativeChatAskRequiresTerminal(agent)
}
onAnswerInTerminal={
activeSessionTabId
? () => controller.setTabView(activeSessionTabId, 'terminal')
: undefined
}
onCancelAsk={controller.handleNativeChatCancelAsk}
onCancelPrompt={controller.handleNativeChatCancelPrompt}
onCollapseAsk={controller.collapseNativeChatAsk}
onCollapsePrompt={controller.collapseNativeChatPrompt}
collapsedPrompt={controller.nativeChatCollapsedPrompt}
question={controller.nativeChatQuestion}
onAnswerQuestion={controller.handleNativeChatQuestionAnswer}
permission={controller.nativeChatPermission}
onRespondPermission={controller.handleNativeChatRespondPermission}
composerTray={composerTray}
onOpenFile={onOpenFile}
hasMore={session.hasMore}
olderPages={session.olderPages}
onLoadEarlier={session.loadEarlier}
onSend={images.sendNativeChat}
sendSurfaceId={sendSurfaceId}
getSendCompletionGeneration={getSendCompletionGeneration}
getComposerEditGeneration={controller.getChatComposerEditGeneration}
pending={controller.chatPending}
imagePreviewsByMessageId={controller.chatImagePreviewsByMessageId}
composerScopeKey={controller.chatComposerScopeKey}
draftKey={controller.chatDraftKey}
onComposerTextChange={controller.setChatComposerText}
onAttachImage={
controller.nativeChatAcceptsImages
? () => void images.attachImage('library')
: undefined
}
attachments={images.attachments}
onRemoveAttachment={images.removeAttachment}
isAttaching={images.isAttaching}
onMicPress={onMicPress}
micActive={micActive}
dictationMode={dictationMode}
onMicPressIn={onMicPressIn}
onMicPressOut={onMicPressOut}
inputLockReason={inputLockReason}
sendErrorMessage={sendErrorMessage}
onClearSendError={onClearSendError}
filePaths={controller.nativeChatFilePaths}
onNeedFiles={controller.loadNativeChatFiles}
skillDiscovery={controller.nativeChatSkills}
onNeedSkills={controller.loadNativeChatSkills}
sessionOptions={controller.nativeChatSessionOptions}
structuredComposer={structuredComposer}
keyboardInset={keyboardInset}
/>
</MobileNativeChatNoticeContext.Provider>
</MobileNativeChatReplyRevealsContext.Provider>
</MobileNativeChatRootItemSourceContext.Provider>
</MobileNativeChatVisualContext.Provider>
</View>
</MobileQueuedMessageComposerContext.Provider>
</MobileNativeChatRowOverlaysHost>
)
}
@@ -183,3 +183,7 @@ describe('MobileNativeChatView: composer lock and prompt cards', () => {
})
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -111,3 +111,7 @@ describe('MobileNativeChatView: send and read failure banners', () => {
expect(onClearSendError).toHaveBeenCalledOnce()
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -216,3 +216,7 @@ describe('MobileNativeChatView: history paging and anchoring', () => {
})
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -250,3 +250,7 @@ describe('terminal prompt presentation with the production view, card and compos
}
)
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -74,3 +74,7 @@ describe('MobileNativeChatView: rows and the streaming bubble', () => {
expect(renderedRow('pending-1').props).not.toHaveProperty('queued')
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -105,3 +105,7 @@ describe('MobileNativeChatView: Stop control', () => {
expect(stops()).toHaveLength(1)
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -382,3 +382,7 @@ describe('MobileNativeChatView: tail-follow', () => {
}
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -100,6 +100,7 @@ type Props = ComposerTrayProps & {
pending: MobileNativeChatPendingItem[]
// Retain local preview URIs after authoritative image messages replace optimistic rows.
imagePreviewsByMessageId?: Record<string, string[]>
composerScopeKey?: string | null
draftKey: string | null
onComposerTextChange: (text: string) => void
onAttachImage?: () => void
@@ -171,6 +172,7 @@ export function MobileNativeChatView({
pending,
imagePreviewsByMessageId,
draftKey,
composerScopeKey,
onComposerTextChange,
onAttachImage,
attachments,
@@ -388,6 +390,7 @@ export function MobileNativeChatView({
{}
{trayContent}
<MobileNativeChatDraftComposer
draftScopeKey={composerScopeKey}
structured={structuredActivityUi ? structuredComposer : null}
draftKey={draftKey}
onChangeText={onComposerTextChange}
@@ -395,3 +395,7 @@ describe('MobileNativeChatView', () => {
})
})
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -178,3 +178,7 @@ it('keeps a steer on its way into an ordinary running turn in the list, above th
expect(drawn).toEqual({ listed: ['ask', 'steer'], footer: ['status'] })
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -5,6 +5,7 @@ import {
AlertCircle,
CornerDownRight,
ListEnd,
Image as ImageIcon,
MoreHorizontal,
Send,
Trash2
@@ -14,7 +15,7 @@ import { queuedMessageCardSteers } from '../../../src/shared/structured-agent-se
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards'
import type { MobileQueuedMessageInlineEditor } from './use-mobile-structured-queued-edit'
import { MobileNativeChatQueuedMessageEditor } from './native-chat/input/MobileNativeChatQueuedMessageEditor'
import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
import { MobileQueuedCardText } from './MobileQueuedCardText'
import { queuedMessageStyles as styles } from './native-chat/input/mobile-native-chat-queued-message-styles'
@@ -45,7 +46,7 @@ export function MobileQueuedMessageCardRow({
style={styles.divided}
onLayout={(event) => onEditorLayout(event.nativeEvent.layout)}
>
<MobileNativeChatQueuedMessageEditor editor={editor} attribution={card.attribution} />
<MobileQueuedMessageComposer editor={editor} attribution={card.attribution} />
</View>
)
}
@@ -93,7 +94,16 @@ function QueuedMessageCardContents({
) : null}
</View>
<View style={styles.actions}>
{}
{card.images ? (
<View
style={styles.actions}
accessible
accessibilityLabel={`${card.images.length} images`}
>
<ImageIcon size={12} color={colors.textMuted} strokeWidth={2} />
<Text style={styles.caption}>{card.images.length}</Text>
</View>
) : null}
{card.waitsForAgent ? null : (
<Pressable
accessibilityRole="button"
@@ -136,7 +146,6 @@ function QueuedMessageCardContents({
>
<Trash2 size={14} color={colors.textPrimary} strokeWidth={2} />
</Pressable>
{}
{card.command ? null : (
<Pressable
accessibilityRole="button"
@@ -0,0 +1,95 @@
import { createElement } from 'react'
import { findByHostType } from '../test-support/react-test-renderer-host-nodes'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { FakeSession } from '../transport/mobile-endpoint-supervisor-test-fakes'
import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
import {
readMobileNativeChatDraftInputs,
resetMobileNativeChatDraftInputsForTests
} from './native-chat/composer/mobile-native-chat-draft-inputs'
vi.mock('react-native', () => ({ Text: 'Text', View: 'View' }))
vi.mock('./native-chat/composer/MobileNativeChatComposer', () => ({
MobileNativeChatComposer: 'Composer'
}))
vi.mock('./native-chat/composer/use-mobile-native-chat-file-attachments', () => ({
useMobileNativeChatFileAttachments: () => ({
files: [],
attachFiles: vi.fn(),
removeFiles: vi.fn()
})
}))
vi.mock('./native-chat/composer/use-mobile-native-chat-image-upload', () => ({
useMobileNativeChatImageUpload: () => ({ attachImage: vi.fn(async () => {}), isAttaching: false })
}))
describe('queued phone composer action boundary', () => {
let renderer: ReactTestRenderer | undefined
afterEach(() => {
act(() => renderer?.unmount())
resetMobileNativeChatDraftInputsForTests()
})
it('saves literal text while refusing picked executable controls and retaining skill picks', async () => {
const save = vi.fn(async () => true)
const onError = vi.fn()
const client = new FakeSession('connected')
await act(async () => {
renderer = create(
createElement(
MobileQueuedMessageComposerContext.Provider,
{
value: {
agent: 'codex',
structured: null,
filePaths: [],
onNeedFiles: undefined,
onError,
onMicPress: undefined,
micActive: false,
dictationMode: undefined,
onMicPressIn: vi.fn(),
onMicPressOut: vi.fn()
}
},
createElement(MobileQueuedMessageComposer, {
attribution: null,
editor: {
messageId: 'card',
scopeKey: 'edit',
sessionId: 'session',
client,
imagesCapable: true,
text: 'hello',
saving: false,
canSave: true,
change: vi.fn(),
save,
removeImage: vi.fn(),
cancel: vi.fn()
}
})
)
)
})
const composer = findByHostType(renderer!.root, 'Composer')
await act(async () => {
expect(await composer.props.onSend('/compact')).toBe(true)
expect(await composer.props.onSend('/goal research')).toBe(true)
expect(composer.props.editSession.refuseCommand('/resume')).toBe(true)
})
expect(save).toHaveBeenCalledTimes(2)
save.mockClear()
expect(client.sendRequest).not.toHaveBeenCalled()
expect(onError).toHaveBeenCalledOnce()
act(() => composer.props.onPickSkill({ name: 'review', path: '/remote/SKILL.md' }))
expect(readMobileNativeChatDraftInputs('edit').skills).toEqual([
{ name: 'review', path: '/remote/SKILL.md' }
])
await act(async () => expect(await composer.props.onSend('hello')).toBe(true))
expect(save).toHaveBeenCalledOnce()
expect(client.sendRequest).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,123 @@
import { useContext, useEffect, useMemo, useRef } from 'react'
import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
import { Text, type TextInput, View } from 'react-native'
import { MobileNativeChatComposer } from './native-chat/composer/MobileNativeChatComposer'
import type { MobileQueuedMessageInlineEditor } from './use-mobile-structured-queued-edit'
import { useMobileNativeChatFileAttachments } from './native-chat/composer/use-mobile-native-chat-file-attachments'
import { useMobileNativeChatImageUpload } from './native-chat/composer/use-mobile-native-chat-image-upload'
import {
updateMobileNativeChatDraftInputs,
useMobileNativeChatDraftInputs
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import { prepareQueuedMessageEditText } from '../../../src/shared/queued-message-edit-command'
import { colors } from '../theme/mobile-theme'
import { useMobileColorScheme } from '../theme/use-mobile-color-scheme'
import { createUuidV4 } from '../../../src/shared/uuid-v4'
export function MobileQueuedMessageComposer({
editor,
attribution
}: {
editor: MobileQueuedMessageInlineEditor
attribution: string | null
}): React.JSX.Element {
useMobileColorScheme()
const context = useContext(MobileQueuedMessageComposerContext)
const inputRef = useRef<TextInput>(null)
const emptyHandle = useRef<string | null>(null)
const inputs = useMobileNativeChatDraftInputs(editor.scopeKey)
const files = useMobileNativeChatFileAttachments({
client: editor.client,
sessionId: editor.sessionId,
scopeKey: editor.scopeKey,
enabled: !editor.saving,
showToast: (message) => context?.onError(message)
})
const images = useMobileNativeChatImageUpload({
client: editor.client,
activeHandleRef: emptyHandle,
getActiveWorktreeConnectionId: async () => null,
connState: 'connected',
scopeKey: editor.scopeKey,
structuredNativeChat: true,
showToast: (message) => context?.onError(message),
onImagesUploaded: (scope, images) =>
updateMobileNativeChatDraftInputs(scope, (current) => ({
...current,
images: [...current.images, ...images.map((image) => ({ ...image, id: createUuidV4() }))]
}))
})
useEffect(() => {
inputRef.current?.focus()
}, [])
const agent = context?.agent ?? 'codex'
const reported = context?.structured?.catalog.reported
const acceptsText = useMemo(
() => prepareQueuedMessageEditText(agent, reported),
[agent, reported]
)
const refuseCommand = (text: string): boolean => {
if (acceptsText(text)) {
return false
}
context?.onError("Commands can't be saved in a queued message.")
return true
}
return (
<View testID="queued-card-editor">
<Text style={{ color: colors.textMuted }}>
Editing message{attribution ? ` · ${attribution}` : ''}
</Text>
<MobileNativeChatComposer
inputRef={inputRef}
draftScopeKey={editor.scopeKey}
insertDictation={editor.insertDictation}
agent={context?.agent}
value={editor.text}
onChangeText={editor.change}
onSend={() => editor.save()}
editSession={{ cancel: editor.cancel, locked: editor.saving, refuseCommand }}
sendSurfaceId={editor.scopeKey}
getSendCompletionGeneration={() => 0}
getComposerEditGeneration={() => 0}
disabled={editor.saving}
sendDisabled={!editor.canSave}
structured={
context?.structured
? {
...context.structured,
files: files.files,
onAttachFiles: () => void files.attachFiles(),
onRemoveFile: (id) => files.removeFiles([id])
}
: null
}
skillDiscovery={context?.skillDiscovery}
onNeedSkills={context?.onNeedSkills}
filePaths={context?.filePaths}
onNeedFiles={context?.onNeedFiles}
onPickSkill={(skill) =>
updateMobileNativeChatDraftInputs(editor.scopeKey, (current) => ({
...current,
skills: [...current.skills.filter(({ name }) => name !== skill.name), skill]
}))
}
attachments={[...inputs.images]}
onRemoveAttachment={editor.imagesCapable ? editor.removeImage : undefined}
onAttachImage={
editor.imagesCapable
? () => {
void images.attachImage('library')
}
: undefined
}
isAttaching={images.isAttaching}
onMicPress={context?.onMicPress}
micActive={context?.micActive}
dictationMode={context?.dictationMode}
onMicPressIn={context?.onMicPressIn}
onMicPressOut={context?.onMicPressOut}
/>
</View>
)
}
@@ -23,15 +23,17 @@ export type MobileQueueDragViewport = {
type Metrics = { offset: number; viewport: number; content: number }
/** The queued cards under the fixed header, capped so a long queue never takes over the screen. */
/** Compact cards are capped; the full editor yields to the available chat viewport. */
export function MobileQueuedMessageScrollList({
messageIds,
newestIsPersons,
inlineEditorActive = false,
children
}: {
messageIds: readonly string[]
/** The newest card has no sender: the person just queued it, so the list shows it. */
newestIsPersons: boolean
inlineEditorActive?: boolean
/** Rows, given `reveal` to keep an edited row in view. */
children: (reveal: (row: LayoutRectangle) => void, drag: MobileQueueDragViewport) => ReactNode
}): React.JSX.Element {
@@ -75,17 +77,17 @@ export function MobileQueuedMessageScrollList({
// Never past the content's end, which may not have caught up with a row that just grew.
const top = Math.max(0, row.y - spacing.lg)
const bottom = Math.min(Math.max(content, rowBottom), rowBottom + spacing.lg)
if (top < offset) {
if (row.height > viewport || top < offset) {
scrollRef.current?.scrollTo({ y: top, animated: false })
} else if (bottom > offset + viewport) {
scrollRef.current?.scrollTo({ y: bottom - viewport, animated: false })
}
}
return (
<View>
<View style={inlineEditorActive && styles.inline}>
<Animated.ScrollView
ref={scrollRef}
style={styles.scroll}
style={inlineEditorActive ? styles.inline : styles.scroll}
scrollEnabled={!dragging}
nestedScrollEnabled
showsVerticalScrollIndicator
@@ -137,6 +139,7 @@ function ListEdgeFade({ edge }: { edge: 'top' | 'bottom' }): React.JSX.Element {
const styles = StyleSheet.create({
scroll: { maxHeight: QUEUE_LIST_MAX_HEIGHT },
inline: { flexShrink: 1, minHeight: 0 },
fade: { position: 'absolute', left: 0, right: 0, height: spacing.lg },
fadeTop: { top: 0 },
fadeBottom: { bottom: 0 }
@@ -25,7 +25,9 @@ vi.mock('@orca/expo-two-way-audio', () => ({
return true
},
requestMicrophonePermissionsAsync: async () => ({ granted: true }),
tearDown: () => {},
tearDown: () => {
device.recording = false
},
toggleRecording: (recording: boolean) => {
device.recording = recording
return true
+3 -1
View File
@@ -50,7 +50,9 @@ const LANGUAGE_ALIASES: Record<string, string> = {
zsh: 'bash',
fish: 'bash',
yml: 'yaml',
'cuda-cpp': 'cpp'
'cuda-cpp': 'cpp',
'glimmer-js': 'javascript',
'glimmer-ts': 'typescript'
}
export function resolveMobileSyntaxLanguage(filePath: string, preferredLanguage?: string): string {
@@ -31,6 +31,8 @@ export type MobileNativeChatController = {
showNativeChat: boolean
showNativeChatRef: MutableRefObject<boolean>
nativeChatAgent: string | null
chatComposerScopeKey?: string | null
reportQueuedEditError?: (message: string) => void
chatDraftKey: string | null
setChatComposerText: Dispatch<SetStateAction<string>>
getChatComposerEditGeneration: () => number
@@ -12,7 +12,7 @@ import {
isUndrawnProviderFrameMessage
} from '../../../src/shared/native-chat/tools/native-chat-tool-fold'
import { projectNativeChatTaskListFrames } from '../../../src/shared/native-chat/input/native-chat-task-list-frames'
import { foldSubagentItems } from '../../../src/shared/native-chat-subagent-items'
import { foldSubagentItems } from '../../../src/shared/native-chat/transcript/native-chat-subagent-items'
import { prepareNativeChatMessages } from '../../../src/shared/native-chat-message-preparation'
import {
isImageRefBlock,
@@ -282,3 +282,7 @@ describe('prompt cards through the production controller, send contract and view
}
)
})
vi.mock('./MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -0,0 +1,628 @@
import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items'
import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params'
import { createElement, type ReactNode } from 'react'
import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
import {
mobileNativeChatDraftDestination,
captureMobileNativeChatTextDestination,
readMobileNativeChatDraftInputs
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import { act } from 'react-test-renderer'
import { beforeAll, describe, expect, it, vi } from 'vitest'
import type {
AcpCommandOptionsFixtureModule,
MobileQueuedEditHostFixtureModule
} from '../../../src/shared/mobile-queued-edit-host.test-fixture-contract'
import { mobileQueuedEditHarness, readOrHoldReply } from './mobile-queued-edit-hook.test-fixture'
import { TextInput } from 'react-native'
import { ActionSheetModal } from '../components/ActionSheetModal'
import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
import { MobileNativeChatQueuedMessages } from './native-chat/input/MobileNativeChatQueuedMessages'
import { MobileNativeChatComposer } from './native-chat/composer/MobileNativeChatComposer'
import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
import type { QueuedEditHostFixtureModule } from '../../../src/shared/queued-edit-host.test-fixture'
import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
import {
mutationOk,
queuedDraft,
SESSION_ID
} from './use-mobile-structured-agent-session-queued.test-fixture'
import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
let queuedEditHost: QueuedEditHostFixtureModule['queuedEditHost']
beforeAll(async () => {
const fixtures = await vi.importActual<QueuedEditHostFixtureModule>(
'../../../src/main/native-chat/agent-session-journal/queued-edit-host.test-fixture'
)
queuedEditHost = fixtures.queuedEditHost
})
const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
vi.mock('../platform/media-picker', () => ({ useMediaPicker: () => picker }))
vi.mock('../components/DragReorderList', () => ({ DragReorderList: 'DragReorderList' }))
vi.mock('react-native-reanimated', async () => {
const { useRef } = await import('react')
return {
default: { ScrollView: 'ScrollView' },
useAnimatedRef: () => useRef(null),
useSharedValue: (value: unknown) => useRef({ value }).current
}
})
vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
vi.mock('../components/mounted-bottom-drawer', () => ({ MountedBottomDrawer: 'BottomDrawer' }))
vi.mock('../components/bottom-drawer-modal-host-scope', () => ({
useBottomDrawerModalHost: () => null
}))
const hostFixtures = await vi.importActual<MobileQueuedEditHostFixtureModule>(
'../../../src/main/native-chat/agent-session-wire/mobile-queued-edit-host.test-fixture'
)
const { AcpStructuredOptions } = await vi.importActual<AcpCommandOptionsFixtureModule>(
'../../../src/main/acp/acp-structured-options'
)
describe('real phone inline composer from More through picker pruning and host body', () => {
const { state, Harness, mount, sendRequest, error, resolved } = mobileQueuedEditHarness()
const profiles = [
['claude', 'model', '/model'],
['codex', 'review.v2', '$review.v2'],
['pi', 'skill:review', '/skill:review'],
['openclaude', 'review', '/review'],
['opencode', 'review', '/review'],
['opencode2', 'review', '/review'],
['grok', 'review', '/review']
] as const
async function rows(
message: Parameters<typeof mount>[0],
agent = 'codex',
sessionId = SESSION_ID,
catalog: {
reported: { name: string; kind: 'skill' | 'command'; path?: string }[]
discovery?: NativeChatSkillDiscoverySnapshot
} = {
reported: []
},
extra?: (hook: NonNullable<typeof state.hook>) => ReactNode
) {
await mount(message, true, agent, sessionId)
act(() => state.hook!.queued.editor!.cancel())
resolved.mockClear()
const renderContent: NonNullable<Parameters<typeof Harness>[0]['renderContent']> = (hook) =>
createElement(
MobileQueuedMessageComposerContext.Provider,
{
value: {
agent,
structured: {
catalog: { reported: catalog.reported, conversationCommands: [] },
onSlashMenuOpen: () => {},
files: [],
onRemoveFile: () => {}
},
skillDiscovery: catalog.discovery ?? {
status: 'ready',
skills: catalog.reported
.filter((entry) => entry.kind === 'skill' && entry.path)
.map((entry) => ({
id: entry.name,
name: entry.name,
description: null,
providers: ['agent-skills'],
sourceKind: 'repo',
sourceLabel: 'Repo',
rootPath: '/skills',
directoryPath: `/skills/${entry.name}`,
skillFilePath: entry.path ?? '',
installed: true,
updatedAt: null
}))
},
filePaths: [],
onNeedFiles: undefined,
onError: error,
onMicPress: undefined,
micActive: false,
dictationMode: undefined,
onMicPressIn: () => {},
onMicPressOut: () => {}
}
},
createElement(MobileNativeChatQueuedMessages, {
cards: hook.queued.cards,
onEdit: hook.queued.edit,
editor: hook.queued.editor
}),
extra?.(hook)
)
const rerender = async () =>
act(async () =>
state.renderer!.update(
createElement(Harness, {
sessionId,
agent,
renderContent,
skillsSupport: true,
imagesSupport: true,
composerScopeKey: 'original-bottom'
})
)
)
await rerender()
const root = () => state.renderer!.root
const button = (label: string) =>
root().findAll(
(node) =>
node.props.accessibilityLabel === label && typeof node.props.onPress === 'function'
)[0]!
const field = () =>
root().find((node) => node.type === TextInput && node.props.multiline === true)
const open = async () => {
await act(async () => button('More actions').props.onPress())
const sheet = root().find(
(node) =>
node.type === ActionSheetModal && node.props.actions?.[0]?.label === 'Edit message'
)
await act(async () => sheet.props.actions[0].onPress())
expect(root().findAllByType(MobileQueuedMessageComposer)).toHaveLength(1)
expect(root().findAllByType(MobileNativeChatComposer)).toHaveLength(extra ? 2 : 1)
}
await open()
return { root, button, field, rerender, open }
}
it.each(profiles)(
'%s preserves its actual offered %s shape through the wrapper and accepted body',
async (agent, name, token) => {
const message = queuedDraft({
messageId: 'picked',
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'seed' }] }
})
const host = queuedEditHost(SESSION_ID, message)
let path = '/A/SKILL.md'
let unknown = agent === 'claude'
let desired = message.body
const scanned = agent === 'opencode' || agent === 'opencode2'
const options = new AcpStructuredOptions()
options.adoptCommands([{ name, description: 'Review the prompt' }])
const catalog: NonNullable<Parameters<typeof rows>[3]> = {
reported: scanned ? (options.readCommands() ?? []) : [{ name, kind: 'skill', path }],
...(scanned
? {
discovery: {
status: 'ready',
skills: [
{
id: 'repo:review',
name,
description: null,
providers: ['agent-skills'],
sourceKind: 'repo',
sourceLabel: 'Repo',
rootPath: '/skills',
directoryPath: '/skills/review',
skillFilePath: path,
installed: true,
updatedAt: null
}
]
}
}
: {})
}
const { button, field, rerender } = await rows(message, agent, SESSION_ID, catalog)
sendRequest.mockImplementation(async (method, params) => {
if (method !== 'agentSession.queuedMessageUpdate') {
return readOrHoldReply(method, params)
}
const fields = QueuedMessageUpdateParams.parse(params)
const edited = queuedMessageWithEdit(host.row!.body, fields)
if (!edited.ok) {
throw new Error(edited.reason)
}
desired = edited.body
if (unknown) {
throw markRpcDeliveryUnknown(new Error('lost'))
}
return mutationOk(host.update(fields))
})
const pick = async () => {
act(() => field().props.onChangeText('/'))
act(() =>
field().props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
)
await act(async () => button(token).props.onPress())
expect(state.hook!.queued.editor?.text).toBe(`${token} `)
expect(readMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey).skills).toEqual(
scanned ? [] : [{ name, path }]
)
}
await pick()
await act(async () => button('Save edited message').props.onPress())
if (unknown) {
const first = desired
path = '/B/SKILL.md'
catalog.reported = [{ name, kind: 'skill', path }]
await rerender()
// Reopen menu after deleting: deletion retires A before picking B.
act(() => field().props.onChangeText(''))
await pick()
act(() => field().props.onChangeText(`${token} suffix`))
const { batchEvent } =
await import('./use-mobile-structured-agent-session-queued.test-fixture')
act(() => state.listener?.(batchEvent([{ ...message, body: first }])))
expect(state.hook!.queued.editor?.text).toBe(`${token} suffix`)
expect(resolved).not.toHaveBeenCalled()
expect(state.bottomText).toBe('')
host.update({
messageId: 'picked',
expectedBodyFingerprint: host.row!.fingerprint,
text: token,
images: [],
skills: [{ name, path: '/A/SKILL.md' }]
})
unknown = false
await act(async () => button('Save edited message').props.onPress())
}
expect(error.mock.calls).toEqual([])
expect(
sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
).not.toHaveLength(0)
expect(state.hook!.queued.editor).toBeUndefined()
expect(host.row!.body.skills).toEqual(scanned ? undefined : [{ name, path }])
expect(
sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
).toHaveLength(agent === 'claude' ? 2 : 1)
expect(
sendRequest.mock.calls.some(([method]) =>
/(?:\.send$|conversationCommand|goal|resume|pty)/i.test(method)
)
).toBe(false)
host.leases.dispose()
}
)
it('keeps both saved files on clean Save and projects the phone picked list after an argument edit', async () => {
const skills = [
{ name: 'review', path: '/A/SKILL.md' },
{ name: 'review', path: '/B/SKILL.md' }
]
const message = queuedDraft({
messageId: 'two-files',
body: {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: '$review old' }],
skills
}
})
const host = queuedEditHost(SESSION_ID, message)
try {
const { button, field, open } = await rows(message)
sendRequest.mockImplementation(async (method, params) =>
method === 'agentSession.queuedMessageUpdate'
? mutationOk(host.update(QueuedMessageUpdateParams.parse(params)))
: readOrHoldReply(method, params)
)
await act(async () => button('Save edited message').props.onPress())
expect(state.hook!.queued.editor).toBeUndefined()
expect(
sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
).toHaveLength(0)
expect(host.row!.body.skills).toEqual(skills)
await open()
act(() => field().props.onChangeText('$review changed'))
await act(async () => button('Save edited message').props.onPress())
expect(state.hook!.queued.editor).toBeUndefined()
expect(host.row!.body.skills).toEqual(skills)
expect(host.row!.body.blocks).toEqual([{ type: 'text', text: '$review changed' }])
expect(
sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
).toHaveLength(1)
} finally {
host.leases.dispose()
}
})
it.each(['question', 'approval'] as const)(
'automatic/mail More→Edit→Save persists user authorship, position and options across journal reopen under %s',
async (kind) => {
const { ok, snapshotEvent } =
await import('./use-mobile-structured-agent-session-queued.test-fixture')
const clock = vi.spyOn(Date, 'now').mockReturnValue(hostFixtures.now)
const rig = await hostFixtures.createMobileQueuedEditHostFixture()
try {
await rig.start()
const from = { kind: 'agent' as const, senders: [], orchestration: null }
const before = await rig.insert({
messageId: `mail-${kind}`,
body: {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: 'mail intent' }],
sentAs: 'goal',
from
},
options: { model: 'saved-model', effort: 'high' }
})
const beforeWire = await rig.published(before.messageId)
const { button, field, open } = await rows(beforeWire, 'codex', rig.sessionId)
act(() => state.hook!.queued.editor!.cancel())
const pending = {
options: [{ id: 'yes', label: 'Yes' }],
resolution: {
state: 'pending' as const,
selectedOptionId: null,
resolvedBy: null,
resolvedAt: null
}
}
const prompt = snapshotEvent({
queuedMessages: [beforeWire],
items: [
{
itemId: 'prompt',
revision: 1,
sequence: 1,
observedAt: 1,
body:
kind === 'question'
? { kind, question: 'Pick', ...pending }
: { kind, title: 'Allow?', detail: null, ...pending }
}
]
})
act(() =>
state.listener?.({
...prompt,
sessionId: rig.sessionId,
page: { ...prompt.page, sessionId: rig.sessionId }
})
)
await open()
const hostResults: unknown[] = []
sendRequest.mockImplementation(async (method, params) => {
if (method === 'agentSession.queuedMessageEditHold') {
return ok(await rig.request(method, params))
}
if (method !== 'agentSession.queuedMessageUpdate') {
return readOrHoldReply(method, params)
}
const result = await rig.request(method, params)
hostResults.push(result)
return ok(result)
})
// Equal Save proves no durable sender mutation or update RPC.
await act(async () => button('Save edited message').props.onPress())
expect(rig.read(before.messageId)?.body.from).toEqual(from)
expect(
sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
).toBe(false)
await open()
act(() => field().props.onChangeText('user replacement'))
await act(async () => button('Save edited message').props.onPress())
expect(hostResults, JSON.stringify(hostResults)).toMatchObject([
{ ok: true, value: { status: 'updated' } }
])
expect(error.mock.calls).toEqual([])
expect(state.hook!.queued.editor).toBeUndefined()
const accepted = rig.read(before.messageId)!
expect(accepted).toMatchObject({
position: before.position,
options: before.options,
body: { sentAs: 'goal', blocks: [{ type: 'text', text: 'user replacement' }] }
})
expect(accepted.body).not.toHaveProperty('from')
await rig.restart()
const reopened = rig.read(before.messageId)!
expect(reopened).toEqual(accepted)
const publication = snapshotEvent({
queuedMessages: [await rig.published(reopened.messageId)]
})
act(() =>
state.listener?.({
...publication,
sessionId: rig.sessionId,
page: { ...publication.page, sessionId: rig.sessionId }
})
)
await open()
expect(state.hook!.queued.editor?.text).toBe('user replacement')
expect(state.hook!.queued.cards[0]?.attribution).toBeNull()
} finally {
await rig.dispose()
clock.mockRestore()
}
},
15000
)
it.each(['updated', 'unknown', 'refused', 'unknown-phase'] as const)(
'real phone Cancel revokes pending/unknown Save before late %s and cannot mutate a new edit',
async (mode) => {
const { batchEvent, fieldsOf } =
await import('./use-mobile-structured-agent-session-queued.test-fixture')
const message = queuedDraft({ messageId: 'pending-cancel' })
const other = queuedDraft({ messageId: 'new-edit', position: 2 })
const host = queuedEditHost(SESSION_ID, message)
const { button, field } = await rows(message)
act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
act(() => field().props.onChangeText('B'))
act(() => field().props.onFocus())
const dictate = captureMobileNativeChatTextDestination()!
expect(dictate).toBeTypeOf('function')
const oldScope = state.hook!.queued.editor!.scopeKey
const destination = mobileNativeChatDraftDestination(oldScope)
let release = () => {}
const pending = new Promise<void>((resolve) => {
release = resolve
})
let oldEditId = ''
sendRequest.mockImplementation(async (method, params) => {
if (
method === 'agentSession.queuedMessageEditHold' &&
fieldsOf(params).action === 'release'
) {
oldEditId = String(fieldsOf(params).editId)
}
if (method !== 'agentSession.queuedMessageUpdate') {
return readOrHoldReply(method, params)
}
const decision =
mode === 'refused'
? { status: 'not-editable' as const, messageId: message.messageId }
: host.update(QueuedMessageUpdateParams.parse(params))
expect(decision.status).toBe(mode === 'refused' ? 'not-editable' : 'updated')
await pending
if (mode === 'unknown' || mode === 'unknown-phase') {
throw markRpcDeliveryUnknown(new Error('lost'))
}
return mutationOk(decision)
})
let save!: Promise<void>
act(() => {
save = button('Save edited message').props.onPress()
})
expect(state.hook!.queued.editor?.saving).toBe(true)
expect(field().props.editable).toBe(false)
expect(button('Save edited message').props.disabled).toBe(true)
expect(button('Cancel editing').props.disabled ?? false).toBe(false)
if (mode === 'unknown-phase') {
await act(async () => {
release()
await save
})
expect(state.hook!.queued.editor?.saving).toBe(false)
expect(field().props.editable).toBe(true)
}
await act(async () => button('Cancel editing').props.onPress())
expect(state.hook!.queued.editor).toBeUndefined()
expect(destination.active).toBe(false)
expect(oldEditId).not.toBe('')
expect(state.bottomText).toBe('occupied')
act(() => state.listener?.(batchEvent([message, other])))
await act(async () => {
await state.hook!.queued.edit!(other.messageId)
})
act(() => field().props.onChangeText('fresh input'))
const newScope = state.hook!.queued.editor!.scopeKey
act(() => expect(dictate('late speech')).toBe(false))
await act(async () => {
release()
await save
})
act(() => state.listener?.(batchEvent([{ ...message, body: host.row!.body }, other])))
expect(state.hook!.queued.editor).toMatchObject({
messageId: other.messageId,
text: 'fresh input',
scopeKey: newScope,
saving: false
})
expect(state.bottomText).toBe('occupied')
expect(readMobileNativeChatDraftInputs(oldScope)).toMatchObject({
files: [],
images: [],
skills: []
})
expect(error).not.toHaveBeenCalled()
expect(resolved).not.toHaveBeenCalled()
expect(
sendRequest.mock.calls.filter(
([method, params]) =>
method === 'agentSession.queuedMessageEditHold' &&
fieldsOf(params).action === 'release' &&
fieldsOf(params).editId === oldEditId
)
).toHaveLength(1)
host.leases.dispose()
}
)
it.each(['files', 'images'] as const)(
'real %s upload Cancel revokes its captured destination while normal pending admission blocks Save',
async (kind) => {
const { ok } = await import('./use-mobile-structured-agent-session-queued.test-fixture')
const message = queuedDraft({ messageId: `cancel-${kind}` })
const { root, button } = await rows(message)
act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
const scope = state.hook!.queued.editor!.scopeKey
const destination = mobileNativeChatDraftDestination(scope)
let release = () => {}
const pending = new Promise<void>((resolve) => {
release = resolve
})
let started = () => {}
const start = new Promise<void>((resolve) => {
started = resolve
})
picker.pickFiles.mockImplementation(async function* () {
yield { name: 'late.txt', mime: 'text/plain', byteLength: 1, base64: 'YQ==' }
yield { name: 'never.txt', mime: 'text/plain', byteLength: 1, base64: 'Yg==' }
})
picker.pickImages.mockResolvedValue([
{ base64: 'YQ==', uri: 'file:///late.png' },
{ base64: 'Yg==', uri: 'file:///never.png' }
])
const isStart = (method: string) =>
method.endsWith('uploadStart') || method === 'clipboard.startImageUpload'
sendRequest.mockImplementation(async (method, params) => {
if (isStart(method)) {
started()
await pending
return ok({ uploadId: 'held' })
}
if (method === 'clipboard.commitImageUpload') {
return ok('/late.png')
}
if (method.endsWith('uploadCommit')) {
return ok({ path: '/late.txt', name: 'late.txt', byteLength: 1 })
}
if (method.includes('uploadChunk') || method === 'clipboard.appendImageUploadChunk') {
return ok(null)
}
return readOrHoldReply(method, params)
})
const inline = root()
.findByType(MobileQueuedMessageComposer)
.findByType(MobileNativeChatComposer)
await act(async () => {
if (kind === 'files') {
inline.props.structured.onAttachFiles()
} else {
inline.props.onAttachImage()
}
await start
})
expect(readMobileNativeChatDraftInputs(scope).pending).toBe(1)
expect(state.hook!.queued.editor!.canSave).toBe(false)
expect(button('Save edited message').props.disabled).toBe(true)
expect(button('Cancel editing').props.disabled ?? false).toBe(false)
await act(async () => button('Cancel editing').props.onPress())
expect(destination.active).toBe(false)
expect(state.hook!.queued.editor).toBeUndefined()
await act(async () => {
release()
await vi.waitFor(() =>
expect(
sendRequest.mock.calls.some(
([method]) =>
method.endsWith('uploadCommit') || method === 'clipboard.commitImageUpload'
)
).toBe(true)
)
})
expect(sendRequest.mock.calls.filter(([method]) => isStart(method))).toHaveLength(1)
expect(
sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
).toBe(false)
expect(readMobileNativeChatDraftInputs(scope)).toMatchObject({
files: [],
images: [],
skills: []
})
expect(readMobileNativeChatDraftInputs('original-bottom')).toMatchObject({
files: [],
images: []
})
expect(state.bottomText).toBe('occupied')
expect(error).not.toHaveBeenCalled()
}
)
})
@@ -0,0 +1,254 @@
import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params'
import { useMobileNativeChatComposerMenu } from './native-chat/composer/use-mobile-native-chat-composer-menu'
import {
resetMobileNativeChatDraftStoreForTests,
useMobileNativeChatDraft
} from './native-chat/composer/mobile-native-chat-draft-store'
import {
updateMobileNativeChatDraftInputs,
resetMobileNativeChatDraftInputsForTests
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import { createElement, type ReactNode } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, expect, vi } from 'vitest'
import type {
AgentSessionQueuedMessage,
AgentSessionQueuedMessageEditHoldResult
} from '../../../src/shared/agent-session-wire'
import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
import { queuedMessageWithEdit } from '../../../src/shared/queued-message-edit'
import type { RpcClient } from '../transport/rpc-client'
import type { RpcResponse } from '../transport/types'
import { useMobileStructuredAgentSession } from './use-mobile-structured-agent-session'
import {
CAPABLE,
SESSION_ID,
fieldsOf,
mutationOk,
ok,
snapshotEvent
} from './use-mobile-structured-agent-session-queued.test-fixture'
export function withText(body: AgentSessionQueuedMessage['body'], text: string) {
const edited = queuedMessageWithEdit(body, { text })
if (!edited.ok) {
throw new Error(edited.reason)
}
return edited.body
}
export function editHoldReply(params: unknown): RpcResponse {
const result: AgentSessionQueuedMessageEditHoldResult =
fieldsOf(params).action === 'release'
? { status: 'released' }
: { status: 'held', fingerprint: 'fp', leaseDurationMs: 120_000, remainingMs: 120_000 }
return ok(result)
}
export function readOrHoldReply(method: string, params: unknown): RpcResponse {
return method === 'agentSession.queuedMessageEditHold'
? editHoldReply(params)
: ok({ models: [], current: {} })
}
vi.mock('react-native', () => ({
Text: 'Text',
View: 'View',
Pressable: 'Pressable',
ScrollView: 'ScrollView',
TextInput: 'TextInput',
ActivityIndicator: 'ActivityIndicator',
Image: 'Image',
Keyboard: { dismiss: vi.fn() },
Platform: { OS: 'ios' },
useWindowDimensions: () => ({ fontScale: 1 }),
StyleSheet: { create: (styles: unknown) => styles }
}))
vi.mock('lucide-react-native', () => ({
FileText: 'FileText',
Package: 'Package',
Terminal: 'Terminal',
ArrowUp: 'ArrowUp',
AtSign: 'AtSign',
AlertCircle: 'AlertCircle',
Image: 'Image',
Paperclip: 'Paperclip',
Check: 'Check',
ChevronDown: 'ChevronDown',
ChevronLeft: 'ChevronLeft',
ChevronRight: 'ChevronRight',
CornerDownRight: 'CornerDownRight',
ListEnd: 'ListEnd',
MoreHorizontal: 'MoreHorizontal',
Mic: 'Mic',
Pencil: 'Pencil',
Play: 'Play',
Plus: 'Plus',
Send: 'Send',
ShieldAlert: 'ShieldAlert',
Square: 'Square',
Trash2: 'Trash2',
X: 'X'
}))
vi.mock('@react-native-async-storage/async-storage', () => ({
default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
}))
export function mobileQueuedEditHarness() {
const state: {
renderer?: ReactTestRenderer
bottomText: string
hook?: ReturnType<typeof useMobileStructuredAgentSession>
menu?: ReturnType<typeof useMobileNativeChatComposerMenu>
listener?: (data: unknown) => void
} = { bottomText: '' }
const append = vi.fn(() => true)
const error = vi.fn()
const notice = vi.fn()
const resolved = vi.fn()
const sendRequest = vi.fn<RpcClient['sendRequest']>()
const client: RpcClient = {
sendRequest,
subscribe: (_method, _params, onData) => {
state.listener = onData
return () => {}
},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => null,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
function Harness({
sessionId = SESSION_ID,
editSupport = true,
enabled = true,
connected = true,
transport = client,
composerScopeKey,
imagesSupport = false,
skillsSupport = false,
agent = 'codex',
renderContent
}: {
sessionId?: string
editSupport?: boolean | null
enabled?: boolean
connected?: boolean
transport?: RpcClient | null
composerScopeKey?: string
imagesSupport?: boolean
skillsSupport?: boolean
agent?: string
renderContent?: (hook: ReturnType<typeof useMobileStructuredAgentSession>) => ReactNode
}): ReactNode {
state.bottomText = useMobileNativeChatDraft('original-bottom')
state.hook = useMobileStructuredAgentSession({
client: transport,
sessionId,
sourceIdentity: 'host-a',
enabled,
connected,
agent,
hostSupport:
editSupport === null
? null
: {
...CAPABLE,
sendSkills: true,
queuedMessages: false,
queuedMessageImageEdit: imagesSupport,
queuedMessageSkillsEdit: skillsSupport,
queuedMessageEdit: editSupport
},
composerScopeKey,
appendComposerText: append,
onSendError: error,
onQueuedEditNotice: notice,
onActionResolved: resolved
})
state.menu = useMobileNativeChatComposerMenu({
value: state.hook.queued.editor?.text ?? '',
onChangeText: (text) => state.hook?.queued.editor?.change(text),
agent,
structuredCatalog: {
reported: [{ name: 'review', kind: 'skill', path: '/B/SKILL.md' }],
conversationCommands: []
},
filePaths: [],
focusField: () => {},
editing: true,
// Mirrors the real composer: the menu hands over its row; the draft keeps name and path.
onPickSkill: ({ token, path }) => {
const key = state.hook?.queued.editor?.scopeKey
if (key && path) {
updateMobileNativeChatDraftInputs(key, (before) => ({
...before,
skills: [{ name: token.slice(1), path }]
}))
}
}
})
return renderContent?.(state.hook) ?? null
}
function requestedFingerprint(message: AgentSessionQueuedMessage) {
const params = sendRequest.mock.calls.findLast(
([method]) => method === 'agentSession.queuedMessageUpdate'
)?.[1]
const fields = QueuedMessageUpdateParams.parse(params)
const edited = queuedMessageWithEdit(message.body, fields)
if (!edited.ok) {
throw new Error(edited.reason)
}
return agentSessionSendBodyFingerprint(SESSION_ID, edited.body)
}
async function mount(
message: AgentSessionQueuedMessage,
editSupport: boolean | null = true,
agent = 'codex',
sessionId = SESSION_ID
) {
vi.clearAllMocks()
resetMobileNativeChatDraftInputsForTests()
resetMobileNativeChatDraftStoreForTests()
sendRequest.mockImplementation(async (method, params) =>
method === 'agentSession.queuedMessageUpdate'
? mutationOk({
status: 'updated',
messageId: message.messageId,
fingerprint: requestedFingerprint(message)
})
: readOrHoldReply(method, params)
)
await act(async () => {
state.renderer = create(createElement(Harness, { editSupport, agent, sessionId }))
})
const snapshot = snapshotEvent({ queuedMessages: [message], runningTurn: true })
act(() => state.listener?.({ ...snapshot, sessionId, page: { ...snapshot.page, sessionId } }))
if (editSupport !== null) {
await act(async () => {
expect(await state.hook!.queued.edit!(message.messageId)).toBe(true)
})
}
}
afterEach(async () => {
await act(async () => state.renderer?.unmount())
vi.useRealTimers()
vi.unstubAllGlobals()
})
return {
state,
Harness,
mount,
client,
sendRequest,
append,
error,
notice,
resolved,
requestedFingerprint
}
}
@@ -0,0 +1,366 @@
import { createElement } from 'react'
import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
import {
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import { act } from 'react-test-renderer'
import { beforeAll, describe, expect, it, vi } from 'vitest'
import type { QueuedEditHostFixtureModule } from '../../../src/shared/queued-edit-host.test-fixture'
import type { AgentSessionQueuedMessageEditHoldResult } from '../../../src/shared/agent-session-wire'
import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
import { mobileQueuedEditHarness, readOrHoldReply } from './mobile-queued-edit-hook.test-fixture'
import {
fieldsOf,
mutationOk,
ok,
queuedDraft,
SESSION_ID
} from './use-mobile-structured-agent-session-queued.test-fixture'
let queuedEditHost: QueuedEditHostFixtureModule['queuedEditHost']
beforeAll(async () => {
const fixtures = await vi.importActual<QueuedEditHostFixtureModule>(
'../../../src/main/native-chat/agent-session-journal/queued-edit-host.test-fixture'
)
queuedEditHost = fixtures.queuedEditHost
})
function deferred<T>() {
let resolve!: (value: T) => void
const promise = new Promise<T>((accept) => {
resolve = accept
})
return { promise, resolve }
}
describe('mobile current acquisition belongs to the Save outcome owner', () => {
const { state, Harness, mount, sendRequest, notice, append, resolved } = mobileQueuedEditHarness()
it.each([
'updated',
'unchanged',
'newer',
'fresh-loss',
'gone',
'refused',
'unknown',
'late-unknown',
'unresolved',
'depart',
'depart-equal'
] as const)(
'%s does not return accepted current input before the delayed result',
async (mode) => {
const message = queuedDraft({ messageId: 'lease-race' })
const host = queuedEditHost(SESSION_ID, message)
await mount(message)
act(() => state.hook!.queued.editor!.cancel())
const loss = deferred<AgentSessionQueuedMessageEditHoldResult>()
const freshLoss = deferred<AgentSessionQueuedMessageEditHoldResult>()
const release = deferred<void>()
let expected = ''
let editId = ''
let acquires = 0
sendRequest.mockImplementation(async (method, params) => {
const fields = fieldsOf(params)
if (method === 'agentSession.queuedMessageEditHold' && fields.action === 'acquire') {
acquires++
expected = String(fields.expectedBodyFingerprint)
editId = String(fields.editId)
return ok(
acquires === 1
? await loss.promise
: mode === 'fresh-loss'
? await freshLoss.promise
: host.acquire(editId, expected)
)
}
if (method !== 'agentSession.queuedMessageUpdate') {
return readOrHoldReply(method, params)
}
await release.promise
if (mode === 'unknown' || mode === 'late-unknown') {
throw markRpcDeliveryUnknown(new Error('lost'))
}
return mutationOk(
mode === 'refused' ? { status: 'not-editable', messageId: message.messageId } : decision
)
})
await act(async () => {
await state.hook!.queued.edit!(message.messageId)
})
act(() => state.hook!.queued.editor!.change('B'))
if (mode === 'unchanged') {
host.update({
messageId: message.messageId,
expectedBodyFingerprint: host.row!.fingerprint,
text: 'B'
})
}
let save!: Promise<boolean>
act(() => {
save = state.hook!.queued.editor!.save()
})
const decision = host.update({
messageId: message.messageId,
expectedBodyFingerprint: expected,
text: 'B'
})
expect(decision.status).toBe(mode === 'unchanged' ? 'unchanged' : 'updated')
if (mode === 'newer' || mode === 'fresh-loss' || mode === 'gone' || mode === 'depart') {
act(() => {
state.hook!.queued.editor!.insertDictation!('C')
})
}
if (mode === 'gone') {
host.depart()
}
const negative = host.acquire(editId, expected)
expect(negative.status).toBe(mode === 'gone' ? 'gone' : 'changed')
if (mode === 'depart' || mode === 'depart-equal') {
act(() => state.renderer!.unmount())
state.renderer = undefined
}
if (mode !== 'late-unknown' && mode !== 'unresolved') {
await act(async () => loss.resolve(negative))
if (mode !== 'depart' && mode !== 'depart-equal') {
expect(state.hook!.queued.editor?.saving).toBe(true)
}
expect(append).not.toHaveBeenCalled()
expect(notice).not.toHaveBeenCalled()
}
await act(async () => {
release.resolve()
await save
})
if (mode === 'late-unknown') {
expect(state.hook!.queued.editor).toMatchObject({ saving: false })
await act(async () => loss.resolve(negative))
}
if (mode === 'newer' || mode === 'fresh-loss') {
expect(state.hook!.queued.editor).toMatchObject({ text: 'B C', saving: false })
expect(append).not.toHaveBeenCalled()
expect(acquires).toBe(2)
expect(resolved).not.toHaveBeenCalled()
if (mode === 'fresh-loss') {
host.depart()
await act(async () => freshLoss.resolve(host.acquire(editId, expected)))
expect(state.hook!.queued.editor).toBeUndefined()
expect(append).toHaveBeenCalledWith('B C')
expect(notice).toHaveBeenCalledOnce()
} else {
act(() => state.hook!.queued.editor!.cancel())
expect(state.bottomText).toBe('')
}
} else if (
mode === 'gone' ||
mode === 'refused' ||
mode === 'unknown' ||
mode === 'late-unknown' ||
mode === 'depart'
) {
if (mode !== 'depart') {
expect(state.hook!.queued.editor).toBeUndefined()
}
expect(append).toHaveBeenCalledOnce()
expect(append).toHaveBeenCalledWith(mode === 'gone' || mode === 'depart' ? 'B C' : 'B')
expect(notice).toHaveBeenCalledOnce()
} else {
if (mode !== 'depart-equal') {
expect(state.hook!.queued.editor).toBeUndefined()
}
expect(append).not.toHaveBeenCalled()
expect(notice).not.toHaveBeenCalled()
if (mode !== 'depart-equal') {
expect(resolved).toHaveBeenCalledOnce()
}
}
if (mode === 'unresolved') {
await act(async () => loss.resolve(negative))
}
expect(append).toHaveBeenCalledTimes(
['gone', 'refused', 'unknown', 'late-unknown', 'depart', 'fresh-loss'].includes(mode)
? 1
: 0
)
host.leases.dispose()
}
)
it.each(['unknown-changed', 'unknown-gone', 'pending-proof', 'rebase-loss'] as const)(
'%s delivers timed terminal loss through the actual phone lease into its owner',
async (mode) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const message = queuedDraft({ messageId: 'timed' })
const host = queuedEditHost(SESSION_ID, message)
await mount(message)
await act(async () => state.hook!.queued.editor!.cancel())
const actions: string[] = []
const reply = deferred<void>()
let decision: ReturnType<typeof host.update>
sendRequest.mockImplementation(async (method, params) => {
if (method === 'agentSession.queuedMessageEditHold') {
const fields = fieldsOf(params)
const editId = String(fields.editId)
const key = { callerKey: 'client', editId }
actions.push(String(fields.action))
if (fields.action === 'release') {
host.leases.release(key, message.messageId)
return ok({ status: 'released' })
}
return ok(
fields.action === 'acquire'
? host.acquire(editId, String(fields.expectedBodyFingerprint))
: host.leases.renew(key, message.messageId)
)
}
if (method !== 'agentSession.queuedMessageUpdate') {
return readOrHoldReply(method, params)
}
decision = host.update({
messageId: message.messageId,
expectedBodyFingerprint: host.row!.fingerprint,
text: '$review B'
})
expect(decision.status).toBe('updated')
await reply.promise
if (mode.startsWith('unknown')) {
throw markRpcDeliveryUnknown(new Error('lost'))
}
return mutationOk(decision)
})
await act(async () =>
state.renderer!.update(
createElement(Harness, {
composerScopeKey: 'original-bottom',
imagesSupport: true,
skillsSupport: true
})
)
)
await act(async () => {
await state.hook!.queued.edit!(message.messageId)
})
act(() => setMobileNativeChatDraftText('original-bottom', 'occupied'))
act(() => state.hook!.queued.editor!.change('$review B'))
let save!: Promise<boolean>
await act(async () => {
save = state.hook!.queued.editor!.save()
})
const scope = state.hook!.queued.editor!.scopeKey
if (mode === 'rebase-loss') {
act(() => {
state.hook!.queued.editor!.insertDictation!('C')
updateMobileNativeChatDraftInputs(scope, (input) => ({
...input,
skills: [{ name: 'review', path: '/C/SKILL.md' }],
images: [{ id: 'new-C', path: '/C.png', previewUri: 'file:///C.png' }]
}))
})
}
if (mode !== 'pending-proof') {
await act(async () => {
reply.resolve()
await save
})
}
if (mode === 'unknown-gone') {
host.depart()
}
if (mode === 'rebase-loss') {
expect(state.hook!.queued.editor).toMatchObject({ text: '$review B C', saving: false })
expect(state.bottomText).toBe('occupied')
expect(host.leases.heldIds()).toEqual(new Set([message.messageId]))
host.update({
messageId: message.messageId,
expectedBodyFingerprint: host.row!.fingerprint,
text: 'rival'
})
}
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
if (mode === 'pending-proof') {
expect(state.hook!.queued.editor?.saving).toBe(true)
expect(notice).not.toHaveBeenCalled()
expect(state.bottomText).toBe('occupied')
await act(async () => {
reply.resolve()
await save
})
}
expect(state.hook!.queued.editor).toBeUndefined()
expect(state.bottomText).toBe(
mode === 'pending-proof'
? 'occupied'
: `occupied\n\n$review B${mode === 'rebase-loss' ? ' C' : ''}`
)
expect(notice).toHaveBeenCalledTimes(mode === 'pending-proof' ? 0 : 1)
if (mode === 'rebase-loss') {
expect(readMobileNativeChatDraftInputs('original-bottom')).toMatchObject({
skills: [{ name: 'review', path: '/C/SKILL.md' }],
images: [{ id: 'new-C', path: '/C.png' }]
})
}
expect(actions).toEqual(
mode === 'rebase-loss'
? ['acquire', 'acquire', 'release', 'renew', 'acquire', 'release']
: ['acquire', 'renew', 'acquire', 'release']
)
const count = sendRequest.mock.calls.length
await act(async () => {
await vi.advanceTimersByTimeAsync(120_000)
})
expect(sendRequest.mock.calls).toHaveLength(count)
host.leases.dispose()
}
)
it.each(['gone', 'held'] as const)(
'initial phone transport failure then timed %s preserves owner outcomes',
async (status) => {
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
const message = queuedDraft({ messageId: 'retry' })
const host = queuedEditHost(SESSION_ID, message)
await mount(message)
act(() => state.hook!.queued.editor!.cancel())
let first = true
sendRequest.mockImplementation(async (method, params) => {
const fields = fieldsOf(params)
if (method !== 'agentSession.queuedMessageEditHold') {
return readOrHoldReply(method, params)
}
if (fields.action === 'release') {
return ok({ status: 'released' })
}
if (first) {
first = false
throw new Error('offline')
}
return ok(host.acquire(String(fields.editId), String(fields.expectedBodyFingerprint)))
})
await act(async () => {
await state.hook!.queued.edit!(message.messageId)
})
act(() => state.hook!.queued.editor!.change('B'))
if (status === 'gone') {
host.depart()
}
await act(async () => {
await vi.advanceTimersByTimeAsync(30_000)
})
if (status === 'gone') {
expect(state.hook!.queued.editor).toBeUndefined()
expect(append).toHaveBeenCalledOnce()
expect(append).toHaveBeenCalledWith('B')
expect(notice).toHaveBeenCalledOnce()
} else {
expect(state.hook!.queued.editor).toMatchObject({ text: 'B', saving: false })
expect(append).not.toHaveBeenCalled()
act(() => state.hook!.queued.editor!.cancel())
}
host.leases.dispose()
warn.mockRestore()
}
)
})
@@ -0,0 +1,594 @@
import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items'
import type { QueuedEditHostFixtureModule } from '../../../src/shared/queued-edit-host.test-fixture'
import type { AcpCommandOptionsFixtureModule } from '../../../src/shared/mobile-queued-edit-host.test-fixture-contract'
import { QueuedMessageUpdateParams } from '../../../src/shared/rpc-contract/structured-agent-session-queued-edit-params'
import { mobileQueuedEditHarness, readOrHoldReply } from './mobile-queued-edit-hook.test-fixture'
import { createElement, type ReactNode } from 'react'
import { act } from 'react-test-renderer'
import { describe, expect, it, vi } from 'vitest'
import { ScrollView, TextInput } from 'react-native'
import { ActionSheetModal } from '../components/ActionSheetModal'
import { MobileQueuedMessageComposerContext } from './mobile-queued-message-composer-context'
import { MobileNativeChatQueuedMessages } from './native-chat/input/MobileNativeChatQueuedMessages'
import {
MobileNativeChatComposer,
MobileNativeChatDraftComposer
} from './native-chat/composer/MobileNativeChatComposer'
import { MobileNativeChatComposerMenu } from './native-chat/composer/MobileNativeChatComposerMenu'
import { MobileQueuedMessageComposer } from './MobileQueuedMessageComposer'
import { useMobileNativeChatDrafts } from './native-chat/composer/use-mobile-native-chat-drafts'
import { useMobileStructuredNativeChatSendBridge } from './use-mobile-structured-native-chat-send-bridge'
import { mobileNativeChatScopeKey } from './native-chat/mobile-native-chat-scope-key'
import { structuredSendResultFixture } from './structured-agent-send-result.test-fixture'
import { useMobileNativeChatFileAttachments } from './native-chat/composer/use-mobile-native-chat-file-attachments'
import { useMobileNativeChatImageAttachments } from './native-chat/composer/use-mobile-native-chat-image-attachments'
import {
useMobileNativeChatDraft,
setMobileNativeChatDraftText
} from './native-chat/composer/mobile-native-chat-draft-store'
import {
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import {
queuedDraft,
SESSION_ID,
mutationOk
} from './use-mobile-structured-agent-session-queued.test-fixture'
const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
vi.mock('../platform/media-picker', () => ({ useMediaPicker: () => picker }))
vi.mock('../components/DragReorderList', () => ({ DragReorderList: 'DragReorderList' }))
vi.mock('react-native-reanimated', async () => {
const { useRef } = await import('react')
return {
default: { ScrollView: 'ScrollView' },
useAnimatedRef: () => useRef(null),
useSharedValue: (value: unknown) => useRef({ value }).current
}
})
vi.mock('../components/ActionSheetModal', () => ({ ActionSheetModal: 'ActionSheetModal' }))
vi.mock('../components/mounted-bottom-drawer', () => ({ MountedBottomDrawer: 'BottomDrawer' }))
vi.mock('../components/bottom-drawer-modal-host-scope', () => ({
useBottomDrawerModalHost: () => null
}))
const { queuedEditHost } = await vi.importActual<QueuedEditHostFixtureModule>(
'../../../src/main/native-chat/agent-session-journal/queued-edit-host.test-fixture'
)
const { AcpStructuredOptions } = await vi.importActual<AcpCommandOptionsFixtureModule>(
'../../../src/main/acp/acp-structured-options'
)
describe('phone inline editor presentation', () => {
const { state, Harness, mount, sendRequest, error, resolved, client } = mobileQueuedEditHarness()
async function rows(
message: Parameters<typeof mount>[0],
agent = 'codex',
sessionId = SESSION_ID,
catalog: {
reported: { name: string; kind: 'skill' | 'command'; path?: string }[]
discovery?: NativeChatSkillDiscoverySnapshot
} = {
reported: []
},
extra?: (hook: NonNullable<typeof state.hook>) => ReactNode,
composerScopeKey = 'original-bottom'
) {
await mount(message, true, agent, sessionId)
act(() => state.hook!.queued.editor!.cancel())
resolved.mockClear()
const renderContent: NonNullable<Parameters<typeof Harness>[0]['renderContent']> = (hook) =>
createElement(
MobileQueuedMessageComposerContext.Provider,
{
value: {
agent,
structured: {
catalog: { reported: catalog.reported, conversationCommands: [] },
onSlashMenuOpen: () => {},
files: [],
onRemoveFile: () => {}
},
skillDiscovery: catalog.discovery,
filePaths: [],
onNeedFiles: undefined,
onError: error,
onMicPress: undefined,
micActive: false,
dictationMode: undefined,
onMicPressIn: () => {},
onMicPressOut: () => {}
}
},
createElement(MobileNativeChatQueuedMessages, {
cards: hook.queued.cards,
onEdit: hook.queued.edit,
editor: hook.queued.editor
}),
extra?.(hook)
)
const rerender = async () =>
act(async () =>
state.renderer!.update(
createElement(Harness, {
sessionId,
agent,
renderContent,
skillsSupport: true,
imagesSupport: true,
composerScopeKey
})
)
)
await rerender()
const root = () => state.renderer!.root
const button = (label: string) =>
root().findAll(
(node) =>
node.props.accessibilityLabel === label && typeof node.props.onPress === 'function'
)[0]!
const field = () =>
root()
.findByType(MobileQueuedMessageComposer)
.find((node) => node.type === TextInput && node.props.multiline === true)
const open = async () => {
await act(async () => button('More actions').props.onPress())
const sheet = root().find(
(node) =>
node.type === ActionSheetModal && node.props.actions?.[0]?.label === 'Edit message'
)
await act(async () => sheet.props.actions[0].onPress())
expect(root().findAllByType(MobileQueuedMessageComposer)).toHaveLength(1)
expect(root().findAllByType(MobileNativeChatComposer)).toHaveLength(extra ? 2 : 1)
}
await open()
return { root, button, field, rerender, open }
}
it('gives the short image editor and open picker the available queue scroll space, separate from the ordinary draft', async () => {
const message = queuedDraft({
messageId: 'photo-layout',
body: {
kind: 'message',
role: 'user',
blocks: [
{ type: 'text', text: 'short edit' },
{ type: 'image-ref', url: 'https://host/photo.png', alt: 'photo' }
]
}
})
const catalog = {
reported: Array.from({ length: 6 }, (_, i) => ({
name: `skill-${i}`,
kind: 'skill' as const,
path: `/skills/${i}/SKILL.md`
}))
}
const { root, button } = await rows(message, 'codex', SESSION_ID, catalog, () =>
createElement(MobileNativeChatDraftComposer, {
draftKey: 'original-bottom',
draftScopeKey: 'original-bottom',
agent: 'codex',
structured: {
catalog: { ...catalog, conversationCommands: [] },
onSlashMenuOpen: () => {},
files: [],
onRemoveFile: () => {}
},
onChangeText: (text) => setMobileNativeChatDraftText('original-bottom', text),
onSend: async () => true,
sendSurfaceId: 'original-bottom',
getSendCompletionGeneration: () => 0,
getComposerEditGeneration: () => 0
})
)
const { snapshotEvent } =
await import('./use-mobile-structured-agent-session-queued.test-fixture')
act(() => {
setMobileNativeChatDraftText('original-bottom', 'Bottom draft stays here.')
state.listener?.(
snapshotEvent({
queuedMessages: [message, queuedDraft({ messageId: 'neighbor', position: 2 })],
runningTurn: true
})
)
})
const style = (value: unknown): Record<string, unknown> => Object.assign({}, ...[value].flat())
const queue = () => root().findByType(MobileNativeChatQueuedMessages)
const scroll = () =>
queue().find((node) => node.type === ScrollView && node.props.onContentSizeChange)
const box = () => root().findByProps({ testID: 'queued-box' })
const editor = () => root().findByType(MobileQueuedMessageComposer)
const bottom = () => root().findByType(MobileNativeChatDraftComposer)
expect(editor().findByType(MobileNativeChatComposer).props.attachments).toHaveLength(1)
expect(queue().findAllByProps({ testID: 'queued-card-row' })).toHaveLength(2)
// Every boundary down to the scrollport must yield to the keyboard/bottom siblings.
for (const node of [box().parent!, box(), scroll().parent!, scroll()]) {
expect(style(node.props.style)).toMatchObject({ flexShrink: 1, minHeight: 0 })
}
expect(style(scroll().props.style).maxHeight).toBeUndefined()
expect(style(box().parent!.props.style).marginBottom).toBe(0)
expect(style(box().props.style).paddingBottom).toBe(0)
expect(queue().findAllByType(MobileNativeChatDraftComposer)).toHaveLength(0)
const field = editor().findByType(TextInput)
act(() => {
field.props.onChangeText('/')
field.props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
})
const menuScroll = root().findByType(MobileNativeChatComposerMenu).findByType(ScrollView)
expect(style(menuScroll.props.style).maxHeight).toBe(300)
expect(menuScroll.props.nestedScrollEnabled).toBe(true)
expect(menuScroll.props.keyboardShouldPersistTaps).toBe('always')
const scrollTo = vi.fn()
scroll().props.ref.current = { scrollTo, flashScrollIndicators: vi.fn() }
act(() => {
scroll().props.onLayout({ nativeEvent: { layout: { height: 280 } } })
scroll().props.onContentSizeChange(360, 800)
editor().parent!.props.onLayout({
nativeEvent: { layout: { x: 0, y: 0, width: 360, height: 620 } }
})
})
expect(scrollTo).toHaveBeenCalledExactlyOnceWith({ y: 0, animated: false })
act(() => scroll().props.onScroll({ nativeEvent: { contentOffset: { y: 120 } } }))
expect(scrollTo).toHaveBeenCalledTimes(1)
await act(async () => button('$skill-5').props.onPress())
expect(state.hook!.queued.editor?.text).toBe('$skill-5 ')
expect(readMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey).skills).toEqual([
{ name: 'skill-5', path: '/skills/5/SKILL.md' }
])
expect(editor().findByType(MobileNativeChatComposer).props.attachments).toHaveLength(1)
expect(bottom().findByType(TextInput).props.value).toBe('Bottom draft stays here.')
await act(async () => button('Cancel editing').props.onPress())
expect(style(scroll().props.style).maxHeight).toBe(160)
expect(style(box().parent!.props.style).marginBottom).toBeLessThan(0)
expect(bottom().findByType(TextInput).props.value).toBe('Bottom draft stays here.')
act(() => {
bottom().findByType(TextInput).props.onChangeText('/')
bottom()
.findByType(TextInput)
.props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
})
const ordinaryMenu = bottom().findByType(MobileNativeChatComposerMenu).findByType(ScrollView)
expect(style(ordinaryMenu.props.style).maxHeight).toBe(300)
expect(ordinaryMenu.props.nestedScrollEnabled).toBeFalsy()
expect(
sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
).toBe(false)
})
it('hands back into the main captured Send path, keeps pending files, and restores a rejected complete draft', async () => {
const { snapshotEvent, ok, fieldsOf } =
await import('./use-mobile-structured-agent-session-queued.test-fixture')
const scope = mobileNativeChatScopeKey('host', 'worktree', 'handoff')!
const message = queuedDraft({
messageId: 'pending-files',
body: {
kind: 'message',
role: 'user',
blocks: [{ type: 'text', text: '$review intent' }],
skills: [{ name: 'review', path: '/edit/SKILL.md' }]
}
})
function Bottom({ session }: { session: NonNullable<typeof state.hook> }) {
const drafts = useMobileNativeChatDrafts({
hostId: 'host',
worktreeId: 'worktree',
tabId: 'handoff',
sessionId: SESSION_ID,
messages: [],
transcriptSettled: true
})
const bridge = useMobileStructuredNativeChatSendBridge({
...drafts,
agent: 'codex',
sendStructured: session.sendWithOutcome,
onSendError: error
})
const text = useMobileNativeChatDraft(scope)
const files = useMobileNativeChatFileAttachments({
client,
sessionId: SESSION_ID,
scopeKey: scope,
enabled: true,
showToast: error
})
const images = useMobileNativeChatImageAttachments({
client,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'connected',
scopeKey: scope,
enabled: true,
structuredNativeChat: true,
showToast: error,
onSendError: error,
baseSend: bridge.sendWithOutcome,
readSeededLaunchDraft: () => null,
files: files.files,
onFilesSent: files.removeFiles
})
return createElement(MobileNativeChatComposer, {
value: text,
agent: 'codex',
draftScopeKey: scope,
onChangeText: drafts.setComposerText,
onSend: images.sendNativeChat,
sendSurfaceId: scope,
getSendCompletionGeneration: () => 0,
getComposerEditGeneration: drafts.getComposerEditGeneration,
attachments: images.attachments,
structured: {
catalog: { reported: [], conversationCommands: [] },
onSlashMenuOpen: () => {},
files: files.files,
onRemoveFile: () => {}
}
})
}
const { root, button, field } = await rows(
message,
'codex',
SESSION_ID,
{ reported: [{ name: 'later', kind: 'skill', path: '/later/SKILL.md' }] },
(hook) => createElement(Bottom, { session: hook }),
scope
)
act(() => {
field().props.onChangeText('$review intent then $la')
field().props.onSelectionChange({ nativeEvent: { selection: { start: 23, end: 23 } } })
})
await act(async () => button('$later').props.onPress())
act(() => {
setMobileNativeChatDraftText(scope, '$prior occupied')
updateMobileNativeChatDraftInputs(scope, () => ({
images: [{ id: 'prior-image', path: '/prior.png', previewUri: 'file:///prior.png' }],
files: [
{
id: 'prior-file',
path: '/prior.txt',
name: 'prior.txt',
mime: 'text/plain',
byteLength: 1
}
],
skills: [{ name: 'prior', path: '/prior/SKILL.md' }]
}))
updateMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey, (input) => ({
...input,
images: [{ id: 'edit-image', path: '/added.png', previewUri: 'file:///added.png' }]
}))
})
let release = () => {}
const held = new Promise<void>((resolve) => {
release = resolve
})
let started = () => {}
const start = new Promise<void>((resolve) => {
started = resolve
})
picker.pickFiles.mockImplementation(async function* () {
yield { name: 'late.txt', mime: 'text/plain', byteLength: 1, base64: 'YQ==' }
})
let rejected = false
sendRequest.mockImplementation(async (method, params) => {
if (method.endsWith('uploadStart')) {
started()
await held
return ok({ uploadId: 'pending-upload' })
}
if (method.endsWith('uploadCommit')) {
return ok({ path: '/late.txt', name: 'late.txt', byteLength: 1 })
}
if (method.endsWith('uploadChunk')) {
return ok(null)
}
if (method === 'agentSession.send') {
if (!rejected) {
rejected = true
return {
id: 'send-refusal',
ok: false,
error: { code: 'unauthorized', message: 'Send refused before execution' }
}
}
return mutationOk(structuredSendResultFixture('accepted'))
}
return readOrHoldReply(method, params)
})
const inline = root()
.findByType(MobileQueuedMessageComposer)
.findByType(MobileNativeChatComposer)
await act(async () => {
inline.props.structured.onAttachFiles()
await start
})
const beforeBottom = root()
.findAllByType(MobileNativeChatComposer)
.find((node) => node.props.draftScopeKey === scope)!
act(() => state.listener?.(snapshotEvent({ queuedMessages: [] })))
expect(root().findByType(MobileNativeChatComposer)).toBe(beforeBottom)
expect(state.hook!.queued.editor).toBeUndefined()
const pressSend = () =>
root()
.findAll(
(node) =>
node.props.accessibilityLabel === 'Send message' &&
typeof node.props.onPress === 'function'
)[0]!
.props.onPress()
await act(async () => pressSend())
expect(sendRequest.mock.calls.some(([method]) => method === 'agentSession.send')).toBe(false)
await act(async () => {
release()
await vi.waitFor(() => expect(readMobileNativeChatDraftInputs(scope).pending ?? 0).toBe(0))
})
await act(async () => pressSend())
expect(root().findByType(MobileNativeChatComposer)).toBe(beforeBottom)
expect(root().findByType(TextInput).props.value).toBe(
'$prior occupied\n\n$review intent then $later '
)
expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([
{ name: 'prior', path: '/prior/SKILL.md' },
{ name: 'review', path: '/edit/SKILL.md' },
{ name: 'later', path: '/later/SKILL.md' }
])
await act(async () => pressSend())
const requests = sendRequest.mock.calls.filter(([method]) => method === 'agentSession.send')
expect(requests).toHaveLength(2)
expect(requests[1]![1]).toMatchObject({ body: fieldsOf(requests[0]![1]).body })
expect(requests[0]![1]).toMatchObject({
body: {
blocks: [
{
type: 'text',
text: '$prior occupied\n\n$review intent then $later\n@/prior.txt @/late.txt'
},
{ type: 'image-ref', path: '/prior.png' },
{ type: 'image-ref', path: '/added.png' }
],
skills: [
{ name: 'prior', path: '/prior/SKILL.md' },
{ name: 'review', path: '/edit/SKILL.md' },
{ name: 'later', path: '/later/SKILL.md' }
]
}
})
expect(readMobileNativeChatDraftInputs(scope).files).toEqual([])
expect(readMobileNativeChatDraftInputs(scope).images).toEqual([])
})
it('refuses a stale control pick but saves a typed namesake literally when its menu is closed', async () => {
const message = queuedDraft({ messageId: 'namesake' })
const { root, button, field } = await rows(message, 'claude', SESSION_ID, {
reported: [{ name: 'model', kind: 'skill', path: '/A/SKILL.md' }]
})
act(() => field().props.onChangeText('/'))
act(() => field().props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } }))
const stale = root().findByType(MobileNativeChatComposerMenu).props.onPick
await act(async () => button('/model').props.onPress())
const key = state.hook!.queued.editor!.scopeKey
expect(readMobileNativeChatDraftInputs(key).skills).toHaveLength(1)
act(() => stale({ kind: 'command', token: '/model', name: 'model', id: 'command:model' }))
expect(error).toHaveBeenLastCalledWith("Commands can't be saved in a queued message.")
expect(state.hook!.queued.editor!.text).toBe('/model ')
act(() => field().props.onChangeText(''))
act(() => field().props.onChangeText('/model literal'))
expect(readMobileNativeChatDraftInputs(key).skills).toEqual([])
act(() =>
field().props.onSelectionChange({ nativeEvent: { selection: { start: 14, end: 14 } } })
)
expect(root().findAllByType(MobileNativeChatComposerMenu)).toHaveLength(0)
await act(async () => button('Save edited message').props.onPress())
expect(error).toHaveBeenCalledOnce()
expect(
sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
).toHaveLength(1)
expect(
sendRequest.mock.calls.some(([method]) =>
/(?:\.send$|conversationCommand|goal|resume|pty)/i.test(method)
)
).toBe(false)
expect(state.hook!.queued.editor).toBeUndefined()
})
it('an image-only attributed card reaches the actual inline composer and no-op Save retains its image and sender', async () => {
const message = queuedDraft({
messageId: 'photo-only',
body: {
kind: 'message',
role: 'user',
blocks: [{ type: 'image-ref', url: 'https://host/photo.png', alt: 'photo' }],
from: { kind: 'agent', senders: [], orchestration: null }
}
})
const { root, button } = await rows(message)
expect(root().findByType(MobileNativeChatComposer).props.attachments).toHaveLength(1)
await act(async () => button('Save edited message').props.onPress())
expect(state.hook!.queued.editor).toBeUndefined()
expect(
sendRequest.mock.calls.some(([method]) => method === 'agentSession.queuedMessageUpdate')
).toBe(false)
expect(state.hook!.queued.cards[0]?.images).toEqual(message.body.blocks)
expect(state.hook!.queued.cards[0]?.attribution).not.toBeNull()
expect(state.bottomText).toBe('')
})
it('saves a scanned model skill picked through More and Edit without dispatching a host command', async () => {
const options = new AcpStructuredOptions()
options.adoptCommands([{ name: 'model', description: 'Choose the model' }])
const reported = options.readCommands() ?? []
expect(reported).toEqual([{ name: 'model', kind: 'command', description: 'Choose the model' }])
const message = queuedDraft({
messageId: 'scanned-model',
body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'seed' }] }
})
const host = queuedEditHost(SESSION_ID, message)
try {
const { root, button, field } = await rows(message, 'opencode2', SESSION_ID, {
reported,
discovery: {
status: 'ready',
skills: [
{
id: 'repo:model',
name: 'model',
description: 'Explain the domain model',
providers: ['agent-skills'],
sourceKind: 'repo',
sourceLabel: 'Repo',
rootPath: '/workspace/.agents/skills',
directoryPath: '/workspace/.agents/skills/model',
skillFilePath: '/workspace/.agents/skills/model/SKILL.md',
installed: true,
updatedAt: null
}
]
}
})
sendRequest.mockImplementation(async (method, params) =>
method === 'agentSession.queuedMessageUpdate'
? mutationOk(host.update(QueuedMessageUpdateParams.parse(params)))
: readOrHoldReply(method, params)
)
act(() => field().props.onChangeText('/'))
act(() =>
field().props.onSelectionChange({ nativeEvent: { selection: { start: 1, end: 1 } } })
)
const menu = root().findByType(MobileNativeChatComposerMenu)
expect(menu.props.rows.filter((row: { token?: string }) => row.token === '/model')).toEqual([
expect.objectContaining({
kind: 'skill',
id: 'skill:model',
token: '/model',
sources: [
{ sourceKind: 'repo', skillFilePath: '/workspace/.agents/skills/model/SKILL.md' }
]
})
])
expect(
menu.props.rows.find((row: { token?: string }) => row.token === '/model')
).not.toHaveProperty('path')
await act(async () => button('/model').props.onPress())
expect(state.hook!.queued.editor?.text).toBe('/model ')
expect(readMobileNativeChatDraftInputs(state.hook!.queued.editor!.scopeKey).skills).toEqual(
[]
)
expect(error.mock.calls).toEqual([])
await act(async () => button('Save edited message').props.onPress())
expect(
sendRequest.mock.calls.some(([method]) =>
/(?:\.send$|conversationCommand|goal|resume|pty|setOption)/i.test(method)
)
).toBe(false)
expect(error.mock.calls).toEqual([])
expect(
sendRequest.mock.calls.filter(([method]) => method === 'agentSession.queuedMessageUpdate')
).toHaveLength(1)
expect(state.hook!.queued.editor).toBeUndefined()
expect(host.row!.body.blocks).toEqual([{ type: 'text', text: '/model' }])
expect(host.row!.body.skills).toBeUndefined()
} finally {
host.leases.dispose()
}
})
})
@@ -0,0 +1,136 @@
import { mobileQueuedEditHarness, withText } from './mobile-queued-edit-hook.test-fixture'
import { countedQueuedEditPublication } from '../../../src/shared/queued-edit-publication.test-fixture'
import * as publication from '../../../src/shared/queued-message-edit-publication'
import * as eligibility from '../../../src/shared/queued-message-edit-command'
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import {
queuedDraft,
snapshotEvent
} from './use-mobile-structured-agent-session-queued.test-fixture'
import { useMobileNativeChatComposerMenu } from './native-chat/composer/use-mobile-native-chat-composer-menu'
import { markRpcDeliveryUnknown } from '../transport/rpc-delivery-ambiguity'
import type { MobileComposerStructuredCatalog } from './native-chat/composer/mobile-native-chat-composer-menu'
afterEach(() => vi.restoreAllMocks())
const { state, mount, sendRequest } = mobileQueuedEditHarness()
it.each([10, 100])(
'actual phone hook bounds publication-key reads with %i fresh Q/C/R rows',
async (n) => {
const counter = countedQueuedEditPublication()
vi.spyOn(publication, 'queuedEditPublicationKey').mockImplementation(counter.key)
const message = queuedDraft({ messageId: 'target' })
await mount(message)
act(() => state.hook!.queued.editor!.cancel())
const rows = () => [
...Array.from({ length: n - 1 }, (_, i) => queuedDraft({ messageId: `other-${i}` })),
message
]
const submissions = () =>
Array.from({ length: n }, (_, i) => ({
clientMessageId: `s${i}`,
queuedMessageId: `unused-${i}`,
fence: 3,
payloadFingerprint: 'other',
dispatchState: 'pending' as const,
providerItemId: null,
reason: null,
submittedAt: 1,
resolvedAt: null
}))
counter.reset()
act(() =>
state.listener?.(snapshotEvent({ queuedMessages: rows(), submissions: submissions() }))
)
expect(counter.reads).toBe(0)
await act(async () => {
await state.hook!.queued.edit!('target')
})
counter.reset()
act(() =>
state.listener?.(snapshotEvent({ queuedMessages: rows(), submissions: submissions() }))
)
expect(counter.reads).toBeGreaterThanOrEqual(3 * n)
expect(counter.reads).toBeLessThanOrEqual(3 * n + 2)
expect(state.hook!.queued.editor).toBeDefined()
act(() => state.hook!.queued.editor!.change('saved'))
sendRequest.mockRejectedValueOnce(markRpcDeliveryUnknown(new Error('lost')))
await act(async () => {
await state.hook!.queued.editor!.save()
})
counter.reset()
act(() =>
state.listener?.(
snapshotEvent({
queuedMessages: [
...rows().slice(0, -1),
{ ...message, body: withText(message.body, 'saved') }
],
submissions: submissions()
})
)
)
expect(counter.reads).toBeLessThanOrEqual(3 * n + 2)
expect(state.hook!.queued.editor).toBeUndefined()
}
)
it.each([10, 100])(
'actual phone menu reuses one eligibility preparation across query/all-token paths for %i rows',
async (n) => {
const prepare = vi.spyOn(eligibility, 'prepareQueuedMessageEditText')
const reported = () =>
Array.from({ length: n }, (_, i) => ({ name: `provider-${i}`, kind: 'command' as const }))
const catalog: MobileComposerStructuredCatalog = {
reported: reported(),
conversationCommands: []
}
let menu!: ReturnType<typeof useMobileNativeChatComposerMenu>
function Menu({
value = '',
agent = 'claude',
editing = true,
structured = catalog
}: {
value?: string
agent?: string
editing?: boolean
structured?: MobileComposerStructuredCatalog
}) {
menu = useMobileNativeChatComposerMenu({
value,
agent,
structuredCatalog: structured,
filePaths: [],
onChangeText: () => {},
focusField: () => {},
editing
})
return null
}
let renderer!: ReturnType<typeof create>
await act(async () => {
renderer = create(createElement(Menu))
})
try {
expect(prepare).toHaveBeenCalledTimes(1)
for (const value of ['/', '/p', '/provider', '/provider-9']) {
act(() => renderer.update(createElement(Menu, { value })))
act(() => menu.onSelectionChange({ start: value.length, end: value.length }))
}
expect(menu.rows.length).toBeGreaterThan(0)
expect(prepare).toHaveBeenCalledTimes(1)
act(() => renderer.update(createElement(Menu, { value: '/', editing: false })))
expect(prepare).toHaveBeenCalledTimes(1)
act(() =>
renderer.update(
createElement(Menu, { value: '/', structured: { ...catalog, reported: reported() } })
)
)
expect(prepare).toHaveBeenCalledTimes(2)
act(() => renderer.update(createElement(Menu, { value: '/', agent: 'codex' })))
expect(prepare).toHaveBeenCalledTimes(3)
} finally {
act(() => renderer.unmount())
}
}
)
@@ -0,0 +1,18 @@
import type { NativeChatSkillDiscoverySnapshot } from '../../../src/shared/native-chat/input/native-chat-picker-items'
import { createContext } from 'react'
import type { MobileNativeChatStructuredComposer } from './native-chat/composer/MobileNativeChatComposer'
export const MobileQueuedMessageComposerContext = createContext<{
agent: string | null
structured: MobileNativeChatStructuredComposer | null
skillDiscovery?: NativeChatSkillDiscoverySnapshot
onNeedSkills?: () => void
filePaths: string[]
onNeedFiles: ((query: string) => void) | undefined
onError: (text: string) => void
onMicPress: (() => void) | undefined
micActive: boolean
dictationMode: string | undefined
onMicPressIn: () => void
onMicPressOut: () => void
} | null>(null)
@@ -0,0 +1,238 @@
import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease'
import type { MobileStructuredAgentMutate } from './use-mobile-structured-agent-mutation'
import type { MobileQueuedMessageCard } from './mobile-structured-queued-message-cards'
import {
mobileQueuedEditValueKey,
sameMobileQueuedEditImage
} from './mobile-queued-message-edit-value'
import { appendBufferedDictation } from '../terminal/terminal-live-dictation-routing'
import type {
MobileNativeChatDraftInputs,
MobileNativeChatDraftDestination
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import type { AgentSessionQueuedMessage } from '../../../src/shared/agent-session-wire'
import type { AgentJournalSubmission } from '../../../src/shared/agent-session-journal-types'
import type { RpcClient } from '../transport/rpc-client'
import type { MobileQueuedEditLease } from './mobile-queued-message-edit-lease'
import { pickedSkillsInText } from '../../../src/shared/structured-agent-session-send-mutation'
import {
queuedEditKeptImages,
queuedEditTextForKeptImages
} from '../../../src/shared/queued-message-edit'
import { appendReturnedDraftText } from '../../../src/shared/returned-draft-text'
import {
closeMobileNativeChatEditInputs,
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs
} from './native-chat/composer/mobile-native-chat-draft-inputs'
import { setMobileNativeChatDraftText } from './native-chat/composer/mobile-native-chat-draft-store'
import { nativeChatTextWithFileReferences } from './native-chat/composer/mobile-native-chat-file-attachment'
export type MobileQueuedMessageInlineEditor = {
messageId: string
scopeKey: string
client: RpcClient
sessionId: string
imagesCapable: boolean
text: string
saving: boolean
canSave: boolean
insertDictation?: (text: string) => boolean
change: (text: string) => void
save: () => Promise<boolean>
removeImage: (id: string) => void
cancel: () => void
}
export type MobileQueuedEditAttempt = {
phase: 'pending' | 'unknown'
expected: string
fingerprint: string
body: AgentSessionQueuedMessage['body']
text: string
inputs: MobileNativeChatDraftInputs
key: string
}
export function mobileQueuedEditSaving(edit: MobileQueuedEditDraft): boolean {
return edit.attempt?.phase === 'pending'
}
export type MobileQueuedEditDraft = {
scope: string
client: RpcClient
sessionId: string
published: {
cards: readonly MobileQueuedMessageCard[]
messages: readonly AgentSessionQueuedMessage[] | null
submissions: readonly AgentJournalSubmission[]
}
scopeKey: string
destination: string | null
handBackText: ((text: string) => boolean) | undefined
messageId: string
body: AgentSessionQueuedMessage['body']
text: string
fingerprint: string
baseKey: string
kept: {
image: MobileNativeChatDraftInputs['images'][number]
block: ReturnType<typeof queuedEditKeptImages>[number]['block']
}[]
uncertain: boolean
leaseLoss?: QueuedEditLeaseLoss
attempt?: MobileQueuedEditAttempt
closed: boolean
pendingClose: boolean
lease: MobileQueuedEditLease
}
export function closeMobileQueuedEditDraft(
edit: MobileQueuedEditDraft,
handBack: boolean,
notice?: (text: string) => void
): void {
if (edit.closed) {
return
}
edit.closed = true
edit.lease.end()
if (handBack) {
const inputs = readMobileNativeChatDraftInputs(edit.scopeKey)
const dirty = edit.uncertain || mobileQueuedEditValueKey(edit.text, inputs) !== edit.baseKey
const kept = edit.kept.filter((entry) =>
inputs.images.some((image) => sameMobileQueuedEditImage(entry.image, image))
)
const text = dirty
? queuedEditTextForKeptImages(
edit.text,
inputs.images.map(({ id }) => id),
inputs.images
.filter((image) => !kept.some((entry) => sameMobileQueuedEditImage(entry.image, image)))
.map(({ id }) => id)
)
: ''
if (dirty && edit.destination) {
setMobileNativeChatDraftText(edit.destination, (before) =>
appendReturnedDraftText(before, text)
)
} else if (dirty) {
edit.handBackText?.(text)
}
closeMobileNativeChatEditInputs(
edit.scopeKey,
edit.destination ?? undefined,
kept.map(({ image }) => image),
!dirty
)
if (dirty) {
notice?.('Your edit is in the chat box.')
}
} else {
closeMobileNativeChatEditInputs(edit.scopeKey)
}
}
export function serializeMobileQueuedEdit(
edit: MobileQueuedEditDraft,
imagesCapable = false,
skillsCapable = false
) {
const inputs = readMobileNativeChatDraftInputs(edit.scopeKey)
return {
text: nativeChatTextWithFileReferences(
edit.text,
inputs.files.flatMap(({ path }) => (path ? [{ path }] : []))
),
...(imagesCapable
? {
images: inputs.images.map(
(image) =>
edit.kept.find((entry) => sameMobileQueuedEditImage(entry.image, image))?.block ?? {
type: 'image-ref' as const,
path: image.path
}
)
}
: {}),
...(skillsCapable ? { skills: pickedSkillsInText(edit.text, inputs.skills, ['$', '/']) } : {})
}
}
export function removeMobileQueuedEditImage(edit: MobileQueuedEditDraft, id: string): void {
const images = readMobileNativeChatDraftInputs(edit.scopeKey).images
const kept = images.filter((image) => image.id !== id)
edit.text = queuedEditTextForKeptImages(
edit.text,
images.map(({ id }) => id),
kept.map(({ id }) => id)
)
updateMobileNativeChatDraftInputs(edit.scopeKey, (current) => ({
...current,
images: kept
}))
}
export function mobileQueuedEditSaveHeld(
edit: MobileQueuedEditDraft,
imagesCapable = false
): boolean {
const inputs = readMobileNativeChatDraftInputs(edit.scopeKey)
return (
(inputs.pending ?? 0) > 0 ||
inputs.files.some(({ path }) => path === null) ||
(!imagesCapable &&
JSON.stringify(inputs.images) !== JSON.stringify(edit.kept.map(({ image }) => image)))
)
}
export function seedMobileQueuedEditInputs(
scopeKey: string,
body: AgentSessionQueuedMessage['body']
): void {
updateMobileNativeChatDraftInputs(scopeKey, () => ({
skills: body.skills ?? [],
files: [],
images: queuedEditKeptImages(body).map(({ id, block }) => ({
id,
path: block.path ?? block.url ?? '',
previewUri: block.url ?? block.path ?? ''
}))
}))
}
export function insertMobileQueuedEditDictation(
edit: MobileQueuedEditDraft,
destination: MobileNativeChatDraftDestination,
text: string
): boolean {
if (!destination.active) {
return false
}
if (destination.scope !== edit.scopeKey) {
setMobileNativeChatDraftText(destination.scope, (before) =>
appendBufferedDictation(before, text)
)
} else {
edit.text = appendBufferedDictation(edit.text, text)
}
return true
}
export type MobileStructuredQueuedEditArgs = {
sessionKey: string
sessionId: string | null
client: RpcClient | null
chatActive: boolean
enabled: boolean
imagesCapable?: boolean
skillsCapable?: boolean
composerScopeKey?: string | null
messages: readonly AgentSessionQueuedMessage[] | null
submissions?: readonly AgentJournalSubmission[]
cards: readonly MobileQueuedMessageCard[]
mutate: MobileStructuredAgentMutate
appendComposerText: ((text: string) => boolean) | undefined
onQueuedEditNotice?: (text: string) => void
onSendError: (text: string) => void
onActionResolved?: () => void
}
@@ -1,4 +1,7 @@
import { startQueuedEditLease } from '../../../src/shared/queued-message-edit-lease'
import {
startQueuedEditLease,
type QueuedEditLeaseLoss
} from '../../../src/shared/queued-message-edit-lease'
import type { RpcClient } from '../transport/rpc-client'
import { callAgentSession } from './mobile-structured-agent-session-rpc'
import { structuredSessionOperationId } from './structured-session-operation-id'
@@ -10,12 +13,14 @@ export function startMobileQueuedEditLease(args: {
sessionId: string
messageId: string
expectedBodyFingerprint: string
onLost: (loss: QueuedEditLeaseLoss) => void
}) {
return startQueuedEditLease({
sessionId: args.sessionId,
messageId: args.messageId,
editId: structuredSessionOperationId(),
expectedBodyFingerprint: args.expectedBodyFingerprint,
onLost: args.onLost,
request: (params) => {
const client = args.getClient()
return client
@@ -0,0 +1,68 @@
import type { QueuedEditLeaseLoss } from '../../../src/shared/queued-message-edit-lease'
import {
queuedMessageEditableText,
queuedEditKeptImages
} from '../../../src/shared/queued-message-edit'
import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
import { createUuidV4 } from '../../../src/shared/uuid-v4'
import { startMobileQueuedEditLease } from './mobile-queued-message-edit-lease'
import { mobileQueuedEditValueKey } from './mobile-queued-message-edit-value'
import { readMobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs'
import {
seedMobileQueuedEditInputs,
type MobileQueuedEditDraft as Edit,
type MobileStructuredQueuedEditArgs
} from './mobile-queued-message-edit-draft'
export function createMobileQueuedEdit(
args: MobileStructuredQueuedEditArgs,
messageId: string,
getClient: () => MobileStructuredQueuedEditArgs['client'],
onLost: (edit: Edit, loss: QueuedEditLeaseLoss) => void
): Edit | null {
const { enabled, client, sessionId, sessionKey } = args
if (!enabled || !client || !sessionId) {
return null
}
const message = args.messages?.find((entry) => entry.messageId === messageId)
const text = message ? queuedMessageEditableText(message.body) : null
if (!message || text === null) {
return null
}
const fingerprint = agentSessionSendBodyFingerprint(sessionId, message.body)
const scopeKey = `queued-edit:${createUuidV4()}`
seedMobileQueuedEditInputs(scopeKey, message.body)
const edit: Edit = {
scope: sessionKey,
client,
sessionId,
published: {
messages: args.messages,
submissions: args.submissions ?? [],
cards: args.cards
},
scopeKey,
destination: args.composerScopeKey ?? null,
handBackText: args.appendComposerText,
messageId,
body: message.body,
text,
fingerprint,
uncertain: false,
baseKey: mobileQueuedEditValueKey(text, readMobileNativeChatDraftInputs(scopeKey)),
kept: queuedEditKeptImages(message.body).map((entry, index) => ({
block: entry.block,
image: readMobileNativeChatDraftInputs(scopeKey).images[index]
})),
closed: false,
pendingClose: false,
lease: startMobileQueuedEditLease({
getClient,
sessionId,
messageId,
expectedBodyFingerprint: fingerprint,
onLost: (loss) => onLost(edit, loss)
})
}
return edit
}
@@ -0,0 +1,109 @@
import type { AgentSessionQueuedMessageUpdateResult } from '../../../src/shared/agent-session-wire'
import { agentSessionSendBodyFingerprint } from '../../../src/shared/structured-agent-session-send-mutation'
import type { MobileQueuedEditDraft } from './mobile-queued-message-edit-draft'
import type { StructuredAgentSessionMutationResult } from './mobile-structured-agent-session-rpc'
import { readMobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs'
import { mobileQueuedEditValueKey } from './mobile-queued-message-edit-value'
type Outcome = 'close' | 'rebase' | 'gone' | 'changed' | 'refused' | 'stay'
export function settleMobileQueuedEdit(
edit: MobileQueuedEditDraft,
attempt = edit.attempt,
result?: StructuredAgentSessionMutationResult<AgentSessionQueuedMessageUpdateResult>
): Outcome {
if (edit.closed || edit.attempt !== attempt) {
return 'stay'
}
const loss =
edit.leaseLoss?.lease === edit.lease && edit.leaseLoss.expected === edit.fingerprint
? edit.leaseLoss.status
: undefined
const lost = loss === 'changed' ? 'changed' : loss ? 'gone' : undefined
const { messages, submissions } = edit.published
const message = messages?.find((entry) => entry.messageId === edit.messageId)
const available = edit.published.cards.some((entry) => entry.messageId === edit.messageId)
const sent =
attempt &&
submissions.some(
(entry) =>
entry.queuedMessageId === edit.messageId && entry.payloadFingerprint === attempt.fingerprint
)
let proof = Boolean(
attempt &&
((message &&
agentSessionSendBodyFingerprint(edit.sessionId, message.body) === attempt.fingerprint) ||
sent)
)
if (result?.status === 'accepted') {
const status = result.value.status
if (status === 'gone' || status === 'changed') {
edit.attempt = undefined
return status
}
if (status !== 'updated' && status !== 'unchanged') {
edit.attempt = undefined
return (
lost ??
(edit.pendingClose || (messages !== null && (!message || !available)) ? 'gone' : 'refused')
)
}
proof = result.value.fingerprint === attempt?.fingerprint
if (!proof && attempt) {
attempt.phase = 'unknown'
edit.uncertain ||= attempt.fingerprint !== attempt.expected
}
} else if (result?.status === 'rejected') {
edit.attempt = undefined
return (
lost ??
(edit.pendingClose || (messages !== null && (!message || !available)) ? 'gone' : 'refused')
)
} else if (result?.status === 'unknown' && attempt) {
attempt.phase = 'unknown'
edit.uncertain ||= attempt.fingerprint !== attempt.expected
}
if (attempt && proof) {
if (edit.uncertain && attempt.fingerprint === edit.fingerprint) {
attempt.phase = 'unknown'
return lost ?? (edit.pendingClose || sent ? 'gone' : 'stay')
}
const equal =
mobileQueuedEditValueKey(edit.text, readMobileNativeChatDraftInputs(edit.scopeKey)) ===
attempt.key
const blocks = attempt.body.blocks.filter((block) => block.type === 'image-ref')
edit.kept = attempt.inputs.images.flatMap((image, index) =>
blocks[index] ? [{ image, block: blocks[index] }] : []
)
edit.body = attempt.body
edit.baseKey = attempt.key
edit.fingerprint = attempt.fingerprint
edit.uncertain = false
edit.attempt = undefined
if (equal) {
return 'close'
}
return edit.pendingClose ||
sent ||
(messages !== null && (!message || !available)) ||
loss === 'gone' ||
loss === 'not-editable'
? 'gone'
: loss === 'changed' && attempt.fingerprint === attempt.expected
? 'changed'
: 'rebase'
}
if (lost) {
return lost
}
if (edit.pendingClose || (messages !== null && (!message || !available))) {
return 'gone'
}
if (
!result &&
message &&
agentSessionSendBodyFingerprint(edit.sessionId, message.body) !== edit.fingerprint
) {
return 'changed'
}
return 'stay'
}
@@ -0,0 +1,30 @@
import type { MobileNativeChatDraftInputs } from './native-chat/composer/mobile-native-chat-draft-inputs'
import { pickedSkillsInText } from '../../../src/shared/structured-agent-session-send-mutation'
type Image = MobileNativeChatDraftInputs['images'][number]
export function sameMobileQueuedEditImage(left: Image, right: Image): boolean {
return left.id === right.id && left.path === right.path && left.previewUri === right.previewUri
}
export function mobileQueuedEditValueKey(
text: string,
inputs: MobileNativeChatDraftInputs
): string {
return JSON.stringify([
text,
pickedSkillsInText(text, inputs.skills, ['$', '/']),
inputs.images,
inputs.files,
inputs.pending ?? 0
])
}
export function snapshotMobileQueuedEditInputs(
inputs: MobileNativeChatDraftInputs
): MobileNativeChatDraftInputs {
return {
...inputs,
images: inputs.images.map((image) => ({ ...image })),
files: inputs.files.map((file) => ({ ...file })),
skills: inputs.skills.map((skill) => ({ ...skill }))
}
}
@@ -63,7 +63,9 @@ export type MobileStructuredAgentSessionArgs = {
agent: string | null
/** What the session reported for its `/` menu; undefined until read or on an older host. */
sessionCommands?: readonly AgentSessionSlashCommand[]
composerScopeKey?: string | null
appendComposerText?: (text: string) => boolean
onQueuedEditNotice?: (message: string) => void
onSendError: MobileNativeChatSendErrorReporter
// Accepted queued actions retire the route’s failure banner.
onActionResolved?: () => void
@@ -20,7 +20,10 @@ import {
AGENT_SESSION_PERMISSION_MODES_RUNTIME_CAPABILITY,
AGENT_SESSION_PERMISSION_OWN_RUNTIME_CAPABILITY
} from '../../../src/shared/agent-session-permission-modes-capability'
import { AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY } from '../../../src/shared/agent-session-runtime-capabilities'
import {
AGENT_SESSION_PHONE_ATTACHMENTS_RUNTIME_CAPABILITY,
AGENT_SESSION_QUEUED_MESSAGE_SKILLS_EDIT_RUNTIME_CAPABILITY
} from '../../../src/shared/agent-session-runtime-capabilities'
import { SKILL_DISCOVER_WORKSPACE_CAPABILITY } from '../../../src/shared/skill-install-capability'
export type StructuredAgentSessionHostSupport = {
@@ -36,6 +39,7 @@ export type StructuredAgentSessionHostSupport = {
queuedMessageReorder?: boolean
// Older hosts edit queued text only.
queuedMessageImageEdit?: boolean
queuedMessageSkillsEdit?: boolean
// Hosts predating mobile access refuse this feed even if they implement it.
statusFeed: boolean
quietRepeatedStop: boolean
@@ -63,6 +67,9 @@ export function structuredAgentSessionHostSupport(
queuedMessages: capabilities.includes(AGENT_SESSION_QUEUED_MESSAGES_RUNTIME_CAPABILITY),
queuedCommands: capabilities.includes(AGENT_SESSION_QUEUED_COMMANDS_RUNTIME_CAPABILITY),
queuedMessageEdit: capabilities.includes(AGENT_SESSION_QUEUED_MESSAGE_EDIT_RUNTIME_CAPABILITY),
queuedMessageSkillsEdit: capabilities.includes(
AGENT_SESSION_QUEUED_MESSAGE_SKILLS_EDIT_RUNTIME_CAPABILITY
),
queuedMessageReorder: capabilities.includes(
AGENT_SESSION_QUEUED_MESSAGE_REORDER_RUNTIME_CAPABILITY
),
@@ -1,3 +1,4 @@
import { stripSentImagePromptMarkers } from '../../../src/shared/native-chat-image-transcript-markers'
// The shared projection decides each card's hold; this layer words it for the phone.
import type { AgentSessionFailureFact } from '../../../src/shared/agent-session-failure'
@@ -67,7 +68,10 @@ export function mobileQueuedMessageCards(
): MobileQueuedMessageCard[] {
return projectQueuedMessageCards(queuedMessages, submissions, facts).map((card) => ({
...card,
line: queuedMessageCardLine(card),
line: queuedMessageCardLine({
...card,
text: stripSentImagePromptMarkers(card.text, card.images?.length ?? 0)
}),
needsAttention: queuedMessageCardNeedsAttention(card),
caption: queuedMessageCardCaption(card, facts.agentName, facts.statedFailures ?? []),
attribution: agentMessageAttribution('From', card.from)
@@ -1,7 +1,40 @@
import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
import {
setMobileNativeChatDraftText,
readMobileNativeChatDraftEditGeneration
} from './mobile-native-chat-draft-store'
import {
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs,
resetMobileNativeChatDraftInputsForTests
} from './mobile-native-chat-draft-inputs'
import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts'
import { useMobileStructuredNativeChatSendBridge } from '../../use-mobile-structured-native-chat-send-bridge'
import { mobileNativeChatScopeKey } from '../mobile-native-chat-scope-key'
import { useMobileStructuredAgentSession } from '../../use-mobile-structured-agent-session'
import {
CAPABLE,
SESSION_ID,
snapshotEvent,
mutationOk,
ok
} from '../../use-mobile-structured-agent-session-queued.test-fixture'
import { structuredSendResultFixture } from '../../structured-agent-send-result.test-fixture'
import { findByHostType } from '../../../test-support/react-test-renderer-host-nodes'
import type { RpcClient } from '../../../transport/rpc-client'
vi.mock('../../../platform/media-picker', () => ({
useMediaPicker: () => ({ pickImages: async () => [] })
}))
vi.mock('@react-native-async-storage/async-storage', () => ({
default: { getItem: async () => null, setItem: async () => {}, removeItem: async () => {} }
}))
import { createElement, type ComponentProps } from 'react'
import { act, create, type ReactTestRenderer } from 'react-test-renderer'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { MobileNativeChatComposer as NativeChatComposer } from './MobileNativeChatComposer'
import {
MobileNativeChatComposer as NativeChatComposer,
MobileNativeChatDraftComposer
} from './MobileNativeChatComposer'
const getNoComposerEditGeneration = () => 0
@@ -99,6 +132,219 @@ describe('MobileNativeChatComposer on a structured chat', () => {
)
const drawers = () => renderer!.root.findAll((node) => node.props.onHidden !== undefined)
it.each(['', 'See this'])(
'sends an ordinary image with %j text through the real RPC and clears its visible chip',
async (text) => {
const scope = mobileNativeChatScopeKey('host', 'worktree', `image-rpc-${text}`)!
resetMobileNativeChatDraftInputsForTests()
setMobileNativeChatDraftText(scope, text)
updateMobileNativeChatDraftInputs(scope, (input) => ({
...input,
images: [{ id: 'photo', path: '/remote/photo.png', previewUri: 'file:///phone-photo.png' }]
}))
let publish: ((data: unknown) => void) | undefined
const sendRequest = vi.fn<RpcClient['sendRequest']>(async (method) =>
method === 'agentSession.send'
? mutationOk(structuredSendResultFixture('accepted'))
: ok({ models: [], current: {} })
)
const client: RpcClient = {
sendRequest,
subscribe: (_m, _p, listener) => {
publish = listener
return () => {}
},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => null,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
function Conversation() {
const session = useMobileStructuredAgentSession({
client,
sessionId: SESSION_ID,
sourceIdentity: 'host',
enabled: true,
connected: true,
agent: 'codex',
hostSupport: { ...CAPABLE, sendSkills: true },
composerScopeKey: scope,
onSendError: vi.fn()
})
const drafts = useMobileNativeChatDrafts({
hostId: 'host',
worktreeId: 'worktree',
tabId: `image-rpc-${text}`,
sessionId: SESSION_ID,
messages: [],
transcriptSettled: true
})
const bridge = useMobileStructuredNativeChatSendBridge({
...drafts,
agent: 'codex',
sendStructured: session.sendWithOutcome,
onSendError: vi.fn()
})
const image = useMobileNativeChatImageAttachments({
client,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'connected',
scopeKey: scope,
enabled: true,
structuredNativeChat: true,
showToast: vi.fn(),
onSendError: vi.fn(),
baseSend: bridge.sendWithOutcome,
readSeededLaunchDraft: () => null
})
return draw({
value: text,
onSend: image.sendNativeChat,
attachments: image.attachments,
onRemoveAttachment: image.removeAttachment,
structured: structured()
})
}
await act(async () => {
renderer = create(createElement(Conversation))
})
act(() => publish?.(snapshotEvent()))
expect(labelled('Remove image')[0]).toBeDefined()
await act(async () => labelled('Send message')[0]!.props.onPress())
const request = sendRequest.mock.calls.find(([method]) => method === 'agentSession.send')?.[1]
expect(request).toMatchObject({
body: {
blocks: [
...(text ? [{ type: 'text', text }] : []),
{ type: 'image-ref', path: '/remote/photo.png' }
]
}
})
expect(readMobileNativeChatDraftInputs(scope).images).toEqual([])
expect(labelled('Remove image')).toEqual([])
}
)
it.each([
['codex', '$review.v2'],
['claude', '/review.v2']
] as const)(
'%s matches main capture/clear and real Send refs, and forgets a deleted pick',
async (agent, token) => {
const scope = mobileNativeChatScopeKey('host', 'worktree', 'menu')!
resetMobileNativeChatDraftInputsForTests()
setMobileNativeChatDraftText(scope, '/re')
let publish: ((data: unknown) => void) | undefined
const sendRequest = vi.fn<RpcClient['sendRequest']>(async (method) =>
method === 'agentSession.send'
? mutationOk(structuredSendResultFixture('accepted'))
: ok({ models: [], current: {} })
)
const client: RpcClient = {
sendRequest,
subscribe: (_m, _p, listener) => {
publish = listener
return () => {}
},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => null,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
function Conversation() {
const session = useMobileStructuredAgentSession({
client,
sessionId: SESSION_ID,
sourceIdentity: 'host',
enabled: true,
connected: true,
agent,
hostSupport: { ...CAPABLE, sendSkills: true },
composerScopeKey: scope,
onSendError: vi.fn()
})
const drafts = useMobileNativeChatDrafts({
hostId: 'host',
worktreeId: 'worktree',
tabId: 'menu',
sessionId: SESSION_ID,
messages: [],
transcriptSettled: true
})
const bridge = useMobileStructuredNativeChatSendBridge({
...drafts,
agent,
sendStructured: session.sendWithOutcome,
onSendError: vi.fn()
})
return createElement(MobileNativeChatDraftComposer, {
draftKey: scope,
agent,
draftScopeKey: scope,
onChangeText: drafts.setComposerText,
onSend: bridge.send,
sendSurfaceId: scope,
getSendCompletionGeneration: () => 0,
getComposerEditGeneration: () => readMobileNativeChatDraftEditGeneration(scope),
structured: structured({
catalog: {
reported: [{ name: 'review.v2', kind: 'skill', path: '/remote/review/SKILL.md' }],
conversationCommands: []
}
})
})
}
await act(async () => {
renderer = create(createElement(Conversation))
})
act(() => publish?.(snapshotEvent()))
act(() => field().props.onSelectionChange({ nativeEvent: { selection: { end: 3 } } }))
await act(async () => labelled(token)[0]!.props.onPress())
expect(field().props.value).toBe(`${token} `)
await act(async () => labelled('Send message')[0]!.props.onPress())
const request = sendRequest.mock.calls.find(([method]) => method === 'agentSession.send')?.[1]
const skills = [{ name: 'review.v2', path: '/remote/review/SKILL.md' }]
expect(request).toMatchObject({ body: { blocks: [{ type: 'text', text: token }] } })
if (agent === 'codex') {
expect(request).toHaveProperty('body.skills', skills)
} else {
expect(request).not.toHaveProperty('body.skills')
}
expect(field().props.value).toBe('')
expect(readMobileNativeChatDraftInputs(scope).skills).toEqual(skills)
act(() => field().props.onChangeText(`${token} `))
await act(async () => labelled('Send message')[0]!.props.onPress())
const second = sendRequest.mock.calls.findLast(
([method]) => method === 'agentSession.send'
)?.[1]
if (agent === 'codex') {
expect(second).toHaveProperty('body.skills', skills)
} else {
expect(second).not.toHaveProperty('body.skills')
}
// Pick again, delete, then retype: text alone cannot resurrect the old remote identity.
act(() => field().props.onChangeText('/re'))
act(() => field().props.onSelectionChange({ nativeEvent: { selection: { end: 3 } } }))
await act(async () => labelled(token)[0]!.props.onPress())
act(() => field().props.onChangeText(''))
act(() => field().props.onChangeText(`${token} `))
expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([])
await act(async () => labelled('Send message')[0]!.props.onPress())
expect(
sendRequest.mock.calls.findLast(([method]) => method === 'agentSession.send')?.[1]
).not.toHaveProperty('body.skills')
}
)
it('puts a picked skill at the start of the draft, highlighted, and deletes it as one unit', async () => {
const onChangeText = vi.fn()
const catalog = structured()
@@ -162,4 +408,29 @@ describe('MobileNativeChatComposer on a structured chat', () => {
await act(async () => labelled('Send message')[0]!.props.onPress())
expect(onSend).toHaveBeenCalledExactlyOnceWith('')
})
it('forgets inline picked skill identity after its token is removed and retyped', async () => {
const scope = 'removed-skill'
updateMobileNativeChatDraftInputs(scope, () => ({
images: [],
files: [],
skills: [{ name: 'review', path: '/remote/SKILL.md' }]
}))
await act(async () => {
renderer = create(
createElement(MobileNativeChatComposer, {
draftScopeKey: scope,
value: '$review draft',
editSession: { cancel: vi.fn(), locked: false, refuseCommand: () => false },
onChangeText: vi.fn(),
onSend: async () => false,
sendSurfaceId: scope,
getSendCompletionGeneration: getNoComposerEditGeneration
})
)
})
const input = () => findByHostType(renderer!.root, 'TextInput')
await act(async () => input().props.onChangeText('draft'))
await act(async () => input().props.onChangeText('$review draft'))
expect(readMobileNativeChatDraftInputs(scope).skills).toEqual([])
})
})
@@ -2,6 +2,10 @@ import { createElement, createRef, StrictMode, type ComponentProps, type ReactNo
import { act, create, type ReactTestInstance, type ReactTestRenderer } from 'react-test-renderer'
import { Keyboard, type TextInput } from 'react-native'
import { afterEach, describe, expect, it, vi } from 'vitest'
import {
useMobileNativeChatDraft,
setMobileNativeChatDraftText
} from './mobile-native-chat-draft-store'
import { radii, spacing } from '../../../theme/mobile-theme'
import { MobileNativeChatComposer as NativeChatComposer } from './MobileNativeChatComposer'
import {
@@ -9,6 +13,8 @@ import {
findByHostType
} from '../../../test-support/react-test-renderer-host-nodes'
import { captureMobileNativeChatTextDestination } from './mobile-native-chat-draft-inputs'
const getNoComposerEditGeneration = () => 0
function MobileNativeChatComposer({
@@ -109,6 +115,34 @@ describe('MobileNativeChatComposer', () => {
)
}
it('uses ordinary append semantics through the registered focused dictation destination', async () => {
const scope = 'dictation-ordinary'
setMobileNativeChatDraftText(scope, '/compact')
function Registered() {
const value = useMobileNativeChatDraft(scope)
return createElement(MobileNativeChatComposer, {
value,
draftScopeKey: scope,
onChangeText: (text) => setMobileNativeChatDraftText(scope, text),
onSend: async () => true,
sendSurfaceId: scope,
getSendCompletionGeneration: () => 0
})
}
await act(async () => {
renderer = create(createElement(Registered))
})
const input = () => findByHostType(renderer!.root, 'TextInput')
act(() => input().props.onFocus())
const insert = captureMobileNativeChatTextDestination()!
act(() => {
insert('hello')
insert('hello')
insert(' there ')
})
expect(input().props.value).toBe('/compact hello hello there ')
})
it('reports an accepted send without owning route-scoped draft cleanup', async () => {
const onChangeText = vi.fn()
const onSend = vi.fn().mockResolvedValue(true)
@@ -1,6 +1,18 @@
import { getNativeChatAgentProfile } from '../../../../../src/shared/native-chat-agent-profiles'
import {
recordMobileNativeChatSkillPick,
setMobileNativeChatDraftText,
useMobileNativeChatDraft
} from './mobile-native-chat-draft-store'
import { appendBufferedDictation } from '../../../terminal/terminal-live-dictation-routing'
import {
focusMobileNativeChatTextDestination,
pruneMobileNativeChatDraftSkills,
registerMobileNativeChatTextDestination
} from './mobile-native-chat-draft-inputs'
import type { NativeChatSkillDiscoverySnapshot } from '../../../../../src/shared/native-chat/input/native-chat-picker-items'
import { useEffect, useLayoutEffect, useRef, useState } from 'react'
import { ActivityIndicator, Keyboard, Pressable, type TextInput, View } from 'react-native'
import { ActivityIndicator, Keyboard, Pressable, type TextInput, Text, View } from 'react-native'
import { ArrowUp, Mic, Plus, Square } from 'lucide-react-native'
import { colors } from '../../../theme/mobile-theme'
import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
@@ -23,10 +35,6 @@ import { keepHeldPressThroughLongPress } from '../../held-press-long-press'
import { mobileNativeChatComposerShowsStop } from './mobile-native-chat-composer-layout'
import { MobileNativeChatStopButton } from '../input/MobileNativeChatStopButton'
import { mobileNativeChatComposerStyles as styles } from './mobile-native-chat-composer-styles'
import {
recordMobileNativeChatSkillPick,
useMobileNativeChatDraft
} from './mobile-native-chat-draft-store'
const NO_FILE_PATHS: string[] = []
const NO_ATTACHMENTS: PendingNativeChatImage[] = []
@@ -42,6 +50,10 @@ export type MobileNativeChatStructuredComposer = {
}
type Props = {
insertDictation?: (text: string) => boolean | void
draftScopeKey?: string | null
editSession?: { cancel: () => void; refuseCommand: (text: string) => boolean; locked: boolean }
onPickSkill?: (skill: { name: string; path: string }) => void
inputRef?: React.RefObject<TextInput | null>
// Terminal-backed chats keep curated commands and image-only attachment actions.
structured?: MobileNativeChatStructuredComposer | null
@@ -79,6 +91,10 @@ type Props = {
export function MobileNativeChatComposer({
inputRef,
draftScopeKey,
insertDictation,
editSession,
onPickSkill,
value,
onChangeText,
onSend,
@@ -106,6 +122,19 @@ export function MobileNativeChatComposer({
onNeedSkills,
stop = null
}: Props): React.JSX.Element {
useEffect(() => {
if (!draftScopeKey) {
return
}
return registerMobileNativeChatTextDestination(
draftScopeKey,
insertDictation ??
((text) =>
setMobileNativeChatDraftText(draftScopeKey, (before) =>
appendBufferedDictation(before, text)
))
)
}, [draftScopeKey, insertDictation])
useMobileColorScheme()
const fallbackInputRef = useRef<TextInput>(null)
const fieldRef = inputRef ?? fallbackInputRef
@@ -121,7 +150,26 @@ export function MobileNativeChatComposer({
const files = structured?.files ?? NO_FILES
const menu = useMobileNativeChatComposerMenu({
value,
onChangeText,
onChangeText: (text) => {
if (editSession && draftScopeKey) {
pruneMobileNativeChatDraftSkills(
draftScopeKey,
text,
getNativeChatAgentProfile(agent)?.skillPrefix ?? '/'
)
}
onChangeText(text)
},
onPickSkill: (skill) => {
if (onPickSkill && skill.path) {
onPickSkill({ name: skill.token.slice(1), path: skill.path })
}
if (!editSession) {
recordMobileNativeChatSkillPick(sendSurfaceId, skill)
}
},
refuseCommand: editSession?.refuseCommand,
editing: editSession !== undefined,
agent,
structuredCatalog: structured?.catalog,
filePaths,
@@ -129,8 +177,6 @@ export function MobileNativeChatComposer({
skillDiscovery,
onNeedSkills,
onSlashMenuOpen: structured?.onSlashMenuOpen,
// The surface id is the draft key both send paths read picks back from.
onPickSkill: (skill) => recordMobileNativeChatSkillPick(sendSurfaceId, skill),
focusField: () => fieldRef.current?.focus()
})
const sendingRef = useRef(false)
@@ -196,7 +242,9 @@ export function MobileNativeChatComposer({
menu.resetCursor()
// Why: the turn is now the agent's — the keyboard would cover the reply.
// A rejected send keeps it up so the handed-back draft stays editable.
Keyboard.dismiss()
if (!editSession) {
Keyboard.dismiss()
}
}
} finally {
sendingRef.current = false
@@ -211,22 +259,31 @@ export function MobileNativeChatComposer({
return (
<View>
{menu.rows.length > 0 ? (
<MobileNativeChatComposerMenu rows={menu.rows} onPick={menu.pick} />
<MobileNativeChatComposerMenu
rows={menu.rows}
onPick={menu.pick}
nestedScrollEnabled={editSession ? true : undefined}
/>
) : null}
<View style={styles.composerInset} testID="native-chat-composer-inset">
<View style={styles.bar} testID="native-chat-composer">
<MobileNativeChatComposerAttachments
images={attachments}
files={files}
onRemoveImage={onRemoveAttachment}
onRemoveFile={structured?.onRemoveFile}
onRemoveImage={editSession?.locked ? undefined : onRemoveAttachment}
onRemoveFile={editSession?.locked ? undefined : structured?.onRemoveFile}
/>
<MobileNativeChatComposerField
ref={fieldRef}
value={value}
skillToken={menu.skillToken}
onChangeText={menu.onFieldChange}
onFocus={() => setFocused(true)}
onFocus={() => {
setFocused(true)
if (draftScopeKey) {
focusMobileNativeChatTextDestination(draftScopeKey)
}
}}
onBlur={() => setFocused(false)}
// Controlled only transiently right after an autocomplete insert.
selection={menu.pendingSelection ?? undefined}
@@ -235,6 +292,7 @@ export function MobileNativeChatComposer({
placeholderTextColor={colors.textMuted}
selectionColor={colors.accentBlue}
multiline
editable={!editSession?.locked}
// Why: never revoke `editable` — iOS resigns first responder on a focused
// field, so a transient lock would yank the keyboard mid-typing (#10681).
// The lock gates sending; the draft survives and rides the next send.
@@ -302,12 +360,22 @@ export function MobileNativeChatComposer({
)}
</Pressable>
) : null}
{editSession ? (
<Pressable
accessibilityRole="button"
accessibilityLabel="Cancel editing"
style={styles.ghostButton}
onPress={editSession.cancel}
>
<Text style={{ color: colors.textSecondary }}>Cancel</Text>
</Pressable>
) : null}
{showsStop && stop ? (
// Only this phone's own request holds Stop: a repeat is how a stuck stop escalates.
<MobileNativeChatStopButton onStop={stop.onStop} held={stop.held} />
) : (
<Pressable
accessibilityLabel="Send message"
accessibilityLabel={editSession ? 'Save edited message' : 'Send message'}
style={({ pressed }) => [
styles.sendButton,
!canSend && styles.sendButtonDisabled,
@@ -316,11 +384,15 @@ export function MobileNativeChatComposer({
onPress={handleSend}
disabled={!canSend}
>
<ArrowUp
size={19}
color={canSend ? colors.bgBase : colors.textMuted}
strokeWidth={2.4}
/>
{editSession ? (
<Text style={{ color: canSend ? colors.bgBase : colors.textMuted }}>Save</Text>
) : (
<ArrowUp
size={19}
color={canSend ? colors.bgBase : colors.textMuted}
strokeWidth={2.4}
/>
)}
</Pressable>
)}
</View>
@@ -1,3 +1,4 @@
import { isRenderableImageUri } from '../visual/mobile-native-chat-image-preview'
import {
ActivityIndicator,
Image,
@@ -7,7 +8,7 @@ import {
Text,
View
} from 'react-native'
import { FileText, X } from 'lucide-react-native'
import { FileText, Image as ImageIcon, X } from 'lucide-react-native'
import { colors, radii, spacing } from '../../../theme/mobile-theme'
import { themedStyleSheet } from '../../../theme/themed-styles'
import { useMobileColorScheme } from '../../../theme/use-mobile-color-scheme'
@@ -49,7 +50,21 @@ export function MobileNativeChatComposerAttachments({
>
{images.map((image) => (
<View key={image.id} style={styles.thumb}>
<Image source={{ uri: image.previewUri }} style={styles.thumbImage} resizeMode="cover" />
{isRenderableImageUri(image.previewUri) ? (
<Image
source={{ uri: image.previewUri }}
style={styles.thumbImage}
resizeMode="cover"
/>
) : (
<View
style={styles.fileIcon}
accessible
accessibilityLabel={image.path.split(/[\\/]/).at(-1) || 'Attached image'}
>
<ImageIcon size={17} color={colors.textSecondary} strokeWidth={2} />
</View>
)}
{onRemoveImage ? (
<RemoveBadge label="Remove image" onPress={() => onRemoveImage(image.id)} />
) : null}
@@ -11,15 +11,21 @@ const HEADINGS = { command: 'Commands', skill: 'Skills', file: 'Files' } as cons
export function MobileNativeChatComposerMenu({
rows,
onPick
onPick,
nestedScrollEnabled
}: {
rows: readonly ComposerMenuRow[]
onPick: (row: ComposerMenuRow) => void
nestedScrollEnabled?: boolean
}): React.JSX.Element {
useMobileColorScheme()
return (
<View style={styles.card}>
<ScrollView keyboardShouldPersistTaps="always" style={styles.scroll}>
<ScrollView
keyboardShouldPersistTaps="always"
nestedScrollEnabled={nestedScrollEnabled}
style={styles.scroll}
>
{rows.map((row, index) => (
<View key={row.id}>
{rows[index - 1]?.kind !== row.kind ? (
@@ -0,0 +1,215 @@
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import { useMobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments'
import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
import {
closeMobileNativeChatEditInputs,
readMobileNativeChatDraftInputs,
resetMobileNativeChatDraftInputsForTests
} from './mobile-native-chat-draft-inputs'
import type { RpcClient } from '../../../transport/rpc-client'
import type { RpcResponse } from '../../../transport/types'
const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => picker }))
afterEach(() => resetMobileNativeChatDraftInputsForTests())
it.each(['files', 'images'] as const)(
'retires remaining %s uploads on Cancel, and follows hand-back before the first chip',
async (kind) => {
for (const cancel of [true, false]) {
let release = () => {}
let started = () => {}
const firstStarted = new Promise<void>((resolve) => {
started = resolve
})
const held = new Promise<void>((resolve) => {
release = resolve
})
const starts: string[] = []
const client: RpcClient = {
sendRequest: vi.fn(async (method: string): Promise<RpcResponse> => {
if (method.endsWith('uploadStart') || method === 'clipboard.startImageUpload') {
starts.push(method)
if (starts.length === 1) {
started()
await held
}
return {
id: 'r',
ok: true,
result: { uploadId: `upload-${starts.length}` },
_meta: { runtimeId: 'r' }
}
}
const result =
method === 'clipboard.commitImageUpload'
? `/stored/${starts.length}.png`
: method.endsWith('uploadCommit')
? {
path: `/stored/${starts.length}.png`,
name: `${starts.length}.png`,
byteLength: 1
}
: null
return { id: 'r', ok: true, result, _meta: { runtimeId: 'r' } }
}),
subscribe: () => () => {},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => null,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
picker.pickFiles.mockImplementation(async function* () {
for (const name of ['a.txt', 'b.txt']) {
yield { name, mime: 'text/plain', byteLength: 1, base64: 'YQ==' }
}
})
picker.pickImages.mockResolvedValue([
{ base64: 'YQ==', uri: 'file:///a.png' },
{ base64: 'Yg==', uri: 'file:///b.png' }
])
let attach = () => Promise.resolve()
let send = () => Promise.resolve(false)
const baseSend = vi.fn().mockResolvedValue('accepted')
function Probe() {
const file = useMobileNativeChatFileAttachments({
client,
sessionId: 's',
scopeKey: 'edit',
enabled: true,
showToast: vi.fn()
})
const image = useMobileNativeChatImageAttachments({
client,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'connected',
scopeKey: 'edit',
enabled: true,
structuredNativeChat: true,
showToast: vi.fn(),
onSendError: vi.fn(),
baseSend,
readSeededLaunchDraft: () => null
})
attach = kind === 'files' ? file.attachFiles : () => image.attachImage('library')
return null
}
let edit!: ReturnType<typeof create>
await act(async () => {
edit = create(createElement(Probe))
})
let work!: Promise<void>
await act(async () => {
work = attach()
await firstStarted
})
act(() => closeMobileNativeChatEditInputs('edit', cancel ? undefined : 'bottom'))
if (!cancel) {
// Bottom Send must consume the transferred pending obligation even before a completed image exists.
function Bottom() {
const image = useMobileNativeChatImageAttachments({
client,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'connected',
scopeKey: 'bottom',
enabled: true,
structuredNativeChat: true,
showToast: vi.fn(),
onSendError: vi.fn(),
baseSend,
readSeededLaunchDraft: () => null
})
send = () => image.sendNativeChat('bottom')
return null
}
let bottom!: ReturnType<typeof create>
await act(async () => {
bottom = create(createElement(Bottom))
})
await act(async () => expect(await send()).toBe(false))
expect(baseSend).not.toHaveBeenCalled()
act(() => bottom.unmount())
}
await act(async () => {
release()
await work
})
expect(starts).toHaveLength(cancel ? 1 : 2)
const result = readMobileNativeChatDraftInputs('bottom')
expect(result[kind]).toHaveLength(cancel ? 0 : 2)
expect(result.pending ?? 0).toBe(0)
act(() => edit.unmount())
resetMobileNativeChatDraftInputsForTests()
}
}
)
it('retains unique image identity across a real hook remount and removes only the chosen photo', async () => {
const client: RpcClient = {
sendRequest: vi.fn(async (method: string): Promise<RpcResponse> => ({
id: 'r',
ok: true,
result:
method === 'clipboard.startImageUpload'
? { uploadId: 'upload' }
: method === 'clipboard.commitImageUpload'
? '/stored/photo.png'
: null,
_meta: { runtimeId: 'r' }
})),
subscribe: () => () => {},
updateTerminalSubscriptionViewport: () => {},
getState: () => 'connected',
getReconnectAttempt: () => 0,
getLastConnectedAt: () => null,
onStateChange: () => () => {},
notifyForeground: () => {},
close: () => {}
}
picker.pickImages.mockResolvedValue([{ base64: 'YQ==', uri: 'file:///photo.png' }])
let hook!: ReturnType<typeof useMobileNativeChatImageAttachments>
function Probe() {
hook = useMobileNativeChatImageAttachments({
client,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'connected',
scopeKey: 'retained',
enabled: true,
structuredNativeChat: true,
showToast: vi.fn(),
onSendError: vi.fn(),
baseSend: vi.fn().mockResolvedValue('accepted'),
readSeededLaunchDraft: () => null
})
return null
}
let mounted!: ReturnType<typeof create>
await act(async () => {
mounted = create(createElement(Probe))
})
await act(async () => hook.attachImage('library'))
const first = hook.attachments[0]!.id
act(() => mounted.unmount())
await act(async () => {
mounted = create(createElement(Probe))
})
await act(async () => hook.attachImage('library'))
const second = hook.attachments[1]!.id
expect(second).not.toBe(first)
act(() => hook.removeAttachment(second))
expect(hook.attachments.map(({ id }) => id)).toEqual([first])
act(() => mounted.unmount())
})
@@ -0,0 +1,166 @@
import { createElement } from 'react'
import { act, create } from 'react-test-renderer'
import { afterEach, expect, it, vi } from 'vitest'
import { useMobileNativeChatFileAttachments } from './use-mobile-native-chat-file-attachments'
import { useMobileNativeChatImageAttachments } from './use-mobile-native-chat-image-attachments'
import {
useMobileNativeChatDraft,
setMobileNativeChatDraftText,
resetMobileNativeChatDraftStoreForTests
} from './mobile-native-chat-draft-store'
import {
subscribeMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs,
closeMobileNativeChatEditInputs,
useMobileNativeChatDraftInputs
} from './mobile-native-chat-draft-inputs'
const picker = vi.hoisted(() => ({ pickFiles: vi.fn(), pickImages: vi.fn() }))
vi.mock('../../../platform/media-picker', () => ({ useMediaPicker: () => picker }))
afterEach(resetMobileNativeChatDraftStoreForTests)
it.each([20, 200])(
'isolates mounted text, input, image and file consumers across %i other scopes',
async (count) => {
const scopes = [
'own-host:target',
...Array.from({ length: count }, (_, i) => `other-host:${i}`)
]
const own = scopes[0]
const renders = scopes.map(() => ({ text: 0, input: 0, image: 0, file: 0 }))
const values: {
text: string
pending: number
images: readonly string[]
files: readonly string[]
}[] = scopes.map(() => ({ text: '', pending: 0, images: [], files: [] }))
const upstream = scopes.map(() => vi.fn())
const releases = scopes.map((scope, i) =>
subscribeMobileNativeChatDraftInputs(scope, upstream[i])
)
function Text({ index }: { index: number }) {
values[index].text = useMobileNativeChatDraft(scopes[index])
renders[index].text++
return null
}
function Input({ index }: { index: number }) {
values[index].pending = useMobileNativeChatDraftInputs(scopes[index]).pending ?? 0
renders[index].input++
return null
}
function File({ index }: { index: number }) {
const file = useMobileNativeChatFileAttachments({
client: null,
sessionId: null,
scopeKey: scopes[index],
enabled: false,
showToast: vi.fn()
})
values[index].files = file.files.map((entry) => entry.path ?? '')
renders[index].file++
return null
}
function Image({ index }: { index: number }) {
const image = useMobileNativeChatImageAttachments({
client: null,
agent: 'codex',
activeHandleRef: { current: null },
deviceTokenRef: { current: null },
getActiveWorktreeConnectionId: async () => null,
connState: 'disconnected',
scopeKey: scopes[index],
enabled: false,
structuredNativeChat: true,
showToast: vi.fn(),
onSendError: vi.fn(),
baseSend: async () => 'rejected',
readSeededLaunchDraft: () => null
})
values[index].images = image.attachments.map((entry) => entry.path)
renders[index].image++
return null
}
let view: ReturnType<typeof create> | undefined
await act(async () => {
view = create(
createElement(
'fixture',
{},
scopes.flatMap((_, index) => [
createElement(Text, { key: `t${index}`, index }),
createElement(Input, { key: `p${index}`, index }),
createElement(File, { key: `f${index}`, index }),
createElement(Image, { key: `i${index}`, index })
])
)
)
})
renders.forEach((entry) => {
entry.text = entry.input = entry.image = entry.file = 0
})
try {
await act(async () => setMobileNativeChatDraftText(own, 'own text'))
expect(values[0].text).toBe('own text')
expect(renders[0]).toEqual({ text: 1, input: 0, image: 0, file: 0 })
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 1 }))
)
expect(values[0].pending).toBe(1)
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({
...current,
images: [{ id: 'image', path: '/saved.png', previewUri: 'file:///saved.png' }]
}))
)
expect(values[0].images).toEqual(['/saved.png'])
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({
...current,
files: [
{ id: 'file', path: '/saved.txt', name: 'saved.txt', mime: 'text/plain', byteLength: 1 }
]
}))
)
expect(values[0].files).toEqual(['/saved.txt'])
expect(renders[0]).toEqual({ text: 1, input: 3, image: 3, file: 3 })
expect(upstream[0]).toHaveBeenCalledTimes(3)
for (let index = 1; index < scopes.length; index++) {
expect(renders[index]).toEqual({ text: 0, input: 0, image: 0, file: 0 })
expect(upstream[index]).not.toHaveBeenCalled()
}
} finally {
await act(async () => view?.unmount())
releases.forEach((release) => release())
}
await act(async () =>
updateMobileNativeChatDraftInputs(own, (current) => ({ ...current, pending: 0 }))
)
expect(renders[0]).toEqual({ text: 1, input: 3, image: 3, file: 3 })
expect(upstream[0]).toHaveBeenCalledTimes(3)
}
)
it.each([20, 200])(
'notifies only affected scopes across %i retained input subscribers and retires listeners',
(count) => {
const idle = vi.fn()
const releases = Array.from({ length: count }, (_, index) =>
subscribeMobileNativeChatDraftInputs(`idle-${index}`, idle)
)
const source = vi.fn()
const destination = vi.fn()
releases.push(
subscribeMobileNativeChatDraftInputs('queued-edit:one', source),
subscribeMobileNativeChatDraftInputs('bottom', destination)
)
updateMobileNativeChatDraftInputs('queued-edit:one', (inputs) => ({ ...inputs, pending: 1 }))
expect(source).toHaveBeenCalledTimes(1)
expect(idle).not.toHaveBeenCalled()
closeMobileNativeChatEditInputs('queued-edit:one', 'bottom')
expect(source).toHaveBeenCalledTimes(2)
expect(destination).toHaveBeenCalledTimes(1)
expect(idle).not.toHaveBeenCalled()
releases.forEach((release) => release())
updateMobileNativeChatDraftInputs('bottom', (inputs) => ({ ...inputs, pending: 0 }))
expect(destination).toHaveBeenCalledTimes(1)
}
)
@@ -1,3 +1,4 @@
import { prepareQueuedMessageEditText } from '../../../../../src/shared/queued-message-edit-command'
import { describe, expect, it } from 'vitest'
import { deriveComposerAutocomplete } from '../../../../../src/shared/native-chat-composer-autocomplete'
import type { NativeChatSkillDiscoverySnapshot } from '../../../../../src/shared/native-chat/input/native-chat-picker-items'
@@ -13,6 +14,7 @@ import {
function mobileComposerSlashItems(input: {
agent: string
editing?: boolean
structured: MobileComposerStructuredCatalog | undefined
query: string
discovery?: NativeChatSkillDiscoverySnapshot
@@ -27,7 +29,10 @@ function mobileComposerSlashItems(input: {
catalog.profile,
catalog.discovery,
null,
catalog.sessionSkills
catalog.sessionSkills,
input.editing
? (name) => prepareQueuedMessageEditText(input.agent, input.structured?.reported)(`/${name}`)
: undefined
)
return result.mode === 'slash' ? boundedMenuItems(result.items) : []
}
@@ -176,3 +181,27 @@ describe('narrowedMenuItems', () => {
expect(narrowedMenuItems(commandsOnly, 'skill')).toEqual(commandsOnly)
})
})
it('keeps edit-valid provider commands and namesake skills without changing the ordinary catalog', () => {
const input = {
agent: 'claude',
structured: {
reported: [
{ name: 'model', kind: 'skill' as const, path: '/model/SKILL.md' },
{ name: 'review', kind: 'command' as const },
{ name: 'goal', kind: 'command' as const }
],
conversationCommands: ['clear' as const, 'compact' as const]
},
query: ''
}
const ordinary = mobileComposerSlashItems(input)
const editing = mobileComposerSlashItems({ ...input, editing: true })
expect(editing.map(({ kind, name }) => `${kind}:${name}`)).toEqual([
'command:review',
'command:goal',
'skill:model'
])
expect(ordinary.map(({ name }) => name)).toContain('compact')
expect(ordinary.map(({ kind, name }) => `${kind}:${name}`)).toContain('command:model')
})
@@ -0,0 +1,143 @@
import { useCallback, useSyncExternalStore } from 'react'
import { pickedSkillsInText } from '../../../../../src/shared/structured-agent-session-send-mutation'
import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session-journal-types'
import type { PendingNativeChatImage } from './mobile-native-chat-image-attachment'
import type { PendingNativeChatFile } from './mobile-native-chat-file-attachment'
export type MobileNativeChatDraftInputs = {
images: readonly PendingNativeChatImage[]
files: readonly PendingNativeChatFile[]
skills: readonly AgentJournalSkillRef[]
pending?: number
}
const empty: MobileNativeChatDraftInputs = { images: [], files: [], skills: [] }
const drafts = new Map<string, MobileNativeChatDraftInputs>()
const listeners = new Map<string, Set<() => void>>()
// Operations capture this object: hand-back redirects it; Cancel removes its right to publish.
export type MobileNativeChatDraftDestination = { scope: string; active: boolean }
const destinations = new Map<string, MobileNativeChatDraftDestination>()
export function mobileNativeChatDraftDestination(scope: string): MobileNativeChatDraftDestination {
let destination = destinations.get(scope)
if (!destination) {
destination = { scope, active: true }
destinations.set(scope, destination)
}
return destination
}
export function readMobileNativeChatDraftInputs(scope: string | null): MobileNativeChatDraftInputs {
return scope ? (drafts.get(scope) ?? empty) : empty
}
export function updateMobileNativeChatDraftInputs(
target: string | MobileNativeChatDraftDestination,
update: (current: MobileNativeChatDraftInputs) => MobileNativeChatDraftInputs
): void {
const destination = typeof target === 'string' ? mobileNativeChatDraftDestination(target) : target
if (!destination.active) {
return
}
drafts.set(destination.scope, update(readMobileNativeChatDraftInputs(destination.scope)))
listeners.get(destination.scope)?.forEach((listener) => listener())
}
export function subscribeMobileNativeChatDraftInputs(
scope: string | null,
listener: () => void
): () => void {
if (!scope) {
return () => {}
}
const scoped = listeners.get(scope) ?? new Set<() => void>()
listeners.set(scope, scoped)
scoped.add(listener)
return () => {
scoped.delete(listener)
if (scoped.size === 0) {
listeners.delete(scope)
}
}
}
export function useMobileNativeChatDraftInputs(scope: string | null): MobileNativeChatDraftInputs {
const subscribe = useCallback(
(listener: () => void) => subscribeMobileNativeChatDraftInputs(scope, listener),
[scope]
)
return useSyncExternalStore(subscribe, () => readMobileNativeChatDraftInputs(scope))
}
export function closeMobileNativeChatEditInputs(
scope: string,
to?: string,
kept: readonly PendingNativeChatImage[] = [],
clean = false
): void {
const destination = mobileNativeChatDraftDestination(scope)
const input = readMobileNativeChatDraftInputs(scope)
if (to) {
updateMobileNativeChatDraftInputs(to, (current) => ({
images: [
...current.images,
...input.images.filter(
(image) =>
!kept.some(
(owned) =>
owned.id === image.id &&
owned.path === image.path &&
owned.previewUri === image.previewUri
)
)
],
files: [...current.files, ...(clean ? [] : input.files)],
skills: [...current.skills, ...(clean ? [] : input.skills)],
pending: (current.pending ?? 0) + (input.pending ?? 0)
}))
destination.scope = to
} else {
destination.active = false
}
drafts.delete(scope)
destinations.delete(scope)
listeners.get(scope)?.forEach((listener) => listener())
}
const textDestinations = new Map<string, (text: string) => boolean | void>()
let focusedScope: string | null = null
export function registerMobileNativeChatTextDestination(
scope: string,
insert: (text: string) => boolean | void
): () => void {
textDestinations.set(scope, insert)
return () => {
if (textDestinations.get(scope) === insert) {
textDestinations.delete(scope)
}
}
}
export function focusMobileNativeChatTextDestination(scope: string): void {
focusedScope = scope
}
export function captureMobileNativeChatTextDestination():
| ((text: string) => boolean | void)
| undefined {
return focusedScope ? textDestinations.get(focusedScope) : undefined
}
export function resetMobileNativeChatDraftInputsForTests(): void {
drafts.clear()
destinations.clear()
textDestinations.clear()
focusedScope = null
}
export function pruneMobileNativeChatDraftSkills(
scope: string,
text: string,
sigil: '$' | '/' | readonly ('$' | '/')[] = '$'
): void {
const current = readMobileNativeChatDraftInputs(scope)
const skills = pickedSkillsInText(
text,
current.skills,
typeof sigil === 'string' ? [sigil] : sigil
)
if (skills.length !== current.skills.length) {
updateMobileNativeChatDraftInputs(scope, (current) => ({ ...current, skills }))
}
}
@@ -4,6 +4,8 @@ import { afterEach, describe, expect, it } from 'vitest'
import type { NativeChatMessage } from '../../../../../src/shared/native-chat-types'
import { useMobileNativeChatDrafts } from './use-mobile-native-chat-drafts'
import {
clearMobileNativeChatDraftForSend,
readMobileNativeChatDraftEditGeneration,
readMobileNativeChatPickedSkills,
editMobileNativeChatDraft,
readMobileNativeChatSkillOrigin,
@@ -13,6 +15,11 @@ import {
setMobileNativeChatDraftText,
useMobileNativeChatDraft
} from './mobile-native-chat-draft-store'
import {
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs,
resetMobileNativeChatDraftInputsForTests
} from './mobile-native-chat-draft-inputs'
type DraftState = ReturnType<typeof useMobileNativeChatDrafts> & { composerText: string }
@@ -23,6 +30,7 @@ describe('mobile native-chat draft store', () => {
afterEach(() => {
act(() => renderer?.unmount())
resetMobileNativeChatDraftStoreForTests()
resetMobileNativeChatDraftInputsForTests()
renderer = null
state = null
})
@@ -77,6 +85,25 @@ describe('mobile native-chat draft store', () => {
expect(currentState().composerText).toBe('ping')
})
it('keeps main picked refs across Send-clear but revokes them on a real token edit', () => {
const scope = 'sent-skills'
setMobileNativeChatDraftText(scope, '$review draft')
updateMobileNativeChatDraftInputs(scope, () => ({
images: [],
files: [],
skills: [{ name: 'review', path: '/remote/SKILL.md' }]
}))
const generation = readMobileNativeChatDraftEditGeneration(scope)
clearMobileNativeChatDraftForSend(scope, generation - 1, '$review draft')
expect(readMobileNativeChatDraftInputs(scope).skills).toHaveLength(1)
clearMobileNativeChatDraftForSend(scope, generation, '$review draft')
expect(readMobileNativeChatPickedSkills(scope)).toEqual([
{ name: 'review', path: '/remote/SKILL.md' }
])
editMobileNativeChatDraft(scope, 'different text')
expect(readMobileNativeChatPickedSkills(scope)).toEqual([])
})
it('keeps a typed draft after the chat screen unmounts and remounts', async () => {
await mount('a')
act(() => currentState().setComposerText('half-written prompt'))
@@ -1,6 +1,11 @@
import { useSyncExternalStore, type SetStateAction } from 'react'
import type { AgentJournalSkillRef } from '../../../../../src/shared/agent-session-journal-types'
import { pickedSkillsInText } from '../../../../../src/shared/structured-agent-session-send-mutation'
import {
resetMobileNativeChatDraftInputsForTests,
pruneMobileNativeChatDraftSkills,
readMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs
} from './mobile-native-chat-draft-inputs'
import type { MobileNativeChatLaunchDraftSeed } from './use-mobile-native-chat-launch-draft-seed'
// Text and its edit revision outlive the screen, including callbacks from an older mount.
@@ -8,7 +13,6 @@ import type { MobileNativeChatLaunchDraftSeed } from './use-mobile-native-chat-l
type Draft = {
text: string
editGeneration: number
skills?: AgentJournalSkillRef[]
skillOrigin?: string
}
@@ -29,9 +33,11 @@ export function recordMobileNativeChatSkillPick(
const current = drafts.get(draftKey) ?? { text: '', editGeneration: 0 }
const name = skill.token.slice(1)
// A pick replaces whatever file its token named before, like re-picking a desktop chip.
const kept = (current.skills ?? []).filter((held) => held.name !== name)
const skills = skill.path ? [...kept, { name, path: skill.path }] : kept
drafts.set(draftKey, { ...current, skillOrigin: skill.token, skills })
updateMobileNativeChatDraftInputs(draftKey, (inputs) => {
const kept = inputs.skills.filter((held) => held.name !== name)
return { ...inputs, skills: skill.path ? [...kept, { name, path: skill.path }] : kept }
})
drafts.set(draftKey, { ...current, skillOrigin: skill.token })
}
// A rejected send's restored text gets back the files it named, even if newer edits dropped them.
@@ -39,15 +45,14 @@ export function restoreMobileNativeChatPickedSkills(
draftKey: string,
skills: readonly AgentJournalSkillRef[]
): void {
const current = drafts.get(draftKey)
if (!current || skills.length === 0) {
if (!drafts.has(draftKey) || skills.length === 0) {
return
}
const paths = new Set((current.skills ?? []).map((skill) => skill.path))
drafts.set(draftKey, {
const paths = new Set(readMobileNativeChatDraftInputs(draftKey).skills.map((skill) => skill.path))
updateMobileNativeChatDraftInputs(draftKey, (current) => ({
...current,
skills: [...(current.skills ?? []), ...skills.filter((skill) => !paths.has(skill.path))]
})
skills: [...current.skills, ...skills.filter((skill) => !paths.has(skill.path))]
}))
}
export function readMobileNativeChatSkillOrigin(draftKey: string): string | null {
@@ -55,7 +60,7 @@ export function readMobileNativeChatSkillOrigin(draftKey: string): string | null
}
export function readMobileNativeChatPickedSkills(draftKey: string): AgentJournalSkillRef[] {
return drafts.get(draftKey)?.skills ?? []
return [...readMobileNativeChatDraftInputs(draftKey).skills]
}
function subscribe(listener: () => void): () => void {
@@ -73,14 +78,14 @@ function writeDraft(draftKey: string, update: SetStateAction<string>, userEdit:
return
}
// Send clears and restores are not edits, so a rejected draft keeps its picks.
const skills =
userEdit && current?.skills ? pickedSkillsInText(next, current.skills) : current?.skills
if (userEdit) {
pruneMobileNativeChatDraftSkills(draftKey, next)
}
const skillOrigin =
userEdit && current?.skillOrigin !== next.split(/\s/, 1)[0] ? undefined : current?.skillOrigin
drafts.set(draftKey, {
text: next,
editGeneration: (current?.editGeneration ?? 0) + 1,
...(skills ? { skills } : {}),
...(skillOrigin ? { skillOrigin } : {})
})
if (next === text) {
@@ -123,6 +128,7 @@ export function useMobileNativeChatDraft(draftKey: string | null): string {
}
export function resetMobileNativeChatDraftStoreForTests(): void {
resetMobileNativeChatDraftInputsForTests()
drafts.clear()
mobileNativeChatLaunchDraftSeeds.clear()
}
@@ -33,6 +33,7 @@ function nativeChatFileAttachFailureMessage(error: unknown, fileName?: string):
// Keep successfully uploaded files when a later pick/upload fails; only the failing chip is removed.
export async function uploadPickedNativeChatFiles(args: {
canContinue?: () => boolean
picked: AsyncIterable<PickedMobileFile>
upload: (file: PickedMobileFile) => Promise<AgentSessionAttachmentUploadCommitResult>
nextId: () => string
@@ -42,7 +43,13 @@ export async function uploadPickedNativeChatFiles(args: {
onError: (message: string) => void
}): Promise<void> {
try {
if (args.canContinue?.() === false) {
return
}
for await (const file of args.picked) {
if (args.canContinue?.() === false) {
break
}
const id = args.nextId()
args.onPicked({
id,
@@ -57,6 +64,9 @@ export async function uploadPickedNativeChatFiles(args: {
args.onFailed(id)
args.onError(nativeChatFileAttachFailureMessage(error, file.name))
}
if (args.canContinue?.() === false) {
break
}
}
} catch (error) {
args.onError(nativeChatFileAttachFailureMessage(error))
@@ -25,6 +25,7 @@ export function appendPendingNativeChatImages(
}
export type UploadNativeChatImagesDeps = {
readonly canContinue?: () => boolean
readonly client: MobileClipboardImageRpcSender
readonly getConnectionId: () => Promise<string | null>
readonly pickImages: (
@@ -43,6 +44,7 @@ export async function uploadMobileNativeChatImages(
source: MobileImageSource,
{
client,
canContinue,
getConnectionId,
pickImages,
onUploadStart,
@@ -52,11 +54,20 @@ export async function uploadMobileNativeChatImages(
const picked = await pickImages(source)
const uploaded: Omit<PendingNativeChatImage, 'id'>[] = []
let connectionId: string | null = null
if (canContinue?.() === false) {
return uploaded
}
for await (const image of picked) {
if (canContinue?.() === false) {
break
}
if (uploaded.length === 0) {
onUploadStart?.()
connectionId = await getConnectionId()
}
if (canContinue?.() === false) {
break
}
const path = await saveMobileClipboardImageAsTempFile(client, image.base64, { connectionId })
const previewUri = image.uri ?? `data:image/png;base64,${image.base64}`
const result = {
@@ -65,6 +76,9 @@ export async function uploadMobileNativeChatImages(
}
uploaded.push(result)
onImageUploaded?.(result)
if (canContinue?.() === false) {
break
}
}
return uploaded
}
@@ -1,3 +1,4 @@
import { prepareQueuedMessageEditText } from '../../../../../src/shared/queued-message-edit-command'
import { useEffect, useMemo, useState } from 'react'
import {
applyMentionSuggestion,
@@ -37,6 +38,8 @@ export function useMobileNativeChatComposerMenu(input: {
onSlashMenuOpen?: () => void
/** A picked skill; a send carries its file while its token stays, and treats a leading one as chat. */
onPickSkill?: (skill: { token: string; path?: string }) => void
editing?: boolean
refuseCommand?: (text: string) => boolean
focusField: () => void
}) {
const { value, onChangeText, agent, structuredCatalog, filePaths, skillDiscovery } = input
@@ -46,6 +49,15 @@ export function useMobileNativeChatComposerMenu(input: {
const [pendingSelection, setPendingSelection] = useState<Selection | null>(null)
const [menuKind, setMenuKind] = useState<MenuKind | null>(null)
const reported = structuredCatalog?.reported
const acceptsText = useMemo(
() => prepareQueuedMessageEditText(agent ?? 'codex', reported),
[agent, reported]
)
const commandAvailable = useMemo(
() => (input.editing ? (name: string) => acceptsText(`/${name}`) : undefined),
[input.editing, acceptsText]
)
const catalog = useMemo(
() =>
mobileComposerCatalog({ agent, structured: structuredCatalog, discovery: skillDiscovery }),
@@ -79,9 +91,10 @@ export function useMobileNativeChatComposerMenu(input: {
catalog.profile,
catalog.discovery,
null,
catalog.sessionSkills
catalog.sessionSkills,
commandAvailable
),
[beforeCaret, catalog]
[beforeCaret, catalog, commandAvailable]
)
const rows = useMemo<ComposerMenuRow[]>(() => {
if (autocomplete.mode === 'mention') {
@@ -127,6 +140,9 @@ export function useMobileNativeChatComposerMenu(input: {
if (autocomplete.mode === 'none') {
return
}
if (row.kind === 'command' && input.refuseCommand?.(row.token)) {
return
}
setMenuKind(null)
// Restore page field focus after a menu tap so typing continues at the inserted pick.
input.focusField()
@@ -208,3 +208,7 @@ describe('useMobileNativeChatComposerTray', () => {
expect(duplicateKeys).toEqual([])
})
})
vi.mock('../../MobileQueuedMessageComposer', () => ({
MobileQueuedMessageComposer: 'QueuedMessageComposer'
}))
@@ -1,17 +1,20 @@
import { useCallback, useRef, useState } from 'react'
import { createUuidV4 } from '../../../../../src/shared/uuid-v4'
import {
useMobileNativeChatDraftInputs,
updateMobileNativeChatDraftInputs,
mobileNativeChatDraftDestination,
type MobileNativeChatDraftDestination
} from './mobile-native-chat-draft-inputs'
import { useCallback } from 'react'
import type { RpcClient } from '../../../transport/rpc-client'
import { useMediaPicker } from '../../../platform/media-picker'
import { uploadMobileAgentSessionAttachment } from '../../mobile-agent-session-attachment-upload'
import { withScopeAttachments } from './mobile-native-chat-image-scope-state'
import {
uploadPickedNativeChatFiles,
type PendingNativeChatFile
} from './mobile-native-chat-file-attachment'
type ShowToast = (message: string, durationMs?: number) => void
type FilesByScope = Readonly<Record<string, readonly PendingNativeChatFile[]>>
const NO_FILES: readonly PendingNativeChatFile[] = []
export type MobileNativeChatFileAttachments = {
readonly files: readonly PendingNativeChatFile[]
@@ -28,17 +31,19 @@ export function useMobileNativeChatFileAttachments(args: {
showToast: ShowToast
}): MobileNativeChatFileAttachments {
const { client, sessionId, scopeKey, enabled, showToast } = args
const [filesByScope, setFilesByScope] = useState<FilesByScope>({})
const picker = useMediaPicker()
const idCounter = useRef(0)
const files = (scopeKey ? filesByScope[scopeKey] : undefined) ?? NO_FILES
const files = useMobileNativeChatDraftInputs(scopeKey).files
const updateScope = useCallback(
(
scope: string,
scope: string | MobileNativeChatDraftDestination,
next: (current: readonly PendingNativeChatFile[]) => readonly PendingNativeChatFile[]
) =>
setFilesByScope((prev) => withScopeAttachments(prev, scope, next(prev[scope] ?? NO_FILES))),
updateMobileNativeChatDraftInputs(scope, (current) => ({
...current,
files: next(current.files)
})),
[]
)
@@ -47,28 +52,43 @@ export function useMobileNativeChatFileAttachments(args: {
if (!client || !sessionId || !scope || !enabled) {
return
}
await uploadPickedNativeChatFiles({
picked: picker.pickFiles(),
upload: (file) =>
uploadMobileAgentSessionAttachment(client, {
sessionId,
name: file.name,
base64: file.base64
}),
nextId: () => {
idCounter.current += 1
return `file-${idCounter.current}`
},
onPicked: (file) => updateScope(scope, (current) => [...current, file]),
onStored: (id, stored) =>
updateScope(scope, (current) =>
current.map((file) =>
file.id === id ? { ...file, name: stored.name, path: stored.path } : file
)
),
onFailed: (id) => updateScope(scope, (current) => current.filter((file) => file.id !== id)),
onError: (message) => showToast(message)
})
const destination = mobileNativeChatDraftDestination(scope)
updateMobileNativeChatDraftInputs(destination, (current) => ({
...current,
pending: (current.pending ?? 0) + 1
}))
try {
await uploadPickedNativeChatFiles({
canContinue: () => destination.active,
picked: picker.pickFiles(),
upload: (file) =>
uploadMobileAgentSessionAttachment(client, {
sessionId,
name: file.name,
base64: file.base64
}),
nextId: createUuidV4,
onPicked: (file) => updateScope(destination, (current) => [...current, file]),
onStored: (id, stored) =>
updateScope(destination, (current) =>
current.map((file) =>
file.id === id ? { ...file, name: stored.name, path: stored.path } : file
)
),
onFailed: (id) =>
updateScope(destination, (current) => current.filter((file) => file.id !== id)),
onError: (message) => {
if (destination.active) {
showToast(message)
}
}
})
} finally {
updateMobileNativeChatDraftInputs(destination, (current) => ({
...current,
pending: Math.max(0, (current.pending ?? 0) - 1)
}))
}
}, [client, enabled, picker, scopeKey, sessionId, showToast, updateScope])
const removeFiles = useCallback(

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