提交 Haven Android 仓库源码 v5.87.79

This commit is contained in:
ali
2026-09-10 13:45:36 +08:00
parent 87b452c4dc
commit 22f4ca5830
2524 changed files with 599455 additions and 1 deletions
@@ -0,0 +1,202 @@
# Plan — custom text-selection toolbar for the floating text input dialog
## ⚠️ ROUND 2 (2026-07-23) — round-1 fix FAILED real-device test, new lead found
The round-1 implementation (custom `TextToolbar` via `LocalTextToolbar`, committed as
`f420edf1` on `fix/floating-text-input-selection-toolbar`) compiled clean, passed its own unit
tests, and was reasoned to be correct — but **Batin tested the real debug APK on his device and
the toolbar still does not appear.** Selection still works (handles visible), still no
Copy/Cut/Paste/Select-all menu. This is a genuine implementation failure, not a test error — do
not re-ship round 1 as-is.
**New lead, found by reading real Compose Foundation source** (`androidx/androidx` on GitHub,
`compose/foundation/foundation/.../text/selection/TextFieldSelectionManager.kt` and
`ComposeFoundationFlags.kt`): recent Compose Foundation has **two parallel context-menu systems**
gated by `ComposeFoundationFlags.isNewContextMenuEnabled` (default comes from a per-platform
`internal expect val isNewContextMenuInitiallyEnabled`, not confirmed for Android/this exact
version via web source alone — **verify the REAL compiled default by decompiling the actual
pinned `androidx.compose.foundation` AAR classes in this machine's Gradle cache, not by trusting
a web search** of the source, which hit rate limits and inconclusive results this round).
The doc comment on the flag: *"Whether to use the new context menu API and default
implementations in SelectionContainer and all BasicTextFields. If false, the previous context
menu that has no public APIs will be used instead."* `TextFieldSelectionManager.kt` branches on
this flag for how it decides the toolbar is "shown" (`textToolbarShownViaProvider` vs
`textToolbar?.status`), and toolbar display in the new-flag-true path appears to go through
`textContextMenuToolbarHandler()` / `updateFloatingToolbar()` — a **different mechanism than
`LocalTextToolbar.showMenu()`** entirely. **If this flag defaults to true for the pinned Compose
version, round 1's entire `LocalTextToolbar` override may be a no-op**, because the real UI path
never calls `showMenu` at all in that mode — this would fully explain the real-device failure
without any bug in round 1's own code.
**What round 2 must do, in order:**
1. Decompile/inspect the REAL `androidx.compose.foundation:foundation` jar for the exact version
this repo pins (check `gradle/libs.versions.toml` → compose-bom → resolve to the exact
foundation artifact version, same technique round 1 used successfully for the `TextToolbar`
interface via `javap`) to get the actual compiled default of `isNewContextMenuInitiallyEnabled`
on Android for that version. Don't guess from web search.
2. If the new system is enabled by default: find the real, current public API for customizing the
NEW context menu (search the same real Compose Foundation source/jar for whatever composition
local or provider interface the new system exposes — the AndroidX doc comment says the new
system "has public APIs", implying there IS a documented customization point; find its actual
name from the real source/jar, don't guess a name).
3. Decide and implement one of: (a) wire the fix through the new system's real customization API
instead of `LocalTextToolbar`, or (b) if `ComposeFoundationFlags.isNewContextMenuEnabled` can be
scoped/overridden narrowly (not just a single global static toggle affecting the whole app) —
verify whether it's genuinely global-only or has some scoping mechanism — and only fall back to
forcing it off globally if there's no narrower option, flagging that as an app-wide behavior
change for the reviewer to weigh consciously (it would also change every OTHER text field in
Haven, not just this dialog — that's a real, non-trivial trade-off to surface honestly, not
silently take).
4. This dialog uses Material3 `TextField`, not `BasicTextField` directly — confirm which context-
menu path Material3's `TextField` actually wires up to for the pinned Compose Material3
version too (it may not follow `BasicTextField`'s flag-gated behavior identically; verify, don't
assume it's the same).
5. Still no real device available in this environment — be exactly as honest as round 1 was about
what's proven vs. reasoned. If genuinely impossible to verify visual rendering without a real
device/emulator here, say so plainly and say what the NEXT real-device test should specifically
check, rather than re-claiming confidence that didn't hold up last time.
## Context (round 1, still accurate)
Batin found (real device, 2026-07-23): highlighting/selecting text inside the floating Text
Input dialog (`FloatingTextInputDialog.kt`) shows the selection handles fine, but the native
Android floating action-mode toolbar (Copy / Cut / Paste / Select all) that normally appears
above a text selection never shows up. Every other native text input on the device shows it
normally — only this dialog is missing it.
Root cause (verified, not guessed): the dialog renders its `TextField` inside a Compose `Popup`
(`Popup(properties = PopupProperties(focusable = true))`, `FloatingTextInputDialog.kt` line ~263).
This is a documented Compose limitation — a `TextField` inside a focusable `Popup` has a known
focus-management conflict with the platform `ActionMode`/text-selection-toolbar machinery, so the
toolbar silently never appears (no crash, no error — it just never shows). Source:
https://github.com/JetBrains/compose-multiplatform/issues/2810 (same underlying Popup+TextField
focus conflict, filed against Compose Multiplatform but the same root mechanism affects Compose
on Android). Not switching to `Dialog` to fix this: the design doc
(`docs/plans/floating-text-input.md`, already in this repo) and the maintainer's own device-test
comment on PR #439 confirm the `Popup` was chosen deliberately (isolated pointer-input dispatch —
verified no touch double-consumption with the terminal underneath; a `Dialog` would change that
touch-dispatch behavior and the tap-outside-to-dismiss-without-clearing-draft behavior, which is
already correct and tested). Fix the toolbar without changing the window type.
## Ground truth read before writing this plan (don't skip re-verifying this against upstream/main
before implementing — Haven moves fast, this repo was at v5.83.3 when this plan was written)
- Current file: `feature/terminal/src/main/kotlin/sh/haven/feature/terminal/FloatingTextInputDialog.kt`
(405 lines on `upstream/main` as of this writing). `TextField(...)` call is the one composable
that needs the toolbar fix; nothing else in the file changes.
- `git grep LocalTextToolbar` across the whole repo: **zero hits** — no existing custom
`TextToolbar` implementation anywhere in Haven to copy from. This is new ground, not a
copy-paste-from-elsewhere job.
- Existing clipboard-access idiom already used elsewhere in this codebase (match this style, don't
introduce Compose's `LocalClipboardManager` instead — it isn't used anywhere else here):
`core/toolbar/src/main/kotlin/sh/haven/core/toolbar/KeyboardToolbar.kt` line ~271:
```kotlin
val view = LocalView.current
val clipboardManager = remember {
view.context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
}
```
Use the same `LocalView.current` → platform `android.content.ClipboardManager` pattern here.
## The fix
Compose's public, documented escape hatch for exactly this situation is `TextToolbar` +
`LocalTextToolbar` (`androidx.compose.ui.platform.TextToolbar`, `LocalTextToolbar` composition
local) — verified against the real API reference:
https://developer.android.com/reference/kotlin/androidx/compose/ui/platform/TextToolbar . A custom
`TextToolbar` implementation gets exactly 4 fixed callback slots — `onCopyRequested`,
`onCutRequested`, `onPasteRequested`, `onSelectAllRequested` — the API does not support adding
extra menu items, which is fine here since those 4 are exactly what's missing.
**Verify the exact `TextToolbar` interface shape against the real installed Compose UI version
before writing code** — check `androidx.compose.ui:ui` version pinned in
`gradle/libs.versions.toml` and read the actual decompiled/sources-jar interface (`showMenu`,
`hide`, `status` members) rather than assuming from memory; the interface has changed slightly
across Compose versions in the past (parameter types on `showMenu`, e.g. `Rect` vs `Offset`-based
overloads).
Implementation shape (adjust exact signatures to whatever the verified real interface requires):
```kotlin
private class DialogTextToolbar(
private val view: View,
private val clipboardManager: ClipboardManager?,
) : TextToolbar {
override var status: TextToolbarStatus = TextToolbarStatus.Hidden
private set
override fun showMenu(
rect: Rect,
onCopyRequested: (() -> Unit)?,
onPasteRequested: (() -> Unit)?,
onCutRequested: (() -> Unit)?,
onSelectAllRequested: (() -> Unit)?,
) {
// Build a small Compose-based floating menu (a Popup positioned at `rect`,
// OR — simpler and known to sidestep the same Popup-in-Popup focus issue —
// a plain Android PopupWindow anchored via `view`) with up to 4 buttons,
// calling straight through to the passed callbacks. Verify which approach
// actually renders/dismisses correctly inside the outer floating-text-input
// Popup before committing to one — this is the one part of the plan that's
// a genuine implementation risk, not a known-good recipe. Test on a real
// device/emulator, not just "it compiles".
status = TextToolbarStatus.Shown
}
override fun hide() {
status = TextToolbarStatus.Hidden
}
}
```
Wire it in `FloatingTextInputDialog.kt` around just the `TextField`:
```kotlin
val view = LocalView.current
val clipboardManager = remember {
view.context.getSystemService(Context.CLIPBOARD_SERVICE) as? ClipboardManager
}
val customToolbar = remember(view, clipboardManager) { DialogTextToolbar(view, clipboardManager) }
CompositionLocalProvider(LocalTextToolbar provides customToolbar) {
TextField(
value = text,
onValueChange = onTextChange,
// ...unchanged...
)
}
```
`onCopyRequested`/`onCutRequested`/`onPasteRequested`/`onSelectAllRequested` operate on the
`TextFieldValue`'s current selection (`text`/`onTextChange` are already hoisted to the caller per
the existing design — the toolbar callbacks read/write through those, they don't need their own
state) plus `clipboardManager.setPrimaryClip(...)`/`getPrimaryClip()` for the actual clipboard I/O,
matching the existing `KeyboardToolbar.kt` idiom.
## What to verify before calling this done
1. Real device or emulator test (not just compile): open the dialog, type multi-word text, select
a range by drag, confirm the Copy/Cut/Paste/Select-all toolbar now appears and each button
actually works (copy → paste back in, cut removes + clipboard has it, select-all selects
everything).
2. Confirm the toolbar's own popup/menu doesn't visually break or get clipped by the outer
floating-text-input window's bounds — this is the actual open implementation risk flagged
above, verify it doesn't recreate a NEW version of the same Popup-focus problem one level down.
3. Confirm existing behavior is unchanged: bracket-paste send path, drag-to-move, resize, TalkBack
custom actions (move/resize) — this fix should touch nothing except the selection toolbar.
4. Re-run whatever this module's existing Compose UI tests are (check for a
`FloatingTextInputDialogTest.kt` or similar under `feature/terminal/src/test` /
`src/androidTest` — verify it exists and what it currently covers before assuming there's
nothing to run).
## What NOT to do
- Do not switch `Popup` to `Dialog` to sidestep the issue — changes touch-dispatch behavior that's
deliberate and already tested (see Context section above).
- Do not touch any file other than `FloatingTextInputDialog.kt` (and a new test file if one is
warranted) — this is a scoped, single-file fix.
- Do not guess the `TextToolbar` interface shape from a general Compose blog post — verify against
the actual pinned Compose UI version's real interface first.
- Do not commit/push — leave changes as an uncommitted diff on a fresh branch cut from
`upstream/main` for review before anything ships.
@@ -0,0 +1,302 @@
# Floating text-input dialog for terminal
Status: planning — red-team reviewed 2026-07-22 (4 independent Fable-5 passes:
gesture/UX conflict, architecture-integration correctness, multi-tab/state
risk, completeness/testing gaps). Corrections below are resolved decisions,
not open questions, unless marked otherwise. Target: next minor after this
revision is accepted.
## Corrections from red-team review (2026-07-22)
1. **Send path must go through bracket-paste-aware injection, not raw
`sendInput`.** Two independent passes flagged this. Haven's existing
paste path checks `bracketPasteMode`/mode 2004 and wraps in
`ESC[200~…ESC[201~` before calling `sendInput` (see
`TerminalScreen.kt` `doPaste`, ~line 1117–1128, and the scan-injection
comment at ~line 321–335 — read the exact lines at implementation time,
they may drift). `sendInput` itself never wraps; callers decide. The new
dialog is explicitly a multi-line-capable input (the `↩`/`⇥` visual
transform is the point) — sending raw newlines unwrapped means every
embedded `\n` executes as a literal Enter in the remote session (e.g.
inside `vim`/`psql`), not as "paste this whole block." **Decision: reuse
the same bracket-wrap helper the paste path uses, do not call
`activeTab.sendInput` directly with unwrapped bytes.**
2. **Dialog must render inside `key(activeTab.sessionId)`, and draft text
must be hoisted out per-tab.** The per-tab UI subtree in
`TerminalScreen.kt` is wrapped in `key(activeTab.sessionId) { ... }`
(~line 875–879, confirm exact range at implementation time). Two tabs
can look identical UI-wise while the *active* tab changes without a
user tap on the tab bar — a session dying (`syncTabs` clamps the index),
an MCP-driven `selectTabBySessionId`, or a delayed `selectTabByProfileId`
(~2s async). If the dialog is rendered **outside** that `key()` block,
its send closure re-binds to whatever tab is active *at send time*, not
the tab that was active when typing started — typed text can go to the
wrong session with no visible tab-switch to notice. Rendering **inside**
`key()` avoids this by construction (a tab-identity change tears down
and recreates the subtree, so a send can never outlive its own tab) at
the cost of losing an in-progress, unsent draft on tab switch. Decision:
accept that trade — safety over convenience for a feature whose whole
purpose is precise text delivery. Mitigate the convenience loss by NOT
storing draft text in local Compose `remember` inside the dialog itself;
instead keep an in-memory `Map<sessionId, String>` of drafts one level up
(e.g. in the screen's own state or a small holder), so switching back to
a tab restores what was typed there, even though the dialog instance
itself was torn down and recreated.
3. **Toolbar integration must go through the `ToolbarKey` system, not a
bare callback + hardcoded button.** Confirmed (not just "check in
review" as originally written): the toolbar is data-driven off
`enum class ToolbarKey`, rendered through `ToolbarItem.BuiltIn(key)`
layouts and `when (key)` branches, and the settings editor iterates
`ToolbarKey.entries` for the user-facing reorder/configure UI. A bare
`IconButton` bypasses reorder mode, uniform-grid layout, and the
settings editor entirely — inconsistent with how every other toolbar
action in this app works. Concrete touch points (verify exact file/line
at implementation time, this is from a point-in-time read): new
`ToolbarKey` entry, a `KeyVisual`/icon mapping, a `when(key)` render
branch in `KeyboardToolbar.kt`, a new `ToolbarCallbacks` field
(mirroring `onAttachTap`), and confirming the settings-editor listing
picks it up automatically via `ToolbarKey.entries` (it should, if the
enum entry is added correctly — verify, don't assume).
4. **Restore focus to the terminal on dismiss.** Plan previously wrote
`onDismiss = { showTextInputDialog = false }`. Add the terminal's own
focus requester call on dismiss (upstream's ConsoleScreen does this;
find Haven's equivalent terminal `FocusRequester` in `TerminalScreen.kt`
and call `.requestFocus()` in the dismiss lambda, not just flip the
boolean).
5. **License attribution must be file-level, not just the existing
README dependency-table row.** Haven's own `LICENSE` is AGPL-3.0; the
README's "ConnectBot termlib | Apache-2.0" row is a *dependency* credit
for the separate termlib submodule, not blanket coverage for copying
application-layer UI source out of the same upstream project. Apache-2.0
§4 requires retaining attribution in copied source. House precedent
exists for exactly this (an existing `.kt` file in this repo carries a
"Ported from &lt;project&gt; (&lt;license&gt;)…" comment; there is also a
NOTICE-style doc for asset attribution elsewhere in the repo — find and
match that pattern, don't invent a new one). Add: (a) an Apache-2.0
license header block at the top of the new file (matching upstream's),
(b) a short "Ported from org.connectbot.ui.components.FloatingTextInputDialog
(Apache-2.0)" comment, (c) keep the existing README dependency-table row
as-is (it's still correct, just not sufficient alone).
6. **Use `rememberSaveable`, not `remember`, for in-progress draft text**
(in whatever form the per-tab draft map from item 2 takes) — plain
`remember` loses unsent typed text across rotation or process death from
backgrounding. This holds user-authored content, unlike the
`attachSheetVisible` boolean flag it was templated from (losing a
dialog-open boolean is harmless; losing typed text is not).
7. **Add a CHANGELOG.md entry before shipping.** Confirmed CI-enforced
(`scripts/check-changelog.sh`) — a release cannot ship without its
section. Add this to whatever step actually ships the feature, not
just to this plan.
8. **Accessibility: decide explicitly, don't leave silent.** The
move/resize interactions are raw `pointerInput { detectDragGestures }`
drags with no `semantics { customActions }` — invisible to TalkBack.
Haven has shipped explicit TalkBack work for the terminal before
(gesture accessibility descriptions in a recent release), so this
project visibly cares about this class of gap. Minimum bar: either add
semantic custom actions for move/resize, or explicitly document in the
PR description that position is fixed (not TalkBack-adjustable) as a
known, accepted limitation — do not ship silently unaddressed.
### Noted but deferred to implementation-time judgment (not blocking)
- The dialog's containing `Popup` covers the full screen while open
(matches upstream), which means terminal scroll/selection/mouse-SGR
reporting AND Haven's own swipe-to-switch-tab gesture are all
unavailable while the dialog is open (no double-dispatch risk — Compose
`Popup` is a genuinely separate window — but a real "everything else is
frozen" UX trade while it's up). Decide at implementation time whether
to keep full-screen modal (simplest, matches upstream) or size the popup
window to its own content instead of `fillMaxSize` so a tap outside its
bounds can still reach the terminal.
- Haven already has at least two related-but-different mechanisms for
"phone keyboard vs. terminal" friction (a `COMPOSE` IME-composition
toolbar mode and a `VOICE_KEYBOARD` mode). Worth one sentence in the
eventual PR description on why this is additive rather than overlapping,
but not a blocker.
- Rotation/split-screen: the screen-fraction position/size persistence
(inherited from upstream) can go stale across a resize without full
Activity recreation; this is a pre-existing upstream gap, not introduced
by the port. Fine to inherit as-is unless it proves annoying in testing.
- Existing snippet-library injection path uses a similar send mechanism —
worth a byte-level parity check during testing, not a design change.
## Goal
Port ConnectBot's "Text Input" floating dialog into Haven's terminal screen.
Lets the user type a full command/line into a normal Compose `TextField`
(full IME: autocorrect, cursor movement, voice input, swipe typing) instead
of fighting the raw terminal cell for text entry, then send the whole
string to the active session in one shot.
## Why
Typing directly onto the terminal surface on a phone software keyboard is
error-prone: the keyboard's autocorrect/predictive layer and the terminal's
own key-dispatch path interact badly, cursor/backspace behavior over an
already-rendered terminal cell is confusing, and there is no way to review
what you typed before it goes out keystroke-by-keystroke. Batin hit this
directly on `nec` (screenshot, 2026-07-22) and asked for ConnectBot's
existing "Text Input" feature, which solves exactly this by decoupling
"where you type" (a normal text box) from "where it's displayed" (the
terminal).
## Source
`org.connectbot.ui.components.FloatingTextInputDialog` in
[connectbot/connectbot](https://github.com/connectbot/connectbot)
(`app/src/main/java/org/connectbot/ui/components/FloatingTextInputDialog.kt`),
Apache-2.0 — same license as Haven's existing `termlib` dependency from the
same upstream, already credited in `README.md`. Confirmed present in the
current upstream tree (not from an older/incompatible architecture): it is
a Jetpack Compose `@Composable`, same UI framework Haven uses throughout
(`feature/terminal/.../TerminalScreen.kt` is Compose-based too).
Upstream shape (as read from source, not guessed):
- Draggable + resizable `Popup` positioned/sized from `SharedPreferences`
(`floating_input_x/y/width/height`, stored as screen-fraction floats).
- One Compose `TextField` with a `VisualTransformation` that shows `↩` for
embedded newlines and `⇥` for tabs inline while keeping the real
characters in the underlying string.
- Header row: title + close (`X`) button, draggable to reposition.
- Footer/side: send button (paper-plane icon) and a resize handle
(`OpenInFull` icon), both via `pointerInput { detectDragGestures { ... } }`.
- Send path: `bridge.injectString(text)` then clear the field. Field is
**not** auto-cleared on dismiss without sending (only `X`/outside-tap
dismisses without send).
## Integration point in Haven (found by reading the code, not assumed)
Haven's per-tab session object already exposes the exact primitive needed:
```kotlin
activeTab.sendInput(bytes: ByteArray)
```
used today for paste (`TerminalScreen.kt`, both the main toolbar and the
selection-toolbar paste path):
```kotlin
onPaste = { text -> activeTab.sendInput(text.toByteArray()) },
```
So the port is `bridge.injectString(text)` → `activeTab.sendInput(text.toByteArray())`,
not a new session-write path.
`KeyboardToolbar` (`core/toolbar/.../KeyboardToolbar.kt`) already follows a
plain callback-param pattern for toolbar actions, e.g.:
```kotlin
val onAttachTap: () -> Unit = {}
```
The new trigger button follows the same shape: `onOpenTextInput: () -> Unit = {}`,
wired from `TerminalScreen.kt` to flip a `showTextInputDialog` state flag,
same pattern as the existing `attachSheetVisible` flag for the attach sheet.
## Plan
1. **New file** `feature/terminal/.../FloatingTextInputDialog.kt` (package
`sh.haven.feature.terminal`, not a straight file copy into
`org.connectbot.*` — Haven has already re-namespaced its own code).
Port the Composable body as-is; only the send call changes
(`activeTab.sendInput(text.toByteArray())`). Reuse Haven's own
`MaterialTheme` color roles already in use elsewhere in this file so it
matches Haven's theme, not ConnectBot's.
2. **String resources**: add Haven-side keys (do not assume upstream's
exact resource names carry over; Haven's `R.string.*` catalog is its
own). Needs: dialog title, placeholder/label, close/send content
descriptions, resize-handle content description. Add to the base
`strings.xml`; do **not** hand-translate into every locale Haven ships —
flag as a translation-debt item for whatever process currently handles
Haven's i18n (fastlane/metadata shows many locales already tracked).
3. **Toolbar wiring**: add `onOpenTextInput: () -> Unit = {}` to
`KeyboardToolbar`'s param list (mirroring `onAttachTap`), add one
`IconButton`/`KeyCell` entry, decide **exact placement** in review (a
free slot, or behind the existing toolbar's overflow/settings path —
`TerminalScreen.kt` already treats the toolbar as configurable
`toolbarLayout`/`uniformGrid`, so this may need a `ToolbarKey`-style
entry rather than a bare hardcoded button — check `ToolbarKey` enum
before assuming a raw button is idiomatic here).
4. **State**: `var showTextInputDialog by remember { mutableStateOf(false) }`
in `TerminalScreen.kt`, same shape as `attachSheetVisible`; render
`FloatingTextInputDialog(activeTab, onDismiss = { showTextInputDialog = false })`
conditionally, same conditional-render pattern already used for the
attach sheet / VNC dialog in this file.
5. **Persistence keys**: upstream uses bare `SharedPreferences` keys
(`floating_input_x` etc.) with no per-profile/per-tab scoping — confirm
in review whether Haven wants this shared across all tabs/profiles
(upstream behavior) or scoped, since Haven supports multiple concurrent
tabs/sessions unlike a single-session assumption this key naming might
imply.
## Open questions for review (not decided here)
- Does the floating window's own `pointerInput { detectDragGestures }`
(drag-to-move, drag-to-resize) fight with `TerminalScreen.kt`'s existing
gesture stack (`combinedClickable`, mouse SGR reporting, text selection
drag, scroll) when the dialog is shown as an overlay `Popup` on the same
screen? Upstream renders it as a `Popup(properties = PopupProperties(focusable = true))`
— need to confirm Compose `Popup` truly isolates its own pointer input
from the composables underneath, not just visually.
- Toolbar placement: is there a free `ToolbarKey` slot, or does adding one
require a settings-visible toggle (Haven's toolbar is already
user-configurable per `toolbarLayout`/`uniformGrid`/`editModeControlsPlacement`)?
- Multi-tab semantics: should the dialog be tied to `activeTab` only (text
vanishes if the user switches tabs mid-type), or should in-progress text
survive a tab switch?
- i18n debt: how many locales realistically need the new strings before
ship vs. after (Haven tracks translations in `fastlane/metadata/android/<locale>`
for store listings; in-app `strings.xml` locale coverage is separate and
wasn't audited here).
## Testing before ship
- Real device (not just `./gradlew assembleDebug` succeeding): open the
dialog over a live SSH/mosh/local session, type text with autocorrect
on, send, confirm exact bytes land in the session, correctly bracket-
wrapped when the remote app has bracketed-paste mode on (test explicitly
inside `vim`/`psql`: an embedded newline must not execute as Enter).
- Confirm existing terminal gestures (scroll, tap-to-position-cursor,
text selection, mouse reporting on apps like `less`/`vim`) still work
normally with the dialog closed, and that opening/closing the dialog
doesn't leave the terminal's focus/keyboard state stuck (focus must
return to the terminal on dismiss, not just close the dialog).
- **Multi-tab specific (new, from red-team review):**
- Start typing in the dialog, switch tabs via the tab bar mid-type,
switch back — confirm the draft text is restored for that tab (per
the per-tab draft map) and confirm nothing was sent to the tab you
switched to.
- Trigger a *non-tap* active-tab change while the dialog is open (an
MCP-driven tab select, or let a session die so the active index
clamps to another tab) — confirm the dialog tears down safely (no
crash, no send into the wrong session) rather than silently rebinding
its send target.
- Close the tab whose dialog is open (if reachable) — confirm no crash
from a stale `sendInput` reference into a removed transport.
- Send text into a tab whose transport has since disconnected — confirm
this fails silently/loudly in a way consistent with how paste already
behaves for a dead session (don't introduce a new crash path).
- Confirm dialog position/size persists across dialog close+reopen and
across app restart (matches upstream's `SharedPreferences` contract);
confirm draft text survives rotation (via `rememberSaveable`/hoisted
state) rather than being silently discarded.
- Toolbar: confirm the new button appears correctly through the normal
toolbar settings/reorder editor (drag it, hide it, restore it) like any
other `ToolbarKey` — not just that it renders in the default layout.
- Accessibility: with TalkBack on, confirm the documented behavior (either
working custom actions for move/resize, or the accepted "position fixed
under TalkBack" limitation) — don't ship with an undocumented silent gap.
- Before merge: CHANGELOG.md has an entry (CI-enforced by
`scripts/check-changelog.sh` — a release cannot ship without it).
- Rollback: this is a pure addition (new file + one new `ToolbarKey` entry
+ new strings + one focus-restore call) — revert is a single commit
revert, no data-model or migration involved, low regression risk if
reverted.
@@ -0,0 +1,176 @@
# VNC-as-child-of-SSH refactor
Status: planning. Target: v5.25.0.
## Goal
Replace the current "VNC fields bolted onto an SSH profile" + "VNC profile
with `vncSshProfileId` back-reference" dual model with a single clean
parent → child relationship. A VNC service that runs over an SSH tunnel
becomes a separate `ConnectionProfile` row whose `parentId` points at its
SSH tunnel. Standalone VNC (no tunnel) has `parentId = null`.
The same shape generalises later to RDP-over-SSH and any "service hosted
by another connection" pattern.
## Why
Today there are two ways to express "VNC reached through SSH":
1. A profile with `connectionType = "VNC"`, `vncSshForward = true`,
`vncSshProfileId` pointing at the parent SSH profile.
2. A profile with `connectionType = "SSH"` and `vncPort` / `vncUsername` /
`vncPassword` / `vncColorDepth` / `vncSshForward` populated — created
by the terminal's "Save for this connection" path in the VNC quick
dialog.
This duality has caused real bugs (e.g. v5.24.38: the colour-depth
dropdown was wired into path 1's edit dialog but missing from path 2's
"Saved VNC settings" block — Nesos-ita's #107 follow-up). It also makes
it impossible to host two VNC services on one SSH tunnel
(`:0` on 5900 + `:1` on 5901), which is a normal multi-display setup.
A single `parentId` column collapses both representations into one.
## Data model
One new column on `ConnectionProfile`:
```kotlin
val parentId: String? = null // FK → ConnectionProfile.id, ON DELETE SET NULL
```
What this lets us delete (eventually):
- `vncSshProfileId` (subsumed by `parentId`)
- `vncSshForward` (`parentId != null` is the signal)
- The "Saved VNC settings" block on SSH profiles — those fields move to
child VNC profiles
- The duality where a `connectionType = "SSH"` row may also carry VNC
state
## Migration (DB v40)
Walk every existing profile:
1. **SSH with stored VNC fields** (`type=SSH && vncPort != null`):
insert a new child `type=VNC` row with `parentId = ssh.id`, copy
`vncPort` / `vncUsername` / `vncPassword` / `vncColorDepth` to its
own port/username/password/colour-depth fields, then null those
fields on the SSH parent.
2. **VNC with `vncSshProfileId` set**: `parentId = vncSshProfileId`.
Drop the now-redundant `vncSshForward` flag.
3. **Standalone VNC** (`vncSshForward = false`, no `vncSshProfileId`):
`parentId = null`, no other change.
4. **Orphan check**: if `parentId` references a row that doesn't exist
(deleted at some point), `parentId = null` and keep the VNC profile
as standalone with whatever host it has.
`BackupService` mirrors the same migration when importing old backup
files (a v5.24.x backup must restore cleanly into v5.25.x).
## UI
### Connections list
Child profiles render indented under their parent, with a connector
glyph. Long-press menu on an SSH profile gains "Add VNC service" / "Add
RDP service".
### `ConnectionEditDialog` — three modes
| Mode | Layout |
|---|---|
| **SSH (no parent)** | Only SSH fields. Bottom of dialog shows "Services on this SSH connection" with a list of children (tap to edit) and an "Add VNC / Add RDP" row. |
| **VNC with parent** | Header reads "Through: [Parent SSH name]" (non-editable, links to parent). Host field hidden (shows "Reachable from SSH server" hint with default `127.0.0.1`). Only VNC-specific fields: port, username, password, colour depth, label, color tag. |
| **VNC standalone** | Current standalone VNC layout, no changes. |
### Terminal's VNC quick dialog
When the user clicks the "VNC" affordance from inside a terminal session,
instead of stuffing fields onto the SSH profile via "Save for this
connection", we **create or update the child VNC profile**:
- look it up by `parentId == ssh.id` first;
- if exactly one exists, edit it;
- if none, create one;
- if multiple, show a picker.
## Connection launch flow
`ConnectionsViewModel.connectVnc` already navigates with the SSH session
ID + tunnel host/port. The change is just where it reads the SSH parent
from: `parentId` instead of `vncSshProfileId`. End-user behaviour
identical for one tunneled VNC; just naturally supports multiple.
## Edge cases
- **Deleting a parent SSH profile**: Room's `ON DELETE SET NULL` orphans
the children. They become standalone VNC profiles pointing at whatever
host they had (which is usually `127.0.0.1`, so the user will need to
fix the host before the standalone profile becomes usable).
Alternatives considered:
- Refuse delete if children exist — bad for the "I'm cleaning up"
workflow.
- Cascade delete — silently drops the child's saved password. Worse.
- **`vncSshForward = false` on a VNC with `vncSshProfileId` set** —
pre-existing contradiction in the data. Migration resolves by trusting
the back-reference (sets `parentId`).
- **Multiple VNC children on one SSH** — supported with no extra UX
work; user just adds another via the "Add VNC service" entry.
## Critical files
| File | Change |
|---|---|
| `core/data/.../entities/ConnectionProfile.kt` | add `parentId: String?` |
| `core/data/.../db/HavenDatabase.kt` | v39 → v40 + `MIGRATION_39_40` (the four-case walk above) |
| `core/data/.../db/DatabaseModule.kt` | register the migration |
| `core/data/.../db/ConnectionRepository.kt` | `childrenOf(parentId)` query |
| `core/data/.../backup/BackupService.kt` | round-trip `parentId`; same migration on import |
| `feature/connections/.../ConnectionsScreen.kt` | indent children, "Add service" entry on long-press menu |
| `feature/connections/.../ConnectionEditDialog.kt` | three-mode rework above; remove "Saved VNC settings" block |
| `feature/connections/.../ConnectionsViewModel.kt` | `VncNavigation` constructed via parent lookup |
| `feature/terminal/.../TerminalScreen.kt` | `VncSettingsDialog` writes a child profile, not SSH fields |
## Phasing
- **Phase 1** — data only (~1 day): add `parentId`, migration,
BackupService, repository helper, migration tests. Both new and old
code paths read from `parentId` — UI unchanged.
- **Phase 2** — edit + launch (~1 day): edit dialog three-mode rework;
connection launch reads from `parentId`. Old code paths still work as
a safety net via fallback to `vncSshProfileId`.
- **Phase 3** — list + terminal + cleanup (~1 day): connections list
indenting, terminal quick-dialog rewrite, delete `vncSshProfileId` /
`vncSshForward` / SSH-with-VNC-fields code.
- **Phase 4** — optional follow-up: apply the same to RDP
(`rdpSshForward` path) and any future protocol that runs over SSH.
## Verification
- **Unit tests** for the migration with five fixture profiles (one of
each scenario above + an orphan).
- **Round-trip** a v5.24.38 backup file through the new code; existing
profiles + saved-VNC-settings appear as parent + child.
- **Manual — existing user, no regression**: a user with
terminal-quick-dialog-saved VNC settings sees no functional change;
the "VNC" button still launches the same target with the same colour
depth and password.
- **Manual — new capability**: create two VNC children under one SSH
parent (e.g. ports 5900 and 5901), both connect via the same SSH
session.
- **Manual — orphaning**: delete an SSH profile that has VNC children;
children become standalone, are still listable + editable, and the
edit dialog now shows the host field.
## Out of scope
- Replacing the per-profile reachability / IP-discovery logic.
- Anything to do with how the SSH session itself is established (reuses
existing `SshSessionManager`).
- The eventual extraction of "tunnels" as their own first-class entity
separate from "shells you can attach to" — for now, an SSH profile is
both.
- Promoting `parentId` to a real Room foreign-key relation; we leave it
as a plain `String?` and rely on the migration / orphan check.