You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@maka.apache.org by "testikun (via GitHub)" <gi...@apache.org> on 2026/09/26 02:25:15 UTC

[PR] feat(desktop): hand off live terminals for private user input [maka]

testikun opened a new pull request, #5732:
URL: https://github.com/apache/maka/pull/5732

   ## Summary
   
   Fixes #5309
   
   Agents can discover `WriteStdin`'s terminal handoff action in a supported interactive Desktop session, reveal the original terminal, and wait for explicit user completion. A masked input card reuses `ChatComposer` and `TextInput`; Submit sends one private line, while **Let the agent continue** separately returns control to the same live PTY. The existing Runtime resource and Interaction lifecycle own the flow, with no SSH-specific prompt detection, replacement shell, or credential store.
   
   Admission fences queued agent writes before human input. Private controls are nonjournalled, sequenced and bound to the original resource and live controller; uncertain delivery is never replayed. Cancel, exit, reload and disconnect retain explicit lifecycle outcomes. Resume preserves command permissions and does not claim successful authentication.
   
   **Output remains private after Resume**, including delayed credential echoes. The user explicitly selects and shares a non-sensitive observation before the model can read it. Private display also fences Desktop computer-use capture. This first slice supports Unix PTYs; Windows and headless sessions do not advertise it. The protocol compatibility epoch advances to 190. [Design and recording boundaries](https://github.com/testikun/maka/blob/fa83431be3e413bdf482b16a8d3e43e0da9b1c68/docs/terminal-handoff.md).
   
   ## Verification
   
   - Real Electron + Runtime Host + OpenSSH journey against an actual compatible endpoint using **gpt-5.6-terra**: wrong-password rejection and retry, second challenge, refresh clearing an unsubmitted draft, explicit Resume, and model continuation in the same SSH shell. An unexported shell marker and `/tmp` working directory survived; the model subsequently read the user-reviewed observation.
   - Both no-echo input and intentional immediate/delayed echoes exercised. Eight provider requests, 18 live workspace files and 68 closed-profile files were scanned with **zero synthetic-secret leaks**; ordinary events and process/renderer logs were checked too. Reproducible opt-in harness: [instructions](https://github.com/testikun/maka/blob/fa83431be3e413bdf482b16a8d3e43e0da9b1c68/scripts/terminal-handoff/README.md).
   - Relevant Runtime/Host/core/UI suites: **227 passed, 4 platform skips**. Desktop/CLI suites: **176 passed**. Session event regressions: **37 passed**.
   - Full workspace build, typecheck, lint and format checks passed; Desktop/UI Knip, ASF headers, E2E budget and renderer architecture checks passed, including `--base upstream/main --strict-base`.
   - Ablation: removing output isolation exposed a sentinel in a public projection; removing the input-epoch fence allowed a queued agent write. Both regression tests failed as expected, so both protections remain. Removed a redundant display helper and normal-terminal polling.
   - Real acceptance ran on macOS. Linux, Windows, remote Runtime Host transport and packaged installers were not exercised by the real-model journey.
   
   Same-size screenshots; the normal view is a separate user terminal baseline, and waiting/resumed show the same SSH resource. No submitted credentials are captured.
   
   | Normal terminal | Waiting for user input | After explicit Resume |
   | --- | --- | --- |
   | ![Normal terminal](https://raw.githubusercontent.com/testikun/maka/codex/issue-5309-terminal-handoff/docs/images/pr/terminal-handoff/01-normal.png) | ![Waiting for user input](https://raw.githubusercontent.com/testikun/maka/codex/issue-5309-terminal-handoff/docs/images/pr/terminal-handoff/02-waiting.png) | ![After explicit Resume](https://raw.githubusercontent.com/testikun/maka/codex/issue-5309-terminal-handoff/docs/images/pr/terminal-handoff/03-resumed.png) |
   
   ## AI use
   
   - [ ] No generative tool made a substantive contribution
   - [x] Generative tooling made a substantive contribution
   
   Tool(s) and scope: Codex implemented and tested the change, wrote the documentation, and prepared this PR. The real-provider acceptance journey used gpt-5.6-terra. The commit includes `Generated-by: Codex`.
   
   ## Checklist
   
   - [x] Tests cover the change and fail without it
   - [x] Lint, format, typecheck and the affected suites pass locally
   
   Does this PR entail a change in behavior?
   
   - [x] Yes — described under Summary above
   - [ ] No
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4120412771


##########
packages/runtime/src/shell-run-manager.ts:
##########
@@ -633,6 +637,98 @@ export class ShellRunProcessManager
     };
   }
 
+  async preparePtyHandoff(sessionId: string, ref: string, signal: AbortSignal): Promise<void> {
+    const live = this.requirePrivatePtyTarget(sessionId, ref);
+    assertShellRunCaller(live.record, 'model');
+    if (!live.driver.supportsInputFence)
+      throw new Error('Private terminal input is unavailable on this platform');
+    if (live.privateTerminal?.inputOpen) throw new Error('Terminal handoff is already active');
+    if (!live.privateTerminal) {
+      const stack = await loadPtyStack();
+      if (live.driverExit || live.termination)
+        throw new Error('Original terminal is no longer running');
+      const size = live.collector.currentSize();
+      const collector = new PtyScreenCollector({
+        stack,
+        ...size,
+        onProtocolReply: (data) => {
+          // Ignore replay while constructing the private parser. Subsequent
+          // device/status replies stay within the PTY, never in model output.
+          if (!live.privateTerminal || live.driverExit || live.termination || live.integrityFailure)
+            return;
+          live.driver.write(data);
+        },
+        onDirty: () => {},
+        onFailure: () =>
+          this.handleIntegrityFailure(live, new Error('Private terminal display failed')),
+      });
+      collector.accept(live.rawBuffer);
+      live.privateTerminal = { collector, inputOpen: true };

Review Comment:
   [P2] Do not enable protocol replies until the historical buffer has finished parsing. `collector.accept(live.rawBuffer)` only queues an asynchronous parse (`pty-screen-collector.ts:118-157`), but `live.privateTerminal` is assigned immediately afterward. When the replay contains an old DSR/cursor query, its delayed `onProtocolReply` sees a truthy `live.privateTerminal` and calls `live.driver.write(data)` into the *current* password/verification prompt. The new head leaves this ordering unchanged, so the prior real-PTY reproduction still applies. Fence replies for the replay generation or await a parse cut before enabling the reply path, and add a regression with an old query in `rawBuffer` plus a live private prompt.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "testikun (via GitHub)" <gi...@apache.org>.
testikun commented on PR #5732:
URL: https://github.com/apache/maka/pull/5732#issuecomment-5862159052

   Review follow-up after rebasing onto current main (head c7f54731a):
   
   - Fixed the Windows recovery source closure by including runtime-resource-coordinator.ts, and regenerated the Windows/Astryx/renderer inventories.
   - The Desktop private-surface fence now rolls back when ready admission throws or returns a non-human phase; a focused IPC regression test covers failure, closed, human, and release paths.
   - Replaced request-id linear scans and unbounded terminal retention with an O(1) request index plus a separately ordered terminal index capped at 128 entries. Release removes the tombstone from every index. Both inline threads are resolved.
   - Handoff-control failures now emit a bounded diagnostic before returning the stable protocol error.
   - I did not replace the native writeSync path: the pinned/patched node-pty 1.2.0-beta.15 sets O_NONBLOCK before exposing the PTY fd, and its own CustomWriteStream uses writeSync on that fd. The real PTY backpressure/protocol tests pass against that contract.
   - I retained the committed harness/screenshots as durable acceptance evidence for this privacy-sensitive flow.
   
   Validation: full build:test; 281 focused terminal/interaction/runtime tests; Windows source-closure and inventory checks; Astryx inventory; renderer architecture; protocol epoch 196 -> 197.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4119548761


##########
packages/runtime/src/shell-run-manager.ts:
##########
@@ -633,6 +637,129 @@ export class ShellRunProcessManager
     };
   }
 
+  async preparePtyHandoff(sessionId: string, ref: string, signal: AbortSignal): Promise<void> {
+    const live = this.requirePrivatePtyTarget(sessionId, ref);
+    assertShellRunCaller(live.record, 'model');
+    if (!live.driver.supportsInputFence)
+      throw new Error('Private terminal input is unavailable on this platform');
+    if (live.privateTerminal?.inputOpen) throw new Error('Terminal handoff is already active');
+    if (!live.privateTerminal) {
+      const stack = await loadPtyStack();
+      if (live.driverExit || live.termination)
+        throw new Error('Original terminal is no longer running');
+      const size = live.collector.currentSize();
+      const collector = new PtyScreenCollector({
+        stack,
+        ...size,
+        onProtocolReply: (data) => {
+          // Ignore replay while constructing the private parser. Subsequent
+          // device/status replies stay within the PTY, never in model output.
+          if (!live.privateTerminal || live.driverExit || live.termination || live.integrityFailure)

Review Comment:
   P2: `collector.accept(live.rawBuffer)` parses asynchronously, and `live.privateTerminal` is set on the next line. By the time the replayed output is parsed, this guard no longer applies, so old DSR or cursor queries in the replay get fresh replies written into the PTY, landing at the password prompt. Please wait for the replay to finish parsing before letting replies through.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "testikun (via GitHub)" <gi...@apache.org>.
testikun commented on PR #5732:
URL: https://github.com/apache/maka/pull/5732#issuecomment-5866786573

   @hqhq1025 @Astro-Han, I have refreshed the PR description and screenshots to show the current interaction, and replied directly to the four still-open inline threads.
   
   **This is a preliminary design/interaction draft.** My [input-card proposal in #5309](https://github.com/apache/maka/issues/5309#issuecomment-5712523401) has not yet received a reply in the issue. I do not want to treat implementation progress as agreement on that change to the user journey. Could you first assess whether the approach and the screenshots make sense? If so, I will continue developing the PR and resolving the remaining gaps before requesting merge.
   
   Current review status:
   
   | Finding | Current status |
   | --- | --- |
   | Raw fd / PTY-to-PTY private-input leak | Fixed by the owned node-pty writer and close fence; both later reviews independently confirmed it. The fingerprint is gone. |
   | Resume → hide/switch → return loses the private terminal | Fixed. Controller release retains the live handoff; real collapse/tab/reload recovery and two later turns passed. Manual sharing is now removed, and model result observation remains open. |
   | Stale Desktop capture fence after failed/closed ready | Fixed: failed admission and non-human/non-resumed results clear the fence. |
   | Unbounded closed-handoff retention / linear request lookup | Fixed with a request index and bounded closed-state retention; live resumed terminals are retained. |
   | Private-mode terminal protocol replies | New live queries receive replies, but replayed queries are still incorrectly eligible for replies. The latest P2 remains open. |
   | Terminal apply failure poisons unrelated interactions | Fixed: the failed terminal request is rejected locally; the focused regression passed again. |
   | EIO-to-exit first-write receipt / later error classification | Still open. Rejecting drains protects against secret leakage, but does not make the queued receipt/error semantics correct. |
   | Resume recheck fails after the decision was persisted | Still open. Queue revalidation fences stale/uncertain input, but the failure path can stop the terminal after a Resume decision is recorded. |
   | Resize after fd closure | Reported pre-existing behavior, not fixed here; tracked separately in the checklist. |
   | Control tied to a Desktop device | The existing owner/grant boundary is documented: another authorized client may claim after release; a live controller prevents another connection from claiming it. |
   | Harness portability / review artifacts | The real harness accepts `HANDOFF_BASE_URL` and `HANDOFF_MODEL` overrides (currently Responses-compatible providers). I retained selected redacted screenshots for this design review; they are evidence, not regression assertions. |
   
   The earlier Windows inventory/source-closure problems were fixed and confirmed in the later reviews; I am not extrapolating older green CI to the new screenshot commit. The latest owned-writer change also avoids the Driver's raw-fd assumption; the pinned Unix node-pty implementation sets O_NONBLOCK, and availability requires its owned writer. This does not replace the remaining platform acceptance.
   
   Latest real App run: 24 captured steps, 14 model requests, two subsequent turns in the same SSH shell without another password, and no generated credential found in the scanned model/event/log/file surfaces. This review pass also reran 49 focused Desktop/Host/driver tests plus the isolated apply-failure regression on macOS.
   
   **Automatic post-handoff result observation is still unresolved.** I removed the manual sharing flow to simplify the interaction, but kept private output isolated: the real delayed-echo experiment showed why opening output on Resume is unsafe. The PR remains Draft, with the replay, closed-input and Resume issues explicitly unchecked. Please assess the proposed direction rather than treating these screenshots as a request for merge approval.
   
   This update was prepared with Codex; the claims above distinguish implemented fixes, prior independent review, current local validation and outstanding work.
   


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4214224263


##########
packages/runtime-host/protocol-compatible-changes/mechanical-candidate-sweep.json:
##########
@@ -1,5 +1,5 @@
 {
-  "epoch": 200,
+  "epoch": 206,

Review Comment:
   [P3] This declaration, and `turn-snapshot-optional-fields.json:2`, was added by main at epoch 200 and has already landed. The directory README says landed declarations "are history, which is why the older files here still pin long-past epochs". `scripts/protocol-epoch-check.mjs` only reads declarations newly added against the base (`--diff-filter=A`), so this re-pin has no effect in CI. It just rewrites history in files this PR doesn't own, and you would have to re-pin again after moving the epoch. It was probably forced by the `--staged` hook during the merge commit. Please revert both files to 200.



##########
packages/runtime-host/src/protocol/index.ts:
##########
@@ -104,7 +104,8 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
 export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
 // Increment when the same protocol version no longer guarantees safe Client-Host
 // interoperability. Mismatches are rejected before domain commands are admitted.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 205 as const;
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 206 as const;

Review Comment:
   [P3, epoch coordination] Epoch 206 collides with other open PRs: #4138, #5902, #5961 and #5458 also claim it, and 207–210 are taken as well. This PR changes the wire protocol (`terminal-handoff.ts`, `operations.ts`, `runtime-resource.ts`), so it needs its own slot. Two branches that bump to the same number merge without a textual conflict (#3313). Please coordinate 211/212 (#5458 → 211, this PR → 212, or the next free slot at merge time) and update the line-108 comment to match.



##########
packages/runtime/src/shell-run-manager.ts:
##########
@@ -861,8 +971,13 @@ export class ShellRunProcessManager
         onProtocolReply: (data) => {
           if (!live || !driver)
             throw new Error('PTY protocol reply arrived before driver admission');
-          if (live.driverExit || live.termination || live.integrityFailure) return;
-          driver.write(data);
+          if (live.driverExit || live.termination || live.integrityFailure || live.privateTerminal)

Review Comment:
   [P3] Now that the replay at `:679` has replies disabled, this `|| live.privateTerminal` guard can leave a query with no reply.
   
   The sequence:
   1. A DA/DSR/CPR query arrives just before `preparePtyHandoff`.
   2. The public parser has queued it but not parsed it yet, because xterm schedules writes asynchronously.
   3. Handoff sets `privateTerminal`, so this guard drops the public reply.
   4. The private replay does not answer either.
   
   The program then waits for a reply that never comes. The window is narrow (a startup probe that coincides with the handoff).
   
   The public parser only ever receives pre-handoff bytes plus the RIS banner, because `onPtyData` at `:1147-1150` routes everything after handoff to the private collector. Dropping `|| live.privateTerminal` here would therefore answer each pre-handoff query exactly once without exposing private bytes. Alternatively, await a public `mutateAtCut` before installing the private parser.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "github-actions[bot] (via GitHub) via commits" <co...@maka.apache.org>.
github-actions[bot] commented on PR #5732:
URL: https://github.com/apache/maka/pull/5732#issuecomment-6843118884

   <!-- maka-lifecycle:stale-warning -->
   This pull request has had no new commits for 30 days and has been marked stale. It will be closed in 7 days unless a new commit is pushed.
   
   Comments do not reset this timer: only a new commit does. If the pull request is intentionally long-lived, a maintainer can apply the `pinned` label.


-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4109990982


##########
packages/runtime/src/__tests__/pty-process-driver.test.ts:
##########
@@ -81,3 +81,63 @@ function withTimeout<T>(promise: Promise<T>, message: string): Promise<T> {
     }),
   ]);
 }
+
+test('a real PTY input fence drains backpressure before the next owner writes', {
+  skip: process.platform === 'win32',

Review Comment:
   [P1] Record this new Windows skip in the generated inventory. The current-head CI `test` run 36211630629 fails in `npm run windows:inventory` with `Windows test skip inventory is stale`; this new `skip: process.platform === 'win32'` is detected by `collectWindowsTestSkips` as a new entry, but `docs/windows-test-inventory.md` is unchanged. On a clean runner, the check fails before the rest of the suite can run. Regenerate the inventory and rerun CI.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4118812389


##########
packages/runtime/src/pty-process-driver.ts:
##########
@@ -124,6 +231,35 @@ export class PtyProcessDriver {
   }
 }
 
+type UnixFdIdentity = Pick<Stats, 'dev' | 'ino' | 'mode' | 'rdev'>;
+
+function captureUnixFd(pty: IPty): { fd: number; identity: UnixFdIdentity } | undefined {
+  if (process.platform === 'win32') return undefined;
+  const fd = (pty as IPty & { fd?: number }).fd;
+  if (typeof fd !== 'number' || !Number.isInteger(fd)) return undefined;
+  try {
+    return { fd, identity: fstatSync(fd) };
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'EBADF') return undefined;
+    throw error;
+  }
+}
+
+function ownsUnixFd(target: { fd: number; identity: UnixFdIdentity }): boolean {

Review Comment:
   P1 (confirmed independently): all Linux `/dev/ptmx` masters share `dev/ino/mode/rdev`, so this fingerprint accepts a different PTY that reused the fd number. A proof of concept delivered the private input to the other shell. Before the fd closes, a closed flag has to be set synchronously.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4260780537


##########
packages/runtime-host/src/protocol/index.ts:
##########
@@ -106,7 +106,8 @@ export const RUNTIME_HOST_REGISTRATION_SCHEMA_VERSION = 1 as const;
 export const RUNTIME_HOST_PROTOCOL_VERSION = 0 as const;
 // Increment when the same protocol version no longer guarantees safe Client-Host
 // interoperability. Mismatches are rejected before domain commands are admitted.
-export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 220 as const;
+export const RUNTIME_HOST_COMPATIBILITY_EPOCH = 221 as const;

Review Comment:
   P3: epoch 221 is also claimed by open PRs #5969, #6088 and #6090. Please coordinate and re-pin to the next free slot right before merge (re-run `scripts/protocol-epoch-check.mjs`).



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4110287367


##########
packages/runtime-host/src/server/runtime-resource-coordinator.ts:
##########
@@ -257,14 +301,354 @@ export class HostRuntimeResourceCoordinator
     );
   }
 
+  isHandoffAvailable(sessionId: string): boolean {
+    return (
+      !this.#draining &&
+      process.platform !== 'win32' &&
+      Boolean(
+        this.#humanControl && this.#interactionAuthority && this.#humanSurfaces.has(sessionId),
+      )
+    );
+  }
+
+  async requestHandoff(ref: string, message: string, ctx: MakaToolContext): Promise<string> {
+    if (!this.isHandoffAvailable(ctx.sessionId) || !ctx.runId) {
+      throw new Error(
+        'Interactive terminal handoff is unavailable. Open this task in a connected Desktop window.',
+      );
+    }
+    const key = resourceKey(ctx.sessionId, ref);
+    const state: TerminalHandoffState = {
+      message,
+      command: '',
+      sessionId: ctx.sessionId,
+      ref,
+      requestId: randomUUID(),
+      phase: 'waiting',
+      nextSequence: 1,
+      lifetime: new AbortController(),
+    };
+    await this.#sessionAdmission.run(ctx.sessionId, async () => {
+      await this.#assertActiveSession(ctx.sessionId);
+      // Validate model visibility before installing a fence or any failure cleanup.
+      // Client inspection alone also accepts user-owned terminals.
+      await this.#manager.readRuntimeResource(ctx.sessionId, ref, ctx.abortSignal);
+      const previous = this.#handoffs.get(key);
+      if (previous && previous.phase !== 'resumed' && previous.phase !== 'closed')
+        throw new Error('Terminal handoff is already pending');
+      const resource = await this.#manager.inspectResource(ctx.sessionId, ref);
+      state.command = Array.from(resource.cmd).slice(0, 1_024).join('');
+      if (resource.mode !== 'pty' || !isActiveShellRunStatus(resource.status))
+        throw new Error('Handoff requires the original live PTY');
+      const controller = this.#controllers.get(key);
+      if (controller && controller.connectionId !== this.#humanSurfaces.get(ctx.sessionId))
+        throw new Error('Terminal is controlled by another client');
+      this.#inputEpochs.set(key, (this.#inputEpochs.get(key) ?? 0) + 1);
+      this.#releaseController(key);
+      this.#handoffs.set(key, state);
+    });
+    const authority = this.#interactionAuthority!();
+    const abort = () => {
+      state.lifetime.abort();
+      void authority
+        .closeTerminalHandoff(ctx.sessionId, state.requestId)
+        .catch(() => this.#requestDrain());
+    };
+    ctx.abortSignal.addEventListener('abort', abort, { once: true });
+    // Bound only readiness, never the time a person needs to authenticate.
+    const readyDeadline = setTimeout(() => {
+      if (state.phase === 'waiting') abort();
+    }, 30_000);
+    readyDeadline.unref();
+    try {
+      const signal = AbortSignal.any([
+        ctx.abortSignal,
+        state.lifetime.signal,
+        AbortSignal.timeout(5_000),
+      ]);
+      await this.#resourceQueue.run(key, () =>
+        this.#humanControl!.preparePtyHandoff(ctx.sessionId, ref, signal),
+      );
+      if (!this.isHandoffAvailable(ctx.sessionId) || ctx.abortSignal.aborted)
+        throw new Error('Interactive terminal surface disappeared before handoff');
+      const outcome = await authority.requestTerminalHandoff({
+        signal: state.lifetime.signal,
+        sessionId: ctx.sessionId,
+        runId: ctx.runId,
+        turnId: ctx.turnId,
+        requestId: state.requestId,
+        request: { kind: 'terminal_handoff', toolUseId: ctx.toolCallId, ref, message },
+        canAnswer: (action, connectionId, controllerId) =>
+          action === 'cancel' ||
+          (state.phase === 'human' &&
+            state.connectionId === connectionId &&
+            state.controllerId === controllerId &&
+            state.lastReceipt?.status !== 'outcome_unknown'),
+        apply: async (action) => {
+          await this.#resourceQueue.run(key, async () => {
+            if (this.#handoffs.get(key) !== state || state.phase === 'closed') return;
+            if (action === 'resume') {
+              // A child can exit while its final input fence is draining. That
+              // closes this handoff; it is not an Interaction-store failure.
+              const live = await this.#humanControl!.resumePtyHandoff(ctx.sessionId, ref).catch(
+                () => false,
+              );
+              state.phase = live ? 'resumed' : 'closed';
+              if (!live) state.closure = 'unavailable';
+              this.#inputEpochs.set(key, (this.#inputEpochs.get(key) ?? 0) + 1);
+              if (!live) {
+                state.lifetime.abort();
+                await this.#manager.stopBackgroundTask(
+                  ctx.sessionId,
+                  ref,
+                  new AbortController().signal,
+                  'model',
+                );
+              }
+            } else {
+              state.phase = 'closed';
+              state.closure = 'cancelled';
+              state.lifetime.abort();
+              await this.#manager.stopBackgroundTask(
+                ctx.sessionId,
+                ref,
+                new AbortController().signal,
+                'client',
+              );
+            }
+          });
+        },
+      });
+      return JSON.stringify({
+        ref,
+        outcome:
+          outcome.kind === 'terminal_handoff_answer' &&
+          outcome.action === 'resume' &&
+          state.phase === 'resumed'
+            ? 'resumed'
+            : 'closed',
+        outputVisibility: 'private',
+        instruction:
+          state.phase === 'resumed'
+            ? 'The user checked that this terminal is ready and explicitly pressed Resume. Continue the original task now: send the next requested command to this same ref under existing permissions. Do not ask for another confirmation, a post-login prompt, or shared output before sending that command. The user confirmation is not machine-verified authentication success: do not claim success or describe unseen output. After executing the command, ask the user to review and share its non-sensitive result, then use Read on this ref to retrieve the published observation.'
+            : 'The handoff closed without returning control. Do not retry credentials or recreate the original terminal.',
+      });
+    } catch (error) {
+      state.phase = 'closed';
+      state.closure = 'unavailable';
+      state.lifetime.abort();
+      // Failure after admission must not leave a secretly writable half-handoff.
+      await this.#manager
+        .stopBackgroundTask(ctx.sessionId, ref, new AbortController().signal, 'model')
+        .catch(() => {});
+      throw error;
+    } finally {
+      clearTimeout(readyDeadline);
+      ctx.abortSignal.removeEventListener('abort', abort);
+    }
+  }
+
+  async #handoffControl(
+    input: RuntimeResourceHandoffInput,
+    context: ConnectionContext,
+  ): Promise<OperationOutcome<'runtime.resource.handoff'>> {
+    try {
+      const failure = await this.#mutableSessionFailure(input.sessionId);
+      if (failure) return mutationFailure('runtime.resource.handoff', failure);
+      if (input.action === 'lookup') {
+        const handoff = this.#handoffs.get(resourceKey(input.sessionId, input.ref));
+        return {
+          ok: true,
+          result: {
+            status: handoff?.phase === 'closed' ? 'closed' : handoff ? 'available' : 'unavailable',
+            ...(handoff?.phase === 'closed' ? { closure: handoff.closure ?? 'exited' } : {}),
+            phase: handoff?.phase ?? 'closed',
+            nextSequence: handoff?.nextSequence ?? 1,
+            ...(handoff
+              ? {
+                  request: {
+                    requestId: handoff.requestId,
+                    ref: handoff.ref,
+                    message: handoff.message,
+                    command: handoff.command,
+                  },
+                }
+              : {}),
+          },
+        };
+      }
+      if (input.action === 'surface') {
+        if (input.available) this.#humanSurfaces.set(input.sessionId, context.connectionId);
+        else if (this.#humanSurfaces.get(input.sessionId) === context.connectionId)
+          this.#humanSurfaces.delete(input.sessionId);
+        return {
+          ok: true,
+          result: {
+            status: this.isHandoffAvailable(input.sessionId) ? 'available' : 'unavailable',
+            phase: 'waiting',
+            nextSequence: 1,
+          },
+        };
+      }
+      const state = [...this.#handoffs.values()].find(
+        (entry) => entry.sessionId === input.sessionId && entry.requestId === input.requestId,
+      );
+      if (!state || !this.#humanControl)
+        throw new Error('Original terminal handoff is no longer live');
+      return await this.#resourceQueue.run(resourceKey(state.sessionId, state.ref), async () => {
+        if (state.phase === 'closed')
+          return {
+            ok: true as const,
+            result: {
+              status: 'closed' as const,
+              phase: 'closed' as const,
+              nextSequence: state.nextSequence,
+              closure: state.closure ?? 'exited',
+            },
+          };
+        const result = (
+          status: RuntimeResourceHandoffResult['status'],
+        ): RuntimeResourceHandoffResult => ({
+          status: state.lastReceipt?.status === 'outcome_unknown' ? 'outcome_unknown' : status,
+          phase: state.phase,
+          nextSequence: state.nextSequence,
+        });
+        if (input.action === 'ready') {
+          if (this.#humanSurfaces.get(input.sessionId) !== context.connectionId)
+            throw new Error('No interactive terminal surface on this connection');
+          // A renderer reload keeps the Desktop's authenticated Host connection.
+          // Reclaiming from that connection fences the old card identity.
+          if (state.connectionId && state.connectionId !== context.connectionId)
+            throw new Error('Terminal handoff belongs to another controller');
+          state.connectionId = context.connectionId;
+          state.controllerId = input.controllerId;
+          if (state.phase === 'waiting') state.phase = 'human';
+          return { ok: true as const, result: result('ready') };
+        }
+        if (
+          state.connectionId !== context.connectionId ||
+          state.controllerId !== input.controllerId
+        )
+          return {
+            ok: true as const,
+            result: {
+              ...result('rejected'),
+              status: 'rejected' as const,
+              rejection: 'controller_expired' as const,
+            },
+          };
+        if (input.action === 'release') {
+          delete state.connectionId;
+          delete state.controllerId;
+          return { ok: true as const, result: result('observed') };
+        }
+        if (input.action === 'observe') {
+          const display = await this.#humanControl!.readPrivatePtySnapshot(
+            state.sessionId,
+            state.ref,
+          );
+          return {
+            ok: true as const,
+            result: {
+              ...result('observed'),
+              display: { ...display, text: Array.from(display.text).slice(-12_000).join('') },
+            },
+          };
+        }
+        if (input.action === 'share') {
+          if (state.phase !== 'resumed') throw new Error('Resume before sharing a new observation');
+          const snapshot = await this.#humanControl!.readPrivatePtySnapshot(
+            state.sessionId,
+            state.ref,
+          );
+          if (
+            snapshot.sequence !== input.sequence ||
+            !input.text ||
+            !snapshot.text.includes(input.text)
+          )
+            return {
+              ok: true as const,
+              result: { ...result('rejected'), rejection: 'observation_expired' as const },
+            };
+          await this.#humanControl!.sharePrivatePtyObservation(
+            state.sessionId,
+            state.ref,
+            input.sequence,
+            input.text,
+          );
+          return { ok: true as const, result: result('shared') };
+        }
+        if (input.action !== 'input' || state.phase !== 'human')
+          throw new Error('Terminal is not accepting private input');
+        if (state.lastReceipt?.sequence === input.sequence)
+          return { ok: true as const, result: result(state.lastReceipt.status) };
+        if (state.lastReceipt?.status === 'outcome_unknown')
+          throw new Error('Resolve unknown input delivery by stopping this terminal');
+        if (input.sequence !== state.nextSequence)
+          throw new Error('Private input sequence expired');
+        if (
+          !input.input ||
+          !isWellFormedTerminalInput(input.input) ||
+          /[\x00-\x1f\x7f]/.test(input.input)
+        )
+          return {
+            ok: true as const,
+            result: { ...result('rejected'), rejection: 'invalid_input' as const },
+          };
+        state.nextSequence++;
+        state.lastReceipt = { sequence: input.sequence, status: 'outcome_unknown' };
+        try {
+          await this.#humanControl!.writePrivatePtyInput(
+            state.sessionId,
+            state.ref,
+            `${input.input}\r`,
+            AbortSignal.any([state.lifetime.signal, AbortSignal.timeout(5_000)]),
+          );
+          state.lastReceipt.status = 'written';
+        } catch {
+          // Never echo input, retry it, or call a partial delivery "not sent".
+        }
+        return { ok: true as const, result: result(state.lastReceipt.status) };
+      });
+    } catch {
+      return mutationFailure('runtime.resource.handoff', {
+        code: 'operation_conflict',
+        message:
+          'Terminal handoff is unavailable, stale, or no longer accepts this operation. Reconnect to the original task and inspect its live terminal.',
+      });
+    }
+  }
+
   observeShellRunUpdate(update: ShellRunUpdate): void {
     if (!isActiveShellRunStatus(update.result.status)) {
+      const key = resourceKey(update.sessionId, update.result.ref);
+      this.#inputEpochs.delete(key);
+      const handoff = this.#handoffs.get(key);
+      if (handoff) {
+        handoff.phase = 'closed';
+        handoff.closure ??= 'exited';
+        handoff.lifetime.abort();
+        // Retain identity/status only so an open or reconnected card can explain

Review Comment:
   [P2] This keeps every finished handoff in the Host-global `#handoffs` map. No later path removes closed entries, while `#handoffControl` scans all entries for each request (including repeated observation polls). A long-running Host therefore accumulates one state per completed terminal and progressively slows control operations. Please retain the closure outcome only for a bounded period or until the card/session releases it, then evict the tombstone; the previous path deleted it on exit.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "testikun (via GitHub)" <gi...@apache.org>.
testikun commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4120312090


##########
packages/runtime/src/pty-process-driver.ts:
##########
@@ -124,6 +231,35 @@ export class PtyProcessDriver {
   }
 }
 
+type UnixFdIdentity = Pick<Stats, 'dev' | 'ino' | 'mode' | 'rdev'>;
+
+function captureUnixFd(pty: IPty): { fd: number; identity: UnixFdIdentity } | undefined {
+  if (process.platform === 'win32') return undefined;
+  const fd = (pty as IPty & { fd?: number }).fd;
+  if (typeof fd !== 'number' || !Number.isInteger(fd)) return undefined;
+  try {
+    return { fd, identity: fstatSync(fd) };
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'EBADF') return undefined;
+    throw error;
+  }
+}
+
+function ownsUnixFd(target: { fd: number; identity: UnixFdIdentity }): boolean {
+  try {
+    const current = fstatSync(target.fd);
+    return (

Review Comment:
   Addressed in 83e697267: the fd fingerprint was removed. The Driver now calls the owning node-pty instance's patched `makaWriteSync`, which refuses writes once its socket is destroyed or its write stream is disposed. It no longer writes a captured raw fd based on matching fstat fields.
   
   `pty-process-driver-write-lifecycle.test.ts` now queues synthetic private input under backpressure, closes the original PTY before child exit, and uses a second real PTY (requiring the same fd on Linux) to verify that no queued secret arrives. Your later [review](https://github.com/apache/maka/pull/5732#pullrequestreview-5335117041) independently confirmed this fix. I reran the macOS lifecycle/driver tests in this follow-up; I am not claiming a new Linux run.
   
   This addresses the ownership/leak finding, not the separate first-write/closed-input reporting issue raised in the latest review, which remains open in the PR checklist. Leaving the thread for your verification.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "testikun (via GitHub)" <gi...@apache.org>.
testikun commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4120314216


##########
apps/desktop/src/renderer/features/workbar/tools/terminal/terminal-handoff-panel.tsx:
##########
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { Button, useUiLocale } from '@maka/ui';
+import type { UiCatalog } from '@maka/core/ui-locale';
+import { Banner, ChatComposer, CheckboxInput, TextInput, isImeKeyEvent } from '@astryxdesign/core';
+import type { RuntimeResourceHandoffResult } from '@maka/runtime-host/protocol';
+import { useWorkbarServices } from '../../services-context.js';
+import { parseDesktopSessionKey } from '../../../../../shared/runtime-host-identity.js';
+import { isValidPrivateTerminalInput, terminalFeedback } from './terminal-handoff-feedback.js';
+
+const COPY = {
+  en: {
+    waiting: 'Your input is private. The agent is waiting.', resumed: 'Control returned to the agent. Output stays private.',
+    input: 'Private terminal input', submit: 'Submit', resume: 'Let the agent continue', cancel: 'Cancel and stop',
+    shared: 'Selected observation shared with the agent.', share: 'Share selected text with the agent',
+    review: 'Review new output and select only non-sensitive text to share. Sharing records that text in the task.',
+    sent: 'Submitted. Check the terminal response; if it asks you to retry, enter another response. Submission does not confirm authentication.',
+    unknown: 'Delivery could not be confirmed. Input was not retried. Stop this terminal to avoid duplicate input.',
+    disconnected: 'Connection to this terminal was lost. Input and Resume are paused. Reconnect to check the original process; nothing will be resent.',
+    reconnect: 'Reconnect to original terminal', invalid: 'Not sent. Enter one line without control characters, up to 32 KB.',
+    select: 'Select current non-sensitive text to share. The output may have changed; select it again.',
+    target: 'Execution host', confirm: 'I checked the terminal and it is ready for the agent to continue',
+    confirmHelp: 'Finish authentication and check the terminal response before returning control. Clear or submit any draft first.',
+    password: 'SSH is requesting a password. Enter it below.', authentication_retry: 'SSH rejected authentication and is asking for the password again. Check the account and retry.',
+    exited: 'The original terminal process exited. This handoff has ended; no replacement was started.',
+    cancelled: 'Terminal stopped. This handoff was cancelled.', unavailable: 'The original terminal is no longer available. Control was not returned to the agent.',
+  },
+  'zh-CN': {
+    waiting: '输入仅发送给此终端,Agent 正在等待。', resumed: '已交还 Agent,输出仍保持私密。',
+    input: '私密终端输入', submit: '提交', resume: '让 Agent 继续', cancel: '取消并停止',
+    shared: '已将所选观察分享给 Agent。', share: '将所选文字分享给 Agent', review: '请审阅新输出,只选择非敏感文字分享。分享的文字将记入任务。',
+    sent: '已提交,请查看终端回应;如要求重试,请重新输入。提交不代表验证通过。',
+    unknown: '无法确认投递结果,未自动重试。请停止此终端,避免重复输入。',
+    disconnected: '与终端的连接已中断,已暂停输入和交还。请重新连接以检查原进程,不会重发输入。',
+    reconnect: '重新连接原终端', invalid: '尚未发送。请输入不含控制字符的单行内容,最多 32 KB。',
+    select: '请选择当前的非敏感文字。输出可能已变化,请重新选择。', target: '执行主机',
+    confirm: '我已检查终端,确认可以让 Agent 继续操作', confirmHelp: '请完成验证并检查终端回应后再交还;先提交或清空尚未发送的内容。',
+    password: 'SSH 正在请求密码,请在下方输入。', authentication_retry: 'SSH 拒绝了本次验证,正在重新请求密码。请核对账户后重试。',
+    exited: '原终端进程已退出,本次接管已结束,未启动替代进程。', cancelled: '已停止终端并取消本次接管。', unavailable: '原终端已不可用,未将控制权交还 Agent。',
+  },
+  'zh-TW': {
+    waiting: '輸入僅傳送給此終端,Agent 正在等待。', resumed: '已交還 Agent,輸出仍保持私密。',
+    input: '私密終端輸入', submit: '提交', resume: '讓 Agent 繼續', cancel: '取消並停止',
+    shared: '已將所選觀察分享給 Agent。', share: '將所選文字分享給 Agent', review: '請審閱新輸出,只選擇非敏感文字分享。分享的文字將記入任務。',
+    sent: '已提交,請查看終端回應;如要求重試,請重新輸入。提交不代表驗證通過。',
+    unknown: '無法確認投遞結果,未自動重試。請停止此終端,避免重複輸入。',
+    disconnected: '與終端的連線已中斷,已暫停輸入及交還。請重新連線以檢查原行程,不會重送輸入。',
+    reconnect: '重新連線原終端', invalid: '尚未傳送。請輸入不含控制字元的單行內容,最多 32 KB。',
+    select: '請選擇目前的非敏感文字。輸出可能已變更,請重新選擇。', target: '執行主機',
+    confirm: '我已檢查終端,確認可以讓 Agent 繼續操作', confirmHelp: '請完成驗證並檢查終端回應後再交還;先提交或清空尚未傳送的內容。',
+    password: 'SSH 正在要求密碼,請在下方輸入。', authentication_retry: 'SSH 拒絕了本次驗證,正在重新要求密碼。請核對帳戶後重試。',
+    exited: '原終端行程已結束,本次接管已結束,未啟動替代行程。', cancelled: '已停止終端並取消本次接管。', unavailable: '原終端已無法使用,未將控制權交還 Agent。',
+  },
+} satisfies UiCatalog<Record<string, string>>;
+type Notice = '' | 'sent' | 'unknown' | 'invalid' | 'shared' | 'select';
+
+export function TerminalHandoffPanel(props: {
+  sessionId: string;
+  request: NonNullable<RuntimeResourceHandoffResult['request']>;
+  active: boolean;
+}) {
+  const { terminal } = useWorkbarServices();
+  const locale = useUiLocale();
+  const copy = COPY[locale];
+  const [controllerId] = useState(() => crypto.randomUUID());
+  const [state, setState] = useState<RuntimeResourceHandoffResult>();
+  const [notice, setNotice] = useState<Notice>('');
+  const [busy, setBusy] = useState(false);
+  const [uncertain, setUncertain] = useState(false);
+  const [connected, setConnected] = useState(false);
+  const [disconnected, setDisconnected] = useState(false);
+  const [confirmed, setConfirmed] = useState(false);
+  const [revision, setRevision] = useState(0);
+  // Component-local only: never reuse chat drafts or generic form responses.
+  const [privateInput, setPrivateInput] = useState('');
+  const input = useRef<HTMLInputElement>(null);
+  const screen = useRef<HTMLPreElement>(null);
+  const sending = useRef(false);
+  const displayEpoch = useRef(0);
+  const identity = { sessionId: props.sessionId, requestId: props.request.requestId, controllerId };
+
+  function accept(result: RuntimeResourceHandoffResult) {
+    setState(result);
+    if (result.status === 'outcome_unknown') { setUncertain(true); setNotice('unknown'); }
+    if (result.status === 'closed') { setNotice(''); setConfirmed(false); }
+    if (result.rejection === 'controller_expired') { setConnected(false); setDisconnected(true); setConfirmed(false); }
+    if (result.rejection === 'invalid_input') setNotice('invalid');
+    if (result.rejection === 'observation_expired') setNotice('select');
+  }
+
+  useEffect(() => {
+    if (!terminal.handoff || !props.active) return;
+    let disposed = false;
+    let timer: ReturnType<typeof setTimeout>;
+    const failed = () => {
+      if (disposed) return;
+      setConnected(false); setDisconnected(true); setConfirmed(false);
+      if (input.current) input.current.value = '';
+      setPrivateInput(''); setState((previous) => previous ? { ...previous, display: undefined } : previous);
+    };
+    const poll = async () => {
+      const epoch = displayEpoch.current;
+      try {
+        const result = await terminal.handoff!({ ...identity, action: 'observe' });
+        if (!disposed && epoch === displayEpoch.current) accept(result);
+        if (!disposed && result.phase !== 'closed' && result.rejection !== 'controller_expired') timer = setTimeout(poll, 300);
+      } catch { failed(); }
+    };
+    // Reclaim only the original resource. Input is never replayed on recovery.
+    void terminal.handoff({ action: 'surface', sessionId: props.sessionId, available: true })
+      .then(() => terminal.handoff!({ ...identity, action: 'ready' }))
+      .then((result) => {
+        if (disposed) { void terminal.handoff!({ ...identity, action: 'release' }).catch(() => {}); return; }
+        setConnected(true); setDisconnected(false); accept(result);
+        if (result.phase !== 'closed') void poll();
+      }).catch(failed);
+    return () => {
+      disposed = true; displayEpoch.current++; clearTimeout(timer);
+      if (input.current) input.current.value = '';
+      setPrivateInput(''); setState(undefined); setConnected(false); setConfirmed(false);
+      void terminal.handoff!({ ...identity, action: 'release' }).catch(() => {});

Review Comment:
   The loss of the live private display is fixed. `release` now removes only the controller identity; the Host retains a live resumed handoff until the original process exits. Returning can reclaim and observe that same terminal. The Host regression also checks that the retention cap does not evict live resumed terminals.
   
   The latest real Desktop/SSH/model run passed Resume → collapse/expand → switch tabs/return → reload, followed by two more turns in the original shell with its marker and working directory preserved. The input card stays gone after completion.
   
   The interaction has also changed: manual sharing was removed, so there is no longer a Share action to validate. That is not a solution to model result observation: the agent still cannot read private output, and this remains an explicit merge-blocking acceptance gap. The refreshed PR screenshots show the current behavior. Could you recheck the retention fix and whether this simpler interaction is the right direction?



##########
packages/runtime/src/pty-process-driver.ts:
##########
@@ -124,6 +231,35 @@ export class PtyProcessDriver {
   }
 }
 
+type UnixFdIdentity = Pick<Stats, 'dev' | 'ino' | 'mode' | 'rdev'>;
+
+function captureUnixFd(pty: IPty): { fd: number; identity: UnixFdIdentity } | undefined {
+  if (process.platform === 'win32') return undefined;
+  const fd = (pty as IPty & { fd?: number }).fd;
+  if (typeof fd !== 'number' || !Number.isInteger(fd)) return undefined;
+  try {
+    return { fd, identity: fstatSync(fd) };
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'EBADF') return undefined;
+    throw error;
+  }
+}
+
+function ownsUnixFd(target: { fd: number; identity: UnixFdIdentity }): boolean {

Review Comment:
   Addressed by removing the fingerprint and using the owning node-pty instance's synchronous writer/close fence in 83e697267. The guard checks `_socket.destroyed` and the write stream's disposed state before writing, so matching /dev/ptmx metadata no longer authorizes a write.
   
   The regression now uses two real PTYs, including same-fd reuse on Linux, and checks that queued private input never reaches the replacement. Your [later review](https://github.com/apache/maka/pull/5732#pullrequestreview-5335187114) independently confirmed both the close ordering and that your original PoC no longer leaks. The macOS lifecycle test passed again in this follow-up. The separate closed-input reporting and resize concerns remain tracked as open; this reply only addresses the private-input ownership leak.



##########
packages/runtime/src/shell-run-manager.ts:
##########
@@ -633,6 +637,129 @@ export class ShellRunProcessManager
     };
   }
 
+  async preparePtyHandoff(sessionId: string, ref: string, signal: AbortSignal): Promise<void> {
+    const live = this.requirePrivatePtyTarget(sessionId, ref);
+    assertShellRunCaller(live.record, 'model');
+    if (!live.driver.supportsInputFence)
+      throw new Error('Private terminal input is unavailable on this platform');
+    if (live.privateTerminal?.inputOpen) throw new Error('Terminal handoff is already active');
+    if (!live.privateTerminal) {
+      const stack = await loadPtyStack();
+      if (live.driverExit || live.termination)
+        throw new Error('Original terminal is no longer running');
+      const size = live.collector.currentSize();
+      const collector = new PtyScreenCollector({
+        stack,
+        ...size,
+        onProtocolReply: (data) => {
+          // Ignore replay while constructing the private parser. Subsequent
+          // device/status replies stay within the PTY, never in model output.
+          if (!live.privateTerminal || live.driverExit || live.termination || live.integrityFailure)

Review Comment:
   Confirmed by checking the current code: this remains open. `collector.accept(live.rawBuffer)` is still followed immediately by assigning `live.privateTerminal`, so the callback guard does not cover asynchronous parsing of the replay. The existing live private-mode DSR test only verifies responses to new queries after Resume; it does not establish that replayed queries are suppressed.
   
   I have added this explicitly to the PR's remaining-work checklist and am not marking it fixed. The correction needs a replay-completion barrier while preserving the routing/recording boundary for newly arriving private bytes, plus a regression proving that an old DSR query does not inject a second response into the password prompt. The refreshed screenshots and successful normal SSH journey do not cover this edge case.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "hqhq1025 (via GitHub)" <gi...@apache.org>.
hqhq1025 commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4118796767


##########
packages/runtime/src/pty-process-driver.ts:
##########
@@ -124,6 +231,35 @@ export class PtyProcessDriver {
   }
 }
 
+type UnixFdIdentity = Pick<Stats, 'dev' | 'ino' | 'mode' | 'rdev'>;
+
+function captureUnixFd(pty: IPty): { fd: number; identity: UnixFdIdentity } | undefined {
+  if (process.platform === 'win32') return undefined;
+  const fd = (pty as IPty & { fd?: number }).fd;
+  if (typeof fd !== 'number' || !Number.isInteger(fd)) return undefined;
+  try {
+    return { fd, identity: fstatSync(fd) };
+  } catch (error) {
+    if ((error as NodeJS.ErrnoException).code === 'EBADF') return undefined;
+    throw error;
+  }
+}
+
+function ownsUnixFd(target: { fd: number; identity: UnixFdIdentity }): boolean {
+  try {
+    const current = fstatSync(target.fd);
+    return (

Review Comment:
   P1: Comparing dev/ino/mode/rdev does not prove that this is the original PTY. On Linux, I opened a PTY master, closed it, and opened a different PTY; the new master reused fd 3 and had the *same* four fstat fields, while bytes written to it arrived at the other slave. Thus the queued private input can still be sent to a different live terminal after node-pty closes the original fd. The new regression only reuses the fd as a regular file, so it misses this case. Please cover PTY-to-PTY reuse and bind writes to the actual owned handle/lifecycle rather than this metadata tuple.



##########
apps/desktop/src/renderer/features/workbar/tools/terminal/terminal-handoff-panel.tsx:
##########
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+import { useEffect, useRef, useState } from 'react';
+import { Button, useUiLocale } from '@maka/ui';
+import type { UiCatalog } from '@maka/core/ui-locale';
+import { Banner, ChatComposer, CheckboxInput, TextInput, isImeKeyEvent } from '@astryxdesign/core';
+import type { RuntimeResourceHandoffResult } from '@maka/runtime-host/protocol';
+import { useWorkbarServices } from '../../services-context.js';
+import { parseDesktopSessionKey } from '../../../../../shared/runtime-host-identity.js';
+import { isValidPrivateTerminalInput, terminalFeedback } from './terminal-handoff-feedback.js';
+
+const COPY = {
+  en: {
+    waiting: 'Your input is private. The agent is waiting.', resumed: 'Control returned to the agent. Output stays private.',
+    input: 'Private terminal input', submit: 'Submit', resume: 'Let the agent continue', cancel: 'Cancel and stop',
+    shared: 'Selected observation shared with the agent.', share: 'Share selected text with the agent',
+    review: 'Review new output and select only non-sensitive text to share. Sharing records that text in the task.',
+    sent: 'Submitted. Check the terminal response; if it asks you to retry, enter another response. Submission does not confirm authentication.',
+    unknown: 'Delivery could not be confirmed. Input was not retried. Stop this terminal to avoid duplicate input.',
+    disconnected: 'Connection to this terminal was lost. Input and Resume are paused. Reconnect to check the original process; nothing will be resent.',
+    reconnect: 'Reconnect to original terminal', invalid: 'Not sent. Enter one line without control characters, up to 32 KB.',
+    select: 'Select current non-sensitive text to share. The output may have changed; select it again.',
+    target: 'Execution host', confirm: 'I checked the terminal and it is ready for the agent to continue',
+    confirmHelp: 'Finish authentication and check the terminal response before returning control. Clear or submit any draft first.',
+    password: 'SSH is requesting a password. Enter it below.', authentication_retry: 'SSH rejected authentication and is asking for the password again. Check the account and retry.',
+    exited: 'The original terminal process exited. This handoff has ended; no replacement was started.',
+    cancelled: 'Terminal stopped. This handoff was cancelled.', unavailable: 'The original terminal is no longer available. Control was not returned to the agent.',
+  },
+  'zh-CN': {
+    waiting: '输入仅发送给此终端,Agent 正在等待。', resumed: '已交还 Agent,输出仍保持私密。',
+    input: '私密终端输入', submit: '提交', resume: '让 Agent 继续', cancel: '取消并停止',
+    shared: '已将所选观察分享给 Agent。', share: '将所选文字分享给 Agent', review: '请审阅新输出,只选择非敏感文字分享。分享的文字将记入任务。',
+    sent: '已提交,请查看终端回应;如要求重试,请重新输入。提交不代表验证通过。',
+    unknown: '无法确认投递结果,未自动重试。请停止此终端,避免重复输入。',
+    disconnected: '与终端的连接已中断,已暂停输入和交还。请重新连接以检查原进程,不会重发输入。',
+    reconnect: '重新连接原终端', invalid: '尚未发送。请输入不含控制字符的单行内容,最多 32 KB。',
+    select: '请选择当前的非敏感文字。输出可能已变化,请重新选择。', target: '执行主机',
+    confirm: '我已检查终端,确认可以让 Agent 继续操作', confirmHelp: '请完成验证并检查终端回应后再交还;先提交或清空尚未发送的内容。',
+    password: 'SSH 正在请求密码,请在下方输入。', authentication_retry: 'SSH 拒绝了本次验证,正在重新请求密码。请核对账户后重试。',
+    exited: '原终端进程已退出,本次接管已结束,未启动替代进程。', cancelled: '已停止终端并取消本次接管。', unavailable: '原终端已不可用,未将控制权交还 Agent。',
+  },
+  'zh-TW': {
+    waiting: '輸入僅傳送給此終端,Agent 正在等待。', resumed: '已交還 Agent,輸出仍保持私密。',
+    input: '私密終端輸入', submit: '提交', resume: '讓 Agent 繼續', cancel: '取消並停止',
+    shared: '已將所選觀察分享給 Agent。', share: '將所選文字分享給 Agent', review: '請審閱新輸出,只選擇非敏感文字分享。分享的文字將記入任務。',
+    sent: '已提交,請查看終端回應;如要求重試,請重新輸入。提交不代表驗證通過。',
+    unknown: '無法確認投遞結果,未自動重試。請停止此終端,避免重複輸入。',
+    disconnected: '與終端的連線已中斷,已暫停輸入及交還。請重新連線以檢查原行程,不會重送輸入。',
+    reconnect: '重新連線原終端', invalid: '尚未傳送。請輸入不含控制字元的單行內容,最多 32 KB。',
+    select: '請選擇目前的非敏感文字。輸出可能已變更,請重新選擇。', target: '執行主機',
+    confirm: '我已檢查終端,確認可以讓 Agent 繼續操作', confirmHelp: '請完成驗證並檢查終端回應後再交還;先提交或清空尚未傳送的內容。',
+    password: 'SSH 正在要求密碼,請在下方輸入。', authentication_retry: 'SSH 拒絕了本次驗證,正在重新要求密碼。請核對帳戶後重試。',
+    exited: '原終端行程已結束,本次接管已結束,未啟動替代行程。', cancelled: '已停止終端並取消本次接管。', unavailable: '原終端已無法使用,未將控制權交還 Agent。',
+  },
+} satisfies UiCatalog<Record<string, string>>;
+type Notice = '' | 'sent' | 'unknown' | 'invalid' | 'shared' | 'select';
+
+export function TerminalHandoffPanel(props: {
+  sessionId: string;
+  request: NonNullable<RuntimeResourceHandoffResult['request']>;
+  active: boolean;
+}) {
+  const { terminal } = useWorkbarServices();
+  const locale = useUiLocale();
+  const copy = COPY[locale];
+  const [controllerId] = useState(() => crypto.randomUUID());
+  const [state, setState] = useState<RuntimeResourceHandoffResult>();
+  const [notice, setNotice] = useState<Notice>('');
+  const [busy, setBusy] = useState(false);
+  const [uncertain, setUncertain] = useState(false);
+  const [connected, setConnected] = useState(false);
+  const [disconnected, setDisconnected] = useState(false);
+  const [confirmed, setConfirmed] = useState(false);
+  const [revision, setRevision] = useState(0);
+  // Component-local only: never reuse chat drafts or generic form responses.
+  const [privateInput, setPrivateInput] = useState('');
+  const input = useRef<HTMLInputElement>(null);
+  const screen = useRef<HTMLPreElement>(null);
+  const sending = useRef(false);
+  const displayEpoch = useRef(0);
+  const identity = { sessionId: props.sessionId, requestId: props.request.requestId, controllerId };
+
+  function accept(result: RuntimeResourceHandoffResult) {
+    setState(result);
+    if (result.status === 'outcome_unknown') { setUncertain(true); setNotice('unknown'); }
+    if (result.status === 'closed') { setNotice(''); setConfirmed(false); }
+    if (result.rejection === 'controller_expired') { setConnected(false); setDisconnected(true); setConfirmed(false); }
+    if (result.rejection === 'invalid_input') setNotice('invalid');
+    if (result.rejection === 'observation_expired') setNotice('select');
+  }
+
+  useEffect(() => {
+    if (!terminal.handoff || !props.active) return;
+    let disposed = false;
+    let timer: ReturnType<typeof setTimeout>;
+    const failed = () => {
+      if (disposed) return;
+      setConnected(false); setDisconnected(true); setConfirmed(false);
+      if (input.current) input.current.value = '';
+      setPrivateInput(''); setState((previous) => previous ? { ...previous, display: undefined } : previous);
+    };
+    const poll = async () => {
+      const epoch = displayEpoch.current;
+      try {
+        const result = await terminal.handoff!({ ...identity, action: 'observe' });
+        if (!disposed && epoch === displayEpoch.current) accept(result);
+        if (!disposed && result.phase !== 'closed' && result.rejection !== 'controller_expired') timer = setTimeout(poll, 300);
+      } catch { failed(); }
+    };
+    // Reclaim only the original resource. Input is never replayed on recovery.
+    void terminal.handoff({ action: 'surface', sessionId: props.sessionId, available: true })
+      .then(() => terminal.handoff!({ ...identity, action: 'ready' }))
+      .then((result) => {
+        if (disposed) { void terminal.handoff!({ ...identity, action: 'release' }).catch(() => {}); return; }
+        setConnected(true); setDisconnected(false); accept(result);
+        if (result.phase !== 'closed') void poll();
+      }).catch(failed);
+    return () => {
+      disposed = true; displayEpoch.current++; clearTimeout(timer);
+      if (input.current) input.current.value = '';
+      setPrivateInput(''); setState(undefined); setConnected(false); setConfirmed(false);
+      void terminal.handoff!({ ...identity, action: 'release' }).catch(() => {});

Review Comment:
   P2: This cleanup still sends release whenever the card becomes inactive/unmounts. After Resume, the Host release path discards the resumed handoff (runtime-resource-coordinator.ts:568-573); returning to the card cannot observe or Share the private output (the Host now reports that the original handoff is no longer live). The new commits do not change this path. Please retain the resumed handoff across temporary card switches and test Resume → switch away → return → Share.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org


Re: [PR] feat(desktop): hand off live terminals for private user input [maka]

Posted by "Astro-Han (via GitHub)" <gi...@apache.org>.
Astro-Han commented on code in PR #5732:
URL: https://github.com/apache/maka/pull/5732#discussion_r4118330806


##########
packages/runtime/src/pty-process-driver.ts:
##########
@@ -100,7 +111,99 @@ export class PtyProcessDriver {
   }
 
   write(data: string): void {
-    this.pty.write(data);
+    if (this.writeFailure) throw this.writeFailure;
+    if (this.exited || this.disposed) throw new Error('PTY input is closed');
+    if (!this.supportsInputFence) {
+      this.pty.write(data);
+      return;
+    }
+    const buffer = Buffer.from(data, 'utf8');
+    if (this.queuedBytes + buffer.length > 2 * 1024 * 1024) {
+      throw new Error('PTY input queue capacity exceeded');
+    }
+    this.writes.push({ buffer, offset: 0 });
+    this.queuedBytes += buffer.length;
+    this.flushWrites();
+  }
+
+  get supportsInputFence(): boolean {
+    return process.platform !== 'win32' && Number.isInteger(this.unixFd);
+  }
+
+  /** Wait for admitted bytes to reach the OS, not for the child to consume them. */
+  async drainInput(signal: AbortSignal): Promise<void> {
+    if (this.writeFailure) throw this.writeFailure;
+    if (!this.supportsInputFence)
+      throw new Error('PTY input fencing is unavailable on this platform');
+    if (signal.aborted) throw new Error('PTY input fence cancelled');
+    if (this.exited || this.disposed) throw new Error('PTY input is closed');
+    if (this.writes.length === 0) return;
+    await new Promise<void>((resolve, reject) => {
+      const finish = (error?: Error) => {
+        signal.removeEventListener('abort', abort);
+        this.drains.delete(waiter);
+        if (error) reject(error);
+        else resolve();
+      };
+      const abort = () => finish(new Error('PTY input fence cancelled'));
+      const waiter = { resolve: () => finish(), reject: (error: Error) => finish(error) };
+      this.drains.add(waiter);
+      signal.addEventListener('abort', abort, { once: true });
+    });
+  }
+
+  private get unixFd(): number | undefined {
+    return (this.pty as IPty & { fd?: number }).fd;
+  }
+
+  private flushWrites(): void {
+    if (this.writeTimer || this.exited || this.disposed) return;
+    const fd = this.unixFd;
+    if (fd === undefined) return;
+    // A synchronous nonblocking write cannot outlive this PTY's fd ownership.
+    // Yield under backpressure and between bounded batches, never in the write.
+    let budget = 64 * 1024;
+    try {
+      while (this.writes.length && budget > 0) {
+        const entry = this.writes[0]!;
+        const length = Math.min(entry.buffer.length - entry.offset, budget);
+        if (length === 0) {
+          this.writes.shift();
+          continue;
+        }
+        const written = writeSync(fd, entry.buffer, entry.offset, length);

Review Comment:
   P1: this raw `writeSync` is gated only on `exited`/`disposed`. node-pty closes the fd on EIO before `exit`, so queued private input can land on a reused fd (reproduced on Linux: a newly opened file received `SECRET-PASSWORD\r`). Please stop flushing and drop the queue once node-pty reports EIO or end, or write through a dup'd fd closed together with node-pty's.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@maka.apache.org
For additional commands, e-mail: commits-help@maka.apache.org