diff --git a/.github/workflows/canvaslink.yml b/.github/workflows/canvaslink.yml
new file mode 100644
index 000000000..dba77a9f2
--- /dev/null
+++ b/.github/workflows/canvaslink.yml
@@ -0,0 +1,48 @@
+name: CanvasLink Android
+
+on:
+ pull_request:
+ workflow_dispatch:
+
+permissions:
+ contents: read
+
+jobs:
+ contracts:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ cache: npm
+ - run: npm ci --ignore-scripts
+ - run: npx playwright install --with-deps chromium
+ - run: npm run test:canvaslink
+ - run: npm run typecheck
+
+ android-debug:
+ runs-on: ubuntu-latest
+ timeout-minutes: 15
+ steps:
+ - uses: actions/checkout@v7
+ - uses: actions/setup-node@v7
+ with:
+ node-version: 22
+ - uses: actions/setup-java@v4
+ with:
+ distribution: temurin
+ java-version: '17'
+ - uses: android-actions/setup-android@v3
+ with:
+ packages: platform-tools
+ log-accepted-android-sdk-licenses: 'false'
+ - run: sdkmanager 'platforms;android-35' 'build-tools;35.0.0'
+ - run: node integrations/canvaslink/scripts/build-android.cjs
+ - name: Upload APK (ephemeral CI signature; official releases use the owner key)
+ uses: actions/upload-artifact@v4
+ with:
+ name: CanvasLink-Android
+ path: integrations/canvaslink/dist/CanvasLink-*.apk
+ retention-days: 30
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index be0b07f17..ca898bfa1 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -139,6 +139,22 @@ jobs:
with:
path: release-artifacts
merge-multiple: true
+ - name: Include the pinned CanvasLink installers
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ canvaslink_version="$(node -p "require('./integrations/canvaslink/package.json').version")"
+ gh release download "canvaslink-v${canvaslink_version}" --repo "${GITHUB_REPOSITORY}" \
+ --pattern '*.apk' --pattern 'canvaslink-release.json' --dir release-artifacts
+ node --input-type=module <<'JS'
+ import { createHash } from 'node:crypto';
+ import { readFileSync } from 'node:fs';
+ import { CANVASLINK_ANDROID_RELEASE as release } from './src/shared/canvasLinkInstall.ts';
+ const apk = readFileSync(`release-artifacts/CanvasLink-${release.version}.apk`);
+ if (createHash('sha256').update(apk).digest('hex') !== release.sha256) {
+ throw new Error('CanvasLink APK does not match the pinned installation checksum');
+ }
+ JS
- name: Verify release tag and artifact set
run: node scripts/verify-release-artifacts.mjs "${GITHUB_REF_NAME}" release-artifacts
- name: Create GitHub release
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 36535428a..2aabbca0f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,16 @@
[English](CHANGELOG.md) · [Русский](CHANGELOG.ru.md) · [简体中文](CHANGELOG.zh-CN.md)
+## 1.8.3
+
+- Added canvas Auto-sort by task, status, project or grid, with scoped movement and undo (#163, @BIackFIame).
+- Added animated ASCII terminal backgrounds, Fine Dots rendering, scene creation, presets and a quick-hide shortcut (#164, @CLOSETTTY).
+- Fixed native browser bounds and input coordinates at non-default renderer zoom (#165, @teo-nex).
+- Added CanvasLink 1.0 for Android: LAN window streaming, touch and terminal input, pairing and explicit revocation (#166, @teo-nex). Desktop access is off on startup.
+- Retained Codex prompt-delivery and account-scoped quota fixes already merged in #158 (@pepechka-kun).
+- Integration fixes preserve backgrounds across F8, prevent terminal glyph ghosting, keep zoomed-out cards opaque, repair background-settings scrolling, and add official reset/reload icons and button motion. CanvasLink gains LAN/VPN network selection, bounded reconnects without input replay, a CanvasTTY-style mobile shell and non-selectable controls.
+- Original contributor commits are preserved. Maintainer integration and follow-up patches are recorded separately; #159, #160, #161 and #162 are not included.
+
## 1.8.1
- Fixed the Files reader rejecting all regular files on macOS: `/dev/fd` device paths are not treated as resolved file targets, and the opened file's identity is checked against its current path before reading. The 1.8.0 build was not published.
diff --git a/CHANGELOG.ru.md b/CHANGELOG.ru.md
index 4904afd26..63f99df81 100644
--- a/CHANGELOG.ru.md
+++ b/CHANGELOG.ru.md
@@ -2,6 +2,16 @@
[English](CHANGELOG.md) · [Русский](CHANGELOG.ru.md) · [简体中文](CHANGELOG.zh-CN.md)
+## 1.8.3
+
+- Автосортировка окон по задаче, состоянию, проекту или сетке с отменой перемещения: #163, @BIackFIame.
+- Анимированные ASCII-фоны терминалов, Fine Dots, создание сцен, пресеты и быстрое скрытие: #164, @CLOSETTTY.
+- Исправление координат и размера встроенного браузера при изменении масштаба интерфейса: #165, @teo-nex.
+- CanvasLink 1.0 для Android: изображение окна по локальной сети, касания, ввод в терминал, сопряжение и отзыв доступа: #166, @teo-nex. После запуска доступ выключен.
+- Сохранены уже принятые исправления отправки заданий Codex и устаревших данных лимитов: #158, @pepechka-kun.
+- Наши патчи исправляют восстановление фонов после F8, наложение символов, прозрачность отдалённых карточек и прокрутку настроек; добавляют SVG-иконки и анимации кнопок. Для CanvasLink улучшены выбор локальной сети при VPN, ограниченное ожидание подключения без повторения ввода и мобильный интерфейс в стиле CanvasTTY.
+- Исходные коммиты участников сохранены; интеграционные правки выделены отдельно. #159, #160, #161 и #162 не включены.
+
## 1.8.1
- Исправлен запрет чтения обычных файлов на macOS: пути устройств `/dev/fd` больше не считаются адресами самих файлов; перед чтением проверяется идентичность открытого файла и текущего пути. Сборка 1.8.0 не была опубликована.
diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md
index fda65adbf..d74f5ac09 100644
--- a/CHANGELOG.zh-CN.md
+++ b/CHANGELOG.zh-CN.md
@@ -2,6 +2,16 @@
[English](CHANGELOG.md) · [Русский](CHANGELOG.ru.md) · [简体中文](CHANGELOG.zh-CN.md)
+## 1.8.3
+
+- 新增按任务、状态、项目或网格自动排列窗口,并可撤销移动(#163,@BIackFIame)。
+- 新增 ASCII 动态终端背景、Fine Dots、场景创建、预设和快速隐藏快捷键(#164,@CLOSETTTY)。
+- 修复界面缩放后内置浏览器的大小与输入坐标(#165,@teo-nex)。
+- 新增 Android CanvasLink 1.0,支持局域网窗口画面、触控、终端输入、配对与撤销授权(#166,@teo-nex)。桌面端每次启动时默认关闭访问。
+- 保留 #158 中已合并的 Codex 提示发送与账户额度修复(@pepechka-kun)。
+- 集成修复包括 F8 背景恢复、字符残影、缩小卡片的不透明背景、设置滚动、官方 SVG 图标和按钮动效。CanvasLink 增加 VPN 环境下的局域网选择、连接超时和不重放输入的恢复机制,以及 CanvasTTY 风格的移动界面。
+- 保留原作者提交,维护者集成修复单独记录;不包含 #159、#160、#161 或 #162。
+
## 1.8.1
- 修复 macOS 拒绝读取所有普通文件的问题:不再将 `/dev/fd` 设备路径当作文件实际路径,读取前核对已打开文件与当前路径的身份。1.8.0 构建未发布。
diff --git a/README.md b/README.md
index 5efdb8790..873eeadd3 100644
--- a/README.md
+++ b/README.md
@@ -69,6 +69,10 @@ npm run dev
The opt-in **Settings → Controls → Even G2** integration adapts CanvasTTY's terminal and AI-agent workflows to Even G2 glasses. Pair with six digits on the same local network, approve access on the computer, then read responses on the glasses HUD, dictate through local Nemotron speech recognition, and create, rename or close shared sessions. The companion includes a More agents picker and supports the desktop's provider list. Its source lives in `integrations/even-g2` and builds with the desktop. See [setup, distribution status and acceptance limits](docs/even-g2.md); a compatible public installer and Even Hub approval are still pending.
+## CanvasLink 1.0 for Android
+
+**Settings → CanvasLink** streams the current CanvasTTY window to an Android phone or tablet on the same LAN, with touch, direct terminal keyboard input and a shortcut bar. Access starts off; pairing uses a short-lived six-digit code. The desktop host is integrated, with no separate application. See [setup, APK builds and platform limits](docs/canvaslink.md). Original CanvasLink implementation: @teo-nex (#166). The integrated LAN/VPN path has a Linux/Android user trial; final cross-platform device acceptance remains limited.
+
## Web companion
The opt-in [Web companion](docs/mobile-companion.md) shares selected sessions with Android, iOS, and desktop browsers through **Tailscale Serve HTTPS**, not Funnel. CanvasTTY binds its companion endpoint to `127.0.0.1:3481` in this mode; pair with a short-lived code and approve each browser on the desktop. Open **Settings → Controls → Web companion** for setup, grants, and revocation. End-to-end Tailscale Serve deployment on Windows, Linux, and macOS remains unverified.
diff --git a/docs/README.md b/docs/README.md
index 3e0c19d1d..5a4c007bb 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -12,6 +12,7 @@ CanvasTTY is a spatial Electron desktop for real local terminals and AI-agent CL
| [Built-in browser and audit log](browser.md) | Canvas controls, settings, agent access, website/file boundaries, activity, and persistent redacted audit files |
| [File browser and reader](files.md) | Opening a Files card, session and folder roots, supported content, read limits, quick open, persistence, and read-only security boundaries |
| [Web companion](mobile-companion.md) | Tailscale Serve HTTPS setup, browser pairing, session grants, revocation, and security limits |
+| [CanvasLink for Android (alpha)](canvaslink.md) | Full-window LAN streaming, touch/keyboard input, APK build, security boundaries and platform limits |
| [Installing, releases, and local data](installing-and-security.md) | Installer formats, unsigned-preview caveats, credential boundaries, and release checks |
| [Widget authoring](widget-authoring.md) | Source-level extension paths, visual grammar, process boundaries, and an AI-agent brief |
| [Pixel terminal themes (Russian)](pixel-skin-packs.ru.md) | Ten-PNG ZIP layout, terminal apertures, app import, and local agent CLI |
diff --git a/docs/UI_CONTRACT.md b/docs/UI_CONTRACT.md
index 7acaf490d..94e865c2d 100644
--- a/docs/UI_CONTRACT.md
+++ b/docs/UI_CONTRACT.md
@@ -64,6 +64,7 @@ This contract preserves the approved MVP concept and prevents feature ownership
- The Files viewer renders Markdown (`.md`, `.markdown`, `.mdown`, `.mkd`) as formatted GitHub-Flavored Markdown with fenced code blocks syntax-highlighted, and syntax-highlights recognized code files by the language detected from their extension while unknown languages stay plain monospaced text. All rendered output is sanitized: raw HTML and scripts never render and event-handler attributes and dangerous link schemes such as `javascript:` are neutralized. Activating an `http(s)` link opens it in the built-in browser while other schemes are inert, only embedded `data:` images render while remote or relative sources fall back to alt text or a placeholder without a network request, and text or code above the rich-rendering size threshold falls back to plain text with a notice.
- An authenticated connection or heartbeat alone never shows agent presence. A branded badge appears only after that agent actually issues a browser command, and its cursor appears only after a real pointer position exists. Claude uses `#D97757`, Codex `#10A37F`, Qwen `#6D44E8`, Kimi `#7C5CFC`, OpenCode `#5A5858`, Hermes `#D6A700`, and an unknown provider `#7A8291`. Browser Settings separately controls indicator visibility without revoking browser access; the agent-access kill switch revokes the connection itself.
- With window snapping enabled, drag and resize use a hidden `10px` grid and a `10px` magnetic threshold for neighboring edges, centers, and a consistent `20px` gap.
+- The empty-canvas context menu also lists Files and a **Tools** submenu between Browser and Settings. **Tools** holds a single **Auto-sort** action whose criteria (by task, i.e. subagents to the right of the session that spawned them; by status; by project folder; grid) are radio rows in that submenu; there is no separate layouts surface, toolbar, or saved preset. Auto-sort moves the windows of the current multi-selection when it holds at least two, or else every terminal, plugin, and Browser window that is not completely inside a region (companion mascots move only when selected); sticky notes, materials, and Files cards never move. The sorted block keeps the snapping grid and `20px` gap when snapping is on, and shifts right or down until it is clear of HOME, regions, notes, materials, Files cards, and windows it does not move. The moved windows show the existing selection outline for a few seconds or until the next press; it is presentation-only and does not select them. They glide into place unless reduced motion is requested, and **Undo auto-sort** stays in the same submenu while any of them is still where the sort put it. Undo restores only those untouched windows; there is no global undo shortcut, so terminal and text inputs keep their keys. The criterion is remembered only for the running session.
- One trusted context dispatcher owns right-clicks on the canvas. Truly empty canvas offers region creation, a sticky note, the Settings-configured launcher submenu, Browser, and Settings. Holding RMB on empty canvas also opens the configurable radial quick launcher: moving toward an action and releasing activates it, while a stationary right-click continues to open the standard empty-canvas menu. Region and note right-clicks remain context-specific. A region offers rename, color, a note at the pressed point, and region-only deletion. A note frame offers edit, bring-to-front, and deletion. Terminal, Browser, plugin, textarea/input, and contenteditable surfaces keep their native context menus; middle-button panning is unchanged. `Cmd/Ctrl+K` opens a searchable palette over live sessions and the same global creation/launch actions. Regions persist independently of terminal restore, render behind HOME and windows, resize from every edge/corner, and move every terminal, plugin, Browser, or note whose complete bounds were inside the region at drag start. Attached contents follow the region continuously during the gesture and persist once at pointer release; deleting a region never deletes its contents. Sticky notes persist bounded text and geometry, snap like other windows, and resize from every edge/corner. General Settings exposes independent **Save colored regions after exit** and **Save notes after exit** controls. Both default on to preserve existing profiles. Turning either off removes only that collection from disk persistence without deleting its live canvas objects; turning it back on saves the current collection, while leaving it off starts the next launch with that collection empty.
- Context menus, region editors, the radial launcher, and the command palette use official Lucide/provider assets and shared application color tokens. Their dimensions follow root `--ui-scale`. Appearance owns the `0.85–1.25` scale in `0.05` steps and the sage/lilac/night system palette; the scale changes UI chrome rather than canvas zoom or terminal font size. Agents owns the independent context-menu and radial-launcher subsets and their safe reset defaults.
- Settings uses the approved two-pane modal grammar: a persistent icon-labelled sidebar for all seven sections, a separate current-section header, and a scrollable content pane. Settings must not fall back to the legacy light slide-over with one horizontal segmented tab strip. Simple settings use compact copy/control rows; all Settings chrome reads the active system tokens, official Lucide assets, and root `--ui-scale`.
diff --git a/docs/UI_CONTRACT.ru.md b/docs/UI_CONTRACT.ru.md
index 33926a2da..28339d575 100644
--- a/docs/UI_CONTRACT.ru.md
+++ b/docs/UI_CONTRACT.ru.md
@@ -58,6 +58,7 @@
- Drag по пустому canvas всегда выполняет pan. В свежем профиле обычный scroll над пустым canvas перемещает его по обеим осям, а pinch и `Cmd/Ctrl + scroll` масштабируют вокруг указателя. **Зум обычным скроллом** возвращает исторический wheel zoom и автоматически включается при миграции существующего профиля. Только focused input-виджет прерывает canvas wheel/pinch; над unfocused или нефокусируемым виджетом события остаются канвасу. **Перехват wheel/pinch над виджетами** имеет режимы Off, On и Key: Off сохраняет владение focused-виджета, On постоянно передаёт канвасу только wheel/pinch, а Key делает это при удержании комбинации. Поэтому focused live Browser page прокручивается обычным scroll в Off или при отпущенном Key; unfocused Browser, On, активный Key binding, полный override, pinch и `Cmd/Ctrl + scroll` принадлежат канвасу. Выбранный в начале Browser wheel-sequence владелец сохраняется до 250 мс без wheel-событий. Browser summary и placeholder всегда принадлежат канвасу. Свежий профиль использует Key с `Command` на macOS или `Ctrl` на остальных платформах. Отдельный **Перехват навигации канвасом** (по умолчанию `Option` на macOS и `Alt` на остальных платформах) передаёт wheel/pinch и drag; одиночный Command/Ctrl разрешён. При удержании полного override все canvas-поверхности показывают `grab`, а начатый pan — `grabbing` до pointer up/cancel даже после отпускания комбинации.
- Мини-карта центрирует камеру по нажатию без изменения масштаба. В Controls выбирается **Клик** (по умолчанию, движение указателя игнорируется) или **Перетаскивание** (мини-карта захватывает указатель и непрерывно двигает камеру); клавиши-стрелки работают в обоих режимах.
- Canvas двигается RTS-style, пока указатель находится в пределах `56px` от viewport edge над пустым canvas; скорость линейно возрастает до `900px/s` на самой границе. Edge panning выключен по умолчанию и включается в Settings. Motion останавливается над interactive surfaces и во время drag-pan.
+- Контекстное меню пустого канваса содержит подменю **Инструменты** с одним действием **Автосортировка**. Критерии (по задачам — субагенты справа от запустившей их сессии; по статусу; по папке проекта; сеткой) — пункты-переключатели в том же подменю, без отдельной панели, тулбара или сохранённых раскладок. Сортируются окна текущего множественного выделения, если их хотя бы два, а иначе — все окна терминалов, плагинов и браузера, которые не лежат целиком внутри региона (маскоты — только если выделены); заметки, материалы и карточки Files не двигаются. При включённой привязке блок держит сетку и зазор `20px`, и сдвигается вправо или вниз, пока не перестанет задевать HOME, регионы, заметки, материалы, карточки Files и неперемещаемые окна. Перемещённые окна на несколько секунд (или до следующего нажатия) получают обычную обводку выделения — только визуально, без выделения — и плавно переезжают, если не включено уменьшение движения. Пункт **Отменить автосортировку** остаётся в подменю, пока хотя бы одно окно стоит там, куда его поставила сортировка, и возвращает только нетронутые окна. Глобального сочетания отмены нет: клавиши остаются у терминалов и полей ввода. Выбранный критерий помнится только до перезапуска.
- Dialog close actions остаются внутри своей header/control row с одинаковым inset и не перекрывают field, outline или panel boundary.
## Приёмочные проверки
diff --git a/docs/UI_CONTRACT.zh-CN.md b/docs/UI_CONTRACT.zh-CN.md
index 9baea3f06..99618b3e3 100644
--- a/docs/UI_CONTRACT.zh-CN.md
+++ b/docs/UI_CONTRACT.zh-CN.md
@@ -57,6 +57,7 @@
- Window snapping 开启时,drag/resize 使用隐藏 `10px` grid、相邻 edge/center 的 `10px` magnetic threshold,以及一致的 `20px` gap。
- 在空白 canvas 上 drag 始终执行 pan。新配置中,空白 canvas 上的普通 scroll 会沿两个轴移动,pinch 与 `Cmd/Ctrl + scroll` 会以指针为中心缩放。**Use scroll wheel to zoom** 恢复历史 wheel zoom,并在迁移现有配置时自动启用。只有 focused input widget 会中断 canvas wheel/pinch;在 unfocused 或不可聚焦 widget 上,事件仍归 canvas。**Wheel/pinch capture over widgets** 有 Off、On、Key 三种模式:Off 保留 focused-widget ownership,On 始终只交给 canvas,Key 仅在按住绑定键时交给 canvas。因此,focused live Browser page 在 Off 或 Key 未按下时会由普通 scroll 原生滚动;unfocused Browser、On、激活的 Key binding、完整 override、pinch 与 `Cmd/Ctrl + scroll` 都归 canvas。Browser wheel sequence 开始时选定的 owner 会保持到 250 ms 没有 wheel event。Browser summary 与 placeholder 始终归 canvas。新配置默认使用 Key,在 macOS 为 `Command`,其他平台为 `Ctrl`。独立的 **Canvas navigation override**(macOS 默认 `Option`,其他平台默认 `Alt`)接管 wheel/pinch 与 drag,也允许单独 Command/Ctrl。按住完整 override 时所有 canvas surface 显示 `grab`;已开始的 pan 会显示 `grabbing`,并由 canvas 持有到 pointer up/cancel。
- 指针停在空白 canvas 的 viewport edge `56px` 范围内时,canvas 以 RTS 风格 edge-pan;速度线性增加,到边缘达到 `900px/s`。Edge panning 默认关闭,在 Settings 启用。指针位于 interactive surface 或正在 drag-pan 时暂停。
+- 空白画布的右键菜单包含 **Tools** 子菜单,其中只有一个 **Auto-sort** 操作。排序条件(按任务:子代理放在启动它的会话右侧;按状态;按项目文件夹;网格)是同一子菜单中的单选行,不提供单独的面板、工具栏或保存的布局。当前多选中至少有两个窗口时,Auto-sort 只移动这些窗口;否则,移动所有未完全位于区域内的终端、插件与 Browser 窗口(吉祥物仅在被选中时移动);便签、素材与 Files 卡片从不移动。开启吸附时排列保持 10px 网格与 `20px` 间距,并向右或向下移动,直到不再覆盖 HOME、区域、便签、素材、Files 卡片和未参与排序的窗口。被移动的窗口在几秒内(或直到下一次按下)显示现有的选中轮廓,这只是视觉提示,不会选中它们;在未要求减少动态效果时平滑移动。只要仍有窗口停在排序放置的位置,**Undo auto-sort** 就保留在同一子菜单中,并且只恢复这些未被改动的窗口。没有全局撤销快捷键,终端与文本输入保留自己的按键。所选条件只在本次运行期间记住。
- Dialog close action 留在自己的 header/control row 内,使用一致 inset,不覆盖 field、outline 或 panel boundary。
## 验收检查
diff --git a/docs/canvaslink-security-audit-2026-10-26.md b/docs/canvaslink-security-audit-2026-10-26.md
new file mode 100644
index 000000000..1fee75ffe
--- /dev/null
+++ b/docs/canvaslink-security-audit-2026-10-26.md
@@ -0,0 +1,101 @@
+# CanvasLink: bounded security and failure-path audit
+
+Reviewed on 2026-10-26, starting at `f643b31c476e490904437c95c13f0db33ad7c310`.
+This report covers the embedded host, Android transport/direct-input assets,
+pairing/channel implementation, IPC ownership and installation contract. It is
+not a penetration-test certification or acceptance of an installed release.
+
+## Confirmed findings and fixes
+
+Severity below is a local assessment of the demonstrated behavior, not a CVSS score.
+
+| Finding | Preconditions and impact | Fix and regression evidence |
+| --- | --- | --- |
+| Medium: session expiry did not revoke an established video peer | An already paired client could stop polling and keep receiving video after the advertised 12-hour session lifetime. Request/input checks rejected expired credentials, but no passive expiry path stopped media. This did not bypass the PIN. | `Pairing.expire()` removes credentials before invoking revocation; requests and outgoing signals invoke it, and the host invokes it every 200 ms independently of client traffic and UI health polling. Tests cover the exact expiry boundary, one-time revocation, silent clients and rejected expired requests/queues. Timer delivery still depends on the Electron main event loop. |
+| Medium: revocation waited for an asynchronous UI refresh | A stalled or rejected settings-state read delayed or prevented closing a live peer after a valid revoke event. | The capture worker closes tracks, peer and input ownership synchronously before refreshing its UI. A deferred/rejected refresh test proves media and control stop first. |
+| Low: delayed signalling could undo client suspension/disconnect | In-flight offers could create a new peer while hidden or locally disconnected. A delayed native pairing callback could also re-arm the client after explicit disconnect. These were stale messages from an existing authenticated connection, not unauthenticated remote pairing. | Ignore offers/disconnect signals unless paired and visible; ignore pairing completions after explicit disconnect until a new connect request. Tests cover unpaired, hidden and disconnected clients, delayed pairing completion and negotiation completion after disconnect. |
+| Reliability: stale SDP failure overwrote current connection state | Failure of a superseded offer could mark a healthy new connection as failed. | Peer generations and checks after asynchronous SDP steps isolate stale completion/errors. |
+| Reliability: buffered pointer motion survived session close | A queued animation-frame callback could submit old pointer movement to the next connection. | Close discards buffered movement and cancels its frame callback. No clicks, text or keys are replayed. |
+| Input safety: one-shot Ctrl leaked through other commits | A Unicode/multi-character IME commit or native key could leave Ctrl armed, turning the next letter into an unexpected shortcut such as Ctrl+C. | Consume Ctrl on each committed text/key event. Browser fixture covers Cyrillic, emoji, multi-character text and native arrow input. |
+
+Before fixes, the new regressions failed in seven cases in the first targeted
+run and two further cases in the revocation-focused run. These were application
+failures. A separate HTTP fixture initially lacked Node's `Buffer` global; that
+test-harness error was corrected and is not an application finding.
+
+## Boundaries exercised
+
+- Real SRP mutual authentication and AES-GCM request/response code, using
+ synthetic keys and messages. Wrong PIN, used/expired code, attempt limits,
+ wrong address, tampering, reflection and replay are rejected.
+- The actual HTTP request handler, driven by in-memory Node request streams:
+ public source addresses, browser origins (including `null`), unsupported
+ routes/methods, non-JSON content types, invalid JSON and oversized bodies are
+ rejected. An authenticated signal reaches the renderer once; a forged,
+ replayed, unsupported or revoked signal does not.
+- IPC owner/main-frame checks and serialized settings operations, including a
+ window closing while a command waits. Capture is scoped to the owned window;
+ no global input injector or shell execution was added.
+- Android navigation/resource allowlists, disabled file/content access, denied
+ WebView media permissions and encrypted app-private session storage were
+ inspected. Those native boundaries were not penetration-tested on hardware.
+- Installation remains pinned to the published APK hash/certificate and stops
+ on signing conflicts. No private signing files or pairing credentials were
+ copied into the source tree or report.
+
+## Verification of this patch
+
+- **115/115 CanvasLink tests passed**, no skips; 12 tests added to the previous 103.
+- **3/3 desktop installation-prompt tests passed**.
+- TypeScript checks, production desktop bundles and the source/built-output
+ secret audit passed.
+- The Android development APK compiled with SDK 35 / JDK 17; apksigner verified
+ its v2/v3 signatures. This is a local development artifact, not a release APK.
+- Tests use simulated WebRTC/Electron objects and browser fixtures; HTTP tests
+ do not open a network listener. They prove the demonstrated control flow,
+ not real GPU capture or physical input on Windows/Linux/Android.
+
+The installed desktop/tablet and public `0.3.0-alpha.1` APK were not replaced.
+The client-side fixes require a subsequent APK build/release; desktop fixes
+require a CanvasTTY build containing this patch. No new release is claimed.
+
+## Open dependency issues
+
+Fresh `npm audit --package-lock-only --json` reports **6 vulnerable packages:
+5 high, 1 moderate**, matching an audit of the unchanged upstream baseline
+`0fa6895d3675b40ec4dc75886826dd2db234c234` with its own manifest/lockfile.
+The package names are Electron, Vite, undici, zod, source-map-js and fast-uri.
+An installed-tree audit reports 18 affected packages including dependent parent
+packages; this is a different audit tree/count, not 12 newly introduced root
+advisories. CanvasLink's bonjour/SRP dependencies are not listed by these audits.
+
+`npm audit --omit=dev` reports zero, but that **does not establish runtime safety**:
+Electron is declared as a development dependency and is shipped in the desktop.
+Its pinned version here is 43.7.7. The maintainer's
+[Electron advisory](https://github.com/electron/electron/security/advisories/GHSA-jr5w-w6x2-84p9)
+describes compromised intermediate TLS certificates; 43.8.1 contains the fix
+for this release line. Exploitation requires intercepted TLS traffic and a
+relevant certificate. This audit did not demonstrate exploitation in CanvasTTY.
+Vite's
+[file-serving advisory](https://github.com/vitejs/vite/security/advisories/GHSA-rq7h-c2jc-7f22)
+requires an exposed development server and additional path/import conditions;
+it is not evidence that CanvasLink's separate JSON listener serves files.
+
+Dependency updates and their desktop/native packaging validation remain open;
+this patch does not silently change the upstream Electron/build toolchain.
+
+## Remaining acceptance and review gaps
+
+- Physical source-port acceptance on macOS, Windows, Linux and Android remains
+ pending. Prior prototype acceptance is not acceptance of this patch or APK.
+- Native Android logout clears persisted credentials only after its queued
+ network revoke attempt. Abrupt process death during an offline logout and
+ pairing/restore cancellation need a native lifecycle regression and follow-up;
+ the JavaScript disconnect guard does not prove durable native logout.
+- No independent cryptographic review of the SRP implementation or WebRTC stack
+ was performed. Passing protocol tests is not such a review.
+- A paired device controls the entire owned CanvasTTY window, including its
+ terminals and settings. Pairing is a broad trust grant, not terminal sandboxing.
+ LAN/source-address checks do not protect against a compromised paired device.
+- No claim of denial-of-service resistance under adversarial LAN load,
+ dependency remediation, zero vulnerabilities or release readiness is made.
diff --git a/docs/canvaslink-verification.md b/docs/canvaslink-verification.md
new file mode 100644
index 000000000..660dcdbed
--- /dev/null
+++ b/docs/canvaslink-verification.md
@@ -0,0 +1,99 @@
+# CanvasLink alpha: verification scope
+
+Follow-up: [2026-10-26 security/failure-path audit](canvaslink-security-audit-2026-10-26.md)
+records six fixed findings, 115 passing integration tests, dependency issues and
+the remaining native/runtime acceptance gaps. The older counts below describe
+the earlier source-port and distribution snapshots.
+
+The source port is based on upstream commit
+`0fa6895d3675b40ec4dc75886826dd2db234c234` (package version 1.8.1).
+It does not replace the user's installed CanvasTTY 1.8.2 or its active preview.
+
+## Prior prototype acceptance
+
+The user manually exercised the macOS/Android prototype and confirmed it worked
+before publication preparation. Its installed APK SHA-256 was
+`48b967d7102c8e733666a630562b420e5bee5ac3bc734ad065d7a89ffd038783`.
+Prior bounded device checks covered real terminal input/ACKs, Settings touch,
+native selects, resume, Wi-Fi and high-density capture on Android 12.
+This is prototype evidence, not device acceptance of this source-port package.
+
+## Source-port checks
+
+- General upstream suite in an isolated source snapshot with a clean environment:
+ 2,221 passed, 27 skipped, zero failures. No Go toolchain was present; native-helper
+ parity/release coverage is not claimed.
+- 103 CanvasLink tests passed: pairing/authentication/replay rejection, input
+ ordering and uncertainty, reconnect races, direct-input/gesture fixtures,
+ select/touch behavior, graphics bounds, icons and IPC/lifecycle ownership.
+- TypeScript node and renderer checks passed.
+- Production desktop bundles built with the integrated settings section,
+ preload API and copied host assets.
+- Android 0.3.0-alpha.1 debug APK built; apksigner verified v2/v3 signatures.
+ Instrumentation entry points are excluded from the normal APK.
+- Even G2: 47 tests passed; its access and pairing implementation is unchanged.
+- Source and built-output secret audit passed.
+- npm audit found six advisories (five high, one moderate). An audit of the
+ unchanged upstream lockfile reports the same six dependency names; no
+ dependency-security remediation is claimed by this feature port.
+
+The general upstream suite initially exposed a path-handling bug in existing
+hook tests when the checkout path contains spaces (URL `.pathname` retains
+`%20`). The affected hook tests passed through a temporary path without spaces
+using Node's `--preserve-symlinks` and `--preserve-symlinks-main`. The final full
+run used a real source copy without spaces and removed inherited agent-capability
+environment variables. This port does not change unrelated hook handling.
+
+The Android HTML/CSS/JS/font assets are byte-identical to the accepted prototype.
+The new normal APK omits instrumentation and carries the alpha version:
+SHA-256 `509e44e12d0be251db6ed323e03035a0e2d16897c519a439679e8533ff5934fb`.
+It has not replaced the installed APK.
+
+A macOS directory package reached ASAR creation; inspection found the host assets,
+bonjour-service and secure-remote-password and no acceptance instrumentation.
+Final ad-hoc signing failed with a local “internal error in Code Signing
+subsystem”. No signing certificate/keychain access was requested. This is not a
+successfully signed distributable. The standalone hidden Electron smoke also
+failed to start to completion in this environment (timeout with no script output),
+including an attempt from a disposable unprotected directory. Its runtime result
+is **unverified**; the installed prototype remains the only user-accepted runtime.
+
+## Required release acceptance
+
+Real packaged-build acceptance for this source port remains pending. CI and
+synthetic fixtures do not prove GPU capture, Android IME, TalkBack, rotation,
+host firewalls or real device input on Windows/Linux. Official desktop release
+signing, store distribution and a 30 FPS guarantee are outside this alpha.
+
+The `CanvasLink alpha` workflow runs the contracts and builds a downloadable
+development APK. Its CI signature is ephemeral; it is not an update channel.
+Run `node scripts/smoke-canvaslink.mjs` after the desktop build to exercise real
+Electron preload/IPC and host enable/revoke/disable against a disposable hidden
+fixture. It does not send input to user terminals or provide video acceptance.
+
+## Community APK distribution and onboarding (2026-10-26)
+
+- [CanvasLink](https://github.com/teo-nex/CanvasLink) is a separate public
+ distribution repository; application source remains in this PR.
+- Version `0.3.0-alpha.1` is the APK from successful CI run `40235936427`, source
+ commit `eba7baf1f3db716b6600a605f1fda07c39e9119f`, re-signed locally with a
+ persistent distribution key. All ZIP entries outside `META-INF` match the CI
+ input byte for byte. Normal APKs contain no acceptance instrumentation.
+- Distribution APK SHA-256:
+ `0534857896b2e22d7e832a8aaa6146b3fc6acb19f3df857cc9d3e8c1caf5a760`.
+ Public signing certificate SHA-256:
+ `0235b1aee591e4f0e24e59484927ead112889521a1b92e40959076d03635b3cb`.
+ The private key and password remain outside both repositories.
+- Settings can copy a bilingual, pinned installation prompt and open the guide.
+ Copying does not enable the host, mutate pairing, install an APK or expose the
+ pairing code/device name. Three handler tests cover both locales and clipboard
+ failure; all passed. They use the repository's React test stand-in, not a live
+ desktop clipboard or physical Android device.
+- The 103 integration tests, TypeScript checks, production build and source/built
+ output secret audit passed again after the settings change.
+- The agent prompt selects one ADB device, verifies the APK hash, preserves app
+ data and stops on signature/downgrade conflicts. USB debugging and the initial
+ Android RSA confirmation belong to the device owner.
+- Earlier debug signatures may conflict with the new distribution signature.
+ No APK was installed on the accepted tablet and no installed desktop was replaced.
+ Publication is distinct from physical acceptance of this exact APK/desktop port.
diff --git a/docs/canvaslink.md b/docs/canvaslink.md
new file mode 100644
index 000000000..f3c95e638
--- /dev/null
+++ b/docs/canvaslink.md
@@ -0,0 +1,169 @@
+# CanvasLink 1.0 for Android
+
+CanvasLink streams the **whole current CanvasTTY window** to an Android phone or
+tablet on the same private IPv4 LAN. Touch, terminal keyboard input and shortcuts
+are delivered to that window. This includes Settings and any sensitive content
+visible in it. Enable access only for a device you trust.
+
+The host lives in **Settings → CanvasLink**. There is no separate desktop app to
+install. It starts **off** on every desktop launch. The existing Web companion
+and Even G2 integration retain their separate pairing and permissions.
+
+## Connect
+
+1. Install [CanvasLink 1.0](https://github.com/howdeploy/CanvasTTY/releases/tag/canvaslink-v1.0.0)
+ (Android 8+). **Settings → CanvasLink → Copy prompt for agent** copies USB/ADB
+ installation instructions with the exact APK URL and checksum. Enable USB
+ debugging and approve the RSA dialog on Android yourself. The agent installs
+ on one selected device and preserves data; it must stop on signing conflicts.
+ Use CanvasTTY 1.8.3 or newer. For an existing **CanvasLink DEV** installation,
+ choose `CanvasLink-1.0.0-dev.apk`; it preserves the DEV package ID and key.
+ Older alpha APKs can have incompatible signatures: stop on a signing conflict
+ and keep existing data. The DEV package can be installed alongside the alpha.
+2. Open Settings → CanvasLink on the desktop and choose **Enable access**.
+3. Open CanvasLink on Android, select the discovered computer and enter the six
+ digits shown on the desktop. The code expires after two minutes and is used
+ once. If discovery is blocked, the Android connection screen has a manual
+ private IPv4 address option. Both devices must be on the same non-isolated LAN.
+4. Tap a terminal to open the Android keyboard. Text goes directly into the
+ focused terminal; Enter executes it. The shortcut bar includes paste and
+ interrupt. Zoom/pan can bring a terminal into view.
+5. **Forget device** revokes its session and generates a new code. **Turn off
+ access** closes the listener, discovery, video and input. A desktop restart
+ requires fresh pairing. Sessions expire after twelve hours and are bound to
+ the client's address; a changed address can require pairing again.
+
+The app distinguishes processed, pending and uncertain input. A disconnect does
+not automatically replay a command. Check the terminal before retrying uncertain
+input. Clipboard paste uses the Android clipboard; it does not read the desktop
+clipboard.
+
+## Local networks and VPNs
+
+Android selects a non-VPN Wi-Fi or Ethernet network with a route to the private
+computer address. A sole local network's IPv4 gateway can also reach neighbouring
+private subnets. HTTP signalling uses that network explicitly without a proxy;
+there is no cellular fallback. Android 13+ also restricts discovery to these
+networks; older versions retain system discovery and the manual address option.
+Process binding requests the local network for new WebView sockets, but WebRTC
+routing in the device's WebView must be verified on hardware. Changing networks
+closes the old input channel and retries signalling without replaying input.
+A changed client address may still require fresh pairing because sessions
+remain address-bound.
+
+On Linux, desktop discovery selects physical network interfaces, including
+bridges/VLANs linked to them. Other platforms filter common virtual adapter
+names; macOS retains native DNS-SD publication. Bonjour advertisements are sent
+on each selected LAN IPv4 interface and contain only its address. Multiple LAN
+addresses may appear as separate computer entries. If discovery is unavailable,
+use **Computer not found?** on Android and enter the computer's LAN IPv4 and port,
+for example `192.168.0.171:3499`.
+
+Pairing success does not mean video/control is connected. A connection attempt
+has a 30-second deadline; **Check connection** starts another attempt. Host capture
+or negotiation errors are reported to the phone instead of leaving it waiting.
+
+VPNs must permit local traffic, including mDNS and WebRTC traffic in addition to
+TCP 3499. A VPN kill switch or Android's **Block connections without VPN** can
+prevent direct LAN access; CanvasLink does not change those settings. Enable the
+VPN's local-network allowance or exclude CanvasLink where the VPN supports it.
+These changes do not establish compatibility with every VPN or WebView version.
+
+## Mobile interface
+
+The Android shell follows CanvasTTY's Sage tokens: graphite panels, sage actions,
+flat surfaces and short labels. Pairing is a compact form. During a session, only
+the terminal key row reserves space; connection state and diagnostics live in the
+session menu. Errors and delivery uncertainty remain visible when relevant.
+Button labels are not selectable. Pairing fields and diagnostic text still
+support selection; terminal gestures and native IME keep their own input path.
+
+## Transport and boundaries
+
+- Host listener: private IPv4 clients on TCP 3499; mDNS `_canvaslink._tcp` discovery.
+ Do not expose or forward this port to the Internet. Networks may require an
+ inbound firewall allowance. No firewall rule or startup service is installed.
+- No cloud service, STUN or TURN. Pairing uses SRP-6a; the code is not sent as
+ plaintext. Signalling uses AES-256-GCM with authenticated sequence numbers;
+ WebRTC media/data use DTLS-SRTP/SCTP encryption. The HTTP endpoint is not HTTPS;
+ the application protocol supplies the encryption.
+- Pairing attempts and request sizes are bounded. A code authorizes the **whole
+ window**, not a selected-session grant. Treat the Android device as a keyboard
+ and pointer with the same authority as the person at that window.
+- Electron capture is restricted to CanvasTTY's own main frame; input uses its
+ `webContents`, never OS-wide keyboard or pointer injection. This integrated
+ path does not require Accessibility control of other applications.
+- A hidden isolated renderer handles media. Its IPC and the settings IPC reject
+ other renderers and child frames. Private test sockets, startup automation,
+ instrumentation entry points and global input helpers are not shipped.
+
+## Build
+
+From the repository root:
+
+```sh
+npm ci
+npx playwright install chromium
+npm run test:canvaslink
+npm run typecheck
+npm run build
+```
+
+For the APK, install JDK 17 and Android SDK platform 35/build-tools 35.0.0, set
+`JAVA_HOME` and `ANDROID_SDK_ROOT` (or `ANDROID_HOME`), then run:
+
+```sh
+npm run build:canvaslink:android
+```
+
+For a separate **CanvasLink DEV** installation that preserves an existing app,
+run `npm run build:canvaslink:android -- --dev`. This produces
+`integrations/canvaslink/dist/CanvasLink-1.0.0-dev.apk` with package ID
+`io.nexcore.canvaslink.dev`. Use the DEV app when testing modified source.
+
+Output: `integrations/canvaslink/dist/CanvasLink-1.0.0.apk` (or
+`CanvasLink-1.0.0-dev.apk` with `--dev`). No Gradle or Android
+Java dependencies are downloaded by the build script. A local development key
+is generated under the ignored `.runtime` directory. CI produces an APK artifact
+with an ephemeral development signature. Different builds can have different
+keys and may not install as an update over one another. Keep your existing app
+and its data until you have planned the transition.
+
+The original CanvasLink implementation and alpha distribution are by @teo-nex:
+[#166](https://github.com/howdeploy/CanvasTTY/pull/166) and the
+[community distribution repository](https://github.com/teo-nex/CanvasLink).
+CanvasLink 1.0 is distributed with this project using an owner-held persistent
+key. Its URL, checksum and public certificate fingerprint are pinned in
+`src/shared/canvasLinkInstall.ts`. The private key is never committed. CI APKs
+retain ephemeral signatures and are separate from the pinned release APK.
+
+Maintainer follow-ups add LAN/VPN routing, bounded negotiation and recovery,
+the CanvasTTY mobile shell, and versioned normal/DEV APKs. Original contributor
+commits are retained in the integration history.
+
+## Quality and platform status
+
+The prototype was physically tested on macOS with an Android 12 tablet and
+accepted by its user before this source port. That acceptance applies to the
+prototype APK/preview, not automatically to a newly packaged desktop or APK.
+See [the port verification record](canvaslink-verification.md).
+
+Windows and Linux have not received physical device acceptance. Their shared
+Electron path and JavaScript discovery implementation are candidates for testing,
+not a verified compatibility promise. CI tests contracts and builds an APK; it
+cannot establish real IME, GPU capture, firewall or touch behavior on those hosts.
+
+Capture first tries the owned renderer stream and falls back to bounded raw
+snapshots (up to 2560×1600). The prototype's observed fallback was around 3–6 FPS;
+30 FPS is not promised. High density can improve text clarity at a cost in CPU
+and bandwidth. Normal desktop density is unchanged. For an isolated developer
+run, `--force-device-scale-factor=2` supplies density at process start, or
+`--canvaslink-high-density` requests one relaunch with that switch. Never enable
+this while preserving an active terminal session without planning the restart.
+
+Before promotion beyond alpha: test a packaged build with a physical Android
+device on macOS, Windows and Linux; include discovery, pairing/revocation,
+Settings touch, native selects, IME composition, Ctrl+C/paste, Unicode, rotation,
+background/resume, network loss, minimized/closed windows and capture quality.
+
+Краткая инструкция по-русски: [canvaslink.ru.md](canvaslink.ru.md).
diff --git a/docs/canvaslink.ru.md b/docs/canvaslink.ru.md
new file mode 100644
index 000000000..264e6d030
--- /dev/null
+++ b/docs/canvaslink.ru.md
@@ -0,0 +1,67 @@
+# CanvasLink 1.0: Android по локальной сети
+
+Экспериментальная интеграция: планшет показывает **всё текущее окно CanvasTTY**
+и управляет им. Доступ включает терминалы, настройки и видимые секреты.
+Подключайте только своё доверенное устройство.
+
+1. Установите [CanvasLink 1.0 на Android 8+](https://github.com/howdeploy/CanvasTTY/releases/tag/canvaslink-v1.0.0).
+ В **Настройки → CanvasLink** есть кнопка **«Скопировать промпт агенту»**:
+ она копирует инструкцию по USB/ADB с точной ссылкой и SHA-256 APK.
+ Владелец включает USB-отладку и подтверждает RSA-запрос на Android;
+ агент устанавливает приложение на выбранное устройство с сохранением данных.
+ Нужна CanvasTTY 1.8.3 или новее. Для обновления существующего **CanvasLink DEV**
+ выберите `CanvasLink-1.0.0-dev.apk`: сохраняются идентификатор приложения и ключ.
+ При конфликте подписи старой alpha остановитесь, не удаляя данные;
+ DEV-приложение можно установить рядом с ней.
+2. На компьютере откройте **Настройки → CanvasLink → Включить доступ**.
+3. Откройте CanvasLink на планшете, выберите найденный компьютер и введите код.
+ Оба устройства должны быть в одной локальной сети без изоляции клиентов.
+ Ручной адрес нужен только при недоступном обнаружении.
+4. Коснитесь терминала: появится клавиатура. Ввод передаётся напрямую;
+ Enter выполняет команду. В панели есть вставка и прерывание.
+5. «Забыть устройство» отзывает сессию. «Выключить доступ» останавливает сеть,
+ видео и управление. При новом запуске компьютера доступ выключен.
+
+Одноразовый код действует две минуты. Сессия — до двенадцати часов; смена адреса
+может потребовать нового подключения. При обрыве команды не повторяются
+автоматически: сначала проверьте терминал. Вставка берёт буфер Android.
+
+При включённом VPN Android выбирает локальную сеть Wi-Fi/Ethernet с маршрутом
+к адресу ПК; HTTP использует её напрямую без прокси и без перехода на мобильную
+сеть. На Android 13+ поиск также ограничен этими сетями; на старых версиях
+сохранены системный поиск и ручной адрес. На Linux обнаружение ПК привязано
+к физическим LAN-интерфейсам. Если компьютер не найден, раскройте
+**«Компьютер не находится?»** на телефоне и введите его локальный IPv4 с портом,
+например `192.168.0.171:3499`.
+
+Сопряжение и соединение видео/управления — разные этапы. Ожидание подключения
+ограничено 30 секундами; кнопка **«Проверить связь»** запускает новую попытку.
+При смене сети старый канал ввода закрывается; команды не воспроизводятся.
+Маршрутизацию WebRTC внутри WebView нужно отдельно проверить на устройстве.
+
+VPN должен разрешать локальные подключения: одного TCP-порта 3499 недостаточно
+для обнаружения и WebRTC. Kill switch и системное **«Блокировать соединения без
+VPN»** могут запрещать прямую связь. CanvasLink не меняет эти настройки:
+разрешите локальную сеть или добавьте приложение в исключения, если VPN это
+поддерживает. Совместимость со всеми VPN и версиями WebView не гарантирована.
+
+Отдельное приложение на компьютере не требуется. Очки Even G2 и Web companion
+сохраняют свои отдельные коды и разрешения. Порт 3499 не открывайте в Интернет.
+
+Исходная версия проверялась пользователем на Mac с планшетом Android 12;
+интеграционная LAN/VPN-версия получила положительный отзыв на Linux с Android.
+Это отдельные пользовательские проверки; полная проверка всех платформ
+ещё не завершена, плавность 30 FPS не обещается.
+Отладочные APK разных сборок могут иметь разные подписи и не устанавливаться
+поверх друг друга. Рабочую установленную версию сохраняйте до проверки новой.
+
+Исходная реализация CanvasLink — вклад @teo-nex в #166; предыдущая alpha
+доступна в его репозитории [CanvasLink](https://github.com/teo-nex/CanvasLink).
+Версия 1.0 публикуется здесь с постоянной подписью владельца проекта.
+URL, SHA-256 и отпечаток сертификата закреплены в `src/shared/canvasLinkInstall.ts`.
+Наши дополнения: LAN/VPN-маршрутизация, ограниченное ожидание подключения,
+восстановление без повторения ввода, мобильная оболочка и сборки normal/DEV.
+Исходные коммиты автора сохранены. Приватный ключ в Git не включается.
+При несовместимой подписи агент останавливается: удаление приложения и данных не выполняется.
+
+Команды сборки, устройство защиты и границы проверки: [canvaslink.md](canvaslink.md).
diff --git a/docs/getting-started.md b/docs/getting-started.md
index 73e52dca7..c57f3b4f8 100644
--- a/docs/getting-started.md
+++ b/docs/getting-started.md
@@ -33,6 +33,14 @@ npm run dev
Launch modes are **Auto** (the default), **Manual**, **Accept edits**, **Plan** and **Bypass**, each offered only where that CLI supports it; the protection layers around them are described in [Installing and security](installing-and-security.md#agent-protection-layers). **Bypass** (YOLO) disables provider safety prompts where the provider supports such a mode, still inside base protection and agent isolation. For OpenCode, CanvasTTY applies a launch-only inline `permission: "allow"` override while preserving the rest of the merged OpenCode configuration. Hermes receives its native `--yolo` flag, while Grok Build receives its native `--always-approve` flag for that launch. CanvasTTY asks you to acknowledge it once per CLI and never gives it to a subagent; use it only in a directory you are willing to let the agent modify.
+## Animated terminal backgrounds
+
+Choose a background in **Settings → Appearance → Terminal backgrounds**. To see the animation in OpenCode, you must select its system theme: enter `/theme` inside OpenCode and choose **system**. It uses the terminal's default background; regular OpenCode themes paint their own opaque background over the animation. See [OpenCode themes](https://docs.opencode.ai/docs/themes/).
+
+For other TUI agents that paint their own screen background, choose the equivalent system-theme, terminal-default-background or transparency mode, where supported. This is needed to show the animated background, not to run the agent normally in CanvasTTY. Individual TUI panels, input fields and selections may retain their own backgrounds.
+
+**Terminal backgrounds → Adjust → Text readability** adds a dark backdrop behind text. If it looks like dark strips over the animation, reduce **Darkness behind text** or turn readability off to compare. Clipped or missing parts of the glyphs themselves are not an expected effect.
+
## Terminal input and controls
- Press any live terminal card to select and focus it. Input focus is independent from selection, so future multi-selection can keep one unambiguous keyboard and wheel target.
diff --git a/docs/getting-started.ru.md b/docs/getting-started.ru.md
index 64d15927d..0627105a3 100644
--- a/docs/getting-started.ru.md
+++ b/docs/getting-started.ru.md
@@ -33,6 +33,14 @@ npm run dev
Режимы запуска — **Авто** (по умолчанию), **Вручную**, **Правки**, **План** и **Обход**; каждый предлагается только там, где его поддерживает CLI. Слои защиты вокруг них описаны в разделе [Установка и безопасность](installing-and-security.ru.md#слои-защиты-агентов). **Обход** (YOLO) отключает защитные запросы провайдера там, где провайдер такой режим поддерживает, и всё равно остаётся внутри базовой защиты и изоляции агентов. Для OpenCode CanvasTTY добавляет только на время запуска inline override `permission: "allow"`, сохраняя остальную объединённую конфигурацию OpenCode. Hermes получает штатный `--yolo`, а Grok Build — штатный `--always-approve` только для этого запуска. CanvasTTY просит подтвердить его один раз для каждого CLI и никогда не передаёт субагенту; используйте его только в каталоге, который вы готовы отдать агенту на изменение.
+## Анимированные фоны терминалов
+
+Фон выбирается в **Настройки → Оформление → Фоны терминалов**. Чтобы анимация была видна в OpenCode, обязательно выберите внутри него системную тему: введите `/theme` и выберите **system**. Эта тема использует стандартный фон терминала; обычные темы OpenCode рисуют собственную непрозрачную заливку поверх анимации. Подробнее: [темы OpenCode](https://docs.opencode.ai/docs/themes/).
+
+Для других TUI-агентов, которые заливают экран своим цветом, выберите аналогичный режим системной темы, стандартного фона терминала или прозрачности, если он поддерживается. Это условие отображения анимированного фона, а не требование для обычного запуска агента в CanvasTTY. Собственная заливка отдельных панелей, поля ввода и выделений TUI может сохраняться.
+
+Параметр **Фоны терминалов → Настройка → Читаемость текста** добавляет затемнение под текстом. Если оно выглядит как тёмные полоски на анимации, уменьшите **Затемнение под текстом** или выключите читаемость, чтобы сравнить. Обрезанные или пропавшие части самих символов не являются ожидаемым эффектом.
+
## Ввод и управление терминалом
- Нажмите на любую живую карточку терминала, чтобы выбрать и сфокусировать её. Input focus не зависит от selection, поэтому будущий multi-selection сохранит одну однозначную цель для keyboard и wheel.
diff --git a/docs/getting-started.zh-CN.md b/docs/getting-started.zh-CN.md
index 5f5ccdf9b..ac7545c6a 100644
--- a/docs/getting-started.zh-CN.md
+++ b/docs/getting-started.zh-CN.md
@@ -33,6 +33,14 @@ npm run dev
启动模式有 **Auto**(默认)、**Manual**、**Accept edits**、**Plan** 与 **Bypass**,只在对应 CLI 支持时提供;它们外面的防护层见[安装与安全](installing-and-security.zh-CN.md#智能体防护层)。在服务商支持的情况下,**Bypass**(YOLO)会关闭其安全确认提示,但仍处于基础防护与智能体隔离之内。对于 OpenCode,CanvasTTY 只在本次启动中添加 inline `permission: "allow"` override,并保留其余合并后的 OpenCode 配置;Hermes 接收原生 `--yolo`,Grok Build 接收原生 `--always-approve`,且都只作用于本次启动。CanvasTTY 会要求你为每个 CLI 确认一次,且不会交给子智能体;只在你愿意让智能体改动的目录中使用它。
+## 终端动画背景
+
+在 **Settings → Appearance → Terminal backgrounds** 中选择背景。要在 OpenCode 中显示动画,必须选择其系统主题:在 OpenCode 中输入 `/theme` 并选择 **system**。该主题使用终端默认背景;普通 OpenCode 主题会在动画上绘制自己的不透明背景。参见 [OpenCode 主题文档](https://docs.opencode.ai/docs/themes/)。
+
+对于会自行填充屏幕背景的其他 TUI 智能体,请在支持的情况下选择对应的系统主题、终端默认背景或透明模式。这是显示动画背景的条件,并非在 CanvasTTY 中正常运行智能体的要求。TUI 的面板、输入框和选中区域仍可能保留各自的背景。
+
+**Terminal backgrounds → Adjust → Text readability** 会在文字后面添加暗色衬底。如果动画上出现暗色条带,可降低 **Darkness behind text**,或关闭可读性选项进行比较。字符本身被截断或缺失并非预期效果。
+
## 终端输入与控制
- 点击任意实时终端卡片即可选中并聚焦它。Input focus 与 selection 相互独立,因此未来加入 multi-selection 后仍能保持唯一明确的 keyboard 与 wheel 目标。
diff --git a/electron-builder.yml b/electron-builder.yml
index ab72403ef..78076ed60 100644
--- a/electron-builder.yml
+++ b/electron-builder.yml
@@ -73,6 +73,8 @@ electronFuses:
enableNodeCliInspectArguments: false
enableEmbeddedAsarIntegrityValidation: true
extraResources:
+ - from: node_modules/ascii.rest/LICENSE
+ to: licenses/ascii-rest.txt
- from: assets/mascot-pipeline
to: mascot-pipeline
filter:
diff --git a/electron.vite.config.ts b/electron.vite.config.ts
index eefc35363..8b058fb9c 100644
--- a/electron.vite.config.ts
+++ b/electron.vite.config.ts
@@ -1,4 +1,5 @@
import { resolve } from "node:path";
+import { cpSync, mkdirSync } from "node:fs";
import react from "@vitejs/plugin-react";
import { defineConfig, externalizeDepsPlugin } from "electron-vite";
@@ -11,7 +12,14 @@ export default defineConfig({
|| ""
)
},
- plugins: [externalizeDepsPlugin()],
+ plugins: [externalizeDepsPlugin(), {
+ name: "canvaslink-host-assets",
+ closeBundle() {
+ const destination = resolve("out/main/canvaslink/host");
+ mkdirSync(destination, { recursive: true });
+ cpSync(resolve("integrations/canvaslink/host"), destination, { recursive: true });
+ }
+ }],
build: {
rollupOptions: {
input: resolve("src/main/index.ts")
@@ -37,6 +45,7 @@ export default defineConfig({
renderer: {
root: resolve("src/renderer"),
plugins: [react()],
+ worker: { format: "es" },
// electron-vite leaves every bundle unminified; the renderer's (React, xterm and the app, about 1.8 MB)
// is parsed on every window load, so it is minified. Source maps stay off, as before.
build: {
diff --git a/integrations/canvaslink/.gitignore b/integrations/canvaslink/.gitignore
new file mode 100644
index 000000000..172582f4f
--- /dev/null
+++ b/integrations/canvaslink/.gitignore
@@ -0,0 +1,7 @@
+node_modules/
+build/
+dist/
+.runtime/
+*.log
+verification/*.png
+verification/icon-previews.json
diff --git a/integrations/canvaslink/LICENSE b/integrations/canvaslink/LICENSE
new file mode 100644
index 000000000..d57e4c69a
--- /dev/null
+++ b/integrations/canvaslink/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 CanvasLink contributors
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/integrations/canvaslink/THIRD_PARTY_NOTICES.md b/integrations/canvaslink/THIRD_PARTY_NOTICES.md
new file mode 100644
index 000000000..68d498468
--- /dev/null
+++ b/integrations/canvaslink/THIRD_PARTY_NOTICES.md
@@ -0,0 +1,24 @@
+# Dependencies
+
+- Electron 43.7.7 — MIT; Chromium and other bundled notices remain inside the
+ Electron distribution (`LICENSE`, `LICENSES.chromium.html`).
+- bonjour-service 1.3.0 — MIT.
+- secure-remote-password 0.3.1 — MIT.
+
+Transitive dependency licenses remain in their installed package directories.
+The CanvasTTY desktop bundle retains production dependency licenses and Electron's
+original bundled notices. Android uses platform APIs and contains no embedded
+third-party Java libraries. No RustDesk or spacedesk source or binaries are used.
+
+## Onest
+
+Bundled Android UI font, from google/fonts/ofl/onest (Onest Project Authors).
+SIL Open Font License 1.1; full license: `android/assets/onest-OFL.txt`.
+Source: https://github.com/google/fonts/tree/main/ofl/onest
+
+## Lucide icons
+
+Android inline SVG symbols reuse official Lucide geometry from CanvasTTY's
+`src/renderer/src/assets/icons/lucide`. Keyboard, corner-down-left and delete were
+retrieved from https://github.com/lucide-icons/lucide/tree/main/icons on 2026-10-26.
+ISC / MIT notices are bundled as `android/assets/lucide-LICENSE.txt`.
diff --git a/integrations/canvaslink/android/AndroidManifest.xml b/integrations/canvaslink/android/AndroidManifest.xml
new file mode 100644
index 000000000..8f2b77a32
--- /dev/null
+++ b/integrations/canvaslink/android/AndroidManifest.xml
@@ -0,0 +1,13 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/integrations/canvaslink/android/assets/client.js b/integrations/canvaslink/android/assets/client.js
new file mode 100644
index 000000000..0a62c1bf5
--- /dev/null
+++ b/integrations/canvaslink/android/assets/client.js
@@ -0,0 +1,50 @@
+(()=>{
+ 'use strict';
+ const $=id=>document.getElementById(id),api=window.CanvasLinkClient,input=window.CanvasLinkInput;
+ let state=api.getState(),selected='',signature='',lastPointer=null,touchTimer,noticeTimer;
+ const put=(id,value)=>{if($(id)&&$(id).textContent!==value)$(id).textContent=value;};
+ const errors={'delivery-uncertain':'Доставка не подтверждена. Проверьте терминал. Ввод остановлен, повтора не будет.','input-busy':'Канал занят. Ввод остановлен. Коснитесь терминала, чтобы продолжить.','not-connected':'Связь прервана. Ввод остановлен.','text-target-required':'Коснитесь терминала или текстового поля.','invalid-code':'Введите шесть цифр из Настройки → CanvasLink.','input-rejected':'Компьютер отклонил ввод.','lan-connection-timeout':'Сопряжение выполнено, но канал видео и управления не подключился за 30 секунд. Проверьте общую локальную сеть и доступ к ней в настройках VPN, затем повторите подключение.','lan-network-unavailable':'Локальная сеть недоступна. Подключитесь к Wi-Fi или Ethernet.','host-connection-failed':'Компьютеру не удалось подготовить передачу окна. Проверьте CanvasTTY и повторите подключение.','ice-timeout':'Не удалось подготовить прямое соединение. Проверьте доступ к локальной сети в настройках VPN и повторите подключение.'};
+ function notice(value){put('input-status',errors[value]||value);$('input-status').hidden=!value;clearTimeout(noticeTimer);if(value)noticeTimer=setTimeout(()=>{$('input-status').hidden=true;},7000);}
+ function updateConnect(){const busy=['connecting','pairing','resuming'].includes(state.connection);$('connect').disabled=busy||!/^\d{6}$/.test($('pin').value)||(!selected&&!($('manual').open&&$('address').value.trim()));$('connect').querySelector('span').textContent=busy?'Подключаем…':'Подключиться';}
+ function renderComputers(s){
+ const list=s.computers||[];if(!list.some(c=>c.id===selected))selected=list.length===1?list[0].id:'';
+ const next=JSON.stringify(list.map(c=>[c.id,c.name]));
+ if(next!==signature){signature=next;$('computers').replaceChildren();for(const c of list){const button=document.createElement('button');button.type='button';button.dataset.computerId=c.id;button.className='computer';const name=document.createElement('span');name.textContent=String(c.name||'CanvasTTY').replace(/^CanvasLink\s+/,'');button.append($('computer-icon').content.cloneNode(true),name,$('computer-check').content.cloneNode(true));button.onclick=()=>{selected=c.id;renderComputers(state);updateConnect();};$('computers').append(button);}}
+ for(const b of $('computers').querySelectorAll('button'))b.setAttribute('aria-pressed',String(b.dataset.computerId===selected));
+ $('pair-status').hidden=!!list.length;put('pair-status',s.discovery==='searching'?'Ищем компьютер в вашей Wi-Fi сети…':'Включите CanvasLink в настройках CanvasTTY на компьютере.');
+ }
+ function render(s){
+ state=s;const show=s.connection==='connected'||['connecting','reconnecting','suspended'].includes(s.connection)||(!['idle','error'].includes(s.connection)&&!$('workspace').hidden);
+ $('workspace').hidden=!show;$('pairing').hidden=show;document.body.classList.toggle('is-workspace',show);renderComputers(s);updateConnect();
+ const labels={connected:'Подключено',connecting:'Подключаем…',pairing:'Проверяем код…',resuming:'Восстанавливаем…',reconnecting:'Нет связи',suspended:'На паузе'};
+ put('connection-status',labels[s.connection]||'Нет связи');$('connection-pill').dataset.state=s.connection;
+ for(const button of $('controls').querySelectorAll('button'))if(button.id!=='menu-toggle')button.disabled=s.connection!=='connected';
+ const stats=s.stats||{};
+ const wait=s.connection!=='connected'||!stats.framesDecoded; // A static frame remains usable; do not cover it with an opaque waiting card.
+ $('waiting').hidden=!wait;$('resume').hidden=!['reconnecting','suspended'].includes(s.connection);
+ put('waiting-title',s.connection==='suspended'?'Соединение на паузе':s.connection==='reconnecting'?'Восстанавливаем связь':'Открываем CanvasTTY');
+ put('waiting-copy',s.connection==='reconnecting'?'Ввод остановлен. Ничего не отправляем повторно.':s.connection==='connecting'?'Сопряжение выполнено. Подключаем видео и управление по локальной сети…':'Изображение появится здесь.');
+ put('metrics',`Видео ${stats.width||'—'} × ${stats.height||'—'}\nКадров/с ${Number.isFinite(stats.framesPerSecond)?stats.framesPerSecond.toFixed(1):'—'}\nRTT канала ${Number.isFinite(stats.rtt)?Math.round(stats.rtt)+' мс':'—'}\nОжидают ACK ${s.pending||0}`);
+ const error=s.error?errors[s.error]||s.error:'';put('pair-error',show?'':error);put('stream-error',show?error:'');$('stream-error').hidden=!show||!error;
+ }
+ $('pair-form').onsubmit=e=>{e.preventDefault();try{if(api.connect({code:$('pin').value,computerId:selected||undefined,host:$('manual').open?$('address').value.trim()||undefined:undefined})){$('pin').value='';document.activeElement?.blur();api.hideKeyboard();}}catch(error){put('pair-error',errors[error.message]||error.message);}updateConnect();};
+ $('pin').oninput=updateConnect;$('address').oninput=updateConnect;$('manual').ontoggle=updateConnect;$('rescan').onclick=()=>api.discover();$('resume').onclick=()=>api.resume();
+ // Pointer-down never steals the native terminal IME focus.
+ $('controls').addEventListener('pointerdown',e=>{if(e.target.closest('button'))e.preventDefault();});
+ document.addEventListener('contextmenu',e=>{if(e.target.closest('button,summary,.keybar'))e.preventDefault();});
+ for(const b of document.querySelectorAll('[data-key]'))b.onclick=()=>input.key(b.dataset.key,b.dataset.control?['control']:[]);
+ $('ctrl').onclick=()=>input.toggleControl();$('paste').onclick=()=>input.paste();
+ $('keyboard-toggle').onclick=()=>{if(input.active())input.stop();else notice('Коснитесь терминала — клавиатура откроется сама.');};
+ $('menu-toggle').onclick=()=>{input.stop();$('session-menu').showModal();};$('menu-close').onclick=()=>$('session-menu').close();
+ $('diagnostics-toggle').onclick=()=>{$('session-menu').close();$('diagnostics').showModal();};$('diagnostics-close').onclick=()=>$('diagnostics').close();
+ $('disconnect').onclick=()=>{$('session-menu').close();$('disconnect-dialog').showModal();};$('cancel-disconnect').onclick=()=>$('disconnect-dialog').close();$('confirm-disconnect').onclick=()=>{$('disconnect-dialog').close();input.stop();api.disconnect();};
+ for(const id of ['fit','mode','reset-view'])$(id).addEventListener('click',()=>{$('session-menu').close();});
+ window.addEventListener('canvaslink:tap',e=>{if(document.querySelector('dialog[open]')||state.connection!=='connected')return;input.open(e.detail.focus);});
+ window.addEventListener('canvaslink:notice',e=>notice(e.detail));
+ window.addEventListener('canvaslink:input-state',e=>{const d=e.detail;$('ctrl').setAttribute('aria-pressed',String(d.control));$('keyboard-toggle').setAttribute('aria-pressed',String(d.active));$('keyboard-toggle').setAttribute('aria-label',d.active?'Скрыть клавиатуру':'Как открыть клавиатуру');$('workspace').classList.toggle('is-typing',d.active);if(d.composition!==undefined){put('preedit',d.composition);$('preedit').hidden=!d.composition;}if(d.focus)state={...state,source:{...state.source,...d.focus,target:d.focus.kind}};});
+ function pointerPosition(p){const video=$('video'),b=video.getBoundingClientRect(),v=$('viewport').getBoundingClientRect(),w=video.videoWidth||state.stats?.width||1280,h=video.videoHeight||state.stats?.height||800,k=Math.min(b.width/w,b.height/h);return{x:b.left-v.left+(b.width-w*k)/2+p.x*w*k,y:b.top-v.top+(b.height-h*k)/2+p.y*h*k};}
+ function paint(p,pulse){const q=pointerPosition(p);$('local-cursor').hidden=!p.trackpad;$('local-cursor').style.transform=`translate(${q.x-13}px,${q.y-13}px)`;if(pulse&&p.action==='down'){const f=$('touch-feedback');clearTimeout(touchTimer);f.hidden=false;f.style.transform=`translate(${q.x-16}px,${q.y-16}px)`;touchTimer=setTimeout(()=>{f.hidden=true;},280);}}
+ window.addEventListener('canvaslink:pointer',e=>{lastPointer=e.detail;paint(lastPointer,true);});window.addEventListener('canvaslink:view',e=>{if(lastPointer){lastPointer.trackpad=e.detail.trackpad;paint(lastPointer,false);}});
+ const resize=()=>{document.documentElement.style.setProperty('--app-height',Math.max(120,Math.round(window.visualViewport?.height||innerHeight))+'px');if(lastPointer)paint(lastPointer,false);};window.visualViewport?.addEventListener('resize',resize);window.addEventListener('resize',resize);resize();
+ api.attachVideo($('video'));api.subscribe(render);
+})();
diff --git a/integrations/canvaslink/android/assets/delivery.js b/integrations/canvaslink/android/assets/delivery.js
new file mode 100644
index 000000000..cb1537500
--- /dev/null
+++ b/integrations/canvaslink/android/assets/delivery.js
@@ -0,0 +1,25 @@
+/* Transport contract v2. No DOM dependencies; shared by the client and tests. */
+(function(root,factory){if(typeof module==='object')module.exports=factory();else root.CanvasLinkDelivery=factory();})(globalThis,()=>{
+ class Delivery {
+ constructor({channel,onChange=()=>{},timeout=65000,setTimer=(fn,ms)=>setTimeout(fn,ms),clearTimer=token=>clearTimeout(token),id=()=>crypto.randomUUID()}){Object.assign(this,{channel,onChange,timeout,setTimer,clearTimer,id});this.pending=new Map();this.sent=0;this.acked=0;this.seq=0;}
+ send(input){
+ const dc=this.channel();
+ if(!dc||dc.readyState!=='open')return Promise.reject(Error('not-connected'));
+ if(dc.bufferedAmount>65536||this.pending.size>=64)return Promise.reject(Error('input-busy'));
+ const id=this.id();
+ return new Promise((resolve,reject)=>{
+ const entry={resolve,reject,input,timer:this.setTimer(()=>this.finish(id,false,'delivery-uncertain'),this.timeout)};
+ this.pending.set(id,entry);
+ try{dc.send(JSON.stringify({...input,id,seq:++this.seq}));this.sent++;this.onChange({id,status:'pending',kind:input.type,pending:this.pending.size});}
+ catch{this.finish(id,false,'not-sent');}
+ });
+ }
+ finish(id,ok,error,focus){const entry=this.pending.get(id);if(!entry)return false;this.pending.delete(id);this.clearTimer(entry.timer);if(ok)this.acked++;
+ this.onChange({id,status:ok?'processed':error==='delivery-uncertain'?'uncertain':'failed',kind:entry.input.type,error:error||'',pending:this.pending.size});
+ if(ok)entry.resolve({id,status:'processed',...(focus?{focus}:{})});else entry.reject(Error(error||'input-rejected'));return true;
+ }
+ receive(value){if(!['input-ok','input-error'].includes(value?.type))return false;return this.finish(value.id,value.type==='input-ok',value.error,value.focus);}
+ close(){for(const id of [...this.pending.keys()])this.finish(id,false,'delivery-uncertain');}
+ }
+ return {Delivery};
+});
diff --git a/integrations/canvaslink/android/assets/direct-input.js b/integrations/canvaslink/android/assets/direct-input.js
new file mode 100644
index 000000000..ec04faa66
--- /dev/null
+++ b/integrations/canvaslink/android/assets/direct-input.js
@@ -0,0 +1,41 @@
+/* Ordered, immediate terminal input. Only the peer owns the queue; never replay. */
+(()=>{
+ const api=window.CanvasLinkClient;
+ let token='',control=false,inflight=0;
+ const notify=detail=>window.dispatchEvent(new CustomEvent('canvaslink:input-state',{detail:{active:!!token,control,inflight,...detail}}));
+ function stop(focus){token='';control=false;api.hideKeyboard();notify({composition:'',...(focus?{focus}:{})});}
+ function fail(error){stop();window.dispatchEvent(new CustomEvent('canvaslink:notice',{detail:error.message||String(error)}));}
+ function send(value){
+ if(api.getState().connection!=='connected')return Promise.reject(Error('not-connected'));
+ const owner=token;inflight++;notify();
+ let promise;try{promise=api.sendInput(value);}catch(error){promise=Promise.reject(error);}
+ return Promise.resolve(promise).then(result=>{if(result?.status!=='processed')throw Error('delivery-uncertain');return result;}).catch(error=>{if(owner===token)fail(error);throw error;}).finally(()=>{inflight--;notify();});
+ }
+ window.CanvasLinkInput=Object.freeze({
+ open(focus){if(!focus?.editable)return stop(focus);token=crypto.randomUUID();control=false;notify({focus,composition:''});if(typeof Native?.showKeyboard==='function')Native.showKeyboard(token);},
+ stop,
+ toggleControl(){control=!control;notify();},
+ key(key,modifiers=[]){
+ if(control&&!modifiers.includes('control'))modifiers=[...modifiers,'control'];control=false;notify();
+ if(typeof Native?.terminalKey==='function'&&token)Native.terminalKey(key,JSON.stringify(modifiers));else send({type:'key',key,modifiers}).catch(()=>{});
+ },
+ paste(){control=false;notify();if(token&&typeof Native?.paste==='function')Native.paste();else window.dispatchEvent(new CustomEvent('canvaslink:notice',{detail:'Сначала коснитесь терминала или текстового поля для вставки.'}));},
+ receive(value){
+ if(!token||value?.token!==token)return;
+ if(value.type==='composition'){notify({composition:value.text||''});return;}
+ if(value.type==='notice'){window.dispatchEvent(new CustomEvent('canvaslink:notice',{detail:value.text}));return;}
+ if(value.type==='paste'){control=false;notify();send({type:'text',text:value.text}).catch(()=>{});return;}
+ if(value.type==='text'){
+ const useControl=control;control=false;notify();
+ if(useControl&&[...value.text].length===1&&/^[a-z]$/i.test(value.text)){send({type:'key',key:value.text.toLowerCase(),modifiers:['control']}).catch(()=>{});}
+ else send({type:'text',text:value.text}).catch(()=>{});
+ }
+ if(value.type==='key'){
+ let modifiers=value.modifiers||[];if(control&&!modifiers.includes('control'))modifiers=[...modifiers,'control'];
+ control=false;notify();send({type:'key',key:value.key,modifiers}).catch(()=>{});
+ }
+ },
+ active:()=>!!token
+ });
+ api.subscribe(state=>{if(state.connection!=='connected'&&token)stop();});
+})();
diff --git a/integrations/canvaslink/android/assets/gestures.js b/integrations/canvaslink/android/assets/gestures.js
new file mode 100644
index 000000000..c31fbef60
--- /dev/null
+++ b/integrations/canvaslink/android/assets/gestures.js
@@ -0,0 +1,289 @@
+/* Local interaction layer. CanvasLinkClient v2 and the pointer DOM contract stay stable. */
+(() => {
+ 'use strict';
+ const $ = id => document.getElementById(id);
+ const api = window.CanvasLinkClient;
+ const viewport = $('viewport'), video = $('video');
+ const touches = new Map();
+ const clamp = (value, min, max) => Math.max(min, Math.min(max, value));
+ const editor = target => target instanceof Element && (target.isContentEditable ||
+ Boolean(target.closest('input,textarea,select,[contenteditable]:not([contenteditable="false"])')));
+ const control = target => target instanceof Element &&
+ Boolean(target.closest('button,input,textarea,select,a,summary,[role="button"],[contenteditable]'));
+ let scale = 1, offset = {x: 0, y: 0}, trackpad = false;
+ let pointer = {x: .5, y: .5}, drag = false, press = null, pinch = null;
+ let composing = false, pairFrame = 0, holdTimer = 0;
+ let tapEpoch=0, focusRect=null, focusCaret=null, focusKind='',focusFont=14,focusViewportWidth=0,focusContext=null,knownTerminal=null,autoFramePending=true,focusedView=false,beforeFocus=null,remoteSurface='canvas',remoteViewportWidth=0,dragRects=[];
+ const validRect=r=>r&&['x','y','width','height'].every(k=>Number.isFinite(r[k]))&&r.width>0&&r.height>0;
+
+ const connected = () => api.getState().connection === 'connected';
+ const canInput = () => connected() && !composing && !editor(document.activeElement);
+ // Never queue, retry, or turn a rejected/uncertain delivery into another input.
+ function deliver(send) {
+ try { return Promise.resolve(send()).catch(() => undefined); } catch (_) { return Promise.resolve(); }
+ }
+ function send(value, cleanup = false) {
+ if (cleanup ? connected() : canInput()) return deliver(() => api.sendInput(value));
+ }
+ function mouse(action, at, extra = {}) {
+ // A held button must still be released if focus has just entered an editor.
+ const cleanup = action === 'up' && drag;
+ if (!(cleanup ? connected() : canInput())) return;
+ pointer = {x: at.x, y: at.y};
+ window.dispatchEvent(new CustomEvent('canvaslink:pointer', {
+ detail: {...pointer, action, trackpad}
+ }));
+ return send({type: 'pointer', action, ...pointer, button: 0, ...extra}, cleanup);
+ }
+
+ // The element fills the viewport, but object-fit:contain can leave letterboxes.
+ // Its transformed bounding box already includes our centre-origin scale/offset.
+ function contentBox() {
+ const rect = video.getBoundingClientRect();
+ const vw = video.videoWidth || 1280, vh = video.videoHeight || 800;
+ const fit = Math.min(rect.width / vw, rect.height / vh);
+ const width = vw * fit, height = vh * fit;
+ return {rect, width, height, left: rect.left + (rect.width - width) / 2,
+ top: rect.top + (rect.height - height) / 2};
+ }
+ function position(x, y) {
+ const box = contentBox();
+ return {x: clamp((x - box.left) / Math.max(1, box.width), 0, 1),
+ y: clamp((y - box.top) / Math.max(1, box.height), 0, 1)};
+ }
+ function transform() {
+ video.style.transform = `translate(${offset.x}px,${offset.y}px) scale(${scale})`;
+ const percentage = `${Math.round(scale * 100)}%`;
+ if($('view-toggle')){$('view-toggle').disabled=!connected()||!focusedView&&scale===1&&(!knownTerminal||remoteSurface==='settings');$('view-toggle').setAttribute('aria-label',focusedView||scale>1?'Показать весь Canvas':'Приблизить активный терминал');$('view-toggle-label').textContent=focusedView||scale>1?'Весь Canvas':'Терминал';}
+ if ($('zoom-label')) $('zoom-label').textContent = percentage;
+ $('fit').setAttribute('aria-label', `${percentage} — ${scale === 1 ? 'увеличить окно' : 'вписать окно целиком'}`);
+ if ($('mode-label')) $('mode-label').textContent = trackpad ? 'Тачпад' : 'Касание';
+ $('mode').setAttribute('aria-pressed', String(trackpad));
+ if ($('gesture-hint')) $('gesture-hint').textContent = trackpad
+ ? 'Палец — курсор · касание — клик · удержание — перетаскивание · два пальца — прокрутка · щипок — масштаб'
+ : 'Касание — клик · движение — перетаскивание · два пальца — масштаб и обзор';
+ window.dispatchEvent(new CustomEvent('canvaslink:view', {
+ detail: {scale, offset: {...offset}, trackpad,...(focusedView?{target:focusKind}:{})}
+ }));
+ }
+ function zoomView(nextScale, anchor, nextAnchor = anchor, base = {scale, offset: {...offset}}) {
+ autoFramePending=false;focusedView=false;
+ const box = contentBox(), bounds = viewport.getBoundingClientRect();
+ const centre = {x: box.rect.left + box.rect.width / 2 - offset.x,
+ y: box.rect.top + box.rect.height / 2 - offset.y};
+ const width = box.width / scale, height = box.height / scale;
+ scale = clamp(nextScale, 1, 8);
+ const ratio = scale / base.scale;
+ const maxX = Math.max(0, (width * scale - bounds.width) / 2);
+ const maxY = Math.max(0, (height * scale - bounds.height) / 2);
+ offset = {
+ x: clamp(nextAnchor.x - centre.x - (anchor.x - centre.x - base.offset.x) * ratio, -maxX, maxX),
+ y: clamp(nextAnchor.y - centre.y - (anchor.y - centre.y - base.offset.y) * ratio, -maxY, maxY)
+ };
+ transform();
+ }
+
+ function frameFocus(){
+ if(!focusedView||!focusRect)return;
+ const r=viewport.getBoundingClientRect(),vw=video.videoWidth||1280,vh=video.videoHeight||800;
+ const fit=Math.min(r.width/vw,r.height/vh),width=vw*fit,height=vh*fit;
+ const field=focusKind==='text-field',typing=!!window.CanvasLinkInput?.active();
+ const remoteWidth=focusViewportWidth||vw;
+ scale=field?clamp(Math.min(r.width*.92/(Math.max(.08,focusRect.width)*width),14/(width/remoteWidth*Math.max(10,focusFont))),1,4):clamp(Math.min(r.width*.96/(Math.max(.08,focusRect.width)*width),typing?8:r.height*.92/(Math.max(.08,focusRect.height)*height)),1,8);
+ const maxX=Math.max(0,(width*scale-r.width)/2),maxY=Math.max(0,(height*scale-r.height)/2);
+ const context=field&&validRect(focusContext)&&focusContext.width*width*scale{
+ const d=e.detail;
+ if(d.focus){remoteSurface=d.focus.surface||'canvas';dragRects=d.focus.dragRects||[];}
+ if(['terminal','text-field'].includes(d.focus?.kind)&&d.focus.editable&&validRect(d.focus.rect)){
+ if(!focusedView)beforeFocus={scale,offset:{...offset}};
+ focusRect=d.focus.rect;focusCaret=d.focus.caret;focusKind=d.focus.kind;focusFont=d.focus.fontSize||14;focusViewportWidth=d.focus.viewport?.width||0;focusContext=d.focus.contextRect;focusedView=true;frameFocus();
+ }else if(d.focus){
+ // Non-text controls keep the surrounding Settings context.
+ if(focusedView&&beforeFocus){scale=beforeFocus.scale;offset=beforeFocus.offset;transform();}
+ focusedView=false;beforeFocus=null;focusRect=null;focusCaret=null;
+ }else if(!d.active){if(focusedView&&focusKind==='text-field'&&beforeFocus){scale=beforeFocus.scale;offset=beforeFocus.offset;transform();beforeFocus=null;focusedView=false;}else if(focusedView&&focusKind==='terminal')frameFocus();}
+ });
+ new ResizeObserver(()=>{if(focusedView)frameFocus();else transform();}).observe(viewport);
+ video.addEventListener('resize',()=>{if(focusedView)frameFocus();});
+ $('view-toggle')?.addEventListener('click',()=>{autoFramePending=false;if(focusedView||scale>1){window.CanvasLinkInput?.stop();focusedView=false;scale=1;offset={x:0,y:0};transform();}else if(knownTerminal&&remoteSurface!=='settings'){focusKind='terminal';focusRect=knownTerminal.rect;focusCaret=knownTerminal.caret;focusViewportWidth=knownTerminal.viewport?.width||0;focusedView=true;frameFocus();}});
+
+ const stopHold = () => { clearTimeout(holdTimer); holdTimer = 0; };
+ function updatePair() {
+ pairFrame = 0;
+ if (touches.size !== 2 || !pinch || !canInput()) return;
+ const [a, b] = [...touches.values()];
+ const x = (a.x + b.x) / 2, y = (a.y + b.y) / 2;
+ const distance = Math.hypot(a.x - b.x, a.y - b.y);
+ if (trackpad && !pinch.kind) {
+ if (Math.abs(distance - pinch.distance) > 8 && Math.abs(distance / pinch.distance - 1) > .06) pinch.kind = 'zoom';
+ else if (Math.hypot(x - pinch.x, y - pinch.y) > 6) pinch.kind = 'scroll';
+ else return;
+ }
+ if (trackpad && pinch.kind === 'scroll') {
+ focusedView=false;
+ const dx = clamp(pinch.lastX - x, -2000, 2000), dy = clamp(pinch.lastY - y, -2000, 2000);
+ if (dx || dy) send({type: 'scroll', ...pointer, dx, dy});
+ } else {
+ zoomView(pinch.scale * distance / pinch.distance, {x: pinch.x, y: pinch.y}, {x, y}, pinch);
+ }
+ pinch.lastX = x; pinch.lastY = y;
+ }
+ function flushPair() {
+ if (pairFrame) { cancelAnimationFrame(pairFrame); updatePair(); }
+ }
+ function cancelGesture() {
+ stopHold();
+ if (pairFrame) { cancelAnimationFrame(pairFrame); pairFrame = 0; }
+ if (drag && connected()) mouse('up', pointer);
+ drag = false; press = null; pinch = null;
+ const ids = [...touches.keys()];
+ touches.clear(); // Clear before releasing capture: loss can arrive synchronously.
+ for (const id of ids) {
+ try { if (viewport.hasPointerCapture(id)) viewport.releasePointerCapture(id); } catch (_) {}
+ }
+ }
+
+ $('fit').onclick = () => {
+ cancelGesture(); autoFramePending=false;focusedView=false;scale = scale === 1 ? 2 : 1; offset = {x: 0, y: 0}; transform();
+ };
+ $('mode').onclick = () => { cancelGesture(); trackpad = !trackpad; transform(); };
+ // Optional hook: also works while the parent UI is being upgraded in place.
+ document.addEventListener('click', e => {
+ if (e.target instanceof Element && e.target.closest('#reset-view')) {
+ cancelGesture(); autoFramePending=false;focusedView=false;scale = 1; offset = {x: 0, y: 0}; transform();
+ }
+ });
+ if (!viewport.hasAttribute('tabindex')) viewport.tabIndex = 0;
+ viewport.addEventListener('pointerdown', e => {
+ if (!canInput()) { e.preventDefault(); return; }
+ if (e.button !== 0 || control(e.target) || e.target.closest?.('#waiting')) return;
+ e.preventDefault();++tapEpoch;viewport.focus({preventScroll: true});
+ try { viewport.setPointerCapture(e.pointerId); } catch (_) { cancelGesture(); return; }
+ touches.set(e.pointerId, {x: e.clientX, y: e.clientY});
+ if (touches.size === 1) {
+ const at=position(e.clientX,e.clientY);
+ const onSlider=dragRects.some(r=>validRect(r)&&at.x>=r.x&&at.x<=r.x+r.width&&at.y>=r.y&&at.y<=r.y+r.height);
+ press = {x: e.clientX, y: e.clientY, travel: 0,scroll:!trackpad&&remoteSurface==='settings'&&!onSlider,at};
+ if (trackpad && e.pointerType !== 'mouse') {
+ const held = press;
+ holdTimer = setTimeout(() => {
+ holdTimer = 0;
+ if (press === held && touches.size === 1 && held.travel < 8 && canInput()) {
+ drag = true; mouse('down', pointer);
+ }
+ }, 450);
+ }
+ } else if (touches.size === 2) {
+ stopHold();
+ if (drag) mouse('up', pointer);
+ drag = false; press = null;
+ const [a, b] = [...touches.values()];
+ pinch = {distance: Math.max(1, Math.hypot(a.x - b.x, a.y - b.y)), scale,
+ x: (a.x + b.x) / 2, y: (a.y + b.y) / 2, lastX: (a.x + b.x) / 2,
+ lastY: (a.y + b.y) / 2, offset: {...offset}, kind: null};
+ }
+ });
+ viewport.addEventListener('pointermove', e => {
+ const previous = touches.get(e.pointerId);
+ if (!previous) return;
+ touches.set(e.pointerId, {x: e.clientX, y: e.clientY});
+ if (touches.size === 2 && pinch) {
+ // Classify the settled frame, not half of a two-pointer update. Scroll uses
+ // centroid deltas, so moving both fingers never doubles the remote scroll.
+ if (!pairFrame) pairFrame = requestAnimationFrame(updatePair);
+ return;
+ }
+ if (!press) return;
+ press.travel = Math.max(press.travel, Math.hypot(e.clientX - press.x, e.clientY - press.y));
+ if (press.travel >= 8) stopHold();
+ if (trackpad) {
+ const r = viewport.getBoundingClientRect();
+ pointer = {x: clamp(pointer.x + (e.clientX - previous.x) / Math.max(1, r.width), 0, 1),
+ y: clamp(pointer.y + (e.clientY - previous.y) / Math.max(1, r.height), 0, 1)};
+ mouse('move', pointer, drag ? {drag: true} : {});
+ } else if(press.scroll&&press.travel>8){
+ focusedView=false;
+ const k=(remoteViewportWidth||video.videoWidth)/Math.max(1,contentBox().width);
+ send({type:'scroll',...press.at,dx:clamp((previous.x-e.clientX)*k,-2000,2000),dy:clamp((previous.y-e.clientY)*k,-2000,2000)});
+ } else if (press.travel > 8 || drag) {
+ if (!drag) { mouse('down', position(press.x, press.y)); drag = true; }
+ mouse('move', position(e.clientX, e.clientY), {drag: true});
+ }
+ });
+ function release(e) {
+ if (!touches.has(e.pointerId)) return;
+ stopHold();
+ if (e.type === 'pointerup') flushPair();
+ else if (pairFrame) { cancelAnimationFrame(pairFrame); pairFrame = 0; }
+ if (drag && e.type === 'pointercancel') mouse('up', pointer);
+ if (touches.size === 1 && press && e.type !== 'pointercancel') {
+ const at = trackpad ? pointer : position(e.clientX, e.clientY);
+ if (drag) mouse('up', at);
+ else if (press.travel < 8 && Math.hypot(e.clientX - press.x, e.clientY - press.y) < 8) {
+ const epoch=tapEpoch;
+ mouse('down', at);Promise.resolve(mouse('up', at)).then(receipt=>{
+ if(epoch===tapEpoch&&connected()&&receipt?.status==='processed')window.dispatchEvent(new CustomEvent('canvaslink:tap',{detail:{focus:receipt.focus,at}}));
+ });
+ }
+ }
+ touches.delete(e.pointerId);
+ if (touches.size < 2) pinch = null;
+ // No remaining finger may turn a pair gesture into a tap or resumed drag.
+ press = null; drag = false;
+ }
+ viewport.addEventListener('pointerup', release);
+ viewport.addEventListener('pointercancel', release);
+ viewport.addEventListener('lostpointercapture', e => {
+ // The video's implicit capture is transferred to the viewport. Its own loss
+ // bubbles here but must NOT cancel the viewport's newly captured gesture.
+ if (e.target === viewport) release({pointerId: e.pointerId, type: 'pointercancel'});
+ });
+ window.addEventListener('blur', cancelGesture);
+ document.addEventListener('visibilitychange', () => { if (document.hidden) cancelGesture(); });
+ api.subscribe(state => {
+ if(state.connection!=='connected'){++tapEpoch;cancelGesture();focusedView=false;focusCaret=null;return;}
+ if(state.source?.viewport?.width>0)remoteViewportWidth=state.source.viewport.width;
+ if(state.source?.surface){remoteSurface=state.source.surface;dragRects=state.source.dragRects||[];}
+ const terminal=state.source?.target==='terminal'&&validRect(state.source.rect)?state.source:state.source?.terminalView;
+ if(terminal&&validRect(terminal.rect)){knownTerminal=terminal;if(autoFramePending&&remoteSurface!=='settings'){autoFramePending=false;focusKind='terminal';focusRect=knownTerminal.rect;focusCaret=knownTerminal.caret;focusViewportWidth=knownTerminal.viewport?.width||0;focusedView=true;frameFocus();}}
+ if(remoteSurface==='settings'&&focusedView&&focusKind==='terminal'){focusedView=false;scale=1;offset={x:0,y:0};transform();}
+ // Health may follow an already selected cursor, but can never open an IME.
+ // Manual pan/zoom/scroll disables following until another confirmed tap.
+ if(focusedView&&focusKind==='terminal'&&state.source?.target==='terminal'&&validRect(state.source.rect)&&validRect(state.source.caret)){focusRect=state.source.rect;focusCaret=state.source.caret;frameFocus();}
+ });
+ document.addEventListener('focusin', e => { if (editor(e.target)) cancelGesture(); });
+ window.addEventListener('compositionstart', () => { composing = true; cancelGesture(); });
+ window.addEventListener('compositionend', () => { composing = false; });
+
+ viewport.addEventListener('wheel', e => {
+ if (!canInput() || control(e.target) || e.target.closest?.('#waiting')) return;
+ e.preventDefault();
+ const dx = e.deltaX * (e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? viewport.clientWidth : 1);
+ const dy = e.deltaY * (e.deltaMode === 1 ? 16 : e.deltaMode === 2 ? viewport.clientHeight : 1);
+ // Chromium exposes physical trackpad pinch as Ctrl+wheel, not touch pointers.
+ if (e.ctrlKey) { cancelGesture(); zoomView(scale * Math.exp(-dy * .002), {x: e.clientX, y: e.clientY}); return; }
+ focusedView=false;send({type: 'scroll', ...(trackpad ? pointer : position(e.clientX, e.clientY)),
+ dx: clamp(dx, -2000, 2000), dy: clamp(dy, -2000, 2000)});
+ }, {passive: false});
+ const terminalKeys = new Set(['Enter', 'Tab', 'Escape', 'Backspace', 'Delete',
+ 'ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown', 'Home', 'End', 'PageUp', 'PageDown']);
+ window.addEventListener('keydown', e => {
+ if (document.querySelector('dialog[open]') || !canInput() || e.defaultPrevented || e.isComposing || e.keyCode === 229 || editor(e.target)) return;
+ if (!(e.target instanceof Element) || control(e.target)) return;
+ if (e.target !== $('workspace') && !viewport.contains(e.target)) return;
+ if (e.key === 'Enter' && e.repeat) { e.preventDefault(); return; }
+ const modifiers = [e.ctrlKey ? 'control' : null, e.shiftKey ? 'shift' : null,
+ e.altKey ? 'alt' : null, e.metaKey ? 'meta' : null].filter(Boolean);
+ let sendKey;
+ if (terminalKeys.has(e.key)) sendKey = () => api.sendKey(e.key, modifiers);
+ else if ((e.ctrlKey || e.metaKey) && 'cavzdl'.includes(e.key.toLowerCase())) sendKey = () => api.sendKey(e.key.toLowerCase(), modifiers);
+ else if ([...e.key].length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) sendKey = () => api.sendText(e.key);
+ if (sendKey) { e.preventDefault(); deliver(sendKey); }
+ });
+})();
diff --git a/integrations/canvaslink/android/assets/index.html b/integrations/canvaslink/android/assets/index.html
new file mode 100644
index 000000000..593a54d16
--- /dev/null
+++ b/integrations/canvaslink/android/assets/index.html
@@ -0,0 +1,99 @@
+
+
+
+
+
+
+ CanvasLink
+
+
+
+
+
+
+
+
+ CanvasLink
+
+
Подключение к CanvasTTY
+
Телефон и компьютер должны быть в одной локальной сети.
+
+
+
+
+
Рабочая область CanvasTTY
+
+
+
+
+
+
Открываем CanvasTTY
Ожидаем изображение.
+
+
+
+
+
+
+
+
+
+
+
diff --git a/integrations/canvaslink/android/assets/lucide-LICENSE.txt b/integrations/canvaslink/android/assets/lucide-LICENSE.txt
new file mode 100644
index 000000000..718bb3f0e
--- /dev/null
+++ b/integrations/canvaslink/android/assets/lucide-LICENSE.txt
@@ -0,0 +1,43 @@
+ISC License
+
+Copyright (c) 2026 Lucide Icons and Contributors
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+
+---
+
+The following Lucide icons are derived from the Feather project:
+
+airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
+
+The MIT License (MIT) (for the icons listed above)
+
+Copyright (c) 2013-present Cole Bemis
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/integrations/canvaslink/android/assets/onest-OFL.txt b/integrations/canvaslink/android/assets/onest-OFL.txt
new file mode 100644
index 000000000..f480c31d2
--- /dev/null
+++ b/integrations/canvaslink/android/assets/onest-OFL.txt
@@ -0,0 +1,93 @@
+Copyright 2021 The Onest Project Authors (https://github.com/googlefonts/onest)
+
+This Font Software is licensed under the SIL Open Font License, Version 1.1.
+This license is copied below, and is also available with a FAQ at:
+https://scripts.sil.org/OFL
+
+
+-----------------------------------------------------------
+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
+-----------------------------------------------------------
+
+PREAMBLE
+The goals of the Open Font License (OFL) are to stimulate worldwide
+development of collaborative font projects, to support the font creation
+efforts of academic and linguistic communities, and to provide a free and
+open framework in which fonts may be shared and improved in partnership
+with others.
+
+The OFL allows the licensed fonts to be used, studied, modified and
+redistributed freely as long as they are not sold by themselves. The
+fonts, including any derivative works, can be bundled, embedded,
+redistributed and/or sold with any software provided that any reserved
+names are not used by derivative works. The fonts and derivatives,
+however, cannot be released under any other type of license. The
+requirement for fonts to remain under this license does not apply
+to any document created using the fonts or their derivatives.
+
+DEFINITIONS
+"Font Software" refers to the set of files released by the Copyright
+Holder(s) under this license and clearly marked as such. This may
+include source files, build scripts and documentation.
+
+"Reserved Font Name" refers to any names specified as such after the
+copyright statement(s).
+
+"Original Version" refers to the collection of Font Software components as
+distributed by the Copyright Holder(s).
+
+"Modified Version" refers to any derivative made by adding to, deleting,
+or substituting -- in part or in whole -- any of the components of the
+Original Version, by changing formats or by porting the Font Software to a
+new environment.
+
+"Author" refers to any designer, engineer, programmer, technical
+writer or other person who contributed to the Font Software.
+
+PERMISSION & CONDITIONS
+Permission is hereby granted, free of charge, to any person obtaining
+a copy of the Font Software, to use, study, copy, merge, embed, modify,
+redistribute, and sell modified and unmodified copies of the Font
+Software, subject to the following conditions:
+
+1) Neither the Font Software nor any of its individual components,
+in Original or Modified Versions, may be sold by itself.
+
+2) Original or Modified Versions of the Font Software may be bundled,
+redistributed and/or sold with any software, provided that each copy
+contains the above copyright notice and this license. These can be
+included either as stand-alone text files, human-readable headers or
+in the appropriate machine-readable metadata fields within text or
+binary files as long as those fields can be easily viewed by the user.
+
+3) No Modified Version of the Font Software may use the Reserved Font
+Name(s) unless explicit written permission is granted by the corresponding
+Copyright Holder. This restriction only applies to the primary font name as
+presented to the users.
+
+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
+Software shall not be used to promote, endorse or advertise any
+Modified Version, except to acknowledge the contribution(s) of the
+Copyright Holder(s) and the Author(s) or with their explicit written
+permission.
+
+5) The Font Software, modified or unmodified, in part or in whole,
+must be distributed entirely under this license, and must not be
+distributed under any other license. The requirement for fonts to
+remain under this license does not apply to any document created
+using the Font Software.
+
+TERMINATION
+This license becomes null and void if any of the above conditions are
+not met.
+
+DISCLAIMER
+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
+OTHER DEALINGS IN THE FONT SOFTWARE.
diff --git a/integrations/canvaslink/android/assets/onest.ttf b/integrations/canvaslink/android/assets/onest.ttf
new file mode 100644
index 000000000..477cb3102
Binary files /dev/null and b/integrations/canvaslink/android/assets/onest.ttf differ
diff --git a/integrations/canvaslink/android/assets/style.css b/integrations/canvaslink/android/assets/style.css
new file mode 100644
index 000000000..97ac9bb28
--- /dev/null
+++ b/integrations/canvaslink/android/assets/style.css
@@ -0,0 +1,124 @@
+/* CanvasTTY Sage tokens: src/renderer/src/styles/tokens.css. */
+:root {
+ color-scheme:dark;
+ font-family:"Trebuchet MS","Segoe UI",sans-serif;
+ font-synthesis:none;
+ --canvas:#aaa7a2;
+ --surface:#353442;
+ --surface-soft:#424251;
+ --text:#f8f7f1;
+ --text-dark:#30313d;
+ --muted:rgba(255,255,255,.7);
+ --primary:#b8cf99;
+ --primary-hover:#c6dca8;
+ --danger:#e3615e;
+ --line:rgba(248,247,241,.13);
+ --app-height:100dvh;
+}
+* {box-sizing:border-box;-webkit-tap-highlight-color:transparent}
+[hidden] {display:none!important}
+html,body {margin:0;min-height:100%;background:var(--surface);color:var(--text)}
+body {-webkit-user-select:none;user-select:none;-webkit-touch-callout:none;font-size:14px;line-height:1.5}
+body.is-workspace {height:var(--app-height);overflow:hidden;overscroll-behavior:none}
+button,input,summary {font:inherit}
+button,summary,button * {-webkit-user-select:none;user-select:none;-webkit-touch-callout:none}
+button {display:inline-flex;align-items:center;justify-content:center;gap:10px;min-height:48px;padding:10px 16px;border:0;border-radius:9px;color:var(--text);background:var(--surface-soft);font-weight:600;cursor:pointer;touch-action:manipulation}
+button:active:not(:disabled) {background:#525262}
+button:disabled {opacity:.4;cursor:default}
+button:focus-visible,summary:focus-visible,input:focus-visible {outline:2px solid var(--primary);outline-offset:3px}
+button[aria-pressed=true],.primary {background:var(--primary);color:var(--text-dark)}
+button[aria-pressed=true]:active,.primary:active:not(:disabled) {background:var(--primary-hover)}
+.danger {color:#ffb5b1}
+.icon {width:20px;height:20px;flex:none;fill:none;stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;pointer-events:none}
+.icon-definitions {position:absolute;width:0;height:0;overflow:hidden;pointer-events:none}
+.icon-button {width:48px;min-width:48px;padding:0}
+.sr-only {position:absolute!important;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap;border:0}
+.subtle,.hint {color:var(--muted)}
+.subtle {margin:12px 0 24px}
+.hint {font-size:12px;line-height:1.5;margin:10px 0 20px}
+.pairing-screen {min-height:var(--app-height);padding:env(safe-area-inset-top) max(20px,env(safe-area-inset-right)) max(24px,env(safe-area-inset-bottom)) max(20px,env(safe-area-inset-left));background:var(--canvas)}
+.pair-header {max-width:440px;margin:auto;min-height:88px;display:flex;align-items:center;color:var(--text-dark)}
+.brand {font-size:20px;font-weight:700}
+.pair-card {width:100%;max-width:440px;margin:8px auto 0;padding:28px;background:var(--surface);border-radius:20px}
+.pair-card h1 {font-size:24px;font-weight:700;line-height:1.25;margin:0}
+.field-heading {display:flex;align-items:center;justify-content:space-between;gap:12px;margin:0 0 8px;font-weight:600}
+.field-heading .icon-button {background:transparent;color:var(--muted)}
+.computers {display:grid;gap:8px}
+.computer {width:100%;justify-content:flex-start;text-align:left;min-height:56px;padding:12px;gap:12px;border:2px solid transparent;font-weight:400}
+.computer>span {flex:1;min-width:0;overflow-wrap:anywhere}
+.computer[aria-pressed=true] {background:var(--surface-soft);border-color:var(--primary);color:var(--text)}
+.computer-check {margin-left:auto;color:var(--primary);visibility:hidden}
+.computer[aria-pressed=true] .computer-check {visibility:visible}
+.field-label {display:block;margin:20px 0 10px;font-weight:600}
+input {width:100%;min-height:52px;border:1px solid var(--line);border-radius:9px;background:#292935;padding:12px 14px;color:var(--text);font-size:16px;-webkit-user-select:text;user-select:text;touch-action:auto}
+input::placeholder {color:rgba(248,247,241,.4);opacity:1}
+#pin {font-family:ui-monospace,monospace;font-size:28px;letter-spacing:.3em;text-align:center;padding-left:calc(14px + .3em)}
+#connect {width:100%;justify-content:space-between}
+.error-message {margin:16px 0 0;color:#ffb5b1;font-size:13px;overflow-wrap:anywhere}
+.error-message:empty {display:none}
+details {margin-top:20px;border-top:1px solid var(--line)}
+summary {display:flex;align-items:center;justify-content:space-between;gap:12px;min-height:52px;list-style:none;cursor:pointer;font-size:13px;color:var(--muted);touch-action:manipulation}
+summary::-webkit-details-marker {display:none}
+summary .icon {width:16px;height:16px}
+details[open] summary .icon {transform:rotate(180deg)}
+details .field-label {margin-top:0}
+.workspace {height:var(--app-height);width:100%;display:flex;flex-direction:column;overflow:hidden;background:var(--surface)}
+.remote-viewport {flex:1;min-height:0;position:relative;overflow:hidden;touch-action:none;background:#20212b}
+#video {position:absolute;inset:0;width:100%;height:100%;object-fit:contain;transform-origin:center;pointer-events:none}
+.keybar {display:flex;align-items:center;gap:6px;flex:0 0 auto;min-width:0;min-height:56px;padding:3px max(6px,env(safe-area-inset-right)) max(3px,env(safe-area-inset-bottom)) max(6px,env(safe-area-inset-left));background:var(--surface)}
+.keybar button {flex:0 0 auto;height:44px;min-height:44px;min-width:44px;padding:0 12px;font:600 13px/1 "Trebuchet MS","Segoe UI",sans-serif;white-space:nowrap}
+.keybar .icon-button {width:44px;padding:0}
+.keybar>.icon-button {background:transparent;color:var(--muted)}
+.keybar button[aria-pressed=true] {background:var(--primary);color:var(--text-dark)}
+.keys {display:flex;flex:1;min-width:0;gap:6px;align-items:center;overflow-x:auto;overflow-y:hidden;overscroll-behavior-x:contain;scrollbar-width:none;padding:3px 2px}
+.keys::-webkit-scrollbar {display:none}
+.keybar .enter-key {color:var(--primary);min-width:48px}
+.direction-left {transform:rotate(180deg)}
+.direction-up {transform:rotate(-90deg)}
+.direction-down {transform:rotate(90deg)}
+.local-cursor {position:absolute;left:0;top:0;width:26px;height:26px;color:var(--text);filter:drop-shadow(0 1px 2px #000);pointer-events:none}
+.local-cursor .icon {width:26px;height:26px}
+.touch-feedback {position:absolute;left:0;top:0;width:32px;height:32px;border-radius:50%;border:2px solid var(--primary);pointer-events:none}
+.preedit {position:absolute;left:16px;bottom:12px;max-width:calc(100% - 32px);padding:6px 12px;background:var(--surface);border-radius:9px;text-decoration:underline;font:16px/1.4 ui-monospace,monospace;white-space:pre-wrap;overflow:hidden}
+.waiting {position:absolute;inset:0;display:flex;flex-direction:column;justify-content:center;align-items:center;background:#20212b;padding:24px;text-align:center;z-index:4}
+.waiting>.icon {width:28px;height:28px;color:var(--muted)}
+.waiting h2 {font-size:20px;line-height:1.3;font-weight:600;margin:20px 0 8px}
+.waiting p {font-size:14px;color:var(--muted);max-width:340px;margin:0 0 20px}
+.toast {position:absolute;bottom:12px;left:50%;transform:translateX(-50%);max-width:min(560px,calc(100% - 32px));width:max-content;max-height:60%;overflow:auto;z-index:6;background:var(--surface);border:1px solid var(--line);border-radius:9px;padding:12px 16px;font-size:13px;margin:0;overflow-wrap:anywhere}
+.toast.error {color:#ffb5b1;border-color:rgba(227,97,94,.5)}
+.sheet {color:var(--text);background:var(--surface);border:0;border-radius:20px;padding:20px;width:min(440px,calc(100% - 32px));max-height:calc(var(--app-height) - 32px);overflow:auto;box-shadow:0 16px 48px #0005}
+.sheet::backdrop {background:rgba(24,24,32,.6)}
+.sheet-heading {display:flex;align-items:center;justify-content:space-between;gap:16px;margin:-4px -4px 0 0}
+.sheet-heading .icon-button {background:transparent;color:var(--muted)}
+.sheet h2 {font-size:20px;line-height:1.3;font-weight:700;margin:0}
+.connection-state {font-size:12px;color:var(--muted);margin:4px 0 12px}
+.menu-actions {display:grid;gap:8px;margin-top:20px}
+.menu-actions>button {justify-content:space-between;min-height:52px;text-align:left;font-weight:400}
+.menu-actions>button>span:last-child {color:var(--muted)}
+.menu-actions>button[aria-pressed=true]>span:last-child {color:var(--text-dark)}
+.sheet pre {font:13px/2 ui-monospace,monospace;margin:20px 0;white-space:pre-wrap;-webkit-user-select:text;user-select:text}
+.sheet-actions {display:flex;gap:8px;margin-top:24px;flex-wrap:wrap}
+.sheet-actions button {flex:1;min-width:120px}
+@media(hover:hover) {
+ button:hover:not(:disabled) {background:#525262}
+ button.primary:hover:not(:disabled),button[aria-pressed=true]:hover {background:var(--primary-hover)}
+ .computer[aria-pressed=true]:hover {background:#525262}
+}
+@media(max-width:380px) {
+ .pairing-screen {padding-left:16px;padding-right:16px}
+ .pair-card {padding:20px}
+ .pair-card h1 {font-size:22px}
+ .keybar {gap:4px}
+}
+@media(max-height:500px) {
+ .pair-header {min-height:56px}
+ .pair-card {margin-top:0}
+ .sheet {padding:16px;max-height:calc(var(--app-height) - 16px)}
+}
+@media(prefers-reduced-motion:no-preference) {
+ button {transition:background-color .12s ease,color .12s ease,opacity .12s ease}
+ dialog[open] {animation:sheet-in .14s ease-out}
+ .touch-feedback {animation:touch .28s ease-out}
+ @keyframes sheet-in {from{opacity:0;translate:0 6px}to{opacity:1;translate:0 0}}
+ @keyframes touch {from{opacity:1;scale:.7}to{opacity:0;scale:1.3}}
+}
diff --git a/integrations/canvaslink/android/assets/transport.js b/integrations/canvaslink/android/assets/transport.js
new file mode 100644
index 000000000..110fa6c8c
--- /dev/null
+++ b/integrations/canvaslink/android/assets/transport.js
@@ -0,0 +1,117 @@
+/* Public designer API v2. This file owns secure transport and delivery state. */
+(()=>{
+ let pc,dc,video,paired=false,acceptPairing=true,acceptOffers=false,move,moveFrame,peerEpoch=0,stats={},lastFrames=0,lastFrameAt=0,draftTouched=false,connectionTimer,retryTimer;
+ const listeners=new Set(),computers=new Map();
+ let state={version:2,connection:'idle',discovery:'searching',computers:[],computer:'',error:'',pending:0,delivery:null,stats:{},source:null,draft:''};
+ const snapshot=()=>JSON.parse(JSON.stringify(state));
+ const update=patch=>{Object.assign(state,patch);for(const listener of listeners)listener(snapshot());};
+ const signal=message=>Native.signal(JSON.stringify(message));
+ const delivery=new CanvasLinkDelivery.Delivery({channel:()=>dc,onChange:value=>{if(['pointer','scroll'].includes(value.kind)){state.pending=value.pending;return;}update({delivery:value,pending:value.pending});}});
+ const raw=value=>{if(dc?.readyState==='open'&&dc.bufferedAmount<65536)dc.send(JSON.stringify(value));};
+ function stopWaiting(){clearTimeout(connectionTimer);connectionTimer=null;}
+ function waitForConnection(){
+ if(connectionTimer||!paired||document.hidden)return;
+ // Offers and polling retries share one deadline, so they cannot prolong it forever.
+ connectionTimer=setTimeout(()=>{connectionTimer=null;if(!paired||document.hidden)return;acceptOffers=false;close();update({connection:'reconnecting',error:'lan-connection-timeout'});},30000);
+ }
+ function connected(){stopWaiting();clearTimeout(retryTimer);retryTimer=null;update({connection:'connected',error:''});}
+ function close(){clearTimeout(retryTimer);retryTimer=null;peerEpoch++;if(moveFrame)cancelAnimationFrame(moveFrame);moveFrame=null;move=null;delivery.close();dc=null;const previous=pc;pc=null;previous?.close();stats={};lastFrames=0;lastFrameAt=0;window.CanvasLink.stats={};update({stats:{},source:null});if(video)video.srcObject=null;}
+ function retry(current){
+ if(current!==pc||!paired||document.hidden)return;
+ delivery.close();update({connection:'reconnecting'});waitForConnection();
+ clearTimeout(retryTimer);retryTimer=setTimeout(()=>{retryTimer=null;if(paired&&!document.hidden&¤t===pc&&(current.connectionState!=='connected'||dc?.readyState!=='open'))signal({type:'ping'});},2500);
+ }
+ function resume(){if(!paired||document.hidden)return;stopWaiting();close();acceptOffers=true;update({connection:'reconnecting',error:''});waitForConnection();signal({type:'ping'});}
+ async function offer(message){
+ close();waitForConnection();update({connection:'connecting',error:''});
+ const epoch=peerEpoch;
+ try{
+ const current=pc=new RTCPeerConnection({iceServers:[]});
+ current.ontrack=event=>{if(current!==pc)return;if(video){video.srcObject=event.streams[0];video.play().catch(()=>{});}};
+ current.ondatachannel=event=>{
+ if(current!==pc)return;dc=event.channel;
+ dc.onopen=()=>{if(current===pc)connected();};
+ dc.onclose=()=>retry(current);
+ dc.onmessage=event=>{
+ if(current!==pc||typeof event.data!=='string'||event.data.length>40000)return;
+ let value;try{value=JSON.parse(event.data);}catch{return;}
+ if(value.type==='source-state'){update({source:{capture:value.capture,windowFocused:!!value.windowFocused,target:value.target,surface:value.surface||'canvas',viewport:value.viewport||null,terminalView:value.terminalView||null,dragRects:value.dragRects||[],rect:value.rect||null,caret:value.caret||null}});return;}
+ if(value.type==='pong')stats.rtt=Math.round(performance.now()-value.at);
+ if(delivery.receive(value))return;
+ if(value.type==='fixture-state'){window.CanvasLink.fixture=value;Native.acceptance(JSON.stringify(value));}
+ };
+ };
+ current.onconnectionstatechange=()=>{
+ if(current!==pc)return;
+ if(current.connectionState==='connected'&&dc?.readyState==='open')connected();
+ if(['failed','disconnected'].includes(current.connectionState))retry(current);
+ };
+ await current.setRemoteDescription(message);if(current!==pc)return;
+ const answer=await current.createAnswer();if(current!==pc)return;
+ await current.setLocalDescription(answer);if(current!==pc)return;
+ await new Promise((resolve,reject)=>{if(current.iceGatheringState==='complete')return resolve();const timer=setTimeout(()=>reject(Error('ice-timeout')),12000);current.onicegatheringstatechange=()=>{if(current.iceGatheringState==='complete'){clearTimeout(timer);resolve();}};});
+ if(current===pc)signal({type:'answer',sdp:current.localDescription.sdp});
+ }catch(error){if(epoch===peerEpoch){acceptOffers=false;stopWaiting();close();update({connection:paired?'reconnecting':'error',error:error.message});}}
+ }
+ function connect({code,computerId,host}={}){
+ const address=host||computers.get(computerId)?.host||(computers.size===1?[...computers.values()][0].host:'');
+ if(!address){update({error:computers.size?'choose-computer':'computer-not-found'});return false;}
+ if(!/^\d{6}$/.test(code||'')){update({error:'invalid-code'});return false;}
+ stopWaiting();close();paired=false;acceptOffers=false;acceptPairing=true;update({connection:'pairing',computer:address,error:''});Native.connect(address,code);return true;
+ }
+ function sendInput(input){
+ if(input.type==='pointer'&&input.action==='move'){
+ // Coalesce motion only; never replay or coalesce text, clicks, or keys.
+ move=input;if(!moveFrame)moveFrame=requestAnimationFrame(()=>{moveFrame=null;const m=move;move=null;delivery.send(m).catch(()=>{});});return Promise.resolve({status:'coalesced'});
+ }
+ if(move){cancelAnimationFrame(moveFrame);moveFrame=null;const m=move;move=null;delivery.send(m).catch(()=>{});}
+ return delivery.send(input);
+ }
+ const api=window.CanvasLinkClient=Object.freeze({
+ version:2,getState:snapshot,subscribe(listener){listeners.add(listener);listener(snapshot());return()=>listeners.delete(listener);},
+ attachVideo(element){video=element;},connect,discover(){update({discovery:'searching'});Native.discover();},
+ disconnect(){acceptPairing=false;acceptOffers=false;paired=false;stopWaiting();close();Native.disconnect();update({connection:'idle',error:''});},
+ sendInput,sendText(text){if(typeof text!=='string'||!text.length||text.length>8000)return Promise.reject(Error('invalid-text'));return sendInput({type:'text',text});},
+ sendKey(key,modifiers=[]){return sendInput({type:'key',key,modifiers});},
+ setDraft(text){draftTouched=true;state.draft=String(text).slice(0,8000);return Native.saveDraft(state.draft);},
+ hideKeyboard(){Native.hideKeyboard();},resume
+ });
+ window.CanvasLink={stats:{},fixture:null,connectForTest:(host,code)=>connect({host,code}),requestFixture:requestId=>raw({type:'stats',...(typeof requestId==='string'&&requestId.length<=80?{requestId}:{})}),receive(event){
+ const value=event.value;
+ if(event.type==='discovered'){computers.set(value.id,{...value});update({discovery:'ready',computers:[...computers.values()]});}
+ if(event.type==='lost'){computers.delete(value);update({computers:[...computers.values()]});}
+ if(event.type==='discovery')update({discovery:value});
+ if(event.type==='draft'&&!draftTouched)update({draft:value||''});
+ if(event.type==='paired'){if(!acceptPairing)return;stopWaiting();close();paired=true;acceptOffers=true;waitForConnection();update({connection:'connecting',computer:value.host,error:''});}
+ if(event.type==='signal'){
+ if(!paired||document.hidden)return;
+ if(value.type==='offer'&&acceptOffers)void offer(value);
+ if(value.type==='disconnect'){acceptOffers=false;stopWaiting();close();update({connection:'reconnecting',error:value.reason==='host-connection-failed'?'host-connection-failed':state.error});}
+ }
+ if(event.type==='error')update({connection:paired?'reconnecting':'error',error:String(value)});
+ if(event.type==='network')update({connection:paired?'reconnecting':'idle',error:String(value)});
+ if(event.type==='network-changed'){
+ acceptOffers=false;stopWaiting();close();
+ if(paired){update({connection:'reconnecting',error:value==='offline'?'lan-network-unavailable':''});if(value==='ready')resume();}
+ }
+ // A reconnect ping sent while Wi-Fi is down cannot reach the host. Retry
+ // only signalling once encrypted polling succeeds; input is never replayed.
+ if(event.type==='network-restored'&&paired&&!document.hidden&&state.connection!=='connected'){acceptOffers=true;waitForConnection();signal({type:'ping'});}
+ if(event.type==='disconnected'){paired=false;acceptOffers=false;stopWaiting();close();update({connection:'idle'});}
+ }};
+ document.addEventListener('visibilitychange',()=>{if(!paired)return;if(document.hidden){acceptOffers=false;stopWaiting();signal({type:'disconnect'});close();update({connection:'suspended'});}else resume();});
+ setInterval(async()=>{
+ const current=pc;if(!current)return;
+ try{
+ raw({type:'ping',at:performance.now(),videoFrames:stats.framesDecoded||0});const reports=await current.getStats();if(current!==pc)return;let inbound,selected;
+ reports.forEach(r=>{if(r.type==='inbound-rtp'&&r.kind==='video')inbound=r;if(r.type==='candidate-pair'&&r.state==='succeeded'&&r.nominated)selected=r;});
+ if(inbound){
+ const now=performance.now(),frames=inbound.framesDecoded||0;if(frames>lastFrames){lastFrameAt=now;lastFrames=frames;}
+ stats={...stats,framesDecoded:frames,framesPerSecond:inbound.framesPerSecond||0,width:inbound.frameWidth||0,height:inbound.frameHeight||0,inputs:delivery.sent,ackedInputs:delivery.acked,state:current.connectionState,bytes:inbound.bytesReceived||0,stalled:state.source?state.source.capture==='stalled':!!lastFrameAt&&now-lastFrameAt>15000};
+ if(selected){const local=reports.get(selected.localCandidateId),remote=reports.get(selected.remoteCandidateId);stats.transport=local?.protocol||'';stats.local=local?.address||'';stats.remote=remote?.address||'';stats.candidateType=remote?.candidateType||'';}
+ window.CanvasLink.stats=stats;Native.diagnostics(JSON.stringify(stats));update({stats:{...stats}});
+ }
+ }catch{}
+ },1000);
+ Native.discover();Native.restore();Native.loadDraft();
+})();
diff --git a/integrations/canvaslink/android/res/drawable/ic_launcher_foreground.xml b/integrations/canvaslink/android/res/drawable/ic_launcher_foreground.xml
new file mode 100644
index 000000000..6ab56d856
--- /dev/null
+++ b/integrations/canvaslink/android/res/drawable/ic_launcher_foreground.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
diff --git a/integrations/canvaslink/android/res/drawable/ic_launcher_monochrome.xml b/integrations/canvaslink/android/res/drawable/ic_launcher_monochrome.xml
new file mode 100644
index 000000000..a483831b3
--- /dev/null
+++ b/integrations/canvaslink/android/res/drawable/ic_launcher_monochrome.xml
@@ -0,0 +1,10 @@
+
+
+
+
+
+
diff --git a/integrations/canvaslink/android/res/mipmap-anydpi-v26/ic_launcher.xml b/integrations/canvaslink/android/res/mipmap-anydpi-v26/ic_launcher.xml
new file mode 100644
index 000000000..51deb97dc
--- /dev/null
+++ b/integrations/canvaslink/android/res/mipmap-anydpi-v26/ic_launcher.xml
@@ -0,0 +1 @@
+
diff --git a/integrations/canvaslink/android/res/mipmap-anydpi-v33/ic_launcher.xml b/integrations/canvaslink/android/res/mipmap-anydpi-v33/ic_launcher.xml
new file mode 100644
index 000000000..3d1008cb4
--- /dev/null
+++ b/integrations/canvaslink/android/res/mipmap-anydpi-v33/ic_launcher.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
diff --git a/integrations/canvaslink/android/res/values/colors.xml b/integrations/canvaslink/android/res/values/colors.xml
new file mode 100644
index 000000000..e50c4c575
--- /dev/null
+++ b/integrations/canvaslink/android/res/values/colors.xml
@@ -0,0 +1 @@
+#121814
diff --git a/integrations/canvaslink/android/src/io/nexcore/canvaslink/AcceptanceInstrumentation.java b/integrations/canvaslink/android/src/io/nexcore/canvaslink/AcceptanceInstrumentation.java
new file mode 100644
index 000000000..1aa894c58
--- /dev/null
+++ b/integrations/canvaslink/android/src/io/nexcore/canvaslink/AcceptanceInstrumentation.java
@@ -0,0 +1,185 @@
+package io.nexcore.canvaslink;
+
+import android.app.Instrumentation;
+import android.app.Activity;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.SystemClock;
+import android.view.MotionEvent;
+import org.json.*;
+import java.util.concurrent.*;
+
+/** Local adb-only acceptance. Never logs pairing material or captured content. */
+public final class AcceptanceInstrumentation extends Instrumentation {
+ private Bundle arguments; private MainActivity activity;
+ void stage(String name){Bundle b=new Bundle();b.putString("stage",name);sendStatus(0,b);}
+ @Override public void onCreate(Bundle args){arguments=args;start();}
+ String js(String code) throws Exception {
+ CountDownLatch latch=new CountDownLatch(1);String[] out={"null"};
+ runOnMainSync(()->activity.web.evaluateJavascript(code,value->{out[0]=value;latch.countDown();}));
+ if(!latch.await(5,TimeUnit.SECONDS))throw new Exception("WebView evaluation timeout");return out[0];
+ }
+ void tap(String selector) throws Exception {
+ tap(selector,null);
+ }
+ void tap(String selector, String point) throws Exception {
+ boolean[] focused={false};runOnMainSync(()->focused[0]=activity.web.hasWindowFocus());
+ if(!focused[0])throw new Exception("Touch Activity is not foreground");
+ String coordinate="{x:r.x+r.width/2,y:r.y+r.height/2}";
+ if(point!=null){String[] xy=point.split(",");double x=Double.parseDouble(xy[0]),y=Double.parseDouble(xy[1]);if(x<0||x>1||y<0||y>1)throw new Exception("Invalid normalized point");coordinate="(()=>{const f=Math.min(r.width/e.videoWidth,r.height/e.videoHeight),w=e.videoWidth*f,h=e.videoHeight*f;return {x:r.x+(r.width-w)/2+w*"+x+",y:r.y+(r.height-h)/2+h*"+y+"}})()";}
+ String rect=js("(()=>{const e=document.querySelector("+JSONObject.quote(selector)+");e.scrollIntoView({block:'center',inline:'center'});const r=e.getBoundingClientRect(),p="+coordinate+";return {...p,dpr:devicePixelRatio,w:innerWidth,h:innerHeight}})()");
+ JSONObject p=new JSONObject(rect);int[] offset=new int[2];runOnMainSync(()->activity.web.getLocationOnScreen(offset));
+ if(p.getDouble("x")<0||p.getDouble("x")>=p.getDouble("w")||p.getDouble("y")<0||p.getDouble("y")>=p.getDouble("h"))throw new Exception("Touch target outside viewport: "+selector);
+ float x=(float)(p.getDouble("x")*p.getDouble("dpr"))+offset[0];
+ float y=(float)(p.getDouble("y")*p.getDouble("dpr"))+offset[1];
+ // CSS px and WebView device px differ by density, including viewport scaling.
+ long at=SystemClock.uptimeMillis();MotionEvent down=MotionEvent.obtain(at,at,MotionEvent.ACTION_DOWN,x,y,0);
+ MotionEvent up=MotionEvent.obtain(at,at+60,MotionEvent.ACTION_UP,x,y,0);
+ down.setSource(android.view.InputDevice.SOURCE_TOUCHSCREEN);up.setSource(android.view.InputDevice.SOURCE_TOUCHSCREEN);
+ if(!getUiAutomation().injectInputEvent(down,true)||!getUiAutomation().injectInputEvent(up,true))throw new Exception("Android rejected touch: "+selector);
+ down.recycle();up.recycle();
+ SystemClock.sleep(120);
+ }
+ void commitText(String text) throws Exception {
+ boolean[] committed={false};runOnMainSync(()->{
+ android.view.inputmethod.InputConnection input=activity.web.onCreateInputConnection(new android.view.inputmethod.EditorInfo());
+ if(input!=null){input.performContextMenuAction(android.R.id.selectAll);committed[0]=input.commitText(text,1);}
+ });
+ SystemClock.sleep(200);
+ if(!committed[0])throw new Exception("Android IME commit was rejected");
+ stage("android-ime-commit");
+ }
+ void menu(String id)throws Exception{tap("#menu-toggle");tap("#"+id);SystemClock.sleep(400);}
+ int decodedFrames()throws Exception{return new JSONObject(js("window.CanvasLink.stats")).optInt("framesDecoded");}
+ void waitVideoAfterTouch(int before)throws Exception{
+ for(int i=0;i<120;i++){if(decodedFrames()>before)return;SystemClock.sleep(100);}
+ throw new Exception("Decoded video did not advance after real remote touch");
+ }
+ String freshNativePoint()throws Exception{
+ java.io.File directory=activity.getExternalFilesDir(null);if(directory==null)throw new Exception("Owned external acceptance directory unavailable");
+ java.io.File target=new java.io.File(directory,"acceptance-target.json");stage("native-target-request");
+ for(int i=0;i<80&&!target.exists();i++)SystemClock.sleep(100);
+ if(!target.exists())throw new Exception("Fresh owned terminal target unavailable");
+ JSONObject p=new JSONObject(new String(java.nio.file.Files.readAllBytes(target.toPath()),java.nio.charset.StandardCharsets.UTF_8));target.delete();
+ return p.getDouble("x")+","+p.getDouble("y");
+ }
+ void waitTerminalKeyboard()throws Exception{
+ for(int i=0;i<60;i++){
+ boolean[] visible={false};runOnMainSync(()->{TerminalWebView view=(TerminalWebView)activity.web;visible[0]=view.terminalActive()&&(android.os.Build.VERSION.SDK_INT<30||view.getRootWindowInsets()!=null&&view.getRootWindowInsets().isVisible(android.view.WindowInsets.Type.ime()));});
+ if(visible[0]&&"true".equals(js("CanvasLinkInput.active()"))){SystemClock.sleep(400);return;}
+ SystemClock.sleep(100);
+ }
+ boolean[] nativeState={false,false};runOnMainSync(()->{nativeState[0]=((TerminalWebView)activity.web).terminalActive();nativeState[1]=activity.web.getRootWindowInsets()!=null&&activity.web.getRootWindowInsets().isVisible(android.view.WindowInsets.Type.ime());});
+ throw new Exception("Terminal keyboard inactive: native="+nativeState[0]+",visible="+nativeState[1]+",client="+js("JSON.stringify({active:CanvasLinkInput.active(),delivery:CanvasLinkClient.getState().delivery,notice:document.getElementById('stream-error').textContent,source:CanvasLinkClient.getState().source})"));
+ }
+ @Override public void onStart(){
+ Bundle result=new Bundle();
+ try{
+ stage("launch");
+ Intent intent=new Intent(getTargetContext(),MainActivity.class);intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+ getTargetContext().startActivity(intent);
+ for(int i=0;i<100&&MainActivity.active==null;i++)SystemClock.sleep(100);
+ activity=MainActivity.active;if(activity==null)throw new Exception("Activity launch timeout");stage("activity-ready");
+ for(int i=0;i<80&&!"true".equals(js("!!window.CanvasLink"));i++)SystemClock.sleep(100);
+ String host=arguments.getString("host"),pin=arguments.getString("pin");
+ boolean restoring="restore".equals(arguments.getString("mode"));
+ boolean discoveryFlow="true".equals(arguments.getString("discovery"));
+ if(!restoring){
+ if(pin==null)throw new Exception("pin argument required");
+ if(discoveryFlow){
+ String selected=null,port=arguments.getString("port");
+ for(int i=0;i<150&&selected==null;i++){
+ JSONArray computers=new JSONObject(js("window.CanvasLinkClient.getState()")).getJSONArray("computers");
+ for(int j=0;jc.id==="+JSONObject.quote(chosen)+")"));
+ tap("#computers button:nth-child("+(index+1)+")");SystemClock.sleep(400);
+ tap("#pin");SystemClock.sleep(200);commitText(pin);
+ if(!"true".equals(js("document.getElementById('pin').value.length===6")))throw new Exception("PIN IME input did not reach form; focused="+js("document.activeElement.id")+", length="+js("document.getElementById('pin').value.length"));
+ runOnMainSync(()->((android.view.inputmethod.InputMethodManager)activity.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(activity.web.getWindowToken(),0));SystemClock.sleep(400);
+ tap("#connect");stage("discovery-and-code-form");result.putBoolean("discoveryForm",true);
+ }else{
+ if(host==null)throw new Exception("host required without discovery");
+ js("window.CanvasLink.connectForTest("+JSONObject.quote(host)+","+JSONObject.quote(pin)+")");
+ }
+ }
+ stage("connecting");
+ // A static owned window legitimately sends one initial image. Confirm
+ // subsequent live updates after an actual remote action, below.
+ int minimumFrames=("native".equals(arguments.getString("mode"))||"settings".equals(arguments.getString("mode")))?1:9;
+ JSONObject stats=null;
+ for(int i=0;i<200;i++){
+ SystemClock.sleep(200);
+ try{stats=new JSONObject(js("window.CanvasLink.stats"));}catch(Exception ignored){}
+ if(stats!=null&&stats.optInt("framesDecoded")>=minimumFrames&&"connected".equals(stats.optString("state")))break;
+ }
+ if(stats==null||stats.optInt("framesDecoded")=4){complete=true;break;}
+ }
+ if(!complete)throw new Exception("Host did not finish all native input events");
+ stage("native-text-and-enter-sent");
+ if("true".equals(arguments.getString("snapshot")))SystemClock.sleep(4000);
+ if("true".equals(arguments.getString("controls"))){
+ String encoded=arguments.getString("proofDir64");
+ if(encoded==null)throw new Exception("Owned control proof directory required");
+ String directory=new String(android.util.Base64.decode(encoded,android.util.Base64.DEFAULT),java.nio.charset.StandardCharsets.UTF_8);
+ new NativeControlChecks(this).run(directory,result);
+ }
+ }
+ if("settings".equals(arguments.getString("mode")))new SettingsTouchChecks(this).run(result);
+ if(isFixture){
+ menu("fit");
+ if(!"true".equals(js("getComputedStyle(document.getElementById('video')).transform.startsWith('matrix(2')")))throw new Exception("Zoom control failed");
+ menu("fit");menu("mode");
+ if(!"true".equals(js("document.getElementById('mode').getAttribute('aria-pressed')==='true'")))throw new Exception("Trackpad mode failed");
+ menu("mode");result.putBoolean("zoomAndModeControls",true);
+ tap("#viewport");stage("touch-sent");waitTerminalKeyboard();
+ commitText("Проверка CanvasLink 42");
+ SystemClock.sleep(600);tap("[data-key=Enter]");
+ stage("text-and-key-sent");
+ JSONObject fixture=null;
+ for(int i=0;i<40;i++){
+ js("window.CanvasLink.requestFixture()");SystemClock.sleep(150);
+ try{fixture=new JSONObject(js("window.CanvasLink.fixture"));}catch(Exception ignored){}
+ if(fixture!=null&&fixture.optInt("clicks")>0&&fixture.optString("text").contains("Проверка CanvasLink 42")&&fixture.optJSONArray("keys").toString().contains("Enter"))break;
+ }
+ if(fixture==null||fixture.optInt("clicks")<1||!fixture.optString("text").contains("Проверка CanvasLink 42")||!fixture.optJSONArray("keys").toString().contains("Enter"))throw new Exception("Fixture input roundtrip failed: clicks="+(fixture==null?-1:fixture.optInt("clicks"))+", text="+(fixture!=null&&fixture.optString("text").contains("Проверка CanvasLink 42"))+", Enter="+(fixture!=null&&fixture.optJSONArray("keys").toString().contains("Enter")));
+ result.putBoolean("touchRoundtrip",true);result.putBoolean("unicodeTextRoundtrip",true);result.putBoolean("enterRoundtrip",true);
+ if("true".equals(arguments.getString("ux")))new DeviceUxChecks(this,activity).run(result);
+ }
+ if("true".equals(arguments.getString("draftCheck")))throw new Exception("Removed composer draft flow; use direct-input UX acceptance");
+ result.putString("stats",js("window.CanvasLink.stats"));result.putBoolean("fixture",isFixture);result.putBoolean("restored",restoring);result.putString("status","PASS");
+ finish(Activity.RESULT_OK,result);
+ }catch(Exception e){result.putString("status","FAIL");result.putString("error",e.getMessage());finish(Activity.RESULT_CANCELED,result);}
+ }
+}
diff --git a/integrations/canvaslink/android/src/io/nexcore/canvaslink/DeviceUxChecks.java b/integrations/canvaslink/android/src/io/nexcore/canvaslink/DeviceUxChecks.java
new file mode 100644
index 000000000..55bb43fe9
--- /dev/null
+++ b/integrations/canvaslink/android/src/io/nexcore/canvaslink/DeviceUxChecks.java
@@ -0,0 +1,89 @@
+package io.nexcore.canvaslink;
+
+import android.content.pm.ActivityInfo;
+import android.os.Bundle;
+import android.os.ParcelFileDescriptor;
+import android.os.SystemClock;
+import android.view.InputDevice;
+import android.view.KeyEvent;
+import android.view.MotionEvent;
+import android.view.inputmethod.InputConnection;
+import org.json.JSONObject;
+import java.io.FileInputStream;
+
+/** Additional adb-only checks on the owned fixture, never a user's terminal. */
+final class DeviceUxChecks {
+ final AcceptanceInstrumentation test; final MainActivity activity;
+ DeviceUxChecks(AcceptanceInstrumentation test,MainActivity activity){this.test=test;this.activity=activity;}
+ boolean value(String expression)throws Exception{return "true".equals(test.js(expression));}
+ void require(boolean ok,String message)throws Exception{if(!ok)throw new Exception(message);}
+ void until(String expression,int timeout,String failure)throws Exception{
+ long end=SystemClock.uptimeMillis()+timeout;
+ while(SystemClock.uptimeMillis(){const r=document.getElementById('viewport').getBoundingClientRect();return {x:r.x+r.width*"+x+",y:r.y+r.height*"+y+",d:devicePixelRatio}})()"));
+ int[] origin=new int[2];test.runOnMainSync(()->activity.web.getLocationOnScreen(origin));
+ return new float[]{(float)(r.getDouble("x")*r.getDouble("d"))+origin[0],(float)(r.getDouble("y")*r.getDouble("d"))+origin[1]};
+ }
+ void motion(long down,int action,float[][] coordinates)throws Exception{
+ MotionEvent.PointerProperties[] properties=new MotionEvent.PointerProperties[coordinates.length];
+ MotionEvent.PointerCoords[] points=new MotionEvent.PointerCoords[coordinates.length];
+ for(int i=0;i{const v=document.getElementById('viewport').getBoundingClientRect(),bar=document.getElementById('controls').getBoundingClientRect(),rows=[...document.querySelectorAll('#controls button')].map(e=>e.getBoundingClientRect().top);return Math.abs(v.width-innerWidth)<2&&Math.abs(v.height+56-innerHeight)<2&&bar.height===56&&new Set(rows).size===1&&!document.getElementById('compose');})()"),"Direct workspace geometry failed with real IME");
+ }
+ void rotate(int orientation)throws Exception{
+ test.runOnMainSync(()->activity.setRequestedOrientation(orientation));
+ until(orientation==ActivityInfo.SCREEN_ORIENTATION_PORTRAIT?"screen.height>screen.width":"screen.width>screen.height",6000,"Android orientation did not change");SystemClock.sleep(500);
+ }
+ void run(Bundle result)throws Exception{
+ test.stage("ux-gestures");test.menu("reset-view");
+ test.js("window.__gestureAudit=[];for(const type of ['pointerdown','pointerup','pointercancel','lostpointercapture','canvaslink:pointer'])document.addEventListener(type,e=>{const a=window.__gestureAudit;a.push({type,id:e.pointerId,target:e.target?.id,action:e.detail?.action});if(a.length>40)a.shift();},true)");
+ int before=clicks();drag(false,false);int observed=clicks();require(observed==before+1,"Direct drag press mismatch before="+before+", after="+observed+", state="+test.js("JSON.stringify({pending:CanvasLinkClient.getState().pending,ime:CanvasLinkInput.active(),focus:document.activeElement.id,mode:document.getElementById('mode').getAttribute('aria-pressed'),events:window.__gestureAudit})"));
+ before=clicks();drag(false,true);test.tap("#video","0.5,0.5");require(clicks()==before+2,"Cancellation left held button or duplicate tap");result.putBoolean("nativeDragAndCancel",true);
+ test.menu("mode");before=clicks();int acks=acked();drag(false,false);require(clicks()==before&&value("!document.getElementById('local-cursor').hidden"),"Trackpad movement clicked or had no cursor");until("CanvasLink.stats.ackedInputs>"+acks,4000,"Trackpad move missing");
+ before=clicks();drag(true,false);require(clicks()==before+1,"Hold-drag press count wrong");test.menu("reset-view");before=clicks();acks=acked();pair(false);require(clicks()==before,"Scroll created click");until("CanvasLink.stats.ackedInputs>"+acks,4000,"Native scroll missing");result.putBoolean("nativeTrackpadAndScroll",true);
+ test.menu("mode");before=clicks();pair(true);require(value("new DOMMatrix(getComputedStyle(document.getElementById('video')).transform).a>1.25"),"Pinch did not zoom");require(clicks()==before,"Pinch ghost click");test.menu("reset-view");result.putBoolean("nativePinchAndFit",true);
+ test.stage("ux-direct-ime");test.tap("#video","0.5,0.5");test.waitTerminalKeyboard();
+ int oldLength=fixture().getString("text").length();boolean[] accepted={false};
+ test.runOnMainSync(()->{InputConnection retired=activity.web.onCreateInputConnection(new android.view.inputmethod.EditorInfo());InputConnection input=activity.web.onCreateInputConnection(new android.view.inputmethod.EditorInfo());accepted[0]=input!=null&&!retired.commitText("STALE",1)&&input.setComposingText("日本🙂X",1)&&input.deleteSurroundingText(1,0)&&input.deleteSurroundingTextInCodePoints(1,0)&&((android.view.inputmethod.BaseInputConnection)input).getEditable().toString().equals("日本")&&input.commitText("日本語🙂",1)&&input.finishComposingText();if(input!=null){input.deleteSurroundingText(1,0);input.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_ENTER));input.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP,KeyEvent.KEYCODE_ENTER));}});
+ require(accepted[0],"Native composition/commit failed");SystemClock.sleep(500);JSONObject remote=fixture();require(remote.getString("text").substring(oldLength).equals("日本語"),"Composition was duplicated or lost after emoji Backspace");require(remote.getJSONArray("keys").toString().contains("Backspace"),"Native deletion missing");result.putBoolean("directCompositionUnicodeDeleteEnter",true);
+ int unchanged=acked();test.runOnMainSync(()->((TerminalWebView)activity.web).paste(new String(new char[8001]).replace('\0','x')));until("document.getElementById('input-status').textContent.includes('8000')",4000,"Oversized paste feedback missing");require(value("CanvasLinkClient.getState().connection==='connected'&&CanvasLinkInput.active()"),"Oversized paste interrupted terminal connection");require(acked()==unchanged,"Oversized paste sent remote input");result.putBoolean("staleConnectionCodePointDeleteOversizedPaste",true);
+ int previous=activity.getRequestedOrientation();try{for(int orientation:new int[]{ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE}){rotate(orientation);test.waitTerminalKeyboard();workspaceFits();}}finally{test.runOnMainSync(()->activity.setRequestedOrientation(previous));SystemClock.sleep(700);}result.putBoolean("singleRowRealImeBothOrientations",true);
+ shell("input keyevent KEYCODE_BACK");until("!CanvasLinkInput.active()",4000,"Android Back did not retire terminal input");test.tap("#video","0.5,0.5");test.waitTerminalKeyboard();result.putBoolean("keyboardBackDismissAndRetap",true);
+ test.stage("ux-background");int hostLength=fixture().getString("text").length();shell("input keyevent KEYCODE_HOME");until("document.hidden&&['suspended','reconnecting'].includes(CanvasLinkClient.getState().connection)",8000,"Background not suspended");shell("am start -n io.nexcore.canvaslink/.MainActivity");until("!document.hidden&&CanvasLinkClient.getState().connection==='connected'&&CanvasLink.stats.framesDecoded>8",30000,"Foreground video missing");require(fixture().getString("text").length()==hostLength,"Background replayed text");require(value("!CanvasLinkInput.active()"),"Old native input owner survived background");result.putBoolean("backgroundNoReplay",true);
+ test.stage("ux-wifi-loss");try{shell("svc wifi disable");until("CanvasLinkClient.getState().connection!=='connected'",20000,"Wi-Fi loss not detected");require(value("!CanvasLinkInput.active()"),"Offline IME not stopped");}finally{shell("svc wifi enable");}until("CanvasLinkClient.getState().connection==='connected'&&CanvasLink.stats.framesDecoded>8",40000,"Wi-Fi video recovery missing");require(fixture().getString("text").length()==hostLength,"Wi-Fi recovery replayed text");result.putBoolean("wifiLossRecoveryNoReplay",true);test.stage("ux-complete");
+ }
+}
diff --git a/integrations/canvaslink/android/src/io/nexcore/canvaslink/GraphicsChecks.java b/integrations/canvaslink/android/src/io/nexcore/canvaslink/GraphicsChecks.java
new file mode 100644
index 000000000..a071f4b5b
--- /dev/null
+++ b/integrations/canvaslink/android/src/io/nexcore/canvaslink/GraphicsChecks.java
@@ -0,0 +1,37 @@
+package io.nexcore.canvaslink;
+
+import android.os.Bundle;
+import android.os.SystemClock;
+import org.json.JSONArray;
+
+/** ADB-only visual acceptance; all view controls use real Android touches. */
+final class GraphicsChecks {
+ final AcceptanceInstrumentation test;
+ GraphicsChecks(AcceptanceInstrumentation test){this.test=test;}
+ void until(String expression,String error)throws Exception{
+ long end=SystemClock.uptimeMillis()+12000;
+ while(SystemClock.uptimeMillis()f.family==='Onest'&&f.status==='loaded')","Bundled Onest font was not consumed by WebView");
+ until("document.getElementById('view-toggle-label').textContent==='Весь Canvas'&&!!CanvasLinkClient.getState().source?.terminalView","Initial terminal view did not follow source geometry");
+ if(!"false".equals(test.js("CanvasLinkInput.active()")))throw new Exception("Visual framing must not start terminal input");
+ until("(()=>{const s=CanvasLinkClient.getState().source.terminalView,e=document.getElementById('video'),r=e.getBoundingClientRect(),v=document.getElementById('viewport').getBoundingClientRect(),k=Math.min(r.width/e.videoWidth,r.height/e.videoHeight),left=r.left+(r.width-e.videoWidth*k)/2+s.rect.x*e.videoWidth*k,top=r.top+(r.height-e.videoHeight*k)/2+s.rect.y*e.videoHeight*k;return left>=v.left-2&&top>=v.top-2&&left+s.rect.width*e.videoWidth*k<=v.right+2&&top+s.rect.height*e.videoHeight*k<=v.bottom+2;})()","Initial framing cuts off the selected terminal");
+ result.putBoolean("automaticTerminalViewWithoutIme",true);result.putBoolean("bundledFontLoaded",true);
+ test.stage("graphics-terminal-view-ready");SystemClock.sleep(700);
+ int sent=Integer.parseInt(test.js("CanvasLink.stats.inputs||0"));
+ test.tap("#view-toggle");
+ until("document.getElementById('zoom-label').textContent==='100%'","Overview button did not restore Canvas");
+ SystemClock.sleep(1200);
+ if(!"100%".equals(new JSONArray("["+test.js("document.getElementById('zoom-label').textContent")+"]").getString(0)))throw new Exception("Source health overrode explicit overview");
+ test.stage("graphics-overview-ready");SystemClock.sleep(700);test.tap("#view-toggle");
+ until("document.getElementById('view-toggle-label').textContent==='Весь Canvas'","Terminal button did not restore framing");
+ if(!"false".equals(test.js("CanvasLinkInput.active()"))||Integer.parseInt(test.js("CanvasLink.stats.inputs||0"))!=sent)throw new Exception("Local view button sent remote input");
+ result.putBoolean("viewToggleTouchRoundtripWithoutRemoteInput",true);
+ String encoded=new JSONArray("["+test.js("(()=>{const v=document.getElementById('video'),c=document.createElement('canvas');c.width=v.videoWidth;c.height=v.videoHeight;c.getContext('2d').drawImage(v,0,0);return c.toDataURL('image/png').split(',')[1];})()")+"]").getString(0);
+ byte[] frame=android.util.Base64.decode(encoded,android.util.Base64.DEFAULT);
+ java.nio.file.Files.write(new java.io.File(MainActivity.active.getExternalFilesDir(null),"graphics-decoded-frame.png").toPath(),frame);
+ result.putBoolean("decodedVideoFrameSavedPrivately",true);test.stage("graphics-decoded-frame-ready");SystemClock.sleep(500);
+ }
+}
diff --git a/integrations/canvaslink/android/src/io/nexcore/canvaslink/MainActivity.java b/integrations/canvaslink/android/src/io/nexcore/canvaslink/MainActivity.java
new file mode 100644
index 000000000..7e55c0e01
--- /dev/null
+++ b/integrations/canvaslink/android/src/io/nexcore/canvaslink/MainActivity.java
@@ -0,0 +1,289 @@
+package io.nexcore.canvaslink;
+
+import android.app.Activity;
+import android.os.Bundle;
+import android.os.Build;
+import android.net.ConnectivityManager;
+import android.net.Network;
+import android.net.NetworkCapabilities;
+import android.net.NetworkRequest;
+import android.net.LinkProperties;
+import android.net.RouteInfo;
+import android.net.nsd.NsdManager;
+import android.net.nsd.NsdServiceInfo;
+import android.net.wifi.WifiManager;
+import android.webkit.*;
+import android.view.WindowManager;
+import android.util.Log;
+import org.json.*;
+import java.io.*;
+import java.net.*;
+import java.nio.charset.StandardCharsets;
+import java.security.SecureRandom;
+import java.util.*;
+import java.util.concurrent.*;
+import javax.crypto.*;
+import javax.crypto.spec.*;
+
+public final class MainActivity extends Activity {
+ static volatile MainActivity active;
+ WebView web;
+ private final ScheduledExecutorService network = Executors.newSingleThreadScheduledExecutor();
+ private final SecureRandom random = new SecureRandom();
+ private NsdManager nsd; private NsdManager.DiscoveryListener discovery;
+ private WifiManager.MulticastLock multicast;
+ private final Map found = new HashMap<>();
+ private final ArrayDeque resolving = new ArrayDeque<>();
+ private final android.os.Handler ui = new android.os.Handler(android.os.Looper.getMainLooper());
+ private boolean resolveBusy=false; private int discoveryEpoch=0;
+ private final ExecutorService storage=Executors.newSingleThreadExecutor();
+ private SessionVault drafts;
+ private String base, id; private byte[] key; private long sent=0, received=0;
+ private long reserved=0; private SessionVault vault;
+ private ScheduledFuture> polling; private int errors=0; private long networkFailureAt=0;
+ private ConnectivityManager connectivity; private ConnectivityManager.NetworkCallback localNetworks;
+ private volatile Network localNetwork; private String localAddresses=""; private volatile boolean destroyed=false;
+ volatile String acceptance = "", diagnostics = "{}";
+ @Override public void onCreate(Bundle saved) {
+ super.onCreate(saved);
+ connectivity=(ConnectivityManager)getSystemService(CONNECTIVITY_SERVICE);
+ watchLocalNetworks();
+ getWindow().setStatusBarColor(0xff353442); getWindow().setNavigationBarColor(0xff353442);
+ web = new TerminalWebView(this); setContentView(web);
+ web.setBackgroundColor(0xff353442);
+ WebSettings s=web.getSettings(); s.setJavaScriptEnabled(true); s.setDomStorageEnabled(false);
+ s.setAllowFileAccess(false); s.setAllowContentAccess(false); s.setMixedContentMode(WebSettings.MIXED_CONTENT_NEVER_ALLOW);
+ s.setMediaPlaybackRequiresUserGesture(false); s.setSupportZoom(false);
+ web.setWebChromeClient(new WebChromeClient() {
+ @Override public boolean onConsoleMessage(ConsoleMessage m) {
+ if (m.messageLevel()==ConsoleMessage.MessageLevel.ERROR) Log.e("CanvasLink", "Web client error at line " + m.lineNumber());
+ return true;
+ }
+ @Override public void onPermissionRequest(PermissionRequest r) { r.deny(); }
+ });
+ web.setWebViewClient(new WebViewClient() {
+ @Override public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
+ android.net.Uri u=request.getUrl();
+ if (!"https".equals(u.getScheme()) || !"appassets.androidplatform.net".equals(u.getHost()) || !u.getPath().startsWith("/client/")) return blocked();
+ String file=u.getPath().substring(8);
+ if (!Arrays.asList("index.html","client.js","style.css","delivery.js","transport.js","gestures.js","direct-input.js","onest.ttf").contains(file)) return blocked();
+ try { return new WebResourceResponse(file.endsWith(".js")?"application/javascript":file.endsWith(".css")?"text/css":file.endsWith(".ttf")?"font/ttf":"text/html", "UTF-8", getAssets().open(file)); }
+ catch(Exception e) { return blocked(); }
+ }
+ @Override public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) { return true; }
+ });
+ web.addJavascriptInterface(new Bridge(), "Native");
+ web.loadUrl("https://appassets.androidplatform.net/client/index.html");
+ nsd=(NsdManager)getSystemService(NSD_SERVICE);
+ vault=new SessionVault(this);drafts=new SessionVault(this,"draft");
+ synchronized(MainActivity.class){active=this;}
+ }
+ private static WebResourceResponse blocked() { return new WebResourceResponse("text/plain","UTF-8",403,"Blocked",Collections.emptyMap(),new ByteArrayInputStream(new byte[0])); }
+ private void emit(String type, Object value) {
+ if(destroyed)return;
+ JSONObject event=new JSONObject(); try { event.put("type",type); event.put("value",value); }catch(JSONException ignored){}
+ runOnUiThread(() -> {if(!destroyed)web.evaluateJavascript("window.CanvasLink&&window.CanvasLink.receive("+event.toString()+")",null);});
+ }
+ private void watchLocalNetworks(){
+ localNetworks=new ConnectivityManager.NetworkCallback(){
+ private void refresh(){if(!destroyed)network.execute(()->{if(base==null||id==null)return;try{selectLocalNetwork(new URL(base));}catch(Exception e){emit("network",e.getMessage());}});}
+ @Override public void onAvailable(Network value){refresh();}
+ @Override public void onCapabilitiesChanged(Network value,NetworkCapabilities capabilities){refresh();}
+ @Override public void onLinkPropertiesChanged(Network value,LinkProperties properties){refresh();}
+ @Override public void onLost(Network value){if(value.equals(localNetwork))emit("network-changed","offline");refresh();}
+ };
+ try{connectivity.registerNetworkCallback(localNetworkRequest(),localNetworks,ui);}
+ catch(SecurityException e){localNetworks=null;}
+ }
+ private NetworkRequest localNetworkRequest(){
+ return new NetworkRequest.Builder().addTransportType(NetworkCapabilities.TRANSPORT_WIFI)
+ .addTransportType(NetworkCapabilities.TRANSPORT_ETHERNET).addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build();
+ }
+ private synchronized Network selectLocalNetwork(URL url) throws Exception {
+ if(destroyed)throw new IOException("Приложение закрыто");
+ InetAddress address=InetAddress.getByName(url.getHost());
+ if(address.isLoopbackAddress())return null;
+ Network selected=null,fallback=null;String addresses="",fallbackAddresses="";int prefix=0,fallbacks=0;
+ for(Network candidate:connectivity.getAllNetworks()){
+ NetworkCapabilities capabilities=connectivity.getNetworkCapabilities(candidate);
+ if(capabilities==null||!capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN)||
+ !(capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)||capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET)))continue;
+ LinkProperties properties=connectivity.getLinkProperties(candidate);if(properties==null)continue;
+ boolean defaultRoute=false;
+ for(RouteInfo route:properties.getRoutes()){
+ int bits=route.getDestination().getPrefixLength();
+ if(bits==0&&route.getDestination().getAddress() instanceof Inet4Address)defaultRoute=true;
+ if(bits>0&&(bits>prefix||bits==prefix&&candidate.equals(localNetwork))&&route.getDestination().contains(address)){
+ selected=candidate;prefix=bits;addresses=properties.getLinkAddresses().toString();
+ }
+ }
+ if(defaultRoute){fallbacks++;fallback=candidate;fallbackAddresses=properties.getLinkAddresses().toString();}
+ }
+ // A sole physical LAN can reach a neighbouring private subnet via its router.
+ if(selected==null&&fallbacks==1){selected=fallback;addresses=fallbackAddresses;}
+ if(selected==null){
+ if(localNetwork!=null){localNetwork=null;emit("network-changed","offline");}
+ // Keep the old process binding on loss: never fall back to cellular/VPN.
+ throw new IOException("Нет локального маршрута к ПК. Подключите устройства к одной сети Wi-Fi и разрешите доступ к локальной сети в VPN.");
+ }
+ if(!selected.equals(localNetwork)||!addresses.equals(localAddresses)){
+ if(localNetwork!=null)emit("network-changed","offline");
+ try{synchronized(MainActivity.class){if(destroyed||active!=this||!connectivity.bindProcessToNetwork(selected))throw new SecurityException();}}
+ catch(SecurityException e){throw new IOException("Не удалось выбрать локальную сеть. Разрешите CanvasLink доступ к локальной сети в настройках VPN.",e);}
+ localNetwork=selected;localAddresses=addresses;
+ // WebRTC runs in WebView; process binding is best effort for its sockets.
+ if(id!=null)emit("network-changed","ready");
+ }
+ return selected;
+ }
+ private String localBase(String host) throws Exception {
+ if (!host.matches("[0-9.]+:[0-9]{1,5}")) throw new Exception("Нужен локальный IPv4-адрес и порт");
+ String[] hp=host.split(":"); String[] parts=hp[0].split("\\.");
+ if(parts.length!=4) throw new Exception("Неверный адрес");
+ int[] a=new int[4]; for(int i=0;i<4;i++){a[i]=Integer.parseInt(parts[i]); if(a[i]<0||a[i]>255)throw new Exception("Неверный адрес");}
+ boolean local=a[0]==10||a[0]==127||(a[0]==192&&a[1]==168)||(a[0]==172&&a[1]>=16&&a[1]<=31)||(a[0]==169&&a[1]==254);
+ int p=Integer.parseInt(hp[1]); if(!local||p<1024||p>65535) throw new Exception("Разрешена только локальная сеть");
+ return "http://"+hp[0]+":"+p;
+ }
+ private JSONObject post(String route, JSONObject payload) throws Exception {
+ URL url=new URL(base+route);Network selected=selectLocalNetwork(url);
+ HttpURLConnection c=(HttpURLConnection)(selected==null?url.openConnection(Proxy.NO_PROXY):selected.openConnection(url,Proxy.NO_PROXY));
+ c.setConnectTimeout(4000);c.setReadTimeout(5000);c.setInstanceFollowRedirects(false);
+ c.setRequestMethod("POST");c.setRequestProperty("Content-Type","application/json");c.setDoOutput(true);
+ byte[] bytes=payload.toString().getBytes(StandardCharsets.UTF_8);c.setFixedLengthStreamingMode(bytes.length);
+ try {
+ try(OutputStream out=c.getOutputStream()){out.write(bytes);}
+ if(c.getResponseCode()!=200) throw new Exception("Компьютер отклонил подключение. Проверьте код и срок его действия.");
+ try(InputStream in=c.getInputStream();ByteArrayOutputStream out=new ByteArrayOutputStream()){
+ byte[] buffer=new byte[4096];int n;while((n=in.read(buffer))!=-1){out.write(buffer,0,n);if(out.size()>150000)throw new Exception("Ответ слишком большой");}
+ return new JSONObject(out.toString("UTF-8"));
+ }
+ }catch(IOException e){throw new IOException("Нет связи с ПК по локальной сети. Проверьте Wi-Fi и разрешение локальных подключений в VPN.",e);}
+ finally{c.disconnect();}
+ }
+ private JSONObject exchange(JSONObject value) throws Exception {
+ if(id==null||key==null)throw new Exception("Нет сопряжения");
+ if(sent+1>=reserved)reserve();
+ long seq=++sent;byte[] iv=new byte[12];random.nextBytes(iv);
+ Cipher cipher=Cipher.getInstance("AES/GCM/NoPadding");
+ cipher.init(Cipher.ENCRYPT_MODE,new SecretKeySpec(key,"AES"),new GCMParameterSpec(128,iv));
+ cipher.updateAAD(Srp.utf8("CanvasLink/1/"+id+"/"+seq+"/request"));
+ JSONObject packet=new JSONObject().put("id",id).put("seq",seq).put("iv",Srp.hex(iv))
+ .put("data",android.util.Base64.encodeToString(cipher.doFinal(Srp.utf8(value.toString())),android.util.Base64.NO_WRAP));
+ JSONObject response=post("/channel",packet);
+ long next=response.getLong("seq");if(!id.equals(response.getString("id"))||next!=seq||next<=received)throw new SecurityException("Повторный или неподтверждённый ответ");
+ String nonce=response.getString("iv");if(!nonce.matches("[0-9a-f]{24}"))throw new SecurityException("Неверный пакет");
+ cipher.init(Cipher.DECRYPT_MODE,new SecretKeySpec(key,"AES"),new GCMParameterSpec(128,Srp.bytes(nonce)));
+ cipher.updateAAD(Srp.utf8("CanvasLink/1/"+id+"/"+next+"/response"));
+ byte[] plain=cipher.doFinal(android.util.Base64.decode(response.getString("data"),android.util.Base64.NO_WRAP));
+ received=next;return new JSONObject(new String(plain,StandardCharsets.UTF_8));
+ }
+ private void connect(String host,String pin){
+ network.execute(()->{try{
+ if(polling!=null)polling.cancel(false);id=null;key=null;
+ base=localBase(host);if(!pin.matches("[0-9]{6}"))throw new Exception("Введите шесть цифр");
+ Srp srp=new Srp();
+ JSONObject challenge=post("/pair/start",new JSONObject().put("A",srp.publicHex()).put("name",(Build.MANUFACTURER+" "+Build.MODEL)));
+ if(!Srp.USER.equals(challenge.getString("user")))throw new SecurityException("Неверный протокол");
+ Srp.Session result=srp.derive(pin,challenge.getString("salt"),challenge.getString("B"));
+ JSONObject finish=post("/pair/finish",new JSONObject().put("id",challenge.getString("id")).put("proof",Srp.hex(result.proof)));
+ result.verify(finish.getString("proof"));
+ String nextId=finish.getString("id");if(!nextId.matches("[0-9a-f]{32}"))throw new SecurityException("Неверный идентификатор");
+ id=nextId;key=result.channelKey;sent=0;received=0;reserved=0;errors=0;reserve();
+ emit("paired",new JSONObject().put("host",host));
+ runOnUiThread(()->getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
+ startPolling();
+ }catch(Exception e){emit("error",e.getMessage());}});
+ }
+ private void reserve() throws Exception {
+ reserved=sent+10000;
+ vault.save(new JSONObject().put("host",base.substring(7)).put("id",id).put("key",Srp.hex(key)).put("counter",reserved));
+ }
+ private void startPolling(){
+ if(polling!=null)polling.cancel(false);
+ networkFailureAt=0;errors=0;
+ polling=network.scheduleWithFixedDelay(()->{try{
+ JSONObject response=exchange(new JSONObject().put("type","poll"));boolean recovered=errors>0;errors=0;networkFailureAt=0;
+ if(recovered)emit("network-restored",true);
+ JSONArray messages=response.getJSONArray("messages");for(int i=0;i=60000){polling.cancel(false);vault.clear();id=null;key=null;emit("disconnected",true);emit("error","Соединение потеряно. Создайте новый код на компьютере.");}}},0,200,TimeUnit.MILLISECONDS);
+ }
+ public final class Bridge {
+ @JavascriptInterface public boolean saveDraft(String text){if(text.length()>8000)return false;try{synchronized(drafts){drafts.save(new JSONObject().put("text",text));}return true;}catch(Exception e){emit("error","Не удалось сохранить черновик");return false;}}
+ @JavascriptInterface public void loadDraft(){storage.execute(()->{try{JSONObject saved=drafts.load();emit("draft",saved==null?"":saved.optString("text"));}catch(Exception ignored){}});}
+ @JavascriptInterface public void showKeyboard(String token){runOnUiThread(()->((TerminalWebView)web).openTerminal(token));}
+ @JavascriptInterface public void terminalKey(String key,String modifiers){runOnUiThread(()->((TerminalWebView)web).key(key,modifiers));}
+ @JavascriptInterface public void paste(){runOnUiThread(()->{android.content.ClipboardManager clipboard=(android.content.ClipboardManager)getSystemService(CLIPBOARD_SERVICE);if(clipboard.hasPrimaryClip()&&clipboard.getPrimaryClip().getItemCount()>0){CharSequence value=clipboard.getPrimaryClip().getItemAt(0).coerceToText(MainActivity.this);((TerminalWebView)web).paste(value==null?"":value.toString());}else ((TerminalWebView)web).paste("");});}
+ @JavascriptInterface public void hideKeyboard(){runOnUiThread(()->((TerminalWebView)web).closeTerminal());}
+ @JavascriptInterface public void connect(String host,String pin){MainActivity.this.connect(host,pin);}
+ @JavascriptInterface public void signal(String json){
+ if(json.length()>90000)return;
+ network.execute(()->{try{exchange(new JSONObject().put("type","signal").put("message",new JSONObject(json)));}catch(Exception e){emit("error",e.getMessage());}});
+ }
+ @JavascriptInterface public void discover(){runOnUiThread(()->startDiscovery());}
+ @JavascriptInterface public void restore(){network.execute(()->{try{
+ JSONObject saved=vault.load();if(saved==null)return;
+ base=localBase(saved.getString("host"));id=saved.getString("id");key=Srp.bytes(saved.getString("key"));
+ if(!id.matches("[0-9a-f]{32}")||key.length!=32)throw new Exception("Invalid saved pairing");
+ sent=saved.getLong("counter");received=0;reserve();
+ exchange(new JSONObject().put("type","signal").put("message",new JSONObject().put("type","ping")));
+ emit("paired",new JSONObject().put("host",saved.getString("host")));startPolling();
+ runOnUiThread(()->getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));
+ }catch(Exception e){vault.clear();id=null;key=null;emit("network","Введите новый код подключения на компьютере.");}});}
+ @JavascriptInterface public void disconnect(){network.execute(()->{try{exchange(new JSONObject().put("type","revoke"));}catch(Exception ignored){} if(polling!=null)polling.cancel(false);id=null;key=null;vault.clear();emit("disconnected",true);});runOnUiThread(()->getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON));}
+ @JavascriptInterface public void diagnostics(String json){if(json.length()<2000){diagnostics=json;Log.i("CanvasLink", "STATS "+json);}}
+ @JavascriptInterface public void acceptance(String json){if(json.length()<2000)acceptance=json;}
+ }
+ private void resolveNext(final int epoch){
+ if(epoch!=discoveryEpoch||resolveBusy||resolving.isEmpty())return;
+ final NsdServiceInfo service=resolving.remove();resolveBusy=true;
+ nsd.resolveService(service,new NsdManager.ResolveListener(){
+ public void onResolveFailed(NsdServiceInfo s,int c){ui.post(()->{if(epoch!=discoveryEpoch)return;resolveBusy=false;emit("discovery","resolving-failed");ui.postDelayed(()->resolveNext(epoch),500);});}
+ public void onServiceResolved(NsdServiceInfo s){ui.post(()->{
+ if(epoch!=discoveryEpoch)return;resolveBusy=false;
+ try{
+ String address=s.getHost().getHostAddress()+":"+s.getPort();
+ // Host advertises a private IPv4 hint for API26-32 resolvers that
+ // return only one IPv6 address. This is discovery, never authority:
+ // localBase and the existing SRP proof remain mandatory.
+ byte[] hint=s.getAttributes().get("ipv4");
+ if(!(s.getHost() instanceof Inet4Address)&&hint!=null)address=new String(hint,StandardCharsets.UTF_8)+":"+s.getPort();
+ localBase(address);found.put(s.getServiceName(),address);
+ emit("discovered",new JSONObject().put("id",s.getServiceName()).put("name",s.getServiceName()).put("host",address));
+ }catch(Exception e){emit("discovery","unsupported-address");}
+ resolveNext(epoch);
+ });}
+ });
+ }
+ private void startDiscovery(){
+ if(discovery!=null){
+ try{nsd.stopServiceDiscovery(discovery);}catch(Exception ignored){}
+ discovery=null;discoveryEpoch++;resolving.clear();resolveBusy=false;
+ for(String name:found.keySet())emit("lost",name);found.clear();
+ ui.postDelayed(()->startDiscovery(),500);return;
+ }
+ final int epoch=++discoveryEpoch;
+ WifiManager wifi=(WifiManager)getApplicationContext().getSystemService(WIFI_SERVICE);
+ if(multicast==null){multicast=wifi.createMulticastLock("CanvasLink discovery");multicast.setReferenceCounted(false);}
+ if(!multicast.isHeld())multicast.acquire();
+ discovery=new NsdManager.DiscoveryListener(){
+ public void onDiscoveryStarted(String t){if(epoch==discoveryEpoch)emit("discovery","searching");}
+ public void onDiscoveryStopped(String t){}
+ public void onStartDiscoveryFailed(String t,int c){ui.post(()->{if(epoch!=discoveryEpoch)return;discovery=null;emit("discovery","unavailable");if(multicast.isHeld())multicast.release();});}
+ public void onStopDiscoveryFailed(String t,int c){}
+ public void onServiceLost(NsdServiceInfo service){ui.post(()->{if(epoch!=discoveryEpoch)return;found.remove(service.getServiceName());resolving.removeIf(s->s.getServiceName().equals(service.getServiceName()));emit("lost",service.getServiceName());});}
+ public void onServiceFound(NsdServiceInfo service){ui.post(()->{if(epoch!=discoveryEpoch||!service.getServiceName().startsWith("CanvasLink "))return;resolving.add(service);resolveNext(epoch);});}
+ };
+ try{
+ if(Build.VERSION.SDK_INT>=33)nsd.discoverServices("_canvaslink._tcp.",NsdManager.PROTOCOL_DNS_SD,localNetworkRequest(),getMainExecutor(),discovery);
+ else nsd.discoverServices("_canvaslink._tcp.",NsdManager.PROTOCOL_DNS_SD,discovery);
+ }catch(Exception e){discovery=null;emit("discovery","unavailable");}
+ }
+ @Override protected void onDestroy(){
+ synchronized(MainActivity.class){destroyed=true;if(active==this){active=null;connectivity.bindProcessToNetwork(null);}}
+ if(localNetworks!=null)try{connectivity.unregisterNetworkCallback(localNetworks);}catch(Exception ignored){}
+ if(discovery!=null)try{nsd.stopServiceDiscovery(discovery);}catch(Exception ignored){}
+ if(multicast!=null&&multicast.isHeld())multicast.release();
+ discoveryEpoch++;ui.removeCallbacksAndMessages(null);storage.shutdown();network.shutdownNow();web.destroy();super.onDestroy();
+ }
+}
diff --git a/integrations/canvaslink/android/src/io/nexcore/canvaslink/NativeControlChecks.java b/integrations/canvaslink/android/src/io/nexcore/canvaslink/NativeControlChecks.java
new file mode 100644
index 000000000..9565b1eac
--- /dev/null
+++ b/integrations/canvaslink/android/src/io/nexcore/canvaslink/NativeControlChecks.java
@@ -0,0 +1,96 @@
+package io.nexcore.canvaslink;
+
+import android.os.Bundle;
+import android.os.SystemClock;
+
+/** ADB-only controls against the controller's disposable CanvasTTY terminal. */
+final class NativeControlChecks {
+ final AcceptanceInstrumentation test;
+ NativeControlChecks(AcceptanceInstrumentation test){this.test=test;}
+ void until(String expression,String error)throws Exception{
+ long end=SystemClock.uptimeMillis()+10000;
+ while(SystemClock.uptimeMillis()"+before,"Control was not acknowledged: "+key);
+ test.waitTerminalKeyboard();
+ }
+ void text(String value)throws Exception{
+ if(!"true".equals(test.js("CanvasLinkInput.active()")))throw new Exception("Direct IME must remain active during terminal editing");
+ int before=Integer.parseInt(test.js("CanvasLink.stats.ackedInputs"));test.commitText(value);
+ until("CanvasLink.stats.ackedInputs>"+before+"&&CanvasLinkClient.getState().pending===0","Direct text was not acknowledged");
+ }
+ String quote(String text){return "'"+text.replace("'","'\\''")+"'";}
+ void cursorVisible()throws Exception{
+ until("(()=>{const c=CanvasLinkClient.getState().source?.caret;if(!c)return false;const e=document.getElementById('video'),r=e.getBoundingClientRect(),v=document.getElementById('viewport').getBoundingClientRect(),k=Math.min(r.width/e.videoWidth,r.height/e.videoHeight),x=r.left+(r.width-e.videoWidth*k)/2+(c.x+c.width/2)*e.videoWidth*k,y=r.top+(r.height-e.videoHeight*k)/2+(c.y+c.height/2)*e.videoHeight*k;return x>v.left&&xv.top+8&&yMainActivity.active.setRequestedOrientation(orientation));
+ until(orientation==android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT?"screen.height>screen.width":"screen.width>screen.height","Native orientation not applied");test.waitTerminalKeyboard();cursorVisible();
+ until("(()=>{const v=document.getElementById('viewport').getBoundingClientRect(),b=document.getElementById('controls').getBoundingClientRect();return Math.abs(v.height+56-innerHeight)<2&&b.height===56&&new Set([...document.querySelectorAll('#controls button')].map(e=>e.getBoundingClientRect().top)).size===1;})()","Native IME workspace geometry failed");
+ test.stage(orientation==android.content.pm.ActivityInfo.SCREEN_ORIENTATION_PORTRAIT?"native-real-portrait-ready":"native-real-landscape-ready");android.os.SystemClock.sleep(900);
+ }}finally{test.runOnMainSync(()->MainActivity.active.setRequestedOrientation(previous));}
+ result.putBoolean("actualCursorAndSingleRowWithRealImeBothOrientations",true);
+ }
+ void run(String directory,Bundle result)throws Exception{
+ if(directory==null||!directory.startsWith("/")||directory.indexOf('\n')>=0)throw new Exception("Owned proof directory required");
+ cursorVisible();orientations(result);
+ test.stage("native-five-real-retaps");
+ for(int i=0;i<5;i++){test.menu("reset-view");test.tap("#video",test.freshNativePoint());test.waitTerminalKeyboard();cursorVisible();}
+ result.putInt("realTerminalRetaps",5);
+ test.stage("native-control-cancel-and-history");
+ text("touch "+quote(directory+"/must-not-exist"));key("c");key("Escape");key("ArrowUp");key("ArrowDown");key("c");
+ test.stage("native-control-editing");
+ text("printf '%s\\n' > "+quote(directory+"/controls-edit.txt")+" 'OKX'");
+ key("ArrowLeft");key("Backspace");key("ArrowRight");key("Enter");
+ test.stage("native-control-tab");
+ text("cd "+quote(directory)+"; : > canvaslink-tab-proof.txt");key("Enter");
+ text("printf '%s\\n' 'TAB' > canvaslink-tab-pro");key("Tab");key("Enter");
+ test.stage("native-control-no-duplicate-enter");
+ for(int i=1;i<=5;i++){text("printf '%s\\n' '"+i+"' >> "+quote(directory+"/controls-once.txt"));key("Enter");}
+ test.stage("native-direct-composition-paste");
+ text("printf '%s\\n' '");
+ final android.content.ClipData[] oldClip={null};
+ boolean[] direct={false},clipboardChanged={false};try{test.runOnMainSync(()->{
+ android.view.inputmethod.InputConnection input=MainActivity.active.web.onCreateInputConnection(new android.view.inputmethod.EditorInfo());
+ direct[0]=input!=null&&input.setComposingText("日本X",1)&&input.deleteSurroundingText(1,0)&&input.commitText("日本語🙂X",1)&&input.finishComposingText()&&input.deleteSurroundingText(1,0);
+ android.content.ClipboardManager clipboard=(android.content.ClipboardManager)MainActivity.active.getSystemService(android.content.Context.CLIPBOARD_SERVICE);
+ oldClip[0]=clipboard.getPrimaryClip();
+ clipboard.setPrimaryClip(android.content.ClipData.newPlainText("CanvasLink acceptance"," · ёЖ"));
+ clipboardChanged[0]=true;
+ });
+ if(!direct[0])throw new Exception("Native direct composing input failed");
+ until("CanvasLinkClient.getState().pending===0","Composition did not finish");test.tap("#paste");
+ until("CanvasLinkClient.getState().pending===0","Clipboard input did not finish");
+ test.runOnMainSync(()->((android.content.ClipboardManager)MainActivity.active.getSystemService(android.content.Context.CLIPBOARD_SERVICE)).setPrimaryClip(android.content.ClipData.newPlainText("CanvasLink acceptance","a")));
+ test.tap("#ctrl");test.tap("#paste");until("CanvasLinkClient.getState().pending===0","Literal one-letter paste did not finish");
+ }finally{if(clipboardChanged[0])test.runOnMainSync(()->{android.content.ClipboardManager c=(android.content.ClipboardManager)MainActivity.active.getSystemService(android.content.Context.CLIPBOARD_SERVICE);if(oldClip[0]!=null)c.setPrimaryClip(oldClip[0]);else if(android.os.Build.VERSION.SDK_INT>=28)c.clearPrimaryClip();});}
+ result.putBoolean("literalClipboardWithLatchedCtrl",true);
+ text("' > "+quote(directory+"/controls-direct.txt"));
+ test.runOnMainSync(()->MainActivity.active.web.onCreateInputConnection(new android.view.inputmethod.EditorInfo()).performEditorAction(android.view.inputmethod.EditorInfo.IME_ACTION_NONE));
+ until("CanvasLinkClient.getState().pending===0","Native IME Enter did not finish");
+ result.putBoolean("directCompositionUnicodeBackspaceClipboardImeEnter",true);
+ test.stage("native-physical-ime-key");text("printf '%s\\n' '");
+ test.runOnMainSync(()->((android.view.inputmethod.InputMethodManager)MainActivity.active.getSystemService(android.content.Context.INPUT_METHOD_SERVICE)).restartInput(MainActivity.active.web));
+ test.waitTerminalKeyboard();test.stage("native-physical-ime-key-ready");android.os.SystemClock.sleep(800);
+ android.accessibilityservice.AccessibilityServiceInfo info=test.getUiAutomation().getServiceInfo();info.flags|=android.accessibilityservice.AccessibilityServiceInfo.FLAG_RETRIEVE_INTERACTIVE_WINDOWS;test.getUiAutomation().setServiceInfo(info);
+ android.graphics.Rect keyRect=null;StringBuilder labels=new StringBuilder();
+ for(android.view.accessibility.AccessibilityWindowInfo window:test.getUiAutomation().getWindows())if(window.getType()==android.view.accessibility.AccessibilityWindowInfo.TYPE_INPUT_METHOD){keyRect=findImeKey(window.getRoot(),"a",labels);if(keyRect!=null)break;}
+ if(keyRect==null){result.putString("imeKeyLabels",labels.toString());throw new Exception("Real keyboard letter a not exposed; inspect IME-only labels");}
+ long at=android.os.SystemClock.uptimeMillis();for(int action:new int[]{android.view.MotionEvent.ACTION_DOWN,android.view.MotionEvent.ACTION_UP}){android.view.MotionEvent e=android.view.MotionEvent.obtain(at,android.os.SystemClock.uptimeMillis(),action,keyRect.centerX(),keyRect.centerY(),0);e.setSource(android.view.InputDevice.SOURCE_TOUCHSCREEN);if(!test.getUiAutomation().injectInputEvent(e,true))throw new Exception("IME key touch rejected");e.recycle();android.os.SystemClock.sleep(80);}
+ android.os.SystemClock.sleep(400);text("' > "+quote(directory+"/controls-ime-key.txt"));key("Enter");result.putBoolean("physicalKeyboardKeyTouched",true);
+ result.putBoolean("nativeToolbarControlsAcknowledged",true);
+ result.putInt("nativeSingleEnterCommands",5);
+ }
+ android.graphics.Rect findImeKey(android.view.accessibility.AccessibilityNodeInfo node,String wanted,StringBuilder labels){
+ if(node==null)return null;String text=node.getText()==null?"":node.getText().toString(),desc=node.getContentDescription()==null?"":node.getContentDescription().toString();
+ if(labels.length()<1500&&(!text.isEmpty()||!desc.isEmpty()))labels.append('[').append(text).append('|').append(desc).append(']');
+ android.graphics.Rect r=new android.graphics.Rect();node.getBoundsInScreen(r);if(node.isVisibleToUser()&&!r.isEmpty()&&(wanted.equalsIgnoreCase(text)||wanted.equalsIgnoreCase(desc)))return r;
+ for(int i=0;i WebRTC -> ordinary compiled CanvasTTY Settings. */
+final class SettingsTouchChecks {
+ final AcceptanceInstrumentation test;
+ final DeviceUxChecks gestures;
+ SettingsTouchChecks(AcceptanceInstrumentation test){this.test=test;gestures=new DeviceUxChecks(test,MainActivity.active);}
+ JSONObject probe()throws Exception{
+ java.io.File file=new java.io.File(MainActivity.active.getExternalFilesDir(null),"acceptance-settings.json");
+ file.delete();test.stage("remote-settings-request");
+ for(int i=0;i<80&&!file.exists();i++)SystemClock.sleep(100);
+ if(!file.exists())throw new Exception("Read-only Settings geometry unavailable");
+ JSONObject value=new JSONObject(new String(java.nio.file.Files.readAllBytes(file.toPath()),java.nio.charset.StandardCharsets.UTF_8));file.delete();return value;
+ }
+ JSONObject rect(JSONObject p,String name)throws Exception{
+ JSONObject item=name.startsWith("settings-tab-")?p.getJSONObject("tabs").optJSONObject(name):p.getJSONObject("controls").optJSONObject(name);
+ if(item==null||item.isNull("rect"))throw new Exception("Settings target not visible: "+name);
+ JSONObject r=item.getJSONObject("rect");if(!r.optBoolean("hit"))throw new Exception("Settings target covered: "+name);return r;
+ }
+ void tap(JSONObject p,String name)throws Exception{JSONObject r=rect(p,name);test.tap("#video",(r.getDouble("x")+r.getDouble("width")/2)+","+(r.getDouble("y")+r.getDouble("height")/2));SystemClock.sleep(500);}
+ float[] point(double x,double y)throws Exception{
+ JSONObject r=new JSONObject(test.js("(()=>{const e=document.getElementById('video'),r=e.getBoundingClientRect(),k=Math.min(r.width/e.videoWidth,r.height/e.videoHeight);return {x:r.x+(r.width-e.videoWidth*k)/2+e.videoWidth*k*"+x+",y:r.y+(r.height-e.videoHeight*k)/2+e.videoHeight*k*"+y+",d:devicePixelRatio}})()"));
+ int[] origin=new int[2];test.runOnMainSync(()->MainActivity.active.web.getLocationOnScreen(origin));return new float[]{(float)(r.getDouble("x")*r.getDouble("d"))+origin[0],(float)(r.getDouble("y")*r.getDouble("d"))+origin[1]};
+ }
+ void swipe(JSONObject r,double direction)throws Exception{
+ double x=r.getDouble("x")+r.getDouble("width")*.9,y=r.getDouble("y"),h=r.getDouble("height");
+ float[] a=point(x,y+h*(direction>0?.75:.25)),b=point(x,y+h*(direction>0?.25:.75));
+ long down=SystemClock.uptimeMillis();gestures.motion(down,MotionEvent.ACTION_DOWN,new float[][]{a});
+ for(int i=1;i<=16;i++){SystemClock.sleep(25);float f=i/16f;gestures.motion(down,MotionEvent.ACTION_MOVE,new float[][]{{a[0]+(b[0]-a[0])*f,a[1]+(b[1]-a[1])*f}});}
+ gestures.motion(down,MotionEvent.ACTION_UP,new float[][]{b});SystemClock.sleep(600);
+ }
+ JSONObject reveal(JSONObject p,String name)throws Exception{
+ for(int i=0;i<28;i++){JSONObject c=p.getJSONObject("controls").optJSONObject(name);if(c!=null&&!c.isNull("rect")&&c.getJSONObject("rect").optBoolean("hit"))return p;
+ JSONObject scroll=p.getJSONObject("scroll");if(scroll.getDouble("top")+scroll.getDouble("height")>=scroll.getDouble("total")-2)break;
+ swipe(rect(p,"content"),1);p=probe();
+ }throw new Exception("Cannot reveal Settings control: "+name);
+ }
+ void noKeyboard(String context)throws Exception{
+ boolean[] visible={false};test.runOnMainSync(()->visible[0]=MainActivity.active.web.getRootWindowInsets()!=null&&MainActivity.active.web.getRootWindowInsets().isVisible(android.view.WindowInsets.Type.ime()));
+ if(visible[0]||!"false".equals(test.js("CanvasLinkInput.active()")))throw new Exception("Non-text Settings control opened IME: "+context);
+ if(!"true".equals(test.js("document.getElementById('zoom-label').textContent==='100%'")))throw new Exception("Non-text Settings control changed Canvas zoom: "+context);
+ }
+ void dragRange(JSONObject r)throws Exception{
+ float[] a=point(r.getDouble("x")+r.getDouble("width")*.3,r.getDouble("y")+r.getDouble("height")/2),b=point(r.getDouble("x")+r.getDouble("width")*.65,r.getDouble("y")+r.getDouble("height")/2);
+ long down=SystemClock.uptimeMillis();gestures.motion(down,MotionEvent.ACTION_DOWN,new float[][]{a});for(int i=1;i<=12;i++){SystemClock.sleep(25);float f=i/12f;gestures.motion(down,MotionEvent.ACTION_MOVE,new float[][]{{a[0]+(b[0]-a[0])*f,a[1]+(b[1]-a[1])*f}});}gestures.motion(down,MotionEvent.ACTION_UP,new float[][]{b});SystemClock.sleep(400);
+ }
+ void run(Bundle result)throws Exception{
+ test.stage("settings-touch-open");test.menu("reset-view");JSONObject p=probe();int framesBeforeTouch=test.decodedFrames();tap(p,"open");p=probe();
+ if(!p.optBoolean("open"))throw new Exception("Touch did not open Settings");result.putBoolean("remoteSettingsOpened",true);noKeyboard("open");
+ test.waitVideoAfterTouch(framesBeforeTouch);result.putBoolean("remoteSettingsVideoRespondedToTouch",true);
+ tap(p,"settings-tab-general");p=probe();boolean wasOn=p.getJSONObject("controls").getJSONObject("toggleOn").getBoolean("selected");
+ tap(p,wasOn?"toggleOff":"toggleOn");p=probe();if(p.getJSONObject("controls").getJSONObject("toggleOn").getBoolean("selected")==wasOn)throw new Exception("Touch toggle did not change");noKeyboard("toggle");
+ tap(p,wasOn?"toggleOn":"toggleOff");result.putBoolean("remoteToggleChangedAndRestored",true);
+ tap(probe(),"settings-tab-appearance");p=probe();if(!"settings-panel-appearance".equals(p.optString("tab")))throw new Exception("Touch did not select Appearance");
+ double before=p.getJSONObject("scroll").getDouble("top");swipe(rect(p,"content"),1);p=probe();
+ if(p.getJSONObject("scroll").getDouble("top")<=before+20)throw new Exception("One-finger Settings swipe did not scroll remote content");
+ result.putBoolean("remoteSettingsOneFingerScroll",true);noKeyboard("scroll");
+ for(int i=0;i<12&&(p.getJSONObject("controls").optJSONObject("range")==null||p.getJSONObject("controls").getJSONObject("range").isNull("rect"));i++){swipe(rect(p,"content"),1);p=probe();}
+ double oldRange=p.getJSONObject("controls").getJSONObject("range").getDouble("value");
+ tap(p,"range");noKeyboard("range");p=probe();double beforeDrag=p.getJSONObject("controls").getJSONObject("range").getDouble("value");JSONObject slider=rect(p,"range");
+ String fresh="(()=>{const p="+slider.toString()+",x=p.x+p.width/2,y=p.y+p.height/2;return CanvasLinkClient.getState().source.dragRects.some(r=>x>=r.x&&x<=r.x+r.width&&y>=r.y&&y<=r.y+r.height)})()";
+ if(!"true".equals(test.js(fresh)))throw new Exception("Slider geometry stayed stale after UI resize");
+ dragRange(slider);p=probe();double selected=p.getJSONObject("controls").getJSONObject("range").getDouble("value");if(Math.abs(selected-beforeDrag)<.001)throw new Exception("Actual range drag did not change value");result.putBoolean("remoteRangeTouchDrag",true);noKeyboard("range drag");
+ test.tap("[data-key=ArrowRight]");SystemClock.sleep(300);p=probe();double next=p.getJSONObject("controls").getJSONObject("range").getDouble("value");
+ if(next<=selected)throw new Exception("Range ArrowRight failed without IME");
+ for(int i=0;i<60&&Math.abs(next-oldRange)>.001;i++){test.tap(next>oldRange?"[data-key=ArrowLeft]":"[data-key=ArrowRight]");SystemClock.sleep(120);p=probe();next=p.getJSONObject("controls").getJSONObject("range").getDouble("value");}
+ if(Math.abs(next-oldRange)>.001)throw new Exception("Range could not be restored");
+ result.putBoolean("remoteRangeNoKeyboard",true);result.putBoolean("remoteRangeScreenKeysChangedAndRestored",true);
+ test.stage("settings-text-and-select");tap(probe(),"settings-tab-agents");p=reveal(probe(),"preset");tap(p,"preset");p=reveal(probe(),"text");
+ JSONObject textRect=rect(p,"text");test.tap("#video",(textRect.getDouble("x")+textRect.getDouble("width")*.96)+","+(textRect.getDouble("y")+textRect.getDouble("height")/2));test.waitTerminalKeyboard();test.stage("settings-text-ime-ready");SystemClock.sleep(800);
+ JSONObject legibility=new JSONObject(test.js("(()=>{const e=document.getElementById('video'),r=e.getBoundingClientRect(),k=Math.min(r.width/e.videoWidth,r.height/e.videoHeight);return {font:"+p.getJSONObject("controls").getJSONObject("text").getDouble("fontSize")+"*e.videoWidth/(CanvasLinkClient.getState().source.viewport?.width||e.videoWidth)*k,scale:new DOMMatrix(getComputedStyle(e).transform).a}})()"));if(legibility.getDouble("font")<11.5||legibility.getDouble("scale")>4.01)throw new Exception("Settings field too small or excessively zoomed with real IME");
+ test.commitText(" · CL touch");SystemClock.sleep(400);p=probe();if(!p.getJSONObject("controls").getJSONObject("text").optBoolean("testMarker"))throw new Exception("Text field did not receive direct IME commit");
+ test.tap("#keyboard-toggle");SystemClock.sleep(400);noKeyboard("text edit ended");result.putBoolean("remoteTextReadableWithImeAndOverviewRestored",true);p=probe();tap(p,"save");SystemClock.sleep(500);
+ tap(probe(),"settings-tab-general");tap(probe(),"settings-tab-agents");p=reveal(probe(),"text");if(!p.getJSONObject("controls").getJSONObject("text").optBoolean("testMarker"))throw new Exception("Settings text did not persist across tab reopen");result.putBoolean("remoteTextDirectImeSavedAndReopened",true);
+ p=reveal(p,"select");int prior=p.getJSONObject("controls").getJSONObject("select").getInt("index");tap(p,"select");noKeyboard("select");test.stage("settings-select-open");SystemClock.sleep(800);
+ p=probe();int choice=prior==0?1:0;tap(p,"option-"+choice);p=probe();
+ if(p.getJSONObject("controls").getJSONObject("select").getInt("index")!=choice)throw new Exception("Select did not change through actual option touch");result.putBoolean("remoteSelectOptionTouch",true);
+ tap(p,"select");test.tap("[data-key=ArrowDown]");test.tap("[data-key=Enter]");SystemClock.sleep(400);p=probe();
+ int keyboardChoice=p.getJSONObject("controls").getJSONObject("select").getInt("index");if(keyboardChoice==choice)throw new Exception("Select did not change through screen keys");result.putBoolean("remoteSelectScreenKeys",true);
+ tap(p,"select");test.tap("[data-key=ArrowUp]");test.tap("[data-key=Escape]");p=probe();if(p.getJSONObject("controls").getJSONObject("select").getInt("index")!=keyboardChoice||p.getJSONObject("controls").has("option-0"))throw new Exception("Select Escape did not dismiss without applying");result.putBoolean("remoteSelectEscape",true);noKeyboard("select options");
+ tap(p,"save");tap(probe(),"settings-tab-general");tap(probe(),"settings-tab-agents");p=reveal(probe(),"select");if(p.getJSONObject("controls").getJSONObject("select").getInt("index")!=keyboardChoice)throw new Exception("Select value did not persist");result.putBoolean("remoteSelectSavedAndReopened",true);
+ tap(p,"remove");SystemClock.sleep(400);
+ tap(probe(),"close");if(probe().optBoolean("open"))throw new Exception("Touch did not close Settings");result.putBoolean("remoteSettingsClosed",true);
+ }
+}
diff --git a/integrations/canvaslink/android/src/io/nexcore/canvaslink/Srp.java b/integrations/canvaslink/android/src/io/nexcore/canvaslink/Srp.java
new file mode 100644
index 000000000..0c4c92cf1
--- /dev/null
+++ b/integrations/canvaslink/android/src/io/nexcore/canvaslink/Srp.java
@@ -0,0 +1,61 @@
+package io.nexcore.canvaslink;
+
+import java.math.BigInteger;
+import java.nio.charset.StandardCharsets;
+import java.security.MessageDigest;
+import java.security.SecureRandom;
+import java.util.Arrays;
+
+/** SRP-6a/SHA-256 interoperability with secure-remote-password 0.3.1.
+ * Fixed RFC 5054 2048-bit group. PIN is never sent to the network. */
+public final class Srp {
+ static final String PRIME = "AC6BDB41324A9A9BF166DE5E1389582FAF72B6651987EE07FC319294"
+ + "3DB56050A37329CBB4A099ED8193E0757767A13DD52312AB4B03310D"
+ + "CD7F48A9DA04FD50E8083969EDB767B0CF6095179A163AB3661A05FB"
+ + "D5FAAAE82918A9962F0B93B855F97993EC975EEAA80D740ADBF4FF74"
+ + "7359D041D5C33EA71D281E446B14773BCA97B43A23FB801676BD207A"
+ + "436C6481F1D2B9078717461A5B9D32E688F87748544523B524B0D57D"
+ + "5EA77A2775D2ECFA032CFBDBF52FB3786160279004E57AE6AF874E73"
+ + "03CE53299CCC041C7BC308D82A5698F3A8D0C38271AE35F8E9DBFBB6"
+ + "94B5C803D89F7AE435DE236D525F54759B65E372FCD68EF20FA7111F9E4AFF73";
+ static final BigInteger N = new BigInteger(PRIME, 16), G = BigInteger.valueOf(2);
+ static final String USER = "CanvasLink/v1";
+ final BigInteger secret, publicValue;
+ public Srp() { byte[] a = new byte[32]; new SecureRandom().nextBytes(a); secret = new BigInteger(1, a); publicValue = G.modPow(secret, N); }
+ Srp(String fixedSecret) { secret = new BigInteger(fixedSecret, 16); publicValue = G.modPow(secret, N); }
+ public String publicHex() { return hex(pad(publicValue, 256)); }
+ public static byte[] utf8(String value) { return value.getBytes(StandardCharsets.UTF_8); }
+ public static byte[] hash(byte[]... values) {
+ try { MessageDigest d = MessageDigest.getInstance("SHA-256"); for (byte[] v : values) d.update(v); return d.digest(); }
+ catch (Exception e) { throw new IllegalStateException(e); }
+ }
+ public static String hex(byte[] value) { StringBuilder s = new StringBuilder(); for (byte b : value) s.append(String.format(java.util.Locale.ROOT, "%02x", b & 255)); return s.toString(); }
+ public static byte[] bytes(String value) {
+ if (value == null || !value.matches("[0-9a-fA-F]+") || value.length() % 2 != 0) throw new IllegalArgumentException("Invalid hex");
+ byte[] out = new byte[value.length() / 2]; for (int i = 0; i < out.length; i++) out[i] = (byte) Integer.parseInt(value.substring(i*2, i*2+2), 16); return out;
+ }
+ static byte[] pad(BigInteger value, int length) {
+ byte[] raw = value.toByteArray(), out = new byte[length];
+ int count = Math.min(length, raw.length); System.arraycopy(raw, raw.length-count, out, length-count, count); return out;
+ }
+ public Session derive(String pin, String saltHex, String serverHex) {
+ if (!pin.matches("[0-9]{6}") || !saltHex.matches("[0-9a-f]{64}") || !serverHex.matches("[0-9a-f]{512}")) throw new IllegalArgumentException("Invalid SRP challenge");
+ byte[] salt = bytes(saltHex), a = pad(publicValue, 256), b = bytes(serverHex), n = bytes(PRIME), g = {2};
+ BigInteger B = new BigInteger(1, b);
+ if (B.mod(N).equals(BigInteger.ZERO)) throw new IllegalArgumentException("Invalid server ephemeral");
+ BigInteger k = new BigInteger(1, hash(n, g));
+ BigInteger x = new BigInteger(1, hash(salt, hash(utf8(USER + ":" + pin))));
+ BigInteger u = new BigInteger(1, hash(a, b));
+ if (u.equals(BigInteger.ZERO)) throw new IllegalArgumentException("Invalid scrambling parameter");
+ BigInteger S = B.subtract(k.multiply(G.modPow(x, N))).mod(N).modPow(secret.add(u.multiply(x)), N);
+ byte[] K = hash(pad(S, 256)), xor = hash(n), hg = hash(g);
+ for (int i=0; ishowTerminal(next),150);postDelayed(()->showTerminal(next),350);
+ }
+ private void showTerminal(String owner){if(owner.equals(token)&&!owner.isEmpty()){requestFocus();ime().showSoftInput(this,InputMethodManager.SHOW_IMPLICIT);}}
+ void closeTerminal(){token="";connection=null;ime().hideSoftInputFromWindow(getWindowToken(),0);ime().restartInput(this);}
+ boolean terminalActive(){return !token.isEmpty();}
+ @Override public boolean onTouchEvent(MotionEvent event){
+ String owner=token;boolean handled=super.onTouchEvent(event);
+ // Blink dismisses its DOM keyboard when a toolbar button is touched. Our
+ // terminal input connection still owns focus, so keep the terminal IME up.
+ // Menu/explicit hide invalidates owner before this delayed callback runs.
+ if(event.getActionMasked()==MotionEvent.ACTION_UP&&!owner.isEmpty())postDelayed(()->showTerminal(owner),150);
+ return handled;
+ }
+ private void event(JSONObject value){
+ if(token.isEmpty())return;
+ try{value.put("token",token);}catch(JSONException ignored){}
+ evaluateJavascript("window.CanvasLinkInput&&window.CanvasLinkInput.receive("+value.toString()+")",null);
+ }
+ private void text(String value){if(value.isEmpty())return;try{event(new JSONObject().put("type","text").put("text",value));}catch(JSONException ignored){}}
+ void key(String key,String modifiers){
+ if(connection!=null)connection.finishComposingText();
+ try{event(new JSONObject().put("type","key").put("key",key).put("modifiers",new JSONArray(modifiers)));}catch(JSONException ignored){}
+ }
+ void paste(String value){
+ if(value.isEmpty()){try{event(new JSONObject().put("type","notice").put("text","Буфер обмена пуст"));}catch(JSONException ignored){}return;}
+ if(value.length()>8000){try{event(new JSONObject().put("type","notice").put("text","В буфере больше 8000 символов"));}catch(JSONException ignored){}return;}
+ if(connection!=null)connection.finishComposingText();
+ try{event(new JSONObject().put("type","paste").put("text",value));}catch(JSONException ignored){}
+ }
+ @Override public boolean onCheckIsTextEditor(){return terminalActive()||super.onCheckIsTextEditor();}
+ @Override public InputConnection onCreateInputConnection(EditorInfo out){
+ if(!terminalActive())return super.onCreateInputConnection(out);
+ out.inputType=InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD|InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS|InputType.TYPE_TEXT_FLAG_MULTI_LINE;
+ out.imeOptions=EditorInfo.IME_FLAG_NO_EXTRACT_UI|EditorInfo.IME_FLAG_NO_FULLSCREEN|EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING|EditorInfo.IME_ACTION_NONE;
+ out.initialSelStart=out.initialSelEnd=0;
+ return connection=new TerminalConnection(token);
+ }
+ private boolean hardware(KeyEvent e){
+ if(!terminalActive()||e.getKeyCode()==KeyEvent.KEYCODE_BACK)return false;
+ String k=null;
+ switch(e.getKeyCode()){
+ case KeyEvent.KEYCODE_ENTER:k="Enter";break;case KeyEvent.KEYCODE_DEL:k="Backspace";break;
+ case KeyEvent.KEYCODE_FORWARD_DEL:k="Delete";break;case KeyEvent.KEYCODE_TAB:k="Tab";break;
+ case KeyEvent.KEYCODE_ESCAPE:k="Escape";break;case KeyEvent.KEYCODE_DPAD_LEFT:k="ArrowLeft";break;
+ case KeyEvent.KEYCODE_DPAD_RIGHT:k="ArrowRight";break;case KeyEvent.KEYCODE_DPAD_UP:k="ArrowUp";break;
+ case KeyEvent.KEYCODE_DPAD_DOWN:k="ArrowDown";break;case KeyEvent.KEYCODE_MOVE_HOME:k="Home";break;
+ case KeyEvent.KEYCODE_MOVE_END:k="End";break;case KeyEvent.KEYCODE_PAGE_UP:k="PageUp";break;
+ case KeyEvent.KEYCODE_PAGE_DOWN:k="PageDown";break;
+ }
+ int code=e.getUnicodeChar();
+ if(k==null&&code==0)return false;
+ if(e.getAction()!=KeyEvent.ACTION_DOWN)return true;
+ JSONArray mods=new JSONArray();if(e.isCtrlPressed())mods.put("control");if(e.isAltPressed())mods.put("alt");if(e.isShiftPressed())mods.put("shift");if(e.isMetaPressed())mods.put("meta");
+ if(k!=null)key(k,mods.toString());
+ else if(e.isCtrlPressed()||e.isMetaPressed()){
+ int base=e.getUnicodeChar(0);if(base>0)key(new String(Character.toChars(base)).toLowerCase(java.util.Locale.ROOT),mods.toString());
+ }else if(code>0&&code<=Character.MAX_CODE_POINT){if(connection!=null)connection.finishComposingText();text(new String(Character.toChars(code)));}
+ return true;
+ }
+ @Override public boolean dispatchKeyEvent(KeyEvent e){return hardware(e)||super.dispatchKeyEvent(e);}
+ @Override public boolean onKeyPreIme(int code,KeyEvent event){
+ if(code==KeyEvent.KEYCODE_BACK&&terminalActive()){
+ if(event.getAction()==KeyEvent.ACTION_UP){closeTerminal();evaluateJavascript("window.CanvasLinkInput&&window.CanvasLinkInput.stop()",null);}
+ return true;
+ }
+ return super.onKeyPreIme(code,event);
+ }
+ private final class TerminalConnection extends BaseInputConnection {
+ final String owner;final Editable composing=new SpannableStringBuilder();
+ TerminalConnection(String owner){super(TerminalWebView.this,true);this.owner=owner;Selection.setSelection(composing,0);}
+ private boolean valid(){return connection==this&&owner.equals(token)&&!token.isEmpty();}
+ @Override public Editable getEditable(){return composing;}
+ private void preedit(){try{event(new JSONObject().put("type","composition").put("text",composing.toString()));}catch(JSONException ignored){}ime().updateSelection(TerminalWebView.this,Selection.getSelectionStart(composing),Selection.getSelectionEnd(composing),getComposingSpanStart(composing),getComposingSpanEnd(composing));}
+ private void clear(){composing.clear();Selection.setSelection(composing,0);preedit();}
+ @Override public boolean setComposingText(CharSequence value,int cursor){if(!valid())return false;super.setComposingText(value,cursor);preedit();return true;}
+ @Override public boolean commitText(CharSequence value,int cursor){if(!valid())return false;String committed=value.toString();clear();if("\n".equals(committed))key("Enter","[]");else text(committed);return true;}
+ @Override public boolean finishComposingText(){if(!valid())return false;String value=composing.toString();super.finishComposingText();clear();text(value);return true;}
+ @Override public boolean deleteSurroundingText(int before,int after){
+ if(!valid()||before<0||after<0||before>8000||after>8000)return false;
+ if(composing.length()>0){int cursor=Math.max(0,Selection.getSelectionEnd(composing));int from=Math.max(0,cursor-before),to=Math.min(composing.length(),cursor+after);composing.delete(from,to);Selection.setSelection(composing,from);preedit();return true;}
+ for(int i=0;i8000||after>8000)return false;
+ if(composing.length()==0)return deleteSurroundingText(before,after);
+ int cursor=Math.max(0,Selection.getSelectionEnd(composing));
+ int left=Character.codePointCount(composing,0,cursor),right=Character.codePointCount(composing,cursor,composing.length());
+ int from=Character.offsetByCodePoints(composing,cursor,-Math.min(before,left)),to=Character.offsetByCodePoints(composing,cursor,Math.min(after,right));
+ composing.delete(from,to);Selection.setSelection(composing,from);preedit();return true;
+ }
+ @Override public boolean sendKeyEvent(KeyEvent event){return valid()&&hardware(event);}
+ @Override public boolean performEditorAction(int action){if(!valid())return false;key("Enter","[]");return true;}
+ @Override public boolean performContextMenuAction(int action){
+ if(!valid()||action!=android.R.id.paste)return false;
+ android.content.ClipboardManager clipboard=(android.content.ClipboardManager)getContext().getSystemService(Context.CLIPBOARD_SERVICE);
+ if(clipboard.hasPrimaryClip()&&clipboard.getPrimaryClip().getItemCount()>0){CharSequence value=clipboard.getPrimaryClip().getItemAt(0).coerceToText(getContext());if(value!=null)paste(value.toString());}return true;
+ }
+ }
+}
diff --git a/integrations/canvaslink/design/canvaslink-icon.svg b/integrations/canvaslink/design/canvaslink-icon.svg
new file mode 100644
index 000000000..b9f3ffcb1
--- /dev/null
+++ b/integrations/canvaslink/design/canvaslink-icon.svg
@@ -0,0 +1,10 @@
+
+
+
+
diff --git a/integrations/canvaslink/host/discovery.cjs b/integrations/canvaslink/host/discovery.cjs
new file mode 100644
index 000000000..bb83a98e1
--- /dev/null
+++ b/integrations/canvaslink/host/discovery.cjs
@@ -0,0 +1,32 @@
+const {spawn}=require('node:child_process');
+const {lanAddresses}=require('./network.cjs');
+// macOS mDNSResponder owns multicast publication. UDP-only JS Bonjour can
+// report "up" while its records remain invisible to native DNS-SD browsers.
+function publish({name,port,ipv4=lanAddresses()[0]||'',embedded=false}){
+ if(process.platform==='darwin'){
+ const child=spawn('/usr/bin/dns-sd',['-R',name,'_canvaslink._tcp','local.',String(port),'v=2','ipv4='+ipv4,'host='+(embedded?'canvastty':'standalone')],{stdio:'ignore'});
+ child.on('error',()=>{});
+ return {destroy(){child.kill('SIGTERM');}};
+ }
+ const {Bonjour}=require('bonjour-service'),publishers=new Map();let destroyed=false;
+ const stop=bonjour=>bonjour.unpublishAll(()=>bonjour.destroy());
+ const refresh=()=>{
+ const addresses=lanAddresses();
+ for(const [address,bonjour] of publishers)if(!addresses.includes(address)){publishers.delete(address);stop(bonjour);}
+ for(const address of addresses){
+ if(publishers.has(address))continue;
+ // Bind multicast to the LAN adapter instead of the VPN's default route.
+ const onError=error=>console.warn('CanvasLink discovery unavailable:',error.code||error.message);
+ const bonjour=new Bonjour({interface:address,bind:'0.0.0.0'},onError);
+ bonjour.server.mdns.on('error',onError);
+ const service=bonjour.publish({name:`${name} (${address})`,host:`canvaslink-${address.replaceAll('.','-')}.local`,type:'canvaslink',port,disableIPv6:true,txt:{v:'2',ipv4:address,host:embedded?'canvastty':'standalone'}});
+ const records=service.records.bind(service);
+ // Bonjour 1.3 enumerates every adapter; advertise only this LAN endpoint.
+ service.records=()=>records().filter(record=>record.type!=='AAAA'&&(record.type!=='A'||record.data===address));
+ publishers.set(address,bonjour);
+ }
+ };
+ refresh();const timer=setInterval(refresh,5000);timer.unref();
+ return {destroy(){if(destroyed)return;destroyed=true;clearInterval(timer);for(const bonjour of publishers.values())stop(bonjour);publishers.clear();}};
+}
+module.exports={publish};
diff --git a/integrations/canvaslink/host/display-scale.cjs b/integrations/canvaslink/host/display-scale.cjs
new file mode 100644
index 000000000..49dc23ee0
--- /dev/null
+++ b/integrations/canvaslink/host/display-scale.cjs
@@ -0,0 +1,13 @@
+// Optional high-density startup; the desktop must opt in explicitly.
+// Never change density or restart the default desktop process.
+function configureRenderScale(app,argv=process.argv){
+ if(app.isReady())throw Error('render-scale-requires-startup');
+ const scale=argv.find(arg=>arg.startsWith('--force-device-scale-factor='));
+ if(scale){if(!['--force-device-scale-factor=1','--force-device-scale-factor=2'].includes(scale))throw Error('invalid-render-scale');return;}
+ // Electron 43/macOS reads this switch before JavaScript: appendSwitch at the
+ // top of main still leaves DPR=1. A normal preview launch restarts once with
+ // the process-start switch. The owned acceptance launcher already passes it.
+ app.relaunch({args:[...argv.slice(1),'--force-device-scale-factor=2']});
+ app.exit(0);
+}
+module.exports={configureRenderScale};
diff --git a/integrations/canvaslink/host/embedded.cjs b/integrations/canvaslink/host/embedded.cjs
new file mode 100644
index 000000000..684ffe81a
--- /dev/null
+++ b/integrations/canvaslink/host/embedded.cjs
@@ -0,0 +1,138 @@
+// CanvasTTY main-process integration. No global input or desktop capture.
+const {app,BrowserWindow,ipcMain,session,nativeImage}=require('electron');
+const http=require('node:http'),os=require('node:os'),path=require('node:path'),fs=require('node:fs');
+const {publish}=require('./discovery.cjs');
+const {lanAddresses:addresses}=require('./network.cjs');
+const {Pairing,privateAddress}=require('./security.cjs');
+const {InputQueue}=require('./input-queue.cjs');
+const {focusOwnedWindow}=require('./owned-focus.cjs');
+const {OwnedPointer}=require('./owned-pointer.cjs');
+const {installSettingsHost}=require('./settings-host.cjs');
+const {validateInput}=require('./native-input.cjs');
+const {selectPointerScript,closeSelectScript}=require('./remote-select.cjs');
+const {createSnapshot}=require('./snapshot.cjs');
+function install({getWindow,glasses}={}){
+ let target,panel,server,bonjour,pairing,port,frameTimer,healthTimer,enabled=false;
+ const queues=new Map(),epochs=new Map(),pointer=new OwnedPointer();let bound=false,captureMode='tab',captureError='',captureQuality=null,frameSequence=0,pendingFrame=0,healthBusy=false,selectPointer=false,sourceSurface='canvas',lastHealth=0;let report={phase:'disabled'},lastFrame=0,startFallback=()=>{};
+ const runtime=()=>path.join(app.getPath('userData'),'canvaslink');
+ const option=name=>{const i=process.argv.indexOf(name);return i<0?undefined:process.argv[i+1];};
+ const closeRemoteSelect=()=>{selectPointer=false;if(target&&!target.isDestroyed())target.webContents.executeJavaScript(closeSelectScript).catch(()=>{});};
+ const ownWindow=()=>getWindow?.()||BrowserWindow.getAllWindows().find(w=>!w.getParentWindow()&&/\/renderer\/index\.html/.test(w.webContents.getURL()));
+ const settingsSnapshot=()=>({enabled,phase:enabled?report.phase:'disabled',pin:enabled?pairing.pin:'',expires:enabled?pairing.expires:0,devices:enabled?[...pairing.sessions.values()].filter(s=>s.expires>Date.now()).map(s=>({name:s.name})):[]});
+ installSettingsHost({ipcMain,getWindow:ownWindow,snapshot:settingsSnapshot,command:async action=>{
+ if(action==='enable')await open();
+ else if(action==='disable')disable();
+ else{if(!enabled)throw Error('canvaslink-disabled');pairing.rotate();report={phase:'waiting',inputs:0,error:''};events({type:'state'});}
+ return settingsSnapshot();
+ }});
+ const events=value=>{if(panel&&!panel.isDestroyed())panel.webContents.send('link:event',value);};
+ const source=()=>({id:'embedded:'+target.id,name:target.getTitle(),pid:process.pid});
+ const state=()=>{const [width,height]=target.getContentSize();return {pin:pairing.pin,expires:pairing.expires,addresses:addresses(),port,fixture:false,embedded:true,nativeCapture:true,captureMode,glassesSupported:!!glasses,width,height,source:target.getTitle(),connected:[...pairing.sessions.values()].map(s=>({id:s.id,name:s.name})),report};};
+ const trusted=event=>{if(!panel||event.sender!==panel.webContents||event.senderFrame!==panel.webContents.mainFrame)throw Error('untrusted-renderer');};
+ const authorized=id=>enabled&&pairing?.sessions.has(id)&&pairing.sessions.get(id).expires>Date.now()&&target&&!target.isDestroyed();
+ function safeSignal(message){if(!message||!['offer','answer','disconnect','ping'].includes(message.type))throw Error('invalid-signal');if(['offer','answer'].includes(message.type)&&(typeof message.sdp!=='string'||message.sdp.length>80000))throw Error('invalid-sdp');return message;}
+ function stopFrames(){clearInterval(healthTimer);clearInterval(frameTimer);frameTimer=null;try{if(target&&!target.isDestroyed())target.webContents.endFrameSubscription();}catch{}}
+ const {focusScript}=require('./focus.cjs');
+ async function apply(input,active){
+ validateInput(input);if(!target||target.isDestroyed())throw Error('window-closed');
+ if(target.isMinimized())throw Error('window-minimized');
+ // Electron routes these events solely to its own renderer. Never use CGEvent
+ // or system keystrokes, and never inject into another app's focused window.
+ // The pairing child must not retain key-window focus over its parent.
+ if(panel&&!panel.isDestroyed()&&panel.isVisible())panel.hide();
+ await focusOwnedWindow({app,target,active});
+ if(!target.isFocused())throw Error('canvas-focus-required');
+ const wc=target.webContents,[width,height]=target.getContentSize();
+ const point={x:Math.min(width-1,Math.round(input.x*width)),y:Math.min(height-1,Math.round(input.y*height))};
+ if(input.type==='text'){const focus=await wc.executeJavaScript(focusScript);if(!active())throw Error('session-ended');if(!focus.editable)throw Error('text-target-required');await wc.insertText(input.text);return;}
+ if(input.type==='pointer'){
+ if(input.action==='down')selectPointer=input.button!==2&&await wc.executeJavaScript(selectPointerScript(point.x,point.y));
+ if(!active()){await wc.executeJavaScript(closeSelectScript);throw Error('session-ended');}
+ if(!selectPointer)pointer.send(wc,{...point,type:{down:'mouseDown',up:'mouseUp',move:'mouseMove'}[input.action],button:input.button===2?'right':'left',clickCount:1,modifiers:input.drag?['leftButtonDown']:[]});if(input.action==='up'){
+ selectPointer=false;
+ // Input dispatch is asynchronous. Read focus after the renderer has handled
+ // the click and settled its layout, rather than acknowledging old focus.
+ const focus=await wc.executeJavaScript(`new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(${focusScript}))))`);
+ sourceSurface=focus.surface;if(!active())throw Error('session-ended');return {focus};}return;}
+ if(input.type==='scroll'){wc.sendInputEvent({...point,type:'mouseWheel',deltaX:-input.dx,deltaY:-input.dy,canScroll:true});return;}
+ const keyCode={Enter:'Return',ArrowLeft:'Left',ArrowRight:'Right',ArrowUp:'Up',ArrowDown:'Down'}[input.key]||input.key;
+ wc.sendInputEvent({type:'keyDown',keyCode,modifiers:input.modifiers});wc.sendInputEvent({type:'keyUp',keyCode,modifiers:input.modifiers});
+ }
+ function reply(res,status,body){res.writeHead(status,{'Content-Type':'application/json','Cache-Control':'no-store','X-Content-Type-Options':'nosniff'});res.end(JSON.stringify(body));}
+ async function serve(req,res){
+ if(!enabled||!privateAddress(req.socket.remoteAddress)||req.headers.origin||req.method!=='POST'||!['/pair/start','/pair/finish','/channel'].includes(req.url)){reply(res,403,{error:'forbidden'});return;}
+ if(!/^application\/json(?:;|$)/i.test(req.headers['content-type']||'')){reply(res,415,{error:'json-required'});return;}
+ try{let size=0,chunks=[];for await(const chunk of req){size+=chunk.length;if(size>131072)throw Error('too-large');chunks.push(chunk);}const body=JSON.parse(Buffer.concat(chunks).toString());let result;
+ if(req.url==='/pair/start')result=pairing.start(body,req.socket.remoteAddress);
+ else if(req.url==='/pair/finish')result=pairing.finish(body,req.socket.remoteAddress);
+ else result=pairing.receive(body,req.socket.remoteAddress,(s,message)=>{
+ if(message.type==='poll')return {messages:s.queue.splice(0),source:target.getTitle()};
+ if(message.type==='signal'){events({type:'signal',id:s.id,message:safeSignal(message.message)});return {ok:true};}
+ if(message.type==='revoke'){pairing.rotate();events({type:'state'});return {ok:true};}throw Error('unsupported-operation');
+ });reply(res,200,result);
+ }catch{if(!res.headersSent)reply(res,403,{error:'request-rejected'});}
+ }
+ function bindIPC(){
+ if(bound)return;bound=true;
+ ipcMain.handle('link:input-session',(event,id,token)=>{trusted(event);if(token===null){epochs.delete(id);pointer.release();selectPointer=false;target?.webContents.executeJavaScript(closeSelectScript).catch(()=>{});}else{if(!authorized(id))throw Error('not-authorized');pointer.release();epochs.set(id,token);queues.delete(id);}return true;});
+ ipcMain.handle('link:capture-fallback',(event,reason)=>{trusted(event);captureMode='snapshot-fallback';captureError=String(reason||'').replace(/[^A-Za-z]/g,'').slice(0,60);startFallback();return true;});
+ ipcMain.on('link:frame-consumed',(event,sequence)=>{trusted(event);if(sequence===pendingFrame)pendingFrame=0;});
+ ipcMain.handle('link:glasses',async(event,command)=>{trusted(event);if(!glasses||!['state','begin-pairing','cancel-pairing'].includes(command))throw Error('unsupported-glasses-command');return command==='state'?glasses.state():glasses.command({type:command});});
+ ipcMain.handle('link:state',event=>{trusted(event);return state();});
+ ipcMain.handle('link:permissions',event=>{trusted(event);return {platform:process.platform,embedded:true};});
+ ipcMain.handle('link:settings',event=>{trusted(event);throw Error('not-required-for-owned-window');});
+ ipcMain.handle('link:sources',event=>{trusted(event);return [source()];});
+ ipcMain.handle('link:select',(event,id)=>{trusted(event);if(id!==source().id)throw Error('invalid-source');return state();});
+ ipcMain.handle('link:rotate',event=>{trusted(event);pairing.rotate();return state();});
+ ipcMain.handle('link:signal',(event,id,message)=>{trusted(event);if(!authorized(id))throw Error('not-authorized');pairing.queue(id,safeSignal(message));});
+ ipcMain.handle('link:input',(event,id,input)=>{
+ trusted(event);if(!authorized(id))throw Error('not-authorized');if(typeof input?.id!=='string'||!/^[A-Za-z0-9-]{1,80}$/.test(input.id))throw Error('invalid-input-id');
+ let q=queues.get(id);if(!q){const active=()=>authorized(id)&&epochs.get(id)===input.epoch;q=new InputQueue({active,apply:value=>apply(value,active),reply:result=>{const resolve=q.waiters.get(result.id);if(resolve){q.waiters.delete(result.id);resolve(result);}}});q.waiters=new Map();queues.set(id,q);}
+ if(q.waiters.has(input.id))throw Error('input-in-progress');return new Promise(resolve=>{q.waiters.set(input.id,resolve);q.receive(input);});
+ });
+ ipcMain.on('link:report',(event,value)=>{
+ if(!panel||panel.isDestroyed())return;
+ trusted(event);if(!value||typeof value.phase!=='string')return;
+ report={phase:value.phase.slice(0,80),inputs:Number(value.inputs)||0,error:String(value.error||'').slice(0,200)};
+ });
+ }
+ async function open(){
+ if(enabled)return;
+ target=ownWindow();
+ if(!target||target.isDestroyed())throw Error('canvas-window-unavailable');
+ fs.mkdirSync(runtime(),{recursive:true,mode:0o700});
+ pairing=new Pairing({onPair:s=>{events({type:'paired',id:s.id});},onRevoke:id=>{epochs.delete(id);queues.delete(id);pointer.release();closeRemoteSelect();events({type:'revoke',id});}});
+ server=http.createServer(serve);server.requestTimeout=10000;server.headersTimeout=5000;server.maxConnections=32;
+ try{await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(Number(option('--canvaslink-port')||3499),'0.0.0.0',resolve);});}catch(error){server.close();throw error;}
+ try{
+ port=server.address().port;enabled=true;captureMode='tab';captureError='';lastFrame=0;pendingFrame=0;bindIPC();
+ const captureSession=session.fromPartition('canvaslink-owned-capture');
+ panel=new BrowserWindow({width:600,height:700,show:false,parent:target,title:'CanvasTTY · Телефон / планшет',webPreferences:{session:captureSession,preload:path.join(__dirname,'preload.cjs'),contextIsolation:true,sandbox:true,nodeIntegration:false,backgroundThrottling:false}});
+ // Older Electron reports display capture as media with an empty mediaTypes
+ // array. Actual camera/microphone requests remain denied in this own session.
+ captureSession.setPermissionCheckHandler((contents,permission)=>contents===panel?.webContents&&permission==='display-capture');
+ captureSession.setPermissionRequestHandler((contents,permission,callback,details)=>callback(contents===panel?.webContents&&(permission==='display-capture'||permission==='media'&&Array.isArray(details.mediaTypes)&&details.mediaTypes.length===0)));
+ captureSession.setDisplayMediaRequestHandler((request,callback)=>{try{if(!enabled||request.frame!==panel.webContents.mainFrame||target.isDestroyed())return callback({});callback({video:target.webContents.mainFrame});}catch{callback({});}});
+ panel.webContents.setWindowOpenHandler(()=>({action:'deny'}));panel.webContents.on('will-navigate',e=>e.preventDefault());
+ panel.on('close',event=>{if(enabled){event.preventDefault();panel.hide();}});
+ bonjour=publish({name:`CanvasLink ${os.hostname().split('.')[0]}`,port,ipv4:addresses()[0]||'',embedded:true});
+ await panel.loadFile(path.join(__dirname,'index.html'));
+ startFallback=()=>{if(frameTimer)return;let busy=false;
+ const frame=image=>{
+ const now=Date.now();if(!enabled||!pairing.sessions.size||pendingFrame||now-lastFrame<100||image.isEmpty())return;lastFrame=now;
+ const encoded=createSnapshot(image,nativeImage);if(!encoded)return;
+ captureQuality={format:encoded.format,width:encoded.width,height:encoded.height,nativeScale:encoded.scaleFactor,bytes:encoded.pixels.length,encodeMs:Date.now()-now};
+ pendingFrame=++frameSequence;events({type:'frame',sequence:pendingFrame,width:encoded.width,height:encoded.height,pixels:encoded.pixels});
+ };
+ target.webContents.beginFrameSubscription(false,frame);
+ frameTimer=setInterval(async()=>{if(busy||pendingFrame||!pairing.sessions.size||Date.now()-lastFrame<100||target.isDestroyed())return;busy=true;try{frame(await target.webContents.capturePage(undefined,{stayHidden:true,stayAwake:false}));}catch{}finally{busy=false;}},100);
+ };
+ healthTimer=setInterval(async()=>{pairing.expire();if(healthBusy||!pairing.sessions.size||target.isDestroyed()||sourceSurface!=='settings'&&Date.now()-lastHealth<1000)return;healthBusy=true;lastHealth=Date.now();try{const focus=await target.webContents.executeJavaScript(focusScript);sourceSurface=focus.surface;events({type:'health',value:{capture:captureMode==='tab'?(target.webContents.isBeingCaptured()?'active':'stalled'):(Date.now()-lastFrame<3000?'active':'stalled'),windowFocused:target.isFocused(),target:focus.kind,surface:focus.surface,viewport:focus.viewport,terminalView:focus.terminalView,dragRects:focus.dragRects,rect:focus.rect,caret:focus.caret}});}catch{}finally{healthBusy=false;}},200);
+ target.removeListener('closed',disable);target.once('closed',disable);
+ }catch(error){disable();throw error;}
+ }
+ function disable(){enabled=false;pairing?.rotate();pointer.release();closeRemoteSelect();stopFrames();bonjour?.destroy();server?.close();if(panel&&!panel.isDestroyed())panel.destroy();queues.clear();epochs.clear();}
+ app.on('before-quit',()=>{disable();});
+ return {open,disable};
+}
+module.exports={install};
diff --git a/integrations/canvaslink/host/focus.cjs b/integrations/canvaslink/host/focus.cjs
new file mode 100644
index 000000000..5dda9e91b
--- /dev/null
+++ b/integrations/canvaslink/host/focus.cjs
@@ -0,0 +1,18 @@
+// Geometry only; no field values or surrounding text cross the input channel.
+function readFocus(){
+ const e=document.activeElement,panel=document.querySelector('.settings-panel--open');
+ const editable=!!e&&!e.disabled&&!e.readOnly&&(e.tagName==='TEXTAREA'||e.tagName==='INPUT'&&['text','search','email','url','tel','password','number'].includes(e.type)||e.isContentEditable);
+ const kind=e?.classList.contains('xterm-helper-textarea')?'terminal':editable?'text-field':e?.matches('input,select,button,[role=button],[role=slider]')?'control':'canvas';
+ const node=kind==='terminal'?e.closest('.xterm')?.querySelector('.xterm-screen'):editable?e:null;
+ const r=node?.getBoundingClientRect(),c=kind==='terminal'?e.getBoundingClientRect():null;
+ const normalized=b=>b&&b.width>0&&b.height>0?{x:b.x/innerWidth,y:b.y/innerHeight,width:b.width/innerWidth,height:b.height/innerHeight}:null;
+ const clipped=e=>{const r=e.getBoundingClientRect();let x=Math.max(0,r.left),y=Math.max(0,r.top),right=Math.min(innerWidth,r.right),bottom=Math.min(innerHeight,r.bottom);for(let p=e.parentElement;p;p=p.parentElement){const s=getComputedStyle(p);if(/hidden|auto|scroll|clip/.test(s.overflow+s.overflowX+s.overflowY)){const b=p.getBoundingClientRect();x=Math.max(x,b.left);y=Math.max(y,b.top);right=Math.min(right,b.right);bottom=Math.min(bottom,b.bottom);}}return normalized({x,y,width:right-x,height:bottom-y});};
+ const dragRects=panel?[...panel.querySelectorAll('input[type=range]')].filter(e=>!e.disabled).map(clipped).filter(Boolean):[];
+ const screens=panel?[]:[...document.querySelectorAll('.xterm-screen')].filter(node=>clipped(node));
+ const selected=screens.filter(node=>node.closest('.terminal-card--selected'));
+ const candidate=selected.length===1?selected[0]:screens.length===1?screens[0]:null;
+ const terminalView=candidate?{rect:clipped(candidate),viewport:{width:innerWidth,height:innerHeight}}:null;
+ const context=kind==='text-field'?e.closest('.api-profile-row,.provider-secret,.setting-group'):null;
+ return {editable,kind,terminalView,surface:panel?'settings':'canvas',viewport:{width:innerWidth,height:innerHeight},dragRects,rect:normalized(r),contextRect:context?clipped(context):null,fontSize:editable?parseFloat(getComputedStyle(e).fontSize)||14:null,caret:r&&c&&c.x>=r.x-2&&c.y>=r.y-2&&c.right<=r.right+2&&c.bottom<=r.bottom+2?normalized(c):null};
+}
+module.exports={focusScript:'('+readFocus.toString()+')()'};
diff --git a/integrations/canvaslink/host/frames.js b/integrations/canvaslink/host/frames.js
new file mode 100644
index 000000000..de05b4467
--- /dev/null
+++ b/integrations/canvaslink/host/frames.js
@@ -0,0 +1,11 @@
+// NativeImage pixels are BGRA with premultiplied alpha; ImageData expects RGBA.
+// The main process waits for frameConsumed before sending another full frame.
+(function(root){
+ function rgba(pixels,width,height){
+ if(!ArrayBuffer.isView(pixels)||pixels.byteLength!==width*height*4||width<1||height<1||width>2560||height>1600)throw Error('invalid-bitmap-frame');
+ const data=new Uint8ClampedArray(pixels);
+ for(let i=0;i
+
+CanvasLink
+
+
+C↗
CanvasLink
Рабочее окно. На расстоянии касания.
LOCAL / 01
+
Очки Even G2
Отдельный код и выбранные в CanvasTTY разрешения для очков.
01 — ПОДКЛЮЧЕНИЕ ANDROID
··· ···
Подготовка…
+
02 — ОКНО ДЛЯ ПЕРЕДАЧИ
На macOS при первом запуске потребуется разрешение на запись экрана. Передаётся выбранное окно CanvasTTY.
+
03 — ПРЯМОЕ СОЕДИНЕНИЕ
Откройте CanvasLink на Android, выберите компьютер и введите код. Оба устройства должны быть в одной локальной сети.
+
Ожидание планшета
+
ДОСТУП MACOS
Включите CanvasLink в открывшемся списке. После выдачи доступа перезапустите только CanvasLink.
{ru ? "Анимированные сцены внутри окон терминалов. Выберите фон и настройте его с живым предпросмотром." : "Animated scenes inside terminal windows. Choose a background and adjust it with a live preview."}
+
+
+
+ {scope ? <>
+ {override ? (ru ? "У этого терминала своё оформление." : "This terminal has its own appearance.")
+ : (ru ? "Использует общие настройки. Любая правка создаст отдельное оформление." : "Uses defaults. Any change creates its own appearance.")}
+
+
+
+
+ > : <>
+
+ {hasAnyBackground && (
+
+ {ru ? (hasOverrides
+ ? `Внимание: у ${overrideCount} ${overrideCount === 1 ? "терминала" : "терминалов"} задан индивидуальный фон. Кнопка выше отключит фоны сразу на всех терминалах.`
+ : "Отключает фоновые анимации на всех терминалах.")
+ : (hasOverrides
+ ? `Note: ${overrideCount} terminal(s) have individual backgrounds. The button above will disable backgrounds on all terminals.`
+ : "Disables background animations on all terminals.")}
+
+ )}
+ >}
+
}
+ {error && {error}}
+ ;
+}
diff --git a/src/renderer/src/features/settings/CanvasLinkSettings.css b/src/renderer/src/features/settings/CanvasLinkSettings.css
new file mode 100644
index 000000000..982d321ce
--- /dev/null
+++ b/src/renderer/src/features/settings/CanvasLinkSettings.css
@@ -0,0 +1,10 @@
+.canvaslink-settings{max-width:54rem;color:var(--text);line-height:1.5}
+.canvaslink-settings__intro{padding:.3rem 0 1.6rem}.canvaslink-settings__eyebrow{font:600 .7rem var(--font-mono,monospace);letter-spacing:.1em;color:var(--primary)}
+.canvaslink-settings h3{font-size:1.05em;margin:0 0 .4rem}.canvaslink-settings__intro h3{font-size:1.55em;letter-spacing:-.025em}.canvaslink-settings p{margin:.4rem 0;color:var(--text-muted-on-dark)}
+.canvaslink-settings__card{padding:1.4rem;margin-bottom:1rem;border:1px solid color-mix(in srgb,var(--text) 13%,transparent);border-radius:1rem;background:color-mix(in srgb,var(--surface-soft) 65%,var(--surface))}
+.canvaslink-settings__row{display:flex;gap:1.2rem;align-items:center;justify-content:space-between}.canvaslink-settings__status{font-size:.85em}.canvaslink-settings__connection{margin-top:1.2rem;border-top:1px solid color-mix(in srgb,var(--text) 10%,transparent);padding-top:.8rem}
+.canvaslink-settings ol{padding-left:1.3rem;font-size:.9em;color:var(--text-muted-on-dark)}.canvaslink-settings li+li{margin-top:.45rem}.canvaslink-settings__code-block{display:flex;flex-direction:column;align-items:flex-start;gap:.35rem;margin:1.2rem 0}.canvaslink-settings__code-block>span,.canvaslink-settings small{font-size:.8em;color:var(--text-muted-on-dark)}
+.canvaslink-settings__code{font:600 clamp(1.8rem,4vw,2.8rem)/1.3 var(--font-mono,monospace);letter-spacing:.14em;color:var(--text);font-variant-numeric:tabular-nums}.canvaslink-settings__button{min-height:48px;padding:.65rem 1rem;border:1px solid color-mix(in srgb,var(--text) 25%,transparent);border-radius:.65rem;color:var(--text);background:transparent;font:inherit;font-size:.85em;cursor:pointer}.canvaslink-settings__button:hover{background:color-mix(in srgb,var(--text) 8%,transparent)}.canvaslink-settings__button--primary{border-color:var(--primary);background:var(--primary);color:var(--text-dark)}.canvaslink-settings__button--primary:hover{background:var(--primary-hover)}.canvaslink-settings__button:focus-visible{outline:2px solid var(--primary);outline-offset:3px}.canvaslink-settings__button:disabled{opacity:.55;cursor:wait}
+.canvaslink-settings__card--quiet p{font-size:.85em}.canvaslink-settings__note{font-size:.9em}.canvaslink-settings__devices h4{margin:.8rem 0 .4rem}.canvaslink-settings__error{color:var(--danger)!important}
+.canvaslink-settings__install-actions{display:flex;flex-wrap:wrap;gap:.6rem;margin:.9rem 0}
+@media(max-width:760px){.canvaslink-settings__row{align-items:flex-start;flex-direction:column}.canvaslink-settings__card{padding:1rem}}
diff --git a/src/renderer/src/features/settings/CanvasLinkSettings.tsx b/src/renderer/src/features/settings/CanvasLinkSettings.tsx
new file mode 100644
index 000000000..1caa5e0c2
--- /dev/null
+++ b/src/renderer/src/features/settings/CanvasLinkSettings.tsx
@@ -0,0 +1,107 @@
+import { useEffect, useRef, useState } from "react";
+import type { LocaleId } from "../../../../shared/contracts";
+import type { CanvasLinkCommand, CanvasLinkState } from "../../../../shared/canvasLink";
+import { CANVASLINK_ANDROID_RELEASE, canvasLinkInstallPrompt } from "../../../../shared/canvasLinkInstall";
+import "./CanvasLinkSettings.css";
+
+export function CanvasLinkSettings({ locale, open }: { locale: LocaleId; open: boolean }) {
+ const [state, setState] = useState(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [promptCopied, setPromptCopied] = useState(false);
+ const revision = useRef(0);
+ const text = (ru: string, en: string) => locale === "ru" ? ru : en;
+
+ function copyInstallPrompt() {
+ try {
+ window.canvasTTY.clipboard.writeText(canvasLinkInstallPrompt(locale));
+ setPromptCopied(true);
+ } catch {
+ setPromptCopied(false);
+ setError(text("Не удалось скопировать промпт. Откройте инструкцию.", "Could not copy the prompt. Open the installation guide."));
+ }
+ }
+
+ useEffect(() => {
+ if (!open) return;
+ let active = true;
+ let timer: ReturnType;
+ async function poll() {
+ const current = revision.current;
+ try {
+ const next = await window.canvasTTY.canvasLink.state();
+ if (active && current === revision.current) setState(next);
+ } catch {
+ if (active) setError(locale === "ru" ? "Не удалось получить состояние подключения." : "Could not read connection status.");
+ } finally {
+ if (active) timer = setTimeout(poll, 1000);
+ }
+ }
+ void poll();
+ return () => { active = false; clearTimeout(timer); };
+ }, [open, locale]);
+
+ async function run(action: CanvasLinkCommand) {
+ revision.current++;
+ setBusy(true);
+ setError("");
+ try { setState(await window.canvasTTY.canvasLink.command(action)); }
+ catch { setError(text("Действие не выполнено. Попробуйте ещё раз.", "The action failed. Try again.")); }
+ finally { revision.current++; setBusy(false); }
+ }
+ const button = (label: string, action: CanvasLinkCommand, primary = false) => (
+
+ );
+ const enabled = !!state?.enabled;
+ const devices = state?.devices ?? [];
+ const seconds = Math.max(0, Math.ceil(((state?.expires ?? 0) - Date.now()) / 1000));
+ const status = !enabled ? text("Выключено", "Off") : devices.length
+ ? state?.phase === "streaming" ? text("Подключено · видео и управление", "Connected · video and control")
+ : text("Устройство связано · подключение", "Device paired · connecting")
+ : text("Ожидает подключения", "Waiting for connection");
+
+ return
+
+
{text("ТЕЛЕФОН И ПЛАНШЕТ", "PHONE AND TABLET")}
+
{text("Ваш CanvasTTY на Android", "Your CanvasTTY on Android")}
+
{text("Работайте в этом окне с планшета или телефона. Оба устройства должны быть в одной локальной сети.", "Use this window from your tablet or phone. Both devices must be on the same local network.")}
+
+
+
{text("Установить на Android", "Install on Android")}
+
{text("Подключите телефон или планшет по USB, включите USB-отладку и подтвердите запрос на Android. Скопируйте промпт своему агенту — он проверит APK и установит приложение. После установки USB не нужен.", "Connect your phone or tablet over USB, enable USB debugging and approve the Android prompt. Copy the prompt to your agent: it will verify the APK and install the app. USB is not needed after installation.")}
+
+
+
+
+ {promptCopied &&
{text("Промпт скопирован. Вставьте его в чат с агентом на этом компьютере.", "Prompt copied. Paste it into your agent chat on this computer.")}
{text("Откройте CanvasLink на Android.", "Open CanvasLink on Android.")}
+
{text("Выберите этот компьютер и введите код. IP-адрес вводить не нужно.", "Select this computer and enter the code. No IP address is needed.")}
+ {state?.pin && seconds > 0 ?
+ {text("Одноразовый код", "One-time code")}
+
+ {text(`Действует ещё ${seconds} с`, `Valid for ${seconds} s`)}
+
:
{devices.length ? text("Устройство связано. Код больше не нужен до завершения сессии.", "Device paired. No code is needed until this session ends.") : text("Срок действия кода истёк. Получите новый код.", "The code expired. Get a new code.")}
{text("Управление с планшета", "Tablet controls")}
+
{text("Коснитесь терминала, чтобы открыть клавиатуру. Ввод передаётся напрямую; Enter запускает команду. При потере связи ввод автоматически не повторяется. Доступ распространяется на всё это окно CanvasTTY.", "Tap a terminal to open the keyboard. Input is sent directly; Enter runs the command. Input is never automatically replayed after a disconnect. Access covers this entire CanvasTTY window.")}
+
{text("Очки Even G2 подключаются отдельно — в разделе «Внешние интеграции». Коды и доступы независимы.", "Even G2 glasses connect separately under External integrations. Their codes and access are independent.")}