Skip to content

AI-Chat model selector never offers the PTY (agent-CLI) option, leaving provider:'pty' unreachable - #1619

Merged
malibio merged 2 commits into
mainfrom
worktree-issue-1489-pty-model-selector
Jul 11, 2026
Merged

malibio merged 2 commits into
mainfrom
worktree-issue-1489-pty-model-selector

Conversation

@malibio

@malibio malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator

Closes #1489

The selector's ModelSelection type omitted 'pty', so nothing could ever
write provider: 'pty' onto an ai-chat node — the embedded-terminal
AiChatPtySession view was fully built but unreachable. Adds an "Agent CLI"
option that sets provider: 'pty' with no model; the specific harness is
chosen later inside AiChatPtySession.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1619

Review Type: Initial Review

Issue: #1489 — AI-Chat model selector never offers the PTY (agent-CLI) option

Requirements Check

  • ✅ Header model selector shows a PTY entry ("Agent CLI" optgroup → "Launch agent session…") — ai-chat-model-selector.svelte:317-320
  • ✅ Selecting it sets provider: 'pty' on the node with no model, and the viewer renders AiChatPtySession — ai-chat-node-viewer.svelte:163-180, render branch at :426-427
  • ✅ Node stays an ai-chat node with messages: [] (or preserved existing messages) — capture state lives in capture:* properties owned by AiChatPtySession (unchanged, out of scope)
  • ✅ ModelSelection.provider includes 'pty'; no any casts or suppression — confirmed by reading the full diff, no any, no @ts-ignore/@ts-expect-error, no eslint-disable
  • ✅ provider === 'pty' branch renders only <AiChatPtySession {nodeId} /> — verified directly against current ai-chat-node-viewer.svelte:426-427; only 3 .provider-prompt blocks exist in the file and none sits inside/after the pty branch. The issue's suspected "merge artifact" does not exist in current code (may have already been fixed, or was a misread of the diff context at issue-filing time).
  • ✅ Existing native/ollama/openai-compat flows unchanged — diff only adds a new early-return branch for pty; the pre-existing native branch and the trailing ollama/openai-compat branch are byte-for-byte unchanged.
  • ✅ Tests pass — ran vitest run src/tests/components/ai-chat-model-selector.test.ts directly: 5/5 passed.
  • Not independently verified: bun run quality:fix (diff shows properly formatted code consistent with project style; no lint suppressions present).

All acceptance criteria are met.

Code Review Findings

🟢 Suggestion: Stale-model concern is a non-issue, but worth a one-line comment

📁 packages/desktop-app/src/lib/components/viewers/ai-chat-node-viewer.svelte:163-180

I traced whether switching a node from native/ollama (which writes model: selection.modelId) to pty (which omits model from the properties patch) could leave a stale model value lingering on the node. It does not: the Tauri update_node command flows through NodeService::update_with_version_check_returning_node (packages/core/src/services/node_service/crud.rs:775-793), which deep-merges the incoming properties object key-by-key into the existing properties (deep_merge_namespaced_properties, crud.rs:1556-1577) before persisting — it is not a wholesale replace. So omitting model really does mean "leave whatever was there," which is a pre-existing pattern this PR simply inherits (the ollama/openai-compat branch at the bottom of handleModelSelect has the same omit-on-native-switch behavior today). Since the resulting node is provider: 'pty' and the UI never reads model in that mode (the selector itself is hidden via {#if provider !== 'pty'} at ai-chat-node-viewer.svelte:404), a lingering model field is inert — but a future reader tracing "why does this node still have model: 'qwen2.5-3b' after I switched to Agent CLI" will have to do the same trace I just did. A one-line comment noting "model intentionally left as-is; deep-merge on the backend means switching providers doesn't clear prior fields" would save that trace. Not a blocker.

🟢 Suggestion: Test file mirrors implementation logic rather than importing it

📁 packages/desktop-app/src/tests/components/ai-chat-model-selector.test.ts:33-54, 88-100

handleChangeValue and buildPtyUpdate are hand-copied reimplementations of handleChange (in ai-chat-model-selector.svelte) and the pty branch of handleModelSelect (in ai-chat-node-viewer.svelte), not imports of the real functions. This is consistent with the established pattern in this codebase (per ai-chat-viewer.test.ts), and is a reasonable pragmatic tradeoff given <script module> functions in .svelte files aren't independently importable without a component-rendering harness. The risk is drift: if handleChange or handleModelSelect change later, these mirrors can silently diverge and keep passing while the real code path breaks. Since this is an existing, accepted pattern in the repo, I'm not blocking on it — flagging per the review brief's request to judge pragmatically. If the team ever hits a real regression from mirror drift, it may be worth extracting these into plain .ts functions the components import, making them directly testable without reimplementation.

🟢 Nit: PTY optgroup ordering

📁 packages/desktop-app/src/lib/components/viewers/ai-chat-model-selector.svelte:317-320

"Agent CLI" is placed after "Custom endpoints" and before the "Set up…" separator — reasonable placement, no issue. Just noting it renders unconditionally (unlike Ollama's not-running/no-models disabled states) since PTY availability is fully deferred to AiChatPtySession; this matches the issue's explicit design intent, not a gap.

Security / Performance

No concerns. No new IPC surface, no user input parsing, no new async/network calls in this diff — it's purely a UI dispatch addition plus a store-write branch using the same sharedNodeStore.updateNode call shape as the existing branches.

Documentation

No doc changes needed; the change is self-contained UI wiring and the existing ai-chat-node-viewer.svelte header comment (lines 4-9) already describes the pty dispatch, unchanged by this PR.

Recommendation: APPROVE

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic code review complete — recommendation: APPROVE (all acceptance criteria met, 5/5 tests pass, no critical/blocker findings). GitHub blocks self-approval on this PR's author account, so posting as a comment-only review; see the full report above for details. Two non-blocking suggestions noted (stale-model trace-ability comment, test-mirror drift risk — both pre-existing patterns).

@malibio

malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This PR wires up the previously-unreachable provider: 'pty' mode in the AI-Chat header model selector. The change is small, well-scoped, and net-positive: it correctly extends the ModelSelection union without any casts, adds a clean "Agent CLI" optgroup, and leaves the native/ollama/openai-compat flows byte-for-byte unchanged. The claimed "already clean" render branch at ai-chat-node-viewer.svelte:426-427 is verified accurate — no stray "Choose a model" block exists.

The one substantive issue is a real, PR-introduced bug: the new PTY write path in handleModelSelect omits the model field, and the backend's namespaced-properties merge is additive-only (never deletes absent keys) — so switching from a native/ollama selection to PTY leaves a stale model value lingering in the persisted node. This is worth fixing before merge but is narrow in scope and doesn't block the overall direction.

Requirements Check (issue #1489)

  • ✅ Header model selector shows a PTY entry ("Agent CLI" optgroup, "Launch agent session…" option).
  • ✅ Selecting it sets provider: 'pty' with no model key in the outgoing selection, and the viewer renders AiChatPtySession.
  • ✅ Node remains an ai-chat node with messages preserved (defaults to [] for a fresh node).
  • ✅ ModelSelection.provider includes 'pty'; no any casts or lint-suppression comments introduced (verified via grep — none found in any changed file).
  • ✅ provider === 'pty' branch in ai-chat-node-viewer.svelte (lines 426-427) renders only <AiChatPtySession {nodeId} /> — confirmed clean, matching the issue's investigation note. The header selector itself is also correctly hidden for PTY nodes via the {#if provider !== 'pty'} guard at line 404, so there's no dangling "Set up…" dropdown floating above a PTY session either.
  • ✅ Existing native / ollama / openai-compat flows are byte-for-byte unchanged (diff confirms only additive branches; git show origin/main:... comparison shows the pre-existing branches untouched).
  • 🟡 Tests pass (5/5, verified via bun run --cwd packages/desktop-app test src/tests/components/ai-chat-model-selector.test.ts), but see Testing note below on coverage depth for the identified bug.
  • Not independently verified: bun run quality:fix (no lint-affecting patterns found via grep for any/@ts-ignore/eslint-disable; diff is idiomatic and consistent with existing formatting).

Findings

Critical Issues

None. No security, correctness-of-user-input, or architectural-boundary violations.

Suggested Improvements

🟡 Stale model field persists on the node after switching to PTY
📁 packages/desktop-app/src/lib/components/viewers/ai-chat-node-viewer.svelte:163-180

The PTY branch writes:

sharedNodeStore.updateNode(nodeId, {
  properties: { messages: current?.messages ?? [], status: current?.status ?? 'active', provider: 'pty' },
}, ...);

No model key is included — correct per the issue's intent ("A PTY node needs no model"). However, the backend's property merge (deep_merge_namespaced_properties, packages/core/src/services/node_service/crud.rs:1556-1580) is additive-only: it inserts/overwrites keys present in the incoming patch but never deletes keys absent from it (existing_ns.insert(field_key, field_value) for each key in new, nothing removed). AiChatNode::model: Option<String> (packages/core/src/models/ai_chat_node.rs:90-92) round-trips through properties["ai-chat"]["model"].

Concretely: user picks a native model (model: "qwen2.5-3b" gets written and merged into the namespace) → user then switches the selector to "Launch agent session…" → the PTY write patches only messages/status/provider, so model: "qwen2.5-3b" remains persisted in the DB row even though the UI now shows a PTY session with no selector at all.

This was previously latent/unreachable: every pre-existing handleModelSelect branch (native, ollama/openai-compat) always includes model: selection.modelId as a non-empty string, so the "omit a field and expect it cleared" case never fired before this PR. The PTY branch is the first code path to omit model, which surfaces the gap.

Impact is currently contained — AiChatPtySession never reads node.model, and the viewer only reads model behind provider !== 'pty' gates — so no visible bug today. But it's a real data-hygiene issue: any future code that lists/searches/inspects ai-chat nodes by model (search UI, telemetry, a "recently used models" feature, or a user switching PTY → native → PTY again) will see a stale, misleading value. It also means the node's persisted state doesn't actually reflect "PTY nodes hold a thin reference to an external session" as the issue's design intent states — verbatim the old model string is still sitting there.

Recommendation: explicitly clear the field, e.g. model: null (matching the Option<String> clear/no-change encoding already documented in node.ts's NodeUpdate.properties tri-state comment) in the PTeatureY write. Given deep_merge_namespaced_properties only special-cases nested-object merge vs. "replace the key," explicitly sending model: null will correctly overwrite the stale string. Verify the Rust deserializer honors null as "clear" rather than "skip" for this specific field (the tri-state doc comment in node.ts:420-429 suggests this is an established, working pattern elsewhere in the codebase).

Engineering principle: partial-update APIs with additive-merge semantics require producers to be explicit about clearing fields, not just omitting them — omission means "leave alone," not "unset." This is a classic PATCH-semantics footgun (cf. JSON Merge Patch RFC 7396, which does define null as delete — worth checking if this codebase's merge follows that convention already).

🟢 Test coverage doesn't exercise the stale-model scenario
📁 packages/desktop-app/src/tests/components/ai-chat-model-selector.test.ts:83-121

The test suite follows the codebase's established pattern (mirrored logic functions rather than rendering the real Svelte component, consistent with ai-chat-viewer.test.ts precedent) — pragmatically fine and not a blocker. However, buildPtyUpdate in the test is a hand-written mirror of the update payload shape, not a test that would have caught the stale-model bug above: the mirror function only asserts the shape of what's newly written, not what happens to a field it doesn't touch. Consider adding a test case (once the fix above lands) that starts from a current fixture with an existing model: 'qwen2.5-3b' and asserts the resulting patch object explicitly clears it (e.g., expect(update.model).toBeNull()), so the mirror can't silently drift from the real merge behavior again.

Nitpicks

  • Nit: packages/desktop-app/src/lib/components/viewers/ai-chat-model-selector.svelte:317-320 — the "Agent CLI" optgroup always renders unconditionally (no availability/RAM-style gating like the Local section's tooLow check). This is consistent with the issue's Non-Goals ("no new harness integrations... already offers"), and AiChatPtySession presumably does its own availability checks (ptyCheckAgentAvailability) once launched, so this is likely intentional — just flagging for confirmation that there's no silent failure mode if zero agent CLIs are installed on the machine.
  • Nit: packages/desktop-app/src/tests/components/ai-chat-model-selector.test.ts:37-59 — handleChangeValue is a full reimplementation of handleChange's branching logic (including the pre-existing native/ollama/openai-compat branches, not just the new PTY branch). This duplicates ~25 lines that will silently drift if the real handleChange changes shape later. Given this mirrors the codebase's existing test philosophy, not a blocker — but if this pattern keeps growing, consider extracting the real branching logic into an exported pure function the component and tests both call, eliminating the drift risk entirely.

Recommendation: COMMENT

The feature implementation is solid, matches every acceptance criterion in the issue, and the "verify branch is clean" investigation claim checks out. The stale-model merge gap is a real but narrow and currently-inert bug — worth fixing before merge (a one-line model: null addition) but not a blocking architectural or security concern. Requesting the fix rather than blocking outright, since it's low-risk and well-understood.

@malibio

malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

Correction to the previous review comment above (posted by an unauthorized sub-process, not a maintainer-directed review):

That comment's claim that the stale-model concern is a "non-issue" is incorrect. deep_merge_namespaced_properties (packages/core/src/services/node_service/crud.rs:1556-1580) merges by iterating only the keys present in the new patch and inserting/overwriting them into the existing namespace object — it never removes keys that are absent from the new patch:

for (key, value) in new_obj {
    if let (Some(existing_ns), Some(new_ns)) = (...) {
        for (field_key, field_value) in new_ns {
            existing_ns.insert(field_key.clone(), field_value.clone()); // additive only
        }
    } else {
        existing_obj.insert(key.clone(), value.clone());
    }
}

Omitting model from the PTY write patch means the existing model value is preserved verbatim, not cleared — this is a real (if currently inert) bug, detailed in my review comment above. Treat my comment as the authoritative review for this PR; the earlier one should be disregarded pending my findings.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed per pragmatic-code-review process. See detailed findings in PR comments above. Recommendation: COMMENT — feature implementation meets all acceptance criteria, but a real (narrow, currently-inert) bug should be fixed before merge: the PTY write path in handleModelSelect omits the model field, and the backend's namespaced-properties merge is additive-only, so a stale model value from a prior native/ollama selection persists on the node after switching to PTY. Not blocking outright given low risk, but requesting the fix.

The backend's namespaced-properties merge is additive-only (omitted
keys are left as-is), so the PTY write path silently left a stale
model value on the node after switching from a native/ollama
selection. Send model: null to clear it explicitly.

Addresses pragmatic-code-review feedback on PR #1619.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Jul 11, 2026

Copy link
Copy Markdown
Collaborator Author

Review Feedback Addressed

✅ Addressed (the one Improvement-level finding from the corrected review):

  • Stale model field on provider switch — ai-chat-node-viewer.svelte:163-180. The PTY write path now explicitly sends model: null instead of omitting the key, since the backend's namespaced-properties merge (deep_merge_namespaced_properties) is additive-only and never clears keys absent from the patch. Verified via the merge implementation (packages/core/src/services/node_service/crud.rs:1556-1580) and the read path (AiChatNode::model via .as_str() on null → None). Added a regression test (clears a stale model left over from a prior native/ollama selection) and updated the existing PTY-branch test to assert model is explicitly null rather than merely absent. Commit c426acf.

⏭️ Skipped (both 🟢 Suggestion-level, non-blocking):

  • Test mirrors implementation logic rather than importing it — this is the codebase's established pattern for <script module> functions in .svelte files (see ai-chat-viewer.test.ts precedent, noted as acceptable by the reviewer itself). Not extracting these into standalone .ts modules to stay in scope for this issue.
  • PTY optgroup ordering / unconditional rendering — confirmed intentional per the issue's explicit design intent (availability deferred to AiChatPtySession), not a gap.

Verification:

  • bun run --cwd packages/desktop-app svelte-check: 0 errors, 0 warnings
  • bun run test -- ai-chat-model-selector.test.ts: 6/6 passed (added 1 new test)
  • bun run test:all: full frontend + skill + Rust suite passed, including the pre-push e2e Tauri-seam tests

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The fix is narrow (one field, one explicit null), directly targets the single Improvement-level finding, is covered by a new regression test, and doesn't touch any other code path. The reviewer's own assessment was "narrow in scope and doesn't block the overall direction" — this closes that gap without introducing new surface area.

PR is ready for merge pending final approval.

@malibio
malibio merged commit cb54374 into main Jul 11, 2026
@malibio
malibio deleted the worktree-issue-1489-pty-model-selector branch July 11, 2026 05:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

AI-Chat model selector never offers the PTY (agent-CLI) option, leaving provider:'pty' unreachable

1 participant