Skip to content

[P1][LM-2] Add secure local connections and bounded model discovery #378

Closed

Description

@BunsDev

Outcome and dependencies

Persist user-approved local connections and enumerate their models without scanning the machine, exposing credentials or sending project content.

Parent: #376. Blocked for completion by: #377 (LM-1: accepted identity/capability/migration contract and native configuration map). Delivery group: Local models v1 / Gate B. Priority: P1. The shared execution contract and privacy invariants in #376 apply. Dependencies refer to accepted artifacts, not unrelated producer issue closure.

Context and source entry points

Refresh current main, scoped instructions and open PRs. Publication baseline: ec7be578765f9ce54976882853e57ca190252361. Existing: apps/desktop/src/main/engine/{store,secrets}.ts and the actual main/preload IPC registration identified in #377. Proposed: apps/desktop/src/main/engine/local-models/{connections,discovery,endpoint-policy}.ts, apps/desktop/test/local-model-discovery.test.ts. Reuse equivalent existing mechanisms rather than duplicating them.

Consumes: #377's connection/model/qualification schema. Produces: main-owned persisted profiles, narrow validated discovery commands, bounded non-secret model descriptors and revision-aware discovery results for execution and UI consumers.

Implementation steps

  • Add explicit Ollama, LM Studio and Custom Responses connection settings backed by main-owned storage. Initial scope is same-machine loopback only; defer LAN/remote configuration. Metadata adapters may differ, but share the execution/identity contract.
  • Validate IPC sender, request schema, connection ownership/revision and endpoint in main. Allow explicitly configured loopback HTTP(S) destinations only. Normalize IPv4/IPv6; reject credentials-in-URL, non-HTTP schemes, non-loopback resolution, unexpected paths and redirects outside the approved origin. Protect against hostname-resolution changes. Never execute renderer-supplied auth helpers or shell strings.
  • Store optional local-server credentials with the existing encrypted secret store. Renderer receives only an opaque reference/status. Never reuse or forward cloud account credentials to a local endpoint. Redact secrets before logs/persistence/export, not only in the UI.
  • Fetch bounded runtime metadata with deadlines, cancellation, bounded response size and stale-result protection. Distinguish installed, loaded and unavailable when exposed; otherwise say unknown. Keep exact model IDs opaque, including aliases/slashes/spaces where the runtime accepts them. Support explicitly entered IDs when discovery is incomplete.
  • Represent generative, embedding, decision and other model types accurately where known. Metadata-advertised tools are not qualified tool use. Exclude known cloud-routed models from local-only selection; unknown downstream inference location remains unverified.
  • Opening Settings or refreshing must not install a runtime, download weights, load/unload models, scan directories or probe arbitrary ports. Explain separately that an explicit user-started inference turn may cause the selected runtime's ordinary cold load.
  • Define profile edit/delete behavior: revision changes invalidate stale discovery/qualification; active runs retain their snapshot; subsequent execution cannot resolve deleted credentials or silently rebind to a replacement profile. Preserve readable historical provenance.

Acceptance criteria

  • AC1: normal, empty, malformed, unavailable, authenticated and delayed metadata fixtures work through main/IPC without inference or project-data transmission.
  • AC2: non-loopback, URL injection, IPv4/IPv6 normalization, DNS/redirect and forged-IPC cases cannot bypass the endpoint policy.
  • AC3: tokens are absent from renderer state, URLs, diagnostics, snapshots and exported records; cloud account credentials are never forwarded.
  • AC4: identical model IDs on different connections remain distinct targets; a delayed response after connection edit/switch cannot appear current.
  • AC5: custom/manual IDs remain available for explicit compatibility tests; known embedding-only models cannot be selected as coding agents.
  • AC6: discovery causes zero installs/downloads/model loads/port scans; profile deletion/edit preserves history and cannot redirect an existing run.

Verification and handoff

Write failing-first endpoint, credential, discovery and race tests. Run pnpm build && pnpm test; UI changes also pnpm test:e2e, plus focused tests from current scripts. Record actual request counts, redaction checks, SHA and result evidence. Metadata requests to a real user-installed runtime need appropriate authorization and no private prompt data. Update status and a dated review receipt. No merge/release/global configuration writes.

Long-running goal prompt

Implement LM-2 in TypeSafeAI/modex under #376 after consuming #377's accepted contract. Read current AGENTS.md, source, open PRs and the tracker execution contract; verify main and worktree ownership. Start with failing endpoint, credential and stale-response tests. Build only main-owned profiles and bounded metadata discovery for explicit loopback connections, using existing encrypted secret storage. Return non-secret descriptors with accurate unknown/installed/loaded/capability states and exact model IDs. No inference, downloads, filesystem scans, arbitrary port discovery or global CLI configuration changes. Implement one acceptance slice at a time, run targeted/full checks, update status/evidence and prepare signed commits. Checkpoint SHAs, versions, exact results, unresolved gates and one next action. Do not merge or release.

Follow-up / resume prompt

Resume LM-2 from its live issue/PR and checkpoint. Verify ownership, actual diff and #377's current contract. Retest forged IPC, URL canonicalization, IPv4/IPv6, DNS/redirect boundaries, same-name models and late responses after profile edits/deletion. Inspect logs/snapshots/exports for tokens and count requests to prove discovery never starts inference or downloads. Continue the smallest failing criterion without adding remote connection management or installers. Rerun smoke/full checks, record fresh criterion-level evidence and leave unavailable native/human gates open. No merge, publication or scope expansion.

Activity

  1. self-assigned this
    on Oct 22, 2026
  2. BunsDev commented on Oct 23, 2026

    @BunsDev
    ContributorAuthor

    Refreshed goal prompts — 2026-10-23 (main at 203a350)

    On main already:

    • nothing from LM-2. There is no apps/desktop/src/main/engine/local-models/ on main, and docs/status.md has no local-model entry.

    Still open:

    • Draft PR LM-2: secure local connections and bounded model discovery (#378) #386 (lm2-discovery, head 3654053, six commits on ec7be57). It adds a loopback-only endpoint policy, main-owned profiles in app/local-connections.json with tokens in the existing SecretStore, and bounded discovery for Ollama, LM Studio and Responses-compatible servers. These go through one strict local-models:command IPC channel that the Store desktop demo refuses. There is no UI, no execution binding and no inference. All evidence comes from synthetic loopback fixtures, written up in docs/reviews/2026-10-22-lm2-connections-discovery.md. CI is green, including unit + e2e (macOS), and GitHub reports the PR mergeable. The PR says not to merge yet.
    • Two defects reported in review, not yet fixed. The first matches the write ordering in connections.ts; the second is not yet reproduced, so confirm it with a failing test first. They are recorded in an unpublished review in the lm-foundation worktree.
      • P1: connections.ts replaces or clears the token before it writes the new revision. If the profile write then fails, the old revision resolves the new credential. I confirmed the ordering in the source.
      • P2: a server can echo the bearer token back as a model ID, and discovery returns it to IPC.
    • [P1][LM-1] Define local-model contracts and prove the native Codex integration seam #377 is not accepted. LM-1's contract is an unpushed commit (048d1e8 on lm1-contract). LM-2: secure local connections and bounded model discovery (#378) #386 must adopt its types: model refs gain schema: 1, ConnectionRef gets one owner, and LM-2: secure local connections and bounded model discovery (#378) #386's ollama/lmstudio/responses metadata runtimes map onto LM-1's profile kinds.
    • Native metadata evidence. Listing-only reads against a real Ollama and LM Studio the user has already installed, with their versions recorded. This needs Val's authorization.
    • Policy note. AGENTS.md lists every network call the app makes outside the CLIs. Loopback metadata discovery is not on that list yet.

    Long-running goal prompt

    Finish LM-2 (#378) in TypeSafeAI/modex under tracker #376. Read AGENTS.md, #376's shared execution contract and privacy invariants, this issue, draft PR #386 and its receipt docs/reviews/2026-10-22-lm2-connections-discovery.md, then verify main's SHA. Never edit the primary checkout. The work is on lm2-discovery. If you are not its owner, claim it with scripts/worktree.sh claim lm2-discovery --owner <session> and run check. Slice 1: rebase #386 onto current main and re-run the focused local-model tests. Slice 2: fix the persistence defect. Write a failing test first that injects a profile-write failure during token rotation, token clear, address change, create and delete. Then make sure an old revision can never resolve a changed credential, for example with credential references versioned per revision or a recoverable write order. Slice 3: write failing tests for a server that echoes the token back, exactly or embedded, as a model ID. Refuse that metadata before it reaches IPC, without rewriting real model IDs. Slice 4: once #377 is accepted, adopt its types in place of shared/local-connections.ts. Add schema: 1 and map runtimes explicitly, so there is one identity model and no behaviour change. Until then, leave completion blocked on #377. Slice 5: only with Val's authorization, do listing-only reads against an Ollama and an LM Studio already installed on the machine and record their versions. Never pull, load or unload a model. Discovery must never start inference. Coding turns stay in the codex and claude CLIs. Propose an AGENTS.md line that names loopback metadata discovery. Run pnpm build && pnpm test, pnpm --filter @modex/desktop typecheck and the local-models IPC Playwright spec. Run the full pnpm test:e2e if any renderer code changes. Update the receipt and docs/status.md. Push signed commits and take #386 out of draft only when #377 is accepted. Wait for Val's go-ahead to merge.
    

    Follow-up / resume prompt

    Resume LM-2 (#378). Confirm you own lm2-discovery, fetch main and read the latest comments here, on #377 and on #386. Re-run the focused local-model tests and the failure-injection and token-echo regressions. Check whether #377's contract changed or was accepted. If it was, adopt it now. Count the requests each fixture makes, to show that discovery never hits an inference, pull, load or unload route. Do not add remote or LAN connections, installers or UI here. Post a checkpoint: SHA, results, runtime versions if native reads were authorized, what's left for a human, and one next action.
    
  3. BunsDev commented on Oct 24, 2026

    @BunsDev
    ContributorAuthor

    LM-2 checkpoint, 2026-10-24 (main at 70123b9)

    Owner: this session, in its own worktrees lm2-integrate and lm2-adopt. lm2-fixes (#398), lm2-discovery (#386) and lm1-contract (#397) belong to other sessions and were not edited.

    Draft #402 (lm2-integrate): hardening stacked on #398 at 954cd5b. Head a5da8292b87b89b142854c8c0dba31e692ef2d63; code at b12483c2439639ae274d1fcb2bca03e638a03207. Every fix began with a regression that failed on 954cd5b:

    • an unreadable, wrongly shaped or newer-version profiles file was replaced on the next save, losing profiles and tombstones (AC6). It is now refused and left byte-for-byte, and entries this build can't validate are written back exactly as found;
    • the saved token could be saved into the label or a manual model ID in plain text (AC3). That is now refused;
    • token entries left by a crash or a failed clear stayed in secrets.json (AC3/AC6). They are now swept after every successful save, and other secrets are never touched;
    • an undecryptable saved token turned into an unauthenticated read that could report ready. It is now credential-unavailable, with zero requests;
    • a whole discovery had no deadline: 32 slow /api/show reads took 7.2 s at a 1 s per-request deadline. It now ends within three per-request deadlines, and unread detail stays unknown.

    Regression-only coverage found no defect: stale answers through LocalModelsService after every kind of edit and after deletion, and more IPv4/IPv6/IDN endpoint spellings.

    Results on b12483c: focused 32/32; pnpm build && pnpm test exit 0 (worktree 117, core 16, desktop 1884 with 1868 passed and 16 skipped, native 21, site 10, Store 16); pnpm typecheck exit 0; e2e/local-models-ipc.spec.ts 1/1. PR CI on a5da829 passed every job: unit + e2e (macOS) (required), iPhone companion, CLI and installers on win32 and Linux, and the TypeScript coverage upload.

    Local lm2-adopt (not pushed): LM-1 adoption stacked on #402. Head 2d4536d; code at 121170801d504c96ac57a48600f1379c0da1dbdb.

    • It merges LM-1's reconciliation 91deb281ad36f522636d9b6e2fe55105b74d47ae. That commit is still only on the LM-1 session's local branch (LM-1: local-model contracts and native feasibility (#377) #397 is at c30633d), so this branch can't be pushed until 91deb28 is published unchanged, or rebased if it changes.
    • It applies the LM-1 consumer patch unchanged. ConnectionRef and schema-1 LocalModelRef now come from shared/local-models.ts.
    • It keys advertised by [P1][LM-1] Define local-model contracts and prove the native Codex integration seam #377's Capability (images instead of vision; structuredOutputs, resume and cancellation are unknown).
    • It adds a regression showing that NODE_USE_ENV_PROXY/--use-env-proxy never route a read or its token through HTTP_PROXY. The test fails if agent: false is removed.
    • Results: focused 42/42; pnpm build && pnpm test exit 0 (desktop 1898 with 1882 passed and 16 skipped; other suites as above); typecheck exit 0; IPC e2e 1/1.

    Versions: macOS 27.0.1 arm64, Node v24.22.0, pnpm 10.34.5, Electron 44.4.5, Playwright 1.63.0. No real runtime was contacted. Every result is fixture or real-Electron evidence, not native.

    Still open:

    Next action: once 91deb28 is on origin/lm1-contract, push lm2-adopt and open it as a draft stacked on #402.

  4. BunsDev commented on Oct 24, 2026

    @BunsDev
    ContributorAuthor

    LM-2 checkpoint update (main at 03ce71a)

    The previous checkpoint's next action is done. LM-1's reconciliation was published as #400 (lm1-handoff at cb7ca6c, which descends from 91deb28 with identical contract files), and #397 merged as ffb9e1d.

    Landing order, none of which is authorized here: #377 acceptance, then #400, then #398 (or #386), then #402, then #403. Each stacked PR needs a rebase after the squash below it.

    Still open:

    Next action: Val decides Gate A on #377.

  5. added 2 commits that reference this issue on Oct 24, 2026
  6. BunsDev commented on Oct 24, 2026

    @BunsDev
    ContributorAuthor

    LM-2 note (main at bb0e1a4): #400 landed. Draft #403 (lm2-adopt) now merges that main (head c7107c3350ebdf5dde5edfeace5c161af864eb12, code 3457e0ad5a7c7503cd4a968cdce21224e85109a7), so its diff against main is only the 17 LM-2 files. The only conflict was the adoption paragraph in docs/local-models.md, and this branch's text was kept.

    Fresh local results on 3457e0a: focused 42/42; pnpm build && pnpm test exit 0 (desktop 1907 with 1891 passed and 16 skipped; native/package 26 with 21 passed and 5 skipped from #396's native tests; worktree 117, core 16, site 10, Store 16); typecheck exit 0; IPC e2e 1/1. Hosted CI on the previous head 5652180 was all green.

    Draft #402 still merges cleanly with main.

    Remaining landing order, none of it authorized here: #377 Gate A recorded, then #398 (or #386), then #402, then #403.

    Next action: Val records Gate A on #377.

  7. BunsDev commented on Oct 24, 2026

    @BunsDev
    ContributorAuthor

    LM-2 checkpoint: consuming the accepted contract (main at bb0e1a4)

    Gate A was accepted on #377 on 2026-10-24, narrowly, for main at bb0e1a42ac7bb3e11ccfee05a40d8a02f1dc10c4 and the recorded Strata combination. LM-2 now consumes that accepted contract.

    • LM-2: main-owned local connections and bounded model discovery (#378) #403 (lm2-adopt, head 2956c1a) is ready for review. Its LM-1 files are byte-identical to bb0e1a4. ConnectionRef/schema-1 LocalModelRef come from shared/local-models.ts, advertised is keyed by Capability, and it adds the env-proxy regression. The docs now record the acceptance. The code is unchanged since 3457e0a: local results there were focused 42/42 and pnpm build && pnpm test exit 0 (desktop 1891 passed, 16 skipped). Hosted CI was all green on c7107c3 and again on 2956c1a (docs only), including the required unit + e2e (macOS).
    • LM-2: hardening on #398: history, credential and deadline fixes (#378) #402 (lm2-integrate, head a5da829) is ready for review: five fixes, each failing-first; all hosted CI green.

    Neither is merged. Landing order: #398 (or #386), then #402, then #403. Each needs Val's go-ahead and a rebase after the squash below it.

    Still open:

    Next action: Val chooses between #386 and #398 and gives the go-ahead to land #398, which unblocks #402 and #403.

  8. BunsDev commented on Oct 24, 2026

    @BunsDev
    ContributorAuthor

    LM-2 landed on main as e17aebd2fd4a2c691ee4e8946b5c2ef767aa023a (#403)

    Val asked for #403 to land on main. It was retargeted from lm2-integrate to main and went through the merge queue as one squash. That carries #398's six commits and two review fixes, #402's hardening and the adoption of LM-1's accepted contract.

    Still open on #378:

    Next action: once a local generative model is installed and Val authorizes it, run LM-2 discovery against it and record the result in docs/reviews/2026-10-22-lm2-connections-discovery.md. LM-3 (#379) can build on main now.

  9. BunsDev commented on Nov 12, 2026

    @BunsDev
    ContributorAuthor

    LM-2 implementation step 6 is now supported on protected main 5f1f1fe8bfa93ee971de7b443f794335ae9c414e, delivered by #498. The Settings explanation distinguishes metadata-only checks from an explicit first-message cold load and keeps execution admission unavailable. Refresh enumerates saved explicit profiles; discovery uses fixed bounded metadata adapters, with no runtime installer, model download/load/unload, filesystem scan or arbitrary-port probe.

    The protected queue run passed the actual Settings add/list/Refresh/remove case, whose fixture records only metadata GETs. Its complete macOS log records 2,471 unit passes with 36 skips, 514 desktop E2E passes with 8 skips, and 7 site passes. The earlier criterion audit’s 24 source hashes were independently revalidated against the actual merged tree before this reconciliation.

    Only the cold-load/metadata explanation step is being ticked. The manual-ID visibility repair and added empty/malformed/delayed IPC regressions are still on the separate lm2-visibility candidate; full E2E is running and they have not been delivered. Packaged secure-storage acceptance and the full remaining issue criteria stay open. Metadata request counts do not establish inference compatibility or the runtime’s internal behavior.

  10. BunsDev commented on Nov 12, 2026

    @BunsDev
    ContributorAuthor

    LM-2 complete literal-criteria audit and native credential receipt

    All seven implementation steps and six acceptance criteria are supported on signed protected main 5a580d4f98f5b1c62c5801db4400d5b533634082. The 20 credential/discovery/identity/IPC/export source and test files in the independent audit are byte-identical to their reviewed versions; the intervening #505 runner changes retain the local pinning/no-cloud-fallback guards. This is a narrow consumer check, not a review of the entire credit-conservation feature. The accepted #377 contract dependency is satisfied.

    • S1: main persists explicit Ollama, LM Studio and Custom Responses profiles using the accepted connection/model schema and production Settings IPC; scope remains configured same-machine loopback.
    • S2: trusted-sender and exact-schema checks, connection ownership/revision, canonical IPv4/IPv6 and repeated DNS/socket checks enforce main-owned endpoints. URL credentials, injection, proxy routing and redirects are refused; no renderer auth helper or shell is executed.
    • S3: local tokens use their own opaque namespace in the shared encrypted SecretStore, presence-only replies and fail-closed credential resolution. The packaged native test below proves the real macOS cipher boundary; local-token tests prove namespace, routing and redaction consumers.
    • S4: metadata has request/aggregate deadlines, cancellation, response/model bounds and stale-result protection. Exact/manual IDs survive metadata failures when credentials remain readable; unavailable credentials or rejected IPC cannot reconstruct descriptors. Runtime-exposed installed/loaded state stays separate from unknown.
    • S5: generative, embedding and other advertised model kinds remain distinct; advertised tools do not qualify coding. Known cloud-routed models are excluded and unknown downstream inference locality remains unverified.
    • S6: Settings and refresh use only fixed metadata routes, with no inference, install/download, model load/unload, directory scan or port enumeration. The cold-load explanation is separately delivered by Integrate local-model workflow and native recovery with closeout evidence #498.
    • S7: revisions, tombstones, exact credential binding, active-run edit/delete refusal and retained snapshots prevent replacement/deletion from redirecting an existing run while preserving readable history.
    • AC1: normal, empty, malformed, unavailable, authenticated and delayed fixtures pass through production main/IPC; recorded requests carry only bounded metadata, never project content or inference.
    • AC2: endpoint, DNS/redirect/proxy and forged-IPC tests enforce the same production boundary.
    • AC3: safe renderer descriptors omit tokens; URLs reject credentials; fixed diagnostics and reflection guards avoid secret echoes; pre-event/log/record/snapshot redaction covers split and truncation boundaries. The actual saved and reopened Task Note export retains positive marks while omitting tokens. Authenticated discovery sends exactly its own connection token; tokenless requests have no Authorization header, and a seeded cloud credential is never forwarded. The native proof composes with these separate consumer tests; the generic key test alone does not establish every surface.
    • AC4: identity includes connection and revision; delayed edit/switch/delete responses cannot become current. test(local-models): preserve drafts and selection across metadata races #503's canonical endpoint-replacement case preserves the old thread target.
    • AC5: explicit custom/manual identities remain available for compatibility testing; embedding/nontext/cloud exclusions cannot become coding agents. The downstream compatibility-test interface and execution admission belong to their own issues.
    • AC6: exact request fixtures prove discovery makes no forbidden calls, and revision/history/active-run guards prevent silent rebinding.

    The protected #503 queue passed 2,478 unit cases with 36 skips, 522 desktop cases with eight skips and seven site cases, with zero failures or observed retries (required macOS job). Relevant cases and unchanged source were rechecked against current main. Production references: shared encrypted store, local connection namespace, token/record/export regressions and canonical credential assertions.

    The private QA artifact is ad-hoc macOS arm64 Modex 0.4.2, built from docs head 2825d145ef2ea2297e31553c08a04f57a1be3925 with application inputs equal to protected 558b54f8. ASAR SHA-256: 9f8f2334167e87706eb6a177f745a21e8fb2c10f30943617a5a5114d21e4ec66. The first canonical invocation timed out clicking Settings before key entry; Val observed no Keychain prompt, and the cause remains unestablished. A separate read-only Settings diagnostic passed. One explicitly recorded second canonical invocation then passed the unchanged original assertions: packaged Keychain backend, synthetic key outside state.json, ciphertext without plaintext including after base64 decoding, 0600 file, masked/cleared input, retrieval after reopening and Clear. Result: one pass, zero skips and zero framework retries. The app closed, private canonical fixture directories were cleaned by the test, artifact hashes stayed unchanged and strict deep codesign verification returned zero. No model turn ran and the installed user app was not replaced or closed.

    External retained receipts: full 13-clause independent audit SHA-256 72a20278a2274d42b748976b7add5066c955501251d8b2aaa7cc4eada49f2976; native terminal independent review 02b30a3b37017452a204cc88c7ab550024c12ef0bb12222075b0f2ff6d7476ef; native terminal audit fdd6f9518457e692df9fae11b624826e4d5f5a00f84f9bea7e6285433fe4b628. First-failure logs and both subsequent invocations remain retained. This closes only LM-2's literal metadata/credential requirements. It does not establish cold-start reliability, local coding compatibility, offline privacy, Windows/Linux native-store qualification, human accessibility, product activation or release/notarization. Parent #376 and the downstream issues remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions