diff --git a/.github/workflows/pr-build.yml b/.github/workflows/pr-build.yml index 7ccde260c2..8cb5655e18 100644 --- a/.github/workflows/pr-build.yml +++ b/.github/workflows/pr-build.yml @@ -472,6 +472,9 @@ jobs: packages/ui/src/lib/native/browser.test.ts packages/ui/src/lib/runtime-env.test.ts packages/ui/src/lib/session-transcript-lru.test.ts + packages/ui/src/lib/session-transcript-measurement.test.ts + packages/ui/src/lib/markdown-highlight-schedule.test.ts + packages/ui/src/lib/frame-batch-schedule.test.ts packages/ui/src/lib/server-meta.test.ts packages/ui/src/lib/theme-scheme.test.ts packages/ui/src/lib/trailing-resync.test.ts @@ -588,10 +591,14 @@ jobs: packages/ui/src/components/tool-call/diff-payload.test.ts packages/ui/src/components/tool-call/renderers/edit.test.ts packages/ui/src/components/tool-call/renderers/task-title.test.ts + packages/ui/src/components/tool-call/renderers/subagent-report.test.ts + packages/ui/src/components/tool-call/renderers/execute-data.test.ts + packages/ui/src/components/tool-call/renderers/bash-data.test.ts packages/ui/src/components/prompt-input/usePromptState.test.ts packages/ui/src/components/prompt-input/backend-history.test.ts packages/ui/src/components/session/provider-usage-panel.test.ts packages/ui/src/lib/hooks/use-active-session-message-load.test.ts + packages/ui/src/lib/assistant-meta.test.ts packages/ui/src/lib/sdk-manager.test.ts packages/ui/src/lib/tool-content.test.ts packages/ui/src/lib/background-read-queue.test.ts @@ -638,6 +645,7 @@ jobs: packages/ui/src/stores/opencode-data-idle.test.ts packages/ui/src/stores/opencode-projection-frame.test.ts packages/ui/src/stores/opencode-data-settlement.test.ts + packages/ui/src/stores/opencode-data-round-boundary.test.ts packages/ui/src/stores/opencode-data-reconnect.test.ts packages/ui/src/stores/opencode-data-trailing-read.test.ts packages/ui/src/stores/opencode-data-read-merge.test.ts @@ -650,8 +658,7 @@ jobs: packages/ui/src/lib/settings/behavior-registry.test.ts packages/ui/src/components/instance/shell/right-panel/core-plugin.test.ts packages/ui/src/components/instance/shell/right-panel/registry.test.ts - packages/ui/src/components/instance/shell/right-panel/integration-sections.test.ts - packages/ui/src/components/integration-section-state.test.ts + packages/ui/src/lib/integration-row-state.test.ts packages/ui/src/lib/i18n/messages/integrations-locales.test.ts packages/ui/src/stores/message-v2/empty-content.test.ts packages/ui/src/stores/permission-lifecycle.test.ts @@ -686,6 +693,7 @@ jobs: packages/ui/src/stores/worktrees-delete.test.ts packages/ui/src/stores/project-names.test.ts packages/ui/src/stores/temporary-instances.test.ts + packages/ui/src/stores/closed-workspace-drafts.test.ts - name: Test server run: node --import tsx --test "packages/server/src/**/*.test.ts" diff --git a/.opencode/skills/codenomad-architecture-guide/SKILL.md b/.opencode/skills/codenomad-architecture-guide/SKILL.md index afd950a4cc..cca4410fce 100644 --- a/.opencode/skills/codenomad-architecture-guide/SKILL.md +++ b/.opencode/skills/codenomad-architecture-guide/SKILL.md @@ -17,9 +17,9 @@ description: | ## Native OpenCode V2 Baseline -- Runtime requirements live in `opencode/runtime-support.ts`: OpenCode 2.2.3 is the minimum, required by the `experimental_image_generate` image tool contract (upstream #60258) that the Images gallery, Design agent and Images settings consume; it also provides Code Mode's JavaScript job ordering (`scripts/test-codemode-jobs-native.mjs`) and the `native`/`metadata.keepID` replay contract consumed by the pinned client reducer; 2.2.7 is the recommendation. Each blocking requirement needs demonstrated API/behavior evidence; distinguish technically incompatible, recommended/tested and unverified versions. Shared-daemon restart is explicit and uses the native-parent launch bridge. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the version boundaries and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for setup, installation and admission. +- Runtime requirements live in `opencode/runtime-support.ts`: OpenCode 2.3.0 is the minimum and the recommendation, required by the background subagent report contract (every subagent call returns at once and the child reports through synthetic `` messages) and by the `experimental_image_generate` image tool contract (upstream #60258) that the Images gallery, Design agent and Images settings consume; it also provides Code Mode's JavaScript job ordering (`scripts/test-codemode-jobs-native.mjs`) and the `native`/`metadata.keepID` replay contract consumed by the pinned client reducer. Each blocking requirement needs demonstrated API/behavior evidence; distinguish technically incompatible, recommended/tested and unverified versions. Shared-daemon restart is explicit and uses the native-parent launch bridge. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the version boundaries and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for setup, installation and admission. -- Server and UI pin the official `@opencode/client@2.2.3` together; native plugins pin `@opencode/plugin@2.2.3` for authoring and use `packages/server/scripts/native-plugin-build.mjs` to keep Effect/public SDK modules external. The daemon supplies their runtime instances. The canonical server-info client is `server.info()`, adapted to the authenticated discovered route. Review official V2 docs, installed declarations, generated wire paths and native integration tests when upgrading. Never infer a minimum from the latest publication or dependency pin alone. Update `dev-docs/OPENCODE_COMPATIBILITY.md` in place and retain detailed evidence in PR/CI logs. The runtime CLI is managed independently. +- Server and UI pin the official `@opencode/client@2.3.0` together; native plugins pin `@opencode/plugin@2.3.0` for authoring and use `packages/server/scripts/native-plugin-build.mjs` to keep Effect/public SDK modules external. The daemon supplies their runtime instances. The canonical server-info client is `server.info()`, adapted to the authenticated discovered route. Review official V2 docs, installed declarations, generated wire paths and native integration tests when upgrading. Never infer a minimum from the latest publication or dependency pin alone. Update `dev-docs/OPENCODE_COMPATIBILITY.md` in place and retain detailed evidence in PR/CI logs. The runtime CLI is managed independently. - Do not use `@opencode-ai/sdk`, `@opencode-ai/sdk/v2/client`, or `createOpencodeClient()`; follow installed `@opencode/client` declarations. - Never add general plugin extension points. The narrow native integrations are the bundled `codenomad.automation` plugin, project-local native session coordination (`codenomad.missions`) and the bundled session-pruning RPC; see `dev-docs/BROWSER_AUTOMATION.md`, `dev-docs/MISSIONS.md` and `dev-docs/SESSION_PRUNING_RPC.md`. All automation tools follow backend presence, sharing the authenticated native transport and execution-time session/window fences. - The server uses the selected host or WSL CLI's official `service status`, `service start`, and `service get password` lifecycle to connect to one externally owned global OpenCode daemon. It owns no private port/database/registration/PID and never stops the daemon on backend shutdown. WSL requires Windows localhost forwarding and uses no cross-namespace PID operations. diff --git a/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md b/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md index 83c6933934..1a39fefc3e 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md +++ b/.opencode/skills/codenomad-architecture-guide/references/architecture-overview.md @@ -20,7 +20,7 @@ Client-state V3 is a per-window envelope over the V2 content-addressed partition | Owner | Responsibilities | Main paths | |---|---|---| -| OpenCode V2 | Sessions, messages, permissions, Forms, files, session Shell/instructions, background Shells, interactive PTYs | pinned `@opencode/client@2.2.3` contract across server and UI; host-owned native plugin runtime | +| OpenCode V2 | Sessions, messages, permissions, Forms, files, session Shell/instructions, background Shells, interactive PTYs | pinned `@opencode/client@2.3.0` contract across server and UI; host-owned native plugin runtime | | CodeNomad server | Shared service lifecycle, locations, proxy authorization, Git mutations, Yolo, auth, storage, speech, SSE multiplexing, desktop automation bridge | `packages/server/src/` | | CodeNomad UI | Generated Promise clients, state reconciliation, interaction and rendering | `packages/ui/src/` | | Desktop hosts | Start CodeNomad and provide native OS integration | `packages/electron-app/`, `packages/tauri-app/` | diff --git a/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md b/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md index a2d8511ae2..47f55c8e3a 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md +++ b/.opencode/skills/codenomad-architecture-guide/references/sdk-api-reference.md @@ -2,9 +2,9 @@ ## Package -CodeNomad server and UI pin `@opencode/client@2.2.3`. The runtime CLI is managed independently; startup validates authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404 with the same endpoint, credentials and deadline. Each response has its own validated schema and a 64 KiB bound. The shared transport forwards canonical `server.info()` unchanged. Review official V2 docs, installed declarations, generated routes and native regression tests together when upgrading. +CodeNomad server and UI pin `@opencode/client@2.3.0`. The runtime CLI is managed independently; startup validates authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404 with the same endpoint, credentials and deadline. Each response has its own validated schema and a 64 KiB bound. The shared transport forwards canonical `server.info()` unchanged. Review official V2 docs, installed declarations, generated routes and native regression tests together when upgrading. -Runtime requirements live in `packages/server/src/opencode/runtime-support.ts`: minimum 2.2.3 (the `experimental_image_generate` image tool contract, Code Mode JavaScript job ordering and the `native`/`metadata.keepID` replay contract), with the recommendation (2.2.7) tracked separately. Native builds share the daemon's Effect/public SDK instead of bundling a second runtime. The shared connection binds authenticated runtime identity, the canonical client and forwarding transport. Admission precedes functional requests/plugin provisioning; unlisted custom/prerelease/future labels require authenticated bounded API recognition. Never add operation-specific retry fallbacks. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the version boundaries and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for admission. +Runtime requirements live in `packages/server/src/opencode/runtime-support.ts`: minimum 2.3.0 (the background subagent report contract, the `experimental_image_generate` image tool contract, Code Mode JavaScript job ordering and the `native`/`metadata.keepID` replay contract), with the recommendation (also 2.3.0) tracked separately. Native builds share the daemon's Effect/public SDK instead of bundling a second runtime. The shared connection binds authenticated runtime identity, the canonical client and forwarding transport. Admission precedes functional requests/plugin provisioning; unlisted custom/prerelease/future labels require authenticated bounded API recognition. Never add operation-specific retry fallbacks. See `dev-docs/OPENCODE_COMPATIBILITY.md` for the version boundaries and `dev-docs/OPENCODE_RUNTIME_SETUP.md` for admission. The Promise client preserves the full `baseUrl` path prefix. Forward its generated URL unchanged through `createInstanceFetch`; remove the proxy prefix only when classifying reads for scheduling. Declared API errors are `Error` instances retaining their native `_tag`/data fields. Client errors retain structured `reason`/`cause`, and their `message` may add status, content type or cause detail: classify by structured fields, never exact message text. diff --git a/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md b/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md index 17925e6244..24fee3cdd2 100644 --- a/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md +++ b/.opencode/skills/codenomad-architecture-guide/references/sdk-critical-behaviors.md @@ -2,12 +2,12 @@ ## Contract -- Server and UI pin `@opencode/client@2.2.3`. Manage the runtime CLI independently: startup checks authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404. All probes share the endpoint, credentials, 64 KiB response bound and absolute deadline; authentication, transport and malformed response failures end discovery without fallback. The shared transport forwards canonical `server.info()` unchanged. Review documentation, installed declarations and proxy/API parity whenever the client contract changes. +- Server and UI pin `@opencode/client@2.3.0`. Manage the runtime CLI independently: startup checks authenticated loopback `/api/info`, then (only to identify an outdated daemon) `/api/status`, then `/api/health`, advancing only on HTTP 404. All probes share the endpoint, credentials, 64 KiB response bound and absolute deadline; authentication, transport and malformed response failures end discovery without fallback. The shared transport forwards canonical `server.info()` unchanged. Review documentation, installed declarations and proxy/API parity whenever the client contract changes. - The package root is the generated zero-Effect Promise client. Use installed declarations; never follow `@opencode-ai/sdk` examples. - Native routes are `/api/*`; CodeNomad exposes them only through the authorized `/workspaces/:id/instance` proxy. - That proxy is an explicit method/path allowlist: expose each new upstream API only after review. - Proxy authorization and forwarding share one acquired connection. A stale generation must be rejected at actual HTTP dispatch, including after asynchronous body preparation; late streams cannot invalidate a replacement connection. -- The technical minimum is 2.2.3 for the `experimental_image_generate` image tool contract (upstream #60258: tool, permission action, job type and notice `metadata.source` share that name; on unless `experimental.image_generate` is `false`), alongside Code Mode's JavaScript job ordering and the `native` replay and `metadata.keepID` compaction shapes consumed by the pinned client reducer; the recommendation, 2.2.7, is a separate constant. Plugins use host-owned Effect/public SDK modules through the shared native build settings. Unknown version labels, prereleases and future majors undergo bounded authenticated API recognition, including session environment support. Native `session.inbox.enqueued` has its own shape: its timestamp lives in event metadata, unlike an HTTP inbox record. +- The technical minimum is 2.3.0 for the background subagent report contract (calls return at once; children report through synthetic `` messages) and the `experimental_image_generate` image tool contract (upstream #60258: tool, permission action, job type and notice `metadata.source` share that name; on unless `experimental.image_generate` is `false`), alongside Code Mode's JavaScript job ordering and the `native` replay and `metadata.keepID` compaction shapes consumed by the pinned client reducer; the recommendation, also 2.3.0, is a separate constant. Plugins use host-owned Effect/public SDK modules through the shared native build settings. Unknown version labels, prereleases and future majors undergo bounded authenticated API recognition, including session environment support. Native `session.inbox.enqueued` has its own shape: its timestamp lives in event metadata, unlike an HTTP inbox record. - Never retry a write using another contract after a 400/404/transport failure. Keep the setup/recovery path distinct from functional transport and never replay prompts. ## Location Is Authority diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 58ed18714e..267eaf43cc 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -114,7 +114,7 @@ Then open a pull request on GitHub targeting the `dev` branch. ### OpenCode V2 Boundaries -- Server and UI pin `@opencode/client@2.2.3`; native plugins pin `@opencode/plugin@2.2.3` for authoring but resolve Effect and the public SDK from the daemon at runtime. Upgrade pins together with the lockfile and isolated native validation. The runtime CLI is managed independently; its demonstrated minimum and recommended/tested versions remain separate constants in `packages/server/src/opencode/runtime-support.ts` (minimum 2.2.3 for the `experimental_image_generate` image tool contract of upstream #60258, consumed by the Images gallery, Design agent and Images settings; recommended 2.2.5). A build pin alone is never a runtime requirement, and unfamiliar newer/custom labels retain authenticated contract recognition. Review current OpenCode documentation, installed declarations, and proxy/API parity whenever the client contract changes. +- Server and UI pin `@opencode/client@2.3.0`; native plugins pin `@opencode/plugin@2.3.0` for authoring but resolve Effect and the public SDK from the daemon at runtime. Upgrade pins together with the lockfile and isolated native validation. The runtime CLI is managed independently; its demonstrated minimum and recommended/tested versions remain separate constants in `packages/server/src/opencode/runtime-support.ts` (minimum 2.3.0 for the background subagent report contract and the `experimental_image_generate` image tool contract of upstream #60258, consumed by the subagent cards, Missions, the Images gallery, Design agent and Images settings; recommended 2.3.0). A build pin alone is never a runtime requirement, and unfamiliar newer/custom labels retain authenticated contract recognition. Review current OpenCode documentation, installed declarations, and proxy/API parity whenever the client contract changes. - Upgrade references: [OpenCode V2 changelog](https://opencode.ai/changelog) (GitHub Releases list V1), the exact release tags (`vX.Y.Z`) or published npm packages for source/declaration deltas, [OpenCode V2 documentation](https://opencode.ai/v2/docs/), and `node_modules/@opencode/client/dist/promise/`. - `packages/server/src/workspaces/opencode-service.ts` uses the selected host or WSL CLI's official `service status`, `service start`, and `service get password` lifecycle to connect to one externally owned global daemon. CodeNomad owns no private port, database, registration, or daemon PID and never stops the daemon on backend shutdown. - WSL requires Windows localhost forwarding and runs the Linux CLI lifecycle inside the distribution; never inspect or signal Linux PIDs from Windows. diff --git a/README.md b/README.md index 1449202ffb..6b9cf7d23d 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ npx @neuralnomads/codenomad-dev --password "your-password" --launch ## OpenCode V2 and upgrading from 0.19.x -CodeNomad **1.0.0 requires OpenCode V2**: **2.2.3 minimum, 2.2.5 recommended**; the minimum provides the image generation tool used by the Images settings and the Design extension. OpenCode V1 and the former V2 beta protocol are not supported. The current requirements are maintained in [`runtime-support.ts`](packages/server/src/opencode/runtime-support.ts). +CodeNomad **requires OpenCode V2 2.3.0 or later** (also the recommended version); it provides the background subagent reports shown in subagent cards and used by Missions, and the image generation tool used by the Images settings and the Design extension. OpenCode V1 and the former V2 beta protocol are not supported. The current requirements are maintained in [`runtime-support.ts`](packages/server/src/opencode/runtime-support.ts). - **One shared OpenCode service** owns sessions and messages. Closing a CodeNomad tab, window, or backend leaves that service running. Desktop tabs, drafts, and layout are restored separately for each window. - **Use an existing CLI or install from CodeNomad.** Executables on `PATH` are preferred; the setup screen also supports a selected executable and a shared user npm installation. The former private CodeNomad OpenCode installation is no longer used. @@ -166,7 +166,7 @@ Add SideCar as: ## Requirements -- **[OpenCode V2](https://opencode.ai/v2/docs/)** — 2.2.3 minimum and 2.2.5 recommended for CodeNomad 1.0.0. Install/select it through desktop setup or provide a compatible CLI on the server host. +- **[OpenCode V2](https://opencode.ai/v2/docs/)** — 2.3.0 minimum and recommended. Install/select it through desktop setup or provide a compatible CLI on the server host. - **[Git](https://git-scm.com/downloads)** — a prerequisite for full functionality (repository identity, Git operations and worktrees). Git must be executable in the CodeNomad backend's `PATH`; it is not bundled with the desktop installers. - **Node.js and npm** — required for the standalone npm server and source builds; desktop releases include their own (Electron's integrated Node or Tauri's bundled Node, with npm). Use **Node.js 24 LTS**; development and release builds use the version in [`.node-version`](.node-version). diff --git a/dev-docs/BROWSER_TESTING.md b/dev-docs/BROWSER_TESTING.md index 1d2e658f60..f7d519dc78 100644 --- a/dev-docs/BROWSER_TESTING.md +++ b/dev-docs/BROWSER_TESTING.md @@ -85,6 +85,10 @@ admitted Location before their first RPC, and surface failed setup immediately. ## Agent conventions - History keyboard scenarios await publication of both exact store keys; a controller-held remote response verifies the absence of premature gestures and the actual keydown recipient. +- Mermaid initialization-deadline checks use the file preview's single renderer + consumer and await the held Tiny module's evaluation before checking late + iframe creation. Markdown's deferred highlight pass can remount a fence and + admit a separate initialization attempt; fence rendering has its own coverage. - Fixture shutdown tracks Vite 7 optimizer disposal and pending requests across every server environment before deleting its owned cache. Qualify the optimized-load hook and native cleanup acknowledgements together when changing Vite. - A new browser test either borrows via `borrowFixture({ name, routes })` or joins `fixture-exemptions.ts` with a reason that matches reality (the diff --git a/dev-docs/CACHE_REFRESH_CONVENTIONS.md b/dev-docs/CACHE_REFRESH_CONVENTIONS.md index 148b9b2cda..da408e0799 100644 --- a/dev-docs/CACHE_REFRESH_CONVENTIONS.md +++ b/dev-docs/CACHE_REFRESH_CONVENTIONS.md @@ -53,7 +53,7 @@ content before promoting it, and retain the last good display on expiry. | Providers/models | Retained signals; shared in-flight catalogue load; dirty-bit trailing refresh; instance, location and request-generation checks. `fetchProviders` itself reuses only in-flight loads. | `packages/ui/src/stores/session-api.ts` | | Provider Usage | Panel-local snapshot; same-location `provider.updated` revalidates in place with one in-flight read and coalesced trailing demand. Window-label keys preserve quota DOM across responses. Duplicate transport statuses and instance/status/native-generation snapshots are no-ops. A changed native generation still fences quotas even if the disconnect was missed. Credential/integration/config events, native `server.connected`, real connection transitions and source changes clear the snapshot immediately and fence old responses/trailing demand. Failures revoke quotas, since the account may have changed. Only a visible panel reads, and quotas stay panel-local. | `components/session/provider-usage-panel.tsx`, `provider-usage-state.ts` | | Session goal | Per instance/session snapshot of the shown session's `/goal`. The goal line's demand (Status shown) reads through the secondary budget: one read plus one trailing follow-up. `rpc.opencode.goal.changed` publishes at once and fences replies requested before it (per-session version); an unreadable change reads again. Plugin activation (`plugin.updated`) and reconnects (`server.connected`, connected status, stream open) coalesce reads of demanded sessions; the line's commands read their outcome. A failed read keeps the last goal; deletion and workspace stop drop it. | `stores/session-goal-store.ts`, `session-goal.ts` | -| Integration binding | Demand-only authority for the shown instance/Location/session/integration, shared across Status sections and their picker through the secondary budget. Invalidations immediately publish `unknown` and fence older replies; events coalesce over 300 ms with one trailing follow-up. Reconnect/open reconcile demand, disconnect revokes authority, and read failures publish `unknown`. Last-demand release aborts and drops state. Every admitted attachment mutation invalidates and rereads its captured target in `finally` while demanded. | `stores/integration-bindings-store.ts`, `integrations.ts` | +| Integration binding | Demand-only authority for the shown instance/Location/session/integration, shared by the Plugins rows that show it through the secondary budget. Invalidations immediately publish `unknown` and fence older replies; events coalesce over 300 ms with one trailing follow-up. Reconnect/open reconcile demand, disconnect revokes authority, and read failures publish `unknown`. Last-demand release aborts and drops state. Every admitted attach or detach invalidates and rereads its captured target in `finally` while demanded. | `stores/integration-bindings-store.ts`, `integrations.ts` | | Stats | Backend-owned `state.ui.serviceUsage`; rules in [SETTINGS.md](SETTINGS.md), restoration below. Reads follow explicit demand, terminal hints (shared five-second activity cooldown), reconnect and visibility; never poll. Hiding/disposal fences in-flight publication. | server `opencode/service-usage-cache.ts`, `service-usage.ts`; UI `settings/usage-settings-section.tsx` | | Session model selection | Native selection events invalidate the displayed selection and never overwrite it, because SSE echoes can lag successful HTTP writes. Coalesced authoritative reads share the session admission queue with prompts and explicit selections; client/generation and captured-selection checks fence late responses. Catalog merges preserve pending optimistic choices; successful writes publish a fresh model object so pre-confirmation snapshots lose authority. Read failures retain display state until the next event or reconnect refresh. | `stores/session-model-reconciliation.ts`, `stores/session-action-queue.ts`, `stores/session-generation-recovery.ts` | | OpenCode setup | Shared in-flight status read plus coalesced trailing refresh for focus/visibility/reconnect demand. Executable changes and explicit actions fence old responses. Failed reads retain version/path diagnostics but revoke the connected claim and stale reload/restart controls; Continue checks again before retrying the pending workspace. Activation requires a successful pre-action status read. | UI `stores/opencode-setup.ts`, `components/settings/opencode-setup-panel.tsx` | diff --git a/dev-docs/COMPOSER.md b/dev-docs/COMPOSER.md index cbae54cf42..d33dc834ac 100644 --- a/dev-docs/COMPOSER.md +++ b/dev-docs/COMPOSER.md @@ -8,10 +8,12 @@ The prompt composer: context selectors, height, focus after send, alternate deli - Default model resolution retains configured agent models, saved agent choices and recent choices while the instance's provider catalog is absent. Catalog absence is loading state; native creation and prompt dispatch keep the explicit model identity. Once published, the catalog supplies the existing availability checks. Regression: `stores/session-default-model.test.ts`. +- Draft and attachment hydration has one rule set, `hydrateWorkspacePromptState` (`stores/app-session-prompt-hydration.ts`): only existing sessions or the new-conversation draft, never over a session the user typed in, cleared or sent from (draft/attachment authority). Startup restoration and the closed-tab drafts of [Projects](PROJECTS.md) both go through it; add no other hydration path. - The composer reserves `/btw` for native `session.generate`, outside ordinary prompt/command submission. Its ephemeral question/answer window uses `DismissibleWindow` and `styles/components/session-aside.css`; cancellation and inactive/session transitions fence late results without interrupting the main session. - Keep agent, model and thinking controls in the composer footer via `PromptContextControls`, on one row with the actions on desktop and touch (truncate selector labels, never wrap the footer); adapt it with the named `prompt-composer` container rather than viewport-only breakpoints. Dense conversation toolbar/footer controls and the session list header actions use `--touch-target-size-compact` (the latter must fit four actions plus the panel-toggle reserve in the 220 px minimum sidebar); timeline markers use the compact control height rather than the global touch target. Toolbar touch spacing lives in `styles/panels/session-toolbar-touch.css`. - Composer height limits depend only on the visible conversation height: minimum 8% (44 px floor), maximum 60% (never below that minimum). `prompt-input/usePromptViewport.ts` observes the conversation and its intersection with `visualViewport`, including keyboard resize/pan. Store manually chosen heights as proportions so the field itself follows viewport changes; saved pixel heights convert to a proportion on the first valid measurement. Viewport-driven changes never overwrite the saved proportion; pointer and keyboard resize controls share the same limits and long drafts remain scrollable. - On desktop a send moves focus to the conversation stream for keyboard reading (arrows, paging, Space); a printable character typed there resumes the composer with that character (`prompt-input/type-to-focus.ts`), while fields, controls, IME composition and plain-key shortcuts keep their keys. Touch-only devices keep the keyboard closed. Do not add delayed refocus timers or a preference for this. +- Prompt-history recall places the caret at the end and focuses its textarea synchronously with the selection, preserving subsequent focus and typing in another composer. Covered by `tests/browser/composer-history-focus.test.ts`. - The composer's More actions menu offers the other follow-up delivery than Enter (Queue message when Enter steers, Steer now when Enter queues), enabled only in normal mode while the session runs and a draft can be sent; it reuses the shortcut's delivery resolution and its tooltip shows the `prompt-alternate-send` shortcuts: Alt+Enter plus Mod+Shift+Enter by default, except on macOS where Option+Return is the native line break and only Cmd+Shift+Return sends. Pickers ignore any modified Enter. Covered by `tests/browser/composer-alternate-send.test.ts` and `composer-picker-enter.test.ts`. - The same menu offers Previous/Next User Message through `requestUserMessageJump`, with the configured `user-message-prev`/`-next` shortcuts in their tooltips. These transcript-navigation actions retain the draft, are separate from prompt-history recall and require an active, existing session. Menu entries capture their owning instance/session before dispatch. Covered by `tests/browser/history-navigation.test.ts`. - Composer overlays show attachment counts, shell-mode state and transient stop confirmation only; keep the textarea's semantic description and transient status announcement. Do not add a keyboard-shortcut strip or help footer. Keep overlay styling in `styles/components/prompt-help.css`, without changing field height limits or adding a footer row. diff --git a/dev-docs/MISSIONS.md b/dev-docs/MISSIONS.md index c4f5479ee6..06ac109143 100644 --- a/dev-docs/MISSIONS.md +++ b/dev-docs/MISSIONS.md @@ -478,7 +478,7 @@ Scheduling. Agents and models uses the shared Settings disclosure with an inline requested-profile summary and Agent / Model / Thinking columns. Its fold state survives editor drafts; catalog demand follows its visibility. Options and Scheduling stay open. Notes begins at one line and grows with its content. Blocking profile -errors remain beside the disclosure; scheduling activation is confirmed at Play. +errors remain beside the disclosure; scheduling activation is prepared at Play. Objective, Title and Notes share the instructions group. The footer names Save configuration with a text button; the Configuration picker uses the bookmark glyph. Catalog reads use the panel's existing read indicator and preserve form geometry. @@ -593,12 +593,19 @@ last capability display during same-owner revalidation, so a passive refresh preserves an in-flight pointer click; control dispatch rereads capability. `MissionActionBar` retains its primary glyph for an unchanged action key, preserving the native pointer target while a fresh action object updates its other fields. -Play and Resume use informed native activation. Run now requires an enabled +Play and Resume automatically prepare project-only native activation when a ready +receipt is missing. An already enabled Location receives a zero-target ready proof +without configuration writes. Run now requires an enabled effective native setting, with an explicit disabled explanation and a fresh capability check before reservation. Its click preserves settings activation. -First native activation -asks for confirmation with the exact configuration paths; an uncertain activation -keeps Play unsent. A direct positive activation acknowledgement may continue the +Explicit OFF exposes a scheduling-settings action only for a server-openable configuration +ID; the responsible layer/path or environment explanation stays behind a keyboard-focusable +information tip. The existing configuration editor selects that exact catalogued file. +The requested action alone shows a full-opacity 14px loading glyph and `aria-busy` +during its bounded HTTP requests, with one persistent external status announcement; +confirmation dialogs and uncertain or confirmed-publication waits keep their ordinary glyphs. +Reduced motion uses the shared animation limit. An uncertain activation keeps Play +unsent and exposes the original receipt read. A direct positive activation acknowledgement may continue the same user intention under its original view fences. Read-only recovery of activation retains the publication barrier and leaves the next Play explicit. Never replay an action or continue Play automatically from recovered activation or display publication. @@ -1151,10 +1158,12 @@ the next native `experimental` object (`opencode/experimental-layers.ts`) belong the Global write target and equals its fresh document, since native entries lag behind writes and normalize what they load; otherwise the object stays. The snapshot flags such an object (`emptyExperimental`) so Inherit can repair it. -The shared two-key editor +The shared experimental editor (`opencode/native-experimental-settings.ts`) materializes inherited `schedules:true` when setting a depth would hide that activation, preserves an -explicit local false and depth zero, and copies only these two known keys. +explicit local false and depth zero. Creating a block for scheduling copies every +effective experimental option from the target's lower-priority whole block; +existing blocks retain their own options. A remaining schedules block selects the native depth default unless it also holds a depth. Native settings refuse simultaneous JSON/JSONC files in one layer. The schedule @@ -1387,7 +1396,8 @@ answers mutations with 405 and writes `browser-report.json` to the absolute - Journal editor reconciliation reads the original history request and exact text independently of the task window. Task pages preserve document and cleanup metadata; missing rows require the named display read their reader needs. Current daily/native-scheduled readers acquire their source before bounded task/report windows. The document RPC schema carries the dormant-journal marker and first-Play input digest with the projected summary. - The open create/edit/delete editor lives in window memory per panel scope (`stores/mission-editor-state.ts`), never in the native view layout. A hidden project keeps it mounted and usable on return; when the panel unmounts (another right-panel tab) an idle editor stashes its draft and reopens with it, while one with a request in flight or held closes and settles through its creation/recurrence hold. Editor activity follows the live view: `lib/mission-view-fence.ts` captures guard one operation from capture to completion, never a component's lifetime. - The Missions panel header (`components/mission-picker.tsx`, `styles/panels/mission-picker.css`) is two lines with one rule under the header, sticky at the top of the scrolling panel (`.mission-control-header`): a right-aligned toolbar ([+] create, then the panel's preferences gear and refresh), then the selection line. The selected item's icon toolbar mounts there through `MissionActionBar` and `MissionActionSlot`, followed by the always-shown **Filter missions** field; a narrow panel wraps the filter above the toolbar (`flex-wrap: wrap-reverse`). `MissionRows` uses the session list's row classes (`session-list-item`, `session-item-base`, `session-item-expander`, `session-item-select`, `session-item-title--clamp`): chevron, a flag (repeat icon for a schedule) coloured by its mark, then the title (`lib/mission-display.ts`); full state lives in the tooltip and screen-reader text. The filter always keeps the selected row. Selection uses `--list-item-highlight-*`; never use the input-field surface (`--surface-base`) as a panel or popup background. -- Flags and task icons share the session status palette (`mission-picker-model.ts`, `missionMark`/`scheduleMark`). A requested answer uses permission red; only a question the Mission can open reddens its flag. Observed work uses working yellow with pulse; interrupted and paused use warning orange. A completed Mission this window has not shown uses idle green (`markMissionsFinishedSeen` in `stores/mission-view-state.ts`), seeded from initial completion observations and marked seen only when shown in a focused window. Its per-project watermark on `finishSequence` retains unseen completions and individual acknowledgements within the layout bound; advancing that bound counts older completions as seen. A prepared Mission uses `--accent-primary` blue. Seen completed, failed, blocked and retired tasks stay neutral; active tasks pulse yellow, requested answers are red, unseen finished tasks are green, and tasks not started (assigned, ready, waiting on dependencies) are blue. Blue never reaches the chevron. Never reuse red for anything but a requested answer. Status words and icon shapes keep outcomes accessible independently of colour. +- Flags and task icons share the session status palette (`mission-picker-model.ts`, `missionMark`/`scheduleMark`). A requested answer uses permission red; only a question the Mission can open reddens its flag. Observed work uses working yellow with pulse; interrupted and paused use warning orange. A completed Mission this window has not shown uses idle green (`markMissionsFinishedSeen` in `stores/mission-view-state.ts`), seeded from initial completion observations and marked seen only when shown in a focused window. Its per-project watermark on `finishSequence` retains unseen completions and individual acknowledgements within the layout bound; advancing that bound counts older completions as seen. A prepared Mission uses the palette's `--accent-primary`. Seen completed, failed, blocked and retired tasks stay neutral; active tasks pulse yellow, requested answers are red, unseen finished tasks are green, and tasks not started (assigned, ready, waiting on dependencies) use the accent. Never apply the accent to the chevron or reuse red for anything but a requested answer. Status words and icon shapes keep outcomes accessible independently of colour. +- Daily and unified scheduled documents adapt to one pure schedule-mark projection. A confirmed future native wake uses the ordinary icon in opaque `--accent-primary` with a static 8×1px `--text-secondary` underline, three pixels below its 16px SVG in a shared 16×20px HTML cell. Prepared uses the accent icon alone; Pause uses `Pause`, interruption uses `AlertTriangle`, both warning orange. Native uncertainty, stale display evidence and unresolved controls use neutral **State unconfirmed**. Requests, interruption and uncertainty take priority over successful-history attention; Pause takes priority over a pending passage. The first loaded historical success starts seen. Later successful passages stay green until an explicit row selection in the active attentive window or **Mark as read** acknowledges the captured daily `passageID` or unified history `id`. Per-window/project/document-format/schedule layout state retains exact positive passage identities within the layout-value bound. Restored selection and newly arriving results preserve unread attention. Acknowledged success returns to confirmed waiting while armed, otherwise neutral; terminal Stop is neutral. Hover, focus, selection and reduced motion preserve the waiting underline. - Row actions live in the header's selection line (`components/mission-action-bar.tsx`, `mission-selected-actions.tsx`): Play/Pause (coordinator recovery for an interrupted Mission and resumption of a failed one), Stop, a schedule's Run now, the reader eye, Open conversation, delete and `ActionOverflowMenu`. Every action stays in place, disabled when inapplicable under its owner and H9 guards. Overflow order is request an update, interrupt now, Save configuration and edit; the trigger is disabled when all entries are disabled. Secondary actions, including schedule checks and the configuration name field, stay at the top of the selected detail only while present. Command announcements and recovery actions belong to the persistent header; progress and errors join the primary button's tooltip instead of adding a line under the row. Retrying an unconfirmed control from the header ⟳ first reads its exact status, then resends only its still-unconfirmed original request/revision from that explicit click. Stop confirms first. Delete automatically submits once using the shared `missionDeleteSessions` preference frozen into that request; a failed or unconfirmed deletion retains its consumed automatic-submit state, original retry identity, option and error in the editor draft across remounts. Only explicit Retry continues that deletion. Shared contextual-help actions retain the shared help glyph, keyboard access and localized destination; opening help preserves selection, reader and editor state. - The panel follows the session list. Its single selection is a Mission/schedule row or one task of that row's Mission/passage (`selectedTask` in `stores/mission-view-state.ts`); only the selected row or task is highlighted (`.session-item-active`, `aria-current`), and selecting a row clears the task. Only the chevron (`SessionExpander`) expands or collapses. A Mission with known `MissionSummary.taskCount` zero, or a read map without tasks, uses the session list's spacer; an absent count retains the chevron. Its context menu Mark as read acknowledges the row's unseen finished tasks and own unseen completion. `MissionRows` renders the selected detail once between its surrounding rows, preserving controls and retries through selection changes. Collapse hides that mounted detail; a selected Mission without tasks keeps its action-only detail visible. Expanded rows persist per project in `expanded`, bounded by `MAX_EXPANDED`; an unselected schedule's chevron selects and expands it, while an unselected one-time Mission's chevron expands its task preview without selecting it. Nothing is selected by default. Opening a conversation preserves the selected Mission/task. - The detail (`components/mission-tracking.tsx`, `styles/panels/mission-detail.css`) holds secondary actions such as the configuration name field and the task tree; prose belongs in the central reader or info tips. `components/mission-task-tree.tsx` is THE task view: one session-list row per task (`.session-list-item`, `.session-item-base.session-item-nested`, one level deep), a status icon then title. `mission-graph.tsx` draws only declared `blockedBy` dependencies, completed and retired included, from measured status icons; never infer native ancestry. Lanes start under the Mission row's chevron at a fixed step; `--mission-graph-extra` increases row indentation when necessary. Clicking a task selects it; a correlated red request also opens its question. `missionTaskRowState` supplies both task-row state and the Mission chevron's `data-child-activity` priority: input, active, unseen finished task. A finished task stays green until selection, its icon button (`lib/toggle-sweep.ts` supports sweeping), or Mark as read acknowledges it. `stores/mission-task-seen.ts` retains the per-project first-use boundary, per-Mission Mark as read watermark and individually seen task versions. diff --git a/dev-docs/MISSIONS_NATIVE_CONTRACTS.md b/dev-docs/MISSIONS_NATIVE_CONTRACTS.md index 621a2966e6..e7c67703cf 100644 --- a/dev-docs/MISSIONS_NATIVE_CONTRACTS.md +++ b/dev-docs/MISSIONS_NATIVE_CONTRACTS.md @@ -147,7 +147,7 @@ Exact request receipts remain point reads through `scheduleRead`. | --- | --- | --- | | `@opencode/client/service` | `discover({file})` returns Endpoint/undefined; `headers(endpoint)` builds authentication; public `Info` describes registration fields | Exact absolute registration, bounded non-secret id/pid/url/version projection, current PID/incarnation before dispatch and inside receiving RPC. Keep credentials in operation memory. For wake transport, forbid ensure/start/stop/terminate, CLI children, standalone and alternate namespaces. | | Client HTTP/RPC | `OpenCode.make(...).rpc(definition).method(input,{location,signal})` | Acquired authenticated connection, exact native directory and cancellation; preserve uncertainty after dispatch. | -| Schedule HTTP contract | `experimental.schedule.create/list/get/pause/resume/delete`, `{data:Info}`, session-filtered list, delete 204 | `opencode/native-schedule-capability.ts` recognizes the consumed request/response shapes read-only. Read `experimental.schedules` independently from the highest-priority whole native block. Never create probe schedules. | +| Schedule HTTP contract | `experimental.schedule.create/list/get/pause/resume/delete`, `{data:Info}`, session-filtered list, delete 204 | `opencode/native-schedule-capability.ts` recognizes the consumed request/response shapes read-only. The Location's `scheduleFlag` RPC reads native flag resolution independently. Never create probe schedules. | | Plugin Session facade | get/create/prompt/synthetic/interrupt/context | Prefer facade methods when they expose the required operation. Preserve exact session/message IDs and fixed profiles at admission. Use bounded point/page reads for source coverage. | | Session/AISDK hooks | prompt/context/title/compaction/language | Context admission requires the exact durable user message and schedule correlation. Title/compaction/language carry only local technical work. Treat metadata as correlation within service privileges. | | Native context message classification | Context message IDs select native carrier records | [Read bounds and authority](MISSIONS_NATIVE_SCHEDULE_TRANSPORT.md#context-read-authority-and-bounds). | @@ -169,6 +169,7 @@ documents without imposing a runtime version list. | Session message readers | messages({sessionID,limit,order,cursor:{id,direction}}) → array; message({sessionID,messageID}) → Info/undefined | Same adapter: ≤32 messages/source, ≤256 KiB native message, 16,384-character launch envelope; point-read anchor and each message, stable complete prefix, source placement/bytes rechecked after I/O. Deleted/moved/changed anchors block. | | Session active | `active` is an Effect returning a ReadonlySet | `native-passage-observation.ts`: actual Set, ≤4096 sessions. Treat activity as a process-local observation. Require correlated durable terminal evidence and complete family quiescence for restart settlement. Keep an old execution claim uncertain during asynchronous native recovery. | | `@opencode/Location` | directory/workspaceID/project{id,directory,canonical} | `native-service-adapter.ts`, `native-service-clock.ts`, recurrence readers: structural Location.Info fields, exact native/physical placement and current graph checks after I/O and before effects. | +| `@opencode/Flag`, `@opencode/Config` | `resolve(entries).schedules` → `{enabled:boolean,source:"env"|"config"|"default"}`; `entries()` → Effect of ordered documents/directories | `native-schedule-flag.ts`: receiving RPC/Location graph, checked methods/Effect, at most 256 entries, checked result and live Location/lifecycle before and after the read. `scheduleFlag` returns only effective state and provenance (`environment`, `experimental-block`, `all-flags`, `channel-default`). The calendar facade uses this same reader before carrier effects and retains `Schedule.enabled(sessionID)` for the carrier's own Location. Missing service or shape blocks admission. | | `@opencode/storage/Database` | db.$client.unsafe(sql,params).withoutTransform → Effect rows; db.transaction(callback,{behavior:"immediate"}) | `native-recurrence-storage.ts`, `native-passage-observation.ts`: current graph, actual SQL client/transaction, safe row types and synchronous query guard. Preserve the driver's transaction Context when composing effects. Asynchronous-only reads cannot implement the synchronous admission fence. | | KV/CAS SQL | kv(key,value,time_created,time_updated); plugin namespace is plugin ID encoded as padded UTF-16 hex | `native-recurrence-storage.ts`: exact project key/bytes/revision, immediate transaction, conditional update and readback. Publish invalidation after commit; an invalidation failure preserves the committed result. | | Family SQL | session_v2 placement/parent/time_suspended, session_inbox, session_message id/type/seq/content/idle | `native-passage-observation.ts`: family ≤4096, exact message/inbox presence and nonnegative counts. Anchor the original input in durable seq order and require a later terminal idle as the latest projection. Count failures only between that input and terminal, then recheck family, claims and requests. Missing anchor/terminal or any remaining claim keeps uncertainty. | @@ -409,14 +410,32 @@ remain covered by the separate scheduled-product qualification. `native-experimental-settings.ts` shares the depth/schedules JSONC reader and editor. Preserve explicit false/zero and local companions; materialize inherited -true schedules when writing a depth, and preserve depth from the target's own -lower-priority block only when creating an experimental block for schedules. -An existing block keeps its depth key or native default unchanged. Copy only -those two known keys. +true schedules when writing a depth. Creating an experimental block for schedules +copies every effective experimental option from the target's lower-priority whole +block. An existing block keeps its own options and native defaults. `PluginControls` owns connection/Location/deletion fences, byte expectations and the physical file lock. Duplicate keys, invalid parents and simultaneous JSON/ JSONC in one layer refuse settings edits. +Native flag precedence is environment overrides (a specific key before `all`), +the key in the highest-priority whole `experimental` block, then true from the +highest-priority document setting `experimental.all_flags`, then the daemon's +channel default. `all_flags:false` falls through to that default. The daemon's +Flag service supplies environment and channel decisions. +Activation refuses every discovered explicit `schedules:false`, including a +hidden lower layer, and a native environment OFF. An upper experimental block +masking the project target also refuses activation. `schedule-activation-refused` +responses identify the reason, provenance, layer, discovered path, `openable` and +`configFileID`. An editor action requires an openable ID with exact membership +in the existing global config-file inventory; environment refusals expose their +source through the information tip. + +An activation refusal before any document mutation, for an identity without an +existing intent, includes `notApplied: { requestID, expectedRevision }`. This exact +proof releases that local request for a fresh explicit Start after configuration +correction. A refusal after a document mutation attempt or for an existing intent +retains the original request and its explicit receipt recovery. + Native regression: `node --import tsx scripts/test-mission-experimental-settings-native.mjs `. It exercises real discovery/whole-block precedence/watcher acknowledgement and @@ -426,7 +445,16 @@ The product preparation endpoint is `/api/workspaces/:id/missions/:missionID/schedule-settings`: GET reads its document; POST accepts only `requestID` and `expectedDocumentRevision`. It holds the owned worktree admission, refreshes authority before every typed `documentActivation` -phase and composes the two-file executor with native document CAS. Readiness keeps +phase and composes the project-only executor with native document CAS. An already +enabled Location records a ready proof with zero targets and zero config writes. +The sole writable target is the owned Location's project configuration; global +configuration contributes discovery, refusal and exact editor targeting. +Existing ready proofs retain their original request/revision, authority and digests; +preparation revalidates them read-only. Incomplete persisted intentions containing +a global target observe exact already-attempted effects only; never write global +or unattempted targets during their reconciliation. An attempted effect without +matching proof keeps its original barrier. +Readiness requires the effective native flag in the acquired Location and keeps the Mission paused. Immediate objects refuse this path. A failed intent with no attempted write can be replaced only by a new explicit request at the fresh document revision; an attempted effect retains its original request fence. diff --git a/dev-docs/MISSIONS_RECURRING.md b/dev-docs/MISSIONS_RECURRING.md index beda533542..32981eccee 100644 --- a/dev-docs/MISSIONS_RECURRING.md +++ b/dev-docs/MISSIONS_RECURRING.md @@ -280,6 +280,20 @@ may continue the same user intention; recovered activation leaves Play explicit. Never replay a mutation or start Play from receipt recovery or display publication. List and detail also expose `observation`, `availableActions` and `blockReason`. +The shared list mark uses the current observation's temporal generation and positive +active principal/next-wake evidence for **Waiting for scheduled run**. Daily documents +use the native snapshot's positively observed running state and next date. A missing, +stale, blocked or unresolved observation keeps **State unconfirmed**. Successful-history +attention and exact passage acknowledgement follow the shared marks contract in +`MISSIONS.md` (Agent conventions): accent icon with a static neutral underline for +confirmed waiting, accent alone for prepared, orange Pause or warning triangle for +pause/interruption, yellow pulse during a passage and green for a new successful +passage awaiting review. Explicit attentive selection or **Mark as read** acknowledges +that exact passage and returns an armed schedule to waiting. The context menu captures +its passage identity when opened; a result arriving while it is open stays unread. +Unselected rows count requests from their live coordinator and loaded descendants; +the selected passage uses its authoritative request coverage. First-loaded history +starts read. Acknowledged finished schedules and terminal Stop use neutral. Their `technical` projection exposes only the recorded current/retiring carrier session and calendar identifiers, role, slot, temporal generation and pending cleanup. It derives these from the same document read, including attempted @@ -333,8 +347,19 @@ adapter, with zero model requests. `GET /api/workspaces/:id/missions/scheduled/capabilities` reads the acquired connection's consumed API contract, effective schedules flag and origin. Its -read-only activation plan exposes the target scopes/paths or a refusal category. -The native document preparation endpoint owns authenticated configuration writes. +read-only activation plan exposes the project target/path or a refusal category, +responsible layer and discovered path. Native `scheduleFlag` resolution supplies +the effective state and provenance. Environment OFF and every discovered explicit +document OFF refuse preparation, including an OFF hidden by a higher ON. +The native document preparation endpoint owns authenticated project-only +configuration writes; an already enabled Location receives a zero-target ready +proof. Existing ready proofs are retained and revalidated read-only. +Play/Resume perform this preparation automatically under the original view fences. +A structured refusal offers **Open scheduling settings** only for a server-openable +configuration ID; source/path and environment details use the focusable **i** tip. +The requested button shows loading and `aria-busy` during HTTP work, with a status +announcement. Uncertain activation keeps the exact receipt check available and +leaves the next Play explicit after recovery. Both display routes revalidate workspace, connection, physical checkout and request lifetime after asynchronous work. Missing methods or capabilities return an explicit unavailable response. UI reads use the shared secondary HTTP budget. @@ -675,6 +700,9 @@ Retain pending passage identity and observations rather than clearing live work. Desired running without a live native Job is displayed as **Interrupted** with an interruption reason. Service restart therefore leaves scheduling Interrupted. +An archived daily passage ending without a report keeps its history outcome; +a positively running daily Job with a future date shows **Waiting for scheduled run**. +Failed passages retain their interruption attention. Do not rearm from plugin load, a read, UI reopen or backend reconnect. Only explicit Resume may restore scheduling; pending work is reconciled first. An Interrupted schedule keeps its passage pending. Resume reconciles its original diff --git a/dev-docs/OPENCODE_COMPATIBILITY.md b/dev-docs/OPENCODE_COMPATIBILITY.md index f13fc1346d..2ffc669219 100644 --- a/dev-docs/OPENCODE_COMPATIBILITY.md +++ b/dev-docs/OPENCODE_COMPATIBILITY.md @@ -21,8 +21,18 @@ view; release notes are at [opencode.ai/changelog](https://opencode.ai/changelog (GitHub Releases cover V1 only). Keep results in the PR and CI logs, never as per-version sections here. -Minimum runtime **2.2.3**, recommended **2.2.7** (`runtime-support.ts`), with -**2.2.3** client/schema/plugin pins. The minimum carries the image tool contract of +Positive shared-service test fixtures declare `MINIMUM_OPENCODE_VERSION` when +serving the pinned client contract. Version-refusal scenarios supply their +explicit incompatible identity. + +Minimum and recommended runtime **2.3.0** (`runtime-support.ts`), with **2.3.0** +client/schema/plugin pins and the matching `effect` **4.1.0**. CodeNomad +qualifies only the 2.3 subagent contract: every subagent call returns at once +(`metadata.status: "running"`) and the child reports to its parent through +synthetic `` messages, one per idle period, tagged +`running` while background work remains (the subagent card in `TRANSCRIPT.md`, +`scripts/test-missions-native-trajectory.mjs`, +`scripts/test-subagent-nesting-native.mjs`). The minimum also carries the image tool contract of upstream [#60258](https://github.com/anomalyco/opencode/pull/60258), consumed by the Images gallery, the Design agent and skills and the Images settings: one name, `experimental_image_generate`, for the tool, its permission action, its job @@ -255,6 +265,11 @@ The fixed navigation method adaptation remains conditional on method absence. ## Agent conventions +Readiness ownership fixtures await complete request JSON before one-shot follower +reconciliation. Exclusive file creation exposes its name before the write settles. +Replacement fixtures hold backend ACK consumption until foreign bytes are installed; +overflow fixtures cancel explicitly after observing the refused complete plan. + The bundled `codenomad.memory` plugin exposes `codenomad_memory` with `list`, `read` (exact ID or title), `save` (title/type/text), and revision-conditional `delete`. It uses the native execution session as provenance and the shared diff --git a/dev-docs/OPENCODE_INTEGRATIONS.md b/dev-docs/OPENCODE_INTEGRATIONS.md index 567a276430..71de852861 100644 --- a/dev-docs/OPENCODE_INTEGRATIONS.md +++ b/dev-docs/OPENCODE_INTEGRATIONS.md @@ -95,7 +95,7 @@ it keeps its recognition ways, but neither those shared or foreign sources nor a (no `plugin` fact, `configuredSources` or version from them), and no RPC is called. `GET /api/workspaces/:id/integrations?directory=[&workspaceID=]` (`server/routes/integrations.ts`, -`IntegrationsReader`) answers every catalog entry for an owned Location, without the catalog's plugin ID, `rpc`, +`IntegrationsReader`) answers every catalog entry for an owned Location, without the catalog's `rpc`, `sources` and `package`. `docs` is present only when `isIntegrationDocsUrl` (`opencode/integrations/docs-url.ts`) accepts it: the raw canonical `https://github.com/NeuralNomadsAI/opencode-integrations/tree/main/integrations/` or `…/blob/main/integrations//plugin/README.md` of the same ID. Each entry carries the installation facts @@ -201,9 +201,8 @@ After an `attached` outcome, the session's `metadata["codenomad.integrationAttac `{ integration, label, attachedAt }`: catalog ID, offer's `label` for reattach matching and Unix milliseconds. The server reads the session afresh immediately before native `session.update`, whose whole metadata object replaces the stored object, retaining all unrelated keys from that read. Attach and detach serialize per session -within the backend. Both `detached` and `none` remove the hint. Q8 is a display hint for a confirmed reattach to a -matching integration and label; the plugin's live bindings retain authority. Concurrent writers in other clients -share native whole-object replacement semantics. +within the backend. Both `detached` and `none` remove the hint. The plugin's live bindings retain authority. Concurrent writers in other +clients share native whole-object replacement semantics. ### Confirmed source removal @@ -242,8 +241,8 @@ detected through `WSL_DISTRO_NAME` or the Microsoft kernel marker. Failure to es fails closed. A mirrored compatible application offer must never bypass this check. Installation is Location-scoped and works independently of sessions and offers. The installer acts on the OpenCode -machine, including a remote machine. Its outcome describes that request; application status and a separate explicit -attachment action establish application availability and conversation access. Never retry or replay an installation +machine, including a remote machine. Its outcome describes that request; application status establishes application availability, and the integration +attaches a conversation at its first use or through the row's chain button. Never retry or replay an installation request after an uncertain result: check the application, then require a fresh action and confirmation if needed. ## UI read model @@ -269,55 +268,70 @@ Locations resume on its own reconnect/open. An admitted binding mutation retains settlement; reconciliation requires its captured attachment to remain current. Revocation releases application-installation busy indicators immediately; an older completion can release only its own pending operation. -`right-panel/integration-status-module.tsx` registers a native Status section per unambiguous integration with -`plugin.declared` or `plugin.runtime` facts. Stable `integration:` IDs follow catalog order after Plugins, with -persisted hiding/order and keyboard Up/Down customization. Retained activation rules alone leave the entry in the -installation catalog. `createIntegrationContext` shares the active Location with Plugins and supplies a conversation -only when its Location matches. Sections retain their objects across display refreshes. - -`integration-section-state.ts` derives section and Conversation labels from installation, activation, host and -authoritative binding facts. Headers keep the state visible, with Documentation beside the information Popover; -the body contains Plugin (version, switches and row actions), Application/Conversation for native integrations, -or Connection for the other families. Expected-action changes or an attached conversation expand the section once; -user collapse persists until the expected-action key changes. Each Status tab owns one grouped polite live region. - -The section's Conversation line opens the trusted application picker. It initially focuses Cancel, names its captured -target conversation and the daemon machine, and enables explicit confirmation after 600 ms. Navigation discards the -captured target; reconnect and relevant native invalidations discard offers. Admitted action receipts remain readable -for their unchanged target across native echoes. WSL-unsupported status shows help in the information Popover. -Saved Q8 hints offer confirmed reattachment only for matching integration and label. Action receipts describe the -completed request. **Detach** sends one request directly from the section for the authoritative current binding. - -Plugins retains its ordinary rows with update/remove/refresh actions. Its Add menu opens **Add an integration…**: -the reviewed catalog's installable entries, family label, summary Popover, Documentation, scope and Install. Native -integrations lock scope to Global. Catalog availability and the last valid fetch date appear here. Installation uses -the shared guarded confirmation and `pluginSourcesStore.installIntegration`, preserving its pending/reconciliation -semantics. Activation and plugin package updates use ordinary native mutations without confirmation. -Cancelling attachment or application installation restores the captured visible, enabled opener while its -owning view, conversation and integration context remain current. Navigation, invalidation and view disposal revoke restoration. +Integrations are managed only from their row in **Status → Plugins** (`components/plugin-activation-controls.tsx`). +A row whose plugin ID or declared target correlates with an unambiguous catalog entry is that integration's single +row. `integrationDisplayPlugin` uses the writable `integrationPlugin` correlations or the projected `plugin.runtimeId` +of one exact native inventory entry. Inherited, virtual and runtime-only declarations retain their integration +display and native actions; source mutations keep their writable document/revision checks. + +- its `displayName` followed by its muted installed version (every row with a known package version shows it + right after the name, its buttons at the row's end); +- Global/Project switches in the accent colour of Yolo and the settings switches (`ACCENT_SWITCH_SX`, + `var(--accent-primary)`): `PluginActivationSwitch`'s `integration` flag replaces the green variant that plain + plugin and MCP rows keep. A native integration's Project switch is locked to Global; +- the name's native `title` (also the row's `aria-describedby` text) starts with **Integration: ** where a + plain plugin's starts with **Plugin: **; +- under the first line, one state line (`IntegrationStateLineView`, `components/integration-state-line.tsx`) chosen by + `integrationStateLine` (`lib/integration-row-state.ts`): the most important state only, truncated on one line with + its full text in its `title`. `info` states are muted text, `action` states an accent button (`--accent-primary`), + `warning` states `--status-warning`. A native integration, by priority: part `absent` → **Install in ** and + `outdated` → **Update ** (the existing installation confirmation; muted text without a fresh installable + status), `incompatible` → warning, attached → chain icon and document name (click detaches; title **Detach the + conversation**), application closed → ** closed**, no offer → **: no open document**, no conversation + of this Location → **No conversation displayed**, one compatible document → **Attach **, several or not + read yet → **Attach…** (the document choice menu). Unloaded integrations show **Not loaded**, **Failed to load**, + **Non-conforming**, **Not supported here** or **No answer**; editor MCP integrations **Server detected**/**Server not + found**, API integrations **Connected**/**Disconnected**. Runtime-only failed rows show the same unloaded states. + +The row's menu (`components/plugin-row-actions.tsx`) is labelled by the connection state (open document count, +application closed, unsupported machine, or the other families' server/connection state) and lists **Documentation** +(the catalog's reviewed page), **Install in application…**/**Update application…** for a fresh `host.action` or +**Reinstall in application…** otherwise, then the ordinary package check/update, removal per scope and refresh. A +native integration also attaches a conversation itself at its first use; both paths coexist. `createIntegrationBindingsStore` (`stores/integration-bindings-store.ts`) shares reads for the exact instance, -Location, session and native integration shown by the Status sections. The Conversation line keeps the safe binding -label in isolated text and distinguishes `none` from explicit `unknown` and uncertain outcomes. -Only a fresh `attached` binding offers Detach. Q8 supplies matching confirmed-reattach -suggestions. Binding reads carry only the session selector and receive only the projected state/label. - -The store uses the shared secondary HTTP budget. Relevant integration/plugin/configuration events and exact-session -updates, moves or deletions revoke authority immediately and coalesce reads over 300 ms, with one trailing follow-up. -Reconnect, native stream-open and renderer stream-open reconcile demanded bindings; disconnect revokes them. -Every read checks its demand identity and generation before publication. Errors publish `unknown`; releasing the last -demand aborts and drops its state. Attach and detach run once, then invalidate and reconcile their captured target -in `finally`, including uncertain outcomes, while navigation leaves reads scoped to the latest shown target. - -The integration section's Application line offers **Install in application…** or **Update application…** -for a fresh active native integration reporting -`host.action: "install" | "update"`. `components/integration-host-installation.ts` owns the trusted shared -confirmation: application name, integration package version and the OpenCode-machine warning, with Cancel initially -focused. The captured instance, Location, session-navigation identity, action, version and integration epoch fence -consent. Navigation, reconnects and relevant native invalidations cancel pending confirmation; dispatch rechecks the -captured identity. An admitted request runs once, and receipts use only the projected outcome or a localized fixed -error. Uncertain errors require checking the application before a fresh action. UI strings live in each locale's -`integrations.ts`, and public instructions in `docs/help//integrations.md#application-installation`. +Location, displayed session and native integration of each shown row (`components/integration-row-binding.ts`). +The row also reads the open documents (`GET …/hosts`) while it is shown with at least one offer, again after every +integration epoch or backend attachment change, to name them on the state line. Each read captures its attachment +and row lifetime; revocation clears the offers and fences late results. Attaching reads them afresh, attaches the shown document +when it is still the only compatible one (`integrationAttachChoice`) and otherwise opens the choice. +Binding reads carry only the session selector and receive only the projected state/label. The store uses the +shared secondary HTTP budget. Relevant integration/plugin/configuration events (`status_changed`, `hosts_changed`) +and exact-session updates, moves or deletions revoke authority immediately and coalesce reads over 300 ms, with one +trailing follow-up. Reconnect, native stream-open and renderer stream-open reconcile demanded bindings; disconnect +revokes them. Explicit Plugins header or row refresh reconciles only demanded bindings of the displayed +instance/Location/conversation. Errors publish `unknown`; releasing the last demand aborts and drops its state. +Attach and detach send one request for the displayed conversation, then invalidate and reconcile their captured +target in `finally`, including uncertain outcomes, which show a fixed error toast and are never replayed; `busy`, +`gone` and `refused` attach outcomes have their own message. +Attach intent captures the exact target and integration epoch. Navigation, deactivation, row disposal and native +invalidations/reconnect revoke its cancellable hosts read and document choices. Each choice retains its gesture's +target and offer; dispatch rechecks that intent, and only its own read may clear its busy state. + +`components/integration-host-installation.ts` owns the application part's trusted shared confirmation for a fresh +active native integration: `host.action` (`install`, `update`) or `reinstall` without one, the application open or +closed: application name, integration package +version and the OpenCode-machine warning, with Cancel initially focused. The captured instance, Location, +session-navigation identity, action, version and integration epoch fence consent. Navigation, reconnects and +relevant native invalidations cancel pending confirmation; dispatch rechecks the captured identity. An admitted +request runs once, and receipts use only the projected outcome or a localized fixed error. + +The Plugins Add menu opens **Add an integration…**: the reviewed catalog's installable entries, family label, +summary Popover, Documentation, scope and Install. Native integrations lock scope to Global. Catalog availability +and the last valid fetch date appear here. Installation uses the shared guarded confirmation and +`pluginSourcesStore.installIntegration`, preserving its pending/reconciliation semantics. Activation and plugin +package updates use ordinary native mutations without confirmation. UI strings live in each locale's +`integrations.ts`, and public instructions in `docs/help//integrations.md#integration-rows`. ## Test fixtures @@ -385,23 +399,19 @@ Commands: - `node --import tsx --test packages/server/src/server/__tests__/integration-request-logging.test.ts`: actual Fastify completion hooks and Pino capture at debug/trace, rejected/malformed paths, query/body values and keys, native error data, concurrent requests and error recovery, with positive ordinary-route diagnostics checks. -- `packages/ui/tests/browser/integration-attachment.test.ts`: real Solid entry points and native dispatcher with - all renderer logger namespaces enabled. Every console level's text and structured arguments, nested Error - messages/stacks and page errors are captured before navigation and sentinel-scanned through native teardown. - Document-owned synchronous copies travel with the original console arguments on one ordered CDP channel; - native retirement receipts and exact packet/context/copy reconciliation gate completion. Workers, OOPIFs, - related targets and serialization/association loss fail closed. The helper's native-format, delayed-delivery, - reload/close and negative controls live in `fixture-console.test.ts`; the real dispatcher post-drain control - retains the original deferred-handle failure assertion alongside the by-value capture. Adversarial - HTTP/JSON/transport failures exercise read, hosts, attach, detach, retry and late navigation. - Binding qualification covers external authority, Q8/receipt separation, unknown versus none, wide/narrow durable - labels with isolation/truncation/accessibility, strict projected-response bounds, moved sessions, late replies, - expiry/revocation hints and native/renderer disconnects with pending trailing work. - Installation qualification exercises the existing row's source association and fresh `host.action`, sessionless - visibility, Cancel-first shared confirmation with machine/package-version text, preconsent navigation/event fences, - all projected outcomes, unsupported WSL and uncertain errors without automatic replay. +- `packages/ui/tests/browser/integration-plugin-row.test.ts` (fixture `fixtures/integration-plugin-row.tsx`, HTTP + model `integration-plugin-row-model.ts`) renders the real right panel: one row per integration with its name, + version, accent switches equal to the Yolo accent and tooltip kind; the state line across `hosts_changed`/`status_changed`, + conversation changes and `unknown`; the version right after the name and the state line under it; every state's + text, tone and colour in light and dark (captures with `CODENOMAD_INTEGRATION_SCREENSHOTS`), truncation with the full + title; attaching the only open document, detaching, informing without a document or a conversation, choosing + between several documents and reporting a `busy` outcome; the menu's documentation and connection line, guarded + application installation, one-click detach with a lost answer read again and never replayed, removal; French + and Hebrew labels; and the catalog window's install by ID and consent revocation. + `packages/ui/src/lib/integration-row-state.test.ts` covers the link, connection, state line priorities and offer + choice derivations. - `node --import tsx scripts/test-integrations-attachments-native.mjs [pilot-checkout] [blender-executable]`: - OpenCode 2.2.5 with actual Fastify attachment/read/SSE routes, native sessions and metadata, a loopback + A supported OpenCode runtime (at or above the minimum) with actual Fastify attachment/read/SSE routes, native sessions and metadata, a loopback `IntegrationCatalogSource`, and the real relay feeding `createIntegrationsStore` through SSE. Checks a 60-second event-free demand and ten native plugin events inside 300 ms, strict inputs and cross-Location refusals. The Blender pilot extracts the immutable pin recorded in `VENDORED.json` from the supplied checkout read-only, @@ -414,7 +424,7 @@ Commands: logger and an adversarial opaque session ID. Every child uses the fixture environment. Manual AC-B4 has its own acceptance run. - `node --import tsx scripts/test-integrations-host-install-native.mjs [integration-checkout]`: - actual Fastify installation route and OpenCode 2.2.5 RPCs using the real built integration kit. Environment and + actual Fastify installation route and a supported OpenCode runtime's RPCs using the real built integration kit. Environment and kernel WSL detections run with and without authenticated validated offers; selected/backend WSL refuses before catalog or native RPC reads. Mirrored-offer kit refusals preserve every protected fixture file, including the preloaded catalog. A Linux positive control invokes exactly one installer callback and private sentinel write. diff --git a/dev-docs/OPENCODE_RUNTIME_SETUP.md b/dev-docs/OPENCODE_RUNTIME_SETUP.md index b34d10e27c..ef714bde6b 100644 --- a/dev-docs/OPENCODE_RUNTIME_SETUP.md +++ b/dev-docs/OPENCODE_RUNTIME_SETUP.md @@ -20,10 +20,13 @@ never upgrade or restart a user's service. separately from an untested version. Optional configuration reload follows its own route presence. Never probe support with a write. -Scheduled Missions additionally require the consumed Schedule contract and enabled -`experimental.schedules` in the discovered global configuration and effective whole -Location block. Targeted, confirmed activation and exact read-back are described in -[Missions](MISSIONS.md) and [native contracts](MISSIONS_NATIVE_CONTRACTS.md). +Scheduled Missions additionally require the consumed Schedule contract and an enabled +effective native `experimental.schedules` flag in the acquired Location. Play/Resume +prepare project-only activation automatically, preserving every discovered explicit +OFF and native environment OFF. An already enabled Location receives a ready proof +without configuration writes. Native flag resolution, targeted activation and exact +read-back are described in [Missions](MISSIONS.md) and +[native contracts](MISSIONS_NATIVE_CONTRACTS.md). Missing APIs, explicit OFF, a masking block, failed activation or missing exact calendar registration keep the schedule paused or in an explained error state. Play of a Mission without launch criteria follows its own admission path. diff --git a/dev-docs/PLUGIN_CONTROLS.md b/dev-docs/PLUGIN_CONTROLS.md index 7ad1f51404..2c99b2abe1 100644 --- a/dev-docs/PLUGIN_CONTROLS.md +++ b/dev-docs/PLUGIN_CONTROLS.md @@ -48,7 +48,7 @@ errors like the activation route and add a stable `code` (`invalid-spec`, Unsent consent expires after 120 s and is revoked by navigation, invalidation or disconnection. Cancellation and expiry perform no mutation. The captured request is sent once; uncertain responses reconcile actual configuration through the existing invalidation/read path before any fresh user action. - The integration's own Status section offers application install/update when a fresh active native integration reports + An integration's row menu offers application install/update when a fresh active native integration reports `host.action`. It uses the shared Cancel-first machine/package-version confirmation and the sessionless, outcome-only installation route ([application installation](OPENCODE_INTEGRATIONS.md#application-installation)). WSL is refused before catalog persistence or installer calls; uncertain requests must never be replayed. @@ -109,8 +109,9 @@ The UI excludes managed records from every ordinary plugin row, activation switc check/update action and source-removal path. A compact warning above the Plugins list exposes only managed plugins that are disabled, failed or loading-unconfirmed. Each warning row has an `InfoPopoverButton` with available native error/ref details. Only a disabled row offers -**Re-enable**, through the existing activation mutation: append the positive exact ID, retain -the negative rule and all unrelated configuration. Use the disabling rule's Global/Project +**Re-enable**, through the existing activation mutation: it removes the exact disabling rule when that +alone re-enables the plugin, otherwise it replaces it with the positive exact ID, keeping all unrelated +configuration. Use the disabling rule's Global/Project scope when writable, otherwise the writable Project override. Native rules still determine precedence. Keep the warning until a fenced inventory refresh confirms an active runtime entry; a durable write alone leaves it visible. Native events and the existing Refresh action @@ -125,8 +126,12 @@ Virtual origins remain visible in details when the native rule has no filesystem OpenCode applies plugin entries in configuration order. `-plugin.id` disables an ID, `plugin.id` later re-enables it, `*` matches all plugins, and `prefix.*` -matches an ID prefix. Source declarations remain in place when an activation -rule is added. +matches an ID prefix. Every string without `-` is one ordered add operation: it selects plugins only +when it matches a plugin ID already defined or loaded earlier in that order, or is `*`, `prefix.*` or +`opencode.*`; otherwise OpenCode loads it as a package (an npm install for a bare name). A lone `plugin.id` +whose package has not loaded yet is therefore fetched from the registry (`packages/core/src/config/plugin/source.ts` +and `packages/core/src/plugin/supervisor.ts` in OpenCode). Source declarations remain in place when an +activation rule is written. The native plugin API offers `plugin.list`/`plugin.check`/`plugin.update`, and the pinned client's `config.update` accepts only its declared preference fields, so @@ -227,8 +232,13 @@ connection refuse with `stale` and require a fresh selection/confirmation. 2. Resolve physical file destinations, including symlinked parent directories, and fail closed on malformed content, invalid plugin entries, circular links, or filesystem errors. -3. Edit with `jsonc-parser`: append only the requested exact `id`/`-id` rule or - source spec string, or delete exactly one verified element. Comments, source +3. Edit with `jsonc-parser`: append one source spec string, delete exactly one verified source element, + or write one activation. An activation deletes the target document's earlier exact `id`/`-id` rules for + that plugin, then appends the requested rule, or only deletes them, whichever first produces exactly the + snapshot appending the rule would produce: every control's effective state and displayed switches, and + every source. Otherwise it only appends. Entries the snapshot reads as source declarations (a package named + like its ID), broad selectors and other files are never deleted, and a placeholder or watcher-lag projection + (not no-op safe) keeps the plain append. Each deleted entry is re-verified in the read document. Comments, source objects, options, unknown keys, ordering, indentation, line endings, and a UTF-8 BOM are retained. 4. Serialize in-process mutations and hold a per-target interprocess lock across @@ -273,7 +283,7 @@ daemon are paired positionally and replayed after its normalized document. Raw enable the no-op shortcut. A no-op additionally requires the whole normalized prefix to match the raw target, followed only by concrete rules included in the projection. A raw deletion/replacement or an unprojected entry during watcher -lag instead appends the requested exact rule. +lag instead appends the requested exact rule without deleting earlier ones. The connection generation is rechecked after discovery, before file preparation, and again immediately before the atomic rename. Mutations also enter the active @@ -287,23 +297,25 @@ receives the current acquired configuration entries and native target position. Missions settings request strict document acquisition, rejecting JSON and JSONC coexistence in the same layer; plugin source edits retain the selected target and propagate their deadline signal through acquisition and commit. Missions' -`native-experimental-settings.ts` edits only schedules/depth, retaining explicit +`native-experimental-settings.ts` authors schedules/depth, retaining explicit companion values. Depth writes preserve inherited schedule activation when the -local block omits its flag. Schedule activation materializes inherited depth -only when creating a whole-block override. Adding schedules to an existing block -keeps its effective depth choice, including the native default selected by an +local block omits its flag. Schedule activation copies every effective inherited +experimental option when creating a whole-block override. Adding schedules to an +existing block keeps its options, including the native default selected by an absent depth key. Existing file-byte expectations and the physical replacement lock fence concurrent writers. `editConfigDocuments` prepares and verifies each required target before its first -rename. The Missions activation journal records the plan before effects, an -attempt before each rename, and each exact acknowledgement. A read-only target -or conflicting source refuses preparation; a partial global/project write keeps -its durable receipts and preserves the successful write. An uncertain attempted -write is reconciled only by its exact result bytes, preserving a later explicit -OFF. `native-schedule-settings-activation.ts` acknowledges readiness only after -the native global and effective Location blocks both enable schedules, within -ten seconds, under the acquired connection and host/distro authority. +rename. The Missions activation journal records its project-only plan before effects, +an attempt before each rename, and each exact acknowledgement. A read-only target, +masking block, discovered explicit OFF or native environment OFF refuses preparation. +An already enabled Location receives a zero-target ready proof without configuration +writes. Persisted intentions with global targets retain exact attempted effects for +read-only reconciliation. Never write global or unattempted targets from those intentions. +An uncertain attempted write is reconciled only by its exact result bytes, preserving +a later explicit OFF. `native-schedule-settings-activation.ts` acknowledges readiness +after the effective native Location flag enables schedules, within ten seconds, +under the acquired connection and host/distro authority. OpenCode watches these configuration roots. Never restart the daemon or report a successful file write as an active plugin: the mutation response publishes the @@ -329,8 +341,11 @@ guessed paths. - `CODENOMAD_TEST_WSL_PLUGIN_CONTROLS=Ubuntu` enables the real Linux-filesystem/UNC publication, recognition, tamper and link checks in `desktop-plugin-managed-wsl.test.ts`, alongside the native document suite in `plugin-control-document-wsl.test.ts`. -- JSONC preservation, malformed input, optimistic conflict, and atomic replace: - `plugin-control-document.test.ts` +- JSONC preservation, malformed input, optimistic conflict, atomic replace, and rule replacement with + re-verified deletions: `plugin-control-document.test.ts` +- rule replacement on toggle (no growth over repeated toggles, removal-only re-enable and disable, broad + selectors, rules in another scope, source declarations named like their ID, managed re-enable): + `plugin-controls.test.ts` - spec validation, package identity, append and exact removal (comments, CRLF, BOM, object entries, stale index): `plugin-source-document.test.ts` - source add/remove ownership, scope availability, duplicates across scopes, @@ -374,9 +389,12 @@ guessed paths. ## Agent conventions - Recognise managed plugins on the server through validated installer entries and content-addressed payload locations. All ordinary UI paths exclude `managedBy: "codenomad"` records; surface managed failures only in the compact warning and its on-demand details, with scoped Re-enable for disabled entries. +- Serialization tests await the held mutation's worktree identity lookup before launching competing scopes. Target discovery performs asynchronous filesystem reads, so arrival order is observed explicitly; the independent scope completes while a second same-target mutation stays queued. +- Source-add deadline tests await admission of both parallel configuration reads and advance mocked timers through timeout and grace. Release and join the abandoned reads before checking durable bytes. - Present Global and Project as separate per-plugin columns so every mutation has an explicit scope. Cache display snapshots by instance and worktree directory, and refresh them only while the plugin surface is visible. -- Keep the Plugins surface minimal: plugin names, one compact row-action icon when applicable, and Global/Project switches. The row menu (`components/plugin-row-actions.tsx`, memoized item descriptors) names each exact operation: package check or update with its native target, **Remove from Global/Project** per removable declaration, and Refresh for unconfirmed sources; a single package item keeps its package icon. Put source/status/version/target details, failure `ref`s and the shared-cache effect of package updates in hover/focus tooltips. Do not add general descriptions, inline explanations, target footers or success commentary; source rows carry only a short state label (**Installing**/**Not confirmed**). The compact Refresh and Add icons occupy the name-column header; Refresh spins during loading and refresh; automatic display updates follow native events, reconnects and visible demand. Package writes use native inventory-validated targets, never plugin IDs; styles live in `styles/components/plugin-package-action.css` and `plugin-source-add.css`, and menu chrome is shared with `action-overflow-menu`. +- Keep the Plugins surface minimal: plugin names and versions, one compact row-action icon when applicable, and Global/Project switches. The row menu (`components/plugin-row-actions.tsx`, memoized item descriptors) names each exact operation: package check or update with its native target, **Remove from Global/Project** per removable declaration, and Refresh for unconfirmed sources; a single package item keeps its package icon. Put source/status/version/target details, failure `ref`s and the shared-cache effect of package updates in hover/focus tooltips. Do not add general descriptions, inline explanations, target footers or success commentary; source rows carry only a short state label (**Installing**/**Not confirmed**). The compact Refresh and Add icons occupy the name-column header; Refresh spins during loading and refresh; automatic display updates follow native events, reconnects and visible demand. Package writes use native inventory-validated targets, never plugin IDs; styles live in `styles/components/plugin-package-action.css` and `plugin-source-add.css`, and menu chrome is shared with `action-overflow-menu`. - The Plugins Add menu (`components/plugin-add-menu.tsx`) uses stable item descriptors for **Add an integration…** and **Add a plugin…**. The integration catalog window (`integration-catalog-window.tsx`) uses shared window primitives, overlay surface, an upper-right close button and reviewed catalog IDs through `pluginSourcesStore.installIntegration`; native integrations lock the focusable scope selector to Global. Confirmation uses the shared 600 ms guard. Installation hints and reconciliation use the existing source store. - The Add plugin window (`components/plugin-source-add.tsx`) is a transient `.window-*` popover without a close button: a `--surface-field` spec input, the native scope select (Global default, Project disabled when unavailable), the trust sentence and the Project warning. It closes on success and keeps refusals inline; it never announces an active plugin. -- Recognized integrations keep their Plugins row alongside their own Status section. Both use `PluginActivationSwitch` and `PluginRowActions` with shared mutation/in-flight state. Application installation and conversation attachment actions belong to the integration section. Source ambiguity labels its Plugins row **Non-conforming** and suppresses its integration section. Supplemental integration details use `InfoPopoverButton` or tooltips, with localized terse labels. +- A recognized integration has exactly one surface, its Plugins row ([integration rows](OPENCODE_INTEGRATIONS.md#ui-read-model)): display name, version, `PluginActivationSwitch` with its `integration` flag (the accent switch of Yolo and the settings, `ACCENT_SWITCH_SX`, instead of the green plugin variant), and under it a state line that always says where the integration stands and acts when it can (install or update the application part, attach or detach the displayed conversation). Its `PluginRowActions` menu adds the connection line, documentation and application (re)installation before the ordinary items. Source ambiguity labels a Plugins row **Non-conforming** and attributes it to no integration. Supplemental integration details use tooltips with localized terse labels. - Plugins that fail before exporting an ID remain visible by their native package target or local path, with failure details in the name tooltip; package entries retain check/update actions. Do not fabricate plugin IDs or activation switches for these entries; reconcile them into ordinary rows once native loading succeeds. Managed failures belong to the attention block. +- Plugins rows use the app's ordinary tooltips: the native `title` attribute (multi-line with `\n`) on names, the state line, switches and row actions, never Kobalte `Tooltip` or a custom tooltip surface. A row's details also go into a hidden element the row names through `aria-describedby` (`-details`), and every control keeps its `aria-label`, so keyboard and screen-reader users get the same text. diff --git a/dev-docs/PROJECTS.md b/dev-docs/PROJECTS.md index d37ed65065..b3fb43d0ed 100644 --- a/dev-docs/PROJECTS.md +++ b/dev-docs/PROJECTS.md @@ -38,6 +38,8 @@ Closing project tabs, temporary workspaces, the new-instance launcher and the Gi - Host Git probes report `git_required` only for an absent executable (`ENOENT`). Timeouts, killed processes, unsuccessful exits and invalid version output yield `git_probe_unavailable` (503, retryable); the availability advisory propagates uncertainty to its best-effort caller rather than publishing installation guidance. The probe retains its five-second deadline and rechecks on demand. - Closing a project tab detaches it immediately and requests deletion of that occurrence's logical backend workspace record; failures notify and never retry automatically. Separate occurrences of the same folder are independent. A `workspace.stopped` deletion closes the same record in other windows and notifies only windows displaying it that did not initiate the close. CodeNomad never evicts native Locations; OpenCode sessions keep running and reopening finds them. Whole-window close, app quit, renderer reload and backend shutdown keep existing restoration behavior. Temporary discard and server stop events use local-only tab detachment, not another DELETE; Keep closes the retained project normally. +- A suspended remote occurrence keeps its drafts and attachments in its own saved placeholder snapshot. Removing its live instance returns only unapplied closed-draft claims; normal placeholder Close hands the snapshot to the backend/folder draft vault through `RemoteRestoreTab.remove`, while successful Retry consumes its own snapshot. Restored occurrence state takes precedence over closed sibling drafts. Temporary-folder discard authority follows each backend's current event attachment and resets on its reconnect or detach. +- Unsent drafts and attachments outlive their project tab in the window's memory (`stores/closed-workspace-drafts.ts`). `removeInstance` hands them over just before clearing them, keyed by project identity (`closedWorkspaceDraftKey`: backend id, empty for the window's own backend, plus the `normalizeWorkspacePath` folder), for every removal: user close, a close from another window, a backend stop or restart reconciliation. Temporary discards (`drafts: "discard"`) keep nothing and purge the project's whole entry, drafts and attachments, because the folder is deleted. Every window recognizes them: the server deletes a discarded record (`workspace.stopped` with reason `deleted`) before unregistering its folder, whereas Keep unregisters first, so a deleted record whose folder the latest `workspace.temporaryChanged` still lists was discarded. That registry state is the only authority: the instance's `temporary` mark can be stale (a workspace-list response requested before Keep, a Keep missed while disconnected). Without a broadcast on the current event connection (none yet, or reset on reconnect) no removal is a discard and the drafts are kept, since an entry for a deleted folder is harmless and bounded while dropping a kept project's drafts loses work. Restoration-owned instances discarded by `removeRestoreCreatedInstanceFromUi` keep nothing either (`drafts: "skip"`; restoration still holds what it seeded). Closing several occurrences of a folder merges them, the later close replacing a session's text and attachments together, including a session it emptied by typing, clearing or sending (draft/attachment authority with no content), which removes the older value. A close supersedes those sessions both in the vault and in every pending restore of the project (entries taken by a reopened tab whose restore has not finished), because a pending restore is the only way older drafts return to the vault; the vault therefore stores no clear marks, and another reopening cannot consume one. `addInstance` takes the entry once for that identity and hydrates it through `hydrateWorkspacePromptState`, only into sessions the instance shows nothing for and the user has not touched, so occurrence-aware startup, web or reconnect restoration and the user's own typing always win: the new-conversation draft at once, session drafts after `waitForInstanceInitialSessionHydration` plus `hydrateRestoredSessionChain` for their sessions, so missing sessions get nothing. Filling empty sessions can copy one occurrence's draft into an empty, untouched session of another occurrence of the folder; nothing is overwritten. A restore that fails, or whose tab closes before it finishes, puts back underneath only the sessions it could not apply and the user did not touch there. At most 16 projects are kept, least recently closed evicted first; nothing is persisted, so desktop and web restoration stay the only mechanisms across reloads. - Git is a full-functionality prerequisite, with directory-only degraded conversations when the backend cannot find Git. Only the explicitly opened physical folder is session authority in that mode; never infer sibling worktrees from native project IDs. Keep ancestor/descendant mutation identities covered by the deletion fence across Git availability changes. Inform agents through the owned native `codenomad.git-availability` instruction before prompts/custom commands, remove stale context after recovery, and keep this advisory separate from fail-closed environment synchronization. Do not add a blocking Git setup UI. Validate with `scripts/test-git-degraded-native.mjs` using an isolated CLI/database and provider. - Temporary instances (`workspaces/temporary-workspaces.ts`, UI `stores/temporary-instances.ts`) are ordinary non-Git workspaces on CodeNomad-created direct children of `/temporary-workspaces`. Registry membership (`temporary-workspaces.json`), not location, makes a folder temporary; keeping only unregisters it and adds a named recent project. Discard deletes only registered children of that root, refuses running conversations and other open tabs of the folder, removes conversations deepest-first, closes the workspace before deleting the folder and keeps failed removals registered; such a folder is reachable only by browsing to it. Closing a temporary tab from the UI asks Keep/Discard/Cancel, except that an untouched one (no conversation, file or unsent draft) closes and is discarded silently (`onlyIfEmpty`: the server refuses with `temporary_has_conversations`/`temporary_not_empty`, and any failure of that quiet discard returns the choice without an error). Before the server stops it, a visible temporary tab yields to its neighbour (or closes if alone) and a refusal restores it in place; `workspace.stopped` likewise closes the tab first and clears the instance in a microtask, because clearing a visible shell's state in the same update as its tab freezes the window. Same-minute names get a `(n)` suffix. Registry changes broadcast `workspace.temporaryChanged`, which clears kept marks in every window. Open temporary tabs are saved and restored with the app state like any project tab (still marked temporary). Only the choice dialog overrides initial focus (to its last, non-destructive choice); confirms keep focus on Cancel. Refusals use stable `temporary_*` codes localized by the client. Validate with `scripts/test-temporary-workspaces-native.mjs` against an isolated CLI. - The tab-bar new-instance button follows the last tab like a browser: the instance `TabScroll` frame only spans its tabs and the button sits after it, outside the scroller (so focusing it never scrolls the strip), ending up at the strip's end once tabs overflow. Dragged tabs stay visually within the tab list like a browser's (`KeepDraggedTabInStrip`), while the drop slot follows the pointer's unbounded position (`closestUnboundedCenter`). The button keeps its click (full home page, Cmd/Ctrl+N) while a long press, right-click, Alt+Down, Shift+F10 or Menu opens the anchored `NewInstanceLauncher` (`lib/long-press.ts`; only Escape returns focus to the button, never over another surface or the home page): search-first recent projects (an open project switches to its tab) and Browse/Temporary/Clone only. Remote servers, SideCar and management (rename/remove recents, servers, settings) stay on the home page. Browse/clone flows live once in `components/new-instance-dialogs.tsx` (with optional home-only add-server setup) and recent-folder display helpers in `lib/recent-folder-display.ts`, shared with `FolderSelectionView`; styles in `styles/components/new-instance-launcher.css`. diff --git a/dev-docs/PROVIDER_ACCOUNTS.md b/dev-docs/PROVIDER_ACCOUNTS.md index af5c429ca6..c6d84f66ee 100644 --- a/dev-docs/PROVIDER_ACCOUNTS.md +++ b/dev-docs/PROVIDER_ACCOUNTS.md @@ -277,10 +277,15 @@ credentials, fall back to another login, or use this display for account selecti The fixed public Console API supplies three mandatory `usage/summary` request counters (`24h`, `7d`, `30d`) and sequential `usage/models?range=30d` pages of 50. -These calendar windows begin at UTC midnight today, six days ago and 29 days ago. -The UI labels them **Today (UTC)**, **7 days (UTC)** and **30 days (UTC)**, +CodeNomad shows the Console's own ranges without computing window boundaries. +The UI labels them **24 hours**, **7 days** and **30 days**, formats counters in the selected app locale and lists **Requests by model · 30 days** -with both model and provider identities. OpenCode Go uses its own quota reader. +with both model and provider identities. An optional `billing/status` read +supplies `windows.credits_balance`, shown with the credit-balance preference. +It starts beside the usage reads (three-second bound); once they complete it is +awaited for at most 250 ms. Any failure, 401 included, or a late answer only +omits the balance and never changes the reading's outcome. +OpenCode Go uses its own quota reader. Decimal-string counters, token totals and micro-cent costs must fit safe nonnegative integers, including cumulative sums; 100,000,000 micro-cents is USD 1. Pagination must remain consistent across the complete read, bounded to 20 pages, @@ -305,34 +310,22 @@ malformed-response and network errors keep their distinct localized messages. ## OpenCode free-model display Free `opencode` models (`big-pickle` and `*-free`) use the display-only -`usage/opencode-free-usage.ts` orchestration. It sums only Console's free-model -request counts for the connected account since 00:00 UTC, against an observed -800-request daily reference. **Estimated** describes the reference allowance -and next-UTC-midnight reset. `freeEstimate` carries `requests` (null when -unavailable), `reference` and `exhausted`. A readable Console count supplies the -`windows.daily` gauge; exhaustion forces that gauge to 100% while preserving the -count. Missing credentials show the translated 800-request reference/connection -prompt and **Settings → Providers**. Console failures use the paid reader's -stable, redacted error reasons and keep the count unavailable. Never read native -activity statistics as a fallback for this quota. - -`usage/opencode-free-exhaustion.ts` captures the model at `session.step.started`, -then accepts only a matching session/assistant message's structured -`session.step.failed` `provider.quota`. The connection-local weak state shares a -mark across all free models until the failing UTC day's next midnight. Duplicate, -ambiguous, missing-start and previous-day failures are ignored. The memo admits -1,024 bounded step identities per connection and evicts conservatively. The -observer receives events before rotation deduplication, independently of saved -credentials and automatic-selection policy. Marks live in backend memory and -are lost on restart. Never feed this evidence to account selection. +`usage/opencode-free-usage.ts` orchestration. It shows one aggregate bar: the +sum of Console's free-model request counts for the connected account over its +`24h` range, against an observed 800-request reference, plus the Console credit +balance as `windows.credits_balance`. Nothing is estimated locally: the bar has +no reset time and there is no exhaustion state. `freeEstimate` carries +`requests` (null when unavailable) and `reference`. A readable Console count +supplies the `windows.daily` gauge (`resetAt: null`). Missing credentials show +the Console connection message and **Settings → Providers**. Console failures +use the paid reader's stable, redacted error reasons and keep the count +unavailable. Never read native activity statistics as a fallback for this quota. The reader uses the bounded models parser for sequential `range=24h` pages. -Its demand cache keys by credential digest and UTC day (32 entries, 60-second TTL -capped by midnight and OAuth expiry). A per-caller wait, including credential -lookup, expires 12 seconds from route entry, reserving three seconds for ownership -revalidation and publication. Shared Console transports keep their own 15-second -deadline. Reads crossing midnight discard the previous day's counter. Publication -reapplies exhaustion after asynchronous ownership checks. +Its demand cache keys by credential digest (32 entries, 60-second TTL capped by +OAuth expiry). A per-caller wait, including credential lookup, expires 12 seconds +from route entry, reserving three seconds for ownership revalidation and +publication. Shared Console transports keep their own 15-second deadline. ## Auto-select account @@ -425,4 +418,4 @@ exhausts the current mock account. Never add a simulation action to production. - Public usage failures use `ProviderUsageUnavailableReason` (`api-types.ts`), shared by `ProviderResult`: an enumerated `unavailableReason`, an optional numeric `providerErrorCode` of one to eight digits for `provider-error`, and an optional enumerated `unavailableAction` associated with its known reason. `usage/service.ts` allowlists these fields and clears failure windows. Never serialize `ProviderResult.error`, native errors, upstream bodies, arbitrary messages, URLs or secrets. The UI maps reasons to translated text and actions to fixed destinations (`chatgpt-usage` for `openai-token-sharing-unsupported`); readers opt into the action explicitly. Failure cards use `role="status"`, without quota bars or retained values; their real external anchors have explicit underlined labels, keyboard focus, `noopener noreferrer` and `openExternalUrl`. Add every new public reason/action to the service allowlist, UI mapping, all ten locales and regression tests together. - Provider accounts use a native dropdown like Web search defaults; never add an Accounts disclosure or selectable account rows. Provider headers keep the name and text Manage models button on one row; a faint separator distinguishes the account controls below. Account actions are always visible. The `provider-account` container stacks the label above the dropdown/actions at narrow card widths. Native account ordering supplies the current account; rename/remove drafts stay keyed by credential. Environment connections are read-only. The browser never reads credential secrets. Native labels win; only `default` may display a sanitized login email from the owned server adapter. Opt-in rotation is per integration (`providerAccounts.autoSelect.`) through the selection-adapter registry in `provider-accounts/adapters.ts`, for subscription accounts with quota windows only: Codex, OpenCode Go (Go key and Console sign-in, Go provider only), Claude Pro/Max (OpenCode Anthropic OAuth, never the Claude Code login), GitHub Copilot and key-based coding plans; pay-as-you-go keys/credits stay manual. It runs before prompt/command admission, reading each explicit credential's fresh quota (reusing Usage readers) without activating candidates or refreshing tokens, with local manual-change fences and no mutation/prompt replay; the only switch condition is a full current account. Native `provider.quota` failures add bounded in-memory per-connection marks (`quota-observer.ts`); reactive adapters (Go, Console, Claude) accept unknown-but-unmarked candidates, others need "available". Account styling lives in `styles/components/provider-accounts.css`, backend policy in `provider-accounts/`. Browser preview percentages are simulated. - Provider usage providers receive credentials explicitly: the route projects each integration's active native `credential.list` entry through `usage/native-credentials.ts` (never host auth.json; a missing endpoint is unavailability) and caches snapshots per provider credential identity. Codex uses its selected-connection adapter. Claude quotas follow the session's login (`usage/claude-credential.ts`): `anthropic`/`claude` use only OpenCode's Anthropic OAuth; the providers that run Claude Code inside the daemon, opencode-claude's `claude-code` and OpenCode's Claude Agent `claude-agent` (native method `claude-login`, external), resolve to one `claude-code` reader (shared snapshot and rate-limit backoff) and use only the Claude Code login the route resolves on the daemon host (session environment, WSL path translation, Claude Code's token/Keychain/file order) and injects as the `claude-code` entry, so it joins the cache identity; never cross-fall back between them. Never rewrite an OpenCode connection to read usage. Allow an in-memory access-token refresh only for providers whose refresh token stays stable on each use, including Google's Gemini CLI and Antigravity connections; use their matching public installed-application clients as described under Google usage. Model-scoped limits add `window:Model` rows beside the plan windows. -- OpenCode free usage follows the Console-account display contract above: only upstream free-model request counts, with an observed 800-request reference and estimated reset. Keep ownership/publication fences, unknown counts and the reference caveat intact. Never feed this display to account selection. +- OpenCode free usage follows the Console-account display contract above: only upstream free-model request counts against an observed 800-request reference, plus the credit balance, with no local reset or exhaustion. Keep ownership/publication fences, unknown counts and the reference caveat intact. Never feed this display to account selection. diff --git a/dev-docs/REMOTE_CONTROL.md b/dev-docs/REMOTE_CONTROL.md index 0fb76bddcf..a68f60ef3e 100644 --- a/dev-docs/REMOTE_CONTROL.md +++ b/dev-docs/REMOTE_CONTROL.md @@ -41,6 +41,23 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD - Keep OpenTunnel's per-route PROXY protocol off: the ingress expects plain HTTP. +## Administrator policy + +`server/network-policy.ts` reads two variables from the environment the backend +inherits, so machine-wide values reach every desktop launch and the UI cannot +override them. An unknown value refuses startup. + +- `CODENOMAD_REMOTE_CONTROL=disabled`: the manager opens no tunnel, skips the + launch resume (keeping the registry's choice), refuses Start and pairing links + (`403`, `code: "remote_control_disabled"`) and authorizes no device. Its status + carries `disabledByAdministrator`; Settings shows that state, hides Start, + pairing and previews, and keeps paired devices listed for revocation. +- `CODENOMAD_LOCKED_HOST=
`: the listening address, validated like + `--host`, wins over `--host`, `CLI_HOST` and the desktop listening switch (the + hosts still pass their own `--host`). `ServerMeta.listeningLocked` disables the + switch in Remote Access settings. An intranet address keeps direct access for + colleagues; `127.0.0.1` keeps it on this machine. + ## Admission `server/src/remote-control/`: @@ -59,10 +76,30 @@ browser ─TLS─▶ OpenTunnel relay (forwards ciphertext) ─▶ OpenTunnel SD Direct password login, its page and logout remain available to LAN clients. `GET /api/remote-control/status` is available to authenticated clients and returns `manageable: false` for non-local peers. SideCar registration APIs remain - available to authenticated clients; content and WebSockets require loopback. + available to authenticated clients; content and WebSockets require loopback, + except under the host's SideCar opt-in below. Live preview capabilities retain their scoped admission. `/api/meta` reports - `localRequest` using that same transport authority; the UI hides password changes, - SideCar opening and remote-server management unless it is true. + `localRequest` using that same transport authority; the UI hides password changes + and remote-server management unless it is true. `/api/meta` also reports + `sidecarsAllowed` (local, or admitted by the opt-in); the UI shows SideCar opening + and the picker only when it or `localRequest` is true. +- SideCar opt-in over direct HTTPS: the host setting `server.sidecarsOverDirectHttps` + (`config.yaml`, off unless `true`; **Settings → SideCars → Open SideCars over HTTPS**, + shown to local clients only) lifts the host-only gate for `/sidecars/` content and + SideCar WebSocket upgrades, and nothing else, for a direct-listener request from a + verified direct HTTPS origin (`server/sidecar-direct-https.ts`). The origin rule is + `remote-control/direct-https.ts`: the `https:` advertised local/remote URLs, reachable + addresses and `CODENOMAD_ALLOWED_ORIGINS` entries, never loopback or unspecified + hosts; mutations need their own `Origin`; GET/HEAD/OPTIONS use `Origin`, else the + `Referer` origin, else `https://` plus `Host`; ingress sockets never qualify. Plain-HTTP + LAN, loopback-alias and foreign or opaque origins stay refused. Authentication, the + direct source policy, SideCar cookie stripping and WebSocket Origin/Referer checks + still apply. Admission reads the setting from `config.yaml` as it is now + (`SettingsService.serverFlag`, `settings/server-flag-reader.ts`: re-parsed when its stat + signature changes; missing, unreadable or invalid reads as off), never the display cache, + so a host edit applies to the next request. The config routes refuse a change to this key + from non-local requests with 403 (`settings/host-only-settings.ts`), including deleting + the server owner, judged against the authoritative document each write starts from. - `gate.ts` runs before CORS, authentication and routing. It requires the exact tunnel `Host` and the public `Origin` on browser mutations, and strips forwarding headers. It accepts origin-form targets only (no absolute-form, leading `//` @@ -175,6 +212,19 @@ carriers and WebSocket handshakes require that exact origin; CORS reflects only the owning origin. Same-origin resource policy protects no-CORS sub-resources, and frame-ancestor policy restricts embedding to that content origin and its issuing local UI. + +Preview and SideCar proxies apply a per-listener target boundary before HTTP, +asset-fallback and WebSocket dispatch. Control APIs on this backend's own origins +and loopback aliases, and every preview capability origin, return 404 before IO. +Ordinary application targets retain their proxy behavior. Direct HTTPS SideCar +opt-in admits only SideCar content, including an authenticated direct browser +device; backend relay, memory and remote-preview authority retain their host rules. + +The administrator's listening lock governs the ordinary application listener. +Relay APIs share that listener and retain their loopback-origin admission. +Outbound profile transports, SSH forwards and the isolated preview listener keep +their private lifetimes and bindings; a local relay operation leaves the Remote +Control administrator policy unchanged. See [Browser Automation](BROWSER_AUTOMATION.md#remote-preview-content-transport) for the API and revocation lifetime. @@ -216,7 +266,8 @@ Authentication and the host-only gate also apply with explicitly allowed origins `--dangerously-skip-auth` retains the origin and host-only gates. SideCar WebSocket upgrades apply this same Origin/Referer policy before opening -an upstream connection, alongside their loopback transport and session checks. +an upstream connection, alongside their loopback transport (or the host's direct +HTTPS opt-in) and session checks. Native loopback upgrades may omit both source headers. Preview WebSockets use their scoped capability admission. @@ -251,7 +302,13 @@ credentials follow their separate registry lifetime and revocation rules. peers, credentialed CORS, Origin/Referer checks and host-only routes. `server/__tests__/sidecar-proxy.test.ts` covers SideCar upgrade source checks, refusal before upstream contact, authenticated and skipped-auth exchanges, - native origin-less calls and logout revocation. + native origin-less calls and logout revocation, and the direct HTTPS opt-in for + content and upgrades. `remote-control/direct-https.test.ts` covers the verified + origin rule, the opt-in's `/api/meta` matrix, the other host-only paths and the + ingress; `routes/settings.test.ts` covers the host-only setting guard and config writes + that start from the file on disk. The SideCar and settings tests use the real settings + service and edit `config.yaml` as the host would, including revocation after the display + cache loaded the opt-in. `session-manager.test.ts` covers idle/absolute deadlines, configuration and revocation; `auth-responsiveness.test.ts` covers logout and password replacement through real auth routes alongside concurrent credential checks. diff --git a/dev-docs/SESSION_HISTORY_NAVIGATION.md b/dev-docs/SESSION_HISTORY_NAVIGATION.md index e0496bba73..d6cfc962d5 100644 --- a/dev-docs/SESSION_HISTORY_NAVIGATION.md +++ b/dev-docs/SESSION_HISTORY_NAVIGATION.md @@ -72,8 +72,11 @@ The old transcript stays visible during a jump. A newer target supersedes the pending request, including when the new target is already resident. Cancellation, leaving the view and manual transcript scrolling reject late navigation. Failed jumps keep the visible page and retry the requested destination. Historical -windows remain isolated from live append events; returning to latest uses the -native latest-page loader. +windows remain isolated from live append events; returning to the latest window +from history pages the native latest loader, while the latest control inside the +latest window is a local bottom jump (an authoritative reload would race every +live event and its bounded retries can give up, leaving the control without +effect while the session streams). `session-outline.ts` owns metadata independently of resident transcript windows. It refreshes on activation, terminal status, undo/content mutation and reconnect; @@ -338,7 +341,9 @@ One bottom loop (`bottomPin`) keeps the bottom, and only while following: leavin follow ends it. Ordinary following re-pins for two frames after each bottom write; an explicit pin (send intent, latest paging, restoration at the bottom) lasts until enough rows exist and the bottom stays put, within a frame deadline, then hands the -bottom back to ordinary following. Layout changes apply restoration, then an explicit +bottom back to ordinary following. That hand-over leaves the long-reply hold alone +for its settling frames — the reader just asked for this bottom — and the next +content growth re-evaluates it. Layout changes apply restoration, then an explicit pin, then the long-reply hold, then follow. A restoration requested during a pin supersedes it (the pin settles `interrupted`), except that a restoration to the bottom joins an active explicit pin and keeps its row count; it reports `onApplied` @@ -380,8 +385,9 @@ A hold whose reply grows while its pane is hidden lands at the top only in the switch fixture: native events for an inactive session invalidate its message load, and that fixture's `message.list` omits the in-flight reply, so the reload drops the hold's anchor and restoration waits `ANCHOR_RESTORE_MAX_FRAMES` before its pixel -fallback. With the reply listed, the hold returns exactly; but the latest button's -reload then re-engages the long-reply hold at once, a product decision left open. +fallback. With the reply listed, the hold returns exactly; the latest control's +settled hand-over to follow then exempts the hold for its settling frames, and the +next content growth re-evaluates it. A following list shown again after `display:none` is pinned before its first painted frame: a gap read in the animation frame that shows it predates layout and the ResizeObserver-driven pin, and a browser check measures 0 px once painted. diff --git a/dev-docs/SETTINGS.md b/dev-docs/SETTINGS.md index 2288a6f364..4a2cbc5c13 100644 --- a/dev-docs/SETTINGS.md +++ b/dev-docs/SETTINGS.md @@ -6,6 +6,8 @@ Settings rows and actions, the native Preferences window and its project context - Native Servers Open succeeds after the main renderer accepts its selection. Tauri correlates replies with a native-generated request ID and the exact opener, bounds pending requests to 32 and waits up to five seconds. Refusal, a missing handler and a lost reply reach the existing Preferences error path; expired and duplicate replies leave later selections untouched. Only local main windows can reply. +- `openSettingsConfigFile(id)` opens Configuration files and selects only an ID present in the editor's server catalogue. It shares `openSettingsRow`'s short-lived same-origin hint with native Preferences on Electron and Tauri. A reopened editor preserves its dirty-discard confirmation; unavailable IDs preserve the current file. The editor consumes each target once and focuses its file selector. + - Multi-backend profile removal and URL/TLS/SSH target edits use `confirmRemoteServerChange`: refuse known tabs/drafts or occupied/unavailable remote inventory, then confirm the connection change for saved tabs in other windows. Rename preserves the connection. Profile operations retain their asynchronous result so callers can display a refused change. - The usage check reserves the Preferences renderer's current native remote context, including an unavailable project, before remote IO and after the inventory read. Reopening Settings from another project releases that context; native context read failures refuse the change. @@ -36,7 +38,7 @@ Settings rows and actions, the native Preferences window and its project context - Stats resolves `backendOf(instanceId).api` for the mounted attachment and sends its raw workspace ID at the HTTP boundary. Attachment changes clear the display and cancel owned reads; responses recheck their captured authority before publishing. Native generation/status duplicates coalesce. The local instance key and request shape stay unchanged. Consumer regressions live in `tests/browser/backend-usage-routing.test.ts`. -- Settings → OpenCode's logging card opens `OpenCodeLogsAction` in the common non-modal `OutputWindow`. The explicit host administration action uses the host's `useConfig()` and `serverApi`, including while a remote project is selected. Read once on opening and on Refresh; closing, disposal and executable selection changes abort/fence the request. Snapshots stay in the mounted settings reader. The `switch-to-info` command/shortcut opens OpenCode settings and keeps existing key overrides. Version, executable, service actions and diagnostics share this host settings scope. +- Settings → OpenCode's logging card opens `OpenCodeLogsAction` in the common non-modal `OutputWindow`. The explicit host administration action uses the host's `useConfig()` and `serverApi`, including while a remote project is selected. Read once on explicit opening and on Refresh; closing, disposal and executable selection changes abort/fence the request. Global log snapshots stay in the mounted settings reader, separate from session state. The `switch-to-info` command/shortcut opens OpenCode settings and keeps existing key overrides. Version, executable, service actions and diagnostics share this host settings scope. - Reuse `SettingsInfoTip` for contextual help with `help={{ page: "opencode", anchor: "login-start" }}`. Its short localized `text` remains the hover/focus tooltip; click, Enter or touch opens `helpUrl(locale, page, anchor)` through `openExternalUrl`, with a localized failure alert. The span's link role, cancelled label default and stopped activation events keep containing labels, disclosures and controls unchanged. Without `help`, touch toggles the explanation. `SettingsChoiceRow.help` and behavior-registry `help` carry the same destination. Use only relevant published sections with matching explicit ids in every locale; dynamic diagnostics can remain tooltip-only, and actionable popovers keep `SettingsInfoLink` or `InfoPopoverButton`. Destinations and gesture/native-opener behavior are covered by `lib/help-url.test.ts` and `tests/browser/settings-info-tip.test.ts`. - General's Memory card owns the disabled-by-default `server.memoryEnabled` switch, About you/Project review, visit-stable New/Modified badges, revision-checked editing and confirmed Forget. Shared Preferences project resolution selects the authorized project memory, including its worktree; global memory belongs to the CodeNomad configuration. Flagged entries remain available for human review. Entry format, Git history, API, session instructions and badge frontiers are in [AGENT_MEMORY.md](AGENT_MEMORY.md). @@ -52,6 +54,8 @@ Settings rows and actions, the native Preferences window and its project context - Settings → Providers separates Models, Web search and Images into three shared `.settings-disclosure` groups (no icons): Models starts open, Web search and Images folded, and a folded group mounts nothing, so its connection metadata, configuration contract and image-model catalog are read only once opened. Models and Web search each start with a provider selector, Connect action and configured-provider list; Web search then shows its global default and project override. Images (`opencode/image-settings.ts`, `settings/image-settings-card.tsx`, `styles/components/image-settings.css`) edits the Global document's `experimental.image_generate` and `experimental.media_blob`. OpenCode reads `image_generate` per field from the highest-priority document that sets it (unset means on, with the automatic model; only `false` turns the image tool off), but `media_blob` (like `subagent_depth`) from the whole `experimental` object of the highest-priority document that has one, so writing a project block would hide inherited experimental settings. The document that decides each value is read from the native configuration entries and reported under its control when it is not the Global one. When the selected Location's own project document (the project write target) decides `media_blob` through its existing `experimental` object, the snapshot names it under `mediaStorage.project` instead, the box shows the effective value and saving also writes `media_blob` there; the edit is refused if that object has disappeared, because creating one would hide inherited settings. The Missions depth editor's Inherit removes a project object left holding only that `media_blob` when it equals the Global one (`dev-docs/MISSIONS.md`); Off is written as `false`, because removing the key would expose a lower-priority document that enables it. When the fresh Global write target has no `experimental` object while a lower-priority document has one, creating it would hide that whole object (subagent depth, todos) from every Location without its own, even when the selected Location overrides it, so the group is read-only and the backend refuses the write; never copy the inherited values into the Global document instead. Each control appears only when the connected daemon's `Config.InfoEncoded` declares its key, because the native `experimental` object rejects unknown keys; never write either key without that capability. Image models come from native `GET /api/model?types=image` for the selected Location. Reuse provider rows, selectors, inputs and action styles; do not add an API-key disclosure or a separate card design. Search-only integrations stay out of the Models group. Web search configuration lives entirely here. Read connection metadata while this Settings surface is visible, never credential secret values; keep API-key entry explicit and clear drafts on context changes. Use the authorized Global/Project document operations shared with plugin controls and `opencode/native-setting-document.ts` for targeted JSONC edits. Preserve unrelated fields, native discovery roots, WSL atomic writes and conflict/connection/deletion fences. Group/search styling lives in `styles/components/websearch-settings.css`; credentials use native integration methods and remain global. - Stats preferences explicitly aggregate the entire connected OpenCode service via `opencode/service-usage.ts`. Reserve the Usage label for the provider subscription panel. Native project IDs span independent clones, so never label native `session.stats` as physical-folder/Git-family scoped. Keep connection/workspace fences, `tools: "none"` and periods bounded to 366 days; never load transcripts for statistics or imply billing/quota precision. Last snapshots and period choices restore through backend-owned `state.ui.serviceUsage` (eight each/1 MiB, validated service/channel/folder identity), never a Preferences writer to main-window client state or a workspace-UUID cache. Native aggregation must not await optional discovery/cache reads; cached responses cannot replace fresh data. Backend authorized admission order, not completion order or client time, chooses the period across windows; optional publication is bounded and shutdown-fenced. Keep last-known-owner totals explicitly stale through disconnect/errors and revoke them on verified owner/discovery changes. Read while mounted and document-visible; hide cancels queued/trailing demand, activation revalidates once and terminal hints use the shared activity cooldown. Never treat document visibility as native minimize/occlusion detection or equate blur with hidden. See `dev-docs/CACHE_REFRESH_CONVENTIONS.md` for the remaining native scope. Styles live in `styles/components/usage-dashboard.css`. - Settings rows keep only a title unless a caption is essential; secondary explanations go behind `components/settings/settings-info-tip.tsx` (a focusable "i" with a hover/focus tooltip that a tap toggles on touch screens, a span so it never becomes a row label's control or toggles it), styled in `styles/components/settings-info-tip.css`. An explanation that must end with a link uses `settings-info-link.tsx` instead: the same "i" as a button named by its text, opening a popover named by its `title` (click, Enter or Space; focus moves to the link; Escape or outside interaction closes it). Links to a setting use `openSettingsRow(section, row)` (`stores/settings-screen.ts`) with the row's stable `id` anchor (such as `#opencode-login-start`), never its label, and the link's text is the setting's own title key so it follows any rename; the row (`tabindex="-1"`) calls `useSettingsRowTarget` (`components/settings/settings-row-target.ts`) to claim the target once, focus itself and stay in view while the cards above load, and the embedded Settings dialog skips its own initial focus while the shown section holds the targeted row (`settingsRowPending`); closing Settings drops an unclaimed target. Hosts carry only the section to a native Preferences window, so the row travels as a 15-second same-origin `localStorage` hint that the window adopts for its active section on each request and on `storage` events (`adoptSettingsRowHint`). A link never reads or changes the linked setting. Behavior settings opt in with `infoKey` instead of `subtitleKey`. Folded settings groups use the one `.settings-disclosure` (`styles/components/settings-disclosure.css`; a summary may hold an inline heading that keeps the summary's look): Missions gathers every agent/model choice under "Agents and models" with the current request in its summary, and Advanced ends with the environment-variable editor folded under a single title. +- `SettingsService` config reads (`getOwner`, `getDoc`) are a display cache that does not follow external edits. Config writes for every owner (`mergePatchDoc`, `mergePatchOwner`, and `getDoc`'s normalization) start from the document as it is on disk now (`YamlDocStore.reloadAuthoritative`), so a stale cache is never written back; an unreadable or invalid `config.yaml` refuses the write with `SettingsReadError` (routes answer 503) instead of overwriting it. Access decisions never read the display cache: they use an authoritative read such as `serverFlag(key)` or `readEnvironmentForAdmission()`. +- Server-owner settings that widen host-only access are listed in `settings/host-only-settings.ts`: both config routes pass `hostOnlyServerCheck(isLocalRequest(request))` to the write, which refuses with 403 a non-local write whose result changes one compared with the authoritative document it starts from (deleting the owner included), and their rows render only while `localRequest()` is true. Settings → SideCars ends with such a lone-setting switch, **Open SideCars over HTTPS** (`settings/sidecars-direct-https-card.tsx`, `server.sidecarsOverDirectHttps`, **i** tip linking to the SideCar help); its admission rule is in [REMOTE_CONTROL.md](REMOTE_CONTROL.md#admission). Browser regression: `tests/browser/host-only-controls.test.ts`. - Settings update/install actions (OpenCode and Info), OpenCode's post-update service restart, and Remote Control start/pairing-link actions use the shared `.selector-button-primary` accent treatment. The shared `OpenCodeSetupPanel` keeps those same primary actions in startup recovery. Remote Control's header refresh is an icon-only `.window-icon-button`, retaining its localized accessible name, tooltip, disabled state and loading spinner. - The native Preferences window never owns client state. Its General startup card (`settings/opener-startup-state-settings-card.tsx`) targets the exact local window that opened Preferences: the host records that opener and an epoch (Electron `PreferencesWindowRegistry`, Tauri `PreferencesWindow`), forwards only the fixed commands in `lib/native/startup-state-command.ts` to that renderer, which runs them through its own `stores/client-state` transitions. Mutations carry the displayed epoch and degrade to a read after the opener changes. Startup state is per window: when the opener is unknown (Preferences restored at launch) or closed, the host adopts the most recently used local window as the opener (`startupStateTargetId` + `adoptOpener` / `startup_state_target` + `set_opener`), rotating the epoch so a change prepared for another window is only a read. The card re-reads a few times while the adopted window starts and stays disabled only when no local window can answer. - The native Preferences window shows no session, so it never reacts to session events: `stores/sessions.ts` wires the session event handlers (errors, TUI toasts, permissions, session and worktree updates) only outside it. A session alert, toast or notice therefore appears in the windows showing sessions and is acknowledged once there (`tests/browser/preferences-window.test.ts`). diff --git a/dev-docs/TRANSCRIPT.md b/dev-docs/TRANSCRIPT.md index 0b03f4a6ab..52ade2edf1 100644 --- a/dev-docs/TRANSCRIPT.md +++ b/dev-docs/TRANSCRIPT.md @@ -23,12 +23,15 @@ Message content visibility and presets, token lines, tool renderers, native sess - Status Tokens are independent of message token visibility. The non-interactive `renderStatus` slot keeps the session input/output/cost chips in the header in both states; collapsed they form one ellipsized line, expanded they include reasoning and wrap beside the heading. Expanded content holds descendant-inclusive totals below the header. Keep the layout in `styles/panels/status-tokens.css`. - Message token disclosures keep one row in both states: collapsed shows the input/output/cost summary chips on a single ellipsized line; expanded swaps the same row to all six chips beside the chevron, which wrap onto further lines when narrow instead of truncating (expansion exists to read every value). Messages and Status share `components/usage-metric-chips.tsx` and `styles/components/usage-metrics.css`; message row geometry lives in `styles/messaging/message-usage.css`. - Tool-result images retain native `state.content` and render through the shared `components/tool-call/output-images.tsx` surface, including MCP and specialized tools. Keep image bytes out of text projections (copy/search/speech); image styles live in `styles/messaging/tool-call/images.css`. +- Tool image elements use native lazy loading so only shown images load. - Remote blob images accept only signature-verified PNG, JPEG, GIF, WebP, AVIF, BMP and ICO, with their canonical passive MIME type (`lib/passive-image.ts`). Inline data images use plain fetch with credentials omitted and the same byte gate; reject externally supplied blob references. Refuse SVG, HTML, unknown formats and non-image attachments through the existing unavailable presentation; never expose an openable link for them. Remote blob image interactions suppress opening as a document (including linked images, middle clicks, dragging and context menus); direct navigation to an admitted blob remains passive by its verified format and MIME. Never convert an active remote response into a UI-origin blob document. Server response CSP protects server URLs; blob documents use their creator's origin, so verified bytes and canonical MIME govern their admission. Local image sources and their server CSP stay unchanged. - Transcript pages carry large tool images by reference: the UI's native message list reads (`lib/sdk-manager.ts`) and history windows (`fetchHistoryWindow`) send the `x-codenomad-media: deferred` opt-in (`server/src/opencode/session-media-contract.ts`), and the server replaces each tool image data URI over `INLINE_MEDIA_LIMIT` (32 KiB) with a `/api/workspaces//session-media/////` path (`opencode/session-media.ts`). Mounted tool images, matching Markdown images and attachments select `backendOf(instanceId)` through `lib/media-source.ts`. Local sources retain their exact strings and deferred-path joining contract. Remote owned session-media routes load through the selected backend's authenticated fetch into a blob URL; other same-origin HTTP sources use plain fetch with credentials omitted, and public external HTTP images retain their direct URL. Credential-bearing HTTP URLs are rejected for remote media. Attachment authority and the resource lifetime fence admission and every response/body await; replacement, unmount and revocation release blob URLs and clear displayed sources. Missing backends leave media unavailable. `routes/session-media.ts` serves the bytes of the owned session's native message, pinned by the digest and refused at or after an undo boundary, as an immutable sandboxed image. Single-message reads (`session.message.get`: pruning revisions, previews), live events, user attachments and requests without the opt-in stay whole, so revisions hash native content. - Markdown images of local file paths (`C:/…`, `file://`, absolute or relative POSIX paths) cannot load in the renderer. `lib/markdown.ts` renders them as their alt text in a `span.markdown-local-image`, and `components/markdown.tsx` swaps the label for an `` with the source of a completed tool image of the same path already in the session's loaded messages (`lib/markdown-local-images.ts`: the image's file name or its single-image tool's `filePath`; Windows paths compare case-insensitively, a relative path must match one known path's end). Only blocks containing such a label read and track the session's tool parts, and only matched image sources acquire mounted media resources. Never fetch local paths through a backend route for this; an unmatched path keeps its alt text. - Remote media resolves session-media paths through the owning backend's relay and admits same-origin absolute URLs only inside that owner's namespace. Namespace comparisons use the root origin and path; the media request retains its relay authority query and header. Absolute data and public HTTP sources retain their own URL resolution and passive-image admission rules. - Sanitized remote HTML images with `/`, `./` or `../` sources become the existing local-image labels before insertion into the reading DOM. Markdown cache modes include this owner policy; aside answers and workspace Markdown pass their instance identity. Local HTML image sources retain their exact strings. -- Code Mode reads native `metadata.toolCalls` in `tool-call/renderers/execute-data.ts`; keep call-list styling in `styles/messaging/tool-call/execute.css`, with native image/output ownership in the shared tool shell. +- Code Mode reads native `metadata.toolCalls` in `tool-call/renderers/execute-data.ts`; keep call-list styling in `styles/messaging/tool-call/execute.css`, with native image/output ownership in the shared tool shell. A completed object or array result arrives as compact JSON (with optional `Warnings:`/`Logs:` blocks): `executeOutputForRender` displays it indented within size and nesting-depth bounds, while copy keeps the native text; strings, errors and other output use the shared rendering. +- Subagent cards (`tool-call/renderers/task.tsx`) treat a completed call whose `metadata.status` is `running` as a background launch acknowledgement, never as its result. `tool-call/renderers/subagent-report.ts` shows instead the child's latest hidden synthetic `` report delivered to that call: created at or after the call's execution start (`time.ran`, else its creation) and before the next call continuing the same child, chosen by creation time then message id (never list position), with its state: a `running` tag means the child still owns background work. Every idle period reports, so a call continued before any report joins the next period that reports. One index of reports and call times per parent-session revision serves every card; it is owned by the message store and tied to the session's message-id list, so eviction, reload or store replacement rebuild it. A call stored with its result in the tool output shows that output. Covered by `subagent-report.test.ts` and `tests/browser/task-copy.test.ts`. +- A shell call the user interrupted fails with its output so far followed by `metadata.notice`, flagged `metadata.interrupted`. `tool-call/renderers/bash-data.ts` renders the part before the notice like a finished call's output and the shell's `getErrorText` hook shows only the notice under the error label; other failures keep the whole error. Covered by `bash-data.test.ts` and `tests/browser/tool-images.test.ts`. - Native websearch text is parsed conservatively by `tool-call/renderers/websearch-data.ts`; unknown/oversized responses use the shared raw renderer. Recognized provider-consent Forms retain the generic schema/answer path, with layout in `styles/messaging/tool-call/websearch.css`. - Session lifecycle features use OpenCode V2's published signals: one `session.execution.{succeeded,failed,interrupted}` per busy period (`lib/native-execution-events.ts`) and `session.retry.scheduled` for provider backoff. The schema-declared `session.idle`/`session.status` are never published; never wire a feature only to them. A terminal event is a hint until `session.active` confirms settlement, which alone announces "A session finished", only for root sessions ending in success, failure or an inactivity stop. Transcript reducers retire at settlement, deferred while prompts stay parked in their inbox or a user shell or unsettled tool call still needs reconciling there. A tool part still `streaming` (rendered "pending") once a settlement drained has lost its `called` transition: `session.tool.success` reduces solely from the running status (a later `failed` can still settle it). Symmetrically, admission drops a `session.tool.called` whose newest matching part already holds a terminal status: the reducer would overwrite the settled state wholesale (flipping completed tool images back to "running" until a settlement read healed them), while a legitimate re-call is always preceded by a fresh `session.tool.input.started` part that becomes the reducer's match. The SDK reducer already answers a terminal event whose transcript holds a streaming or running tool by invalidating and re-reading messages, but that refresh is dropped while the stream is not connected and never publishes its result; the terminal event therefore finishes the read itself (`finishOpenCodeDataEvent`: one `message.sync` that shares the SDK's in-flight read when connected and starts it when not) and projects the reconciled page, which keeps the display window's membership. Only a newer admitted execution suppresses that publication — same-round activity such as a late terminal tool event must not leave the repair unpublished. Non-event settlement evidence finishes the same read through the same fence: the liveness activity read observing that a run the UI still believed working has settled (`observeNonEventSettlement`, reported by `session-api`), and an authoritative inbox sync that drops an item the reducer admitted (a delivery or cancellation without events, whose user message may never be admitted either). A tool still streaming or running in a finished round once a later `session.step.started` reduced (`reconcileStrandedRoundTools`, hooked after both the direct emit and the queued replay, where the scan runs at the task boundary between replay chunks) lost its terminal event mid-execution: the loop feeds every tool result back before it continues, so waiting for the settlement read would keep its spinner live through later rounds (and a quickly following execution would suppress that repair). That reconcile and every settlement read share one in-flight reconciliation per transcript (`settlementReadPending`); covered by `opencode-data-settlement.test.ts`. Token/cost lines (`components/message-usage.tsx`) appear once per agent message: the row of an assistant message's final text (the one carrying "delete tools and reasoning") renders, once that message has native usage, the sum (`sumMessageUsage`) of its own usage and of every message holding a tool or reasoning part that cleanup selects (`technicalCleanupParts`). Reuse that selection rather than a separate projection. The line renders inside the content row, so it never shifts `` items or splits a technical group (whose Delete needs two tools); tool-only steps get no line. A message whose text is followed by tools also counts in the next message's line, as its tools belong to that selection. Sums cover the loaded transcript window only, like cleanup. Capture real streams with `scripts/test-session-lifecycle-native.mjs`. - Native transcript events reduce only through `stores/opencode-data.ts` (never add another partial-part reducer), which publishes bounded snapshots through `hydrateMessages` (message-v2/instance-store.ts); these per-event re-projections must not invalidate unchanged messages: `hydrateMessages` reuses the resident `MessageRecord` object whenever content, explicit timestamps and prompt-display metadata are unchanged, and an identical whole snapshot returns before any store write or session-revision bump. Part/info comparisons use allocation-free structural equality (`partDataEqual`), never `JSON.stringify`. The SDK reduce mutates rows in place, so reference identity can never prove a session unchanged — never add a reference-anchored projection skip. A session's reducer is replaced (authoritative resync after an overflow, rotation failure or reconnect; pruning invalidation) only through `replaceTranscriptEntry`, which bumps the transcript's `entryRevision`; reactive readers of the reducer, such as the inbox behind queued badges (`getOpenCodeSessionInbox`), track it so they rebind instead of keeping the disposed reducer's last state (`opencode-inbox-rebinding.test.ts`, `tests/browser/session-rendering.test.ts`). diff --git a/dev-docs/UI_SHELL.md b/dev-docs/UI_SHELL.md index 39193f5b1b..eebe645406 100644 --- a/dev-docs/UI_SHELL.md +++ b/dev-docs/UI_SHELL.md @@ -23,9 +23,8 @@ Panel toggles, floating drawers, project/right-panel tabs, the session sidebar a - Project and right-panel tabs share `components/tab-scroll.tsx` and `styles/components/tab-scroll.css`. Keep their native scrollbar above upright content without mirrored transforms, negative border overlaps or permanent compositing hints. Validate shared scrollbar styling and adjoining edges at fractional zoom in the browser and isolated Electron renderer fixtures (`tests/browser/tab-chrome.test.ts`). - The Status tab starts with the shown session's goal line (`components/session/session-goal-line.tsx`, `styles/panels/status-goal.css`) only while that session has a `/goal`: one row above the sections with the status badge (`.session-goal-badge` in `styles/components/badges.css`), the objective truncated with its full text and the reason in its tooltip (the reason is also the row's accessible description), the rounds, one Pause/Resume button that keeps focus as the status flips, and Clear. While a command runs its actions are `aria-disabled` and ignore activation, never `disabled`, so the focused button keeps keyboard focus. Never add it to `CORE_STATUS_SECTION_ITEMS` or the right-panel customization, and never show a hint, empty state or gap without a goal. Contract, commands and freshness: [OPENCODE_COMPATIBILITY.md](OPENCODE_COMPATIBILITY.md) (Session goal). Validate with `tests/browser/session-goal.test.ts`. - Built-in right-panel tabs are constructed directly in `right-panel/core-runtime.tsx` (never add a first-party plugin loader for them); external sandboxed panels keep their independent consent/loading path. -- Integration Status sections are registered by `right-panel/integration-status-module.tsx` under stable `integration:` IDs, in catalog order after Plugins. Saved order and hidden IDs retain absent sections; dragging moves only the source, and Up/Down in customization uses the same ordering for every section. Stable section objects preserve focused DOM across refreshes. Expected-action changes expand once, respecting subsequent user collapse. One attachment owner and one grouped polite live region belong to each Status tab; disappearing focused sections hand focus to the Plugins accordion trigger. Conversation attachment controls and binding labels live exclusively in these sections. - Embedded floating session drawers use `instance/shell/HostedDrawer.tsx` so their SUID modal roots are direct children of the existing geometry host. A Solid Portal wrapper must not become an ARIA-hidden ancestor of visible controls. Preserve SUID's modal stacking, sibling isolation, focus policy, Escape/backdrop handling and scroll restoration; validate with `tests/browser/drawer-accessibility.test.ts` rather than overriding ARIA or disabling modal enforcement. -- Floating-panel outside-pointer and Escape dismissal leave ARIA menus, listboxes and dialogs to their own selection/dismissal handlers (`shell/drawer-events.ts`). Their portals are outside the drawer DOM, and closing the drawer on pointerdown destroys a menu before touch pointerup selects its action. Both the shell's capture listener and SUID's Escape policy defer to nested surfaces; focus and isolation stay with SUID. Keep this guard shared in the shell, not in individual menu actions; validate the real session Delete confirmation with `tests/browser/session-delete.test.ts` and Status menus with `tests/browser/integration-attachment.test.ts`. +- Floating-panel outside-pointer and Escape dismissal leave ARIA menus, listboxes and dialogs to their own selection/dismissal handlers (`shell/drawer-events.ts`). Their portals are outside the drawer DOM, and closing the drawer on pointerdown destroys a menu before touch pointerup selects its action. Both the shell's capture listener and SUID's Escape policy defer to nested surfaces; focus and isolation stay with SUID. Keep this guard shared in the shell, not in individual menu actions; validate the real session Delete confirmation with `tests/browser/session-delete.test.ts` and Status menus with `tests/browser/integration-plugin-row.test.ts`. - Each side panel has exactly one open/close control: `instance/shell/ShellPanelToggle.tsx` (`PanelLeft`/`PanelRight`, `.icon-toggle` with `aria-expanded`/`aria-controls`), absolutely placed at the shell's outer header corners (`--space-xs` from the window edge) in `.session-shell-frame`, outside the drawer host so modal sibling isolation never hides it, and above floating drawers. The frame is an isolated stacking context: toggles stay above in-frame drawers but below body-portaled dialogs, scrims and utility windows. Both toggles precede the shell content in tab order and use the fixed View-menu labels (`window.menu.leftPanel`/`rightPanel`) with `aria-expanded`, never an Open/Close label flip. They are strictly fixed: no horizontal or vertical movement between docked, floating and closed states in any layout; the sidebar header, right-panel tab bar (both edges when floating) and the conversation header (`data-{left,right}-toggle-reserve`) reserve their footprint instead. Every header's action row (session list header row, right-panel `.tab-strip-shortcuts`, conversation side groups and status indicators, with or without the title row) and the toggles centre on one shared line, `--panel-header-action-center` in `styles/tokens.css`; never measure per-state offsets. The session list header holds a single action row; never add a keyboard-shortcut footer below the session list. Opening one floating drawer closes the other; the outside-pointer handler ignores the toggles. Styles live in `styles/panels/shell-panel-toggles.css`; validate with `tests/browser/shell-navigation.test.ts`. - Each side panel keeps whether the user wants it (opened, or closed while docked) and docks while the window has its room, in a fixed order: the session panel first, the right panel only beside it (`instance/shell/useDrawerChrome.ts`, `drawer-layout.ts`). Narrowing shrinks the conversation to its minimum, then the right panel to its minimum, where it hides, then the left panel to its minimum, where it hides: each panel hides at the end of its own compression, so the other never changes width at that moment and only the conversation takes the room. A hidden wanted panel returns with the room, so the layout follows the window width alone, narrowing and widening alike (a minimizing window's tiny viewport included). A panel opened without room floats over the conversation; dismissing it keeps the docked choice, and it docks once it has room. On touch tablets each orientation remembers the wanted panels. A panel hidden by the layout hands focus to its toggle when it last held focus, even when the focused control already left the DOM. Choosing from the floating session panel's list closes that panel, the shown session included; Back/Forward keep it open. Validate with `tests/browser/shell-navigation.test.ts`, whose narrowing/widening sweep requires panels never to grow back or reappear while narrowing and widening to retrace the same layouts. - The session sidebar header groups Back/Forward beside the leading fixed panel toggle, centres Sessions between navigation and trailing New session/Search, and truncates the title at narrow widths. Back/Forward (`ArrowLeft`/`ArrowRight`, mirrored in RTL; history wording "Back"/"Forward" with conversation tooltips, distinct from the palette's Previous/Next Session list cycling) use a browser-like in-memory history per project tab and window (`stores/session-navigation-history.ts`, `instance/shell/useSessionNavigationHistory.ts`, at most 50 entries). It records every displayed conversation whatever selected it; the no-session draft stays outside the history (Back first returns to the cursor entry). Navigating moves the cursor and selects through the ordinary `handleSessionSelect` path without pushing; a new selection truncates the forward stack; unavailable/deleted sessions are skipped and determine the disabled states. Do not add keyboard shortcuts or persistence to this history. diff --git a/dev-docs/architecture.md b/dev-docs/architecture.md index 9864684d31..7a15c67e9b 100644 --- a/dev-docs/architecture.md +++ b/dev-docs/architecture.md @@ -44,6 +44,8 @@ Remote windows are never restored, and the user can always reach a working local - A local window showing a page that does not run the application (loading, sign-in, pairing, `/auth/*`) closes and lets CodeNomad quit without waiting for a client-state flush it could never answer (Electron `isListenerlessDocument` in `renderer-client-state-flush.ts`, Tauri `awaits_renderer_flush` over `is_listenerless_document`). - A remote window whose server cannot be loaded keeps a way back. Electron loads its own loading page with `#remote-unavailable=` (`lib/native/remote-unavailable.ts`): **Try again**, **Open a local window** and **Close window** (`remote:retry`, `remote:openLocalWindow`). `RemoteRecoveryPages` and `showRemoteUnavailable` (`electron/main/remote-recovery.ts`) load a new document for every token (a `recovery` load counter in the query, so a Try again whose load commits nothing, such as HTTP 204, still replaces the page) and authorise a request only from the registered remote window's main frame with that token and the origin bound once by that load's own commit. Any later main-frame commit or a renderer crash revokes the token for good. The window remembers its revoked recovery documents (up to 16), so when the user brings one back (native Reload, also after a crash, or history) its commit shows a fresh document with a fresh token; a crash itself never reloads. A URL the page can rewrite (History API) is never the authority; `remote-recovery.test.ts` checks this through real Electron IPC. Tauri remote windows show WebView2's error page with its reload button, their native title bar and File menu. +A plain browser tab, including an installed PWA, keeps the same V1 client snapshot in its own `sessionStorage` (`lib/web-session-client-state.ts`, selected by `lib/native/client-state.ts`): every tab is primary, a reload or mobile page discard restores its projects, sessions, drafts and scroll positions, and a new tab session starts empty. Layout values keep their shared, immediately written `localStorage` entries outside that snapshot, and Clear leaves them. Its Restore previous state switch is remembered for the tab; a refused write (quota) fails only that save, so later saves retry and Clear stays available. Web restoration only rebinds workspaces the backend still lists and never creates one. Saved workspace tabs carry their record id, matched before the folder occurrence, which shifts when another client closes a sibling record of the same folder. Desktop remote windows keep no client state. + OpenCode sessions and messages are shared through the global daemon. Window membership, tabs, drafts, view state, and native bounds are local to each UUID window. Client-state V3 is a per-window envelope over the V2 SHA-256 content-addressed partition graph: immutable partitions are prepared before atomic root publication, writes and migrations are fenced by current ownership and renderer authority, and garbage collection runs after publication while retaining every partition referenced by any window. Electron and Tauri local windows load credential-free HTTP(S) preview pages directly in hardened native child views: Chromium, WebView2 (Windows), WKWebView (macOS 14+) or WebKitGTK (Linux). Cookies and localStorage persist in one preview store per profile/configuration, separate from the trusted app renderer and remote windows. Documents and native navigation histories remain session-owned. Tauri's shared `embedded_view.rs` layer owns creation, storage, geometry, visibility, overlay masking and mandatory navigation/permission/download/new-window guards; `browser_controller.rs` retains session registrations and browser behavior. Primary `local-*` webviews alone receive application capabilities. Native preview element comments are unavailable. Agent browser automation supports Electron and Tauri Windows/macOS/Linux. WebKit presets fit CSS viewports and apply mobile identity, with native density and input limits described in [Device profiles](BROWSER_DEVICE_EMULATION.md). See [Native Hosts](BROWSER_AUTOMATION.md#native-hosts) for the common contract and remote-project-tab adoption. @@ -254,6 +256,7 @@ Run `node --import tsx packages/ui/tests/contracts/backend-async-inventory.ts > | `stores/app-session-workspace-hydration.ts` | A+P | hydrateRestoredWorkspaceState | Attachment captured before either hydration; caller logical AbortSignal retains identity through SDK reads, with attachment/binding-current checks between stages and private composed queue cancellation. | | `stores/instances.ts` | A+C | workspace create/ready/attach/hydrate; project/worktree/session/catalog/config hydration; refreshWorkspaceList/initializeWorkspaces; volatile native resync; pending snapshots/forms/permissions/inboxes/liveness; timeout/retry/queue continuations; close/delete/release/cancel/restore cleanup; Yolo read/toggle | Hydration captures signal/client before enqueue and propagates signal through worktree/session/project/supplemental metadata/pending reads, checking before config/pending follow-ups. Descriptor mapping resolves environment preferences on the explicit backend; preference initialization retains that store's attachment authority. Runtime operations combine captureBackendOperation, client/native generation, pending token/controller/request identity; sent creation/close/Yolo/form/permission mutations retain their client/request owner while runtime projection/readback uses A. Direct and observation-triggered creation cancellation share one bounded flight on the captured request/API/attachment through AbortCreatedWorkspaceCleanup; confirmed settlement fences subsequent dispatch, and exhausted flights permit a later explicit demand. | | `stores/app-tabs.ts` | C | select created tab → captured claim release; close tab → closeWorkspace | Tab occurrence identity; an explicit creation lease is checked before attachment and selection, then releases its exact request/API/attachment. Dispatched release/deletion retains its captured client ownership. | +| `stores/closed-workspace-drafts.ts` | C+V | closed-project draft handoff; wait for session hydration; restore saved session chains | Backend/folder identity isolates the bounded vault. A consumed claim and current-instance predicate fence asynchronous hydration; existing occurrence state and touched sessions win. Delegated session reads retain their backend authority; placeholder Close requires the exact saved occurrence. | | `stores/temporary-instances.ts` | C | open/keep/discard/close temporary instance; abandon on failed open; recent-folder persistence | Temporary workspace/creation identity and retained local API client; backend-filtered lifecycle cleanup. | | `stores/worktrees.ts` | A+C | queueWorktreeRequest/load/ensure/reload; ready handler → sessions; create/delete/moveSessionFamily; parent-session slug changes; uncertain family-move reconciliation | captureBackendOperation/signal, client/native generation/folder and request lane; compatible coalescence and owned finally. Sent create/delete/move retains client/request ownership; invalidation, session/worktree readback and move-result projection check the captured A and owned move record. | | `lib/hooks/use-instance-metadata.ts` | A | loadInstanceMetadata/loadInstanceProjectMetadata; project/location/MCP parallel reads | Entry composes signalForInstance with caller signal and refuses aborted admission; SDK reads receive the signal. Client/location/metadata generation/pending identity govern coalescence and publication; finally releases only the matching request. | @@ -365,9 +368,10 @@ Run `node --import tsx packages/ui/tests/contracts/backend-async-inventory.ts > | `components/provider-auth/provider-accounts.tsx` | A+C | read; setAutomatic; activate/remove/update/rename/select credential/account | captureBackendOperation, view controller/disposed/current and location/client; persisted credential/account mutations retain admitted client. | | `components/provider-auth/provider-model-visibility-manager.tsx` | C | single/provider model visibility changes | Serialized persisted preference writes in preferences store; UI focus microtask separate. | | `components/session/provider-usage-panel.tsx` | A | usage interval/manual refresh and source change | captureBackendOperation with client/generation/current; view-owned polling timer. | -| `components/integration-attachment.tsx` | A+C | demand binding; open offers; attach/detach; delayed reconciliation | Action captureBackendOperation with controller/epoch/generation/current/disposed; bindingDemand memo tracks view identity/catalog IDs while the binding store retains/rebinds demand across attachment change; reactive signal effect closes obsolete offers; sent mutation has target/request owner. | +| `components/integration-row-binding.ts` | A+C | demand binding; passive open-document reads; named-document activation; attach/detach | Action captureBackendOperation with controller/epoch/generation/current/disposed; binding demand tracks view identity/catalog IDs while the binding store retains/rebinds demand across attachment change; passive offers acquire the row's current attachment and controller; reactive signal effects clear obsolete offers; sent mutation has target/request owner. | +| `components/integration-state-line.tsx` | P | application installation, attachment, detach and offer selection | Delegated installation/row-binding handlers retain captured action, offer and attachment authority. | | `components/integration-host-installation.ts` | A+C | open installation/consent workflow | captureBackendOperation, epoch/controller/generation/disposed/current; submitted install retained. | -| `components/integration-section.tsx` | P | plugin controls load; catalog refreshDemanded; attachment open/detach; installation open; external URL | Delegated controls/catalog/binding request owner; attachment/installation handlers capture A; external URL is native IPC. | +| `components/plugin-activation-controls.tsx` | P | integration binding and application installation from Plugins rows | Delegated binding/installation handlers capture backend attachment and exact Location/session; row disposal and invalidation revoke pending consent. | | `components/session/session-goal-line.tsx` | P | runSessionGoalCommand | Session goal demand and delegated session-action attachment authority. | | `components/mission-tracking.tsx` | P | onOpenActor callback | Captured actor/selected Mission view; parent navigation callback owns session hydration. | | `components/mission-schedule-list.tsx` | P | controls.act/reconcile | Delegated schedule controls attachment/current and durable mutation receipt. | @@ -386,7 +390,8 @@ Run `node --import tsx packages/ui/tests/contracts/backend-async-inventory.ts > | `components/message-item.tsx` | A+C | attachment download; copy; delete technical parts | Attachment resource fetch and selected message identity; deletion uses captureBackendOperation/current; clipboard/download owns resource lifecycle. | | `components/message-section.tsx` | A | restore/loadMore/copy selection/pageWindow/locate; ranked search and cursor windows | captureBackendOperation plus controller, view/session generation/current and signalForInstance; per-page operation retained. | | `components/tool-call/renderers/task.tsx` | A | child-message demand/load; child transcript copy | captureBackendOperation/current; caller signal passed to child-message reader. | -| `components/markdown.tsx` | A+V+COMPUTE | renderSnapshot/highlighter import; local-image candidates; open preview/external link; metadata read | Render request/disposed/current and deferred-render timer; instance-owned preview and project metadata demand; mounted media source owners fence body reads and revoke blobs; rendering is local. | +| `components/markdown.tsx` | A+V+COMPUTE | renderSnapshot/highlighter import; local-image candidates; route session/external links; metadata read | Render request/disposed/current and deferred-render timer; instance-owned preview and project metadata demand; mounted media source owners fence body reads and revoke blobs; rendering is local. | +| `components/markdown-session-links.ts` | A+V | open session preview or project-file reader | Instance-owned backend attachment and projectScope select preview state; current attachment gates routing and fences late preview errors; worktree/session directory resolves file paths. | | `components/version-pill.tsx` | C | metadata read | Retained server metadata client/cache. | | `components/mission-briefing.tsx` | A+C | ask coordinator | captureBackendOperation, client/generation/current; delegated admission/send mutation. | | `components/mission-cleanup.tsx` | A+C | retry: reread Mission → delete | captureBackendOperation/current, request ID; durable cleanup transaction retained. | @@ -418,6 +423,7 @@ Run `node --import tsx packages/ui/tests/contracts/backend-async-inventory.ts > | `components/settings/remote-access-settings-section.tsx` | C | refreshMeta/toggleExpanded/allow-connections/password submit | Local admin client and auth/settings request state; durable server configuration. | | `components/settings/remote-control-settings-section.tsx` | C | load/refresh/poll; start/stop/previews; pairing/create/copy/revoke | Retained local server administration client; view cleanup/current polling state; durable device/control mutations. | | `components/settings/sidecars-settings-section.tsx` | C | create/delete SideCar | Retained local SideCar API client; durable server mutation and SideCar reload. | +| `components/settings/sidecars-direct-https-card.tsx` | C | read serving-backend metadata; set host SideCar HTTPS opt-in | Serving-backend local-request metadata gates the card; the local server preference document queue owns its mutation. Project-backend selection leaves this host-only control unchanged. | | `components/settings/opencode-setup-panel.tsx` | C | install/restartForTroubleshooting | Local bootstrap/setup client; component disposed/current guard. | | `components/settings/preferences-project-context.ts` | A | backend admission; owner workspace list; coalesced project refresh | Qualified instance key and durable server identity; captureBackendOperation plus view/controller/epoch/disposed/current; scheduler callback signal. Missing and replacement owners stay inactive. | | `components/settings/usage-settings-section.tsx` | A | load; owner discovery/cached usage/fresh usage; coalesced event refresh | captureBackendOperation, epoch/disposed/current and signal; verified owner/identity/connection tuple and freshEpoch fence. | @@ -527,3 +533,4 @@ Server entrypoints are `packages/server/src/index.ts` and `server/http-server.ts ## Agent conventions - SideCar proxy cookies use `sidecars/proxy-cookies.ts`: authenticate locally first, then remove the actual auth cookie, the `codenomad_session` desktop namespace and paired-device cookie upstream; filter the same names from HTTP and WebSocket response cookies, preserving service cookies. Handshakes go through Node's bounded HTTP parser in `server/proxy-websocket.ts`, including non-101 responses and coalesced binary data. Same-origin SideCar scripts keep full application access: SideCars are trusted extensions by design. +- SideCar content and WebSockets are host-only on the direct listener. The one exception is the host's `server.sidecarsOverDirectHttps` opt-in for authenticated requests from a verified direct HTTPS origin (`server/sidecar-direct-https.ts`, rule in `remote-control/direct-https.ts`); keep every other host-only path loopback-only and never widen the origin rule here ([REMOTE_CONTROL.md](REMOTE_CONTROL.md#admission)). diff --git a/docs/help/de/browser-sidecars.md b/docs/help/de/browser-sidecars.md index 99f391f997..1031e4b3c5 100644 --- a/docs/help/de/browser-sidecars.md +++ b/docs/help/de/browser-sidecars.md @@ -77,7 +77,7 @@ Prüfen Sie bei Nichterreichbarkeit Prozess und Port auf dem Backend. Lädt HTML Ein SideCar ist eine vertrauenswürdige Erweiterung von CodeNomad, keine Vorschau in einer Sandbox: Seine Seite läuft unter dem eigenen Origin von CodeNomad, sodass seine Skripte CodeNomad mit Ihrem angemeldeten Zugang nutzen können. Registrieren Sie nur Dienste, deren Code Sie vertrauen. CodeNomad leitet seine eigenen Anmelde-Cookies nicht an den Dienst weiter, während die eigenen Cookies des Dienstes erhalten bleiben. -SideCar-Inhalte (`/sidecars/`) und SideCar-WebSockets erfordern eine Loopback-Verbindung auf dem Host. Die Registrierung über `/api/sidecars` ist für gekoppelte Geräte und authentifizierte direkte LAN-Clients verfügbar. Inhalte aktiver Vorschauen (`/previews/`) sind mit einem gültigen Berechtigungstoken über direkten LAN-Zugriff verfügbar; Web-Vorschauen der [Fernsteuerung](remote-control.md#remote-surface) bleiben mit ihrem Berechtigungstoken verfügbar, solange sie aktiviert sind. Anforderungen für den Direktzugriff stehen unter [Aktualisieren](remote-access.md#upgrading). +SideCar-Inhalte (`/sidecars/`) und SideCar-WebSockets erfordern eine Loopback-Verbindung auf dem Host. Um sie auch von anderen Geräten zu öffnen, aktivieren Sie auf dem Host **SideCars über HTTPS öffnen** unter **Einstellungen → SideCars**: Browser, die über die HTTPS-Adressen dieses Servers oder einen HTTPS-Origin aus `CODENOMAD_ALLOWED_ORIGINS` angemeldet sind, etwa hinter einem TLS-Reverse-Proxy, können dann SideCars öffnen. Einfaches HTTP, `localhost`-Adressen und die Fernsteuerung bleiben dem Host vorbehalten. Die Registrierung über `/api/sidecars` ist für gekoppelte Geräte und authentifizierte direkte LAN-Clients verfügbar. Inhalte aktiver Vorschauen (`/previews/`) sind mit einem gültigen Berechtigungstoken über direkten LAN-Zugriff verfügbar; Web-Vorschauen der [Fernsteuerung](remote-control.md#remote-surface) bleiben mit ihrem Berechtigungstoken verfügbar, solange sie aktiviert sind. Anforderungen für den Direktzugriff stehen unter [Aktualisieren](remote-access.md#upgrading). ## OpenVSCode-Server-Rezept {#openvscode} diff --git a/docs/help/de/conversations.md b/docs/help/de/conversations.md index 7bfd54f6e6..067b961f48 100644 --- a/docs/help/de/conversations.md +++ b/docs/help/de/conversations.md @@ -60,6 +60,12 @@ Auf dem Desktop verschiebt Senden den Tastaturfokus in die Unterhaltung, sodass Entwürfe sind clientseitiger Arbeitszustand, keine gemeinsamen nativen Nachrichten. Die Startwiederherstellung kann unterstützten Eingabezustand behalten; behandeln Sie einen ungesendeten Entwurf oder Anhang aber nicht als Sicherung und nehmen Sie nicht an, dass er auf einem anderen Gerät erscheint. Sichern Sie wichtigen Text vor dem Löschen von Startdaten oder dem Schließen eines Clients mit deaktivierter Wiederherstellung; siehe [Desktop](desktop.md). +## Dateien aus Antworten öffnen {#open-files-from-replies} + +1. Agent-Antworten verlinken Projektdateien mit relativen und absoluten Pfaden. +2. Ein einfacher Klick öffnet die verlinkte Datei in der Dateivorschau, gelesen aus dem Worktree der Unterhaltung. +3. Klicks mit Zusatztasten (Strg/⌘-Klick, Umschalt-Klick, Mittelklick) und Links außerhalb des Session-Worktrees behalten das normale Linkverhalten. + ## Befehle und Shell-Modus {#commands-shell} 1. Geben Sie `/` ein, wählen Sie einen gefundenen benutzerdefinierten Befehl und geben Sie dessen Argumente an. diff --git a/docs/help/de/install.md b/docs/help/de/install.md index 0846766cdf..c5d2797307 100644 --- a/docs/help/de/install.md +++ b/docs/help/de/install.md @@ -45,7 +45,7 @@ Die Electron-Debian-Installation richtet die Chromium-Sandbox ein. Deaktivieren | Anforderung | Wo sie verfügbar sein muss | Aktuelle Anforderung | | --- | --- | --- | -| OpenCode-CLI | Ausgewählter Ausführungshost, gegebenenfalls einschließlich der ausgewählten WSL-Distribution | Mindestens **2.2.3**; **2.2.7** ist das empfohlene/qualifizierte Ziel. Neuere oder angepasste Versionen werden anhand der Schnittstellenverträge geprüft, nicht wegen fehlender Tests ausgeschlossen. | +| OpenCode-CLI | Ausgewählter Ausführungshost, gegebenenfalls einschließlich der ausgewählten WSL-Distribution | Mindestens **2.3.0**; **2.3.0** ist das empfohlene/qualifizierte Ziel. Neuere oder angepasste Versionen werden anhand der Schnittstellenverträge geprüft, nicht wegen fehlender Tests ausgeschlossen. | | Git | Im `PATH` des CodeNomad-Backend-Kontos | Erforderlich für Repository-Identität, Git-Vorgänge und Worktrees. | | Node.js/npm | Host für eigenständigen Server und Quellcode-Builds | Node.js 24 LTS; reproduzierbare Quellcode-Builds verwenden die in `.node-version` festgelegte Version. Desktop-Releases bringen ihre eigene Laufzeit mit: das integrierte Node von Electron oder das gebündelte Node von Tauri, jeweils mit npm. | | Arbeitsbereichsordner | Für das Backend zugänglicher Datenträger | Ein ausdrücklich geöffneter physischer Ordner, kein von einem Remote-Browser angenommener gerätelokaler Ordner. | diff --git a/docs/help/de/integrations.md b/docs/help/de/integrations.md index 5359938d42..daecd92129 100644 --- a/docs/help/de/integrations.md +++ b/docs/help/de/integrations.md @@ -27,7 +27,7 @@ Erscheint kein Server, prüfen Sie aktive Location und native Konfiguration. Pr Von CodeNomad verwaltete Plugins erscheinen außerhalb der gewöhnlichen Plugin-Liste und ihrer Aktivierungs-, Aktualisierungs- und Entfernungsaktionen. CodeNomad erkennt sie am validierten Installationseintrag und am Speicherort ihres inhaltsadressierten Codes; ein Drittanbieter-Plugin mit gleichem Namen oder gleicher ID behält seine gewöhnlichen Bedienelemente. -Ist ein verwaltetes Plugin deaktiviert, schlägt sein Laden fehl oder bleibt das Laden unbestätigt, erscheint **CodeNomad-Plugins erfordern Aufmerksamkeit** oberhalb der Plugin-Liste. Öffnen Sie seine Schaltfläche **i** (**Details zu** diesem Plugin), um den verfügbaren Fehler und die Referenz im OpenCode-Protokoll zu sehen. Nur deaktivierte Plugins bieten **Erneut aktivieren**: Die Aktion ergänzt eine positive Aktivierungsregel für die exakte ID und erhält die deaktivierende Regel. Sie schreibt im Bereich **Global** oder **Projekt** der deaktivierenden Regel, sofern dieser beschreibbar ist, andernfalls in **Projekt**. OpenCode läuft weiter; die Warnung bleibt, bis native Ereignisse oder **Plugin-Steuerung aktualisieren** das Plugin als aktiv bestätigen. +Ist ein verwaltetes Plugin deaktiviert, schlägt sein Laden fehl oder bleibt das Laden unbestätigt, erscheint **CodeNomad-Plugins erfordern Aufmerksamkeit** oberhalb der Plugin-Liste. Öffnen Sie seine Schaltfläche **i** (**Details zu** diesem Plugin), um den verfügbaren Fehler und die Referenz im OpenCode-Protokoll zu sehen. Nur deaktivierte Plugins bieten **Erneut aktivieren**: Die Aktion entfernt die exakte deaktivierende Regel des Plugins aus dieser Datei, wenn das allein es wieder aktiviert, und ergänzt sonst eine positive Regel für die exakte ID. Sie schreibt im Bereich **Global** oder **Projekt** der deaktivierenden Regel, sofern dieser beschreibbar ist, andernfalls in **Projekt**. OpenCode läuft weiter; die Warnung bleibt, bis native Ereignisse oder **Plugin-Steuerung aktualisieren** das Plugin als aktiv bestätigen. Die Warnung und ihre Details kennzeichnen den Konfigurationsursprung gegebenenfalls als **Geerbt / extern** oder **Virtuelle Konfiguration**. Eine separate Angabe **Projekt** bezeichnet das Ziel der erneuten Aktivierung, wenn es vom Ursprung der deaktivierenden Regel abweicht. @@ -38,7 +38,7 @@ Die Warnung und ihre Details kennzeichnen den Konfigurationsursprung gegebenenfa Global zielt auf die gefundene globale Konfiguration des verbundenen Daemons. Projekt zielt auf die Konfiguration innerhalb der aktiven Location, nicht auf eine geerbte übergeordnete Datei. Eine spätere Projektregel kann Global übersteuern; der globale Schalter zeigt weiterhin die globale Regel, statt den endgültigen Projektzustand vorzutäuschen. Ohne Projektregel erbt Projekt den aufgelösten globalen Zustand. -Diese Schalter ergänzen exakte Aktivierungsregeln und bewahren Quelldeklarationen sowie unabhängige Konfiguration. Sie bearbeiten keine Plugin-Optionen, installieren keine Pakete und entfernen keine Dateien. Integrierte OpenCode-Plugins werden nicht als Benutzeraktivierungsschalter angeboten. Projekt ist deaktiviert, wenn sein Ziel nicht sicher von Global getrennt werden kann oder die aktive Location verlassen würde. +Jeder Schalter schreibt eine exakte Aktivierungsregel für das Plugin in die Datei seines Bereichs und ersetzt dort frühere exakte Regeln dieses Plugins oder entfernt sie nur, wenn das dasselbe Ergebnis ergibt. Quelldeklarationen, breitere Regeln wie `*` und unabhängige Konfiguration bleiben erhalten. Sie bearbeiten keine Plugin-Optionen, installieren keine Pakete und entfernen keine Dateien. Integrierte OpenCode-Plugins werden nicht als Benutzeraktivierungsschalter angeboten. Projekt ist deaktiviert, wenn sein Ziel nicht sicher von Global getrennt werden kann oder die aktive Location verlassen würde. Eine Paketaktualisierung ändert dieses Paket im gemeinsamen Cache von OpenCode für jede Location, die es verwendet, wie sein Tooltip angibt; sie ändert keine Aktivierungsregeln, startet OpenCode nicht neu und lädt keine Konfiguration neu. Lokale, integrierte und vom SDK bereitgestellte Plugins haben keine Paketaktion. Ein Paket, das vor dem Melden seiner Plugin-ID scheitert, wird unter seinem Paketnamen aufgeführt, mit dem Fehler in seinem Tooltip und Prüf-/Aktualisierungsaktionen, aber ohne Aktivierungsschalter. Eine fehlgeschlagene Prüfung oder Aktualisierung wird gemeldet und nie automatisch wiederholt. @@ -78,38 +78,30 @@ Die Skill-Verfügbarkeit kommt aus der Location der Unterhaltung, nicht aus eine Befehle werden von OpenCode für die aktive Location ermittelt. Ihre eigene native Definition kann das Ausführungsverhalten bestimmen; das Menü ist weder Paketinstallation noch uneingeschränkter Konfigurationseditor. CodeNomad wendet vor nativen benutzerdefinierten Befehlen die Sitzungsumgebung des Profils an; ein fehlgeschlagenes Umgebungsupdate blockiert das Senden. `/btw` ist CodeNomads separater flüchtiger Frageablauf, kein normaler benutzerdefinierter Befehl. Befehlsdefinitionen und native Konfigurationsvererbung erläutert die [OpenCode-Befehlsdokumentation](https://opencode.ai/v2/docs/commands/). Aktualisieren/öffnen Sie nach Konfigurationsänderungen zuerst die relevante Oberfläche erneut; verwenden Sie explizites Konfigurationsneuladen nur, wenn die Laufzeit es noch benötigt. Wiederholen Sie niemals einen möglicherweise angenommenen Befehl allein zum Aktualisieren seiner Anzeige. -## Integrationsabschnitte in Status {#integration-sections} +## Integrationen in Plugins {#integration-rows} Unter **Status → Plugins** öffnet **+** die Auswahl **Integration hinzufügen…** oder **Plugin hinzufügen…**. Die Integrationsauswahl enthält nicht installierte Einträge des geprüften Katalogs. Wählen Sie den Bereich und **Installieren**: CodeNomad installiert die gewählte Katalog-ID. Native Integrationen verwenden **Nur global**. **Katalog nicht verfügbar** bietet **Aktualisieren**; **Katalog vom {date}** kennzeichnet den letzten gültigen, veralteten Katalog. -Jede erkannte Integration mit einer Deklaration oder einem geladenen/fehlgeschlagenen Plugin hat einen eigenen Abschnitt in **Status**, auch deaktiviert oder während der Installation. Eine mehrdeutige Quelle zeigt **Nicht konform** in Plugins. Jede Integration behält ihre Plugins-Zeile mit Aktualisieren, Entfernen und Statusaktualisierung. Klappen Sie den Abschnitt auf, um Version und Plugin-Steuerung im Inhalt zu sehen. Name und Status bleiben im Kopf neben **Dokumentation** und **i** sichtbar. Das **i**-Popover zeigt Details auf Anfrage: mit Eingabe/Leertaste öffnen, mit Escape schließen. +Eine erkannte Integration hat eine Zeile unter **Status → Plugins**, mit ihrem Namen (zum Beispiel **OpenCode for Blender**) und ihrer Version. Ihre Schalter **Global** und **Projekt** tragen wie die übrigen Schalter die Akzentfarbe, die eines einfachen Plugins sind grün; eine Integration mit einem Teil in einer Anwendung ist **Nur global**. Zeigen Sie auf ihren Namen: Die Details beginnen mit **Integration** statt **Plugin**; Screenreader lesen sie als Beschreibung der Zeile vor. Eine mehrdeutige Quelle zeigt **Nicht konform**. -Über die Status-Anpassung lassen sich alle Statusabschnitte ausblenden und per Ziehen oder mit den Tasten Auf/Ab umordnen. Sichtbarkeit und Reihenfolge bleiben bei Neuladen und vorübergehend fehlenden Integrationen erhalten. Verschwindet ein fokussierter Abschnitt, kehrt der Fokus zu Plugins zurück, oder zu einem anderen sichtbaren Statusabschnitt, wenn Plugins ausgeblendet ist. +Unter dem Namen zeigt eine Statuszeile immer, wo die Integration steht. Grauer Text informiert; Text in der Akzentfarbe ist eine Schaltfläche. Bei einer Integration mit einem Teil in einer Anwendung erscheint der wichtigste Zustand: **In Blender installieren** oder **Blender aktualisieren**, wenn ihr Teil fehlt oder veraltet ist (mit der Installationsbestätigung), eine Inkompatibilität in der Warnfarbe, ein Kettensymbol und das Dokument, wenn die angezeigte Unterhaltung verbunden ist (zum Trennen auswählen), **Blender geschlossen**, **Blender: kein geöffnetes Dokument**, **Keine Unterhaltung angezeigt**, dann **verbinden** mit dem Dokumentnamen oder **Verbinden…**, um zwischen mehreren Dokumenten zu wählen. Eine Unterhaltung verbindet sich außerdem selbst, sobald ihr Agent die Integration zum ersten Mal verwendet. Editor-MCP-Integrationen zeigen **Server erkannt** oder **Server nicht gefunden**, API-Integrationen **Verbunden** oder **Getrennt**. Ein langer Zustand wird gekürzt; zeigen Sie darauf, um den vollständigen Text zu sehen. Von der Integration gemeldete Änderungen und Neuverbindungen aktualisieren die Zeile. -Kataloginstallation, Installation/Aktualisierung des Anwendungsteils, Verbinden und Entfernen erfordern eine Bestätigung. **Abbrechen** erhält zuerst den Fokus; die Bestätigungsaktion wird nach 600 ms verfügbar. Aktivierung und Plugin-Updates werden direkt ausgeführt. +Das Menü **…** der Zeile beginnt mit dem Verbindungsstatus, zum Beispiel **Blender: 1 geöffnetes Dokument** oder **Blender geschlossen**. Danach bietet es **Dokumentation**, **In Anwendung installieren…**, **Anwendung aktualisieren…** oder **In Anwendung neu installieren…** ([siehe unten](#application-installation)), die Update-Prüfung des Pakets, **Aus Global entfernen** oder **Aus Projekt entfernen** und **Plugin-Steuerung aktualisieren**. Trennen erfordert einen Klick ohne Bestätigung und betrifft nur diese Unterhaltung: Die Anwendung bleibt offen, ihr Teil installiert, und andere Unterhaltungen behalten ihre Verbindung. Geht die Antwort verloren, liest die Zeile den Zustand erneut; die Anfrage wird nie wiederholt. -## Geöffnete Anwendung verbinden {#application-attachment} +Kataloginstallation, Installation/Aktualisierung des Anwendungsteils und Entfernen erfordern eine Bestätigung. **Abbrechen** erhält zuerst den Fokus; die Bestätigungsaktion wird nach 600 ms verfügbar. Aktivierung, Plugin-Updates, Verbinden und Trennen werden direkt ausgeführt. -Geben Sie ein Dokument über die Integration der Anwendung frei. Öffnen Sie **Status → die Integration → Unterhaltung** und wählen Sie **Verbinden…**. Dieser Abschnitt steuert die Verbindung der angezeigten Unterhaltung. Wählen Sie Anwendung und Dokument, prüfen Sie Zielunterhaltung und Änderungshinweis und bestätigen Sie mit **Verbinden**. Die Anwendung läuft auf dem OpenCode-Rechner, auch bei Fernzugriff. Nicht unterstützte Hosts, einschließlich WSL, bieten Hilfe über **i**. - -Die Zeile **Unterhaltung** liest die aktuelle Verbindung der angezeigten Unterhaltung. **Verbindung unbekannt** bietet **Aktualisieren**. Bestätigt eine aktuelle maßgebliche Abfrage die Verbindung, ersetzt **Trennen** die Aktion **Verbinden…**. Ein Klick trennt nur diese Unterhaltung ohne weitere Bestätigung. Die Anwendung bleibt offen, ihr Teil installiert und die Verbindungen anderer Unterhaltungen bleiben bestehen. Native Änderungen und Neuverbindungen aktualisieren den Zustand. - -Eine gestartete Aktion behält Ergebnis oder Fehler, solange die Zielunterhaltung angezeigt bleibt; Navigation schließt ihren Beleg. Die aktuelle Verbindung folgt der maßgeblichen Abfrage. **Status ungewiss** nach verlorener Antwort, Zeitüberschreitung oder Verbindungsabbruch bietet **Aktualisieren**, um den tatsächlichen Zustand zu lesen. Wiederholen Sie niemals die Anfrage, um die Anzeige zu aktualisieren. - -Nach einer ausdrücklichen Abfrage der geöffneten Anwendungen im Auswahlfenster können gespeicherte Q8-Metadaten **Erneut verbinden** im Auswahlfenster oder in der Zeile **Unterhaltung** für dieselbe Integration und eine validierte Dokumentbezeichnung anbieten, solange Projekt, Unterhaltung und Verbindungsgeneration gleich bleiben. Erneutes Verbinden erfordert eine ausdrückliche Bestätigung; Navigation oder Invalidierung entfernt den Vorschlag. Maßgeblich für die aktuelle Verbindung ist die sitzungsbezogene Abfrage der Integration. - -Entfernen im Integrationsabschnitt oder in dessen Plugins-Zeile verwendet dieselbe Deklaration und bereichsgebundene Bestätigung. Der Vorgang erfolgt ohne Erfassung der Unterhaltungen oder automatisches Trennen. +Das Entfernen erfolgt ohne Erfassung der Unterhaltungen oder automatisches Trennen. Beim Entfernen zeigt eine Warnung Plugin und genauen Bereich. **Abbrechen** erhält den Fokus; **Aus Global/Projekt entfernen** wird nach 600 ms verfügbar und erfordert eine ausdrückliche Aktion. Das Entfernen kann Verfügbarkeit und Verbindungen verwendender Unterhaltungen unterbrechen; Global kann weitere Projekte betreffen. Abbruch, Ablauf oder Navigation vor dem Senden lassen alles unverändert. Nur die bestätigte Deklaration wird entfernt; Aktivierungsregeln, Cache, Anwendungsdateien und gespeicherte Verbindungshinweise bleiben erhalten. Änderungen der Konfiguration erfordern eine neue Auswahl und Bestätigung. Erfolg bestätigt die entfernte Deklaration; der Laufzeitstatus folgt dem Neuladen durch OpenCode. Bei verlorener Antwort zunächst Plugins aktualisieren und den tatsächlichen Zustand prüfen. Neuinstallation kann die Verfügbarkeit wiederherstellen; Neuladen oder erneutes Verbinden kann nötig sein. Unterbrochene Vorgänge werden möglicherweise nicht fortgesetzt. ## Anwendungsintegration installieren oder aktualisieren {#application-installation} -Wählen Sie unter **Status → die Integration → Anwendung** **In Anwendung installieren…** oder **Anwendung aktualisieren…**, wenn der aktuelle Status die Aktion anbietet. Sie ist auch ohne Unterhaltung oder freigegebenes Dokument verfügbar. Öffnen Sie eine geschlossene Anwendung, um ihren Anwendungsteil zu prüfen; **i** zeigt Rechnerhinweise und Voraussetzungen. +Wählen Sie unter **Status → Plugins** in der Statuszeile der Integration **In Blender installieren** oder **Blender aktualisieren**, wenn der aktuelle Status die Aktion anbietet, oder im Menü **…** **In Anwendung installieren…**, **Anwendung aktualisieren…** oder **In Anwendung neu installieren…**. Eine Neuinstallation schreibt den Anwendungsteil neu, ob die Anwendung offen oder geschlossen ist. Die Aktion ist auch ohne Unterhaltung oder geöffnetes Dokument verfügbar. Die Bestätigung nennt die Anwendung und die **Version des Integrationspakets**, das die Installation bereitstellt. Prüfen Sie beides und den Rechnerhinweis: Die Installation erfolgt auf dem Rechner, auf dem OpenCode läuft. Das kann ein entfernter Rechner sein. **Abbrechen** erhält zunächst den Fokus. Bestätigen Sie ausdrücklich, um fortzufahren. Ein Wechsel von Projekt, Location oder Unterhaltung, eine Neuverbindung oder relevante native Änderungen vor der Bestätigung verwerfen die ausstehende Zustimmung. Öffnen Sie die Aktion erneut, um aktuelle Angaben zu prüfen. WSL lehnt die Installation in der Anwendung immer ab, selbst wenn eine geöffnete Anwendung kompatibel erscheint. Öffnen Sie die Anwendung auf einem unterstützten Rechner. -Das Ergebnis meldet eine Installation, Aktualisierung, einen bereits aktuellen Stand, eine Ablehnung oder einen Fehler. Öffnen Sie nach Installation oder Aktualisierung die Anwendung und prüfen Sie deren Integration. Verbinden Sie eine Unterhaltung separat über [Geöffnete Anwendung verbinden](#application-attachment). Der Installationserfolg beschreibt die Installationsanfrage; die laufende Verfügbarkeit der Anwendung ergibt sich aus deren Status. +Das Ergebnis meldet, dass der Anwendungsteil installiert, aktualisiert, bereits aktuell, abgelehnt oder fehlgeschlagen ist. Öffnen Sie nach Installation oder Aktualisierung die Anwendung und prüfen Sie deren Integration. Der Installationserfolg beschreibt die Installationsanfrage; die laufende Verfügbarkeit der Anwendung ergibt sich aus deren Status. Anfragen werden niemals automatisch wiederholt. Prüfen Sie nach einer Ablehnung oder einem Fehler die Anwendung, bevor Sie eine neue Aktion wählen. Bleibt das Ergebnis nach einem Fehler ungewiss, wiederholen Sie diese Anfrage niemals: Prüfen Sie zuerst die Anwendung und starten Sie bei Bedarf eine neue Aktion mit erneuter Bestätigung. diff --git a/docs/help/de/missions.md b/docs/help/de/missions.md index 365d1c336d..3673cca122 100644 --- a/docs/help/de/missions.md +++ b/docs/help/de/missions.md @@ -42,7 +42,7 @@ Kalenderbasierte Zeitplanung benötigt einen expliziten Agenten und ein Modell f ### Automatisch starten {#automatic-start} -**Automatisch starten** steht außerhalb der Zeitplanung und ist standardmäßig aus. Ausgeschaltet erstellt es eine pausierte Mission für späteres ▶ Starten. Eingeschaltet fordert es den Start nach bestätigter Erstellung unter den üblichen Prüfungen und gegebenenfalls mit Zustimmung zu nativen Einstellungen an. +**Automatisch starten** steht außerhalb der Zeitplanung und ist standardmäßig aus. Ausgeschaltet erstellt es eine pausierte Mission für späteres ▶ Starten. Eingeschaltet fordert es den Start nach bestätigter Erstellung mit den üblichen Prüfungen und automatischer Vorbereitung der Zeitplanung an. Bei verlorener Bestätigung bleibt der Start nach Lesen der Quittung manuell. Behalten Sie die ursprüngliche unbestätigte Anfrage und prüfen Sie Liste und Unterhaltung vor einer erneuten Erstellung. @@ -58,6 +58,8 @@ Verfügbar sind einmal jetzt, alle N Stunden, täglich, ausgewählte Wochentage, Einmal jetzt erhält seinen Zeitpunkt beim Start und bietet nur eine Gelegenheit; eine nicht erfüllte Bedingung kann diese verbrauchen. Zeitplanung benötigt den verfügbaren OpenCode-Dienst und Ausführungshost. +Beim Starten oder Fortsetzen wird die Zeitplanung automatisch in der OpenCode-Projektkonfiguration vorbereitet. Ein ausdrückliches OFF bleibt erhalten: **Zeitplanungseinstellungen öffnen** öffnet, wenn angeboten, die zuständige Datei; **i** zeigt Herkunft oder Umgebungsdetails. Nur während der Anfrage zeigt die betätigte Schaltfläche den Ladevorgang. Ein unbestätigtes Ergebnis bietet eine Prüfung; nach wiederhergestellter Aktivierung starten Sie ausdrücklich selbst. + ### Ereignisse und Kombinationen {#scheduling-conditions} Wählen Sie **Repository-Aktivität → Ereignis**, danach optionale Filter in derselben Karte. Git-Commits teilen dieses Menü mit Ereignissen des automatisch erkannten GitHub-, GitLab- oder Gitea-Repositorys, wie in Contribute (`upstream`, dann `origin`). Alle drei unterstützen neue und zusammengeführte PRs/MRs sowie neue Issues mit optionalem **Autor**, einschließlich `dependabot[bot]`. Die Ereignisauswahl legt das Repository fest; gespeicherte Kriterien behalten ihr Ziel. @@ -90,9 +92,11 @@ Weitere Einträge und Aufgaben laden am Listenende automatisch. Aufgabenseiten b ### Farben und Zustände {#status-colours} -Die Flagge zeigt den Missionszustand, der Chevron die Aufmerksamkeit ihrer Aufgaben. Wiederkehrende Einträge haben ein Wiederholungssymbol. Rot verlangt eine Antwort, pulsierendes Gelb zeigt beobachtete Arbeit, Orange Pause/Unterbrechung, Grün einen ungesehenen Abschluss und Blau Vorbereitung beziehungsweise noch nicht gestartete Aufgaben. +Die Flagge zeigt den Missionszustand, der Chevron die Aufmerksamkeit ihrer Aufgaben. Wiederkehrende Einträge haben ein Wiederholungssymbol. Rot verlangt eine Antwort, pulsierendes Gelb zeigt beobachtete Arbeit. Ein orangefarbenes Pausensymbol bedeutet Pause, ein orangefarbenes Warndreieck Unterbrechung. Grün kennzeichnet eine abgeschlossene Mission, Aufgabe oder einen erfolgreichen Durchlauf zum Ansehen. + +Ein Akzentsymbol mit einem kleinen statischen neutralen Strich darunter bedeutet **Wartet auf geplanten Durchlauf**: der nächste Weckzeitpunkt ist bestätigt. Der Akzent folgt der Palette. Das Akzentsymbol allein steht für Vorbereitung oder noch nicht gestartete Aufgaben. Angesehene Abschlüsse, gestoppte Zeitpläne und **Status unbestätigt** sind neutral; lesen Sie den Statustext. -Auswahl oder grüne Aufgabensymbole bestätigen Ergebnisse; das Chevron-Menü bietet **Als gelesen markieren**. Status und Ergebnis sind getrennt: ein Blocker ist nicht zwingend eine Frage, ein Bericht beweist nicht das Ende aller nativen Vorgänge. Zurückgezogene Aufgaben bleiben im Verlauf. +Auswahl oder Klick/Streichen über grüne Aufgabensymbole bestätigt Ergebnisse; das Chevron-Menü bietet **Als gelesen markieren**. Bei **Erfolgreicher Durchlauf zum Ansehen** bestätigt eine ausdrückliche Auswahl der wiederkehrenden Zeile im aktiven Fenster oder **Als gelesen markieren** genau diesen Durchlauf. Bei aktiver Zeitplanung kehrt das Symbol zum Warten zurück, sonst zu neutral. Wiederhergestellte Auswahl und neue Ergebnisse in einer bereits ausgewählten Zeile bleiben ungelesen. Historische Erfolge beim ersten Laden gelten als gelesen. Zurückgezogene Aufgaben bleiben im Verlauf. ### Fragen und Entscheidungen {#questions} diff --git a/docs/help/de/mobile.md b/docs/help/de/mobile.md index 2767c5b71d..e2cb8290a3 100644 --- a/docs/help/de/mobile.md +++ b/docs/help/de/mobile.md @@ -42,3 +42,5 @@ Das Eingabefeld behält Agent, Modell und Denken in der Fußzeile. Seine Größe | Offline-Arbeit | Kein Offline-Backend und kein zwischengespeicherter API-Verlauf. Statische Oberflächendateien können im Cache liegen, Dokumente und API-Antworten sind aber kein Offline-Arbeitsbereich. | Halten Sie das Backend erreichbar. Mobile OS-Suspendierung oder Netzwerkwechsel kann den Ereignisstrom trennen; Rückkehr verbindet neu und liest aktuellen Zustand ohne garantierte Ereigniswiederholung. Prüfen Sie vor Wiederholung, ob eine Aktion abgeschlossen wurde. PWA-Schließen stoppt kein eigenständiges Backend; das Beenden der Host-Desktop-App samt Backend macht Fernsteuerung bis zum nächsten Start unverfügbar. + +Jeder Browser-Tab, auch die installierte PWA, behält für diesen Tab geöffnete Projekte, ausgewählte Unterhaltungen, nicht gesendete Entwürfe und Scrollpositionen: Sie kehren zurück, wenn die Seite neu lädt oder das mobile Betriebssystem sie nach einem App-Wechsel oder einer Bildschirmsperre neu lädt. Ein neuer Tab oder eine vom Betriebssystem vollständig geschlossene PWA öffnet die Startseite. Schalten Sie dies für den Tab unter **Einstellungen → Allgemein → Vorherigen Zustand wiederherstellen** aus. diff --git a/docs/help/de/opencode.md b/docs/help/de/opencode.md index 2456a14342..8235d36b33 100644 --- a/docs/help/de/opencode.md +++ b/docs/help/de/opencode.md @@ -19,8 +19,8 @@ Installierte Programmdatei und laufender Dienst können unterschiedliche Version | Einstufung | Aktuelle Anforderung | Bedeutung | | --- | --- | --- | -| Minimum | OpenCode **2.2.3** | Das Bildgenerierungswerkzeug, das die Einstellungen unter **Bilder** und die Design-Erweiterung nutzen, sowie die korrekte Reihenfolge von JavaScript-Jobs in Code Mode und das native Wiedergabe- und Komprimierungsformat; mit früheren Versionen gespeicherte Unterhaltungen bleiben nach dem Update lesbar. | -| Empfohlen | OpenCode **2.2.7** | Qualifiziertes Ziel, getrennt vom technischen Minimum. | +| Minimum | OpenCode **2.3.0** | Das Bildgenerierungswerkzeug, das die Einstellungen unter **Bilder** und die Design-Erweiterung nutzen, sowie die korrekte Reihenfolge von JavaScript-Jobs in Code Mode und das native Wiedergabe- und Komprimierungsformat; mit früheren Versionen gespeicherte Unterhaltungen bleiben nach dem Update lesbar. Außerdem liefert sie Subagent-Ergebnisse als Hintergrundberichte, die Subagent-Karten und Missionen lesen. | +| Empfohlen | OpenCode **2.3.0** | Qualifiziertes Ziel; derzeit dieselbe Version wie das Minimum. | | Ungeprüft | Neuere oder angepasste, nicht vollständig validierte Version | Nicht allein wegen fehlender Tests abgelehnt; geprüft werden die tatsächlichen API-Verträge des verbundenen Dienstes. | Der verbundene Dienst muss die erforderlichen Verträge für Sitzungen, Berechtigungen, Forms, Posteingang und Sitzungsumgebung bereitstellen. Native Missionszeitplanung prüft auch die Zeitplan-APIs, das Plugin-/Anbieterpaket und die wirksame Einstellung `experimental.schedules`. Die Verfügbarkeit richtet sich nach diesen genutzten Fähigkeiten, auch bei kompatiblen künftigen Versionen. Meldet die Einrichtung einen nicht unterstützten laufenden Dienst, wählen/installieren Sie eine unterstützte CLI und führen Sie bei Bereitschaft den expliziten Neustart des gemeinsamen Dienstes aus. diff --git a/docs/help/de/projects.md b/docs/help/de/projects.md index da4a6f0a1b..ea2e74c163 100644 --- a/docs/help/de/projects.md +++ b/docs/help/de/projects.md @@ -34,7 +34,7 @@ Ein normaler Klick öffnet weiterhin die vollständige Startseite. Der Schnellst | Tab schließen | Entfernt die CodeNomad-Projektverbindung dieses Tabs; ein anderer, separat geöffneter Tab desselben Ordners bleibt unberührt | Löscht weder Projektdateien noch nativen Verlauf, stoppt keine Sitzungen und entlädt nicht die OpenCode-Location | | Sitzung stoppen | Ausführung der ausgewählten Unterhaltung | Schließt weder Projekt noch löscht es dessen Verlauf | -Zeigt ein anderes Fenster dieselbe Projektverbindung, schließt sich dessen Tab ebenfalls und dieses Fenster zeigt eine Benachrichtigung. Das auslösende Fenster zeigt keine. Das Schließen erfolgt sofort; kann das Backend das Projekt nicht schließen, erscheint ein Fehler, und **Zum offenen Projekt wechseln** auf der Startseite erreicht es weiterhin. Es gibt keine automatische Wiederholung. Ungesendete Entwürfe des geschlossenen Tabs werden nicht in die Startwiederherstellung übernommen. +Zeigt ein anderes Fenster dieselbe Projektverbindung, schließt sich dessen Tab ebenfalls und dieses Fenster zeigt eine Benachrichtigung. Das auslösende Fenster zeigt keine. Das Schließen erfolgt sofort; kann das Backend das Projekt nicht schließen, erscheint ein Fehler, und **Zum offenen Projekt wechseln** auf der Startseite erreicht es weiterhin. Es gibt keine automatische Wiederholung. Ungesendete Entwürfe und Anhänge des geschlossenen Tabs kehren zurück, wenn Sie denselben Ordner in diesem Fenster erneut öffnen; das Fenster behält sie für seine 16 zuletzt geschlossenen Projekte, bis es neu geladen oder geschlossen wird. Sie gehören nicht zur Startwiederherstellung. Das Schließen eines ganzen Fensters, Beenden oder Neuladen schließt dessen Projektverbindungen nicht; die normale Startwiederherstellung gilt weiterhin. Stoppen Sie relevante Ausführungen ausdrücklich, wenn Sie sicherstellen müssen, dass sie beendet sind. CodeNomad entlädt niemals native Locations; die Wartung des gemeinsamen Dienstes beschreibt die [OpenCode-Einrichtung](opencode.md). @@ -59,7 +59,7 @@ Schließen Sie die Projekttabs dieses Servers in allen Fenstern, bevor Sie ihn e | Auswahl | Wirkung | Wiederherstellung | | --- | --- | --- | | Behalten | Schließt das Projekt in CodeNomad, behält Ordner und Unterhaltungen, entfernt den temporären Status und fügt ein zuletzt verwendetes Projekt hinzu | Über zuletzt verwendete Einträge erneut öffnen; der Ordner wird nicht verschoben | -| Verwerfen | Löscht Unterhaltungen und Dateien des temporären Arbeitsbereichs | Nicht rückgängig zu machen; benötigte Inhalte vorher anderswo sichern | +| Verwerfen | Löscht Unterhaltungen, Dateien und ungesendete Entwürfe des temporären Arbeitsbereichs | Nicht rückgängig zu machen; benötigte Inhalte vorher anderswo sichern | | Abbrechen | Lässt den temporären Arbeitsbereich geöffnet | Weiterarbeiten oder später entscheiden | Ein unberührter temporärer Tab ohne Unterhaltung, Datei oder ungesendeten Entwurf wird beim Schließen stillschweigend verworfen. Geöffnete temporäre Tabs nehmen an der normalen Startwiederherstellung teil, aber die Startseite hat keine separate Liste zum Fortsetzen geschlossener temporärer Ordner. diff --git a/docs/help/de/providers.md b/docs/help/de/providers.md index 59ec320668..e42c676b84 100644 --- a/docs/help/de/providers.md +++ b/docs/help/de/providers.md @@ -56,15 +56,15 @@ Für Google-Verbindungen mit OpenCodes Gemini-CLI-Authentifizierungsmethode zeig Googles [Antigravity-FAQ](https://antigravity.google/docs/faq/) erklärt, dass die Nutzung von Drittanbietersoftware mit einer Antigravity-Anmeldung gegen die Nutzungsbedingungen verstößt und zur Sperrung oder Kündigung des Kontos führen kann. -Für kostenpflichtige Modelle der Integration `opencode` zeigt **OpenCode Console** die **Anfragen** für **Heute (UTC)**, **7 Tage (UTC)** und **30 Tage (UTC)**. Diese UTC-Kalenderzeiträume schließen heute ein und beginnen jeweils um 00:00 UTC heute, vor sechs Tagen und vor 29 Tagen. **Anfragen nach Modell · 30 Tage** führt jedes Modell mit seinem Anbieter auf. Die Zähler gelten für das verbundene Console-Konto und werden in der Sprache der App formatiert. **Budgets der Dienstkonten** zeigt **Budgets nicht verfügbar.** OpenCode Go verwendet einen eigenen Kontingentleser. +Für kostenpflichtige Modelle der Integration `opencode` zeigt **OpenCode Console** die **Anfragen** für **24 Stunden**, **7 Tage** und **30 Tage**, wie Console sie meldet. **Anfragen nach Modell · 30 Tage** führt jedes Modell mit seinem Anbieter auf. Die Zähler gelten für das verbundene Console-Konto und werden in der Sprache der App formatiert. **Budgets der Dienstkonten** zeigt **Budgets nicht verfügbar.** Mit aktiviertem **Anbieterguthaben** erscheint das Console-Guthaben als **Guthaben**. OpenCode Go verwendet einen eigenen Kontingentleser. Der Leser verwendet den gespeicherten `opencode`-API-Schlüssel oder bevorzugt dessen OAuth-Console-Verbindung. OAuth erfordert `https://opencode.ai/console` und die Organisations-ID der Verbindung; der Console-Zugriff benötigt die Berechtigung **Usage › Read**. CodeNomad aktualisiert diese Zugangsdaten niemals. Eine ungültige oder abgelaufene OAuth-Verbindung muss über ihren Eigentümer wiederhergestellt werden, auch wenn ein API-Schlüssel gespeichert ist. Console-Fehler unterscheiden eine fehlende Verbindung, ungültige oder abgelaufene Zugangsdaten (401), verweigerten Zugriff (403), eine ungültige Nutzungsantwort und Netzwerkfehler. Prüfen Sie bei Verbindungsfehlern unter **Einstellungen → Anbieter** die Anmeldung und Berechtigungen und aktualisieren Sie **Nutzung**. Ein fehlgeschlagener Abruf einer Zusammenfassung oder Modellseite macht die gesamte Console-Anzeige unverfügbar. -Für kostenlose OpenCode-Modelle (`big-pickle` und Modell-IDs mit der Endung `-free`) summiert **Nutzung** nur kostenlose Anfragen des verbundenen Console-Kontos seit 00:00 UTC, gegenüber einem Tagesrichtwert von **800**. **Geschätzt** bezieht sich auf das Kontingent und die Rücksetzung zur nächsten UTC-Mitternacht; tatsächliche Limits können variieren. Der Zähler umfasst andere Clients des Kontos. Ohne Console-Verbindung fordert das Panel über **Einstellungen → Anbieter** zur Verbindung für kostenlose Modelle und die Kontingentanzeige auf. Bei einem Lesefehler bleibt der Zähler nicht verfügbar. +Für kostenlose OpenCode-Modelle (`big-pickle` und Modell-IDs mit der Endung `-free`) zeigt **Nutzung** einen Balken: die kostenlosen Anfragen des verbundenen Console-Kontos in den letzten 24 Stunden laut Console, gegenüber einem Richtwert von **800**; tatsächliche Limits können variieren. Der Zähler umfasst andere Clients des Kontos und hat keinen Rücksetzzeitpunkt. Mit aktiviertem **Anbieterguthaben** erscheint das Console-Guthaben als **Guthaben**. Ohne Console-Verbindung fordert das Panel auf, OpenCode Console über **Einstellungen → Anbieter** zu verbinden. Bei einem Lesefehler bleibt der Zähler nicht verfügbar. -Ein Kontingentfehler bei einem kostenlosen Modellschritt markiert diese OpenCode-Verbindung bis 00:00 UTC als **Ausgeschöpft**. Bei verfügbarem Console-Zähler steht die Anzeige bei 100 % und bewahrt den Zähler. Die Markierung liegt pro Verbindung im Backend-Arbeitsspeicher und wird beim Neustart gelöscht. Kostenlose Nutzung, Erschöpfung und kostenpflichtige Console-Zähler dienen ausschließlich der Anzeige; die automatische Kontowahl verwendet eigene Leser und Regeln. +Kostenlose Nutzung und kostenpflichtige Console-Zähler dienen ausschließlich der Anzeige; die automatische Kontowahl verwendet eigene Leser und Regeln. Für eine ChatGPT-Anmeldemethode stellt OpenAI keine Nutzungsdaten bereit: Nutzung weist darauf hin, statt Kontingentfenster anzuzeigen. Wählen Sie [ChatGPT-Nutzung anzeigen](https://chatgpt.com/settings/usage), um die App-Nutzung einzusehen und den Zugriff auf Ihren Tarif und Ihr Guthaben in ChatGPT zu verwalten. Chatten funktioniert weiterhin, und eine erneute Verbindung derselben Anmeldung stellt den Wert nicht wieder her. diff --git a/docs/help/de/remote-access.md b/docs/help/de/remote-access.md index f6fb3728ae..032b403a06 100644 --- a/docs/help/de/remote-access.md +++ b/docs/help/de/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true Setzen Sie Port 9898 oder 9899 nicht voraus: Nicht angegebene Ports können bei Belegung ausweichen. Ein expliziter von null verschiedener `--https-port` oder ein `--http-port` bei aktiviertem HTTP legt den Port fest und schlägt bei fehlgeschlagener Bindung fehl; `0` fordert eine OS-Zuweisung an. Die ausgegebenen **Local Connection URL** und **Remote Connection URL** sowie aktualisierte **Erreichbare Adressen** sind für diesen Lauf maßgeblich. Siehe die vollständige [Server-CLI-Referenz](server.md). +## Administratorrichtlinie {#administrator-policy} + +Ein Administrator kann die Abhöradresse festlegen: Setzen Sie `CODENOMAD_LOCKED_HOST` systemweit auf die Adresse, die der Server verwenden muss, und starten Sie CodeNomad neu. Sie hat Vorrang vor `--host`, `CLI_HOST` und **Verbindungen von anderen IPs zulassen**, das das Ergebnis anzeigt, es aber nicht ändern kann. Verwenden Sie eine Intranetadresse, damit Kollegen den Server über das Firmennetz erreichen, oder `127.0.0.1`, um ihn auf diesem Computer zu halten. Damit jeder Zugriff im Firmennetz bleibt, setzen Sie zusätzlich `CODENOMAD_REMOTE_CONTROL=disabled` ([Fernsteuerung](remote-control.md#administrator-policy)). + ## Aktualisieren {#upgrading} Melden Sie sich nach der Aktualisierung erneut an. Setzen Sie für einen Hostnamen-Alias, Reverse-Proxy oder eine separat gehostete Oberfläche `CODENOMAD_ALLOWED_ORIGINS` im Backend auf die vertrauenswürdigen Origins der Oberfläche (Schema, Hostname und Port). Native LAN-Clients müssen bei schreibenden Anfragen einen erlaubten `Origin`-Header mitsenden. Seine HTTPS-Origins erlauben dem Host außerdem, Geräte ohne Tunnel zu koppeln; siehe [Über direktes HTTPS koppeln](remote-control.md#direct-https). -Verwenden Sie eine Loopback-Verbindung für dem Host vorbehaltene Vorgänge: SideCar-Inhalte (`/sidecars/`) und WebSockets, Fernsteuerungsverwaltung (`/api/remote-control/`), Plugin-Brücke (`/api/opencode-plugin/`), Remote-Proxys (`/api/remote-proxy/`), Verwaltung gespeicherter Server (`/api/remote-servers/`), Passwortänderungen und Token-Ersteinrichtung. Diese Vorgänge erfordern auch bei angemeldetem direktem LAN-Zugriff Loopback. Inhalte aktiver Vorschauen (`/previews/`) sind mit einem gültigen Berechtigungstoken über direkten LAN-Zugriff verfügbar. +Verwenden Sie eine Loopback-Verbindung für dem Host vorbehaltene Vorgänge: SideCar-Inhalte (`/sidecars/`) und WebSockets, Fernsteuerungsverwaltung (`/api/remote-control/`), Plugin-Brücke (`/api/opencode-plugin/`), Remote-Proxys (`/api/remote-proxy/`), Verwaltung gespeicherter Server (`/api/remote-servers/`), Passwortänderungen und Token-Ersteinrichtung. Diese Vorgänge erfordern auch bei angemeldetem direktem LAN-Zugriff Loopback. Nur SideCars haben eine Ausnahme: Die Host-Einstellung **SideCars über HTTPS öffnen** gibt ihre Inhalte und WebSockets für Browser frei, die über einen vertrauenswürdigen HTTPS-Origin angemeldet sind ([SideCars](browser-sidecars.md#register-sidecar)). Inhalte aktiver Vorschauen (`/previews/`) sind mit einem gültigen Berechtigungstoken über direkten LAN-Zugriff verfügbar. Die Registrierungs-APIs `/api/sidecars` bleiben für authentifizierte direkte LAN-Clients und gekoppelte Geräte verfügbar. Web-Vorschauen der Fernsteuerung bleiben mit ihrem Berechtigungstoken verfügbar, solange sie auf dem Host aktiviert sind. diff --git a/docs/help/de/remote-control.md b/docs/help/de/remote-control.md index 191abe6ac3..e9ab5986bd 100644 --- a/docs/help/de/remote-control.md +++ b/docs/help/de/remote-control.md @@ -86,3 +86,7 @@ CodeNomad verwendet [OpenTunnel](https://github.com/anomalyco/opentunnel) und be TLS endet im CodeNomad-Backend. Das Relay leitet Chiffretext weiter und kann Anwendungsinhalte nicht lesen, aber Hostnamen, Verbindungszeiten und Datenmengen beobachten. Tunnelzertifikat und privater Schlüssel bleiben auf dem Host. Schützen Sie Tunnelspeicher und CodeNomad-Konfiguration des Hosts wie Zugangsdaten; eine nicht erratbare Adresse ist keine Autorisierung. `CODENOMAD_REMOTE_CONTROL_API` wählt eine selbst gehostete OpenTunnel-API; ohne Wert gilt der gehostete Dienst. Dies ändert die Tunnelbereitstellung, nicht Kopplungsanforderungen oder blockierte Oberflächen. Zum Umgang mit Zugangsdaten und Diagnosen siehe [Sicherheit](security.md). + +## Administratorrichtlinie {#administrator-policy} + +Ein Administrator kann die Fernsteuerung für alle Benutzer eines Computers ausschalten: Setzen Sie die Umgebungsvariable `CODENOMAD_REMOTE_CONTROL=disabled` systemweit und starten Sie CodeNomad neu. Das Backend verbindet dann nie einen Tunnel, lehnt **Fernsteuerung starten** und Kopplungslinks ab und verbindet sich beim Start nicht erneut; die Einstellungen zeigen **Vom Administrator deaktiviert**. Zuvor gekoppelte Geräte können sich nicht verbinden und bleiben zum Widerrufen aufgelistet. Nicht gesetzt oder leer bedeutet keine Richtlinie; jeder andere Wert, auch nur Leerzeichen, verhindert den Start des Backends. diff --git a/docs/help/de/security.md b/docs/help/de/security.md index 7968e3f531..e4efeb8c6e 100644 --- a/docs/help/de/security.md +++ b/docs/help/de/security.md @@ -33,7 +33,7 @@ Direkte Anmeldung erzeugt eine undurchsichtige Backend-Sitzung im Arbeitsspeiche Abmelden widerruft die aktuelle direkte Sitzung. Ein erfolgreicher Passwortwechsel auf dem Host widerruft alle direkten Sitzungen dieses Benutzers einschließlich der aufrufenden Sitzung; melden Sie sich erneut an. Sitzungen laufen nach 24 Stunden ohne authentifizierte Anfrage oder sieben Tagen seit Erstellung ab. Passen Sie diese Grenzen vor dem Backend-Start mit `CODENOMAD_SESSION_IDLE_SECONDS` und `CODENOMAD_SESSION_ABSOLUTE_SECONDS` als positive ganze Sekunden an. Fernsteuerungsgeräte werden separat widerrufen. -LAN-Clients können sich an- und abmelden und Projekte nutzen. Passwortänderungen, Fernsteuerungsverwaltung, Remote-Server-/Proxy-Werkzeuge und SideCars werden auf dem Loopback-Host verwaltet. Browseränderungen benötigen einen erlaubten Origin oder ersatzweise Referer. Die veröffentlichten Server-Ursprünge sind erlaubt; für DNS-Aliasse, Reverse-Proxys oder eine separat gehostete Oberfläche setzen Sie `CODENOMAD_ALLOWED_ORIGINS` auf kommagetrennte exakte HTTP(S)-Ursprünge, etwa `https://code.example.test,https://ui.example.test:8443`, und starten neu. Verwenden Sie keine Pfade oder Platzhalter. Dies gewährt Browserzugriff, keine Host-Rechte. Native LAN-Clients müssen bei Änderungen ebenfalls einen erlaubten Origin senden. Ein vertrauenswürdiger Proxy über Loopback hat Host-Rechte und benötigt eigene Zugriffskontrollen. Lauscht der Server auf Loopback oder auf allen Schnittstellen, funktioniert die Oberfläche auf dem Host auch unter `localhost` mit demselben Schema und Port. +LAN-Clients können sich an- und abmelden und Projekte nutzen. Passwortänderungen, Fernsteuerungsverwaltung, Remote-Server-/Proxy-Werkzeuge und SideCars werden auf dem Loopback-Host verwaltet. Die Host-Einstellung **SideCars über HTTPS öffnen** gibt SideCars für Browser frei, die über einen vertrauenswürdigen HTTPS-Origin angemeldet sind; aktivieren Sie sie nur, wenn alle Nutzer dieser Adressen Ihre SideCar-Dienste verwenden dürfen. Browseränderungen benötigen einen erlaubten Origin oder ersatzweise Referer. Die veröffentlichten Server-Ursprünge sind erlaubt; für DNS-Aliasse, Reverse-Proxys oder eine separat gehostete Oberfläche setzen Sie `CODENOMAD_ALLOWED_ORIGINS` auf kommagetrennte exakte HTTP(S)-Ursprünge, etwa `https://code.example.test,https://ui.example.test:8443`, und starten neu. Verwenden Sie keine Pfade oder Platzhalter. Dies gewährt Browserzugriff, keine Host-Rechte. Native LAN-Clients müssen bei Änderungen ebenfalls einen erlaubten Origin senden. Ein vertrauenswürdiger Proxy über Loopback hat Host-Rechte und benötigt eigene Zugriffskontrollen. Lauscht der Server auf Loopback oder auf allen Schnittstellen, funktioniert die Oberfläche auf dem Host auch unter `localhost` mit demselben Schema und Port. Bei Kompromittierungsverdacht: diff --git a/docs/help/de/server.md b/docs/help/de/server.md index cab3c3db79..7e0dd0dac0 100644 --- a/docs/help/de/server.md +++ b/docs/help/de/server.md @@ -8,7 +8,7 @@ Dieselbe Oberfläche unterstützt [mehrere Projekt-Tabs und Worktrees](projects. 1. Installieren Sie Node.js 24 LTS und npm; die Build-Laufzeit des Repositorys ist in `.node-version` festgelegt. Desktop-Pakete liefern ihre eigene Laufzeit: Electron nutzt sein integriertes Node, Tauri bündelt Node, und beide enthalten npm. 2. Stellen Sie Git im **PATH des Backend-Prozesses** bereit. Git allein in WSL genügt für ein Windows-Backend nicht. -3. Installieren oder wählen Sie OpenCode: **2.2.3** ist das erforderliche Minimum, **2.2.7** das empfohlene Qualifizierungsziel. Neuere/angepasste Builds durchlaufen Kompatibilitätsprüfungen, keine Positivliste getesteter Versionen. Siehe [OpenCode-Einrichtung](opencode.md). +3. Installieren oder wählen Sie OpenCode: **2.3.0** ist das erforderliche Minimum, **2.3.0** das empfohlene Qualifizierungsziel. Neuere/angepasste Builds durchlaufen Kompatibilitätsprüfungen, keine Positivliste getesteter Versionen. Siehe [OpenCode-Einrichtung](opencode.md). 4. Wählen Sie den Startordner des Servers oder übergeben Sie `--workspace-root` ausdrücklich. Ohne Git bleiben Unterhaltungen nur im ausdrücklich geöffneten physischen Ordner verfügbar; Git- und Worktree-Vorgänge schlagen fehl. Installieren Sie Git und starten Sie das Backend nach einer PATH-Änderung neu. Das Arbeitsbereichs-Stammverzeichnis begrenzt Öffnen/Durchsuchen, nicht Agentenausführung: siehe [Sicherheit](security.md). @@ -104,6 +104,8 @@ Die öffentliche Referenz listet benutzerseitige Optionen; Desktop-Hosts verwalt | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; Repository für Release-Angebote. | | `CODENOMAD_REMOTE_CONTROL_API` | Nicht gesetzt: gehostete OpenTunnel-API. Für selbst gehostetes Relay eine API-Origin setzen. | +| `CODENOMAD_REMOTE_CONTROL` | Nicht gesetzt: Benutzer können die Fernsteuerung starten. `disabled`: von einem Administrator ausgeschaltet ([Richtlinie](remote-control.md#administrator-policy)); nicht gesetzt oder leer bedeutet keine Richtlinie, jeder andere Wert (auch Leerzeichen) verhindert den Start. | +| `CODENOMAD_LOCKED_HOST` | Nicht gesetzt oder leer: `--host` gilt; nur Leerzeichen verhindern den Start. Eine Adresse: Der Server lauscht dort, unabhängig von `--host`, `CLI_HOST` oder dem Abhörschalter ([Richtlinie](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | Optionale zusätzliche CA-Datei von Node; wird mit zulässiger Startumgebung beim Start eines fehlenden OpenCode-Daemons übergeben. Ändert keinen bereits laufenden Daemon. | Anbieterspezifische Nutzungszugangsdaten behandelt [Anbieter](providers.md). Desktop-Datenprofilauswahl beschreibt [Desktop](desktop.md); der Release-Kanal steuert sie nicht. diff --git a/docs/help/de/settings.md b/docs/help/de/settings.md index 4e4b6b4dc1..091d37338a 100644 --- a/docs/help/de/settings.md +++ b/docs/help/de/settings.md @@ -70,7 +70,7 @@ Ziehen Sie am inneren Rand eines angedockten Panels, um seine Größe zu ändern 2. Öffnen Sie **Rechtes Panel anpassen** im rechten Panel. Wählen Sie integrierte Tabs und Statusabschnitte per Kontrollkästchen; mindestens ein Statusabschnitt bleibt sichtbar. Ziehen Sie über diese Kontrollkästchen, um mehrere auf einmal einzustellen. 3. Ziehen Sie rechte Panel-Tabs zum Umordnen. **Zurücksetzen** stellt integrierte Layoutauswahlen wieder her. -Erkannte [Integrationen](integrations.md#integration-sections) haben ebenfalls Statusabschnitte. Blenden Sie diese mit denselben Kontrollkästchen aus; ordnen Sie jeden Statusabschnitt per Ziehen oder mit den Tasten Auf/Ab um. Sichtbarkeit und Reihenfolge bleiben bei Neuladen und vorübergehend fehlenden Integrationen erhalten. +Ordnen Sie jeden Statusabschnitt per Ziehen oder mit den Tasten Auf/Ab um. Sichtbarkeit und Reihenfolge bleiben beim Neuladen erhalten. Status enthält Tokeninformationen, Yolo-Modus, Anbieternutzung, Hintergrund-Shells, MCP und Plugins. Solange die Unterhaltung ein [Ziel](conversations.md#goal) hat, zeigt eine Zielzeile über diesen Abschnitten es an; diese Zeile ist kein Abschnitt und lässt sich weder ausblenden noch verschieben. Ausblenden deaktiviert keinen Dienst und widerruft keine Rechte. Schmale Layouts schließen Panels, die nicht mehr passen, statt die Unterhaltung einzuengen; ein dort geöffnetes Panel schwebt über ihr, und ein schwebendes Panel zu öffnen schließt das andere. diff --git a/docs/help/de/troubleshooting.md b/docs/help/de/troubleshooting.md index 942b613be0..8baf919cb3 100644 --- a/docs/help/de/troubleshooting.md +++ b/docs/help/de/troubleshooting.md @@ -42,7 +42,7 @@ Lässt sich ein zugehöriger Worktree oder Unterhaltungsort nicht überprüfen, ## OpenCode-Laufzeit und WSL {#opencode-runtime} 1. Öffnen Sie **Einstellungen → OpenCode** und prüfen Sie die Karte **OpenCode-Version** (installierte Version und Status des laufenden Dienstes), dann die gewählte Programmdatei unter **OpenCode-Binärdatei**. -2. Verwenden Sie die unterstützte Installation/Aktualisierung, falls die erforderliche Laufzeit fehlt. Aktuelles Minimum: **2.2.3**; empfohlene/qualifizierte Version: **2.2.7**. +2. Verwenden Sie die unterstützte Installation/Aktualisierung, falls die erforderliche Laufzeit fehlt. Aktuelles Minimum: **2.3.0**; empfohlene/qualifizierte Version: **2.3.0**. 3. Weicht die installierte CLI vom laufenden Dienst ab, entscheiden Sie ausdrücklich über einen Neustart des gemeinsamen Dienstes. **OpenCode-Dienst neu starten** ist unter **Fehlerbehebung** verfügbar und benötigt Bestätigung. Es unterbricht aktive Arbeit in jedem verbundenen Client, behält aber Sitzungsverlauf. Konfigurationsneuladen ist separat: Es behält den Prozess, erstellt aber geladene Locations neu und storniert offene Fragen/Berechtigungen. Beides ist keine harmlose Aktualisierung. diff --git a/docs/help/en/browser-sidecars.md b/docs/help/en/browser-sidecars.md index a97ebbf18f..a5caeedb5f 100644 --- a/docs/help/en/browser-sidecars.md +++ b/docs/help/en/browser-sidecars.md @@ -77,7 +77,7 @@ If unreachable, check the process and port on the backend. If HTML loads but ass A SideCar is a trusted extension of CodeNomad, not a sandboxed preview: its page runs with CodeNomad's own origin, so its scripts can use CodeNomad with your signed-in access. Register only services whose code you trust. CodeNomad does not forward its own sign-in cookies to the service, while the service's own cookies are kept. -SideCar content (`/sidecars/`) and SideCar WebSockets require a loopback connection on the host. Registration through `/api/sidecars` is available to paired devices and authenticated direct LAN clients. Live preview content (`/previews/`) is available over direct LAN access with a valid capability token; [Remote Control](remote-control.md#remote-surface) web previews remain available with their capability token while enabled. See [Upgrading](remote-access.md#upgrading) for direct-access requirements. +SideCar content (`/sidecars/`) and SideCar WebSockets require a loopback connection on the host. To open them from other devices too, turn on **Open SideCars over HTTPS** in **Settings → SideCars** on the host: browsers signed in through this server's HTTPS addresses or an HTTPS origin in `CODENOMAD_ALLOWED_ORIGINS`, such as a TLS reverse proxy, can then open SideCars. Plain HTTP, `localhost` addresses and Remote Control stay host-only. Registration through `/api/sidecars` is available to paired devices and authenticated direct LAN clients. Live preview content (`/previews/`) is available over direct LAN access with a valid capability token; [Remote Control](remote-control.md#remote-surface) web previews remain available with their capability token while enabled. See [Upgrading](remote-access.md#upgrading) for direct-access requirements. ## OpenVSCode Server recipe {#openvscode} diff --git a/docs/help/en/conversations.md b/docs/help/en/conversations.md index 112525ecb5..e6fb647258 100644 --- a/docs/help/en/conversations.md +++ b/docs/help/en/conversations.md @@ -60,6 +60,12 @@ On desktop, sending moves keyboard focus to the conversation, so arrows, paging Drafts are client-side working state, not shared native messages. Startup restoration can retain supported composer state, but do not treat an unsent draft or attachment as a backup or assume it appears on another device. Save important text before clearing startup data or closing a client whose restore policy is disabled; see [Desktop](desktop.md). +## Open files from replies {#open-files-from-replies} + +1. Agent replies link project files with relative and absolute paths. +2. A plain click opens the linked file in the file preview, read from the conversation’s worktree. +3. Modified clicks (Ctrl/Cmd-click, Shift-click, middle-click) and links outside the session’s worktree keep normal link behavior. + ## Commands and Shell mode {#commands-shell} 1. Type `/` and select a discovered custom command, then supply its arguments. diff --git a/docs/help/en/install.md b/docs/help/en/install.md index dd42c24684..4e9eb95e7d 100644 --- a/docs/help/en/install.md +++ b/docs/help/en/install.md @@ -45,7 +45,7 @@ The Electron Debian installation configures Chromium's sandbox. Do not disable t | Requirement | Where it must be available | Current requirement | | --- | --- | --- | -| OpenCode CLI | Selected execution host, including the selected WSL distribution where applicable | Minimum **2.2.3**; **2.2.7** is the recommended/qualified target. Newer or custom versions undergo contract validation rather than an untested-version ban. | +| OpenCode CLI | Selected execution host, including the selected WSL distribution where applicable | Minimum **2.3.0**; **2.3.0** is the recommended/qualified target. Newer or custom versions undergo contract validation rather than an untested-version ban. | | Git | CodeNomad backend account's `PATH` | Required for repository identity, Git operations and worktrees. | | Node.js/npm | Standalone-server and source-build host | Node.js 24 LTS; reproducible source builds use the version pinned in `.node-version`. Desktop releases include their own: Electron's integrated Node or Tauri's bundled Node, with npm. | | Workspace folder | Backend-accessible disk | An explicitly opened physical folder, not a device-local folder inferred by a remote browser. | diff --git a/docs/help/en/integrations.md b/docs/help/en/integrations.md index ea3d89b9c0..4a3c6b3253 100644 --- a/docs/help/en/integrations.md +++ b/docs/help/en/integrations.md @@ -27,7 +27,7 @@ If no server appears, verify the active Location and its native configuration. I CodeNomad-managed plugins stay outside the ordinary plugin list and its activation, update and removal controls. CodeNomad recognises them by their validated installer entry and content-addressed payload location; a third-party plugin with the same name or ID keeps its ordinary controls. -If a managed plugin is disabled, fails to load or has no confirmed load, **CodeNomad plugins need attention** appears above the Plugins list. Open its **i** button (**Details for** the plugin) for the available error and OpenCode log reference. Only a disabled plugin offers **Re-enable**: it appends a positive exact-ID activation rule, preserving the disabling rule. It writes in the disabling rule's **Global** or **Project** scope when writable, otherwise in **Project**. OpenCode stays running; the warning remains until native events or **Refresh plugin controls** confirm that the plugin is active. +If a managed plugin is disabled, fails to load or has no confirmed load, **CodeNomad plugins need attention** appears above the Plugins list. Open its **i** button (**Details for** the plugin) for the available error and OpenCode log reference. Only a disabled plugin offers **Re-enable**: it removes the plugin's exact disabling rule from that file when that alone re-enables it, and otherwise adds a positive exact-ID rule. It writes in the disabling rule's **Global** or **Project** scope when writable, otherwise in **Project**. OpenCode stays running; the warning remains until native events or **Refresh plugin controls** confirm that the plugin is active. The warning and its details label configuration origins **Inherited / external** or **Virtual configuration** where applicable. A separate **Project** label identifies the re-enable destination when it differs from the disabling rule's origin. @@ -38,7 +38,7 @@ The warning and its details label configuration origins **Inherited / external** Global targets the connected daemon's discovered global configuration. Project targets configuration within the active Location, not an inherited ancestor file. A later Project rule can override Global; the Global switch still shows the Global rule rather than pretending to be the final Project state. With no Project rule, Project inherits the resolved Global state. -These switches append exact activation rules while preserving source declarations and unrelated configuration. They do not edit plugin options, install packages or remove files. Built-in OpenCode plugins are not offered as user activation switches. Project is disabled when its target cannot be safely separated from Global or would escape the active Location. +Each switch writes one exact activation rule for the plugin in its scope's file, replacing that plugin's earlier exact rules there, or only removes them when that gives the same result. Source declarations, broader rules such as `*` and unrelated configuration are preserved. They do not edit plugin options, install packages or remove files. Built-in OpenCode plugins are not offered as user activation switches. Project is disabled when its target cannot be safely separated from Global or would escape the active Location. A package update changes that package in OpenCode's shared cache for every Location using it, as its tooltip states; it does not change activation rules, restart OpenCode or reload configuration. Local, built-in and SDK-provided plugins have no package action. A package that fails before reporting its plugin ID is listed by its package name, with the failure in its tooltip and check/update actions but no activation switches. A failed check or update is reported and never retried automatically. @@ -78,38 +78,30 @@ Skill availability comes from the conversation's Location, not a global CodeNoma Commands are discovered from OpenCode for the active Location. Their own native definition can choose execution behavior; the menu is not a package installer or an unrestricted configuration editor. CodeNomad applies the profile's session environment before native custom-command submission; a failed environment update blocks the send. `/btw` is CodeNomad's separate ephemeral question flow, not an ordinary custom command. For command definitions and native configuration inheritance, use [OpenCode commands documentation](https://opencode.ai/v2/docs/commands/). After configuration changes, refresh/reopen the relevant surface first; use explicit configuration reload only if the runtime still needs it. Never replay a possibly admitted command solely to refresh its display. -## Integration sections in Status {#integration-sections} +## Integrations in Plugins {#integration-rows} In **Status → Plugins**, **+** opens **Add an integration…** or **Add a plugin…**. The integration picker lists uninstalled entries from the reviewed catalogue. Choose the scope and **Install**: CodeNomad installs the selected catalogue ID. Native integrations use **Global only**. **Catalogue unavailable** offers **Refresh**; **Catalogue of {date}** identifies the last valid catalogue when stale. -Each recognised integration with a declaration or a loaded/failed plugin has its own section in **Status**, including disabled or installing integrations. An ambiguous source shows **Non-conforming** in Plugins. Every integration keeps its Plugins row with update, remove and refresh actions. Expand its integration section to see the version and plugin controls in the body; its name and status stay visible in the header, beside **Documentation** and **i**. The **i** popover provides details on demand: open it with Enter/Space and close it with Escape. +A recognised integration has one row in **Status → Plugins**, with its name (for example **OpenCode for Blender**) and version. Its **Global** and **Project** switches use the accent colour like the other switches, where a plain plugin's are green; an integration with a part inside an application is **Global only**. Hover its name: the details start with **Integration** instead of **Plugin**; screen readers read them as the row's description. An ambiguous source shows **Non-conforming**. -Use Status customisation to hide sections or reorder them by dragging or with Up/Down keys, including the other Status sections. Visibility and order persist across reloads and temporary absence of an integration. If a section disappears while focused, focus returns to Plugins, or another visible Status section when Plugins is hidden. +Under the name, a state line always says where the integration stands. Grey text informs; text in the accent colour is a button. For an integration with a part inside an application, the most important state shows: **Install in Blender** or **Update Blender** when its part is missing or old (with the installation confirmation), an incompatibility in the warning colour, a chain icon and the document when the displayed conversation is attached (select it to detach), **Blender closed**, **Blender: no open document**, **No conversation displayed**, then **Attach** and the document name, or **Attach…** to choose between several documents. A conversation also attaches itself the first time its agent uses the integration. Editor MCP integrations show **Server detected** or **Server not found**, API integrations **Connected** or **Disconnected**. A long state is cut short; hover it for the full text. Changes reported by the integration and reconnects refresh the line. -Catalogue installation, application-part installation/update, attachment and removal require confirmation. **Cancel** is focused first; the confirming action becomes available after 600 ms. Activation and plugin updates run directly. +The row's **…** menu starts with the connection state, for example **Blender: 1 open document** or **Blender closed**. It then offers **Documentation**, **Install in application…**, **Update application…** or **Reinstall in application…** ([see below](#application-installation)), the package update check, **Remove from Global** or **Remove from Project**, and **Refresh plugin controls**. Detaching takes one click without confirmation and affects only this conversation: the application stays open, its part stays installed and other conversations keep theirs. If its answer is lost, the row reads the state again; the request is never repeated. -## Attach an open application {#application-attachment} +Catalogue installation, application-part installation/update and removal require confirmation. **Cancel** is focused first; the confirming action becomes available after 600 ms. Activation, plugin updates, attaching and detaching run directly. -Offer a document from the application's integration, then open **Status → the integration → Conversation** and select **Attach…**. This section is the attachment control for the displayed conversation. Select an application/document, check the target conversation and modification warning, then confirm **Attach**. The application runs on the machine where OpenCode runs, including remote connections. An unsupported host, including unsupported WSL, shows help through **i**. - -The section's **Conversation** row reads the current binding for the displayed conversation. **Binding unknown** offers **Refresh**. When a fresh authoritative read confirms the attachment, **Detach** replaces **Attach…**. One click detaches only this conversation, without another confirmation; the application stays open, its part stays installed and other conversations keep their bindings. Native changes and reconnects refresh this state. - -An admitted action keeps its result or error while the target conversation stays displayed; navigation dismisses its receipt. Live attachment follows the authoritative read. **Uncertain state** after a lost response, timeout or disconnection offers **Refresh** to read the actual state. Never replay the request to refresh the display. - -After explicitly reading open applications in the picker, saved Q8 metadata can suggest **Reattach** in the picker or the **Conversation** row for the same integration and validated document label, while the project, conversation and connection generation remain unchanged. Reattachment requires explicit confirmation; navigation or invalidation clears the suggestion. Current binding authority comes from the integration's per-session read. - -Removal from the integration section or its Plugins row uses the same scoped declaration and confirmation. Removal proceeds without a conversation census or automatic detach. +Removal proceeds without a conversation census or automatic detach. Removing any plugin opens a warning naming the plugin and exact scope. **Cancel** is initially focused; **Remove from Global/Project** becomes available after 600 ms and needs an explicit click or keyboard action. Removal can interrupt availability and connections in conversations using the plugin; Global can also affect other projects. Cancellation, expiry or navigation before submission leaves everything unchanged. CodeNomad removes only the confirmed declaration, preserving activation rules, package cache, application files and saved attachment hints. Changed configuration requires a fresh selection and confirmation. Success confirms the declaration was removed; runtime state follows OpenCode's reload. If the response is lost, refresh Plugins to check the actual configuration before a new attempt. Reinstalling may restore availability, with a reload or reattachment sometimes needed; interrupted operations may not resume. ## Install or update the application integration {#application-installation} -In **Status → the integration → Application**, choose **Install in application…** or **Update application…** when its fresh status offers the action. It is available without a conversation or an offered document. If the application is closed, open it to check its application part; **i** provides the machine and prerequisite details. +In **Status → Plugins**, select **Install in Blender** or **Update Blender** on the integration's state line when its fresh status offers the action, or choose **Install in application…**, **Update application…** or **Reinstall in application…** in its **…** menu. Reinstalling rewrites the application part, the application open or closed. It is available without a conversation or an open document. The confirmation names the application and the **integration package version** supplying the installer. Check both and the machine warning: installation runs on the machine where OpenCode runs, which may be remote. **Cancel** has initial focus. Confirm explicitly to proceed. Changing project, Location or conversation, reconnecting, or receiving relevant native changes before confirmation cancels the pending approval; open the action again to review fresh details. WSL always refuses application installation, even when an open application appears compatible. Open the application on a supported machine. -The result reports that the integration was installed, updated, already up to date, refused or failed. For installation or update, open the application and check its integration; attach a conversation separately using [Attach an open application](#application-attachment). Installation success describes the installer request; live application availability comes from the application's status. +The result reports that the application part was installed, updated, already up to date, refused or failed. After installation or update, open the application and check its integration. Installation success describes the installer request; live application availability comes from the application's status. Requests are never retried automatically. After a refusal or failure, check the application before choosing a new action. If an error leaves the outcome uncertain, never repeat that request: inspect the application first, then start a fresh action and confirmation if needed. diff --git a/docs/help/en/missions.md b/docs/help/en/missions.md index df2be9664e..7aa9dae97e 100644 --- a/docs/help/en/missions.md +++ b/docs/help/en/missions.md @@ -46,7 +46,7 @@ Calendar-backed scheduling requires an explicit agent and model for the coordina ### Start automatically {#automatic-start} -**Start automatically** is outside Scheduling and off by default. Leave it off to create a paused Mission, then use ▶ **Start** in the header. Turn it on to request Start after creation is confirmed, with the ordinary checks and any required native-settings consent. +**Start automatically** is outside Scheduling and off by default. Leave it off to create a paused Mission, then use ▶ **Start** in the header. Turn it on to request Start after creation is confirmed, with the ordinary checks and automatic scheduling preparation. If creation's acknowledgement is lost, reading its receipt leaves Start manual. An unconfirmed creation keeps its original request; inspect the list and conversation before creating anything again. @@ -62,6 +62,8 @@ Schedules include Once, now, Every N hours, Every day, Selected weekdays, Day of **Once, now** takes its instant at Start, rather than when the form opens. It offers one opportunity, which a condition can consume without launching. Choose a repeating schedule for later opportunities. Scheduling runs while its OpenCode service and execution host are available. +Starting or resuming prepares scheduling in the project's OpenCode configuration automatically. An explicit OFF is preserved: use **Open scheduling settings** when offered to open the responsible file, and the **i** tip for its source or environment details. The clicked button shows loading only during the request. An unconfirmed result offers verification; recovered activation leaves Start explicit. + ### Events and combinations {#scheduling-conditions} Choose **Repository activity → Event**, then any optional filters in the same card. Git branch commits share this menu with events from the automatically detected GitHub, GitLab or Gitea repository, using the same detection as Contribute (`upstream`, then `origin`). All three support new PRs/MRs, merged PRs/MRs and new issues, with optional **Author**, including `dependabot[bot]`. Choosing an event fixes its repository; saved criteria retain their targets. @@ -100,13 +102,18 @@ More directory entries and tasks load as you approach the end. Loaded task pages The flag shows the Mission's state; its chevron carries its tasks' attention state. A recurring entry uses a repeat icon. -| Colour | Meaning | +| Colour and shape | Meaning | | --- | --- | | Red | An open question or permission needs your answer. Select the asking Mission or task to open the interruption dock. | | Yellow, pulsing | Native work was observed running. | -| Orange | Paused or interrupted, with an action to continue. | -| Green | A Mission or task finished and has not been seen in this window. Select it, click or sweep green task icons, or use **Mark as read** on the chevron's context menu. | -| Blue | Prepared Mission or a task that has not started. | +| Orange pause symbol | Paused. | +| Orange warning triangle | Interrupted, with an action to continue. | +| Green | A Mission, task or successful scheduled run awaits review in this window. | +| Accent icon with a small static neutral line below | **Waiting for scheduled run**: the next wake is confirmed. The accent follows your palette. | +| Accent icon alone | Prepared Mission or a task that has not started. | +| Neutral | Reviewed completion, stopped schedule or **State unconfirmed**; read the status text. | + +Select a green Mission or task, click or sweep green task icons, or use **Mark as read** on the chevron's context menu. For **Successful run to review**, explicitly select the recurring row in the active window or use **Mark as read** to acknowledge that run. Its icon returns to waiting while scheduling remains active, otherwise neutral. Restored selection and results arriving on an already selected row keep the new result unread. Historical successes present on first loading start as read. Status text distinguishes Assigned, Active, Waiting, Blocked, Done, Failed and Retired. A reported blockage is not necessarily a question for you. A recorded result is not proof that every native operation has stopped. Retiring a task keeps its history. diff --git a/docs/help/en/mobile.md b/docs/help/en/mobile.md index 746afd0cf2..c31c4079da 100644 --- a/docs/help/en/mobile.md +++ b/docs/help/en/mobile.md @@ -42,3 +42,5 @@ The composer keeps Agent, Model and Thinking in its footer. The field resizes wi | Offline work | No offline backend or cached API history. Static UI assets may be cached, but documents and API responses are not an offline workspace. | Keep the backend reachable. Mobile OS suspension or a network switch can disconnect the event stream; returning reconnects and refetches current state, with no guaranteed event replay. Check whether an action completed before retrying it. Closing the PWA does not stop a standalone backend; quitting the host desktop app and its backend makes Remote Control unavailable until the next launch. + +Each browser tab, including the installed PWA, keeps its open projects, selected conversations, unsent drafts and scroll positions for that tab: when the page reloads, or the mobile OS reloads it after an app switch or screen lock, they come back. A new tab, or a PWA the OS fully closed, opens on the home page. Turn this off for the tab with **Settings → General → Restore previous state**. diff --git a/docs/help/en/opencode.md b/docs/help/en/opencode.md index 10dbf3b6c4..b49892a5ba 100644 --- a/docs/help/en/opencode.md +++ b/docs/help/en/opencode.md @@ -19,8 +19,8 @@ The installed executable and the running service can have different versions. Co | Classification | Current requirement | Meaning | | --- | --- | --- | -| Minimum | OpenCode **2.2.3** | The image generation tool used by the **Images** settings and the Design extension, alongside correct JavaScript job ordering in Code Mode and the native replay and compaction format; conversations saved by earlier versions stay readable after updating. | -| Recommended | OpenCode **2.2.7** | Qualified target, distinct from the technical minimum. | +| Minimum | OpenCode **2.3.0** | The image generation tool used by the **Images** settings and the Design extension, alongside correct JavaScript job ordering in Code Mode and the native replay and compaction format; conversations saved by earlier versions stay readable after updating. It also delivers subagent results as background reports, which subagent cards and Missions read. | +| Recommended | OpenCode **2.3.0** | Qualified target; currently the same version as the minimum. | | Unverified | A newer or custom version not fully validated | Not rejected merely for being untested; the connected service's actual API contracts are checked. | The connected service must expose the required session, permission, Form, inbox and session-environment contracts. Native Mission scheduling also checks the schedule APIs, plugin/provider bundle and effective `experimental.schedules` setting. Availability follows those consumed capabilities, including on compatible future versions. If setup reports an unsupported running service, select/install a supported CLI and use the explicit shared-service restart when ready. diff --git a/docs/help/en/projects.md b/docs/help/en/projects.md index d41f43e163..f5ee02a3fc 100644 --- a/docs/help/en/projects.md +++ b/docs/help/en/projects.md @@ -34,7 +34,7 @@ A normal click still opens the full home page. The launcher is a shortcut, not t | Close Tab | Removes that tab's CodeNomad project connection; another tab opened separately on the same folder is unaffected | Does not delete project files or native history, stop sessions or unload OpenCode's Location | | Stop session | The selected conversation's execution | Does not close the project or delete its history | -If another window displays the same project connection, its tab closes too and that window shows a notification. The initiating window shows none. Closing is immediate; if the backend cannot close the project, an error appears and **Switch to open project** on the home page still reaches it. There is no automatic retry. Unsent drafts from the closed tab are not retained in startup restoration. +If another window displays the same project connection, its tab closes too and that window shows a notification. The initiating window shows none. Closing is immediate; if the backend cannot close the project, an error appears and **Switch to open project** on the home page still reaches it. There is no automatic retry. Unsent drafts and attachments of the closed tab return when you reopen the same folder in that window; the window keeps them for its 16 most recently closed projects until it reloads or closes. They are not part of startup restoration. Closing a whole window, quitting or reloading does not close its project connections; normal startup restoration still applies. Stop relevant runs explicitly if you need to verify execution ended. CodeNomad never unloads native Locations; shared-service maintenance is described in [OpenCode setup](opencode.md). @@ -59,7 +59,7 @@ Close this server’s project tabs in every window before removing it or changin | Choice | Effect | Recovery | | --- | --- | --- | | Keep | Closes the project in CodeNomad, retains the folder and conversations, removes its temporary status and adds a recent project | Reopen from Recents; the folder is not moved | -| Discard | Deletes the temporary workspace's conversations and files | No undo; save anything needed elsewhere first | +| Discard | Deletes the temporary workspace's conversations, files and unsent drafts | No undo; save anything needed elsewhere first | | Cancel | Leaves the temporary workspace open | Continue working or decide later | An untouched temporary tab, with no conversation, file or unsent draft, is discarded quietly on close. Open temporary tabs participate in normal startup restoration, but the home page has no separate list for resuming closed temporary folders. diff --git a/docs/help/en/providers.md b/docs/help/en/providers.md index 8919160e30..0e0bbad901 100644 --- a/docs/help/en/providers.md +++ b/docs/help/en/providers.md @@ -56,15 +56,15 @@ For Google connections using OpenCode's Gemini CLI authentication method, **Usag Google's [Antigravity FAQ](https://antigravity.google/docs/faq/) states that using third-party software with an Antigravity login violates its terms and may lead to account suspension or termination. -For paid models on the `opencode` integration, **OpenCode Console** shows **Requests** for **Today (UTC)**, **7 days (UTC)** and **30 days (UTC)**. These are UTC calendar windows including today, beginning at 00:00 UTC today, six days ago and 29 days ago respectively. **Requests by model · 30 days** lists each model with its provider. Counts follow the connected Console account and use your app language's number formatting. **Service account budgets** shows **Budgets unavailable.** OpenCode Go uses its own quota reader. +For paid models on the `opencode` integration, **OpenCode Console** shows **Requests** for **24 hours**, **7 days** and **30 days**, as reported by Console. **Requests by model · 30 days** lists each model with its provider. Counts follow the connected Console account and use your app language's number formatting. **Service account budgets** shows **Budgets unavailable.** With **Provider credit balance** enabled, the Console credit balance appears as **Credits**. OpenCode Go uses its own quota reader. The reader uses the saved `opencode` API key or, preferentially, its OAuth Console connection. OAuth requires `https://opencode.ai/console` and the connection's organization ID; Console access needs the **Usage › Read** permission. CodeNomad never refreshes these credentials. An invalid or expired OAuth connection must be repaired through its owner, even when an API key is also saved. Console errors distinguish a missing connection, invalid or expired credentials (401), access denied (403), an invalid usage response, and network failure. For connection errors, use **Settings → Providers** to check the login and its permissions, then refresh **Usage**. A failed summary or model page makes the entire Console reading unavailable. -For free OpenCode models (`big-pickle` and model IDs ending in `-free`), **Usage** sums only the connected Console account's free-model requests since 00:00 UTC, against a daily reference of **800**. **Estimated** describes the allowance and next-UTC-midnight reset; actual limits may vary. The counter includes other clients using that account. Without a Console connection, the panel invites you to connect for free models and quota tracking through **Settings → Providers**. A failed Console read leaves the counter unavailable. +For free OpenCode models (`big-pickle` and model IDs ending in `-free`), **Usage** shows one bar: the connected Console account's free-model requests over Console's last 24 hours, against a reference of **800**; actual limits may vary. The counter includes other clients using that account and has no reset time. With **Provider credit balance** enabled, the Console credit balance appears as **Credits**. Without a Console connection, the panel asks you to connect OpenCode Console through **Settings → Providers**. A failed Console read leaves the counter unavailable. -A quota failure on a free-model step marks that OpenCode connection **Exhausted** until 00:00 UTC. When a Console count is available, the gauge shows 100% while preserving that count. The mark lives in backend memory per connection and clears on restart. Free usage, exhaustion and paid Console counters are display-only; automatic account selection uses its separate quota readers and rules. +Free usage and paid Console counters are display-only; automatic account selection uses its separate quota readers and rules. OpenAI does not provide usage for one ChatGPT sign-in method: Usage says so instead of showing quota windows. Choose [View ChatGPT usage](https://chatgpt.com/settings/usage) to review app usage and manage access to your plan and credits in ChatGPT. Chatting still works, and reconnecting the same login does not restore the reading. diff --git a/docs/help/en/remote-access.md b/docs/help/en/remote-access.md index c2b35f003b..ccb43ab149 100644 --- a/docs/help/en/remote-access.md +++ b/docs/help/en/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true Do not assume port 9898 or 9899: omitted ports can fall back when busy. An explicit nonzero `--https-port`, or `--http-port` with HTTP enabled, pins the port and fails if it cannot bind; `0` asks the OS to assign one. The printed **Local Connection URL** and **Remote Connection URL**, and refreshed **Reachable addresses**, are authoritative for that run. See the complete [server CLI reference](server.md). +## Administrator policy {#administrator-policy} + +An administrator can fix the listening address: set `CODENOMAD_LOCKED_HOST` machine-wide to the address the server must use, then restart CodeNomad. It wins over `--host`, `CLI_HOST` and **Allow connections from other IPs**, which shows the result but cannot change it. Use an intranet address so colleagues reach the server over the company network, or `127.0.0.1` to keep it on this computer. To keep all access inside the company network, also set `CODENOMAD_REMOTE_CONTROL=disabled` ([Remote Control](remote-control.md#administrator-policy)). + ## Upgrading {#upgrading} Sign in again after upgrading. For a hostname alias, reverse proxy or separately hosted UI, set `CODENOMAD_ALLOWED_ORIGINS` on the backend to the trusted UI origins (scheme, hostname and port). Native LAN clients must supply an allowed `Origin` header for mutations. Its HTTPS origins also let the host pair devices without the tunnel; see [Pair over direct HTTPS](remote-control.md#direct-https). -Use a loopback connection for host-only operations: SideCar content (`/sidecars/`) and WebSockets, Remote Control management (`/api/remote-control/`), the plugin bridge (`/api/opencode-plugin/`), remote proxies (`/api/remote-proxy/`), saved-server management (`/api/remote-servers/`), password changes and token bootstrap. These require loopback even when signed in through direct LAN access. Live preview content (`/previews/`) is available over direct LAN access with a valid capability token. +Use a loopback connection for host-only operations: SideCar content (`/sidecars/`) and WebSockets, Remote Control management (`/api/remote-control/`), the plugin bridge (`/api/opencode-plugin/`), remote proxies (`/api/remote-proxy/`), saved-server management (`/api/remote-servers/`), password changes and token bootstrap. These require loopback even when signed in through direct LAN access. Only SideCars have an exception: the host's **Open SideCars over HTTPS** setting opens their content and WebSockets to browsers signed in through a trusted HTTPS origin ([SideCars](browser-sidecars.md#register-sidecar)). Live preview content (`/previews/`) is available over direct LAN access with a valid capability token. The `/api/sidecars` registration APIs remain available to authenticated direct LAN clients and paired devices. Remote Control web previews remain available with their capability token while enabled on the host. diff --git a/docs/help/en/remote-control.md b/docs/help/en/remote-control.md index 831d8314a9..a6f4616a3d 100644 --- a/docs/help/en/remote-control.md +++ b/docs/help/en/remote-control.md @@ -86,3 +86,7 @@ CodeNomad uses [OpenTunnel](https://github.com/anomalyco/opentunnel) and claims TLS terminates in the CodeNomad backend. The relay forwards ciphertext and cannot read application contents, but can observe hostnames, connection timing and traffic sizes. The tunnel certificate/private key remain on the host. Protect the host's tunnel storage and CodeNomad configuration as credentials; an unguessable address is not authorization. `CODENOMAD_REMOTE_CONTROL_API` selects a self-hosted OpenTunnel API; unset uses the hosted service. This changes the tunnel deployment, not pairing requirements or the blocked surfaces. See [Security](security.md) for credential and diagnostic handling. + +## Administrator policy {#administrator-policy} + +An administrator can turn Remote Control off for everyone on a computer: set the environment variable `CODENOMAD_REMOTE_CONTROL=disabled` machine-wide, then restart CodeNomad. The backend never connects a tunnel, refuses **Start Remote Control** and pairing links and does not reconnect at launch; Settings shows **Disabled by administrator**. Devices paired earlier cannot connect and stay listed so you can revoke them. Unset or empty means no policy; any other value, including spaces only, prevents the backend from starting. diff --git a/docs/help/en/security.md b/docs/help/en/security.md index 435fbeffd4..6cc10c780a 100644 --- a/docs/help/en/security.md +++ b/docs/help/en/security.md @@ -33,7 +33,7 @@ Direct sign-in creates an opaque in-memory backend session and a `codenomad_sess Logout revokes the current direct session. A successful password change on the host revokes all that user's direct sessions, including the caller; sign in again. Sessions expire after 24 hours without authenticated requests or seven days from creation. Set `CODENOMAD_SESSION_IDLE_SECONDS` and `CODENOMAD_SESSION_ABSOLUTE_SECONDS` to positive integer seconds before starting the backend to adjust these limits. Remote Control devices are revoked separately. -LAN clients can sign in, sign out and use projects. Password changes, Remote Control management, remote-server/proxy tools and SideCars are managed on the loopback host. Browser mutations require an allowed Origin, or Referer when Origin is absent. The server's advertised origins are allowed; for DNS aliases, reverse proxies or a separately hosted UI, set `CODENOMAD_ALLOWED_ORIGINS` to comma-separated exact HTTP(S) origins, such as `https://code.example.test,https://ui.example.test:8443`, and restart. Use no paths or wildcards. This grants browser access, not host privileges. Native clients making LAN mutations must also supply an allowed Origin. A trusted proxy connected over loopback has host privileges and needs its own access controls. When the server listens on loopback or on all interfaces, the UI opened on the host as `localhost`, with the same scheme and port, also works. +LAN clients can sign in, sign out and use projects. Password changes, Remote Control management, remote-server/proxy tools and SideCars are managed on the loopback host. The host's **Open SideCars over HTTPS** setting opens SideCars to browsers signed in through a trusted HTTPS origin; turn it on only if every user of those addresses may use your SideCar services. Browser mutations require an allowed Origin, or Referer when Origin is absent. The server's advertised origins are allowed; for DNS aliases, reverse proxies or a separately hosted UI, set `CODENOMAD_ALLOWED_ORIGINS` to comma-separated exact HTTP(S) origins, such as `https://code.example.test,https://ui.example.test:8443`, and restart. Use no paths or wildcards. This grants browser access, not host privileges. Native clients making LAN mutations must also supply an allowed Origin. A trusted proxy connected over loopback has host privileges and needs its own access controls. When the server listens on loopback or on all interfaces, the UI opened on the host as `localhost`, with the same scheme and port, also works. For suspected compromise: diff --git a/docs/help/en/server.md b/docs/help/en/server.md index db2515cb90..cc222d2c51 100644 --- a/docs/help/en/server.md +++ b/docs/help/en/server.md @@ -8,7 +8,7 @@ The same UI supports [multiple project tabs and worktrees](projects.md), [conver 1. Install Node.js 24 LTS and npm; the repository pins its build runtime in `.node-version`. Desktop packages provide their own runtime: Electron uses its integrated Node, Tauri bundles Node, and both include npm. 2. Put Git on the **backend process's PATH**. Git inside WSL alone does not satisfy a Windows backend. -3. Install or select OpenCode: **2.2.3** is the required minimum and **2.2.7** the recommended qualification target. Newer or custom builds undergo compatibility checks, not a tested-version allowlist. See [OpenCode setup](opencode.md). +3. Install or select OpenCode: **2.3.0** is the required minimum and **2.3.0** the recommended qualification target. Newer or custom builds undergo compatibility checks, not a tested-version allowlist. See [OpenCode setup](opencode.md). 4. Choose the folder from which to start the server, or pass `--workspace-root` explicitly. Without Git, conversations remain available only in the explicitly opened physical folder; Git and worktree operations fail. Install Git and restart the backend after a PATH change. A workspace root limits opening/browsing, not agent execution: see [Security](security.md). @@ -104,6 +104,8 @@ The public reference lists user-facing options; desktop hosts manage their own p | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; repository queried for release offers. | | `CODENOMAD_REMOTE_CONTROL_API` | Unset: hosted OpenTunnel API. Set an API origin for a self-hosted relay deployment. | +| `CODENOMAD_REMOTE_CONTROL` | Unset: users may start Remote Control. `disabled`: turned off by an administrator ([policy](remote-control.md#administrator-policy)); unset or empty means no policy, any other value (spaces included) refuses startup. | +| `CODENOMAD_LOCKED_HOST` | Unset or empty: `--host` applies; spaces only refuse startup. An address: the server listens there whatever `--host`, `CLI_HOST` or the listening switch request ([policy](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | Node's optional additional CA file; passed with allowed startup environment when starting a missing OpenCode daemon. Does not change an already running daemon. | Provider-specific usage credentials are covered in [Providers](providers.md). Desktop data-profile selection is covered in [Desktop](desktop.md), not controlled by the release feed. diff --git a/docs/help/en/settings.md b/docs/help/en/settings.md index bddb219f9f..9c132a1232 100644 --- a/docs/help/en/settings.md +++ b/docs/help/en/settings.md @@ -70,7 +70,7 @@ Drag a docked panel's inner edge to resize it. The handle stays highlighted and 2. Open **Customize right panel** in the right panel. Use checkboxes to choose built-in tabs and Status sections; at least one Status section remains visible. Drag across these checkboxes to set several at once. 3. Drag right-panel tabs to reorder them. Use **Reset** to restore built-in layout choices. -Recognised [integrations](integrations.md#integration-sections) also have Status sections. Hide them with the same checkboxes; reorder any Status section by dragging or with Up/Down keys. Visibility and order persist across reloads and temporary absence of an integration. +Reorder any Status section by dragging or with Up/Down keys. Visibility and order persist across reloads. Status includes token information, Yolo mode, provider Usage, background shells, MCP and Plugins. While the conversation has a [goal](conversations.md#goal), a goal line above these sections shows it; that line is not a section and cannot be hidden or moved. Hiding a section does not disable its service or revoke permissions. Narrow layouts close panels that no longer fit instead of squeezing the conversation; a panel opened there floats over it, and opening one floating panel closes the other. diff --git a/docs/help/en/troubleshooting.md b/docs/help/en/troubleshooting.md index 3bc5c4a858..f8e8704627 100644 --- a/docs/help/en/troubleshooting.md +++ b/docs/help/en/troubleshooting.md @@ -42,7 +42,7 @@ If an owned worktree or conversation placement cannot be verified, open its phys ## OpenCode runtime and WSL {#opencode-runtime} 1. Open **Preferences → OpenCode** and check the **OpenCode version** card (installed version and running service status), then the selected executable under **OpenCode Binary**. -2. Use the supported installation/update action when the required runtime is missing. Current minimum: **2.2.3**; recommended/qualified version: **2.2.7**. +2. Use the supported installation/update action when the required runtime is missing. Current minimum: **2.3.0**; recommended/qualified version: **2.3.0**. 3. If the installed CLI differs from the running service, decide explicitly whether to restart the shared service. **Restart OpenCode service** is available under **Troubleshooting** and requires confirmation. It interrupts active work in every connected client, but retains session history. Configuration reload is a separate action: it keeps the process but rebuilds loaded Locations and cancels pending questions/permissions. Neither is a harmless refresh. diff --git a/docs/help/es/browser-sidecars.md b/docs/help/es/browser-sidecars.md index 683ddc3462..65d7fdb5c1 100644 --- a/docs/help/es/browser-sidecars.md +++ b/docs/help/es/browser-sidecars.md @@ -77,7 +77,7 @@ Si no es accesible, comprueba el proceso y el puerto en el backend. Si carga el Un SideCar es una extensión de confianza de CodeNomad, no una vista previa aislada: su página se ejecuta con el propio origen de CodeNomad, por lo que sus scripts pueden usar CodeNomad con tu acceso de sesión iniciada. Registra solo servicios cuyo código sea de tu confianza. CodeNomad no reenvía al servicio sus propias cookies de inicio de sesión, mientras que las cookies propias del servicio se conservan. -El contenido de SideCar (`/sidecars/`) y sus WebSockets requieren una conexión loopback en el anfitrión. El registro mediante `/api/sidecars` está disponible para dispositivos emparejados y clientes directos de LAN autenticados. El contenido de las vistas previas activas (`/previews/`) está disponible mediante acceso directo por LAN con un token de capacidad válido; las vistas previas web de [Control remoto](remote-control.md#remote-surface) siguen disponibles con su token de capacidad mientras estén activadas. Consulta [Actualizar](remote-access.md#upgrading) para los requisitos del acceso directo. +El contenido de SideCar (`/sidecars/`) y sus WebSockets requieren una conexión loopback en el anfitrión. Para abrirlos también desde otros dispositivos, activa **Abrir SideCars por HTTPS** en **Configuración → SideCars** en el anfitrión: los navegadores con sesión iniciada a través de las direcciones HTTPS de este servidor o de un origen HTTPS de `CODENOMAD_ALLOWED_ORIGINS`, como un proxy inverso TLS, podrán abrir SideCars. HTTP sin cifrar, las direcciones `localhost` y Control remoto siguen reservados al anfitrión. El registro mediante `/api/sidecars` está disponible para dispositivos emparejados y clientes directos de LAN autenticados. El contenido de las vistas previas activas (`/previews/`) está disponible mediante acceso directo por LAN con un token de capacidad válido; las vistas previas web de [Control remoto](remote-control.md#remote-surface) siguen disponibles con su token de capacidad mientras estén activadas. Consulta [Actualizar](remote-access.md#upgrading) para los requisitos del acceso directo. ## Ejemplo de OpenVSCode Server {#openvscode} diff --git a/docs/help/es/conversations.md b/docs/help/es/conversations.md index 49d00efda6..ff1dd2600c 100644 --- a/docs/help/es/conversations.md +++ b/docs/help/es/conversations.md @@ -60,6 +60,12 @@ En el escritorio, enviar mueve el foco del teclado a la conversación, de modo q Los borradores son estado de trabajo del cliente, no mensajes nativos compartidos. La restauración al iniciar puede conservar el estado compatible del editor, pero no trates un borrador o adjunto sin enviar como una copia de seguridad ni supongas que aparece en otro dispositivo. Guarda el texto importante antes de borrar los datos de inicio o cerrar un cliente cuya política de restauración esté desactivada; consulta [Escritorio](desktop.md). +## Abrir archivos desde las respuestas {#open-files-from-replies} + +1. Las respuestas del agente enlazan archivos del proyecto con rutas relativas y absolutas. +2. Un clic normal abre el archivo enlazado en la vista previa del archivo, leído del worktree de la conversación. +3. Los clics con modificadores (Ctrl/⌘-clic, Mayús-clic, clic central) y los enlaces fuera del worktree de la sesión mantienen el comportamiento normal de los enlaces. + ## Comandos y modo shell {#commands-shell} 1. Escribe `/` y selecciona un comando personalizado descubierto; después, proporciona sus argumentos. diff --git a/docs/help/es/install.md b/docs/help/es/install.md index fed5f93e11..218b6a7a5b 100644 --- a/docs/help/es/install.md +++ b/docs/help/es/install.md @@ -45,7 +45,7 @@ La instalación Debian de Electron configura el aislamiento de Chromium. No desa | Requisito | Dónde debe estar disponible | Requisito actual | | --- | --- | --- | -| CLI de OpenCode | Equipo de ejecución seleccionado, incluida la distribución WSL seleccionada cuando corresponda | Mínimo **2.2.3**; **2.2.7** es la versión recomendada/verificada. Las versiones más nuevas o personalizadas pasan una validación de contratos en lugar de prohibirse por no haberse probado. | +| CLI de OpenCode | Equipo de ejecución seleccionado, incluida la distribución WSL seleccionada cuando corresponda | Mínimo **2.3.0**; **2.3.0** es la versión recomendada/verificada. Las versiones más nuevas o personalizadas pasan una validación de contratos en lugar de prohibirse por no haberse probado. | | Git | `PATH` de la cuenta del backend de CodeNomad | Necesario para la identidad del repositorio, las operaciones Git y los worktrees. | | Node.js/npm | Equipo del servidor independiente y de compilación desde el código fuente | Node.js 24 LTS; las compilaciones reproducibles desde el código fuente usan la versión fijada en `.node-version`. Las versiones de escritorio incluyen el suyo: el Node integrado de Electron o el Node que incluye Tauri, con npm. | | Carpeta del espacio de trabajo | Disco accesible para el backend | Una carpeta física abierta explícitamente, no una carpeta local del dispositivo deducida por un navegador remoto. | diff --git a/docs/help/es/integrations.md b/docs/help/es/integrations.md index 517dab55e0..70d69e25fa 100644 --- a/docs/help/es/integrations.md +++ b/docs/help/es/integrations.md @@ -27,7 +27,7 @@ Si no aparece ningún servidor, verifica la Location activa y su configuración Los plugins gestionados por CodeNomad quedan fuera de la lista ordinaria y de sus controles de activación, actualización y eliminación. CodeNomad los reconoce por la entrada validada del instalador y la ubicación de su código identificado por su huella de contenido; un plugin de terceros con el mismo nombre o ID conserva sus controles ordinarios. -Si un plugin gestionado está desactivado, no se carga o su carga sigue sin confirmarse, aparece **Los plugins de CodeNomad requieren atención** encima de la lista de Plugins. Abre su botón **i** (**Detalles de** ese plugin) para ver el error disponible y la referencia en el registro de OpenCode. Solo un plugin desactivado ofrece **Reactivar**: añade una regla de activación positiva para el ID exacto y conserva la regla de desactivación. Escribe en el ámbito **Global** o **Proyecto** de la regla de desactivación si permite escritura; de lo contrario, en **Proyecto**. OpenCode sigue funcionando; el aviso permanece hasta que los eventos nativos o **Actualizar controles de plugins** confirmen que el plugin está activo. +Si un plugin gestionado está desactivado, no se carga o su carga sigue sin confirmarse, aparece **Los plugins de CodeNomad requieren atención** encima de la lista de Plugins. Abre su botón **i** (**Detalles de** ese plugin) para ver el error disponible y la referencia en el registro de OpenCode. Solo un plugin desactivado ofrece **Reactivar**: quita de ese archivo la regla exacta que desactiva el plugin cuando eso basta para reactivarlo y, si no, añade una regla positiva para el ID exacto. Escribe en el ámbito **Global** o **Proyecto** de la regla de desactivación si permite escritura; de lo contrario, en **Proyecto**. OpenCode sigue funcionando; el aviso permanece hasta que los eventos nativos o **Actualizar controles de plugins** confirmen que el plugin está activo. El aviso y sus detalles identifican el origen de la configuración como **Heredada / externa** o **Configuración virtual**, según corresponda. Una etiqueta **Proyecto** separada indica el destino de reactivación cuando difiere del origen de la regla de desactivación. @@ -38,7 +38,7 @@ El aviso y sus detalles identifican el origen de la configuración como **Hereda Global apunta a la configuración global descubierta del daemon conectado. Proyecto apunta a la configuración dentro de la Location activa, no a un archivo de un antecesor heredado. Una regla posterior de Proyecto puede prevalecer sobre Global; el interruptor Global sigue mostrando la regla Global en lugar de fingir que es el estado final del Proyecto. Sin regla de Proyecto, Proyecto hereda el estado Global resuelto. -Estos interruptores añaden reglas exactas de activación conservando las declaraciones de origen y la configuración no relacionada. No editan opciones de plugins, instalan paquetes ni eliminan archivos. Los plugins integrados de OpenCode no se ofrecen como interruptores de activación del usuario. Proyecto se desactiva cuando su destino no puede separarse de Global con seguridad o saldría de la Location activa. +Cada interruptor escribe una regla exacta de activación para el plugin en el archivo de su ámbito, sustituyendo allí las reglas exactas anteriores de ese plugin, o solo las quita cuando el resultado es el mismo. Se conservan las declaraciones de origen, las reglas más amplias como `*` y la configuración no relacionada. No editan opciones de plugins, instalan paquetes ni eliminan archivos. Los plugins integrados de OpenCode no se ofrecen como interruptores de activación del usuario. Proyecto se desactiva cuando su destino no puede separarse de Global con seguridad o saldría de la Location activa. Una actualización de paquete cambia ese paquete en la caché compartida de OpenCode para todas las Locations que lo usan, como indica su ayuda emergente; no cambia las reglas de activación, no reinicia OpenCode ni recarga la configuración. Los plugins locales, integrados y proporcionados por el SDK no tienen acción de paquete. Un paquete que falla antes de informar del ID de su plugin aparece con su nombre de paquete, con el fallo en su ayuda emergente y las acciones de comprobar/actualizar, pero sin interruptores de activación. Una comprobación o actualización fallida se notifica y nunca se reintenta automáticamente. @@ -78,38 +78,30 @@ La disponibilidad de habilidades procede de la Location de la conversación, no Los comandos se descubren desde OpenCode para la Location activa. Su propia definición nativa puede elegir el comportamiento de ejecución; el menú no es un instalador de paquetes ni un editor de configuración sin restricciones. CodeNomad aplica el entorno de sesión del perfil antes de enviar el comando personalizado nativo; un fallo al actualizar el entorno bloquea el envío. `/btw` es el flujo aparte de preguntas efímeras de CodeNomad, no un comando personalizado normal. Para definiciones de comandos y herencia de configuración nativa, usa la [documentación de comandos de OpenCode](https://opencode.ai/v2/docs/commands/). Tras cambios de configuración, actualiza/reabre primero la superficie correspondiente; usa la recarga explícita de configuración solo si el entorno de ejecución aún la necesita. Nunca repitas un comando posiblemente admitido solo para actualizar su visualización. -## Secciones de integración en Estado {#integration-sections} +## Integraciones en Plugins {#integration-rows} En **Estado → Plugins**, **+** ofrece **Añadir una integración…** o **Añadir un plugin…**. El selector de integraciones muestra las entradas no instaladas del catálogo revisado. Elige el ámbito e **Instalar**: CodeNomad instala el ID del catálogo seleccionado. Las integraciones nativas usan **Solo global**. **Catálogo no disponible** ofrece **Actualizar**; **Catálogo del {date}** identifica el último catálogo válido cuando está obsoleto. -Cada integración reconocida con una declaración o un plugin cargado/con error tiene su sección en **Estado**, incluso desactivada o instalándose. Una fuente ambigua muestra **No conforme** en Plugins. Cada integración conserva su fila de Plugins con acciones de actualización, eliminación y refresco. Despliega su sección para ver la versión y los controles del plugin en el cuerpo; nombre y estado siguen visibles en la cabecera junto a **Documentación** e **i**. El popover **i** muestra detalles a petición: se abre con Intro/Espacio y se cierra con Escape. +Una integración reconocida tiene una fila en **Estado → Plugins**, con su nombre (por ejemplo **OpenCode for Blender**) y su versión. Sus interruptores **Global** y **Proyecto** usan el color de acento como los demás interruptores, los de un plugin simple son verdes; una integración con una parte dentro de una aplicación es **Solo global**. Pasa el puntero sobre su nombre: los detalles empiezan por **Integración** en lugar de **Plugin**; los lectores de pantalla los leen como descripción de la fila. Una fuente ambigua muestra **No conforme**. -La personalización de Estado permite ocultar todas las secciones y reordenarlas arrastrando o con las teclas Arriba/Abajo. La visibilidad y el orden persisten al recargar y durante la ausencia temporal de una integración. Si desaparece una sección enfocada, el foco vuelve a Plugins, o a otra sección de Estado visible si Plugins está oculto. +Bajo el nombre, una línea de estado indica siempre en qué punto está la integración. El texto gris informa; el texto en color de acento es un botón. En una integración con una parte dentro de una aplicación se muestra el estado más importante: **Instalar en Blender** o **Actualizar Blender** cuando su parte falta o es antigua (con la confirmación de instalación), una incompatibilidad en el color de aviso, un icono de cadena y el documento cuando la conversación visible está vinculada (púlsalo para desvincularla), **Blender cerrado**, **Blender: ningún documento abierto**, **No se muestra ninguna conversación**, y después **Vincular** con el nombre del documento, o **Vincular…** para elegir entre varios documentos. Una conversación también se vincula sola la primera vez que su agente usa la integración. Las integraciones MCP de editor muestran **Servidor detectado** o **Servidor no encontrado**; las de API, **Conectado** o **Desconectado**. Un estado largo se acorta; pasa el puntero para ver el texto completo. Los cambios que comunica la integración y las reconexiones actualizan la línea. -Instalar desde el catálogo, instalar/actualizar la parte de la aplicación, vincular y quitar requieren confirmación. **Cancelar** recibe el foco inicial; la acción de confirmación se habilita tras 600 ms. La activación y las actualizaciones del plugin se ejecutan directamente. +El menú **…** de la fila empieza por el estado de la conexión, por ejemplo **Blender: 1 documento abierto** o **Blender cerrado**. Después ofrece **Documentación**, **Instalar en la aplicación…**, **Actualizar la aplicación…** o **Reinstalar en la aplicación…** ([ver más abajo](#application-installation)), la comprobación de actualizaciones del paquete, **Quitar de Global** o **Quitar de Proyecto** y **Actualizar controles de plugins**. Desvincular requiere un clic sin confirmación y solo afecta a esta conversación: la aplicación sigue abierta, su parte sigue instalada y las demás conversaciones conservan su vínculo. Si se pierde la respuesta, la fila vuelve a leer el estado; la solicitud nunca se repite. -## Vincular una aplicación abierta {#application-attachment} +La instalación desde el catálogo, la instalación o actualización de la parte de la aplicación y la eliminación requieren confirmación. **Cancelar** recibe el foco primero; la acción de confirmación se habilita tras 600 ms. La activación, las actualizaciones de plugins, la vinculación y la desvinculación se ejecutan directamente. -Ofrece un documento desde la integración de la aplicación, abre **Estado → la integración → Conversación** y elige **Vincular…**. Esta sección controla el vínculo de la conversación mostrada. Selecciona aplicación y documento, revisa la conversación de destino y la advertencia de modificación y confirma con **Vincular**. La aplicación se ejecuta en el equipo de OpenCode, también en conexiones remotas. Los hosts no compatibles, incluido WSL, ofrecen ayuda mediante **i**. - -La fila **Conversación** consulta el vínculo de la conversación mostrada. **Vínculo desconocido** ofrece **Actualizar**. Cuando una consulta reciente y autoritativa confirma el vínculo, **Desvincular** sustituye a **Vincular…**. Un clic desvincula solo esta conversación, sin otra confirmación; la aplicación sigue abierta, su parte instalada y las demás conversaciones conservan sus vínculos. Los cambios nativos y las reconexiones actualizan el estado. - -Una acción admitida conserva su resultado o error mientras siga visible la conversación de destino; navegar cierra su recibo. El vínculo actual sigue la consulta autoritativa. **Estado incierto** tras perder una respuesta, agotar el tiempo o desconectarse ofrece **Actualizar** para consultar el estado real. Nunca repitas la solicitud para refrescar la pantalla. - -Tras consultar explícitamente las aplicaciones abiertas en el selector, los metadatos Q8 guardados pueden ofrecer **Volver a vincular** en el selector o la fila **Conversación** para la misma integración y una etiqueta de documento validada, mientras se mantengan el proyecto, la conversación y la generación de conexión. Volver a vincular requiere confirmación explícita; navegar o invalidar los datos borra la sugerencia. La autoridad sobre el vínculo actual procede de la consulta por sesión de la integración. - -Quitar desde la sección de integración o su fila de Plugins usa la misma declaración y confirmación de ámbito. Se realiza sin censar conversaciones ni desvincularlas automáticamente. +La eliminación se realiza sin recuento de conversaciones ni desvinculación automática. Al quitar un plugin se muestra una advertencia con su nombre y ámbito exacto. **Cancelar** recibe el foco; **Quitar de Global/Proyecto** se habilita tras 600 ms y exige una acción explícita. Puede interrumpir la disponibilidad y las conexiones de las conversaciones que lo usan; Global también puede afectar a otros proyectos. Cancelar, dejar caducar o navegar antes del envío no cambia nada. Solo se quita la declaración confirmada; se conservan reglas, caché, archivos de la aplicación y pistas guardadas de conexión. Si cambia la configuración, selecciona y confirma de nuevo. El éxito confirma la eliminación de la declaración; el estado de ejecución sigue la recarga de OpenCode. Si se pierde la respuesta, actualiza Plugins para comprobar la configuración antes de reintentar. Reinstalar puede restaurar la disponibilidad; puede ser necesario recargar o volver a vincular y las operaciones interrumpidas podrían no reanudarse. ## Instalar o actualizar la integración de la aplicación {#application-installation} -En **Estado → la integración → Aplicación**, elige **Instalar en la aplicación…** o **Actualizar la aplicación…** cuando el estado reciente ofrezca la acción. Está disponible sin conversación ni documento ofrecido. Si la aplicación está cerrada, ábrela para comprobar su parte de aplicación; **i** muestra el equipo y los requisitos. +En **Estado → Plugins**, pulsa **Instalar en Blender** o **Actualizar Blender** en la línea de estado de la integración cuando su estado actual ofrece la acción, o elige **Instalar en la aplicación…**, **Actualizar la aplicación…** o **Reinstalar en la aplicación…** en su menú **…**. Reinstalar vuelve a escribir la parte de la aplicación, esté abierta o cerrada. Está disponible sin conversación ni documento abierto. La confirmación indica la aplicación y la **versión del paquete de integración** que proporciona el instalador. Comprueba ambos datos y la advertencia sobre el equipo: la instalación se ejecuta en el equipo donde se ejecuta OpenCode, que puede ser remoto. **Cancelar** recibe el foco inicial. Confirma explícitamente para continuar. Cambiar de proyecto, Location o conversación, reconectar o recibir cambios nativos relevantes antes de confirmar cancela la aprobación pendiente; vuelve a abrir la acción para revisar los datos actualizados. WSL siempre rechaza la instalación en la aplicación, aunque una aplicación abierta parezca compatible. Abre la aplicación en un equipo compatible. -El resultado indica instalación, actualización, versión ya actualizada, rechazo o fallo. Tras instalar o actualizar, abre la aplicación y comprueba su integración; vincula una conversación por separado mediante [Vincular una aplicación abierta](#application-attachment). El éxito describe la solicitud de instalación; la disponibilidad de la aplicación procede de su estado. +El resultado indica que la parte de la aplicación se instaló, se actualizó, ya estaba al día, se rechazó o falló. Tras instalar o actualizar, abre la aplicación y comprueba su integración. El éxito de la instalación describe la solicitud del instalador; la disponibilidad real de la aplicación procede de su estado. Las solicitudes nunca se reintentan automáticamente. Tras un rechazo o fallo, comprueba la aplicación antes de elegir una nueva acción. Si un error deja el resultado incierto, nunca repitas esa solicitud: inspecciona primero la aplicación e inicia una nueva acción con confirmación si hace falta. diff --git a/docs/help/es/missions.md b/docs/help/es/missions.md index 9b19037855..0eaf798b9e 100644 --- a/docs/help/es/missions.md +++ b/docs/help/es/missions.md @@ -42,7 +42,7 @@ La programación basada en calendario requiere agente y modelo explícitos para ### Iniciar automáticamente {#automatic-start} -**Iniciar automáticamente** está fuera de Programación y desactivado por defecto. Desactivado crea una Misión en pausa para iniciarla después desde ▶. Activado solicita el inicio tras confirmar la creación, con las comprobaciones habituales y el consentimiento nativo necesario. +**Iniciar automáticamente** está fuera de Programación y desactivado por defecto. Desactivado crea una Misión en pausa para iniciarla después desde ▶. Activado solicita el inicio tras confirmar la creación, con las comprobaciones habituales y la preparación automática de la programación. Si se pierde la confirmación, leer el recibo deja el inicio manual. Conserva la solicitud original no confirmada y comprueba lista y conversación antes de crear otra vez. @@ -56,6 +56,8 @@ El primer criterio es **Una vez, ahora**. **Añadir un criterio** agrega otro. E Hay una vez ahora, cada N horas, diario, días de semana, día del mes y cron. Se usa la zona guardada; su campo aparece si difiere de la del sistema. Los meses sin el día elegido se omiten. Una vez ahora fija su instante al iniciar y ofrece una sola oportunidad, que una condición puede consumir sin lanzar. Se necesitan OpenCode y el equipo de ejecución disponibles. +Al iniciar o reanudar, la programación se prepara automáticamente en la configuración OpenCode del proyecto. Se conserva un OFF explícito: **Abrir los ajustes de programación**, cuando esté disponible, abre el archivo responsable; **i** muestra el origen o los detalles del entorno. El botón pulsado indica carga solo durante la solicitud. Un resultado sin confirmar permite verificarlo; recuperar la activación deja el inicio como acción explícita. + ### Eventos y combinaciones {#scheduling-conditions} Elige **Actividad del repositorio → Evento** y los filtros opcionales en la misma tarjeta. Los commits de Git comparten este menú con los eventos del repositorio GitHub, GitLab o Gitea detectado automáticamente, como en Contribute (`upstream`, luego `origin`). Los tres admiten nuevas PR/MR, PR/MR fusionadas y nuevas issues, con **Autor (opcional)**, incluido `dependabot[bot]`. Elegir un evento fija su repositorio; los criterios guardados conservan su destino. @@ -88,9 +90,11 @@ Más entradas y tareas se cargan automáticamente al acercarse al final. Las pá ### Colores y estados {#status-colours} -La bandera muestra la Misión y el chevrón la atención de sus tareas; las recurrentes usan repetición. Rojo pide respuesta, amarillo pulsante indica trabajo observado, naranja pausa/interrupción, verde un resultado no visto y azul preparación o tarea no iniciada. +La bandera muestra la Misión y el chevrón la atención de sus tareas; las recurrentes usan repetición. Rojo pide respuesta y amarillo pulsante indica trabajo observado. Un símbolo de pausa naranja indica pausa; un triángulo de advertencia naranja, interrupción. Verde indica una Misión, tarea o ejecución correcta pendiente de revisión. + +Un icono de acento con una pequeña línea neutra estática debajo significa **Esperando ejecución programada**: la próxima activación está confirmada. El acento sigue la paleta. El icono de acento solo indica preparación o una tarea sin iniciar. Los resultados revisados, las programaciones detenidas y **Estado sin confirmar** son neutros; consulta el texto de estado. -Seleccionar o pulsar/barrer iconos verdes confirma resultados; el menú del chevrón permite marcarlos como leídos. Un bloqueo no siempre es una pregunta; un informe no prueba que toda operación nativa haya terminado. Las tareas retiradas conservan historial. +Seleccionar o pulsar/barrer iconos verdes confirma resultados; el menú del chevrón ofrece **Marcar como leído**. Para **Ejecución correcta por revisar**, selecciona explícitamente la fila recurrente en la ventana activa o usa **Marcar como leído** para confirmar esa ejecución. El icono vuelve a espera si la programación sigue activa; en caso contrario, a neutro. La selección restaurada y los resultados que llegan a una fila ya seleccionada mantienen el nuevo resultado sin leer. Los éxitos históricos presentes en la primera carga comienzan como leídos. Las tareas retiradas conservan historial. ### Preguntas y decisiones {#questions} diff --git a/docs/help/es/mobile.md b/docs/help/es/mobile.md index 5aa1c33974..5cbed5650d 100644 --- a/docs/help/es/mobile.md +++ b/docs/help/es/mobile.md @@ -42,3 +42,5 @@ El editor de mensajes mantiene Agente, Modelo y Razonamiento en su pie. El campo | Trabajo sin conexión | No hay backend sin conexión ni historial API en caché. Los recursos estáticos de interfaz pueden almacenarse en caché, pero los documentos y respuestas API no son un espacio de trabajo sin conexión. | Mantén el backend accesible. La suspensión del sistema móvil o un cambio de red pueden desconectar el flujo de eventos; al volver se reconecta y obtiene el estado actual, sin reproducción garantizada de eventos. Comprueba si una acción terminó antes de reintentar. Cerrar la PWA no detiene un backend independiente; salir de la aplicación de escritorio anfitriona y su backend deja Control remoto no disponible hasta el siguiente inicio. + +Cada pestaña del navegador, incluida la PWA instalada, conserva para esa pestaña sus proyectos abiertos, conversaciones seleccionadas, borradores sin enviar y posiciones de desplazamiento: vuelven cuando la página se recarga, o cuando el sistema móvil la recarga tras cambiar de aplicación o bloquear la pantalla. Una pestaña nueva, o una PWA que el sistema cerró por completo, se abre en la página de inicio. Desactívalo para la pestaña en **Configuración → General → Restaurar el estado anterior**. diff --git a/docs/help/es/opencode.md b/docs/help/es/opencode.md index 40f4ad8d5f..b73466b3ad 100644 --- a/docs/help/es/opencode.md +++ b/docs/help/es/opencode.md @@ -19,8 +19,8 @@ El ejecutable instalado y el servicio en ejecución pueden tener versiones disti | Clasificación | Requisito actual | Significado | | --- | --- | --- | -| Mínima | OpenCode **2.2.3** | La herramienta de generación de imágenes que usan los ajustes de **Imágenes** y la extensión Design, además del orden correcto de las tareas JavaScript en Code Mode y el formato nativo de reproducción y compactación; las conversaciones guardadas con versiones anteriores siguen siendo legibles tras actualizar. | -| Recomendada | OpenCode **2.2.7** | Objetivo verificado, distinto del mínimo técnico. | +| Mínima | OpenCode **2.3.0** | La herramienta de generación de imágenes que usan los ajustes de **Imágenes** y la extensión Design, además del orden correcto de las tareas JavaScript en Code Mode y el formato nativo de reproducción y compactación; las conversaciones guardadas con versiones anteriores siguen siendo legibles tras actualizar. También entrega los resultados de los subagentes como informes en segundo plano, que leen las tarjetas de subagente y las Misiones. | +| Recomendada | OpenCode **2.3.0** | Objetivo verificado; actualmente la misma versión que la mínima. | | No verificada | Una versión más nueva o personalizada no validada por completo | No se rechaza simplemente por no estar probada; se comprueban los contratos API reales del servicio conectado. | El servicio conectado debe exponer los contratos requeridos de sesiones, permisos, formularios, bandeja de entrada y entorno de sesión. La programación nativa de Misiones también comprueba las API de programación, el paquete de plugin/proveedor y el ajuste efectivo `experimental.schedules`. La disponibilidad depende de esas capacidades utilizadas, también en versiones futuras compatibles. Si la configuración inicial informa de un servicio en ejecución no compatible, selecciona/instala una CLI compatible y usa el reinicio explícito del servicio compartido cuando estés listo. diff --git a/docs/help/es/projects.md b/docs/help/es/projects.md index 413a764845..16dcbbb78e 100644 --- a/docs/help/es/projects.md +++ b/docs/help/es/projects.md @@ -34,7 +34,7 @@ Un clic normal sigue abriendo la página de inicio completa. El lanzador es un a | Cerrar pestaña | Retira la conexión de proyecto de CodeNomad de esa pestaña; otra pestaña abierta por separado en la misma carpeta no se ve afectada | No elimina archivos del proyecto ni el historial nativo, no detiene sesiones ni descarga la Location de OpenCode | | Detener sesión | Ejecución de la conversación seleccionada | No cierra el proyecto ni elimina su historial | -Si otra ventana muestra la misma conexión de proyecto, su pestaña también se cierra y esa ventana muestra una notificación. La ventana que inicia el cierre no muestra ninguna. El cierre es inmediato; si el backend no puede cerrar el proyecto, aparece un error y **Cambiar al proyecto abierto** en la página de inicio sigue llevando a él. No hay reintento automático. Los borradores sin enviar de la pestaña cerrada no se conservan en la restauración al iniciar. +Si otra ventana muestra la misma conexión de proyecto, su pestaña también se cierra y esa ventana muestra una notificación. La ventana que inicia el cierre no muestra ninguna. El cierre es inmediato; si el backend no puede cerrar el proyecto, aparece un error y **Cambiar al proyecto abierto** en la página de inicio sigue llevando a él. No hay reintento automático. Los borradores y adjuntos sin enviar de la pestaña cerrada vuelven al reabrir la misma carpeta en esa ventana; la ventana los conserva para sus 16 últimos proyectos cerrados hasta que se recarga o se cierra. No forman parte de la restauración al iniciar. Cerrar una ventana entera, salir o recargar no cierra sus conexiones de proyecto; se sigue aplicando la restauración normal al iniciar. Detén explícitamente las ejecuciones relevantes si necesitas verificar que la ejecución terminó. CodeNomad nunca descarga las Locations nativas; el mantenimiento del servicio compartido se describe en [configuración de OpenCode](opencode.md). @@ -59,7 +59,7 @@ Cierra las pestañas de proyecto de este servidor en todas las ventanas antes de | Opción | Efecto | Recuperación | | --- | --- | --- | | Conservar | Cierra el proyecto en CodeNomad, conserva la carpeta y las conversaciones, retira su condición temporal y añade un proyecto reciente | Vuelve a abrirlo desde Carpetas recientes; la carpeta no se mueve | -| Descartar | Elimina las conversaciones y los archivos del espacio de trabajo temporal | No se puede deshacer; guarda primero en otro lugar lo que necesites | +| Descartar | Elimina las conversaciones, los archivos y los borradores sin enviar del espacio de trabajo temporal | No se puede deshacer; guarda primero en otro lugar lo que necesites | | Cancelar | Deja abierto el espacio de trabajo temporal | Continúa trabajando o decide más tarde | Una pestaña temporal sin usar, sin conversación, archivo ni borrador sin enviar, se descarta silenciosamente al cerrarla. Las pestañas temporales abiertas participan en la restauración normal al iniciar, pero la página de inicio no tiene una lista aparte para reabrir carpetas temporales cerradas. diff --git a/docs/help/es/providers.md b/docs/help/es/providers.md index 821e2c9614..a54a588246 100644 --- a/docs/help/es/providers.md +++ b/docs/help/es/providers.md @@ -56,15 +56,15 @@ Para las conexiones de Google que usan el método de autenticación Gemini CLI d Las [preguntas frecuentes de Antigravity](https://antigravity.google/docs/faq/) de Google indican que usar software de terceros con un inicio de sesión de Antigravity infringe sus condiciones y puede provocar la suspensión o cancelación de la cuenta. -Para los modelos de pago de la integración `opencode`, **OpenCode Console** muestra **Solicitudes** para **Hoy (UTC)**, **7 días (UTC)** y **30 días (UTC)**. Son periodos de días naturales UTC que incluyen hoy y comienzan a las 00:00 UTC de hoy, de hace seis días y de hace 29 días, respectivamente. **Solicitudes por modelo · 30 días** indica cada modelo y su proveedor. Los contadores corresponden a la cuenta de Console conectada y usan el formato numérico del idioma de la aplicación. **Presupuestos de cuentas de servicio** muestra **Presupuestos no disponibles.** OpenCode Go usa su propio lector de cuota. +Para los modelos de pago de la integración `opencode`, **OpenCode Console** muestra **Solicitudes** para **24 horas**, **7 días** y **30 días**, según las indica Console. **Solicitudes por modelo · 30 días** indica cada modelo y su proveedor. Los contadores corresponden a la cuenta de Console conectada y usan el formato numérico del idioma de la aplicación. **Presupuestos de cuentas de servicio** muestra **Presupuestos no disponibles.** Con **Saldo de créditos del proveedor** activado, el saldo de créditos de Console aparece como **Créditos**. OpenCode Go usa su propio lector de cuota. El lector usa la clave API `opencode` guardada o, preferentemente, su conexión OAuth de Console. OAuth requiere `https://opencode.ai/console` y el ID de organización de la conexión; el acceso a Console necesita el permiso **Usage › Read**. CodeNomad nunca renueva estas credenciales. Una conexión OAuth no válida o caducada debe repararse mediante su propietario, aunque también haya una clave API guardada. Los errores de Console distinguen conexión ausente, credenciales no válidas o caducadas (401), acceso denegado (403), respuesta de uso no válida y fallo de red. Para errores de conexión, abre **Configuración → Proveedores**, comprueba el inicio de sesión y sus permisos y actualiza **Uso**. Si falla un resumen o una página de modelos, toda la lectura de Console queda no disponible. -Para los modelos gratuitos de OpenCode (`big-pickle` e IDs terminados en `-free`), **Uso** suma solo las solicitudes gratuitas de la cuenta Console conectada desde las 00:00 UTC, frente a una referencia diaria de **800**. **Estimado** describe la cuota y el reinicio en la siguiente medianoche UTC; los límites reales pueden variar. El contador incluye otros clientes de la cuenta. Sin conexión Console, el panel invita a conectar los modelos gratuitos y consultar las cuotas mediante **Configuración → Proveedores**. Si falla la lectura de Console, el contador queda no disponible. +Para los modelos gratuitos de OpenCode (`big-pickle` e IDs terminados en `-free`), **Uso** muestra una sola barra: las solicitudes gratuitas de la cuenta Console conectada en las últimas 24 horas de Console, frente a una referencia de **800**; los límites reales pueden variar. El contador incluye otros clientes de la cuenta y no tiene hora de reinicio. Con **Saldo de créditos del proveedor** activado, el saldo de créditos de Console aparece como **Créditos**. Sin conexión Console, el panel pide conectar OpenCode Console mediante **Configuración → Proveedores**. Si falla la lectura de Console, el contador queda no disponible. -Un fallo de cuota en un paso gratuito marca esa conexión OpenCode como **Agotado** hasta las 00:00 UTC. Si hay un contador Console disponible, el indicador muestra 100 % y conserva ese contador. La marca se guarda en memoria del backend por conexión y se borra al reiniciar. El uso gratuito, el agotamiento y los contadores de pago son solo informativos; la selección automática de cuenta usa sus propios lectores y reglas. +El uso gratuito y los contadores de pago de Console son solo informativos; la selección automática de cuenta usa sus propios lectores y reglas. OpenAI no proporciona datos de uso para uno de los métodos de inicio de sesión de ChatGPT: Uso lo indica en lugar de mostrar periodos de cuota. Elija [Ver uso de ChatGPT](https://chatgpt.com/settings/usage) para consultar el uso de las aplicaciones y gestionar su acceso a su plan y créditos en ChatGPT. Chatear sigue funcionando, y volver a conectar el mismo inicio de sesión no restaura la lectura. diff --git a/docs/help/es/remote-access.md b/docs/help/es/remote-access.md index 2ecad049a6..0a0597cd01 100644 --- a/docs/help/es/remote-access.md +++ b/docs/help/es/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true No supongas que el puerto es 9898 o 9899: los puertos omitidos pueden cambiar si están ocupados. Un `--https-port` explícito distinto de cero, o un `--http-port` con HTTP activado, fija el puerto y falla si no puede escuchar; `0` pide al sistema operativo que asigne uno. Las **Local Connection URL** y **Remote Connection URL** indicadas, y las **Direcciones accesibles** actualizadas, son autoritativas para esa ejecución. Consulta la [referencia completa de la CLI del servidor](server.md). +## Política del administrador {#administrator-policy} + +Un administrador puede fijar la dirección de escucha: define `CODENOMAD_LOCKED_HOST` para todo el sistema con la dirección que debe usar el servidor y reinicia CodeNomad. Tiene prioridad sobre `--host`, `CLI_HOST` y **Permitir conexiones desde otras IP**, que muestra el resultado pero no puede cambiarlo. Usa una dirección de la intranet para que los compañeros accedan por la red de la empresa, o `127.0.0.1` para mantenerlo en este equipo. Para que todo acceso quede dentro de la red de la empresa, define también `CODENOMAD_REMOTE_CONTROL=disabled` ([control remoto](remote-control.md#administrator-policy)). + ## Actualizar {#upgrading} Vuelve a iniciar sesión después de actualizar. Para un alias de nombre de host, un proxy inverso o una interfaz alojada por separado, configura `CODENOMAD_ALLOWED_ORIGINS` en el backend con los orígenes de confianza de la interfaz (esquema, nombre de host y puerto). Los clientes nativos de la LAN deben enviar una cabecera `Origin` permitida en las solicitudes de modificación. Sus orígenes HTTPS también permiten al anfitrión emparejar dispositivos sin el túnel; consulta [Emparejar por HTTPS directo](remote-control.md#direct-https). -Usa una conexión loopback para las operaciones reservadas al anfitrión: contenido de SideCar (`/sidecars/`) y WebSockets, gestión de Control remoto (`/api/remote-control/`), puente de plugins (`/api/opencode-plugin/`), proxies remotos (`/api/remote-proxy/`), gestión de servidores guardados (`/api/remote-servers/`), cambios de contraseña e inicialización por token. Estas operaciones requieren loopback incluso con una sesión autenticada mediante acceso directo por LAN. El contenido de las vistas previas activas (`/previews/`) está disponible mediante acceso directo por LAN con un token de capacidad válido. +Usa una conexión loopback para las operaciones reservadas al anfitrión: contenido de SideCar (`/sidecars/`) y WebSockets, gestión de Control remoto (`/api/remote-control/`), puente de plugins (`/api/opencode-plugin/`), proxies remotos (`/api/remote-proxy/`), gestión de servidores guardados (`/api/remote-servers/`), cambios de contraseña e inicialización por token. Estas operaciones requieren loopback incluso con una sesión autenticada mediante acceso directo por LAN. Solo los SideCars tienen una excepción: el ajuste **Abrir SideCars por HTTPS** del anfitrión abre su contenido y sus WebSockets a los navegadores con sesión iniciada desde un origen HTTPS de confianza ([SideCars](browser-sidecars.md#register-sidecar)). El contenido de las vistas previas activas (`/previews/`) está disponible mediante acceso directo por LAN con un token de capacidad válido. Las API de registro `/api/sidecars` siguen disponibles para los clientes directos de LAN autenticados y los dispositivos emparejados. Las vistas previas web de Control remoto siguen disponibles con su token de capacidad mientras estén activadas en el anfitrión. diff --git a/docs/help/es/remote-control.md b/docs/help/es/remote-control.md index 06470e989e..5e38db77c5 100644 --- a/docs/help/es/remote-control.md +++ b/docs/help/es/remote-control.md @@ -86,3 +86,7 @@ CodeNomad usa [OpenTunnel](https://github.com/anomalyco/opentunnel) y reserva un TLS termina en el backend de CodeNomad. El relé reenvía texto cifrado y no puede leer el contenido de la aplicación, pero puede observar nombres de host, tiempos de conexión y tamaños de tráfico. El certificado/clave privada del túnel permanece en el anfitrión. Protege el almacenamiento del túnel del anfitrión y la configuración de CodeNomad como credenciales; una dirección imposible de adivinar no es autorización. `CODENOMAD_REMOTE_CONTROL_API` selecciona una API de OpenTunnel autoalojada; sin definir se usa el servicio alojado. Esto cambia el despliegue del túnel, no los requisitos de emparejamiento ni las superficies bloqueadas. Consulta [Seguridad](security.md) para el tratamiento de credenciales y diagnósticos. + +## Política del administrador {#administrator-policy} + +Un administrador puede desactivar el control remoto para todos los usuarios de un equipo: define la variable de entorno `CODENOMAD_REMOTE_CONTROL=disabled` para todo el sistema y reinicia CodeNomad. El backend nunca conecta un túnel, rechaza **Iniciar control remoto** y los enlaces de emparejamiento y no se reconecta al iniciar; Ajustes muestra **Desactivado por el administrador**. Los dispositivos emparejados antes no pueden conectarse y siguen en la lista para que puedas revocarlos. Sin definir o vacía no aplica ninguna política; cualquier otro valor, incluso solo espacios, impide que el backend se inicie. diff --git a/docs/help/es/security.md b/docs/help/es/security.md index 837f7fc92a..d2f8edc685 100644 --- a/docs/help/es/security.md +++ b/docs/help/es/security.md @@ -33,7 +33,7 @@ El inicio de sesión directo crea una sesión opaca en memoria del backend y una Cerrar sesión revoca la sesión directa actual. Cambiar correctamente la contraseña en el anfitrión revoca todas las sesiones directas de ese usuario, incluida la actual; vuelve a iniciar sesión. Las sesiones caducan tras 24 horas sin solicitudes autenticadas o siete días desde su creación. Ajusta estos límites con `CODENOMAD_SESSION_IDLE_SECONDS` y `CODENOMAD_SESSION_ABSOLUTE_SECONDS` en segundos enteros positivos antes de iniciar el backend. Los dispositivos de Control remoto se revocan por separado. -Los clientes LAN pueden iniciar y cerrar sesión y usar proyectos. Los cambios de contraseña, la gestión de Control remoto, las herramientas de servidores remotos/proxy y los SideCars se administran en el anfitrión por loopback. Las modificaciones del navegador requieren un Origin permitido o, si falta, Referer. Se permiten los orígenes anunciados del servidor; para alias DNS, proxies inversos o una interfaz alojada aparte, configura `CODENOMAD_ALLOWED_ORIGINS` con orígenes HTTP(S) exactos separados por comas, como `https://code.example.test,https://ui.example.test:8443`, y reinicia. No uses rutas ni comodines. Esto concede acceso al navegador, no privilegios del anfitrión. Los clientes nativos también deben enviar un Origin permitido para cambios LAN. Un proxy de confianza conectado por loopback tiene privilegios del anfitrión y necesita sus propios controles de acceso. Si el servidor escucha en loopback o en todas las interfaces, la interfaz abierta en el anfitrión como `localhost`, con el mismo esquema y puerto, también funciona. +Los clientes LAN pueden iniciar y cerrar sesión y usar proyectos. Los cambios de contraseña, la gestión de Control remoto, las herramientas de servidores remotos/proxy y los SideCars se administran en el anfitrión por loopback. El ajuste **Abrir SideCars por HTTPS** del anfitrión abre los SideCars a los navegadores con sesión iniciada desde un origen HTTPS de confianza; actívalo solo si todos los usuarios de esas direcciones pueden usar tus servicios SideCar. Las modificaciones del navegador requieren un Origin permitido o, si falta, Referer. Se permiten los orígenes anunciados del servidor; para alias DNS, proxies inversos o una interfaz alojada aparte, configura `CODENOMAD_ALLOWED_ORIGINS` con orígenes HTTP(S) exactos separados por comas, como `https://code.example.test,https://ui.example.test:8443`, y reinicia. No uses rutas ni comodines. Esto concede acceso al navegador, no privilegios del anfitrión. Los clientes nativos también deben enviar un Origin permitido para cambios LAN. Un proxy de confianza conectado por loopback tiene privilegios del anfitrión y necesita sus propios controles de acceso. Si el servidor escucha en loopback o en todas las interfaces, la interfaz abierta en el anfitrión como `localhost`, con el mismo esquema y puerto, también funciona. Si sospechas una intrusión: diff --git a/docs/help/es/server.md b/docs/help/es/server.md index 4a82a97b94..225b15c757 100644 --- a/docs/help/es/server.md +++ b/docs/help/es/server.md @@ -8,7 +8,7 @@ La misma interfaz admite [varias pestañas de proyecto y worktrees](projects.md) 1. Instala Node.js 24 LTS y npm; el repositorio fija su entorno de compilación en `.node-version`. Los paquetes de escritorio proporcionan su propio entorno: Electron usa su Node integrado, Tauri incluye Node y ambos incluyen npm. 2. Pon Git en el **PATH del proceso del backend**. Git solo dentro de WSL no satisface a un backend Windows. -3. Instala o selecciona OpenCode: **2.2.3** es el mínimo requerido y **2.2.7**, el objetivo recomendado de verificación. Las compilaciones más nuevas o personalizadas pasan comprobaciones de compatibilidad, no una lista de versiones probadas permitidas. Consulta [configuración de OpenCode](opencode.md). +3. Instala o selecciona OpenCode: **2.3.0** es el mínimo requerido y **2.3.0**, el objetivo recomendado de verificación. Las compilaciones más nuevas o personalizadas pasan comprobaciones de compatibilidad, no una lista de versiones probadas permitidas. Consulta [configuración de OpenCode](opencode.md). 4. Elige la carpeta desde la que iniciar el servidor o pasa `--workspace-root` explícitamente. Sin Git, las conversaciones siguen disponibles solo en la carpeta física abierta explícitamente; las operaciones Git y worktree fallan. Instala Git y reinicia el backend tras cambiar PATH. Una raíz de espacio de trabajo limita la apertura/exploración, no la ejecución del agente: consulta [Seguridad](security.md). @@ -104,6 +104,8 @@ La referencia pública enumera las opciones para usuarios; los anfitriones de es | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; repositorio consultado para ofertas de versiones. | | `CODENOMAD_REMOTE_CONTROL_API` | Sin definir: API alojada de OpenTunnel. Establece un origen API para un despliegue de relé autoalojado. | +| `CODENOMAD_REMOTE_CONTROL` | Sin definir: los usuarios pueden iniciar el control remoto. `disabled`: desactivado por un administrador ([política](remote-control.md#administrator-policy)); sin definir o vacía no aplica ninguna política, cualquier otro valor (incluidos espacios) impide el inicio. | +| `CODENOMAD_LOCKED_HOST` | Sin definir o vacía: se aplica `--host`; solo espacios impide el inicio. Una dirección: el servidor escucha en ella sin importar `--host`, `CLI_HOST` ni el interruptor de escucha ([política](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | Archivo CA adicional opcional de Node; se pasa con el entorno de inicio permitido al iniciar un daemon OpenCode ausente. No cambia un daemon ya en ejecución. | Las credenciales de uso específicas de proveedores se cubren en [Proveedores](providers.md). La selección del perfil de datos de escritorio se cubre en [Escritorio](desktop.md); no la controla el canal de versiones. diff --git a/docs/help/es/settings.md b/docs/help/es/settings.md index 67f76105e4..36b2113243 100644 --- a/docs/help/es/settings.md +++ b/docs/help/es/settings.md @@ -70,7 +70,7 @@ Arrastra el borde interior de un panel acoplado para cambiar su tamaño. El tira 2. Abre **Personalizar panel derecho** en el panel derecho. Usa las casillas para elegir pestañas integradas y secciones de Estado; al menos una sección de Estado permanece visible. Arrastra sobre estas casillas para ajustar varias a la vez. 3. Arrastra las pestañas del panel derecho para reordenarlas. Usa **Restablecer** para restaurar las elecciones de disposición integradas. -Las [integraciones](integrations.md#integration-sections) reconocidas también tienen secciones de Estado. Ocúltalas con las mismas casillas; reordena cualquier sección de Estado arrastrando o con las teclas Arriba/Abajo. La visibilidad y el orden persisten al recargar y durante la ausencia temporal de una integración. +Reordena cualquier sección de Estado arrastrando o con las teclas Arriba/Abajo. La visibilidad y el orden persisten al recargar. Estado incluye información de tokens, modo Yolo, Uso del proveedor, shells en segundo plano, MCP y Plugins. Mientras la conversación tiene un [objetivo](conversations.md#goal), una línea de objetivo encima de estas secciones lo muestra; esa línea no es una sección y no se puede ocultar ni mover. Ocultar una sección no desactiva su servicio ni revoca permisos. Las disposiciones estrechas cierran los paneles que ya no caben en lugar de estrechar la conversación; un panel abierto en ellas flota sobre la conversación, y abrir un panel flotante cierra el otro. diff --git a/docs/help/es/troubleshooting.md b/docs/help/es/troubleshooting.md index 0d5b8e37ba..c2ca0c68f2 100644 --- a/docs/help/es/troubleshooting.md +++ b/docs/help/es/troubleshooting.md @@ -42,7 +42,7 @@ Si no puede verificarse un worktree propio o la ubicación de una conversación, ## Entorno de ejecución OpenCode y WSL {#opencode-runtime} 1. Abre **Preferencias → OpenCode** y comprueba la tarjeta **Versión de OpenCode** (versión instalada y estado del servicio en ejecución) y después el ejecutable seleccionado en **Binario de OpenCode**. -2. Usa la acción compatible de instalación/actualización si falta el entorno requerido. Mínimo actual: **2.2.3**; versión recomendada/verificada: **2.2.7**. +2. Usa la acción compatible de instalación/actualización si falta el entorno requerido. Mínimo actual: **2.3.0**; versión recomendada/verificada: **2.3.0**. 3. Si la CLI instalada difiere del servicio en ejecución, decide explícitamente si reiniciar el servicio compartido. **Reiniciar servicio OpenCode** está disponible en **Solución de problemas** y requiere confirmación. Interrumpe el trabajo activo de todos los clientes conectados, pero conserva el historial de sesiones. Recargar la configuración es una acción separada: mantiene el proceso, pero reconstruye las Locations cargadas y cancela preguntas/permisos pendientes. Ninguna es una actualización inofensiva. diff --git a/docs/help/fr/browser-sidecars.md b/docs/help/fr/browser-sidecars.md index d155e9f257..600c7d21cf 100644 --- a/docs/help/fr/browser-sidecars.md +++ b/docs/help/fr/browser-sidecars.md @@ -77,7 +77,7 @@ Si le service est inaccessible, vérifiez le processus et le port sur le backend Un SideCar est une extension de confiance de CodeNomad, pas un aperçu en bac à sable : sa page s’exécute avec l’origine même de CodeNomad, si bien que ses scripts peuvent utiliser CodeNomad avec votre accès connecté. N’enregistrez que des services dont vous jugez le code fiable. CodeNomad ne transmet pas ses propres cookies de connexion au service, tandis que les cookies propres au service sont conservés. -Le contenu SideCar (`/sidecars/`) et les WebSockets SideCar exigent une connexion en boucle locale sur l’hôte. L’enregistrement via `/api/sidecars` est accessible aux appareils appairés et aux clients LAN directs authentifiés. Le contenu des aperçus actifs (`/previews/`) est accessible directement depuis le LAN avec un jeton de capacité valide ; les aperçus web du [Contrôle à distance](remote-control.md#remote-surface) restent accessibles avec leur jeton de capacité lorsqu’ils sont activés. Voir [Mise à niveau](remote-access.md#upgrading) pour les conditions de l’accès direct. +Le contenu SideCar (`/sidecars/`) et les WebSockets SideCar exigent une connexion en boucle locale sur l’hôte. Pour les ouvrir aussi depuis d’autres appareils, activez **Ouvrir les SideCars en HTTPS** dans **Paramètres → SideCars** sur l’hôte : les navigateurs connectés via les adresses HTTPS de ce serveur ou une origine HTTPS de `CODENOMAD_ALLOWED_ORIGINS`, comme un proxy inverse TLS, peuvent alors ouvrir les SideCars. HTTP simple, les adresses `localhost` et le Contrôle à distance restent réservés à l’hôte. L’enregistrement via `/api/sidecars` est accessible aux appareils appairés et aux clients LAN directs authentifiés. Le contenu des aperçus actifs (`/previews/`) est accessible directement depuis le LAN avec un jeton de capacité valide ; les aperçus web du [Contrôle à distance](remote-control.md#remote-surface) restent accessibles avec leur jeton de capacité lorsqu’ils sont activés. Voir [Mise à niveau](remote-access.md#upgrading) pour les conditions de l’accès direct. ## Recette OpenVSCode Server {#openvscode} diff --git a/docs/help/fr/conversations.md b/docs/help/fr/conversations.md index 7766b5d3ef..9dc4c76f94 100644 --- a/docs/help/fr/conversations.md +++ b/docs/help/fr/conversations.md @@ -60,6 +60,12 @@ Sur ordinateur, l’envoi place le focus clavier sur la conversation : les flèc Les brouillons sont un état de travail côté client, pas des messages natifs partagés. La restauration au démarrage peut conserver l’état de saisie pris en charge, mais ne considérez pas un brouillon non envoyé ou une pièce jointe comme une sauvegarde, ni comme disponible sur un autre appareil. Enregistrez le texte important avant d’effacer les données de démarrage ou de fermer un client dont la restauration est désactivée ; voir [Bureau](desktop.md). +## Ouvrir des fichiers depuis les réponses {#open-files-from-replies} + +1. Les réponses de l’agent lient des fichiers du projet par des chemins relatifs et absolus. +2. Un clic simple ouvre le fichier lié dans l’aperçu du fichier, lu depuis le worktree de la conversation. +3. Les clics modifiés (Ctrl/⌘-clic, Maj-clic, clic milieu) et les liens hors du worktree de la session conservent le comportement normal des liens. + ## Commandes et mode shell {#commands-shell} 1. Tapez `/` et sélectionnez une commande personnalisée découverte, puis fournissez ses arguments. diff --git a/docs/help/fr/install.md b/docs/help/fr/install.md index 54f1bbe410..3e6fe4e04c 100644 --- a/docs/help/fr/install.md +++ b/docs/help/fr/install.md @@ -45,7 +45,7 @@ L’installation Debian d’Electron configure le bac à sable Chromium. Ne dés | Prérequis | Où il doit être disponible | Exigence actuelle | | --- | --- | --- | -| CLI OpenCode | Hôte d’exécution sélectionné, y compris la distribution WSL choisie le cas échéant | Minimum **2.2.3** ; **2.2.7** est la cible recommandée/qualifiée. Les versions plus récentes ou personnalisées passent une validation des contrats plutôt qu’une interdiction des versions non testées. | +| CLI OpenCode | Hôte d’exécution sélectionné, y compris la distribution WSL choisie le cas échéant | Minimum **2.3.0** ; **2.3.0** est la cible recommandée/qualifiée. Les versions plus récentes ou personnalisées passent une validation des contrats plutôt qu’une interdiction des versions non testées. | | Git | `PATH` du compte du backend CodeNomad | Requis pour l’identité des dépôts, les opérations Git et les worktrees. | | Node.js/npm | Hôte du serveur autonome et de compilation depuis les sources | Node.js 24 LTS ; les compilations reproductibles utilisent la version épinglée dans `.node-version`. Les versions de bureau fournissent le leur : le Node intégré d’Electron ou le Node embarqué par Tauri, avec npm. | | Dossier de travail | Disque accessible au backend | Dossier physique explicitement ouvert, pas un dossier local à l’appareil déduit par un navigateur distant. | diff --git a/docs/help/fr/integrations.md b/docs/help/fr/integrations.md index fe4061cb99..70d07ff8bf 100644 --- a/docs/help/fr/integrations.md +++ b/docs/help/fr/integrations.md @@ -27,7 +27,7 @@ Si aucun serveur n’apparaît, vérifiez la Location active et sa configuration Les plugins gérés par CodeNomad restent hors de la liste ordinaire et de ses contrôles d’activation, de mise à jour et de retrait. CodeNomad les reconnaît à leur entrée d’installation validée et à l’emplacement de leur code identifié par son empreinte de contenu ; un plugin tiers de même nom ou ID conserve ses contrôles ordinaires. -Si un plugin géré est désactivé, échoue au chargement ou reste sans confirmation de chargement, **Les plugins CodeNomad nécessitent votre attention** apparaît au-dessus de la liste Plugins. Ouvrez son bouton **i** (**Détails de** ce plugin) pour consulter l’erreur disponible et sa référence dans le journal OpenCode. Seul un plugin désactivé propose **Réactiver** : cette action ajoute une règle d’activation positive pour son ID exact, en conservant la règle de désactivation. Elle écrit dans la portée **Global** ou **Projet** de la règle de désactivation si elle est modifiable, sinon dans **Projet**. OpenCode continue de fonctionner ; l’avertissement reste jusqu’à ce que les événements natifs ou **Actualiser les contrôles des plugins** confirment que le plugin est actif. +Si un plugin géré est désactivé, échoue au chargement ou reste sans confirmation de chargement, **Les plugins CodeNomad nécessitent votre attention** apparaît au-dessus de la liste Plugins. Ouvrez son bouton **i** (**Détails de** ce plugin) pour consulter l’erreur disponible et sa référence dans le journal OpenCode. Seul un plugin désactivé propose **Réactiver** : cette action retire de ce fichier la règle exacte qui désactive le plugin quand cela suffit à le réactiver, et sinon ajoute une règle positive pour son ID exact. Elle écrit dans la portée **Global** ou **Projet** de la règle de désactivation si elle est modifiable, sinon dans **Projet**. OpenCode continue de fonctionner ; l’avertissement reste jusqu’à ce que les événements natifs ou **Actualiser les contrôles des plugins** confirment que le plugin est actif. L’avertissement et ses détails indiquent l’origine de configuration **Héritée / externe** ou **Configuration virtuelle** selon le cas. Un libellé **Projet** distinct indique la destination de réactivation lorsqu’elle diffère de l’origine de la règle de désactivation. @@ -38,7 +38,7 @@ L’avertissement et ses détails indiquent l’origine de configuration **Héri Global cible la configuration globale découverte du démon connecté. Projet cible la configuration dans la Location active, pas un fichier ancêtre hérité. Une règle Projet ultérieure peut remplacer Global ; le commutateur Global montre toujours la règle Global, sans prétendre être l’état Projet final. Sans règle Projet, Projet hérite de l’état Global résolu. -Ces commutateurs ajoutent des règles d’activation exactes en préservant les déclarations de sources et la configuration sans rapport. Ils ne modifient pas les options des plugins, n’installent pas de paquets et ne retirent pas de fichiers. Les plugins intégrés d’OpenCode ne sont pas proposés comme commutateurs utilisateur. Projet est désactivé si sa cible ne peut pas être séparée de Global sans risque ou sort de la Location active. +Chaque commutateur écrit une règle d’activation exacte pour le plugin dans le fichier de sa portée, en remplaçant les règles exactes antérieures de ce plugin dans ce fichier, ou se contente de les retirer quand le résultat est le même. Les déclarations de sources, les règles plus larges comme `*` et la configuration sans rapport sont préservées. Ils ne modifient pas les options des plugins, n’installent pas de paquets et ne retirent pas de fichiers. Les plugins intégrés d’OpenCode ne sont pas proposés comme commutateurs utilisateur. Projet est désactivé si sa cible ne peut pas être séparée de Global sans risque ou sort de la Location active. Une mise à jour de paquet modifie ce paquet dans le cache partagé d’OpenCode pour toutes les Locations qui l’utilisent, comme l’indique son infobulle ; elle ne change pas les règles d’activation, ne redémarre pas OpenCode et ne recharge pas la configuration. Les plugins locaux, intégrés et fournis par le SDK n’ont pas d’action de paquet. Un paquet qui échoue avant de communiquer l’ID de son plugin est listé sous son nom de paquet, avec l’échec dans son infobulle et les actions de vérification/mise à jour, mais sans commutateurs d’activation. Une vérification ou mise à jour échouée est signalée et jamais réessayée automatiquement. @@ -78,38 +78,30 @@ Les compétences disponibles viennent de la Location de la conversation, pas d Les commandes sont découvertes depuis OpenCode pour la Location active. Leur définition native peut choisir le comportement d’exécution ; le menu n’est ni un installateur de paquets ni un éditeur de configuration sans restriction. CodeNomad applique l’environnement de session du profil avant la soumission native ; un échec de mise à jour d’environnement bloque l’envoi. `/btw` est le parcours distinct de question éphémère de CodeNomad, pas une commande personnalisée ordinaire. Pour les définitions de commandes et l’héritage de configuration natif, utilisez la [documentation des commandes OpenCode](https://opencode.ai/v2/docs/commands/). Après des changements de configuration, actualisez/rouvrez d’abord la surface concernée ; ne rechargez explicitement la configuration que si l’environnement d’exécution en a encore besoin. Ne rejouez jamais une commande peut-être admise uniquement pour rafraîchir son affichage. -## Sections d’intégration dans Statut {#integration-sections} +## Intégrations dans Plugins {#integration-rows} Dans **Statut → Plugins**, **+** propose **Ajouter une intégration…** ou **Ajouter un plugin…**. Le sélecteur d’intégrations liste les entrées non installées du catalogue revu. Choisissez la portée puis **Installer** : CodeNomad installe l’ID du catalogue choisi. Les intégrations natives sont **Global uniquement**. **Catalogue indisponible** propose **Actualiser** ; **Catalogue du {date}** indique le dernier catalogue valide s’il est périmé. -Chaque intégration reconnue ayant une déclaration ou un plugin chargé/en échec possède sa section **Statut**, même désactivée ou en cours d’installation. Une source ambiguë affiche **Non conforme** dans Plugins. Chaque intégration conserve sa ligne Plugins et ses actions de mise à jour, retrait et actualisation. Dépliez sa section pour voir la version et les contrôles du plugin dans le corps ; son nom et son état restent visibles dans l’en-tête, près de **Documentation** et **i**. Le popover **i** révèle les précisions à la demande : Entrée/Espace l’ouvre, Échap le ferme. +Une intégration reconnue a une seule ligne dans **Statut → Plugins**, avec son nom (par exemple **OpenCode for Blender**) et sa version. Ses interrupteurs **Global** et **Projet** prennent la couleur d’accent comme les autres interrupteurs, ceux d’un plugin simple sont verts ; une intégration qui a une partie dans une application est **Global uniquement**. Survolez son nom : les détails commencent par **Intégration** au lieu de **Plugin** ; les lecteurs d’écran les lisent comme description de la ligne. Une source ambiguë affiche **Non conforme**. -La personnalisation de Statut permet de masquer les sections et de les réordonner par glisser-déposer ou avec les touches Haut/Bas, y compris les autres sections Statut. Le masquage et l’ordre persistent aux rechargements et à l’absence temporaire d’une intégration. Si une section disparaît avec le focus, celui-ci revient à Plugins, ou à une autre section Statut visible si Plugins est masqué. +Sous le nom, une ligne d’état dit toujours où en est l’intégration. Le texte gris informe ; le texte à la couleur d’accent est un bouton. Pour une intégration qui a une partie dans une application, l’état le plus important s’affiche : **Installer dans Blender** ou **Mettre à jour Blender** quand sa partie est absente ou ancienne (avec la confirmation d’installation), une incompatibilité dans la couleur d’avertissement, une icône de chaînon et le document quand la conversation affichée est rattachée (activez-la pour détacher), **Blender fermé**, **Blender : aucun document ouvert**, **Aucune conversation affichée**, puis **Rattacher** suivi du nom du document, ou **Rattacher…** pour choisir entre plusieurs documents. Une conversation se rattache aussi d’elle-même la première fois que son agent utilise l’intégration. Les intégrations MCP d’éditeur affichent **Serveur détecté** ou **Serveur absent**, les intégrations API **Connecté** ou **Déconnecté**. Un état trop long est tronqué ; survolez-le pour le texte complet. Les changements signalés par l’intégration et les reconnexions actualisent la ligne. -L’installation depuis le catalogue, l’installation/mise à jour de la partie application, l’attachement et le retrait demandent confirmation. **Annuler** reçoit le focus ; l’action de confirmation devient disponible après 600 ms. L’activation et les mises à jour du plugin s’exécutent directement. +Le menu **…** de la ligne commence par l’état de la connexion, par exemple **Blender : 1 document ouvert** ou **Blender fermé**. Il propose ensuite **Documentation**, **Installer dans l'application…**, **Mettre à jour l'application…** ou **Réinstaller dans l'application…** ([voir plus bas](#application-installation)), la vérification des mises à jour du package, **Retirer de Global** ou **Retirer de Projet**, et **Actualiser les contrôles des plugins**. Détacher se fait en un clic, sans confirmation, et ne concerne que cette conversation : l’application reste ouverte, sa partie reste installée et les autres conversations gardent leur rattachement. Si la réponse est perdue, la ligne relit l’état ; la requête n’est jamais répétée. -## Attacher une application ouverte {#application-attachment} +L’installation depuis le catalogue, l’installation ou la mise à jour de la partie dans l’application et le retrait demandent une confirmation. **Annuler** reçoit d’abord le focus ; l’action de confirmation devient disponible après 600 ms. L’activation, les mises à jour de plugins, le rattachement et le détachement s’exécutent directement. -Proposez un document depuis l’intégration de l’application, puis ouvrez **Statut → l’intégration → Conversation** et choisissez **Attacher…**. Cette section porte le contrôle d’attachement de la conversation affichée. Sélectionnez l’application et le document, vérifiez la conversation cible et l’avertissement de modification, puis confirmez avec **Attacher**. L’application tourne sur la machine d’OpenCode, y compris à distance. Un hôte non pris en charge, notamment WSL, propose une aide via **i**. - -La ligne **Conversation** de la section lit la liaison de la conversation affichée. **Liaison inconnue** propose **Actualiser**. Lorsqu’une lecture récente faisant autorité confirme l’attachement, **Détacher** remplace **Attacher…**. Un clic détache uniquement cette conversation, sans autre confirmation ; l’application reste ouverte, sa partie hôte installée et les autres conversations gardent leurs liaisons. Les changements natifs et reconnexions actualisent cet état. - -Une action admise conserve son résultat ou son erreur tant que la conversation cible reste affichée ; naviguer ferme son reçu. La liaison actuelle suit la lecture faisant autorité. **État incertain** après une réponse perdue, un délai dépassé ou une coupure propose **Actualiser** pour relire l’état réel. Ne rejouez jamais la demande pour rafraîchir l’affichage. - -Après une lecture explicite des applications ouvertes dans le sélecteur, la métadonnée Q8 sauvegardée peut proposer **Rattacher** dans le sélecteur ou la ligne **Conversation** pour la même intégration et une étiquette de document validée, tant que le projet, la conversation et la génération de connexion restent identiques. Le rattachement demande confirmation explicite ; une navigation ou une invalidation efface la suggestion. L’autorité sur la liaison actuelle provient de la lecture par session de l’intégration. - -Le retrait depuis la section d’intégration ou sa ligne Plugins utilise la même déclaration et confirmation avec portée. Il s’effectue sans recensement des conversations ni détachement automatique. +Le retrait se fait sans recensement des conversations ni détachement automatique. Retirer un plugin ouvre un avertissement nommant le plugin et sa portée exacte. **Annuler** reçoit le focus ; **Retirer de Global/Projet** devient disponible après 600 ms et exige une action explicite. Le retrait peut interrompre la disponibilité et les connexions des conversations utilisant le plugin ; Global peut aussi affecter d’autres projets. Annuler, laisser expirer ou naviguer avant l’envoi conserve tout inchangé. Seule la déclaration confirmée est retirée : règles d’activation, cache, fichiers d’application et indications d’attachement sont conservés. Une configuration modifiée exige une nouvelle sélection et confirmation. Le succès confirme le retrait de la déclaration ; l’état effectif suit le rechargement d’OpenCode. Si la réponse est perdue, actualisez Plugins pour vérifier la configuration avant une nouvelle tentative. Réinstaller peut rétablir la disponibilité ; un rechargement ou rattachement peut être nécessaire, sans reprise garantie des opérations interrompues. ## Installer ou mettre à jour l’intégration de l’application {#application-installation} -Dans **Statut → l’intégration → Application**, choisissez **Installer dans l’application…** ou **Mettre à jour l’application…** quand l’état récent propose l’action. Elle est disponible sans conversation ni document proposé. Si l’application est fermée, ouvrez-la pour vérifier sa partie application ; **i** précise la machine et les prérequis. +Dans **Statut → Plugins**, choisissez **Installer dans Blender** ou **Mettre à jour Blender** sur la ligne d’état de l’intégration quand son état à jour propose l’action, ou **Installer dans l'application…**, **Mettre à jour l'application…** ou **Réinstaller dans l'application…** dans son menu **…**. Réinstaller réécrit la partie dans l’application, qu’elle soit ouverte ou fermée. L’action est disponible sans conversation ni document ouvert. La confirmation indique l’application et la **version du paquet d’intégration** qui fournit l’installateur. Vérifiez ces informations et l’avertissement sur la machine : l’installation a lieu sur la machine où tourne OpenCode, qui peut être distante. **Annuler** reçoit le focus initial. Confirmez explicitement pour continuer. Changer de projet, de Location ou de conversation, se reconnecter ou recevoir un changement natif pertinent avant la confirmation annule l’accord en attente ; rouvrez l’action pour examiner les informations à jour. WSL refuse toujours l’installation dans l’application, même si une application ouverte semble compatible. Ouvrez l’application sur une machine compatible. -Le résultat indique une installation, une mise à jour, une intégration déjà à jour, un refus ou un échec. Après une installation ou une mise à jour, ouvrez l’application et vérifiez son intégration ; attachez une conversation séparément avec [Attacher une application ouverte](#application-attachment). La réussite décrit la requête d’installation ; la disponibilité de l’application vient de son état. +Le résultat indique que la partie dans l’application a été installée, mise à jour, était déjà à jour, a été refusée ou a échoué. Après une installation ou une mise à jour, ouvrez l’application et vérifiez son intégration. Le succès de l’installation décrit la requête de l’installateur ; la disponibilité réelle de l’application vient de son état. Les requêtes ne sont jamais relancées automatiquement. Après un refus ou un échec, vérifiez l’application avant de choisir une nouvelle action. Si une erreur rend le résultat incertain, ne répétez jamais cette requête : examinez d’abord l’application, puis lancez une nouvelle action avec confirmation si nécessaire. diff --git a/docs/help/fr/missions.md b/docs/help/fr/missions.md index 44ec97b706..ca0b973626 100644 --- a/docs/help/fr/missions.md +++ b/docs/help/fr/missions.md @@ -46,7 +46,7 @@ Une programmation gérée par calendrier nécessite un agent et un modèle expli ### Démarrer automatiquement {#automatic-start} -**Démarrer automatiquement** se trouve hors de Programmation et reste décoché par défaut. Laissez-le décoché pour créer une Mission en pause, puis utilisez ▶ **Démarrer** dans l’en-tête. Cochez-le pour demander le démarrage après confirmation de la création, avec les contrôles habituels et l’éventuel consentement aux réglages natifs. +**Démarrer automatiquement** se trouve hors de Programmation et reste décoché par défaut. Laissez-le décoché pour créer une Mission en pause, puis utilisez ▶ **Démarrer** dans l’en-tête. Cochez-le pour demander le démarrage après confirmation de la création, avec les contrôles habituels et la préparation automatique de la programmation. Si l’accusé de création est perdu, lire le reçu laisse le démarrage manuel. Une création non confirmée garde sa requête d’origine ; vérifiez la liste et la conversation avant de créer à nouveau. @@ -62,6 +62,8 @@ Les horaires proposent Une fois, maintenant, Toutes les N heures, Tous les jours **Une fois, maintenant** prend son instant au démarrage, pas à l’ouverture du formulaire. Il offre une seule occasion, qu’une condition peut consommer sans lancement. Choisissez une récurrence pour des occasions ultérieures. La programmation fonctionne tant que son service OpenCode et son hôte d’exécution sont disponibles. +Le démarrage ou la reprise prépare automatiquement la programmation dans la configuration OpenCode du projet. Un OFF explicite est conservé : **Ouvrir les réglages de programmation**, lorsque proposé, ouvre le fichier responsable ; le **i** révèle sa provenance ou les détails d’environnement. Le bouton sollicité affiche le chargement pendant la requête seulement. Un résultat non confirmé propose une vérification ; l’activation récupérée laisse le démarrage explicite. + ### Événements et combinaisons {#scheduling-conditions} Choisissez **Activité du dépôt → Événement**, puis les filtres éventuels dans la même carte. Les commits Git partagent ce menu avec les événements du dépôt GitHub, GitLab ou Gitea détecté automatiquement, comme dans Contribute (`upstream`, puis `origin`). Les trois proposent les nouvelles PR/MR, les PR/MR fusionnées et les nouvelles issues, avec un **Auteur (facultatif)**, y compris `dependabot[bot]`. Choisir un événement fixe son dépôt ; les critères enregistrés conservent leur cible. @@ -100,13 +102,18 @@ Les missions et tâches suivantes se chargent à l’approche de la fin. Les pag Le drapeau indique l’état de la Mission ; son chevron porte l’attention de ses tâches. Une entrée récurrente utilise une icône de répétition. -| Couleur | Sens | +| Couleur et forme | Sens | | --- | --- | | Rouge | Une question ou permission attend votre réponse. Sélectionnez la Mission ou la tâche concernée pour ouvrir le panneau d’interruption. | | Jaune pulsant | Une activité native a été observée. | -| Orange | En pause ou interrompue, avec une action pour continuer. | -| Vert | Une Mission ou tâche terminée n’a pas encore été vue dans cette fenêtre. Sélectionnez-la, cliquez ou balayez les icônes vertes des tâches, ou choisissez **Marquer comme lu** dans le menu du chevron. | -| Bleu | Mission préparée ou tâche qui n’a pas commencé. | +| Symbole pause orange | En pause. | +| Triangle d’avertissement orange | Interrompue, avec une action pour continuer. | +| Vert | Une Mission, tâche ou exécution programmée réussie attend votre consultation dans cette fenêtre. | +| Icône d’accent avec un petit trait neutre statique dessous | **En attente programmée** : le prochain réveil est confirmé. L’accent suit votre palette. | +| Icône d’accent seule | Mission préparée ou tâche qui n’a pas commencé. | +| Neutre | Fin consultée, programmation arrêtée ou **État non confirmé** ; lisez le texte d’état. | + +Sélectionnez une Mission ou tâche verte, cliquez ou balayez les icônes vertes des tâches, ou choisissez **Marquer comme lu** dans le menu du chevron. Pour **Passage réussi à consulter**, sélectionnez explicitement la ligne récurrente dans la fenêtre active ou utilisez **Marquer comme lu** pour acquitter ce passage. L’icône revient à l’attente si la programmation reste active, sinon au neutre. La sélection restaurée et les résultats reçus sur une ligne déjà sélectionnée gardent le nouveau résultat à consulter. Les succès historiques présents au premier chargement commencent comme lus. Le texte d’état distingue Affectée, Active, En attente, Bloquée, Terminée, Échouée et Retirée. Un blocage signalé n’est pas nécessairement une question pour vous. Un résultat enregistré ne prouve pas que chaque opération native est arrêtée. Retirer une tâche conserve son historique. diff --git a/docs/help/fr/mobile.md b/docs/help/fr/mobile.md index 94d90c711b..0fb663c033 100644 --- a/docs/help/fr/mobile.md +++ b/docs/help/fr/mobile.md @@ -42,3 +42,5 @@ La zone de saisie garde Agent, Modèle et Réflexion dans son pied. Le champ se | Travail hors ligne | Aucun backend hors ligne ni historique API en cache. Les ressources d’interface statiques peuvent être en cache, mais les documents et réponses API ne constituent pas un espace de travail hors ligne. | Gardez le backend accessible. La suspension par le système mobile ou un changement de réseau peut déconnecter le flux d’événements ; au retour, le client reconnecte et relit l’état actuel, sans rejeu d’événements garanti. Vérifiez si une action s’est terminée avant de réessayer. Fermer la PWA n’arrête pas un backend autonome ; quitter l’application de bureau hôte et son backend rend le Contrôle à distance indisponible jusqu’au prochain lancement. + +Chaque onglet du navigateur, y compris la PWA installée, garde pour cet onglet ses projets ouverts, ses conversations sélectionnées, ses brouillons non envoyés et ses positions de défilement : ils reviennent quand la page se recharge, ou quand le système mobile la recharge après un changement d'application ou un verrouillage de l'écran. Un nouvel onglet, ou une PWA entièrement fermée par le système, s'ouvre sur l'accueil. Désactivez ce comportement pour l'onglet avec **Paramètres → Général → Restaurer l’état précédent**. diff --git a/docs/help/fr/opencode.md b/docs/help/fr/opencode.md index 99b08c28df..ec005dbe07 100644 --- a/docs/help/fr/opencode.md +++ b/docs/help/fr/opencode.md @@ -19,8 +19,8 @@ L’exécutable installé et le service actif peuvent avoir des versions différ | Classification | Exigence actuelle | Signification | | --- | --- | --- | -| Minimum | OpenCode **2.2.3** | L’outil de génération d’images qu’utilisent les réglages **Images** et l’extension Design, ainsi que l’ordre correct d’exécution des tâches JavaScript dans Code Mode et le format natif de rejeu et de compaction ; les conversations enregistrées par les versions antérieures restent lisibles après la mise à jour. | -| Recommandée | OpenCode **2.2.7** | Cible qualifiée, distincte du minimum technique. | +| Minimum | OpenCode **2.3.0** | L’outil de génération d’images qu’utilisent les réglages **Images** et l’extension Design, ainsi que l’ordre correct d’exécution des tâches JavaScript dans Code Mode et le format natif de rejeu et de compaction ; les conversations enregistrées par les versions antérieures restent lisibles après la mise à jour. Elle fournit aussi les résultats des sous-agents sous forme de rapports en arrière-plan, que lisent les cartes de sous-agent et les Missions. | +| Recommandée | OpenCode **2.3.0** | Cible qualifiée ; actuellement la même version que le minimum. | | Non vérifiée | Version plus récente ou personnalisée non entièrement validée | Non rejetée simplement parce que non testée ; les contrats API réels du service connecté sont vérifiés. | Le service connecté doit exposer les contrats requis de session, permission, Form, boîte de réception et environnement de session. La programmation native des Missions vérifie aussi les API de programmation, l’ensemble plugin/fournisseur et le réglage effectif `experimental.schedules`. La disponibilité suit les capacités consommées, y compris sur les versions futures compatibles. Si la configuration signale un service actif non pris en charge, sélectionnez/installez une CLI prise en charge et utilisez le redémarrage explicite du service partagé lorsque vous êtes prêt. diff --git a/docs/help/fr/projects.md b/docs/help/fr/projects.md index ef0517622b..a770c929de 100644 --- a/docs/help/fr/projects.md +++ b/docs/help/fr/projects.md @@ -34,7 +34,7 @@ Un clic normal ouvre toujours l’accueil complet. Le lanceur est un raccourci, | Fermer l’onglet | Retire la connexion de projet CodeNomad de cet onglet ; un autre onglet ouvert séparément sur le même dossier n’est pas affecté | Ne supprime ni les fichiers du projet ni l’historique natif, n’arrête pas les sessions et ne décharge pas la Location d’OpenCode | | Arrêter la session | Exécution de la conversation sélectionnée | Ne ferme pas le projet et ne supprime pas son historique | -Si une autre fenêtre affiche la même connexion de projet, son onglet se ferme aussi et cette fenêtre affiche une notification. La fenêtre à l’origine de la fermeture n’en affiche pas. La fermeture est immédiate ; si le backend ne peut pas fermer le projet, une erreur apparaît et **Basculer vers le projet ouvert** sur l’accueil permet encore d’y accéder. Il n’y a pas de nouvel essai automatique. Les brouillons non envoyés de l’onglet fermé ne sont pas conservés par la restauration au démarrage. +Si une autre fenêtre affiche la même connexion de projet, son onglet se ferme aussi et cette fenêtre affiche une notification. La fenêtre à l’origine de la fermeture n’en affiche pas. La fermeture est immédiate ; si le backend ne peut pas fermer le projet, une erreur apparaît et **Basculer vers le projet ouvert** sur l’accueil permet encore d’y accéder. Il n’y a pas de nouvel essai automatique. Les brouillons et pièces jointes non envoyés de l’onglet fermé reviennent quand vous rouvrez le même dossier dans cette fenêtre ; elle les garde pour ses 16 derniers projets fermés, jusqu’à son rechargement ou sa fermeture. Ils ne font pas partie de la restauration au démarrage. Fermer une fenêtre entière, quitter ou recharger ne ferme pas ses connexions de projet ; la restauration normale au démarrage s’applique toujours. Arrêtez explicitement les exécutions concernées si vous devez vérifier qu’elles sont terminées. CodeNomad ne décharge jamais les Locations natives ; la maintenance du service partagé est décrite dans [Configuration d’OpenCode](opencode.md). @@ -59,7 +59,7 @@ Fermez les onglets de projet de ce serveur dans chaque fenêtre avant de le supp | Choix | Effet | Récupération | | --- | --- | --- | | Garder | Ferme le projet dans CodeNomad, conserve le dossier et les conversations, retire son statut temporaire et ajoute un projet récent | Rouvrir depuis les dossiers récents ; le dossier n’est pas déplacé | -| Jeter | Supprime les conversations et fichiers de l’espace de travail temporaire | Aucune annulation ; enregistrez d’abord ailleurs ce dont vous avez besoin | +| Jeter | Supprime les conversations, fichiers et brouillons non envoyés de l’espace de travail temporaire | Aucune annulation ; enregistrez d’abord ailleurs ce dont vous avez besoin | | Annuler | Laisse l’espace de travail temporaire ouvert | Continuer à travailler ou décider plus tard | Un onglet temporaire intact, sans conversation, fichier ni brouillon non envoyé, est supprimé discrètement à la fermeture. Les onglets temporaires ouverts participent à la restauration normale au démarrage, mais l’accueil n’a pas de liste séparée pour reprendre les dossiers temporaires fermés. diff --git a/docs/help/fr/providers.md b/docs/help/fr/providers.md index 98ef76bcf0..d5260816c2 100644 --- a/docs/help/fr/providers.md +++ b/docs/help/fr/providers.md @@ -56,15 +56,15 @@ Pour les connexions Google utilisant la méthode d’authentification Gemini CLI La [FAQ Antigravity](https://antigravity.google/docs/faq/) de Google indique que l’utilisation de logiciels tiers avec une connexion Antigravity enfreint ses conditions et peut entraîner la suspension ou la clôture du compte. -Pour les modèles payants de l’intégration `opencode`, **OpenCode Console** affiche les **Requêtes** pour **Aujourd’hui (UTC)**, **7 jours (UTC)** et **30 jours (UTC)**. Ces périodes calendaires UTC incluent aujourd’hui et commencent respectivement à 00:00 UTC aujourd’hui, il y a six jours et il y a 29 jours. **Requêtes par modèle · 30 jours** indique chaque modèle et son fournisseur. Les compteurs couvrent le compte Console connecté et sont formatés selon la langue de l’application. **Budgets des comptes de service** affiche **Budgets indisponibles.** OpenCode Go utilise son propre lecteur de quota. +Pour les modèles payants de l’intégration `opencode`, **OpenCode Console** affiche les **Requêtes** sur **24 heures**, **7 jours** et **30 jours**, telles que Console les fournit. **Requêtes par modèle · 30 jours** indique chaque modèle et son fournisseur. Les compteurs couvrent le compte Console connecté et sont formatés selon la langue de l’application. **Budgets des comptes de service** affiche **Budgets indisponibles.** Avec **Solde de crédits du fournisseur** activé, le solde de crédits Console apparaît sous **Crédits**. OpenCode Go utilise son propre lecteur de quota. Le lecteur utilise la clé API `opencode` enregistrée ou, en priorité, sa connexion OAuth Console. OAuth exige `https://opencode.ai/console` et l’identifiant d’organisation de la connexion ; l’accès Console nécessite l’autorisation **Usage › Read**. CodeNomad ne rafraîchit jamais ces identifiants. Une connexion OAuth invalide ou expirée doit être rétablie via son propriétaire, même si une clé API est aussi enregistrée. Les erreurs Console distinguent une connexion absente, un identifiant invalide ou expiré (401), un accès refusé (403), une réponse d’utilisation invalide et une panne réseau. Pour les erreurs de connexion, ouvrez **Paramètres → Fournisseurs**, vérifiez la connexion et ses autorisations, puis actualisez **Utilisation**. L’échec d’un résumé ou d’une page de modèles rend toute la lecture Console indisponible. -Pour les modèles gratuits OpenCode (`big-pickle` et identifiants finissant par `-free`), **Utilisation** additionne uniquement les requêtes gratuites du compte Console connecté depuis 00:00 UTC, sur une référence quotidienne de **800**. **Estimé** concerne le plafond et la réinitialisation au prochain minuit UTC ; les limites réelles peuvent varier. Le compteur inclut les autres clients du compte. Sans connexion Console, le panneau invite à se connecter pour les modèles gratuits et le suivi des quotas via **Paramètres → Fournisseurs**. Une lecture Console en échec laisse le compteur indisponible. +Pour les modèles gratuits OpenCode (`big-pickle` et identifiants finissant par `-free`), **Utilisation** affiche une seule barre : les requêtes gratuites du compte Console connecté sur les dernières 24 heures de Console, sur une référence de **800** ; les limites réelles peuvent varier. Le compteur inclut les autres clients du compte et n’a pas d’heure de réinitialisation. Avec **Solde de crédits du fournisseur** activé, le solde de crédits Console apparaît sous **Crédits**. Sans connexion Console, le panneau invite à connecter OpenCode Console via **Paramètres → Fournisseurs**. Une lecture Console en échec laisse le compteur indisponible. -Un échec de quota sur une étape gratuite marque cette connexion OpenCode **Épuisé** jusqu’à 00:00 UTC. Si un compteur Console est disponible, la jauge indique 100 % en conservant ce compteur. La marque reste en mémoire du backend par connexion et disparaît au redémarrage. L’utilisation gratuite, l’épuisement et les compteurs Console payants servent uniquement à l’affichage ; la sélection automatique de compte utilise ses propres lecteurs et règles. +L’utilisation gratuite et les compteurs Console payants servent uniquement à l’affichage ; la sélection automatique de compte utilise ses propres lecteurs et règles. OpenAI ne fournit pas l’utilisation pour l’une des méthodes de connexion ChatGPT : Utilisation l’indique au lieu d’afficher les fenêtres de quota. Choisissez [Consulter l’utilisation ChatGPT](https://chatgpt.com/settings/usage) pour consulter l’utilisation des applications et gérer leur accès à votre forfait et à vos crédits dans ChatGPT. Le chat fonctionne toujours, et reconnecter la même connexion ne rétablit pas la lecture. diff --git a/docs/help/fr/remote-access.md b/docs/help/fr/remote-access.md index 55242e0696..70f1cdabfa 100644 --- a/docs/help/fr/remote-access.md +++ b/docs/help/fr/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true Ne supposez pas le port 9898 ou 9899 : les ports omis peuvent changer s’ils sont occupés. Un `--https-port` explicite non nul, ou un `--http-port` avec HTTP activé, fixe le port et échoue si l’écoute est impossible ; `0` demande au système d’en attribuer un. Les **Local Connection URL** et **Remote Connection URL** affichées, et les **Adresses accessibles** actualisées, font autorité pour cette exécution. Voir la [référence CLI serveur](server.md) complète. +## Politique de l’administrateur {#administrator-policy} + +Un administrateur peut fixer l’adresse d’écoute : définissez `CODENOMAD_LOCKED_HOST` pour tout le système avec l’adresse que le serveur doit utiliser, puis redémarrez CodeNomad. Elle l’emporte sur `--host`, `CLI_HOST` et **Autoriser les connexions depuis d'autres IP**, qui affiche le résultat sans pouvoir le changer. Utilisez une adresse intranet pour que vos collègues joignent le serveur par le réseau de l’entreprise, ou `127.0.0.1` pour le garder sur cet ordinateur. Pour que tout accès reste dans le réseau de l’entreprise, définissez aussi `CODENOMAD_REMOTE_CONTROL=disabled` ([contrôle à distance](remote-control.md#administrator-policy)). + ## Mise à niveau {#upgrading} Reconnectez-vous après la mise à niveau. Pour un alias de nom d’hôte, un proxy inverse ou une interface hébergée séparément, définissez `CODENOMAD_ALLOWED_ORIGINS` sur le backend avec les origines de confiance de l’interface (protocole, nom d’hôte et port). Les clients natifs du LAN doivent fournir un en-tête `Origin` autorisé pour les requêtes de modification. Ses origines HTTPS permettent aussi à l’hôte d’appairer des appareils sans le tunnel ; voir [Appairer en HTTPS direct](remote-control.md#direct-https). -Utilisez une connexion en boucle locale pour les opérations réservées à l’hôte : contenu SideCar (`/sidecars/`) et WebSockets, gestion du Contrôle à distance (`/api/remote-control/`), pont des plugins (`/api/opencode-plugin/`), proxys distants (`/api/remote-proxy/`), gestion des serveurs enregistrés (`/api/remote-servers/`), changement de mot de passe et initialisation par jeton. Ces opérations exigent la boucle locale, même avec une connexion authentifiée directe depuis le LAN. Le contenu des aperçus actifs (`/previews/`) est accessible directement depuis le LAN avec un jeton de capacité valide. +Utilisez une connexion en boucle locale pour les opérations réservées à l’hôte : contenu SideCar (`/sidecars/`) et WebSockets, gestion du Contrôle à distance (`/api/remote-control/`), pont des plugins (`/api/opencode-plugin/`), proxys distants (`/api/remote-proxy/`), gestion des serveurs enregistrés (`/api/remote-servers/`), changement de mot de passe et initialisation par jeton. Ces opérations exigent la boucle locale, même avec une connexion authentifiée directe depuis le LAN. Seuls les SideCars font exception : le réglage **Ouvrir les SideCars en HTTPS** de l’hôte ouvre leur contenu et leurs WebSockets aux navigateurs connectés via une origine HTTPS de confiance ([SideCars](browser-sidecars.md#register-sidecar)). Le contenu des aperçus actifs (`/previews/`) est accessible directement depuis le LAN avec un jeton de capacité valide. Les API d’enregistrement `/api/sidecars` restent accessibles aux clients LAN directs authentifiés et aux appareils appairés. Les aperçus web du Contrôle à distance restent accessibles avec leur jeton de capacité lorsqu’ils sont activés sur l’hôte. diff --git a/docs/help/fr/remote-control.md b/docs/help/fr/remote-control.md index 34c8568b5f..1acb7c2017 100644 --- a/docs/help/fr/remote-control.md +++ b/docs/help/fr/remote-control.md @@ -86,3 +86,7 @@ CodeNomad utilise [OpenTunnel](https://github.com/anomalyco/opentunnel) et rése TLS se termine dans le backend CodeNomad. Le relais transfère du texte chiffré et ne peut pas lire le contenu applicatif, mais peut observer les noms d’hôte, horaires de connexion et volumes de trafic. Le certificat/la clé privée du tunnel restent sur l’hôte. Protégez le stockage du tunnel et la configuration CodeNomad comme des identifiants ; une adresse impossible à deviner n’est pas une autorisation. `CODENOMAD_REMOTE_CONTROL_API` sélectionne une API OpenTunnel auto-hébergée ; non définie, elle utilise le service hébergé. Cela change le déploiement du tunnel, pas les exigences d’appairage ni les surfaces bloquées. Voir [Sécurité](security.md) pour le traitement des identifiants et diagnostics. + +## Politique de l’administrateur {#administrator-policy} + +Un administrateur peut désactiver le contrôle à distance pour tous les utilisateurs d’un ordinateur : définissez la variable d’environnement `CODENOMAD_REMOTE_CONTROL=disabled` pour tout le système, puis redémarrez CodeNomad. Le backend ne connecte alors jamais de tunnel, refuse **Démarrer le contrôle à distance** et les liens d’appairage et ne se reconnecte pas au lancement ; les réglages affichent **Désactivé par l’administrateur**. Les appareils appairés auparavant ne peuvent pas se connecter et restent listés pour que vous puissiez les révoquer. Non définie ou vide, elle n’impose aucune politique ; toute autre valeur, même composée seulement d’espaces, empêche le backend de démarrer. diff --git a/docs/help/fr/security.md b/docs/help/fr/security.md index e92a3b7573..56da6b4ec8 100644 --- a/docs/help/fr/security.md +++ b/docs/help/fr/security.md @@ -33,7 +33,7 @@ La connexion directe crée une session opaque en mémoire du backend et un cooki La déconnexion révoque la session directe courante. Un changement de mot de passe réussi sur l’hôte révoque toutes les sessions directes de cet utilisateur, y compris celle de l’appelant ; reconnectez-vous. Les sessions expirent après 24 heures sans requête authentifiée ou sept jours depuis leur création. Pour ajuster ces limites, définissez `CODENOMAD_SESSION_IDLE_SECONDS` et `CODENOMAD_SESSION_ABSOLUTE_SECONDS` en secondes entières positives avant de démarrer le backend. Les appareils de Contrôle à distance se révoquent séparément. -Les clients LAN peuvent se connecter, se déconnecter et utiliser les projets. Le mot de passe, le Contrôle à distance, les outils de serveurs distants/proxy et les SideCars se gèrent sur l’hôte en loopback. Les modifications du navigateur exigent une Origin autorisée, ou le Referer en son absence. Les origines annoncées du serveur sont autorisées ; pour les alias DNS, proxys inverses ou interfaces hébergées séparément, définissez `CODENOMAD_ALLOWED_ORIGINS` avec des origines HTTP(S) exactes séparées par des virgules, par exemple `https://code.example.test,https://ui.example.test:8443`, puis redémarrez. N’ajoutez ni chemin ni joker. Cela autorise le navigateur, sans donner les privilèges de l’hôte. Les clients natifs effectuant des modifications LAN doivent aussi fournir une Origin autorisée. Un proxy de confiance connecté en loopback dispose des privilèges de l’hôte et doit appliquer ses propres contrôles d’accès. Quand le serveur écoute en loopback ou sur toutes les interfaces, l’interface ouverte sur l’hôte en `localhost`, avec le même schéma et le même port, fonctionne aussi. +Les clients LAN peuvent se connecter, se déconnecter et utiliser les projets. Le mot de passe, le Contrôle à distance, les outils de serveurs distants/proxy et les SideCars se gèrent sur l’hôte en loopback. Le réglage **Ouvrir les SideCars en HTTPS** de l’hôte ouvre les SideCars aux navigateurs connectés via une origine HTTPS de confiance ; ne l’activez que si tous les utilisateurs de ces adresses peuvent utiliser vos services SideCar. Les modifications du navigateur exigent une Origin autorisée, ou le Referer en son absence. Les origines annoncées du serveur sont autorisées ; pour les alias DNS, proxys inverses ou interfaces hébergées séparément, définissez `CODENOMAD_ALLOWED_ORIGINS` avec des origines HTTP(S) exactes séparées par des virgules, par exemple `https://code.example.test,https://ui.example.test:8443`, puis redémarrez. N’ajoutez ni chemin ni joker. Cela autorise le navigateur, sans donner les privilèges de l’hôte. Les clients natifs effectuant des modifications LAN doivent aussi fournir une Origin autorisée. Un proxy de confiance connecté en loopback dispose des privilèges de l’hôte et doit appliquer ses propres contrôles d’accès. Quand le serveur écoute en loopback ou sur toutes les interfaces, l’interface ouverte sur l’hôte en `localhost`, avec le même schéma et le même port, fonctionne aussi. En cas de compromission suspectée : diff --git a/docs/help/fr/server.md b/docs/help/fr/server.md index 73c0203ab9..9b6eb3bdf3 100644 --- a/docs/help/fr/server.md +++ b/docs/help/fr/server.md @@ -8,7 +8,7 @@ La même interface prend en charge [plusieurs onglets de projet et worktrees](pr 1. Installez Node.js 24 LTS et npm ; la version d’exécution du dépôt pour la compilation est épinglée dans `.node-version`. Les paquets de bureau fournissent leur propre environnement : Electron utilise son Node intégré, Tauri embarque Node et les deux incluent npm. 2. Placez Git dans le **PATH du processus backend**. Git dans WSL seul ne suffit pas pour un backend Windows. -3. Installez ou sélectionnez OpenCode : **2.2.3** est le minimum requis et **2.2.7** la cible de qualification recommandée. Les versions plus récentes ou personnalisées passent des contrôles de compatibilité, pas une liste de versions testées autorisées. Consultez la [configuration d’OpenCode](opencode.md). +3. Installez ou sélectionnez OpenCode : **2.3.0** est le minimum requis et **2.3.0** la cible de qualification recommandée. Les versions plus récentes ou personnalisées passent des contrôles de compatibilité, pas une liste de versions testées autorisées. Consultez la [configuration d’OpenCode](opencode.md). 4. Choisissez le dossier depuis lequel démarrer le serveur, ou passez explicitement `--workspace-root`. Sans Git, les conversations restent disponibles uniquement dans le dossier physique explicitement ouvert ; les opérations Git et worktree échouent. Installez Git et redémarrez le backend après une modification de PATH. Une racine d’espace de travail limite l’ouverture/la navigation, pas l’exécution de l’agent : voir [Sécurité](security.md). @@ -104,6 +104,8 @@ La référence publique liste les options destinées aux utilisateurs ; les hôt | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad` ; dépôt interrogé pour les versions proposées. | | `CODENOMAD_REMOTE_CONTROL_API` | Non défini : API OpenTunnel hébergée. Définissez une origine d’API pour un déploiement de relais auto-hébergé. | +| `CODENOMAD_REMOTE_CONTROL` | Non définie : les utilisateurs peuvent démarrer le contrôle à distance. `disabled` : désactivé par un administrateur ([politique](remote-control.md#administrator-policy)) ; non définie ou vide : aucune politique, toute autre valeur (espaces compris) empêche le démarrage. | +| `CODENOMAD_LOCKED_HOST` | Non définie ou vide : `--host` s’applique ; des espaces seuls empêchent le démarrage. Une adresse : le serveur écoute sur celle-ci, quels que soient `--host`, `CLI_HOST` ou l’interrupteur d’écoute ([politique](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | Fichier d’AC supplémentaire facultatif de Node ; transmis avec l’environnement de démarrage autorisé au lancement d’un démon OpenCode manquant. Ne modifie pas un démon déjà actif. | Les identifiants d’utilisation propres aux fournisseurs sont décrits dans [Fournisseurs](providers.md). La sélection du profil de données de bureau est décrite dans [Bureau](desktop.md), et n’est pas contrôlée par le flux de versions. diff --git a/docs/help/fr/settings.md b/docs/help/fr/settings.md index 72e46a0234..c87ec35091 100644 --- a/docs/help/fr/settings.md +++ b/docs/help/fr/settings.md @@ -70,7 +70,7 @@ Faites glisser le bord intérieur d’un panneau ancré pour le redimensionner. 2. Ouvrez **Personnaliser le panneau droit** dans le panneau droit. Utilisez les cases pour choisir les onglets intégrés et sections Statut ; au moins une section Statut reste visible. Faites glisser le pointeur sur ces cases pour en régler plusieurs d'un coup. 3. Faites glisser les onglets du panneau droit pour les réordonner. Utilisez **Réinitialiser** pour restaurer les choix de disposition intégrée. -Les [intégrations](integrations.md#integration-sections) reconnues ont aussi leurs sections Statut. Masquez-les avec les mêmes cases ; réordonnez toute section Statut par glisser-déposer ou avec les touches Haut/Bas. Le masquage et l’ordre persistent aux rechargements et à l’absence temporaire d’une intégration. +Réordonnez toute section Statut par glisser-déposer ou avec les touches Haut/Bas. Le masquage et l’ordre persistent aux rechargements. Statut inclut les informations de tokens, le mode Yolo, l’utilisation fournisseur, les shells en arrière-plan, MCP et Plugins. Tant que la conversation a un [objectif](conversations.md#goal), une ligne d’objectif au-dessus de ces sections l’affiche ; cette ligne n’est pas une section et ne peut être ni masquée ni déplacée. Masquer une section ne désactive pas son service et ne révoque pas de permissions. Les dispositions étroites ferment les panneaux qui ne tiennent plus au lieu de comprimer la conversation ; un panneau ouvert alors flotte au-dessus d’elle, et ouvrir un panneau flottant ferme l’autre. diff --git a/docs/help/fr/troubleshooting.md b/docs/help/fr/troubleshooting.md index 822e11a07b..6c202937eb 100644 --- a/docs/help/fr/troubleshooting.md +++ b/docs/help/fr/troubleshooting.md @@ -42,7 +42,7 @@ Si un worktree détenu ou l’emplacement d’une conversation ne peut être vé ## Environnement OpenCode et WSL {#opencode-runtime} 1. Ouvrez **Préférences → OpenCode** et vérifiez la carte **Version d’OpenCode** (version installée et état du service actif), puis l’exécutable sélectionné sous **Binaire OpenCode**. -2. Utilisez l’action d’installation/mise à jour prise en charge si l’environnement requis manque. Minimum actuel : **2.2.3** ; version recommandée/qualifiée : **2.2.7**. +2. Utilisez l’action d’installation/mise à jour prise en charge si l’environnement requis manque. Minimum actuel : **2.3.0** ; version recommandée/qualifiée : **2.3.0**. 3. Si la CLI installée diffère du service actif, décidez explicitement s’il faut redémarrer le service partagé. **Redémarrer le service OpenCode** est disponible sous **Dépannage** et exige confirmation. Cela interrompt le travail actif de tous les clients connectés mais conserve l’historique. Le rechargement de configuration est distinct : il garde le processus mais reconstruit les Locations chargées et annule les questions/autorisations en attente. Aucun n’est une actualisation anodine. diff --git a/docs/help/he/browser-sidecars.md b/docs/help/he/browser-sidecars.md index 05579ffae0..665aad2f0a 100644 --- a/docs/help/he/browser-sidecars.md +++ b/docs/help/he/browser-sidecars.md @@ -77,7 +77,7 @@ Service workers מושבתים בתצוגות מקדימות מרוחקות. SideCar הוא הרחבה מהימנה של CodeNomad, לא תצוגה מקדימה בארגז חול: הדף שלו רץ במקור (origin) של CodeNomad עצמו, ולכן הסקריפטים שלו יכולים להשתמש ב־CodeNomad עם הגישה שלכם כמשתמשים מחוברים. רשמו רק שירותים שאתם סומכים על הקוד שלהם. CodeNomad אינו מעביר לשירות את עוגיות ההתחברות שלו, ואילו העוגיות של השירות עצמו נשמרות. -תוכן SideCar ‏(`/sidecars/`) וחיבורי WebSocket של SideCar דורשים חיבור loopback במארח. רישום דרך `/api/sidecars` זמין למכשירים מצומדים וללקוחות LAN ישירים מאומתים. תוכן תצוגות מקדימות פעילות (`/previews/`) זמין בגישת LAN ישירה עם אסימון יכולת תקף; תצוגות האינטרנט של [שליטה מרחוק](remote-control.md#remote-surface) נשארות זמינות עם אסימון היכולת שלהן כל עוד הן מופעלות. לדרישות הגישה הישירה ראו [שדרוג](remote-access.md#upgrading). +תוכן SideCar ‏(`/sidecars/`) וחיבורי WebSocket של SideCar דורשים חיבור loopback במארח. כדי לפתוח אותם גם ממכשירים אחרים, הפעילו במארח את **פתיחת SideCars דרך HTTPS** ב־**הגדרות → SideCars**: דפדפנים שמחוברים דרך כתובות ה־HTTPS של שרת זה או דרך מקור HTTPS ב־`CODENOMAD_ALLOWED_ORIGINS`, למשל מאחורי מתווך הפוך עם TLS, יוכלו אז לפתוח SideCars. HTTP רגיל, כתובות `localhost` ושליטה מרחוק נשארים במארח בלבד. רישום דרך `/api/sidecars` זמין למכשירים מצומדים וללקוחות LAN ישירים מאומתים. תוכן תצוגות מקדימות פעילות (`/previews/`) זמין בגישת LAN ישירה עם אסימון יכולת תקף; תצוגות האינטרנט של [שליטה מרחוק](remote-control.md#remote-surface) נשארות זמינות עם אסימון היכולת שלהן כל עוד הן מופעלות. לדרישות הגישה הישירה ראו [שדרוג](remote-access.md#upgrading). ## מתכון ל־OpenVSCode Server {#openvscode} diff --git a/docs/help/he/conversations.md b/docs/help/he/conversations.md index 9802b22c5e..f0675f7c9d 100644 --- a/docs/help/he/conversations.md +++ b/docs/help/he/conversations.md @@ -60,6 +60,12 @@ CodeNomad מציג סשנים מקוריים של OpenCode כשיחות, עם ה טיוטות הן מצב עבודה בצד הלקוח, לא הודעות מקוריות משותפות. שחזור בהפעלה יכול לשמר מצב נתמך של שדה הקלט, אך אל תתייחסו לטיוטה או לצירוף שלא נשלחו כאל גיבוי ואל תניחו שהם מופיעים במכשיר אחר. שמרו טקסט חשוב לפני ניקוי נתוני הפעלה או סגירת לקוח שמדיניות השחזור שלו מושבתת; ראו [שולחן עבודה](desktop.md). +## פתיחת קבצים מתשובות {#open-files-from-replies} + +1. תשובות הסוכן מקשרות קבצי פרויקט בנתיבים יחסיים ומוחלטים. +2. לחיצה רגילה פותחת את הקובץ המקושר בתצוגה המקדימה של הקובץ, בקריאה מעץ העבודה של השיחה. +3. לחיצות עם מקשים נוספים (Ctrl/⌘, Shift, לחיצה אמצעית) וקישורים מחוץ לעץ העבודה של ההפעלה שומרים על התנהגות קישור רגילה. + ## פקודות ומצב מעטפת {#commands-shell} 1. הקלידו `/`, בחרו פקודה מותאמת שהתגלתה וספקו את הארגומנטים שלה. diff --git a/docs/help/he/install.md b/docs/help/he/install.md index 292709e4e1..452af2a97a 100644 --- a/docs/help/he/install.md +++ b/docs/help/he/install.md @@ -45,7 +45,7 @@ chmod +x CodeNomad-Tauri-linux-x64-.AppImage | דרישה | היכן עליה להיות זמינה | הדרישה הנוכחית | | --- | --- | --- | -| OpenCode CLI | מארח ההרצה שנבחר, לרבות הפצת WSL שנבחרה כשמתאים | מינימום **2.2.3**; **2.2.7** היא הגרסה המומלצת/שנבדקה. גרסאות חדשות או מותאמות עוברות אימות חוזים ולא חסימה מפני שלא נבדקו. | +| OpenCode CLI | מארח ההרצה שנבחר, לרבות הפצת WSL שנבחרה כשמתאים | מינימום **2.3.0**; **2.3.0** היא הגרסה המומלצת/שנבדקה. גרסאות חדשות או מותאמות עוברות אימות חוזים ולא חסימה מפני שלא נבדקו. | | Git | ב־`PATH` של חשבון שרת הקצה של CodeNomad | נדרש לזהות מאגר, לפעולות Git ול־worktrees. | | Node.js/npm | מארח שרת עצמאי ובנייה מקוד מקור | Node.js 24 LTS; בניות שחזוריות מקוד מקור משתמשות בגרסה המקובעת ב־`.node-version`. גרסאות שולחן העבודה כוללות סביבה משלהן: ה־Node המשולב של Electron או ה־Node ש־Tauri כולל, עם npm. | | תיקיית סביבת עבודה | דיסק נגיש לשרת הקצה | תיקייה פיזית שנפתחה במפורש, לא תיקייה מקומית למכשיר שהוסקה מדפדפן מרוחק. | diff --git a/docs/help/he/integrations.md b/docs/help/he/integrations.md index cf9a646de3..32eb46c018 100644 --- a/docs/help/he/integrations.md +++ b/docs/help/he/integrations.md @@ -27,7 +27,7 @@ CodeNomad מציג את חיבורי MCP, הפעלת התוספים, המיומ תוספים המנוהלים על ידי CodeNomad נשארים מחוץ לרשימת התוספים הרגילה ולפקדי ההפעלה, העדכון וההסרה שלה. CodeNomad מזהה אותם לפי רשומת ההתקנה המאומתת ומיקום הקוד המזוהה לפי גיבוב התוכן שלו; תוסף צד שלישי בעל אותו שם או מזהה שומר על הפקדים הרגילים שלו. -אם תוסף מנוהל מושבת, נכשל בטעינה או שטעינתו טרם אושרה, ההודעה **תוספי CodeNomad דורשים תשומת לב** מופיעה מעל רשימת התוספים. פתחו את כפתור **i** שלו (**פרטים על** התוסף) כדי לראות את השגיאה הזמינה ואת המזהה שלה ביומן OpenCode. רק תוסף מושבת מציע **הפעלה מחדש**: הפעולה מוסיפה כלל הפעלה חיובי עבור המזהה המדויק ושומרת את כלל ההשבתה. היא כותבת בהיקף **כללי** או **פרויקט** של כלל ההשבתה אם אפשר לכתוב בו, ואחרת בהיקף **פרויקט**. OpenCode ממשיך לפעול; האזהרה נשארת עד שאירועים מקוריים או **רענון פקדי התוספים** מאשרים שהתוסף פעיל. +אם תוסף מנוהל מושבת, נכשל בטעינה או שטעינתו טרם אושרה, ההודעה **תוספי CodeNomad דורשים תשומת לב** מופיעה מעל רשימת התוספים. פתחו את כפתור **i** שלו (**פרטים על** התוסף) כדי לראות את השגיאה הזמינה ואת המזהה שלה ביומן OpenCode. רק תוסף מושבת מציע **הפעלה מחדש**: הפעולה מסירה מהקובץ את כלל ההשבתה המדויק של התוסף כשזה לבדו מפעיל אותו מחדש, ואחרת מוסיפה כלל הפעלה חיובי עבור המזהה המדויק. היא כותבת בהיקף **כללי** או **פרויקט** של כלל ההשבתה אם אפשר לכתוב בו, ואחרת בהיקף **פרויקט**. OpenCode ממשיך לפעול; האזהרה נשארת עד שאירועים מקוריים או **רענון פקדי התוספים** מאשרים שהתוסף פעיל. האזהרה והפרטים שלה מסמנים את מקור התצורה כ־**בירושה / חיצונית** או **תצורה וירטואלית**, לפי העניין. תווית **פרויקט** נפרדת מציינת את יעד ההפעלה מחדש כשהוא שונה ממקור כלל ההשבתה. @@ -38,7 +38,7 @@ CodeNomad מציג את חיבורי MCP, הפעלת התוספים, המיומ כללי מכוון לתצורה הגלובלית שהתגלתה בדמון המחובר. פרויקט מכוון לתצורה בתוך ה־Location הפעיל, לא לקובץ אב שממנו יורשים. כלל פרויקט מאוחר יותר יכול לגבור על כללי; המתג הכללי עדיין מציג את הכלל הגלובלי במקום להתחזות למצב הפרויקט הסופי. ללא כלל פרויקט, פרויקט יורש את המצב הכללי הפתור. -מתגים אלה מוסיפים כללי הפעלה מדויקים תוך שימור הכרזות מקור ותצורה לא קשורה. הם אינם עורכים אפשרויות תוסף, מתקינים חבילות או מסירים קבצים. תוספים מובנים של OpenCode אינם מוצעים כמתגי הפעלה למשתמש. פרויקט מושבת כשאי אפשר להפריד בבטחה את היעד שלו מכללי או כשהוא יחרוג מה־Location הפעיל. +כל מתג כותב כלל הפעלה מדויק אחד לתוסף בקובץ של ההיקף שלו, ומחליף שם את הכללים המדויקים הקודמים של אותו תוסף, או רק מסיר אותם כשהתוצאה זהה. הכרזות מקור, כללים רחבים יותר כמו `*` ותצורה לא קשורה נשמרים. הם אינם עורכים אפשרויות תוסף, מתקינים חבילות או מסירים קבצים. תוספים מובנים של OpenCode אינם מוצעים כמתגי הפעלה למשתמש. פרויקט מושבת כשאי אפשר להפריד בבטחה את היעד שלו מכללי או כשהוא יחרוג מה־Location הפעיל. עדכון חבילה משנה את אותה חבילה במטמון המשותף של OpenCode עבור כל Location שמשתמש בה, כפי שמציין תיאור הכלי שלה; הוא אינו משנה כללי הפעלה, מפעיל מחדש את OpenCode או טוען מחדש את התצורה. לתוספים מקומיים, מובנים או כאלה שמסופקים על ידי ה־SDK אין פעולת חבילה. חבילה שנכשלת לפני שהיא מדווחת על מזהה התוסף שלה מופיעה לפי שם החבילה, עם הכשל בתיאור הכלי שלה ועם פעולות בדיקה/עדכון אך ללא מתגי הפעלה. בדיקה או עדכון שנכשלו מדווחים ולעולם אינם מנוסים שוב אוטומטית. @@ -78,38 +78,30 @@ CodeNomad מציג את חיבורי MCP, הפעלת התוספים, המיומ פקודות מתגלות מ־OpenCode עבור ה־Location הפעיל. ההגדרה המקורית שלהן יכולה לבחור התנהגות הרצה; התפריט אינו מתקין חבילות או עורך תצורה ללא הגבלה. CodeNomad מחיל את סביבת הסשן של הפרופיל לפני שליחת פקודה מותאמת מקורית; כשל בעדכון הסביבה חוסם את השליחה. `/btw` הוא זרימת שאלה ארעית נפרדת של CodeNomad, לא פקודה מותאמת רגילה. להגדרות פקודות ולירושת תצורה מקורית, השתמשו ב־[תיעוד פקודות OpenCode](https://opencode.ai/v2/docs/commands/). לאחר שינויי תצורה, רעננו/פתחו מחדש תחילה את הממשק הרלוונטי; השתמשו בטעינת תצורה מפורשת מחדש רק אם סביבת הריצה עדיין דורשת אותה. לעולם אל תחזרו על פקודה שאולי התקבלה להרצה רק כדי לרענן את תצוגתה. -## מקטעי אינטגרציה בסטטוס {#integration-sections} +## אינטגרציות בתוספים {#integration-rows} ב־**סטטוס → תוספים**, התפריט **+** מציע **הוספת אינטגרציה…** או **הוספת תוסף…**. בורר האינטגרציות מציג רשומות שטרם הותקנו מהקטלוג הנבדק. בחרו היקף ו־**התקנה**: CodeNomad מתקין את מזהה הקטלוג שנבחר. אינטגרציות מקומיות משתמשות ב־**כללי בלבד**. **הקטלוג אינו זמין** מציע **רענון**; **קטלוג מתאריך {date}** מציין את הקטלוג התקין האחרון כשהוא מיושן. -לכל אינטגרציה מזוהה עם הכרזה או תוסף שנטען/נכשל יש מקטע משלה ב־**סטטוס**, גם כשהיא מושבתת או בהתקנה. מקור דו־משמעי מציג **לא תואם לתקן** בתוספים. כל אינטגרציה שומרת את שורת התוספים שלה עם פעולות עדכון, הסרה ורענון. הרחיבו את המקטע כדי לראות את הגרסה ופקדי התוסף בגוף; השם והמצב נשארים בכותרת ליד **תיעוד** ו־**i**. החלונית של **i** מציגה פרטים לפי דרישה: Enter/רווח לפתיחה, Escape לסגירה. +לאינטגרציה מזוהה יש שורה אחת ב־**סטטוס → תוספים**, עם שמה (למשל **OpenCode for Blender**) והגרסה שלה. המתגים **כללי** ו־**פרויקט** שלה בצבע ההדגשה כמו שאר המתגים, ואילו המתגים של תוסף רגיל ירוקים; אינטגרציה עם רכיב בתוך יישום היא **כללי בלבד**. רחפו מעל שמה: הפרטים מתחילים ב־**אינטגרציה** במקום **תוסף**; קוראי מסך מקריאים אותם כתיאור השורה. מקור דו־משמעי מציג **לא תואם לתקן**. -התאמת הסטטוס מאפשרת להסתיר את כל המקטעים ולסדר אותם בגרירה או במקשי מעלה/מטה. הנראות והסדר נשמרים בטעינה מחדש ובהיעדר זמני של אינטגרציה. אם מקטע ממוקד נעלם, המיקוד חוזר לתוספים, או למקטע סטטוס גלוי אחר כשהתוספים מוסתרים. +מתחת לשם, שורת מצב מראה תמיד היכן האינטגרציה עומדת. טקסט אפור מיידע; טקסט בצבע ההדגשה הוא כפתור. באינטגרציה עם רכיב בתוך יישום מוצג המצב החשוב ביותר: **התקנה ב־Blender** או **עדכון Blender** כשהרכיב חסר או ישן (עם אישור ההתקנה), אי־תאימות בצבע האזהרה, סמל שרשרת והמסמך כשהשיחה המוצגת מחוברת (בחרו כדי לנתק), **Blender סגור**, **Blender: אין מסמך פתוח**, **אין שיחה מוצגת**, ואחר כך **חיבור** עם שם המסמך, או **חיבור…** כדי לבחור בין כמה מסמכים. שיחה גם מתחברת מעצמה בפעם הראשונה שהסוכן שלה משתמש באינטגרציה. אינטגרציות MCP של עורך מציגות **השרת זוהה** או **השרת לא נמצא**, ואינטגרציות API **מחובר** או **מנותק**. מצב ארוך מקוצר; רחפו מעליו כדי לראות את הטקסט המלא. שינויים שהאינטגרציה מדווחת וחיבורים מחדש מרעננים את השורה. -התקנה מהקטלוג, התקנת/עדכון חלק היישום, חיבור והסרה דורשים אישור. המיקוד הראשוני ב־**ביטול**; פעולת האישור זמינה אחרי 600 אלפיות השנייה. הפעלה ועדכוני תוסף מתבצעים ישירות. +התפריט **…** של השורה מתחיל במצב החיבור, למשל **Blender: מסמך פתוח אחד** או **Blender סגור**. לאחר מכן הוא מציע **תיעוד**, **התקנה ביישום…**, **עדכון היישום…** או **התקנה מחדש ביישום…** ([ראו בהמשך](#application-installation)), בדיקת עדכונים של החבילה, **הסרה מ-כללי** או **הסרה מ-פרויקט**, ו־**רענון פקדי התוספים**. הניתוק נעשה בלחיצה אחת ללא אישור ומשפיע רק על שיחה זו: היישום נשאר פתוח, הרכיב שלו נשאר מותקן ושיחות אחרות שומרות על החיבור שלהן. אם התשובה אובדת, השורה קוראת שוב את המצב; הבקשה לעולם אינה חוזרת. -## חיבור יישום פתוח {#application-attachment} +התקנה מהקטלוג, התקנה או עדכון של רכיב היישום והסרה דורשים אישור. **ביטול** מקבל את המיקוד תחילה; פעולת האישור זמינה אחרי 600 מ״ש. הפעלה, עדכוני תוספים, חיבור וניתוק מתבצעים ישירות. -הציעו מסמך דרך האינטגרציה ביישום, פתחו **סטטוס → האינטגרציה → שיחה** ובחרו **חיבור…**. מקטע זה שולט בחיבור השיחה המוצגת. בחרו יישום ומסמך, בדקו את שיחת היעד ואת אזהרת השינוי ואשרו ב־**חיבור**. היישום פועל במחשב של OpenCode, גם בחיבור מרוחק. מארח שאינו נתמך, כולל WSL, מציע עזרה דרך **i**. - -השורה **שיחה** קוראת את חיבור השיחה המוצגת. **החיבור אינו ידוע** מציע **רענון**. כאשר קריאה עדכנית ומוסמכת מאשרת את החיבור, **ניתוק** מחליף את **חיבור…**. לחיצה אחת מנתקת רק שיחה זו ללא אישור נוסף; היישום נשאר פתוח, חלק היישום מותקן ושיחות אחרות שומרות על חיבוריהן. שינויים מקומיים וחיבורים מחדש מרעננים את המצב. - -פעולה שהתקבלה שומרת את התוצאה או השגיאה כל עוד שיחת היעד מוצגת; ניווט סוגר את הקבלה. החיבור הנוכחי נקבע לפי הקריאה המוסמכת. **מצב לא ודאי** אחרי אובדן תשובה, חריגת זמן או ניתוק מציע **רענון** לקריאת המצב בפועל. אין לשדר שוב בקשה כדי לרענן את התצוגה. - -לאחר קריאה מפורשת של היישומים הפתוחים בבורר, המטא־נתונים השמורים ב־Q8 יכולים להציע **חיבור מחדש** בבורר או בשורה **שיחה** עבור אותה אינטגרציה ותווית מסמך מאומתת, כל עוד הפרויקט, השיחה ודור החיבור נשארים זהים. חיבור מחדש דורש אישור מפורש; ניווט או ביטול תוקף הנתונים מסירים את ההצעה. הסמכות לגבי החיבור הנוכחי מגיעה מקריאת האינטגרציה עבור השיחה המסוימת. - -הסרה ממקטע האינטגרציה או משורת התוספים שלה משתמשת באותה הכרזה ובאותו אישור היקף. היא מתבצעת ללא מפקד שיחות או ניתוק אוטומטי. +ההסרה מתבצעת ללא מפקד שיחות וללא ניתוק אוטומטי. הסרת תוסף מציגה אזהרה עם שמו והטווח המדויק. **ביטול** מקבל מיקוד; **הסרה מ־גלובלי/פרויקט** זמינה אחרי 600 אלפיות השנייה ודורשת פעולה מפורשת. ההסרה עלולה לקטוע זמינות וחיבורים בשיחות המשתמשות בתוסף; בטווח גלובלי גם פרויקטים אחרים עלולים להיפגע. ביטול, תפוגה או ניווט לפני השליחה משאירים הכול ללא שינוי. רק ההצהרה שאושרה מוסרת; כללים, מטמון, קובצי יישום ורמזי חיבור שמורים נשמרים. שינוי בתצורה דורש בחירה ואישור חדשים. הצלחה מאשרת את הסרת ההצהרה; מצב הריצה מתעדכן עם טעינת OpenCode. אם התשובה אבדה, יש לרענן ולבדוק את התצורה לפני ניסיון נוסף. התקנה מחדש עשויה להשיב זמינות, לעיתים עם טעינה או חיבור מחדש; פעולות שנקטעו עלולות שלא להתחדש. ## התקנה או עדכון של האינטגרציה של היישום {#application-installation} -ב־**סטטוס → האינטגרציה → יישום**, בחרו **התקנה ביישום…** או **עדכון היישום…** כשהמצב העדכני מציע את הפעולה. היא זמינה גם בלי שיחה או מסמך מוצע. אם היישום סגור, פתחו אותו כדי לבדוק את חלק היישום; **i** מציג את פרטי המחשב והתנאים המוקדמים. +ב־**סטטוס → תוספים**, בחרו **התקנה ב־Blender** או **עדכון Blender** בשורת המצב של האינטגרציה כשהמצב העדכני שלה מציע את הפעולה, או **התקנה ביישום…**, **עדכון היישום…** או **התקנה מחדש ביישום…** בתפריט **…** שלה. התקנה מחדש כותבת מחדש את רכיב היישום, כשהיישום פתוח או סגור. הפעולה זמינה גם ללא שיחה או מסמך פתוח. האישור מציג את היישום ואת **גרסת חבילת האינטגרציה** שמספקת את המתקין. יש לבדוק את שניהם ואת אזהרת המחשב: ההתקנה מתבצעת במחשב שבו OpenCode פועל, שעשוי להיות מרוחק. המיקוד הראשוני הוא ב־**ביטול**. יש לאשר במפורש כדי להמשיך. מעבר לפרויקט, ל־Location או לשיחה אחרים, חיבור מחדש או קבלת שינויים מקומיים רלוונטיים לפני האישור מבטלים את האישור הממתין; יש לפתוח את הפעולה שוב כדי לבדוק פרטים עדכניים. ב־WSL ההתקנה ביישום תמיד מסורבת, גם אם יישום פתוח נראה תואם. יש לפתוח את היישום במחשב נתמך. -התוצאה מדווחת שהאינטגרציה הותקנה, עודכנה, כבר מעודכנת, סורבה או נכשלה. אחרי התקנה או עדכון יש לפתוח את היישום ולבדוק את האינטגרציה שלו; חיבור שיחה מתבצע בנפרד דרך [חיבור יישום פתוח](#application-attachment). הצלחת ההתקנה מתארת את בקשת ההתקנה; זמינות היישום בזמן אמת נקבעת לפי הסטטוס שלו. +התוצאה מדווחת שרכיב היישום הותקן, עודכן, כבר מעודכן, נדחה או נכשל. אחרי התקנה או עדכון, פתחו את היישום ובדקו את האינטגרציה שלו. הצלחת ההתקנה מתארת את בקשת המתקין; הזמינות בפועל של היישום נקבעת לפי הסטטוס שלו. בקשות לעולם אינן נשלחות שוב אוטומטית. אחרי סירוב או כשל יש לבדוק את היישום לפני בחירת פעולה חדשה. אם שגיאה משאירה את התוצאה לא ודאית, אין לחזור על אותה בקשה: יש לבדוק תחילה את היישום, ואז להתחיל פעולה חדשה עם אישור לפי הצורך. diff --git a/docs/help/he/missions.md b/docs/help/he/missions.md index 20e30cd01a..1d5ee72e27 100644 --- a/docs/help/he/missions.md +++ b/docs/help/he/missions.md @@ -42,7 +42,7 @@ ### התחלה אוטומטית {#automatic-start} -**התחלה אוטומטית** נמצאת מחוץ לתזמון וכבויה כברירת מחדל. כשהיא כבויה, המשימה נוצרת בהשהיה להפעלה מאוחרת ב־▶. כשהיא מופעלת, מתבקשת התחלה לאחר אישור היצירה, בכפוף לבדיקות ולאישור ההגדרות המקוריות הנדרש. +**התחלה אוטומטית** נמצאת מחוץ לתזמון וכבויה כברירת מחדל. כשהיא כבויה, המשימה נוצרת בהשהיה להפעלה מאוחרת ב־▶. כשהיא מופעלת, מתבקשת התחלה לאחר אישור היצירה, עם הבדיקות הרגילות והכנה אוטומטית של התזמון. אם אישור היצירה אבד, קריאת הקבלה משאירה את ההתחלה ידנית. שמרו את הבקשה המקורית שלא אושרה ובדקו רשימה ושיחה לפני יצירה נוספת. @@ -56,6 +56,8 @@ האפשרויות כוללות עכשיו פעם אחת, כל N שעות, כל יום, ימי שבוע, יום בחודש ו־cron. אזור הזמן השמור קובע, והשדה מופיע כשיש הבדל מהמערכת. חודשים בלי היום הנבחר מדולגים. עכשיו פעם אחת נקבע בהפעלה ומעניק הזדמנות אחת, שתנאי יכול לצרוך ללא הרצה. שירות OpenCode ומחשב הביצוע צריכים להיות זמינים. +התחלה או המשך מכינים את התזמון אוטומטית בתצורת OpenCode של הפרויקט. מצב OFF מפורש נשמר: **פתיחת הגדרות התזמון**, כאשר האפשרות זמינה, פותחת את הקובץ האחראי; **i** מציג את המקור או את פרטי הסביבה. הכפתור שנלחץ מציג טעינה רק בזמן הבקשה. תוצאה לא מאושרת מאפשרת בדיקה; לאחר שחזור ההפעלה נדרשת התחלה מפורשת. + ### אירועים ושילובים {#scheduling-conditions} בחרו **פעילות במאגר → אירוע**, ואז מסננים אופציונליים באותו כרטיס. קומיטים של Git חולקים את התפריט עם אירועי מאגר GitHub, GitLab או Gitea המזוהה אוטומטית, כמו ב-Contribute (`upstream`, ואז `origin`). שלושתם תומכים ב-PR/MR חדשים, ב-PR/MR שמוזגו וב-Issues חדשים, עם **מחבר (אופציונלי)**, כולל `dependabot[bot]`. בחירת אירוע קובעת את המאגר; קריטריונים שמורים שומרים על היעד שלהם. @@ -88,9 +90,11 @@ ### צבעים ומצבים {#status-colours} -הדגל מציג את מצב המשימה והחץ את תשומת הלב למטלותיה; רשומה חוזרת משתמשת בסמל חזרה. אדום ממתין לתשובה, צהוב פועם מציין עבודה שנצפתה, כתום השהיה/הפסקה, ירוק תוצאה שלא נראתה וכחול הכנה או מטלה שטרם החלה. +הדגל מציג את מצב המשימה והחץ את תשומת הלב למטלותיה; רשומה חוזרת משתמשת בסמל חזרה. אדום ממתין לתשובה וצהוב פועם מציין עבודה שנצפתה. סמל השהיה כתום מציין השהיה ומשולש אזהרה כתום מציין הפסקה. ירוק מציין משימה, מטלה או הרצה מוצלחת הממתינות לעיון. + +סמל בצבע ההדגשה עם קו ניטרלי קטן וקבוע מתחתיו מציין **בהמתנה להרצה מתוזמנת**: מועד ההתעוררות הבא אושר. צבע ההדגשה נקבע לפי ערכת הצבעים. סמל הדגשה לבדו מציין הכנה או מטלה שטרם התחילה. השלמות שנקראו, תזמונים שנעצרו ו־**מצב לא מאומת** מוצגים בצבע ניטרלי; קראו את טקסט המצב. -בחירה, לחיצה/החלקה על סמלי מטלות ירוקים או סימון כנקרא מתפריט החץ מאשרים תוצאות. מכשול אינו תמיד שאלה; דוח אינו מוכיח שכל פעולה מקורית הסתיימה. מטלות שנמשכו נשמרות בהיסטוריה. +בחירה או לחיצה/החלקה על סמלי מטלות ירוקים מאשרות תוצאות; תפריט החץ מציע **סמן כנקרא**. עבור **הרצה שהצליחה וממתינה לעיון**, בחירה מפורשת בשורה החוזרת בחלון הפעיל או **סמן כנקרא** מאשרות את ההרצה המסוימת. הסמל חוזר להמתנה כשהתזמון פעיל, ואחרת לצבע ניטרלי. בחירה ששוחזרה ותוצאות חדשות בשורה שכבר נבחרה משאירות את התוצאה החדשה לעיון. הצלחות היסטוריות בטעינה הראשונה נחשבות כנקראו. מטלות שנמשכו נשמרות בהיסטוריה. ### שאלות והחלטות {#questions} diff --git a/docs/help/he/mobile.md b/docs/help/he/mobile.md index e29a2203a6..acc5bc54ab 100644 --- a/docs/help/he/mobile.md +++ b/docs/help/he/mobile.md @@ -42,3 +42,5 @@ | עבודה לא מקוונת | אין שרת קצה לא מקוון או היסטוריית API במטמון. נכסי ממשק סטטיים עשויים להישמר במטמון, אך מסמכים ותשובות API אינם סביבת עבודה לא מקוונת. | שמרו על נגישות שרת הקצה. השהיה בידי מערכת ההפעלה הניידת או החלפת רשת עשויות לנתק את זרם האירועים; החזרה מחברת מחדש וקוראת את המצב הנוכחי, ללא הבטחת שחזור אירועים. בדקו אם פעולה הושלמה לפני ניסיון חוזר. סגירת PWA אינה עוצרת שרת קצה עצמאי; יציאה מיישום שולחן העבודה במארח ומשרת הקצה שלו הופכת את השליטה מרחוק ללא זמינה עד ההפעלה הבאה. + +כל לשונית דפדפן, כולל ה-PWA המותקנת, שומרת עבור אותה לשונית את הפרויקטים הפתוחים, השיחות שנבחרו, הטיוטות שלא נשלחו ומיקומי הגלילה: הם חוזרים כשהדף נטען מחדש, או כשמערכת ההפעלה בנייד טוענת אותו מחדש אחרי מעבר בין יישומים או נעילת מסך. לשונית חדשה, או PWA שמערכת ההפעלה סגרה לגמרי, נפתחת בדף הבית. כבו זאת עבור הלשונית ב־**הגדרות → כללי → שחזור המצב הקודם**. diff --git a/docs/help/he/opencode.md b/docs/help/he/opencode.md index abde6dbfec..58b2faf4d0 100644 --- a/docs/help/he/opencode.md +++ b/docs/help/he/opencode.md @@ -19,8 +19,8 @@ CodeNomad מתחבר לשירות OpenCode משותף במארח ההרצה. ב | סיווג | דרישה נוכחית | משמעות | | --- | --- | --- | -| מינימום | OpenCode **2.2.3** | כלי יצירת התמונות שמשמש את הגדרות **תמונות** ואת הרחבת Design, לצד סדר ביצוע תקין של משימות JavaScript ב־Code Mode ופורמט ההפעלה החוזרת והדחיסה המקורי; שיחות שנשמרו בגרסאות קודמות נשארות קריאות לאחר העדכון. | -| מומלצת | OpenCode **2.2.7** | יעד שנבדק, בנפרד מהמינימום הטכני. | +| מינימום | OpenCode **2.3.0** | כלי יצירת התמונות שמשמש את הגדרות **תמונות** ואת הרחבת Design, לצד סדר ביצוע תקין של משימות JavaScript ב־Code Mode ופורמט ההפעלה החוזרת והדחיסה המקורי; שיחות שנשמרו בגרסאות קודמות נשארות קריאות לאחר העדכון. היא גם מעבירה את תוצאות סוכני־המשנה כדוחות ברקע, שאותם קוראים כרטיסי סוכני־המשנה והמשימות. | +| מומלצת | OpenCode **2.3.0** | יעד שנבדק; כרגע אותה גרסה כמו המינימום. | | לא מאומתת | גרסה חדשה או מותאמת שלא אומתה במלואה | אינה נדחית רק מפני שלא נבדקה; חוזי ה־API בפועל של השירות המחובר נבדקים. | השירות המחובר חייב לחשוף את החוזים הנדרשים לסשנים, אישורים, טפסים, תיבת קלט וסביבת סשן. תזמון משימות מקורי בודק גם את ממשקי ה־API של התזמון, חבילת התוסף/הספק ואת הגדרת `experimental.schedules` שבתוקף. הזמינות נקבעת לפי היכולות הנצרכות האלה, גם בגרסאות עתידיות תואמות. אם ההגדרה מדווחת על שירות פועל לא נתמך, בחרו/התקינו CLI נתמך והשתמשו בהפעלה מחדש מפורשת של השירות המשותף כשתהיו מוכנים. diff --git a/docs/help/he/projects.md b/docs/help/he/projects.md index e7e31fa39f..3b71f693be 100644 --- a/docs/help/he/projects.md +++ b/docs/help/he/projects.md @@ -34,7 +34,7 @@ | סגור לשונית | מסירה את חיבור הפרויקט של CodeNomad באותה לשונית; לשונית אחרת שנפתחה בנפרד על אותה תיקייה אינה מושפעת | אינה מוחקת קובצי פרויקט או היסטוריה מקורית, אינה עוצרת סשנים ואינה פורקת את ה־Location של OpenCode | | עצירת סשן | הרצת השיחה הנבחרת | אינה סוגרת את הפרויקט או מוחקת את ההיסטוריה שלו | -אם חלון אחר מציג את אותו חיבור פרויקט, גם הלשונית שלו נסגרת ואותו חלון מציג התראה. החלון שיזם את הסגירה אינו מציג התראה. הסגירה מיידית; אם שרת הקצה אינו יכול לסגור את הפרויקט, מופיעה שגיאה ו־**עבור לפרויקט הפתוח** בדף הבית עדיין מגיע אליו. אין ניסיון חוזר אוטומטי. טיוטות שלא נשלחו מהלשונית שנסגרה אינן נשמרות בשחזור בהפעלה. +אם חלון אחר מציג את אותו חיבור פרויקט, גם הלשונית שלו נסגרת ואותו חלון מציג התראה. החלון שיזם את הסגירה אינו מציג התראה. הסגירה מיידית; אם שרת הקצה אינו יכול לסגור את הפרויקט, מופיעה שגיאה ו־**עבור לפרויקט הפתוח** בדף הבית עדיין מגיע אליו. אין ניסיון חוזר אוטומטי. טיוטות וקבצים מצורפים שלא נשלחו מהלשונית שנסגרה חוזרים כשפותחים מחדש את אותה תיקייה באותו חלון; החלון שומר אותם עבור 16 הפרויקטים שנסגרו בו לאחרונה, עד שהוא נטען מחדש או נסגר. הם אינם חלק מהשחזור בהפעלה. סגירת חלון שלם, יציאה או טעינה מחדש אינן סוגרות את חיבורי הפרויקטים שלו; השחזור הרגיל בהפעלה עדיין חל. עצרו הרצות רלוונטיות במפורש אם עליכם לוודא שההרצה הסתיימה. CodeNomad לעולם אינו פורק Locations מקוריים; תחזוקת השירות המשותף מתוארת ב־[הגדרת OpenCode](opencode.md). @@ -59,7 +59,7 @@ | בחירה | השפעה | התאוששות | | --- | --- | --- | | שמירה | סוגרת את הפרויקט ב־CodeNomad, שומרת את התיקייה והשיחות, מסירה את מעמדה כזמנית ומוסיפה פרויקט אחרון | פתחו מחדש מאחרונים; התיקייה אינה מועברת | -| מחיקה | מוחקת את השיחות והקבצים של סביבת העבודה הזמנית | ללא ביטול; שמרו תחילה כל דבר נחוץ במקום אחר | +| מחיקה | מוחקת את השיחות, הקבצים והטיוטות שלא נשלחו של סביבת העבודה הזמנית | ללא ביטול; שמרו תחילה כל דבר נחוץ במקום אחר | | ביטול | משאיר את סביבת העבודה הזמנית פתוחה | המשיכו לעבוד או החליטו בהמשך | לשונית זמנית שלא נעשה בה דבר, ללא שיחה, קובץ או טיוטה שלא נשלחה, נמחקת בשקט בסגירה. לשוניות זמניות פתוחות משתתפות בשחזור הרגיל בהפעלה, אך בדף הבית אין רשימה נפרדת לחידוש תיקיות זמניות שנסגרו. diff --git a/docs/help/he/providers.md b/docs/help/he/providers.md index a84ef3e0fb..073b4d0413 100644 --- a/docs/help/he/providers.md +++ b/docs/help/he/providers.md @@ -56,15 +56,15 @@ לפי [השאלות הנפוצות של Antigravity](https://antigravity.google/docs/faq/) מטעם Google, שימוש בתוכנת צד שלישי עם התחברות Antigravity מפר את תנאי השימוש ועלול להוביל להשעיית החשבון או לסגירתו. -עבור מודלים בתשלום באינטגרציה `opencode`, **OpenCode Console** מציג **בקשות** עבור **היום (UTC)**, **7 ימים (UTC)** ו־**30 ימים (UTC)**. אלה חלונות של ימים קלנדריים לפי UTC, כולל היום, שמתחילים ב־00:00 UTC היום, לפני שישה ימים ולפני 29 ימים בהתאמה. **בקשות לפי מודל · 30 ימים** מפרט כל מודל ואת הספק שלו. המונים מתייחסים לחשבון Console המחובר ומעוצבים לפי שפת האפליקציה. **תקציבי חשבונות שירות** מציג **התקציבים אינם זמינים.** OpenCode Go משתמש בקורא מכסה משלו. +עבור מודלים בתשלום באינטגרציה `opencode`, **OpenCode Console** מציג **בקשות** עבור **24 שעות**, **7 ימים** ו־**30 ימים**, כפי ש־Console מדווח. **בקשות לפי מודל · 30 ימים** מפרט כל מודל ואת הספק שלו. המונים מתייחסים לחשבון Console המחובר ומעוצבים לפי שפת האפליקציה. **תקציבי חשבונות שירות** מציג **התקציבים אינם זמינים.** כש־**יתרת קרדיטים של הספק** מופעלת, יתרת הקרדיטים של Console מוצגת כ־**זיכויים**. OpenCode Go משתמש בקורא מכסה משלו. הקורא משתמש במפתח ה־API השמור של `opencode`, עם עדיפות לחיבור OAuth של Console. OAuth דורש את `https://opencode.ai/console` ואת מזהה הארגון של החיבור; גישה ל־Console דורשת הרשאת **Usage › Read**. CodeNomad לעולם אינו מרענן את פרטי הגישה האלה. יש לתקן חיבור OAuth לא תקף או שפג תוקפו דרך הגורם שמנהל אותו, גם אם נשמר מפתח API נוסף. שגיאות Console מבחינות בין חיבור חסר, פרטי גישה לא תקפים או שפג תוקפם (401), גישה שנדחתה (403), תגובת שימוש לא תקינה וכשל רשת. בשגיאות חיבור, פתחו **הגדרות → ספקים**, בדקו את ההתחברות וההרשאות ואז רעננו את **שימוש**. כשל בסיכום או בדף מודלים הופך את כל קריאת Console ללא זמינה. -עבור מודלי OpenCode חינמיים (`big-pickle` ומזהים שמסתיימים ב־`-free`), **שימוש** סוכם רק בקשות חינמיות בחשבון Console המחובר מאז 00:00 UTC, מול ערך ייחוס יומי של **800**. **משוער** מתייחס למכסה ולאיפוס בחצות UTC הבא; המגבלות בפועל עשויות להשתנות. המונה כולל לקוחות נוספים של החשבון. ללא חיבור Console, הלוח מזמין להתחבר למודלים חינמיים ולמעקב אחר מכסות דרך **הגדרות → ספקים**. כשל בקריאת Console משאיר את המונה לא זמין. +עבור מודלי OpenCode חינמיים (`big-pickle` ומזהים שמסתיימים ב־`-free`), **שימוש** מציג פס אחד: הבקשות החינמיות של חשבון Console המחובר ב־24 השעות האחרונות לפי Console, מול ערך ייחוס של **800**; המגבלות בפועל עשויות להשתנות. המונה כולל לקוחות נוספים של החשבון ואין לו מועד איפוס. כש־**יתרת קרדיטים של הספק** מופעלת, יתרת הקרדיטים של Console מוצגת כ־**זיכויים**. ללא חיבור Console, הלוח מבקש לחבר את OpenCode Console דרך **הגדרות → ספקים**. כשל בקריאת Console משאיר את המונה לא זמין. -כשל מכסה בצעד חינמי מסמן את חיבור OpenCode כ־**מוצה** עד 00:00 UTC. כשמונה Console זמין, המחוון מציג 100% תוך שמירה על הספירה. הסימון נשמר בזיכרון השרת לכל חיבור ונמחק בהפעלה מחדש. השימוש החינמי, המיצוי ומוני Console בתשלום משמשים לתצוגה בלבד; בחירת חשבון אוטומטית משתמשת בקוראים ובכללים נפרדים. +השימוש החינמי ומוני Console בתשלום משמשים לתצוגה בלבד; בחירת חשבון אוטומטית משתמשת בקוראים ובכללים נפרדים. OpenAI אינה מספקת נתוני שימוש עבור אחת משיטות ההתחברות של ChatGPT: לוח השימוש מציין זאת במקום להציג חלונות מכסה. בחרו [הצגת השימוש ב-ChatGPT](https://chatgpt.com/settings/usage) כדי לבדוק את השימוש באפליקציות ולנהל את הגישה שלהן למסלול ולקרדיטים שלכם ב-ChatGPT. השיחה עדיין עובדת, וחיבור מחדש של אותה התחברות אינו משחזר את הקריאה. diff --git a/docs/help/he/remote-access.md b/docs/help/he/remote-access.md index 1cab8d58de..2c57e9c895 100644 --- a/docs/help/he/remote-access.md +++ b/docs/help/he/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true אל תניחו יציאה 9898 או 9899: יציאות שלא צוינו יכולות להתחלף כשהן תפוסות. `--https-port` מפורש שאינו אפס, או `--http-port` כש־HTTP מופעל, מקבעים את היציאה ונכשלים אם אי אפשר להאזין בה; `0` מבקש ממערכת ההפעלה להקצות אחת. **Local Connection URL** ו־**Remote Connection URL** המודפסות, ו־**כתובות נגישות** לאחר רענון, הן הסמכות לאותה הרצה. ראו [מדריך CLI המלא לשרת](server.md). +## מדיניות מנהל המערכת {#administrator-policy} + +מנהל מערכת יכול לקבע את כתובת ההאזנה: הגדירו את `CODENOMAD_LOCKED_HOST` ברמת המערכת לכתובת שהשרת חייב להשתמש בה והפעילו מחדש את CodeNomad. היא גוברת על `--host`, `CLI_HOST` ועל **אפשר חיבורים מכתובות IP אחרות**, שמציג את התוצאה אך לא יכול לשנות אותה. השתמשו בכתובת אינטראנט כדי שעמיתים יגיעו לשרת דרך רשת החברה, או ב־`127.0.0.1` כדי לשמור אותו במחשב זה. כדי שכל גישה תישאר ברשת החברה, הגדירו גם `CODENOMAD_REMOTE_CONTROL=disabled` ([שליטה מרחוק](remote-control.md#administrator-policy)). + ## שדרוג {#upgrading} התחברו מחדש לאחר השדרוג. עבור כינוי לשם מארח, מתווך הפוך או ממשק שמתארח בנפרד, הגדירו בשרת הקצה את `CODENOMAD_ALLOWED_ORIGINS` למקורות המהימנים של הממשק (סכמה, שם מארח ויציאה). לקוחות LAN מקוריים חייבים לספק כותרת `Origin` מותרת בבקשות לשינוי נתונים. מקורות ה-HTTPS שלו מאפשרים גם למארח לצמד מכשירים בלי המנהרה; ראו [צימוד דרך HTTPS ישיר](remote-control.md#direct-https). -השתמשו בחיבור loopback לפעולות השמורות למארח: תוכן SideCar ‏(`/sidecars/`) ו־WebSockets, ניהול שליטה מרחוק (`/api/remote-control/`), גשר התוספים (`/api/opencode-plugin/`), מתווכים מרוחקים (`/api/remote-proxy/`), ניהול שרתים שמורים (`/api/remote-servers/`), שינוי סיסמה ואתחול באמצעות אסימון. פעולות אלה דורשות loopback גם לאחר התחברות מאומתת בגישה ישירה דרך LAN. תוכן תצוגות מקדימות פעילות (`/previews/`) זמין בגישת LAN ישירה עם אסימון יכולת תקף. +השתמשו בחיבור loopback לפעולות השמורות למארח: תוכן SideCar ‏(`/sidecars/`) ו־WebSockets, ניהול שליטה מרחוק (`/api/remote-control/`), גשר התוספים (`/api/opencode-plugin/`), מתווכים מרוחקים (`/api/remote-proxy/`), ניהול שרתים שמורים (`/api/remote-servers/`), שינוי סיסמה ואתחול באמצעות אסימון. פעולות אלה דורשות loopback גם לאחר התחברות מאומתת בגישה ישירה דרך LAN. רק ל־SideCars יש חריגה: ההגדרה **פתיחת SideCars דרך HTTPS** במארח פותחת את התוכן ואת חיבורי ה־WebSocket שלהם לדפדפנים שמחוברים דרך מקור HTTPS מהימן ([SideCars](browser-sidecars.md#register-sidecar)). תוכן תצוגות מקדימות פעילות (`/previews/`) זמין בגישת LAN ישירה עם אסימון יכולת תקף. ממשקי הרישום `/api/sidecars` נשארים זמינים ללקוחות LAN ישירים מאומתים ולמכשירים מצומדים. תצוגות האינטרנט של שליטה מרחוק נשארות זמינות עם אסימון היכולת שלהן כל עוד הן מופעלות במארח. diff --git a/docs/help/he/remote-control.md b/docs/help/he/remote-control.md index 58f2ae5234..4c3d3136c8 100644 --- a/docs/help/he/remote-control.md +++ b/docs/help/he/remote-control.md @@ -86,3 +86,7 @@ CodeNomad משתמש ב־[OpenTunnel](https://github.com/anomalyco/opentunnel) TLS מסתיים בשרת הקצה של CodeNomad. הממסר מעביר טקסט מוצפן ואינו יכול לקרוא תוכן יישום, אך יכול לראות שמות מארחים, זמני חיבור ונפחי תעבורה. תעודת המנהרה/המפתח הפרטי נשארים במארח. הגנו על אחסון המנהרה של המארח ועל תצורת CodeNomad כאישורי גישה; כתובת שאי אפשר לנחש אינה הרשאה. `CODENOMAD_REMOTE_CONTROL_API` בוחר API של OpenTunnel באירוח עצמי; כשהוא אינו מוגדר משתמשים בשירות המתארח. הדבר משנה את פריסת המנהרה, לא את דרישות הצימוד או הממשקים החסומים. ראו [אבטחה](security.md) לטיפול באישורים ובאבחון. + +## מדיניות מנהל המערכת {#administrator-policy} + +מנהל מערכת יכול לכבות את השליטה מרחוק לכל המשתמשים במחשב: הגדירו את משתנה הסביבה `CODENOMAD_REMOTE_CONTROL=disabled` ברמת המערכת והפעילו מחדש את CodeNomad. השרת לא יחבר מנהרה לעולם, ידחה את **הפעל שליטה מרחוק** ואת קישורי הצימוד ולא יתחבר מחדש בהפעלה; ההגדרות מציגות **הושבת על ידי מנהל המערכת**. מכשירים שצומדו קודם לא יכולים להתחבר ונשארים ברשימה כדי שתוכלו לבטל אותם. ללא הגדרה או ערך ריק אין מדיניות; כל ערך אחר, כולל רווחים בלבד, מונע את הפעלת השרת. diff --git a/docs/help/he/security.md b/docs/help/he/security.md index 224b731b58..bd2b9f5d96 100644 --- a/docs/help/he/security.md +++ b/docs/help/he/security.md @@ -33,7 +33,7 @@ התנתקות מבטלת את הסשן הישיר הנוכחי. שינוי סיסמה מוצלח במארח מבטל את כל הסשנים הישירים של המשתמש, כולל הסשן הנוכחי; התחברו מחדש. סשנים פגים לאחר 24 שעות ללא בקשה מאומתת או שבעה ימים מיצירתם. התאימו את הגבולות באמצעות `CODENOMAD_SESSION_IDLE_SECONDS` ו־`CODENOMAD_SESSION_ABSOLUTE_SECONDS` בשניות שלמות וחיוביות לפני הפעלת שרת הקצה. מכשירי שליטה מרחוק מבוטלים בנפרד. -לקוחות LAN יכולים להתחבר, להתנתק ולהשתמש בפרויקטים. שינוי סיסמה, ניהול שליטה מרחוק, כלי שרתים מרוחקים ו־proxy ו־SideCars מנוהלים במארח דרך loopback. שינויי דפדפן דורשים Origin מורשה, או Referer בהיעדרו. מקורות השרת המפורסמים מורשים; לכינויי DNS, שרתי proxy הפוכים או ממשק המאוחסן בנפרד, הגדירו `CODENOMAD_ALLOWED_ORIGINS` כמקורות HTTP(S) מדויקים המופרדים בפסיקים, למשל `https://code.example.test,https://ui.example.test:8443`, והפעילו מחדש. אין להשתמש בנתיבים או בתווים כלליים. ההרשאה מעניקה גישת דפדפן, לא הרשאות מארח. גם לקוחות מקוריים צריכים לשלוח Origin מורשה לשינויי LAN. ל־proxy מהימן המתחבר דרך loopback יש הרשאות מארח והוא זקוק לבקרת גישה משלו. כשהשרת מאזין ב־loopback או בכל הממשקים, הממשק פועל גם כשהוא נפתח במחשב המארח כ־`localhost`, עם אותה סכמה ואותה יציאה. +לקוחות LAN יכולים להתחבר, להתנתק ולהשתמש בפרויקטים. שינוי סיסמה, ניהול שליטה מרחוק, כלי שרתים מרוחקים ו־proxy ו־SideCars מנוהלים במארח דרך loopback. ההגדרה **פתיחת SideCars דרך HTTPS** במארח פותחת את ה־SideCars לדפדפנים שמחוברים דרך מקור HTTPS מהימן; הפעילו אותה רק אם כל המשתמשים בכתובות אלה רשאים להשתמש בשירותי ה־SideCar שלכם. שינויי דפדפן דורשים Origin מורשה, או Referer בהיעדרו. מקורות השרת המפורסמים מורשים; לכינויי DNS, שרתי proxy הפוכים או ממשק המאוחסן בנפרד, הגדירו `CODENOMAD_ALLOWED_ORIGINS` כמקורות HTTP(S) מדויקים המופרדים בפסיקים, למשל `https://code.example.test,https://ui.example.test:8443`, והפעילו מחדש. אין להשתמש בנתיבים או בתווים כלליים. ההרשאה מעניקה גישת דפדפן, לא הרשאות מארח. גם לקוחות מקוריים צריכים לשלוח Origin מורשה לשינויי LAN. ל־proxy מהימן המתחבר דרך loopback יש הרשאות מארח והוא זקוק לבקרת גישה משלו. כשהשרת מאזין ב־loopback או בכל הממשקים, הממשק פועל גם כשהוא נפתח במחשב המארח כ־`localhost`, עם אותה סכמה ואותה יציאה. בחשד לפריצה: diff --git a/docs/help/he/server.md b/docs/help/he/server.md index 84e5d9f6a8..0712217b4a 100644 --- a/docs/help/he/server.md +++ b/docs/help/he/server.md @@ -8,7 +8,7 @@ 1. התקינו Node.js 24 LTS ו־npm; סביבת הבנייה של המאגר מקובעת ב־`.node-version`. חבילות שולחן העבודה מספקות סביבת ריצה משלהן: Electron משתמש ב־Node המשולב בו, Tauri כולל Node, ושניהם כוללים npm. 2. הוסיפו Git ל־**PATH של תהליך שרת הקצה**. Git בתוך WSL בלבד אינו מספיק לשרת קצה ב־Windows. -3. התקינו או בחרו OpenCode: המינימום הנדרש הוא **2.2.3**, ו־**2.2.7** היא הגרסה המומלצת לבדיקה. בניות חדשות או מותאמות עוברות בדיקות תאימות, לא רשימת היתר של גרסאות שנבדקו. ראו [הגדרת OpenCode](opencode.md). +3. התקינו או בחרו OpenCode: המינימום הנדרש הוא **2.3.0**, ו־**2.3.0** היא הגרסה המומלצת לבדיקה. בניות חדשות או מותאמות עוברות בדיקות תאימות, לא רשימת היתר של גרסאות שנבדקו. ראו [הגדרת OpenCode](opencode.md). 4. בחרו את התיקייה שממנה תפעילו את השרת, או העבירו `--workspace-root` במפורש. ללא Git, שיחות נשארות זמינות רק בתיקייה הפיזית שנפתחה במפורש; פעולות Git ו־worktree נכשלות. התקינו Git והפעילו מחדש את שרת הקצה לאחר שינוי PATH. שורש סביבת עבודה מגביל פתיחה/עיון, לא הרצת סוכן: ראו [אבטחה](security.md). @@ -104,6 +104,8 @@ HTTPS מעדיף את יציאה **9898** ו־HTTP את **9899**. ללא דרי | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; המאגר שנשאל לגבי הצעות גרסאות. | | `CODENOMAD_REMOTE_CONTROL_API` | לא מוגדר: API של OpenTunnel המתארח בשירות. הגדירו מקור API לפריסת ממסר באירוח עצמי. | +| `CODENOMAD_REMOTE_CONTROL` | לא מוגדר: משתמשים יכולים להפעיל שליטה מרחוק. `disabled`: כובתה על ידי מנהל מערכת ([מדיניות](remote-control.md#administrator-policy)); ללא הגדרה או ריק: אין מדיניות, כל ערך אחר (כולל רווחים) מונע הפעלה. | +| `CODENOMAD_LOCKED_HOST` | לא מוגדר או ריק: `--host` חל; רווחים בלבד מונעים הפעלה. כתובת: השרת מאזין בה, ללא קשר ל־`--host`, ל־`CLI_HOST` או למתג ההאזנה ([מדיניות](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | קובץ CA נוסף אופציונלי של Node; מועבר עם סביבת ההפעלה המותרת כשמפעילים דמון OpenCode חסר. אינו משנה דמון שכבר פועל. | פרטי התחברות לשימוש אצל ספקים מכוסים ב־[ספקים](providers.md). בחירת פרופיל נתונים לשולחן העבודה מכוסה ב־[שולחן עבודה](desktop.md), ואינה נשלטת בידי ערוץ העדכונים. diff --git a/docs/help/he/settings.md b/docs/help/he/settings.md index 298efcfc60..4a11c6f15b 100644 --- a/docs/help/he/settings.md +++ b/docs/help/he/settings.md @@ -70,7 +70,7 @@ 2. פתחו **התאמת הלוח הימני** בלוח הימני. השתמשו בתיבות סימון לבחירת לשוניות מובנות וסעיפי סטטוס; לפחות סעיף סטטוס אחד נשאר גלוי. גררו מעל תיבות הסימון האלה כדי לקבוע כמה מהן בבת אחת. 3. גררו לשוניות בלוח הימני לסידורן מחדש. השתמשו ב־**איפוס** לשחזור בחירות הפריסה המובנות. -גם ל[אינטגרציות](integrations.md#integration-sections) מזוהות יש מקטעי סטטוס. הסתירו אותם באותן תיבות סימון; סדרו כל מקטע סטטוס בגרירה או במקשי מעלה/מטה. הנראות והסדר נשמרים בטעינה מחדש ובהיעדר זמני של אינטגרציה. +סדרו כל מקטע סטטוס בגרירה או במקשי מעלה/מטה. הנראות והסדר נשמרים בטעינה מחדש. הסטטוס כולל פרטי טוקנים, מצב Yolo, שימוש אצל ספקים, מעטפות רקע, MCP ותוספים. כל עוד לשיחה יש [יעד](conversations.md#goal), שורת יעד מעל הסעיפים האלה מציגה אותו; שורה זו אינה סעיף ואי אפשר להסתיר או להזיז אותה. הסתרת סעיף אינה משביתה את השירות שלו או מבטלת הרשאות. פריסות צרות סוגרות לוחות שכבר אינם נכנסים במקום לדחוק את השיחה; לוח שנפתח בהן צף מעליה, ופתיחת לוח צף אחד סוגרת את האחר. diff --git a/docs/help/he/troubleshooting.md b/docs/help/he/troubleshooting.md index ece36b005e..8a7347b0f9 100644 --- a/docs/help/he/troubleshooting.md +++ b/docs/help/he/troubleshooting.md @@ -42,7 +42,7 @@ Electron משתמש ב־Chromium ומהווה חלופה באותו מארח. א ## סביבת ריצה של OpenCode ו־WSL {#opencode-runtime} 1. פתחו **העדפות → OpenCode** ובדקו את הכרטיס **גרסת OpenCode** (הגרסה המותקנת ומצב השירות הפועל), ואז את קובץ ההרצה שנבחר תחת **קובץ בינארי של OpenCode**. -2. השתמשו בפעולת ההתקנה/העדכון הנתמכת כשסביבת הריצה הנדרשת חסרה. מינימום נוכחי: **2.2.3**; גרסה מומלצת/שנבדקה: **2.2.7**. +2. השתמשו בפעולת ההתקנה/העדכון הנתמכת כשסביבת הריצה הנדרשת חסרה. מינימום נוכחי: **2.3.0**; גרסה מומלצת/שנבדקה: **2.3.0**. 3. אם ה־CLI המותקן שונה מהשירות הפועל, החליטו במפורש אם להפעיל מחדש את השירות המשותף. **הפעל מחדש את שירות OpenCode** זמין תחת **פתרון בעיות** ודורש אישור. הוא קוטע עבודה פעילה בכל הלקוחות המחוברים, אך משמר היסטוריית סשנים. טעינת תצורה מחדש היא פעולה נפרדת: היא משמרת את התהליך אך בונה מחדש Locations טעונים ומבטלת שאלות/אישורים ממתינים. אף אחת אינה רענון תמים. diff --git a/docs/help/ja/browser-sidecars.md b/docs/help/ja/browser-sidecars.md index 63d8c147a0..1674ed63dd 100644 --- a/docs/help/ja/browser-sidecars.md +++ b/docs/help/ja/browser-sidecars.md @@ -77,7 +77,7 @@ Electron と Windows Tauri では、モバイルテンプレートは、所有 SideCar はサンドボックス化されたプレビューではなく、CodeNomad の信頼された拡張です。そのページは CodeNomad 自身のオリジンで動作するため、スクリプトはサインイン済みのアクセス権で CodeNomad を利用できます。コードを信頼できるサービスだけを登録してください。CodeNomad は自身のサインイン Cookie をサービスへ転送しませんが、サービス自身の Cookie は保持されます。 -SideCar のコンテンツ(`/sidecars/`)と WebSocket には、ホスト上のループバック接続が必要です。`/api/sidecars` による登録は、ペアリング済み端末と認証済みの LAN 直接接続クライアントで利用できます。有効なケイパビリティトークンがあれば、アクティブなプレビューのコンテンツ(`/previews/`)は LAN からの直接アクセスで利用できます。[リモートコントロール](remote-control.md#remote-surface)の Web プレビューは、有効な間、ケイパビリティトークンで利用できます。直接アクセスの要件は[アップグレード](remote-access.md#upgrading)を参照してください。 +SideCar のコンテンツ(`/sidecars/`)と WebSocket には、ホスト上のループバック接続が必要です。他の端末からも開くには、ホストで **設定 → SideCar** の **HTTPS で SideCar を開く** をオンにします。このサーバーの HTTPS アドレス、または TLS リバースプロキシなど `CODENOMAD_ALLOWED_ORIGINS` の HTTPS オリジンからサインインしたブラウザーが SideCar を開けるようになります。通常の HTTP、`localhost` のアドレス、リモートコントロールはホスト専用のままです。`/api/sidecars` による登録は、ペアリング済み端末と認証済みの LAN 直接接続クライアントで利用できます。有効なケイパビリティトークンがあれば、アクティブなプレビューのコンテンツ(`/previews/`)は LAN からの直接アクセスで利用できます。[リモートコントロール](remote-control.md#remote-surface)の Web プレビューは、有効な間、ケイパビリティトークンで利用できます。直接アクセスの要件は[アップグレード](remote-access.md#upgrading)を参照してください。 ## OpenVSCode Server の例 {#openvscode} diff --git a/docs/help/ja/conversations.md b/docs/help/ja/conversations.md index e36d424760..49e0a5de29 100644 --- a/docs/help/ja/conversations.md +++ b/docs/help/ja/conversations.md @@ -60,6 +60,12 @@ CodeNomad は、OpenCode ネイティブのセッションを会話として表 下書きはクライアント側の作業状態であり、共有ネイティブメッセージではありません。起動時の復元で、対応する入力状態を保持できる場合はありますが、未送信の下書きや添付をバックアップと考えたり、別の端末にも表示されると想定したりしないでください。起動データを消去する前や、復元ポリシーが無効なクライアントを閉じる前に、重要なテキストを保存してください。[デスクトップ](desktop.md)を参照してください。 +## 返信からファイルを開く {#open-files-from-replies} + +1. エージェントの返信は、相対パスと絶対パスでプロジェクトファイルにリンクします。 +2. 通常クリックで、リンクされたファイルを会話のワークツリーから読み取り、ファイルのプレビューで開きます。 +3. 修飾キー付きクリック(Ctrl/⌘、Shift、中クリック)と、セッションのワークツリー外へのリンクは通常のリンク動作のままです。 + ## コマンドとシェルモード {#commands-shell} 1. `/` を入力して検出されたカスタムコマンドを選び、引数を指定します。 diff --git a/docs/help/ja/install.md b/docs/help/ja/install.md index 3f63b3052e..b5f0a8a2dc 100644 --- a/docs/help/ja/install.md +++ b/docs/help/ja/install.md @@ -45,7 +45,7 @@ Electron の Debian インストールでは Chromium のサンドボックス | 要件 | 必要な場所 | 現在の要件 | | --- | --- | --- | -| OpenCode CLI | 該当する場合は選択した WSL ディストリビューションを含む、選択した実行ホスト | 最低 **2.2.3**。推奨/検証済みの対象は **2.2.7**。新しいバージョンやカスタム版は、未テストという理由で禁止せず、契約を検証します。 | +| OpenCode CLI | 該当する場合は選択した WSL ディストリビューションを含む、選択した実行ホスト | 最低 **2.3.0**。推奨/検証済みの対象は **2.3.0**。新しいバージョンやカスタム版は、未テストという理由で禁止せず、契約を検証します。 | | Git | CodeNomad バックエンドのアカウントの `PATH` | リポジトリの識別、Git 操作、ワークツリーに必要です。 | | Node.js/npm | スタンドアロンサーバーおよびソースビルドのホスト | Node.js 24 LTS。再現可能なソースビルドは `.node-version` に固定されたバージョンを使用します。デスクトップリリースは独自のものを含みます(Electron 内蔵の Node または Tauri 同梱の Node、いずれも npm 付き)。 | | ワークスペースフォルダー | バックエンドからアクセスできるディスク | 明示的に開いた物理フォルダー。リモートブラウザーから推測した端末ローカルのフォルダーではありません。 | diff --git a/docs/help/ja/integrations.md b/docs/help/ja/integrations.md index 744197bf92..36d9429770 100644 --- a/docs/help/ja/integrations.md +++ b/docs/help/ja/integrations.md @@ -27,7 +27,7 @@ CodeNomad は、OpenCode ネイティブの MCP 接続、プラグイン有効 CodeNomad が管理するプラグインは、通常のプラグイン一覧やその有効化・更新・削除操作の対象外です。CodeNomad は検証済みのインストーラーエントリと、内容のハッシュで識別されるコードの保存先から判別します。同じ名前や ID を持つサードパーティ製プラグインには、通常の操作が表示されます。 -管理対象プラグインが無効、読み込み失敗、または読み込み未確認の場合、一覧の上に **CodeNomad プラグインの確認が必要です** と表示されます。**i** ボタン(プラグインの「**詳細**」)を開くと、取得できたエラーと OpenCode ログの参照情報を確認できます。無効なプラグインにのみ **再度有効化** が表示されます。この操作は無効化ルールを残したまま、完全一致の ID を指定した有効化ルールを追加します。無効化ルールの **グローバル** または **プロジェクト** 範囲に書き込める場合はその範囲を、書き込めない場合は **プロジェクト** を使います。OpenCode は稼働したままです。ネイティブイベントまたは **プラグインコントロールを更新** により有効な状態が確認されるまで、警告は残ります。 +管理対象プラグインが無効、読み込み失敗、または読み込み未確認の場合、一覧の上に **CodeNomad プラグインの確認が必要です** と表示されます。**i** ボタン(プラグインの「**詳細**」)を開くと、取得できたエラーと OpenCode ログの参照情報を確認できます。無効なプラグインにのみ **再度有効化** が表示されます。この操作は、それだけで再び有効になる場合はそのファイルから完全一致の無効化ルールを削除し、そうでない場合は完全一致の ID を指定した有効化ルールを追加します。無効化ルールの **グローバル** または **プロジェクト** 範囲に書き込める場合はその範囲を、書き込めない場合は **プロジェクト** を使います。OpenCode は稼働したままです。ネイティブイベントまたは **プラグインコントロールを更新** により有効な状態が確認されるまで、警告は残ります。 警告と詳細には、設定の出所に応じて **継承 / 外部** または **仮想設定** と表示されます。再度有効化する書き込み先が無効化ルールの出所と異なる場合は、別の **プロジェクト** ラベルで書き込み先を示します。 @@ -38,7 +38,7 @@ CodeNomad が管理するプラグインは、通常のプラグイン一覧や グローバルは、接続先デーモンが検出したグローバル設定を対象とします。プロジェクトは、継承した上位ファイルではなく、アクティブな Location 内の設定を対象とします。後のプロジェクトルールはグローバルを上書きできますが、グローバルのスイッチは、最終的なプロジェクト状態を装わず、グローバルのルールを表示します。プロジェクトルールがなければ、解決済みのグローバル状態を継承します。 -これらのスイッチは、ソース宣言と無関係な設定を保持しつつ、正確な有効化ルールを追記します。プラグインのオプション編集、パッケージのインストール、ファイル削除はしません。OpenCode 組み込みプラグインには、ユーザー用の有効化スイッチを提供しません。対象をグローバルから安全に分離できない、またはアクティブな Location の外に出る場合、プロジェクトは無効になります。 +各スイッチは、その範囲のファイルにプラグインの正確な有効化ルールを 1 つ書き込み、そのファイル内の同じプラグインの以前の正確なルールを置き換えます。同じ結果になる場合は削除だけを行います。ソース宣言、`*` などの広いルール、無関係な設定は保持されます。プラグインのオプション編集、パッケージのインストール、ファイル削除はしません。OpenCode 組み込みプラグインには、ユーザー用の有効化スイッチを提供しません。対象をグローバルから安全に分離できない、またはアクティブな Location の外に出る場合、プロジェクトは無効になります。 パッケージの更新は、ツールチップに記載のとおり、OpenCode の共有キャッシュ内のそのパッケージを、それを使う全 Location について変更します。有効化ルールの変更、OpenCode の再起動、設定の再読み込みは行いません。ローカル、組み込み、SDK 提供のプラグインにはパッケージ操作がありません。プラグイン ID を報告する前に失敗したパッケージは、パッケージ名で一覧に表示され、ツールチップに失敗内容があり、更新確認/更新の操作はありますが、有効化スイッチはありません。更新確認や更新の失敗は報告され、自動的に再試行されることはありません。 @@ -78,38 +78,30 @@ CodeNomad が管理するプラグインは、通常のプラグイン一覧や コマンドはアクティブな Location の OpenCode から検出します。実行動作は、それぞれのネイティブ定義で選べます。メニューはパッケージインストーラーでも無制限の設定エディターでもありません。CodeNomad は、ネイティブのカスタムコマンド送信前にプロファイルのセッション環境を適用します。環境更新に失敗すると送信をブロックします。`/btw` は CodeNomad 独自の一時的な質問フローであり、通常のカスタムコマンドではありません。 コマンド定義とネイティブ設定の継承は、[OpenCode コマンドドキュメント](https://opencode.ai/v2/docs/commands/)を参照してください。設定変更後は、まず関連画面を更新/開き直します。ランタイムがまだ必要とする場合にのみ、明示的な設定再読み込みを使用してください。表示更新のためだけに、受け付け済みかもしれないコマンドを再実行しないでください。 -## ステータスの連携セクション {#integration-sections} +## プラグイン内の連携 {#integration-rows} **ステータス → プラグイン** の **+** から **連携を追加…** または **プラグインを追加…** を選びます。連携の選択画面にはレビュー済みカタログの未インストール項目が表示されます。スコープと **インストール** を選ぶと、CodeNomad が選択したカタログ ID をインストールします。ネイティブ連携は **グローバルのみ** です。**カタログを利用できません** では **更新** を選べます。**{date} のカタログ** は、最後の有効なカタログが古い状態であることを示します。 -宣言があるか、プラグインが読み込み済みまたは失敗している認識済み連携には、無効化中やインストール中も独自の **ステータス** セクションがあります。曖昧なソースはプラグインに **不適合** と表示されます。各連携は更新・削除・状態更新を行えるプラグイン行も保持します。セクションを展開すると、本文にバージョンとプラグイン操作が表示されます。名前と状態はヘッダーの **ドキュメント** と **i** の横に常に表示されます。**i** ポップオーバーで必要な詳細を確認できます。Enter/Space で開き、Escape で閉じます。 +認識された連携は **ステータス → プラグイン** に 1 行だけ表示され、名前(例: **OpenCode for Blender**)とバージョンが示されます。その **グローバル** と **プロジェクト** のスイッチは他のスイッチと同じアクセントカラーで、通常のプラグインのスイッチは緑です。アプリ内にパーツを持つ連携は **グローバルのみ** です。名前にポインターを合わせると、詳細が **プラグイン** ではなく **連携** で始まります。スクリーンリーダーはこれを行の説明として読み上げます。曖昧なソースには **不適合** が表示されます。 -ステータスのカスタマイズで、すべてのセクションを非表示にしたり、ドラッグまたは上下キーで並べ替えたりできます。表示設定と順序は再読み込みや連携の一時的な不在後も保持されます。フォーカス中のセクションが消えると、フォーカスはプラグインに戻り、プラグインが非表示の場合は別の表示中のステータスセクションに移ります。 +名前の下の状態行が、連携の現状を常に示します。灰色の文字は情報、アクセントカラーの文字はボタンです。アプリ内にパーツを持つ連携では、最も重要な状態が表示されます。パーツがない、または古いときは **Blender にインストール** または **Blender を更新**(インストールの確認付き)、互換性がないときは警告色、表示中の会話が接続されているときはチェーンのアイコンと文書(選ぶと接続を解除)、**Blender は閉じています**、**Blender: 開いている文書はありません**、**表示中の会話はありません**、そして文書名付きの **接続**、複数の文書から選ぶ **接続…** です。会話は、そのエージェントが初めて連携を使うときにも自動で接続されます。エディター MCP 連携は **サーバーを検出** または **サーバーが見つかりません**、API 連携は **接続済み** または **切断** を表示します。長い状態は省略されます。ポインターを合わせると全文が表示されます。連携から通知された変更と再接続で行が更新されます。 -カタログからのインストール、アプリ部分のインストール・更新、接続、削除には確認が必要です。初期フォーカスは **キャンセル** で、確認操作は 600 ミリ秒後に有効になります。有効化とプラグイン更新は直接実行されます。 +行の **…** メニューは接続状態(例: **Blender: 開いている文書 1 件**、**Blender は閉じています**)から始まります。続いて **ドキュメント**、**アプリにインストール…**、**アプリを更新…** または **アプリに再インストール…**([下記参照](#application-installation))、パッケージの更新確認、**グローバル から削除** または **プロジェクト から削除**、**プラグインコントロールを更新** が並びます。接続の解除は確認なしの 1 クリックで、この会話だけに適用されます。アプリは開いたまま、パーツはインストールされたままで、他の会話の接続も保たれます。応答が失われた場合、行は状態を読み直し、要求は繰り返されません。 -## 開いているアプリを接続 {#application-attachment} +カタログからのインストール、アプリ側パーツのインストール/更新、削除には確認が必要です。最初に **キャンセル** にフォーカスがあり、確認操作は 600 ms 後に有効になります。有効化、プラグインの更新、接続と接続の解除はすぐに実行されます。 -アプリの連携機能でドキュメントを公開し、**ステータス → 対象の連携 → 会話** で **接続…** を選びます。このセクションが表示中の会話の接続を操作します。アプリとドキュメントを選び、接続先の会話と変更の警告を確認して **接続** で確定します。アプリはリモート接続時も OpenCode のマシン上で動作します。WSL などの非対応ホストでは **i** からヘルプを確認できます。 - -**会話** 行は表示中の会話の接続を読み取ります。**接続状態不明** では **更新** を選べます。最新の正式な読み取り結果で接続が確認されると、**切断** が **接続…** に代わって表示されます。1 回のクリックで、追加の確認なしにこの会話だけを切断します。アプリは開いたまま、アプリ部分はインストールされたままで、他の会話の接続も維持されます。ネイティブの変更や再接続時に状態を更新します。 - -開始した操作の結果やエラーは、対象の会話が表示されている間保持され、移動すると操作記録は閉じます。現在の接続は正式な読み取り結果に従います。応答の消失、タイムアウト、通信切断による **状態不明** では、**更新** で実際の状態を読み取ります。表示更新のために要求を再送しないでください。 - -選択画面で開いているアプリを明示的に読み取ると、保存された Q8 メタデータに基づいて、同じ連携と検証済みのドキュメントラベルに対する **再接続** が選択画面または **会話** 行に表示されます。この候補はプロジェクト、会話、接続世代が同じ間有効で、再接続には明示的な確認が必要です。画面移動やデータの無効化で候補は消えます。現在の接続の正式な状態は、連携によるセッション単位の読み取りで取得します。 - -連携セクションからの削除とプラグイン行からの削除は、同じ宣言とスコープの確認を使用します。会話の全件調査や自動切断を行わずに削除します。 +削除では会話の調査や自動的な接続解除は行われません。 削除時はプラグイン名と正確な範囲を示す警告が開きます。初期フォーカスは **キャンセル** です。**グローバル/プロジェクトから削除** は 600 ミリ秒後に有効となり、明示的な操作が必要です。使用中の会話で利用や接続が中断される場合があり、グローバルでは他のプロジェクトにも影響します。送信前のキャンセル、期限切れ、移動では変更されません。削除するのは確認した宣言のみで、ルール、キャッシュ、アプリのファイル、保存済みの接続ヒントは保持します。設定が変わった場合は再選択と確認が必要です。成功は宣言の削除を示し、実行状態は OpenCode の再読み込みに従います。応答を失った場合は、再試行前に更新して設定を確認してください。再インストールで利用可能になる場合がありますが、再読み込みや再接続が必要なことがあり、中断した操作は再開されない場合があります。 ## アプリ連携をインストールまたは更新 {#application-installation} -**ステータス → 対象の連携 → アプリ** で、最新の状態が提供する **アプリにインストール…** または **アプリを更新…** を選びます。会話や公開中のドキュメントがなくても利用できます。アプリが閉じている場合は開いてアプリ部分を確認してください。**i** でマシンや前提条件の詳細を確認できます。 +**ステータス → プラグイン** で、最新の状態が操作を提示しているときは連携の状態行の **Blender にインストール** または **Blender を更新** を選ぶか、その **…** メニューで **アプリにインストール…**、**アプリを更新…** または **アプリに再インストール…** を選びます。再インストールは、アプリが開いていても閉じていてもアプリ側のパーツを書き直します。会話や開いた文書がなくても使えます。 確認画面には、アプリとインストーラーを提供する **連携パッケージのバージョン** が表示されます。両方とマシンの警告を確認してください。インストール先は OpenCode が動作するマシンで、リモートの場合もあります。初期フォーカスは **キャンセル** です。続行するには明示的に確認します。確認前にプロジェクト、Location、会話を切り替えたり、再接続や関連するネイティブの変更が発生したりすると、保留中の承認は取り消されます。操作を開き直し、最新の情報を確認してください。 WSL では、開いているアプリに互換性があるように見えても、アプリへのインストールは常に拒否されます。対応マシンでアプリを開いてください。 -結果は、インストール済み、更新済み、すでに最新、拒否、失敗のいずれかを示します。インストールや更新後はアプリを開き、連携を確認してください。会話の接続は [開いているアプリを接続](#application-attachment) から別途行います。インストール成功はインストール要求の結果を表し、実際のアプリの利用可否はアプリのステータスで確認します。 +結果は、アプリ側のパーツがインストールされた、更新された、すでに最新、拒否された、または失敗したことを示します。インストールまたは更新の後、アプリを開いて連携を確認してください。インストールの成功はインストーラーへの要求を表し、アプリの実際の可用性はその状態によります。 要求が自動で再試行されることはありません。拒否や失敗の後は、新しい操作を選ぶ前にアプリを確認してください。エラーで結果が不明な場合、その要求を繰り返さないでください。まずアプリを調べ、必要に応じて新しい操作を開始し、改めて確認してください。 diff --git a/docs/help/ja/missions.md b/docs/help/ja/missions.md index f7615b551c..8f20bb60b6 100644 --- a/docs/help/ja/missions.md +++ b/docs/help/ja/missions.md @@ -42,7 +42,7 @@ ### 自動的に開始 {#automatic-start} -**自動的に開始** はスケジュールの外にあり、既定でオフです。オフなら一時停止で作成して後で▶から開始します。オンなら作成の確認後、通常の検査と必要なネイティブ設定への同意を経て開始を要求します。 +**自動的に開始** はスケジュールの外にあり、既定でオフです。オフなら一時停止で作成して後で▶から開始します。オンなら作成の確認後、通常の検査とスケジュールの自動準備を経て開始を要求します。 作成の確認が失われた場合、受領記録を読んでも開始は手動です。元の未確認要求を保持し、再作成前に一覧と会話を確認してください。 @@ -56,6 +56,8 @@ 今すぐ1回、N時間ごと、毎日、曜日、毎月の日、cronがあります。保存したタイムゾーンに従い、システムと異なるときにゾーン欄が表示されます。指定日のない月はスキップします。今すぐ1回は開始時の時刻を使う1回の機会で、条件によって実行せず消費することがあります。OpenCodeサービスと実行ホストが必要です。 +開始または再開時に、プロジェクトのOpenCode設定でスケジュールを自動的に準備します。明示的なOFFは保持されます。**スケジュール設定を開く**が表示された場合は対象ファイルを開き、**i**で設定元や環境の詳細を確認できます。押したボタンはリクエスト中のみ読み込みを表示します。結果が未確認の場合は確認操作が表示され、復旧した有効化の後も開始は明示的な操作が必要です。 + ### イベントと組み合わせ {#scheduling-conditions} **リポジトリのアクティビティ → イベント**を選び、同じカード内で必要なフィルターを設定します。Git コミットと、自動検出された GitHub・GitLab・Gitea のイベントが同じメニューに並びます。検出は Contribute と共通で、`upstream`、次に `origin` を使います。3 種とも新規 PR/MR、マージされた PR/MR、新規 Issue に対応し、**作成者(任意)**に `dependabot[bot]` などを指定できます。イベントを選ぶと対象リポジトリが固定され、保存済み条件は対象を保持します。 @@ -88,9 +90,11 @@ ### 色と状態 {#status-colours} -旗はミッション、山形はタスクの要注意状態を示し、繰り返し項目には反復アイコンがあります。赤は回答待ち、脈動する黄は観測した作業、橙は停止/中断、緑は未確認の完了、青は準備または未開始です。 +旗はミッション、山形はタスクの要注意状態を示し、繰り返し項目には反復アイコンがあります。赤は回答待ち、脈動する黄は観測した作業を示します。橙の一時停止記号は一時停止、橙の警告三角形は中断です。緑は確認待ちのミッション、タスク、成功した実行を示します。 + +アクセント色のアイコンの下に小さな静止した中立色の線があると、**スケジュール実行を待機中**で、次の起動時刻が確認済みです。アクセント色はパレットに従います。線のないアクセント色のアイコンは準備済みまたは未開始を示します。確認済みの完了、停止したスケジュール、**状態未確認**は中立色です。状態のテキストも確認してください。 -選択、緑のタスクアイコンのクリック/なぞり、山形メニューの既読操作で確認します。障害は必ずしも人への質問ではなく、レポートは全ネイティブ操作の終了を証明しません。撤回したタスクも履歴に残ります。 +選択、緑のタスクアイコンのクリック/なぞり、山形メニューの**既読にする**で結果を確認します。**成功した実行を確認**では、アクティブなウィンドウで繰り返し行を明示的に選択するか、**既読にする**でその実行を確認します。スケジュールが有効なら待機表示へ、それ以外は中立色へ戻ります。復元された選択や選択済み行に届いた新しい結果は未読のままです。初回読み込み時の過去の成功は既読として扱います。撤回したタスクも履歴に残ります。 ### 質問と判断 {#questions} diff --git a/docs/help/ja/mobile.md b/docs/help/ja/mobile.md index efd7c1d62f..f16a088bcc 100644 --- a/docs/help/ja/mobile.md +++ b/docs/help/ja/mobile.md @@ -42,3 +42,5 @@ | オフライン作業 | オフラインのバックエンドや API 履歴キャッシュはありません。静的 UI 資産はキャッシュされる場合がありますが、文書と API 応答はオフラインのワークスペースではありません。 | バックエンドを到達可能に保ってください。モバイル OS の一時停止やネットワーク切り替えは、イベントストリームを切断する場合があります。戻ると再接続して現在の状態を取得しますが、イベントの再生は保証されません。再試行前に操作が完了したか確認してください。PWA を閉じてもスタンドアロンバックエンドは停止しません。ホストのデスクトップアプリとバックエンドを終了すると、次の起動までリモートコントロールは利用できなくなります。 + +インストールした PWA を含め、各ブラウザータブは、開いているプロジェクト、選択中の会話、未送信の下書き、スクロール位置をそのタブ用に保持します。ページを再読み込みしたときや、アプリの切り替えや画面ロックの後にモバイル OS がページを再読み込みしたときに元に戻ります。新しいタブや、OS が完全に終了した PWA はホーム画面で開きます。このタブで無効にするには **設定 → 一般 → 前回の状態を復元** をオフにします。 diff --git a/docs/help/ja/opencode.md b/docs/help/ja/opencode.md index 956ad1cf38..1b504b0a87 100644 --- a/docs/help/ja/opencode.md +++ b/docs/help/ja/opencode.md @@ -19,8 +19,8 @@ PATH の先頭に古い OpenCode がある場合、提示される操作はそ | 分類 | 現在の要件 | 意味 | | --- | --- | --- | -| 最低 | OpenCode **2.2.3** | **画像** の設定と Design 拡張機能が使う画像生成ツール、Code Mode の JavaScript ジョブの正しい実行順序、ネイティブ再生・圧縮形式。以前のバージョンで保存した会話は、更新後も読み込めます。 | -| 推奨 | OpenCode **2.2.7** | 検証済みの対象。技術的な最低要件とは別です。 | +| 最低 | OpenCode **2.3.0** | **画像** の設定と Design 拡張機能が使う画像生成ツール、Code Mode の JavaScript ジョブの正しい実行順序、ネイティブ再生・圧縮形式。以前のバージョンで保存した会話は、更新後も読み込めます。サブエージェントの結果をバックグラウンドのレポートとして届け、サブエージェントのカードとミッションがそれを読み取ります。 | +| 推奨 | OpenCode **2.3.0** | 検証済みの対象。現在は最低要件と同じバージョンです。 | | 未検証 | 完全には検証していない、新しいまたはカスタムのバージョン | 未テストという理由だけで拒否せず、接続先サービスの実際の API 契約を確認します。 | 接続先サービスは、必要なセッション、権限、フォーム、受信箱、セッション環境の契約を提供する必要があります。ネイティブのミッションスケジュールは、スケジュール API、プラグイン/プロバイダーのバンドル、有効な `experimental.schedules` 設定も確認します。利用可否はこれらの使用する機能で決まり、互換性のある将来のバージョンにも適用されます。セットアップが実行中のサービスを未対応と報告した場合は、対応する CLI を選択/インストールし、準備ができたら明示的に共有サービスを再起動します。 diff --git a/docs/help/ja/projects.md b/docs/help/ja/projects.md index 96e8f4410d..7c7620fdb5 100644 --- a/docs/help/ja/projects.md +++ b/docs/help/ja/projects.md @@ -34,7 +34,7 @@ | タブを閉じる | そのタブの CodeNomad プロジェクト接続を削除します。同じフォルダーを別に開いたタブには影響しません | プロジェクトファイルやネイティブ履歴の削除、セッションの停止、OpenCode の Location の解放はしません | | セッションを停止 | 選択した会話の実行 | プロジェクトを閉じたり、その履歴を削除したりしません | -同じプロジェクト接続を別のウィンドウでも表示している場合は、そちらのタブも閉じ、そのウィンドウに通知が表示されます。操作したウィンドウには表示されません。閉じる操作は直ちに行われます。バックエンドがプロジェクトを閉じられない場合はエラーが表示され、ホームページの **開いているプロジェクトに切り替え** から引き続きアクセスできます。自動的な再試行はありません。閉じたタブの未送信の下書きは、起動時の復元で保持されません。 +同じプロジェクト接続を別のウィンドウでも表示している場合は、そちらのタブも閉じ、そのウィンドウに通知が表示されます。操作したウィンドウには表示されません。閉じる操作は直ちに行われます。バックエンドがプロジェクトを閉じられない場合はエラーが表示され、ホームページの **開いているプロジェクトに切り替え** から引き続きアクセスできます。自動的な再試行はありません。閉じたタブの未送信の下書きと添付ファイルは、同じウィンドウで同じフォルダーを再度開くと戻ります。ウィンドウは最近閉じた 16 個のプロジェクト分を、再読み込みするか閉じるまで保持します。起動時の復元には含まれません。 ウィンドウ全体を閉じる、終了する、再読み込みする操作では、プロジェクト接続は閉じられず、通常の起動時復元が適用されます。実行の終了を確認する必要がある場合は、該当する実行を明示的に停止してください。CodeNomad がネイティブの Location を解放することはありません。共有サービスの保守は、[OpenCode のセットアップ](opencode.md)で説明しています。 @@ -59,7 +59,7 @@ | 選択 | 効果 | 復旧 | | --- | --- | --- | | 保持 | CodeNomad 内でプロジェクトを閉じ、フォルダーと会話を保持し、一時状態を解除して最近のプロジェクトに追加 | 最近使った項目から再度開きます。フォルダーは移動しません | -| 破棄 | 一時ワークスペースの会話とファイルを削除 | 元に戻せません。必要なものは先に別の場所へ保存してください | +| 破棄 | 一時ワークスペースの会話、ファイル、未送信の下書きを削除 | 元に戻せません。必要なものは先に別の場所へ保存してください | | キャンセル | 一時ワークスペースを開いたままにする | 作業を続けるか、後で決めます | 会話、ファイル、未送信の下書きがなく、手を加えていない一時タブは、閉じるときに確認なしで破棄されます。開いている一時タブは通常の起動時復元の対象ですが、ホームページには閉じた一時フォルダーを再開する専用リストはありません。 diff --git a/docs/help/ja/providers.md b/docs/help/ja/providers.md index 90f35b96b9..383a259e31 100644 --- a/docs/help/ja/providers.md +++ b/docs/help/ja/providers.md @@ -56,15 +56,15 @@ OpenCode の Gemini CLI 認証方式を使用する Google 接続では、**使 Google の [Antigravity FAQ](https://antigravity.google/docs/faq/) は、Antigravity のログインでサードパーティ製ソフトウェアを使用すると利用規約に違反し、アカウントの停止または終了につながる可能性があると説明しています。 -`opencode` 連携の有料モデルでは、**OpenCode Console** に **リクエスト数** が **今日(UTC)**、**7日間(UTC)**、**30日間(UTC)** ごとに表示されます。期間は今日を含む UTC の暦日で、それぞれ今日、6日前、29日前の UTC 00:00 から始まります。**モデル別リクエスト数 · 30日間** には各モデルとプロバイダーが表示されます。集計対象は接続中の Console アカウントで、数値はアプリの言語に合わせて表示されます。**サービスアカウントの予算** には **予算を取得できません。** と表示されます。OpenCode Go は専用の使用枠リーダーを使います。 +`opencode` 連携の有料モデルでは、**OpenCode Console** に Console が報告する **24時間**、**7日間**、**30日間** の **リクエスト数** が表示されます。**モデル別リクエスト数 · 30日間** には各モデルとプロバイダーが表示されます。集計対象は接続中の Console アカウントで、数値はアプリの言語に合わせて表示されます。**サービスアカウントの予算** には **予算を取得できません。** と表示されます。**プロバイダーのクレジット残高** を有効にすると、Console のクレジット残高が **クレジット** として表示されます。OpenCode Go は専用の使用枠リーダーを使います。 リーダーは保存済みの `opencode` API キーを使い、Console の OAuth 接続があればそちらを優先します。OAuth には `https://opencode.ai/console` と接続の組織 ID が必要で、Console へのアクセスには **Usage › Read** 権限が必要です。CodeNomad はこの認証情報を更新しません。OAuth 接続が無効または期限切れの場合、API キーも保存されていても、その認証情報を管理する側で接続を修復してください。 Console のエラーは、接続なし、認証情報が無効または期限切れ(401)、アクセス拒否(403)、無効な使用量応答、ネットワーク障害を区別します。接続エラーでは **設定 → プロバイダー** でログインと権限を確認し、**使用量** を更新してください。サマリーまたはモデル一覧の1ページでも取得に失敗すると、Console の集計全体が利用不可になります。 -OpenCode の無料モデル(`big-pickle` と ID が `-free` で終わるモデル)では、**使用量** は接続中の Console アカウントの UTC 00:00 以降の無料リクエストのみを合計し、1 日 **800** 件の基準値と比較します。**推定** は使用枠と次の UTC 午前0時のリセットを指し、実際の上限は異なる場合があります。件数には同じアカウントの他のクライアントも含まれます。Console 未接続時は、無料モデルと使用枠の確認のために **設定 → プロバイダー** で接続するよう案内します。Console の読み取りに失敗した場合、件数は取得不能になります。 +OpenCode の無料モデル(`big-pickle` と ID が `-free` で終わるモデル)では、**使用量** に 1 本のバーが表示されます。接続中の Console アカウントの、Console が報告する直近 24 時間の無料リクエスト数を **800** 件の基準値と比較します。実際の上限は異なる場合があります。件数には同じアカウントの他のクライアントも含まれ、リセット時刻はありません。**プロバイダーのクレジット残高** を有効にすると、Console のクレジット残高が **クレジット** として表示されます。Console 未接続時は、**設定 → プロバイダー** で OpenCode Console を接続するよう案内します。Console の読み取りに失敗した場合、件数は取得不能になります。 -無料ステップで使用枠エラーが発生すると、その OpenCode 接続は UTC 00:00 まで **上限到達** になります。Console の件数を取得できる場合、ゲージは100%になり件数は保持されます。この印は接続ごとにバックエンドのメモリに保存され、再起動で消去されます。無料使用量、上限到達の印、有料 Console カウンターは表示専用です。アカウントの自動選択は別のリーダーとルールを使います。 +無料使用量と有料 Console カウンターは表示専用です。アカウントの自動選択は別のリーダーとルールを使います。 OpenAI は、ChatGPT のサインイン方式の 1 つについて使用量を提供していません。その場合、**使用量** は割り当て量の期間を表示する代わりにその旨を示します。[ChatGPT の使用状況を確認](https://chatgpt.com/settings/usage) を選ぶと、ChatGPT でアプリの使用状況を確認し、プランやクレジットへのアクセスを管理できます。チャットは引き続き利用でき、同じログインで再接続しても測定値は戻りません。 diff --git a/docs/help/ja/remote-access.md b/docs/help/ja/remote-access.md index 7994acad14..a0611e34d5 100644 --- a/docs/help/ja/remote-access.md +++ b/docs/help/ja/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true ポートを 9898 や 9899 と決めつけないでください。省略時は使用中なら別ポートにフォールバックできます。ゼロ以外の `--https-port`、または HTTP 有効時の `--http-port` を明示するとポートを固定し、バインドできなければ失敗します。`0` は OS の割り当てを要求します。その実行での正規の情報は、表示された **Local Connection URL** と **Remote Connection URL**、および更新した **到達可能なアドレス** です。完全な[サーバー CLI リファレンス](server.md)を参照してください。 +## 管理者ポリシー {#administrator-policy} + +管理者は待ち受けアドレスを固定できます。`CODENOMAD_LOCKED_HOST` にサーバーが使うアドレスをシステム全体で設定し、CodeNomad を再起動します。この設定は `--host`、`CLI_HOST`、**他の IP からの接続を許可** より優先され、スイッチは結果を表示しますが変更できません。同僚が社内ネットワーク経由でサーバーに接続できるようにするにはイントラネットのアドレスを、このコンピューターに限定するには `127.0.0.1` を使います。すべてのアクセスを社内ネットワーク内に留めるには、`CODENOMAD_REMOTE_CONTROL=disabled` も設定します ([リモートコントロール](remote-control.md#administrator-policy))。 + ## アップグレード {#upgrading} アップグレード後は再度ログインしてください。ホスト名の別名、リバースプロキシ、別途ホストする UI を使う場合は、バックエンドの `CODENOMAD_ALLOWED_ORIGINS` に信頼する UI のオリジン(スキーム、ホスト名、ポート)を設定します。LAN 上のネイティブクライアントは、変更リクエストに許可された `Origin` ヘッダーを付ける必要があります。その HTTPS オリジンでは、ホストがトンネルなしで端末をペアリングすることもできます。[直接 HTTPS でペアリングする](remote-control.md#direct-https)を参照してください。 -ホスト専用の操作にはループバック接続を使ってください。対象は SideCar のコンテンツ(`/sidecars/`)と WebSocket、リモートコントロールの管理(`/api/remote-control/`)、プラグインブリッジ(`/api/opencode-plugin/`)、リモートプロキシ(`/api/remote-proxy/`)、保存済みサーバーの管理(`/api/remote-servers/`)、パスワード変更、トークンによる初期設定です。LAN からの直接アクセスでログイン済みでも、これらにはループバックが必要です。有効なケイパビリティトークンがあれば、アクティブなプレビューのコンテンツ(`/previews/`)は LAN からの直接アクセスで利用できます。 +ホスト専用の操作にはループバック接続を使ってください。対象は SideCar のコンテンツ(`/sidecars/`)と WebSocket、リモートコントロールの管理(`/api/remote-control/`)、プラグインブリッジ(`/api/opencode-plugin/`)、リモートプロキシ(`/api/remote-proxy/`)、保存済みサーバーの管理(`/api/remote-servers/`)、パスワード変更、トークンによる初期設定です。LAN からの直接アクセスでログイン済みでも、これらにはループバックが必要です。例外は SideCar だけです。ホストの **HTTPS で SideCar を開く** 設定を有効にすると、信頼された HTTPS オリジンからサインインしたブラウザーにそのコンテンツと WebSocket が開放されます([SideCar](browser-sidecars.md#register-sidecar))。有効なケイパビリティトークンがあれば、アクティブなプレビューのコンテンツ(`/previews/`)は LAN からの直接アクセスで利用できます。 `/api/sidecars` 登録 API は、認証済みの LAN 直接接続クライアントとペアリング済み端末で引き続き利用できます。リモートコントロールの Web プレビューは、ホストで有効な間、ケイパビリティトークンで利用できます。 diff --git a/docs/help/ja/remote-control.md b/docs/help/ja/remote-control.md index bd0b3ab03d..5bc798000e 100644 --- a/docs/help/ja/remote-control.md +++ b/docs/help/ja/remote-control.md @@ -86,3 +86,7 @@ CodeNomad は [OpenTunnel](https://github.com/anomalyco/opentunnel) を使用し TLS は CodeNomad バックエンドで終端します。リレーは暗号文を転送するためアプリ内容を読めませんが、ホスト名、接続の時刻、通信量を観測できます。トンネルの証明書/秘密鍵はホストに残ります。ホストのトンネルストレージと CodeNomad 設定を認証情報として保護してください。推測困難なアドレスは認可ではありません。 `CODENOMAD_REMOTE_CONTROL_API` はセルフホストの OpenTunnel API を選び、未設定ならホスト型サービスを使用します。変わるのはトンネルの配置であり、ペアリング要件やブロック対象ではありません。認証情報と診断の扱いは、[セキュリティ](security.md)を参照してください。 + +## 管理者ポリシー {#administrator-policy} + +管理者は、コンピューター上のすべてのユーザーに対してリモートコントロールを無効にできます。環境変数 `CODENOMAD_REMOTE_CONTROL=disabled` をシステム全体に設定し、CodeNomad を再起動します。バックエンドはトンネルを接続せず、**リモートコントロールを開始** とペアリングリンクを拒否し、起動時に再接続しません。設定には **管理者により無効化** と表示されます。以前にペアリングしたデバイスは接続できず、取り消せるよう一覧に残ります。未設定または空の場合はポリシーなしです。それ以外の値 (空白のみも含む) ではバックエンドは起動しません。 diff --git a/docs/help/ja/security.md b/docs/help/ja/security.md index 806a08cb58..0d37be4d0d 100644 --- a/docs/help/ja/security.md +++ b/docs/help/ja/security.md @@ -33,7 +33,7 @@ CodeNomad へのアクセスにより、OpenCode を通じてバックエンド ログアウトすると現在の直接セッションが失効します。ホストでパスワード変更が成功すると、そのユーザーのすべての直接セッション(現在のセッションを含む)が失効します。再ログインしてください。セッションは認証済みリクエストがない状態で24時間、または作成から7日で期限切れになります。変更する場合はバックエンド起動前に `CODENOMAD_SESSION_IDLE_SECONDS` と `CODENOMAD_SESSION_ABSOLUTE_SECONDS` を正の整数秒で設定してください。リモートコントロール端末は別途取り消します。 -LAN クライアントはログイン、ログアウト、プロジェクトの利用ができます。パスワード変更、リモートコントロール管理、リモートサーバー/プロキシツール、SideCars はホストのループバック接続から管理します。ブラウザーの変更操作には許可された Origin、または Origin がない場合は Referer が必要です。サーバーが公開するオリジンは許可されます。DNS 別名、リバースプロキシ、別ホストの UI には `CODENOMAD_ALLOWED_ORIGINS` に `https://code.example.test,https://ui.example.test:8443` のような正確な HTTP(S) オリジンをカンマ区切りで設定し、再起動します。パスやワイルドカードは使えません。これはブラウザーアクセスを許可するもので、ホスト権限は付与しません。ネイティブ LAN クライアントも変更時に許可された Origin を送信します。ループバック接続の信頼されたプロキシはホスト権限を持つため、独自のアクセス制御が必要です。サーバーがループバックまたはすべてのインターフェースで待ち受けている場合、ホスト上で同じスキームとポートの `localhost` として開いた UI も動作します。 +LAN クライアントはログイン、ログアウト、プロジェクトの利用ができます。パスワード変更、リモートコントロール管理、リモートサーバー/プロキシツール、SideCars はホストのループバック接続から管理します。ホストの **HTTPS で SideCar を開く** 設定は、信頼された HTTPS オリジンからサインインしたブラウザーに SideCar を開放します。これらのアドレスの全ユーザーに SideCar サービスの利用を許可できる場合にのみ有効にしてください。ブラウザーの変更操作には許可された Origin、または Origin がない場合は Referer が必要です。サーバーが公開するオリジンは許可されます。DNS 別名、リバースプロキシ、別ホストの UI には `CODENOMAD_ALLOWED_ORIGINS` に `https://code.example.test,https://ui.example.test:8443` のような正確な HTTP(S) オリジンをカンマ区切りで設定し、再起動します。パスやワイルドカードは使えません。これはブラウザーアクセスを許可するもので、ホスト権限は付与しません。ネイティブ LAN クライアントも変更時に許可された Origin を送信します。ループバック接続の信頼されたプロキシはホスト権限を持つため、独自のアクセス制御が必要です。サーバーがループバックまたはすべてのインターフェースで待ち受けている場合、ホスト上で同じスキームとポートの `localhost` として開いた UI も動作します。 侵害が疑われる場合: diff --git a/docs/help/ja/server.md b/docs/help/ja/server.md index a9543dc9a6..0debfceef8 100644 --- a/docs/help/ja/server.md +++ b/docs/help/ja/server.md @@ -8,7 +8,7 @@ 1. Node.js 24 LTS と npm をインストールします。リポジトリのビルドランタイムは `.node-version` で固定されています。デスクトップパッケージは独自のランタイムを提供します。Electron は内蔵の Node を使用し、Tauri は Node を同梱し、どちらも npm を含みます。 2. **バックエンドプロセスの PATH** に Git を配置します。WSL 内だけの Git では Windows バックエンドの要件を満たしません。 -3. OpenCode をインストールまたは選択します。必須の最低バージョンは **2.2.3**、推奨検証対象は **2.2.7** です。新しい/カスタムビルドは、テスト済みバージョンの許可リストではなく、互換性チェックを受けます。[OpenCode のセットアップ](opencode.md)を参照してください。 +3. OpenCode をインストールまたは選択します。必須の最低バージョンは **2.3.0**、推奨検証対象は **2.3.0** です。新しい/カスタムビルドは、テスト済みバージョンの許可リストではなく、互換性チェックを受けます。[OpenCode のセットアップ](opencode.md)を参照してください。 4. サーバーを起動するフォルダーを選ぶか、`--workspace-root` を明示します。 Git がない場合、会話は明示的に開いた物理フォルダー内だけで利用でき、Git とワークツリー操作は失敗します。Git をインストールし、PATH 変更後にバックエンドを再起動してください。ワークスペースルートは開く/参照する範囲の制限であり、エージェント実行の制限ではありません。[セキュリティ](security.md)を参照してください。 @@ -104,6 +104,8 @@ TauriやElectronの起動には[デスクトップの起動引数](desktop.md#de | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`。リリース提示の問い合わせ先リポジトリ。 | | `CODENOMAD_REMOTE_CONTROL_API` | 未設定ならホスト型 OpenTunnel API。セルフホストのリレー配備には API オリジンを指定。 | +| `CODENOMAD_REMOTE_CONTROL` | 未設定: ユーザーはリモートコントロールを開始できます。`disabled`: 管理者により無効 ([ポリシー](remote-control.md#administrator-policy))。未設定または空はポリシーなし、それ以外の値 (空白を含む) では起動しません。 | +| `CODENOMAD_LOCKED_HOST` | 未設定または空: `--host` が適用されます。空白のみでは起動しません。アドレス: `--host`、`CLI_HOST`、待ち受けスイッチにかかわらず、サーバーはそこで待ち受けます ([ポリシー](remote-access.md#administrator-policy))。 | | `NODE_EXTRA_CA_CERTS` | Node の任意の追加 CA ファイル。OpenCode デーモンがないため起動する際、許可された起動環境とともに渡します。既に稼働中のデーモンは変更しません。 | プロバイダー固有の使用量認証情報は、[プロバイダー](providers.md)で説明しています。デスクトップのデータプロファイル選択は[デスクトップ](desktop.md)を参照してください。リリースフィードで制御するものではありません。 diff --git a/docs/help/ja/settings.md b/docs/help/ja/settings.md index ab56cf6115..1b99bfcfe5 100644 --- a/docs/help/ja/settings.md +++ b/docs/help/ja/settings.md @@ -70,7 +70,7 @@ UI は会話を再起動せずに更新されます。ヘブライ語では右 2. 右パネルの **右パネルをカスタマイズ** を開きます。チェックボックスで組み込みタブとステータスのセクションを選びます。ステータスの最低 1 セクションは表示されます。これらのチェックボックスの上をドラッグすると、まとめて設定できます。 3. 右パネルのタブをドラッグして並べ替えます。**リセット** で組み込みレイアウトの選択を復元します。 -認識された[連携](integrations.md#integration-sections)にもステータスのセクションがあります。同じチェックボックスで非表示にできます。すべてのステータスセクションをドラッグまたは上下キーで並べ替えられます。表示設定と順序は再読み込みや連携の一時的な不在後も保持されます。 +すべてのステータスセクションをドラッグまたは上下キーで並べ替えられます。表示設定と順序は再読み込み後も保持されます。 ステータスには、トークン情報、Yolo モード、プロバイダーの使用量、バックグラウンドシェル、MCP、プラグインがあります。会話に[目標](conversations.md#goal)がある間は、これらのセクションの上に目標の行が表示されます。この行はセクションではないため、非表示にも移動もできません。セクションを隠しても、サービスの無効化や権限の取り消しはしません。狭いレイアウトでは、会話を圧迫せず、収まらなくなったパネルを閉じます。そこで開いたパネルは会話の上に浮かび、一方のフローティングパネルを開くと他方は閉じます。 diff --git a/docs/help/ja/troubleshooting.md b/docs/help/ja/troubleshooting.md index 836235c838..db759dce3d 100644 --- a/docs/help/ja/troubleshooting.md +++ b/docs/help/ja/troubleshooting.md @@ -42,7 +42,7 @@ Git がなくてもディレクトリ専用の会話は使えますが、ワー ## OpenCode ランタイムと WSL {#opencode-runtime} 1. **設定 → OpenCode** を開き、**OpenCode バージョン** カード(インストール済みバージョンと稼働中サービスの状態)、続いて **OpenCode バイナリ** で選択した実行ファイルを確認します。 -2. 必要なランタイムがなければ、サポートされるインストール/更新操作を使用します。現在の最低要件は **2.2.3**、推奨/検証済みバージョンは **2.2.7** です。 +2. 必要なランタイムがなければ、サポートされるインストール/更新操作を使用します。現在の最低要件は **2.3.0**、推奨/検証済みバージョンは **2.3.0** です。 3. インストール済み CLI と稼働中サービスが異なる場合は、共有サービスを再起動するか明示的に判断します。 **OpenCode サービスを再起動** は **トラブルシューティング** にあり、確認が必要です。接続中の全クライアントの作業を中断しますが、セッション履歴は保持します。設定の再読み込みは別操作であり、プロセスを保ちつつ、読み込み済み Location を再構築し、保留中の質問/権限をキャンセルします。どちらも無害な更新ではありません。 diff --git a/docs/help/ne/browser-sidecars.md b/docs/help/ne/browser-sidecars.md index 3d3f3123c9..e7ca870f62 100644 --- a/docs/help/ne/browser-sidecars.md +++ b/docs/help/ne/browser-sidecars.md @@ -77,7 +77,7 @@ Electron र Windows Tauri मा mobile template ले स्वामित SideCar sandbox गरिएको पूर्वावलोकन होइन, CodeNomad को विश्वसनीय विस्तार हो: यसको पृष्ठ CodeNomad कै origin मा चल्छ, त्यसैले यसका script ले तपाईंको sign-in भएको पहुँचसहित CodeNomad प्रयोग गर्न सक्छन्। जसको code मा विश्वास छ ती सेवा मात्र दर्ता गर्नुहोस्। CodeNomad ले आफ्नै sign-in cookie सेवामा पठाउँदैन, तर सेवाका आफ्नै cookie राखिन्छन्। -SideCar सामग्री (`/sidecars/`) र SideCar WebSocket लाई होस्टमा loopback जडान चाहिन्छ। `/api/sidecars` मार्फत दर्ता जोडी बनाइएका उपकरण र प्रमाणीकृत प्रत्यक्ष LAN क्लाइन्टलाई उपलब्ध छ। सक्रिय पूर्वावलोकन सामग्री (`/previews/`) वैध क्षमता टोकनसहित प्रत्यक्ष LAN पहुँचमा उपलब्ध छ; [Remote Control](remote-control.md#remote-surface) का वेब पूर्वावलोकन सक्षम रहँदा आफ्नो क्षमता टोकनसहित उपलब्ध रहन्छन्। प्रत्यक्ष पहुँचका आवश्यकताका लागि [स्तरोन्नति](remote-access.md#upgrading) हेर्नुहोस्। +SideCar सामग्री (`/sidecars/`) र SideCar WebSocket लाई होस्टमा loopback जडान चाहिन्छ। अरू उपकरणबाट पनि खोल्न होस्टमा **सेटिङहरू → SideCars** मा **HTTPS मार्फत SideCars खोल्नुहोस्** सक्रिय गर्नुहोस्: यो सर्भरका HTTPS ठेगाना वा `CODENOMAD_ALLOWED_ORIGINS` को HTTPS origin, जस्तै TLS रिभर्स प्रोक्सी, बाट साइन इन गरिएका ब्राउजरले त्यसपछि SideCars खोल्न सक्छन्। सामान्य HTTP, `localhost` ठेगाना र Remote Control होस्टमा मात्र सीमित रहन्छन्। `/api/sidecars` मार्फत दर्ता जोडी बनाइएका उपकरण र प्रमाणीकृत प्रत्यक्ष LAN क्लाइन्टलाई उपलब्ध छ। सक्रिय पूर्वावलोकन सामग्री (`/previews/`) वैध क्षमता टोकनसहित प्रत्यक्ष LAN पहुँचमा उपलब्ध छ; [Remote Control](remote-control.md#remote-surface) का वेब पूर्वावलोकन सक्षम रहँदा आफ्नो क्षमता टोकनसहित उपलब्ध रहन्छन्। प्रत्यक्ष पहुँचका आवश्यकताका लागि [स्तरोन्नति](remote-access.md#upgrading) हेर्नुहोस्। ## OpenVSCode Server विधि {#openvscode} diff --git a/docs/help/ne/conversations.md b/docs/help/ne/conversations.md index 1fe28ecf76..302e7f17d6 100644 --- a/docs/help/ne/conversations.md +++ b/docs/help/ne/conversations.md @@ -60,6 +60,12 @@ skill रोज्दा `@query` token हटेर chip थपिन्छ। मस्यौदा क्लाइन्टको कामचलाउ अवस्था हुन्, साझा नेटिभ सन्देश होइनन्। startup restoration ले समर्थित कम्पोजर अवस्था राख्न सक्छ, तर नपठाइएको मस्यौदा वा संलग्नकलाई backup नमान्नुहोस् वा अर्को उपकरणमा देखिन्छ नठान्नुहोस्। startup डेटा खाली गर्नुअघि वा restore नीति बन्द भएको क्लाइन्ट बन्द गर्नुअघि महत्त्वपूर्ण पाठ बचत गर्नुहोस्; [डेस्कटप](desktop.md) हेर्नुहोस्। +## जवाफबाट फाइल खोल्ने {#open-files-from-replies} + +1. एजेन्टका जवाफले सापेक्ष र निरपेक्ष मार्गहरूसँग परियोजना फाइलहरू लिंक गर्छन्। +2. सामान्य क्लिकले कुराकानीको वर्कट्रीबाट लिंक गरिएको फाइल पढेर फाइल पूर्वावलोकनमा खोल्छ। +3. मोडिफाइड क्लिक (Ctrl/⌘, Shift, मध्य-क्लिक) र सेसनको वर्कट्री बाहिरका लिंकहरूले सामान्य लिंक व्यवहार राख्छन्। + ## आदेश र Shell मोड {#commands-shell} 1. `/` टाइप गरी भेटिएको custom command चयन गर्नुहोस्, त्यसपछि argument दिनुहोस्। diff --git a/docs/help/ne/install.md b/docs/help/ne/install.md index 64cab5236f..5e96dce3c3 100644 --- a/docs/help/ne/install.md +++ b/docs/help/ne/install.md @@ -45,7 +45,7 @@ Electron Debian स्थापनाले Chromium sandbox कन्फिग | आवश्यकता | कहाँ उपलब्ध हुनुपर्छ | हालको आवश्यकता | | --- | --- | --- | -| OpenCode CLI | चयन गरिएको कार्यान्वयन होस्ट, लागू भए चयन गरिएको WSL वितरणसमेत | न्यूनतम **2.2.3**; **2.2.7** सिफारिस/योग्यता जाँच गरिएको लक्ष्य हो। नयाँ वा अनुकूलित संस्करणलाई परीक्षण नभएको भन्दै निषेध नगरी contract जाँच गरिन्छ। | +| OpenCode CLI | चयन गरिएको कार्यान्वयन होस्ट, लागू भए चयन गरिएको WSL वितरणसमेत | न्यूनतम **2.3.0**; **2.3.0** सिफारिस/योग्यता जाँच गरिएको लक्ष्य हो। नयाँ वा अनुकूलित संस्करणलाई परीक्षण नभएको भन्दै निषेध नगरी contract जाँच गरिन्छ। | | Git | CodeNomad ब्याकएन्ड खाताको `PATH` | रिपोजिटरी पहिचान, Git कार्य र worktree का लागि आवश्यक। | | Node.js/npm | स्वतन्त्र सर्भर र स्रोत-build होस्ट | Node.js 24 LTS; पुनरुत्पादनयोग्य स्रोत build ले `.node-version` मा pinned संस्करण प्रयोग गर्छन्। डेस्कटप रिलिजमा आफ्नै हुन्छ: Electron को integrated Node वा Tauri को bundled Node, npm सहित। | | कार्यस्थान फोल्डर | ब्याकएन्डले पहुँच गर्न सक्ने डिस्क | स्पष्ट रूपमा खोलिएको भौतिक फोल्डर, रिमोट ब्राउजरले अनुमान गरेको उपकरण-स्थानीय फोल्डर होइन। | diff --git a/docs/help/ne/integrations.md b/docs/help/ne/integrations.md index fab57341a5..1b6f25ca7a 100644 --- a/docs/help/ne/integrations.md +++ b/docs/help/ne/integrations.md @@ -27,7 +27,7 @@ server नदेखिए सक्रिय Location र नेटिभ कन CodeNomad ले व्यवस्थापन गर्ने प्लगइनहरू सामान्य प्लगइन सूची र त्यसका सक्रियता, अद्यावधिक तथा हटाउने नियन्त्रणहरूबाट अलग रहन्छन्। CodeNomad ले तिनलाई प्रमाणित इन्स्टलर प्रविष्टि र सामग्रीको ह्यासले चिनिने कोडको भण्डारण स्थानबाट पहिचान गर्छ; उही नाम वा ID भएको तेस्रो-पक्ष प्लगइनमा सामान्य नियन्त्रणहरू रहन्छन्। -व्यवस्थापन गरिएको प्लगइन निष्क्रिय भए, लोड हुन असफल भए वा लोड भएको पुष्टि नभए, प्लगइन सूचीमाथि **CodeNomad प्लगइनहरूमा ध्यान दिनु आवश्यक छ** देखिन्छ। उपलब्ध त्रुटि र OpenCode लगको सन्दर्भ हेर्न त्यसको **i** बटन (प्लगइनको **विवरण**) खोल्नुहोस्। निष्क्रिय प्लगइनले मात्र **पुनः सक्रिय गर्नुहोस्** दिन्छ: यसले निष्क्रिय बनाउने नियम जोगाएर ठ्याक्कै सोही ID को सकारात्मक सक्रियता नियम थप्छ। निष्क्रिय बनाउने नियमको **विश्वव्यापी** वा **परियोजना** दायरामा लेख्न मिल्छ भने त्यहीँ, नत्र **परियोजना** मा लेख्छ। OpenCode चलिरहन्छ; नेटिभ घटनाहरू वा **प्लगइन नियन्त्रण ताजा गर्नुहोस्** ले प्लगइन सक्रिय भएको पुष्टि नगरुन्जेल चेतावनी रहन्छ। +व्यवस्थापन गरिएको प्लगइन निष्क्रिय भए, लोड हुन असफल भए वा लोड भएको पुष्टि नभए, प्लगइन सूचीमाथि **CodeNomad प्लगइनहरूमा ध्यान दिनु आवश्यक छ** देखिन्छ। उपलब्ध त्रुटि र OpenCode लगको सन्दर्भ हेर्न त्यसको **i** बटन (प्लगइनको **विवरण**) खोल्नुहोस्। निष्क्रिय प्लगइनले मात्र **पुनः सक्रिय गर्नुहोस्** दिन्छ: त्यति मात्रले प्लगइन फेरि सक्रिय हुन्छ भने यसले त्यो फाइलबाट ठ्याक्कै निष्क्रिय बनाउने नियम हटाउँछ, नत्र ठ्याक्कै सोही ID को सकारात्मक नियम थप्छ। निष्क्रिय बनाउने नियमको **विश्वव्यापी** वा **परियोजना** दायरामा लेख्न मिल्छ भने त्यहीँ, नत्र **परियोजना** मा लेख्छ। OpenCode चलिरहन्छ; नेटिभ घटनाहरू वा **प्लगइन नियन्त्रण ताजा गर्नुहोस्** ले प्लगइन सक्रिय भएको पुष्टि नगरुन्जेल चेतावनी रहन्छ। चेतावनी र त्यसका विवरणहरूले कन्फिगरेसनको स्रोतअनुसार **विरासत / बाह्य** वा **भर्चुअल कन्फिगरेसन** देखाउँछन्। पुनः सक्रिय गर्ने गन्तव्य निष्क्रिय बनाउने नियमको स्रोतभन्दा फरक हुँदा छुट्टै **परियोजना** लेबलले त्यो गन्तव्य जनाउँछ। @@ -38,7 +38,7 @@ CodeNomad ले व्यवस्थापन गर्ने प्लगइ Global ले जोडिएको daemon को पत्ता लागेको global कन्फिगरेसन लक्षित गर्छ। Project ले सक्रिय Location भित्रको कन्फिगरेसन लक्षित गर्छ, inherited ancestor फाइल होइन। पछिको Project नियमले Global override गर्न सक्छ; Global switch ले अन्तिम Project अवस्था भएको अभिनय नगरी Global नियम नै देखाउँछ। Project नियम नभए resolved Global अवस्था inherit हुन्छ। -यी switch ले स्रोत घोषणा र असम्बन्धित कन्फिगरेसन जोगाउँदै ठ्याक्कै सक्रियता नियम थप्छन्। plugin विकल्प सम्पादन, package स्थापना वा फाइल हटाइ गर्दैनन्। built-in OpenCode plugin user सक्रियता switch मा दिइँदैनन्। लक्ष्य Global बाट सुरक्षित अलग गर्न नसके वा सक्रिय Location बाहिर जाने भए Project अक्षम हुन्छ। +हरेक switch ले आफ्नो दायराको फाइलमा plugin को एउटा ठ्याक्कै सक्रियता नियम लेख्छ र त्यहाँ सोही plugin का पहिलेका ठ्याक्कै नियम बदल्छ, वा नतिजा उही हुने भए तिनलाई हटाउने मात्र गर्छ। स्रोत घोषणा, `*` जस्ता फराकिला नियम र असम्बन्धित कन्फिगरेसन जोगिन्छन्। plugin विकल्प सम्पादन, package स्थापना वा फाइल हटाइ गर्दैनन्। built-in OpenCode plugin user सक्रियता switch मा दिइँदैनन्। लक्ष्य Global बाट सुरक्षित अलग गर्न नसके वा सक्रिय Location बाहिर जाने भए Project अक्षम हुन्छ। package अपडेटले, यसको tooltip ले भनेझैं, त्यो package प्रयोग गर्ने हरेक Location का लागि OpenCode को साझा cache मा त्यो package बदल्छ; यसले सक्रियता नियम बदल्दैन, OpenCode पुनः सुरु गर्दैन वा कन्फिगरेसन reload गर्दैन। स्थानीय, built-in र SDK-प्रदत्त plugin को package कार्य हुँदैन। plugin ID बताउनुअघि नै असफल हुने package यसको package नामले सूचीमा रहन्छ, tooltip मा असफलता र check/update कार्यसहित, तर सक्रियता switch बिना। असफल check वा update बताइन्छ र कहिल्यै स्वतः पुनःप्रयास हुँदैन। @@ -78,38 +78,30 @@ skill उपलब्धता कुराकानीको Location बाट command सक्रिय Location का लागि OpenCode बाट पत्ता लाग्छन्। आफ्नै नेटिभ परिभाषाले execution व्यवहार रोज्न सक्छ; menu package installer वा असीमित configuration editor होइन। CodeNomad ले native custom-command पठाउनुअघि प्रोफाइल सत्र वातावरण लागू गर्छ; environment update असफल भए पठाइ रोकिन्छ। `/btw` CodeNomad को छुट्टै क्षणिक प्रश्न flow हो, सामान्य custom command होइन। command परिभाषा र native configuration inheritance का लागि [OpenCode command दस्तावेज](https://opencode.ai/v2/docs/commands/) प्रयोग गर्नुहोस्। कन्फिगरेसन परिवर्तनपछि पहिले सम्बन्धित सतह refresh/reopen गर्नुहोस्; runtime लाई अझै चाहिँदा मात्र स्पष्ट configuration reload गर्नुहोस्। प्रदर्शन refresh गर्नकै लागि सम्भवतः admitted command replay नगर्नुहोस्। -## स्थितिमा एकीकरण खण्डहरू {#integration-sections} +## प्लगइनहरूमा एकीकरण {#integration-rows} **स्थिति → प्लगइनहरू** को **+** मा **एकीकरण थप्नुहोस्…** वा **प्लगइन थप्नुहोस्…** छान्न सकिन्छ। एकीकरण चयनमा समीक्षा गरिएको सूचीका स्थापना नभएका प्रविष्टि देखिन्छन्। दायरा र **स्थापना गर्नुहोस्** छान्नुहोस्: CodeNomad ले छानिएको सूची ID स्थापना गर्छ। नेटिभ एकीकरण **विश्वव्यापी मात्र** हुन्छन्। **सूची उपलब्ध छैन** मा **ताजा गर्नुहोस्** हुन्छ; **{date} को सूची** ले पुरानो भएको अन्तिम मान्य सूची जनाउँछ। -घोषणा वा लोड भएको/असफल प्लगइन भएको प्रत्येक पहिचान गरिएको एकीकरणको आफ्नै **स्थिति** खण्ड हुन्छ, निष्क्रिय वा स्थापना हुँदै गर्दा पनि। अस्पष्ट स्रोतले प्लगइनहरूमा **मापदण्ड अनुरूप छैन** देखाउँछ। प्रत्येक एकीकरणको प्लगइन पङ्क्ति अद्यावधिक, हटाउने र ताजा गर्ने कार्यसहित रहन्छ। संस्करण र प्लगइन नियन्त्रण खण्डको मुख्य भागमा हेर्न खण्ड खोल्नुहोस्; नाम र अवस्था शीर्षकमा **कागजात** र **i** छेउमा देखिइरहन्छन्। **i** पपओभरले मागअनुसार विवरण दिन्छ: Enter/Space ले खोल्छ र Escape ले बन्द गर्छ। +पहिचान गरिएको एकीकरणको **स्थिति → प्लगइनहरू** मा एउटै पङ्क्ति हुन्छ, जसमा यसको नाम (जस्तै **OpenCode for Blender**) र संस्करण हुन्छ। यसका **विश्वव्यापी** र **परियोजना** स्विच अन्य स्विचजस्तै एक्सेन्ट रङका हुन्छन्, साधारण प्लगइनका हरिया हुन्छन्; अनुप्रयोगभित्र भाग भएको एकीकरण **विश्वव्यापी मात्र** हुन्छ। यसको नाममा पोइन्टर लैजानुहोस्: विवरण **प्लगइन** को सट्टा **एकीकरण** बाट सुरु हुन्छ; स्क्रिन रिडरले यसलाई पङ्क्तिको विवरणका रूपमा पढ्छन्। अस्पष्ट स्रोतमा **मापदण्ड अनुरूप छैन** देखिन्छ। -स्थितिको अनुकूलनबाट सबै स्थिति खण्ड लुकाउन र तानेर वा माथि/तल कुञ्जीले क्रम बदल्न सकिन्छ। दृश्यता र क्रम पुनः लोड हुँदा र एकीकरण अस्थायी रूपमा नहुँदा पनि सुरक्षित रहन्छन्। फोकस भएको खण्ड हराए फोकस प्लगइनहरूमा फर्कन्छ, वा प्लगइनहरू लुकेको भए अर्को देखिने स्थिति खण्डमा जान्छ। +नामको तल, अवस्था पङ्क्तिले एकीकरण कहाँ छ भनेर सधैँ देखाउँछ। खैरो पाठले जानकारी दिन्छ; एक्सेन्ट रङको पाठ बटन हो। अनुप्रयोगभित्र भाग भएको एकीकरणमा सबैभन्दा महत्त्वपूर्ण अवस्था देखिन्छ: भाग नभए वा पुरानो भए **Blender मा स्थापना गर्नुहोस्** वा **Blender अद्यावधिक गर्नुहोस्** (स्थापना पुष्टिसहित), नमिल्दा चेतावनी रङ, देखाइएको कुराकानी जोडिएको भए साङ्लोको आइकन र कागजात (छुट्याउन छान्नुहोस्), **Blender बन्द छ**, **Blender: कुनै खुला कागजात छैन**, **कुनै कुराकानी देखाइएको छैन**, त्यसपछि कागजातको नामसहित **जोड्नुहोस्**, वा धेरै कागजातबाट छान्न **जोड्नुहोस्…**। कुराकानीको एजेन्टले पहिलो पटक एकीकरण प्रयोग गर्दा पनि कुराकानी आफैं जोडिन्छ। सम्पादक MCP एकीकरणले **सर्भर भेटियो** वा **सर्भर भेटिएन**, API एकीकरणले **जोडिएको** वा **विच्छेदित** देखाउँछ। लामो अवस्था छोटो पारिन्छ; पूरा पाठ हेर्न पोइन्टर लैजानुहोस्। एकीकरणले जनाएका परिवर्तन र पुनः जडानले पङ्क्ति ताजा गर्छन्। -सूचीबाट स्थापना, अनुप्रयोग भागको स्थापना/अद्यावधिक, जोड्ने र हटाउने कार्यमा पुष्टि चाहिन्छ। सुरुको फोकस **रद्द गर्नुहोस्** मा हुन्छ; पुष्टि कार्य 600 मिलिसेकेन्डपछि उपलब्ध हुन्छ। सक्रियता र प्लगइन अद्यावधिक सीधै चल्छन्। +पङ्क्तिको **…** मेनु जडान अवस्थाबाट सुरु हुन्छ, जस्तै **Blender: 1 खुला कागजात** वा **Blender बन्द छ**। त्यसपछि **कागजात**, **अनुप्रयोगमा स्थापना गर्नुहोस्…**, **अनुप्रयोग अद्यावधिक गर्नुहोस्…** वा **अनुप्रयोगमा पुनः स्थापना गर्नुहोस्…** ([तल हेर्नुहोस्](#application-installation)), प्याकेजको अद्यावधिक जाँच, **विश्वव्यापी बाट हटाउनुहोस्** वा **परियोजना बाट हटाउनुहोस्**, र **प्लगइन नियन्त्रण ताजा गर्नुहोस्** आउँछन्। छुट्याउन पुष्टि बिना एक क्लिक लाग्छ र यसले यो कुराकानीलाई मात्र असर गर्छ: अनुप्रयोग खुला रहन्छ, यसको भाग स्थापित रहन्छ र अन्य कुराकानीहरूको जडान रहन्छ। उत्तर हराएमा पङ्क्तिले अवस्था फेरि पढ्छ; अनुरोध कहिल्यै दोहोरिँदैन। -## खुला अनुप्रयोग जोड्नुहोस् {#application-attachment} +सूचीबाट स्थापना, अनुप्रयोग भागको स्थापना/अद्यावधिक र हटाउन पुष्टि चाहिन्छ। **रद्द गर्नुहोस्** मा पहिले फोकस हुन्छ; पुष्टि कार्य 600 ms पछि उपलब्ध हुन्छ। सक्रियता, प्लगइन अद्यावधिक, जोड्ने र छुट्याउने काम सिधै चल्छन्। -अनुप्रयोगको एकीकरणबाट कागजात प्रस्ताव गर्नुहोस्, **स्थिति → एकीकरण → कुराकानी** खोल्नुहोस् र **जोड्नुहोस्…** छान्नुहोस्। यही खण्डले देखाइएको कुराकानीको जडान नियन्त्रण गर्छ। अनुप्रयोग र कागजात छान्नुहोस्, लक्षित कुराकानी र परिवर्तन चेतावनी जाँचेर **जोड्नुहोस्** बाट पुष्टि गर्नुहोस्। टाढाको जडानमा पनि अनुप्रयोग OpenCode को मेसिनमा चल्छ। WSL सहित असमर्थित होस्टमा **i** बाट मद्दत पाइन्छ। - -**कुराकानी** पङ्क्तिले देखाइएको कुराकानीको जडान पढ्छ। **जडान अज्ञात छ** मा **ताजा गर्नुहोस्** हुन्छ। ताजा आधिकारिक पठनले जडान पुष्टि गर्दा **छुट्याउनुहोस्** ले **जोड्नुहोस्…** लाई प्रतिस्थापन गर्छ। एक क्लिकले थप पुष्टि बिना यही कुराकानी मात्र छुट्याउँछ; अनुप्रयोग खुला र यसको भाग स्थापित रहन्छ, अन्य कुराकानीका जडान रहन्छन्। नेटिभ परिवर्तन र पुनः जडानले अवस्था ताजा गर्छन्। - -स्वीकार गरिएको कार्यको नतिजा वा त्रुटि लक्षित कुराकानी देखिइरहँदा रहन्छ; नेभिगेसनले रसिद बन्द गर्छ। हालको जडान आधिकारिक पठनअनुसार हुन्छ। उत्तर हराउँदा, समय सकिँदा वा सम्पर्क टुट्दा **अनिश्चित अवस्था** ले वास्तविक अवस्था पढ्न **ताजा गर्नुहोस्** दिन्छ। प्रदर्शन ताजा गर्न अनुरोध कहिल्यै नदोहोर्‍याउनुहोस्। - -चयनमा खुला अनुप्रयोगहरू स्पष्ट रूपमा पढेपछि, सुरक्षित Q8 मेटाडेटाले उही एकीकरण र प्रमाणित कागजात लेबलका लागि चयन वा **कुराकानी** पङ्क्तिमा **फेरि जोड्नुहोस्** सुझाव दिन सक्छ, जबसम्म परियोजना, कुराकानी र जडान पुस्ता उही रहन्छन्। फेरि जोड्न स्पष्ट पुष्टि चाहिन्छ; नेभिगेसन वा डेटा अमान्य हुँदा सुझाव हट्छ। हालको जडानको आधिकारिक अवस्था एकीकरणको सत्रअनुसारको पठनबाट आउँछ। - -एकीकरण खण्ड वा यसको प्लगइन पङ्क्तिबाट हटाउँदा उही घोषणा र दायरा पुष्टि प्रयोग हुन्छ। कुराकानी गणना वा स्वतः जडान छुट्याउने कामबिना हटाइन्छ। +हटाउँदा कुराकानीहरूको गणना वा स्वचालित छुट्याउने काम हुँदैन। हटाउँदा प्लगइन र ठ्याक्कै दायरा भएको चेतावनी खुल्छ। **रद्द गर्नुहोस्** मा फोकस हुन्छ; **विश्वव्यापी/परियोजनाबाट हटाउनुहोस्** 600 मिलिसेकेन्डपछि उपलब्ध हुन्छ र स्पष्ट कार्य चाहिन्छ। यसले प्रयोग गर्ने कुराकानीहरूको उपलब्धता र जडान रोक्न सक्छ; विश्वव्यापी दायराले अन्य परियोजनालाई पनि असर गर्न सक्छ। पठाउनुअघि रद्द, म्याद समाप्त वा नेभिगेसन गर्दा केही बदलिँदैन। पुष्टि गरिएको घोषणा मात्र हट्छ; नियम, क्यास, अनुप्रयोगका फाइल र सुरक्षित जडान सङ्केत रहन्छन्। कन्फिगरेसन बदलिए पुनः चयन र पुष्टि चाहिन्छ। सफलताले घोषणा हटेको जनाउँछ; रनटाइम अवस्था OpenCode को पुनः लोडसँग बदलिन्छ। उत्तर हराए फेरि प्रयास गर्नुअघि प्लगइन ताजा गरी वास्तविक कन्फिगरेसन हेर्नुहोस्। पुनः स्थापनाले उपलब्धता फर्काउन सक्छ; पुनः लोड वा जडान चाहिन सक्छ र रोकिएका कार्य फेरि सुरु नहुन सक्छन्। ## अनुप्रयोग एकीकरण स्थापना वा अद्यावधिक गर्नुहोस् {#application-installation} -**स्थिति → एकीकरण → अनुप्रयोग** मा ताजा अवस्थाले दिएमा **अनुप्रयोगमा स्थापना गर्नुहोस्…** वा **अनुप्रयोग अद्यावधिक गर्नुहोस्…** छान्नुहोस्। कुराकानी वा प्रस्ताव गरिएको कागजातबिना पनि उपलब्ध हुन्छ। अनुप्रयोग बन्द छ भने यसको भाग जाँच्न खोल्नुहोस्; **i** मा मेसिन र पूर्वसर्तका विवरण हुन्छन्। +**स्थिति → प्लगइनहरू** मा, एकीकरणको ताजा अवस्थाले कार्य दिँदा यसको अवस्था पङ्क्तिमा **Blender मा स्थापना गर्नुहोस्** वा **Blender अद्यावधिक गर्नुहोस्** छान्नुहोस्, वा यसको **…** मेनुमा **अनुप्रयोगमा स्थापना गर्नुहोस्…**, **अनुप्रयोग अद्यावधिक गर्नुहोस्…** वा **अनुप्रयोगमा पुनः स्थापना गर्नुहोस्…** छान्नुहोस्। पुनः स्थापनाले अनुप्रयोग खुला वा बन्द जे भए पनि अनुप्रयोग भाग फेरि लेख्छ। यो कुराकानी वा खुला कागजात बिना पनि उपलब्ध छ। पुष्टिमा अनुप्रयोग र स्थापनाकर्ता उपलब्ध गराउने **एकीकरण प्याकेजको संस्करण** देखिन्छ। दुवै र मेसिनसम्बन्धी चेतावनी जाँच्नुहोस्: स्थापना OpenCode चल्ने मेसिनमा हुन्छ, जुन टाढाको पनि हुन सक्छ। सुरुको फोकस **रद्द गर्नुहोस्** मा हुन्छ। अगाडि बढ्न स्पष्ट रूपमा पुष्टि गर्नुहोस्। पुष्टि गर्नुअघि परियोजना, Location वा कुराकानी बदल्दा, पुनः जडान हुँदा वा सम्बन्धित नेटिभ परिवर्तन आउँदा बाँकी स्वीकृति रद्द हुन्छ; ताजा विवरण जाँच्न कार्य फेरि खोल्नुहोस्। खुला अनुप्रयोग मिल्दो देखिए पनि WSL मा अनुप्रयोगभित्र स्थापना सधैँ अस्वीकार हुन्छ। समर्थित मेसिनमा अनुप्रयोग खोल्नुहोस्। -नतिजाले एकीकरण स्थापना भएको, अद्यावधिक भएको, पहिले नै अद्यावधिक रहेको, अस्वीकार भएको वा असफल भएको जनाउँछ। स्थापना वा अद्यावधिकपछि अनुप्रयोग खोलेर यसको एकीकरण जाँच्नुहोस्; [खुला अनुप्रयोग जोड्नुहोस्](#application-attachment) बाट छुट्टै कुराकानी जोड्नुहोस्। स्थापनाको सफलताले स्थापना अनुरोधको नतिजा जनाउँछ; चलिरहेको अनुप्रयोगको उपलब्धता यसको स्थितिबाट थाहा हुन्छ। +नतिजाले अनुप्रयोग भाग स्थापना भयो, अद्यावधिक भयो, पहिले नै अद्यावधिक थियो, अस्वीकार भयो वा असफल भयो भनेर जनाउँछ। स्थापना वा अद्यावधिकपछि अनुप्रयोग खोलेर यसको एकीकरण जाँच्नुहोस्। स्थापनाको सफलताले स्थापनाकर्ताको अनुरोध जनाउँछ; अनुप्रयोगको वास्तविक उपलब्धता यसको अवस्थाबाट आउँछ। अनुरोध स्वतः दोहोरिँदैनन्। अस्वीकार वा असफल भएपछि नयाँ कार्य छान्नुअघि अनुप्रयोग जाँच्नुहोस्। त्रुटिका कारण नतिजा अनिश्चित भए सो अनुरोध नदोहोर्‍याउनुहोस्: पहिले अनुप्रयोग जाँच्नुहोस्, त्यसपछि आवश्यक भए नयाँ कार्य र पुष्टि सुरु गर्नुहोस्। diff --git a/docs/help/ne/missions.md b/docs/help/ne/missions.md index daa6cf47f1..78b0d3ebc7 100644 --- a/docs/help/ne/missions.md +++ b/docs/help/ne/missions.md @@ -42,7 +42,7 @@ ### स्वतः सुरु गर्नुहोस् {#automatic-start} -**स्वतः सुरु गर्नुहोस्** समयतालिकाबाहिर छ र सुरुमा बन्द हुन्छ। बन्द हुँदा विरामको मिसन बनाएर पछि ▶ बाट सुरु गरिन्छ। खोल्दा सिर्जना पुष्टि भएपछि सामान्य जाँच र आवश्यक नेटिभ सेटिङ सहमतिसहित सुरु गर्न अनुरोध हुन्छ। +**स्वतः सुरु गर्नुहोस्** समयतालिकाबाहिर छ र सुरुमा बन्द हुन्छ। बन्द हुँदा विरामको मिसन बनाएर पछि ▶ बाट सुरु गरिन्छ। खोल्दा सिर्जना पुष्टि भएपछि सामान्य जाँच र समयतालिकाको स्वतः तयारीसहित सुरु गर्न अनुरोध हुन्छ। सिर्जनाको पुष्टि हराए रसिद पढेपछि पनि सुरुवात म्यानुअल रहन्छ। मूल अपुष्ट अनुरोध राख्नुहोस्; फेरि सिर्जना गर्नुअघि सूची र कुराकानी जाँच्नुहोस्। @@ -56,6 +56,8 @@ एकपटक अहिले, प्रत्येक N घण्टा, दैनिक, हप्ताका दिन, महिनाको दिन र cron छन्। सुरक्षित समय क्षेत्र लागू हुन्छ; प्रणालीभन्दा फरक हुँदा क्षेत्र देखिन्छ। रोजेको दिन नभएको महिना छोडिन्छ। एकपटक अहिलेले सुरु गर्दाको समय लिन्छ; सर्तले एकमात्र अवसर नचलाइकन खर्च गर्न सक्छ। OpenCode सेवा र कार्यान्वयन होस्ट उपलब्ध चाहिन्छ। +सुरु वा पुनः सुरु गर्दा परियोजनाको OpenCode कन्फिगरेसनमा समयतालिका स्वतः तयार हुन्छ। स्पष्ट OFF कायम रहन्छ: उपलब्ध हुँदा **समयतालिकाका सेटिङ खोल्नुहोस्** ले जिम्मेवार फाइल खोल्छ; **i** ले स्रोत वा वातावरणको विवरण देखाउँछ। थिचिएको बटनले अनुरोध चल्दा मात्र लोडिङ देखाउँछ। अपुष्ट परिणाम जाँच गर्न सकिन्छ; सक्रियता पुनः प्राप्त भएपछि पनि सुरु गर्ने कार्य स्पष्ट रूपमा गर्नुपर्छ। + ### घटना र संयोजन {#scheduling-conditions} **रिपोजिटरी गतिविधि → घटना** छान्नुहोस्, त्यसपछि उही कार्डमा ऐच्छिक फिल्टर राख्नुहोस्। Git कमिट र स्वतः पत्ता लगाइएको GitHub, GitLab वा Gitea रिपोजिटरीका घटना एउटै मेनुमा छन्। Contribute कै पहिचानले पहिले `upstream`, त्यसपछि `origin` प्रयोग गर्छ। तीनैमा नयाँ PR/MR, मर्ज भएका PR/MR र नयाँ मुद्दा, साथै `dependabot[bot]` सहित **लेखक (ऐच्छिक)** उपलब्ध छन्। घटना छान्दा रिपोजिटरी तय हुन्छ; सुरक्षित मापदण्डले आफ्नो लक्ष्य कायम राख्छ। @@ -88,9 +90,11 @@ ### रङ र अवस्था {#status-colours} -झन्डाले मिसनको अवस्था, चेभ्रोनले कार्यहरूको ध्यान अवस्था देखाउँछ; दोहोरिने प्रविष्टिमा पुनरावृत्ति चिन्ह हुन्छ। रातोले उत्तर पर्खन्छ, धड्किने पहेँलोले देखिएको काम, सुन्तलाले विराम/अवरोध, हरियोले नहेरिएको परिणाम र नीलोले तयारी वा नसुरु कार्य जनाउँछ। +झन्डाले मिसनको अवस्था, चेभ्रोनले कार्यहरूको ध्यान अवस्था देखाउँछ; दोहोरिने प्रविष्टिमा पुनरावृत्ति चिन्ह हुन्छ। रातोले उत्तर पर्खन्छ र धड्किने पहेँलोले देखिएको काम जनाउँछ। सुन्तला विराम चिन्हले विराम र सुन्तला चेतावनी त्रिकोणले अवरोध देखाउँछ। हरियोले समीक्षा गर्न बाँकी मिसन, कार्य वा सफल सञ्चालन जनाउँछ। + +एक्सेन्ट रङको चिन्हमुनि सानो स्थिर तटस्थ रेखाले **निर्धारित सञ्चालनको प्रतीक्षामा** जनाउँछ: अर्को जागरणको समय पुष्टि भएको छ। एक्सेन्ट रङ प्यालेटअनुसार हुन्छ। रेखाबिनाको एक्सेन्ट चिन्हले तयारी वा नसुरु कार्य देखाउँछ। हेरिएका समाप्ति, रोकिएका समयतालिका र **स्थिति पुष्टि भएको छैन** तटस्थ हुन्छन्; अवस्थाको पाठ पढ्नुहोस्। -चयन, हरियो कार्य चिन्हमा क्लिक/तान्ने वा चेभ्रोन मेनुबाट पढिएको चिह्न लगाउँदा परिणाम पुष्टि हुन्छ। बाधा सधैँ प्रश्न होइन; प्रतिवेदनले सबै नेटिभ कार्य सकिएको प्रमाण दिँदैन। फिर्ता गरिएका कार्य इतिहासमा रहन्छन्। +चयन वा हरियो कार्य चिन्हमा क्लिक/तान्दा परिणाम पुष्टि हुन्छ; चेभ्रोन मेनुले **पढिएको रूपमा चिन्ह लगाउनुहोस्** दिन्छ। **समीक्षा गर्न बाँकी सफल सञ्चालन** का लागि सक्रिय विन्डोमा दोहोरिने पङ्क्ति स्पष्ट रूपमा छान्नुहोस् वा **पढिएको रूपमा चिन्ह लगाउनुहोस्** प्रयोग गरेर त्यही सञ्चालन पुष्टि गर्नुहोस्। समयतालिका सक्रिय हुँदा चिन्ह प्रतीक्षामा फर्कन्छ, अन्यथा तटस्थ हुन्छ। पुनर्स्थापित चयन र पहिल्यै छानिएको पङ्क्तिमा आएका नयाँ परिणाम नपढिएका रहन्छन्। पहिलो लोडमा भएका पुराना सफलताहरू पढिएका मानिन्छन्। फिर्ता गरिएका कार्य इतिहासमा रहन्छन्। ### प्रश्न र निर्णय {#questions} diff --git a/docs/help/ne/mobile.md b/docs/help/ne/mobile.md index c1f0ebc911..e2739f6b00 100644 --- a/docs/help/ne/mobile.md +++ b/docs/help/ne/mobile.md @@ -42,3 +42,5 @@ navigation र tool खोल्न **बायाँ प्यानल** र * | offline काम | offline backend वा cached API history छैन। static UI asset cache हुन सक्छन्, तर document र API response offline workspace होइनन्। | backend पहुँचयोग्य राख्नुहोस्। mobile OS suspension वा network switch ले event stream छुटाउन सक्छ; फर्कँदा reconnect र current state refetch हुन्छ, सुनिश्चित event replay हुँदैन। retry अघि कार्य सकियो कि जाँच्नुहोस्। PWA बन्द गर्दा standalone backend रोकिँदैन; host desktop app र backend quit हुँदा अर्को launch सम्म Remote Control अनुपलब्ध हुन्छ। + +स्थापना गरिएको PWA सहित प्रत्येक ब्राउजर ट्याबले त्यही ट्याबका लागि खुला परियोजनाहरू, चयन गरिएका कुराकानीहरू, नपठाइएका ड्राफ्टहरू र स्क्रोल स्थिति राख्छ: पृष्ठ पुनः लोड हुँदा, वा एप बदलेपछि वा स्क्रिन लक भएपछि मोबाइल OS ले पुनः लोड गर्दा ती फर्किन्छन्। नयाँ ट्याब, वा OS ले पूर्ण रूपमा बन्द गरेको PWA, गृह पृष्ठमा खुल्छ। यो ट्याबका लागि बन्द गर्न **सेटिङ → सामान्य → अघिल्लो अवस्था पुनर्स्थापना गर्नुहोस्** प्रयोग गर्नुहोस्। diff --git a/docs/help/ne/opencode.md b/docs/help/ne/opencode.md index 2ef3711f46..0e0fb7b3a3 100644 --- a/docs/help/ne/opencode.md +++ b/docs/help/ne/opencode.md @@ -19,8 +19,8 @@ PATH मा पुरानो OpenCode पहिले आउँदा दि | वर्ग | हालको आवश्यकता | अर्थ | | --- | --- | --- | -| न्यूनतम | OpenCode **2.2.3** | **छविहरू** सेटिङहरू र Design विस्तारले प्रयोग गर्ने छवि सिर्जना उपकरण, Code Mode मा JavaScript कार्यहरूको सही कार्यान्वयन क्रम र मूल रिप्ले तथा कम्प्याक्सन ढाँचा; पुराना संस्करणले सुरक्षित गरेका कुराकानीहरू अद्यावधिक गरेपछि पनि पढ्न सकिन्छ। | -| सिफारिस | OpenCode **2.2.7** | योग्य ठहरिएको लक्ष्य, प्राविधिक न्यूनतमभन्दा फरक। | +| न्यूनतम | OpenCode **2.3.0** | **छविहरू** सेटिङहरू र Design विस्तारले प्रयोग गर्ने छवि सिर्जना उपकरण, Code Mode मा JavaScript कार्यहरूको सही कार्यान्वयन क्रम र मूल रिप्ले तथा कम्प्याक्सन ढाँचा; पुराना संस्करणले सुरक्षित गरेका कुराकानीहरू अद्यावधिक गरेपछि पनि पढ्न सकिन्छ। यसले सबएजेन्टका नतिजा पृष्ठभूमि रिपोर्टका रूपमा पनि पठाउँछ, जुन सबएजेन्ट कार्ड र मिसनहरूले पढ्छन्। | +| सिफारिस | OpenCode **2.3.0** | योग्य ठहरिएको लक्ष्य; हाल न्यूनतमसँग एउटै संस्करण। | | अप्रमाणित | पूर्ण जाँच नभएको नयाँ वा custom संस्करण | परीक्षण नभएकै कारण अस्वीकार हुँदैन; जोडिएको सेवाका वास्तविक API contract जाँचिन्छन्। | जडित सेवाले आवश्यक सत्र, अनुमति, फारम, आगमन-पेटिका र सत्र-वातावरण सम्झौता दिनुपर्छ। नेटिभ मिसन समयतालिकाले तालिका API, प्लगइन/प्रदायक प्याकेज र प्रभावकारी `experimental.schedules` सेटिङ पनि जाँच्छ। मिल्ने भावी संस्करणमा समेत उपलब्धता यी प्रयोग गरिने क्षमतामा निर्भर हुन्छ। सेटअपले चलिरहेको सेवा असमर्थित भने समर्थित CLI छानेर/स्थापना गरेर तयार हुँदा साझा सेवा स्पष्ट रूपमा पुनः सुरु गर्नुहोस्। diff --git a/docs/help/ne/projects.md b/docs/help/ne/projects.md index e56a2b6220..51bef180e3 100644 --- a/docs/help/ne/projects.md +++ b/docs/help/ne/projects.md @@ -34,7 +34,7 @@ | ट्याब बन्द | त्यो ट्याबको CodeNomad परियोजना जडान हटाउँछ; उही फोल्डरमा छुट्टै खोलिएको अर्को ट्याब प्रभावित हुँदैन | परियोजना फाइल वा नेटिभ इतिहास मेट्दैन, सत्र रोक्दैन वा OpenCode को Location unload गर्दैन | | सत्र रोक्ने | चयन गरिएको कुराकानीको कार्यान्वयन | परियोजना बन्द वा इतिहास मेट्दैन | -उही परियोजना जडान अर्को विन्डोमा पनि देखाइएको छ भने त्यहाँको ट्याब पनि बन्द हुन्छ र त्यो विन्डोले सूचना देखाउँछ। बन्द गर्ने विन्डोले देखाउँदैन। बन्द तुरुन्तै हुन्छ; ब्याकएन्डले परियोजना बन्द गर्न नसके त्रुटि देखिन्छ र गृह पृष्ठको **खुला परियोजनामा जानुहोस्** ले अझै त्यहाँ पुर्‍याउँछ। स्वतः पुनःप्रयास हुँदैन। बन्द गरिएको ट्याबका नपठाइएका मस्यौदा startup restoration मा राखिँदैनन्। +उही परियोजना जडान अर्को विन्डोमा पनि देखाइएको छ भने त्यहाँको ट्याब पनि बन्द हुन्छ र त्यो विन्डोले सूचना देखाउँछ। बन्द गर्ने विन्डोले देखाउँदैन। बन्द तुरुन्तै हुन्छ; ब्याकएन्डले परियोजना बन्द गर्न नसके त्रुटि देखिन्छ र गृह पृष्ठको **खुला परियोजनामा जानुहोस्** ले अझै त्यहाँ पुर्‍याउँछ। स्वतः पुनःप्रयास हुँदैन। बन्द गरिएको ट्याबका नपठाइएका मस्यौदा र संलग्नक त्यही विन्डोमा उही फोल्डर फेरि खोल्दा फर्किन्छन्; विन्डोले हालै बन्द गरिएका 16 परियोजनासम्मका लागि reload वा बन्द नहुँदासम्म तिनलाई राख्छ। तिनीहरू startup restoration को भाग होइनन्। पूरै विन्डो बन्द गर्दा, एप बन्द गर्दा वा reload गर्दा त्यसका परियोजना जडान बन्द हुँदैनन्; सामान्य startup restoration लागू रहन्छ। कार्यान्वयन सकियो भनी प्रमाणित गर्नुपरे सम्बन्धित run स्पष्ट रोक्नुहोस्। CodeNomad ले नेटिभ Location कहिल्यै unload गर्दैन; साझा-सेवा मर्मत [OpenCode सेटअप](opencode.md) मा छ। @@ -59,7 +59,7 @@ | चयन | असर | पुनःप्राप्ति | | --- | --- | --- | | राख्ने | परियोजना CodeNomad मा बन्द गर्छ, फोल्डर र कुराकानी राख्छ, अस्थायी स्थिति हटाएर recent परियोजना थप्छ | Recents बाट फेरि खोल्नुहोस्; फोल्डर सर्दैन | -| हटाउने | अस्थायी कार्यस्थानका कुराकानी र फाइल मेट्छ | Undo छैन; चाहिने कुरा पहिले अन्तै बचत गर्नुहोस् | +| हटाउने | अस्थायी कार्यस्थानका कुराकानी, फाइल र नपठाइएका मस्यौदा मेट्छ | Undo छैन; चाहिने कुरा पहिले अन्तै बचत गर्नुहोस् | | रद्द | अस्थायी कार्यस्थान खुलै राख्छ | काम जारी राख्नुहोस् वा पछि निर्णय गर्नुहोस् | कुराकानी, फाइल वा नपठाइएको मस्यौदा नभएको अछुतो अस्थायी ट्याब बन्द गर्दा चुपचाप हटाइन्छ। खुला अस्थायी ट्याब सामान्य startup restoration मा समावेश हुन्छन्, तर बन्द अस्थायी फोल्डर फेरि सुरु गर्न गृह पृष्ठमा छुट्टै सूची छैन। diff --git a/docs/help/ne/providers.md b/docs/help/ne/providers.md index fd2cb1fbff..8a5ecf62e5 100644 --- a/docs/help/ne/providers.md +++ b/docs/help/ne/providers.md @@ -56,15 +56,15 @@ OpenCode को Gemini CLI प्रमाणीकरण विधि प्र Google को [Antigravity FAQ](https://antigravity.google/docs/faq/) अनुसार Antigravity लगइनसँग तेस्रो-पक्ष सफ्टवेयर प्रयोग गर्दा यसको सेवा सर्त उल्लङ्घन हुन्छ र खाता निलम्बन वा बन्द हुन सक्छ। -`opencode` एकीकरणका सशुल्क मोडेलका लागि **OpenCode Console** ले **आज (UTC)**, **७ दिन (UTC)** र **३० दिन (UTC)** का **अनुरोधहरू** देखाउँछ। यी आजसहितका UTC पात्रोका अवधि हुन्, जुन क्रमशः आज, छ दिनअघि र २९ दिनअघि 00:00 UTC बाट सुरु हुन्छन्। **मोडेलअनुसार अनुरोधहरू · ३० दिन** मा प्रत्येक मोडेल र यसको प्रदायक देखिन्छ। गणना जडान गरिएको Console खाताको हुन्छ र सङ्ख्या एपको भाषाअनुसार ढाँचाबद्ध हुन्छ। **सेवा खाताका बजेटहरू** मा **बजेटहरू उपलब्ध छैनन्।** देखिन्छ। OpenCode Go ले आफ्नै कोटा रिडर प्रयोग गर्छ। +`opencode` एकीकरणका सशुल्क मोडेलका लागि **OpenCode Console** ले Console ले दिएअनुसार **२४ घण्टा**, **७ दिन** र **३० दिन** का **अनुरोधहरू** देखाउँछ। **मोडेलअनुसार अनुरोधहरू · ३० दिन** मा प्रत्येक मोडेल र यसको प्रदायक देखिन्छ। गणना जडान गरिएको Console खाताको हुन्छ र सङ्ख्या एपको भाषाअनुसार ढाँचाबद्ध हुन्छ। **सेवा खाताका बजेटहरू** मा **बजेटहरू उपलब्ध छैनन्।** देखिन्छ। **प्रदायक क्रेडिट मौज्दात** सक्रिय भए Console क्रेडिट मौज्दात **क्रेडिट** मा देखिन्छ। OpenCode Go ले आफ्नै कोटा रिडर प्रयोग गर्छ। रिडरले सुरक्षित गरिएको `opencode` API key वा प्राथमिकताका साथ यसको OAuth Console जडान प्रयोग गर्छ। OAuth का लागि `https://opencode.ai/console` र जडानको संगठन ID चाहिन्छ; Console पहुँचका लागि **Usage › Read** अनुमति चाहिन्छ। CodeNomad ले यी प्रमाणपत्र कहिल्यै नवीकरण गर्दैन। OAuth जडान अमान्य वा म्याद सकिएको भए, API key पनि सुरक्षित भए तापनि त्यसको स्वामीमार्फत जडान ठीक गर्नुपर्छ। Console त्रुटिले जडान नभएको, प्रमाणपत्र अमान्य वा म्याद सकिएको (401), पहुँच अस्वीकृत (403), अमान्य प्रयोग प्रतिक्रिया र नेटवर्क विफलता छुट्याउँछ। जडान त्रुटिमा **सेटिङहरू → प्रदायकहरू** खोल्नुहोस्, login र अनुमति जाँच्नुहोस् र **प्रयोग** रिफ्रेस गर्नुहोस्। कुनै सारांश वा मोडेल पृष्ठ पढ्न असफल भए पूरै Console गणना अनुपलब्ध हुन्छ। -निःशुल्क OpenCode मोडेल (`big-pickle` र `-free` मा अन्त्य हुने ID) का लागि **प्रयोग** ले जडान गरिएको Console खाताका 00:00 UTC देखिका निःशुल्क अनुरोध मात्र जोड्छ र दैनिक **800** को सन्दर्भसँग तुलना गर्छ। **अनुमानित** ले कोटा र अर्को UTC मध्यरातको रिसेट जनाउँछ; वास्तविक सीमा फरक हुन सक्छ। गणनामा सो खाताका अन्य क्लाइन्ट पनि पर्छन्। Console जडान नभए प्यानलले निःशुल्क मोडेल र कोटा हेर्न **सेटिङहरू → प्रदायकहरू** बाट जडान गर्न भन्छ। Console पढाइ असफल भए गणना अनुपलब्ध रहन्छ। +निःशुल्क OpenCode मोडेल (`big-pickle` र `-free` मा अन्त्य हुने ID) का लागि **प्रयोग** ले एउटा बार देखाउँछ: Console ले दिएको पछिल्लो २४ घण्टामा जडान गरिएको Console खाताका निःशुल्क अनुरोध, **800** को सन्दर्भसँग तुलना गरेर; वास्तविक सीमा फरक हुन सक्छ। गणनामा सो खाताका अन्य क्लाइन्ट पनि पर्छन् र यसको रिसेट समय हुँदैन। **प्रदायक क्रेडिट मौज्दात** सक्रिय भए Console क्रेडिट मौज्दात **क्रेडिट** मा देखिन्छ। Console जडान नभए प्यानलले **सेटिङहरू → प्रदायकहरू** बाट OpenCode Console जडान गर्न भन्छ। Console पढाइ असफल भए गणना अनुपलब्ध रहन्छ। -निःशुल्क चरणमा कोटा विफलता भए सो OpenCode जडानमा 00:00 UTC सम्म **सीमा समाप्त** चिन्ह लाग्छ। Console गणना उपलब्ध हुँदा गेजले १००% देखाउँछ र गणना कायम रहन्छ। चिन्ह प्रत्येक जडानको backend मेमोरीमा रहन्छ र पुनः सुरु गर्दा हट्छ। निःशुल्क प्रयोग, सीमा समाप्त चिन्ह र सशुल्क Console गणना प्रदर्शनका लागि मात्र हुन्; स्वचालित खाता छनोटले छुट्टै रिडर र नियम प्रयोग गर्छ। +निःशुल्क प्रयोग र सशुल्क Console गणना प्रदर्शनका लागि मात्र हुन्; स्वचालित खाता छनोटले छुट्टै रिडर र नियम प्रयोग गर्छ। OpenAI ले एउटा ChatGPT sign-in विधिका लागि usage दिँदैन: त्यसमा **प्रयोग** ले quota window देखाउनुको सट्टा त्यही बताउँछ। ChatGPT मा एपहरूको प्रयोग हेर्न र आफ्नो योजना तथा क्रेडिटमा तिनको पहुँच व्यवस्थापन गर्न [ChatGPT को प्रयोग हेर्नुहोस्](https://chatgpt.com/settings/usage) रोज्नुहोस्। च्याट भने चलिरहन्छ, र उही login फेरि जोड्दा reading फर्किँदैन। diff --git a/docs/help/ne/remote-access.md b/docs/help/ne/remote-access.md index 8bdebe5c42..949461f710 100644 --- a/docs/help/ne/remote-access.md +++ b/docs/help/ne/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true 9898 वा 9899 port नमान्नुहोस्: नदिएका port व्यस्त भए अर्कोमा जान सक्छन्। स्पष्ट nonzero `--https-port`, वा HTTP सक्षम हुँदा `--http-port`, ले port स्थिर गरी bind नसके असफल हुन्छ; `0` ले OS लाई चयन गर्न दिन्छ। छापिएका **Local Connection URL**, **Remote Connection URL** र ताजा **पहुँचयोग्य ठेगानाहरू** त्यस run का आधिकारिक हुन्। पूर्ण [server CLI सन्दर्भ](server.md) हेर्नुहोस्। +## प्रशासक नीति {#administrator-policy} + +प्रशासकले सुन्ने ठेगाना तोक्न सक्छ: सर्भरले प्रयोग गर्नुपर्ने ठेगानामा `CODENOMAD_LOCKED_HOST` सम्पूर्ण प्रणालीमा सेट गर्नुहोस्, त्यसपछि CodeNomad पुनः सुरु गर्नुहोस्। यसले `--host`, `CLI_HOST` र **अन्य IP हरूबाट जडान अनुमति दिनुहोस्** लाई उछिन्छ; स्विचले नतिजा देखाउँछ तर परिवर्तन गर्न सक्दैन। सहकर्मीहरूले कम्पनीको नेटवर्कबाट सर्भरमा पुग्न इन्ट्रानेट ठेगाना, वा यो कम्प्युटरमै राख्न `127.0.0.1` प्रयोग गर्नुहोस्। सबै पहुँच कम्पनीको नेटवर्कभित्रै राख्न `CODENOMAD_REMOTE_CONTROL=disabled` पनि सेट गर्नुहोस् ([रिमोट कन्ट्रोल](remote-control.md#administrator-policy))। + ## स्तरोन्नति {#upgrading} स्तरोन्नतिपछि फेरि साइन इन गर्नुहोस्। होस्टनामको उपनाम, रिभर्स प्रोक्सी वा छुट्टै होस्ट गरिएको इन्टरफेसका लागि backend मा `CODENOMAD_ALLOWED_ORIGINS` लाई इन्टरफेसका विश्वसनीय origin (स्किम, होस्टनाम र पोर्ट) मा सेट गर्नुहोस्। नेटिभ LAN क्लाइन्टले डेटा परिवर्तन गर्ने अनुरोधमा अनुमति दिइएको `Origin` हेडर पठाउनुपर्छ। यसका HTTPS origin ले host लाई tunnel बिना device pair गर्न पनि दिन्छन्; [direct HTTPS मार्फत pair गर्नुहोस्](remote-control.md#direct-https) हेर्नुहोस्। -होस्टमा सीमित कार्यका लागि loopback जडान प्रयोग गर्नुहोस्: SideCar सामग्री (`/sidecars/`) र WebSocket, Remote Control व्यवस्थापन (`/api/remote-control/`), प्लगइन ब्रिज (`/api/opencode-plugin/`), रिमोट प्रोक्सी (`/api/remote-proxy/`), सुरक्षित सर्भर व्यवस्थापन (`/api/remote-servers/`), पासवर्ड परिवर्तन र टोकनबाट प्रारम्भिक सेटअप। प्रत्यक्ष LAN पहुँचबाट साइन इन गरे पनि यी कार्यलाई loopback चाहिन्छ। सक्रिय पूर्वावलोकन सामग्री (`/previews/`) वैध क्षमता टोकनसहित प्रत्यक्ष LAN पहुँचमा उपलब्ध छ। +होस्टमा सीमित कार्यका लागि loopback जडान प्रयोग गर्नुहोस्: SideCar सामग्री (`/sidecars/`) र WebSocket, Remote Control व्यवस्थापन (`/api/remote-control/`), प्लगइन ब्रिज (`/api/opencode-plugin/`), रिमोट प्रोक्सी (`/api/remote-proxy/`), सुरक्षित सर्भर व्यवस्थापन (`/api/remote-servers/`), पासवर्ड परिवर्तन र टोकनबाट प्रारम्भिक सेटअप। प्रत्यक्ष LAN पहुँचबाट साइन इन गरे पनि यी कार्यलाई loopback चाहिन्छ। SideCars मा मात्र अपवाद छ: होस्टको **HTTPS मार्फत SideCars खोल्नुहोस्** सेटिङले विश्वसनीय HTTPS origin बाट साइन इन गरिएका ब्राउजरका लागि तिनको सामग्री र WebSocket खोल्छ ([SideCars](browser-sidecars.md#register-sidecar))। सक्रिय पूर्वावलोकन सामग्री (`/previews/`) वैध क्षमता टोकनसहित प्रत्यक्ष LAN पहुँचमा उपलब्ध छ। `/api/sidecars` दर्ता API प्रमाणीकृत प्रत्यक्ष LAN क्लाइन्ट र जोडी बनाइएका उपकरणलाई उपलब्ध रहन्छन्। होस्टमा सक्षम रहँदा Remote Control का वेब पूर्वावलोकन आफ्नो क्षमता टोकनसहित उपलब्ध रहन्छन्। diff --git a/docs/help/ne/remote-control.md b/docs/help/ne/remote-control.md index 18676e1d98..26f7259b25 100644 --- a/docs/help/ne/remote-control.md +++ b/docs/help/ne/remote-control.md @@ -86,3 +86,7 @@ CodeNomad ले [OpenTunnel](https://github.com/anomalyco/opentunnel) प्र TLS CodeNomad backend मा terminate हुन्छ। relay ले ciphertext forward गर्छ र app सामग्री पढ्न सक्दैन, तर hostname, connection timing र traffic size देख्न सक्छ। tunnel certificate/private key host मै रहन्छन्। host tunnel storage र CodeNomad configuration लाई credential झैं सुरक्षित गर्नुहोस्; अनुमान गर्न नसकिने ठेगाना authorization होइन। `CODENOMAD_REMOTE_CONTROL_API` ले self-hosted OpenTunnel API रोज्छ; unset हुँदा hosted service प्रयोग हुन्छ। यसले tunnel deployment बदल्छ, pairing आवश्यकता वा blocked सतह होइन। credential र निदान व्यवस्थापनका लागि [सुरक्षा](security.md) हेर्नुहोस्। + +## प्रशासक नीति {#administrator-policy} + +प्रशासकले कम्प्युटरका सबै प्रयोगकर्ताका लागि रिमोट कन्ट्रोल बन्द गर्न सक्छ: वातावरण चर `CODENOMAD_REMOTE_CONTROL=disabled` सम्पूर्ण प्रणालीमा सेट गर्नुहोस्, त्यसपछि CodeNomad पुनः सुरु गर्नुहोस्। ब्याकइन्डले कहिल्यै टनेल जोड्दैन, **रिमोट कन्ट्रोल सुरु गर्नुहोस्** र जोड्ने लिङ्क अस्वीकार गर्छ र सुरु हुँदा पुनः जडान गर्दैन; सेटिङहरूमा **प्रशासकद्वारा निष्क्रिय** देखिन्छ। पहिले जोडिएका उपकरणहरू जडान हुन सक्दैनन् र रद्द गर्न सकियोस् भनेर सूचीमै रहन्छन्। सेट नगरिएको वा खाली भए कुनै नीति लागू हुँदैन; अरू कुनै मान, खाली ठाउँ मात्र भए पनि, ले ब्याकइन्ड सुरु हुन दिँदैन। diff --git a/docs/help/ne/security.md b/docs/help/ne/security.md index ec7efadb9a..ee3e4b4d52 100644 --- a/docs/help/ne/security.md +++ b/docs/help/ne/security.md @@ -33,7 +33,7 @@ direct sign-in ले opaque in-memory backend session र `codenomad_session` c logout ले हालको direct session रद्द गर्छ। host मा password सफलतापूर्वक बदल्दा त्यस प्रयोगकर्ताका सबै direct session, हालको समेत, रद्द हुन्छन्; फेरि sign-in गर्नुहोस्। authenticated request नभएको 24 घण्टा वा सिर्जनादेखि सात दिनमा session म्याद सकिन्छ। सीमा बदल्न backend सुरु गर्नुअघि `CODENOMAD_SESSION_IDLE_SECONDS` र `CODENOMAD_SESSION_ABSOLUTE_SECONDS` धनात्मक पूर्णाङ्क सेकेन्डमा सेट गर्नुहोस्। Remote Control device छुट्टै रद्द गरिन्छन्। -LAN client ले sign-in, logout र project प्रयोग गर्न सक्छन्। password परिवर्तन, Remote Control व्यवस्थापन, remote-server/proxy tool र SideCars host को loopback बाट व्यवस्थापन गरिन्छन्। browser परिवर्तनमा अनुमति भएको Origin, वा त्यो नभए Referer चाहिन्छ। server का प्रकाशित origin अनुमति हुन्छन्; DNS alias, reverse proxy वा अलग होस्ट गरिएको UI का लागि `CODENOMAD_ALLOWED_ORIGINS` मा ठ्याक्कै HTTP(S) origin अल्पविरामले छुट्याएर, जस्तै `https://code.example.test,https://ui.example.test:8443`, सेट गरी restart गर्नुहोस्। path वा wildcard नराख्नुहोस्। यसले browser पहुँच दिन्छ, host अधिकार होइन। native LAN client ले पनि परिवर्तन गर्दा अनुमति भएको Origin पठाउनुपर्छ। loopback बाट जोडिएको विश्वसनीय proxy सँग host अधिकार हुन्छ र आफ्नै पहुँच नियन्त्रण चाहिन्छ। server loopback वा सबै interface मा listen गर्दा, host मा उही scheme र port सहित `localhost` बाट खोलिएको UI पनि चल्छ। +LAN client ले sign-in, logout र project प्रयोग गर्न सक्छन्। password परिवर्तन, Remote Control व्यवस्थापन, remote-server/proxy tool र SideCars host को loopback बाट व्यवस्थापन गरिन्छन्। होस्टको **HTTPS मार्फत SideCars खोल्नुहोस्** सेटिङले विश्वसनीय HTTPS origin बाट साइन इन गरिएका ब्राउजरका लागि SideCars खोल्छ; ती ठेगानाका सबै प्रयोगकर्ताले तपाईंका SideCar सेवा प्रयोग गर्न पाउने भए मात्र यसलाई सक्रिय गर्नुहोस्। browser परिवर्तनमा अनुमति भएको Origin, वा त्यो नभए Referer चाहिन्छ। server का प्रकाशित origin अनुमति हुन्छन्; DNS alias, reverse proxy वा अलग होस्ट गरिएको UI का लागि `CODENOMAD_ALLOWED_ORIGINS` मा ठ्याक्कै HTTP(S) origin अल्पविरामले छुट्याएर, जस्तै `https://code.example.test,https://ui.example.test:8443`, सेट गरी restart गर्नुहोस्। path वा wildcard नराख्नुहोस्। यसले browser पहुँच दिन्छ, host अधिकार होइन। native LAN client ले पनि परिवर्तन गर्दा अनुमति भएको Origin पठाउनुपर्छ। loopback बाट जोडिएको विश्वसनीय proxy सँग host अधिकार हुन्छ र आफ्नै पहुँच नियन्त्रण चाहिन्छ। server loopback वा सबै interface मा listen गर्दा, host मा उही scheme र port सहित `localhost` बाट खोलिएको UI पनि चल्छ। compromise शङ्का भए: diff --git a/docs/help/ne/server.md b/docs/help/ne/server.md index 28d277c2b5..dbf895c5de 100644 --- a/docs/help/ne/server.md +++ b/docs/help/ne/server.md @@ -8,7 +8,7 @@ project र tool भएको ठाउँमा CodeNomad चलाएर स 1. Node.js 24 LTS र npm स्थापना गर्नुहोस्; repository को build runtime `.node-version` मा pinned छ। desktop package ले आफ्नै runtime दिन्छ: Electron ले यसको integrated Node प्रयोग गर्छ, Tauri ले Node समावेश गर्छ र दुवैमा npm हुन्छ। 2. Git लाई **backend प्रक्रियाको PATH** मा राख्नुहोस्। WSL भित्रको Git मात्र Windows backend का लागि पुग्दैन। -3. OpenCode स्थापना वा चयन गर्नुहोस्: आवश्यक न्यूनतम **2.2.3**, सिफारिस qualification लक्ष्य **2.2.7**। नयाँ/custom build मा compatibility जाँच हुन्छ, tested-version allowlist होइन। [OpenCode सेटअप](opencode.md) हेर्नुहोस्। +3. OpenCode स्थापना वा चयन गर्नुहोस्: आवश्यक न्यूनतम **2.3.0**, सिफारिस qualification लक्ष्य **2.3.0**। नयाँ/custom build मा compatibility जाँच हुन्छ, tested-version allowlist होइन। [OpenCode सेटअप](opencode.md) हेर्नुहोस्। 4. server सुरु गर्ने फोल्डर रोज्नुहोस्, वा `--workspace-root` स्पष्ट दिनुहोस्। Git बिना स्पष्ट खोलिएको physical folder मा मात्र कुराकानी उपलब्ध हुन्छन्; Git र worktree कार्य असफल हुन्छन्। Git स्थापना र PATH परिवर्तनपछि backend restart गर्नुहोस्। workspace root ले opening/browsing सीमित गर्छ, agent execution होइन: [सुरक्षा](security.md) हेर्नुहोस्। @@ -104,6 +104,8 @@ flag ले environment counterpart override गर्छन्। value-taking | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; release offer का लागि query गरिने repository। | | `CODENOMAD_REMOTE_CONTROL_API` | unset: hosted OpenTunnel API। self-hosted relay deployment का लागि API origin सेट गर्नुहोस्। | +| `CODENOMAD_REMOTE_CONTROL` | सेट नगरिएको: प्रयोगकर्ताले रिमोट कन्ट्रोल सुरु गर्न सक्छन्। `disabled`: प्रशासकद्वारा बन्द ([नीति](remote-control.md#administrator-policy)); सेट नगरिएको वा खाली: कुनै नीति छैन, अरू कुनै मान (खाली ठाउँसमेत) ले सुरु हुन दिँदैन। | +| `CODENOMAD_LOCKED_HOST` | सेट नगरिएको वा खाली: `--host` लागू हुन्छ; खाली ठाउँ मात्र भए सुरु हुँदैन। ठेगाना: `--host`, `CLI_HOST` वा सुन्ने स्विच जे भए पनि सर्भर त्यहीँ सुन्छ ([नीति](remote-access.md#administrator-policy))। | | `NODE_EXTRA_CA_CERTS` | Node को ऐच्छिक additional CA file; missing OpenCode daemon सुरु गर्दा allowed startup environment सँग पठाइन्छ। चलिरहेको daemon बदल्दैन। | provider-specific usage credential [प्रदायक](providers.md) मा छन्। desktop data-profile चयन [डेस्कटप](desktop.md) मा छ, release feed ले नियन्त्रण गर्दैन। diff --git a/docs/help/ne/settings.md b/docs/help/ne/settings.md index 58253172f4..e9d628a711 100644 --- a/docs/help/ne/settings.md +++ b/docs/help/ne/settings.md @@ -70,7 +70,7 @@ 2. दायाँ प्यानलमा **दायाँ प्यानल अनुकूलन गर्नुहोस्** खोल्नुहोस्। built-in ट्याब र Status खण्ड रोज्न checkbox प्रयोग गर्नुहोस्; कम्तीमा एउटा Status खण्ड देखिइरहन्छ। धेरैलाई एकैपटक मिलाउन यी checkbox हरूमाथि ड्र्याग गर्नुहोस्। 3. क्रम बदल्न right-panel ट्याब तान्नुहोस्। built-in लेआउट चयन फर्काउन **रिसेट गर्नुहोस्** प्रयोग गर्नुहोस्। -पहिचान गरिएका [एकीकरण](integrations.md#integration-sections) का पनि स्थिति खण्ड हुन्छन्। उही checkbox बाट लुकाउनुहोस्; कुनै पनि स्थिति खण्ड तानेर वा माथि/तल कुञ्जीले क्रम बदल्नुहोस्। दृश्यता र क्रम पुनः लोड हुँदा र एकीकरण अस्थायी रूपमा नहुँदा पनि सुरक्षित रहन्छन्। +कुनै पनि स्थिति खण्ड तानेर वा माथि/तल कुञ्जीले क्रम बदल्नुहोस्। दृश्यता र क्रम पुनः लोड हुँदा पनि सुरक्षित रहन्छन्। Status मा token जानकारी, Yolo मोड, provider Usage, background shell, MCP र Plugins छन्। कुराकानीमा [लक्ष्य](conversations.md#goal) रहुन्जेल यी खण्डहरूमाथि लक्ष्य लाइनले त्यसलाई देखाउँछ; त्यो लाइन खण्ड होइन र लुकाउन वा सार्न मिल्दैन। खण्ड लुकाउँदा सेवा अक्षम वा अनुमति खारेज हुँदैन। साँघुरो लेआउटले कुराकानी खुम्च्याउनुको सट्टा नअट्ने प्यानल बन्द गर्छ; त्यहाँ खोलिएको प्यानल कुराकानीमाथि तैरिन्छ, र एउटा floating प्यानल खोल्दा अर्को बन्द हुन्छ। diff --git a/docs/help/ne/troubleshooting.md b/docs/help/ne/troubleshooting.md index f9cfcccd47..16ec513def 100644 --- a/docs/help/ne/troubleshooting.md +++ b/docs/help/ne/troubleshooting.md @@ -42,7 +42,7 @@ owned worktree वा conversation placement verify गर्न नसके ## OpenCode runtime र WSL {#opencode-runtime} 1. **प्राथमिकताहरू → OpenCode** खोली **OpenCode संस्करण** card (installed version र running service status), त्यसपछि **OpenCode बाइनरी** अन्तर्गतको selected executable जाँच्नुहोस्। -2. आवश्यक runtime नभए समर्थित installation/update प्रयोग गर्नुहोस्। हालको minimum: **2.2.3**; recommended/qualified संस्करण: **2.2.7**। +2. आवश्यक runtime नभए समर्थित installation/update प्रयोग गर्नुहोस्। हालको minimum: **2.3.0**; recommended/qualified संस्करण: **2.3.0**। 3. installed CLI running service भन्दा फरक भए shared service restart गर्ने कि स्पष्ट निर्णय गर्नुहोस्। **OpenCode सेवा पुनः सुरु गर्नुहोस्** **समस्या समाधान** अन्तर्गत उपलब्ध छ र पुष्टि चाहिन्छ। हरेक connected client को सक्रिय काम interrupt गर्छ, तर session history राख्छ। configuration reload छुट्टै हो: process राख्छ तर loaded Location पुनर्निर्माण र pending question/permission रद्द गर्छ। कुनै हानिरहित refresh होइन। diff --git a/docs/help/ru/browser-sidecars.md b/docs/help/ru/browser-sidecars.md index b2d0e6076b..83bb62c624 100644 --- a/docs/help/ru/browser-sidecars.md +++ b/docs/help/ru/browser-sidecars.md @@ -77,7 +77,7 @@ Service workers в удалённых предпросмотрах отключ SideCar — доверенное расширение CodeNomad, а не изолированный предпросмотр: его страница работает в собственном источнике (origin) CodeNomad, поэтому её скрипты могут пользоваться CodeNomad с вашим выполненным входом. Регистрируйте только службы, коду которых доверяете. CodeNomad не передаёт службе собственные cookies входа, а cookies самой службы сохраняются. -Содержимое SideCar (`/sidecars/`) и WebSocket SideCar требуют loopback-подключения на хосте. Регистрация через `/api/sidecars` доступна сопряжённым устройствам и аутентифицированным прямым LAN-клиентам. Содержимое активных предпросмотров (`/previews/`) доступно через прямой LAN-доступ с действительным токеном доступа; веб-предпросмотры [удалённого управления](remote-control.md#remote-surface) остаются доступны с токеном доступа, пока включены. Требования прямого доступа см. в разделе [Обновление](remote-access.md#upgrading). +Содержимое SideCar (`/sidecars/`) и WebSocket SideCar требуют loopback-подключения на хосте. Чтобы открывать их и с других устройств, включите на хосте **Открывать SideCars по HTTPS** в **Настройки → SideCars**: тогда браузеры, выполнившие вход через HTTPS-адреса этого сервера или HTTPS-источник из `CODENOMAD_ALLOWED_ORIGINS`, например за обратным прокси с TLS, смогут открывать SideCars. Обычный HTTP, адреса `localhost` и удалённое управление остаются доступны только на хосте. Регистрация через `/api/sidecars` доступна сопряжённым устройствам и аутентифицированным прямым LAN-клиентам. Содержимое активных предпросмотров (`/previews/`) доступно через прямой LAN-доступ с действительным токеном доступа; веб-предпросмотры [удалённого управления](remote-control.md#remote-surface) остаются доступны с токеном доступа, пока включены. Требования прямого доступа см. в разделе [Обновление](remote-access.md#upgrading). ## Пример OpenVSCode Server {#openvscode} diff --git a/docs/help/ru/conversations.md b/docs/help/ru/conversations.md index e1155b6d47..f3947ac525 100644 --- a/docs/help/ru/conversations.md +++ b/docs/help/ru/conversations.md @@ -60,6 +60,12 @@ CodeNomad представляет нативные сессии OpenCode как Черновики — клиентское рабочее состояние, а не общие нативные сообщения. Восстановление при запуске может сохранять поддерживаемое состояние поля ввода, но не считайте неотправленный черновик или вложение резервной копией и не предполагайте их наличие на другом устройстве. Сохраните важный текст перед очисткой данных запуска или закрытием клиента с отключённым восстановлением; см. [настольное приложение](desktop.md). +## Открытие файлов из ответов {#open-files-from-replies} + +1. Ответы агента ссылаются на файлы проекта относительными и абсолютными путями. +2. Обычный щелчок открывает связанный файл в просмотре файла, читая его из рабочего дерева беседы. +3. Щелчки с модификаторами (Ctrl/⌘, Shift, средняя кнопка) и ссылки вне рабочего дерева сессии сохраняют обычное поведение ссылок. + ## Команды и режим Shell {#commands-shell} 1. Введите `/`, выберите обнаруженную пользовательскую команду и укажите аргументы. diff --git a/docs/help/ru/install.md b/docs/help/ru/install.md index 2a9161165b..ee83cd29e1 100644 --- a/docs/help/ru/install.md +++ b/docs/help/ru/install.md @@ -45,7 +45,7 @@ chmod +x CodeNomad-Tauri-linux-x64-.AppImage | Требование | Где должно быть доступно | Текущее требование | | --- | --- | --- | -| OpenCode CLI | Выбранный хост выполнения, включая выбранный дистрибутив WSL, если применимо | Минимум **2.2.3**; **2.2.7** — рекомендуемая/проверенная цель. Для новых и пользовательских версий проверяются контракты, а не вводится запрет на непроверенные версии. | +| OpenCode CLI | Выбранный хост выполнения, включая выбранный дистрибутив WSL, если применимо | Минимум **2.3.0**; **2.3.0** — рекомендуемая/проверенная цель. Для новых и пользовательских версий проверяются контракты, а не вводится запрет на непроверенные версии. | | Git | `PATH` учётной записи серверной части CodeNomad | Необходим для идентификации репозитория, операций Git и worktree. | | Node.js/npm | Хост отдельного сервера и сборки из исходников | Node.js 24 LTS; воспроизводимые сборки из исходников используют версию, закреплённую в `.node-version`. Настольные релизы содержат свою среду: встроенный Node Electron или Node из комплекта Tauri, с npm. | | Папка рабочего пространства | Диск, доступный серверной части | Явно открытая физическая папка, а не локальная папка устройства, предполагаемая удалённым браузером. | diff --git a/docs/help/ru/integrations.md b/docs/help/ru/integrations.md index 9ecde7fd0f..85540148bb 100644 --- a/docs/help/ru/integrations.md +++ b/docs/help/ru/integrations.md @@ -27,7 +27,7 @@ CodeNomad предоставляет нативные подключения MCP Плагины под управлением CodeNomad скрыты из обычного списка и его элементов активации, обновления и удаления. CodeNomad распознаёт их по проверенной записи установщика и расположению кода, адресуемого по хешу содержимого; сторонний плагин с тем же именем или ID сохраняет обычные элементы управления. -Если управляемый плагин отключён, завершил загрузку с ошибкой или его загрузка ещё не подтверждена, над списком появляется **Плагины CodeNomad требуют внимания**. Откройте его кнопку **i** (**Сведения о** плагине), чтобы увидеть доступную ошибку и ссылку на неё в журнале OpenCode. Только отключённый плагин предлагает **Включить снова**: действие добавляет положительное правило активации для точного ID, сохраняя отключающее правило. Запись выполняется в области отключающего правила — **Глобально** или **Проект**, — если она доступна для записи, иначе в области **Проект**. OpenCode продолжает работать; предупреждение остаётся, пока нативные события или **Обновить управление плагинами** не подтвердят активное состояние плагина. +Если управляемый плагин отключён, завершил загрузку с ошибкой или его загрузка ещё не подтверждена, над списком появляется **Плагины CodeNomad требуют внимания**. Откройте его кнопку **i** (**Сведения о** плагине), чтобы увидеть доступную ошибку и ссылку на неё в журнале OpenCode. Только отключённый плагин предлагает **Включить снова**: действие удаляет из этого файла точное отключающее правило плагина, если этого достаточно для повторного включения, а иначе добавляет положительное правило для точного ID. Запись выполняется в области отключающего правила — **Глобально** или **Проект**, — если она доступна для записи, иначе в области **Проект**. OpenCode продолжает работать; предупреждение остаётся, пока нативные события или **Обновить управление плагинами** не подтвердят активное состояние плагина. Предупреждение и его сведения обозначают источник конфигурации как **Унаследованная / внешняя** или **Виртуальная конфигурация**, когда это применимо. Отдельная метка **Проект** указывает область повторного включения, если она отличается от источника отключающего правила. @@ -38,7 +38,7 @@ CodeNomad предоставляет нативные подключения MCP Глобальная область — обнаруженная глобальная конфигурация подключённого демона. Проектная — конфигурация внутри активной Location, а не унаследованный родительский файл. Более позднее правило проекта может переопределить глобальное; глобальный переключатель всё равно показывает глобальное правило, не выдавая его за итоговое состояние проекта. Без проектного правила проект наследует разрешённое глобальное состояние. -Переключатели добавляют точные правила активации с сохранением объявлений источников и остальной конфигурации. Они не редактируют параметры плагина, не устанавливают пакеты и не удаляют файлы. Встроенные плагины OpenCode не предлагаются как пользовательские переключатели активации. Проект недоступен, если его цель нельзя безопасно отделить от глобальной или она вышла бы за активную Location. +Каждый переключатель записывает одно точное правило активации плагина в файл своей области, заменяя там прежние точные правила этого плагина, или только удаляет их, если результат тот же. Объявления источников, более широкие правила вроде `*` и остальная конфигурация сохраняются. Они не редактируют параметры плагина, не устанавливают пакеты и не удаляют файлы. Встроенные плагины OpenCode не предлагаются как пользовательские переключатели активации. Проект недоступен, если его цель нельзя безопасно отделить от глобальной или она вышла бы за активную Location. Обновление пакета меняет этот пакет в общем кэше OpenCode для каждой Location, где он используется, как указано в его подсказке; оно не меняет правила активации, не перезапускает OpenCode и не перезагружает конфигурацию. У локальных, встроенных и предоставленных SDK плагинов нет действия с пакетом. Пакет, давший сбой до сообщения ID своего плагина, показывается по имени пакета: сбой описан в подсказке, действия проверки/обновления есть, а переключателей активации нет. О неудачной проверке или обновлении сообщается, и они никогда не повторяются автоматически. @@ -78,38 +78,30 @@ CodeNomad предоставляет нативные подключения MCP Команды обнаруживаются в OpenCode для активной Location. Их собственное нативное определение может выбирать поведение выполнения; меню — не установщик пакетов и не неограниченный редактор конфигурации. CodeNomad применяет окружение сессии профиля перед отправкой нативной пользовательской команды; сбой обновления окружения блокирует отправку. `/btw` — отдельная временная процедура вопроса CodeNomad, а не обычная пользовательская команда. Определения команд и наследование нативной конфигурации см. в [документации команд OpenCode](https://opencode.ai/v2/docs/commands/). После изменений конфигурации сначала обновите/снова откройте нужную поверхность; используйте явную перезагрузку конфигурации только при необходимости для среды выполнения. Никогда не повторяйте возможно допущенную команду лишь для обновления её отображения. -## Разделы интеграций в Статусе {#integration-sections} +## Интеграции в Плагинах {#integration-rows} В **Статус → Плагины** меню **+** предлагает **Добавить интеграцию…** или **Добавить плагин…**. Выбор интеграций содержит неустановленные записи проверенного каталога. Выберите область и **Установить**: CodeNomad устанавливает выбранный ID каталога. Нативные интеграции используют **Только глобально**. **Каталог недоступен** предлагает **Обновить**; **Каталог от {date}** обозначает последний корректный устаревший каталог. -Каждая распознанная интеграция с объявлением или загруженным/ошибочным плагином имеет свой раздел в **Статусе**, в том числе отключённая или устанавливаемая. Неоднозначный источник показывает **Не соответствует** в Плагинах. Каждая интеграция сохраняет строку Плагинов с обновлением пакета, удалением и обновлением состояния. Разверните раздел, чтобы увидеть версию и управление плагином в его содержимом; имя и статус остаются в заголовке рядом с **Документация** и **i**. Всплывающее окно **i** показывает пояснения по запросу: Enter/Пробел открывает, Escape закрывает. +У распознанной интеграции одна строка в **Статус → Плагины** с её названием (например, **OpenCode for Blender**) и версией. Её переключатели **Глобально** и **Проект** окрашены в акцентный цвет, как остальные переключатели, у обычного плагина — зелёные; интеграция с частью внутри приложения работает **Только глобально**. Наведите указатель на название: сведения начинаются со слова **Интеграция** вместо **Плагин**; программы чтения с экрана читают их как описание строки. Неоднозначный источник показывает **Не соответствует**. -Настройка Статуса позволяет скрывать все его разделы и менять порядок перетаскиванием или клавишами Вверх/Вниз. Видимость и порядок сохраняются при перезагрузке и временном отсутствии интеграции. При исчезновении раздела с фокусом фокус возвращается к Плагинам, а если они скрыты — к другому видимому разделу Статуса. +Под названием строка состояния всегда показывает, в каком состоянии интеграция. Серый текст сообщает; текст акцентного цвета — это кнопка. Для интеграции с частью внутри приложения показывается самое важное состояние: **Установить в Blender** или **Обновить Blender**, если части нет или она устарела (с подтверждением установки), несовместимость цветом предупреждения, значок цепочки и документ, если открытая беседа подключена (выберите, чтобы отсоединить), **Blender закрыт**, **Blender: нет открытых документов**, **Беседа не открыта**, затем **Подключить** с именем документа или **Подключить…**, чтобы выбрать из нескольких документов. Беседа также подключается сама, когда её агент впервые использует интеграцию. MCP-интеграции редакторов показывают **Сервер обнаружен** или **Сервер не найден**, API-интеграции — **Подключено** или **Отключено**. Длинное состояние сокращается; наведите указатель, чтобы увидеть весь текст. Изменения, о которых сообщает интеграция, и переподключения обновляют строку. -Установка из каталога, установка/обновление части приложения, подключение и удаление требуют подтверждения. Сначала фокус получает **Отмена**; действие подтверждения доступно через 600 мс. Активация и обновление плагина выполняются напрямую. +Меню **…** строки начинается с состояния соединения, например **Blender: 1 открытый документ** или **Blender закрыт**. Затем оно предлагает **Документация**, **Установить в приложение…**, **Обновить приложение…** или **Переустановить в приложение…** ([см. ниже](#application-installation)), проверку обновлений пакета, **Удалить (Глобально)** или **Удалить (Проект)** и **Обновить управление плагинами**. Отсоединение выполняется одним щелчком без подтверждения и касается только этой беседы: приложение остаётся открытым, его часть установленной, а другие беседы сохраняют подключение. Если ответ потерян, строка снова читает состояние; запрос никогда не повторяется. -## Подключить открытое приложение {#application-attachment} +Установка из каталога, установка или обновление части в приложении и удаление требуют подтверждения. Сначала фокус получает **Отмена**; действие подтверждения становится доступным через 600 мс. Активация, обновления плагинов, подключение и отсоединение выполняются сразу. -Предложите документ через интеграцию в приложении, откройте **Статус → интеграция → Разговор** и выберите **Подключить…**. Этот раздел управляет подключением отображаемого разговора. Выберите приложение и документ, проверьте целевой разговор и предупреждение об изменениях, затем подтвердите кнопкой **Подключить**. Приложение работает на машине OpenCode, в том числе при удалённом доступе. Неподдерживаемый хост, включая WSL, предлагает справку через **i**. - -Строка **Разговор** считывает подключение отображаемого разговора. **Подключение неизвестно** предлагает **Обновить**. После свежего авторитетного чтения, подтверждающего подключение, **Отключить** заменяет **Подключить…**. Один щелчок отключает только этот разговор без дополнительного подтверждения; приложение остаётся открытым, его часть установленной, а другие разговоры сохраняют подключения. Нативные изменения и переподключения обновляют состояние. - -Принятое действие сохраняет результат или ошибку, пока показан целевой разговор; переход закрывает квитанцию. Текущее подключение определяется авторитетным чтением. **Состояние неизвестно** после потери ответа, тайм-аута или разрыва связи предлагает **Обновить** для чтения фактического состояния. Никогда не повторяйте запрос ради обновления экрана. - -После явного чтения открытых приложений в окне выбора сохранённые метаданные Q8 могут предложить **Повторно подключить** в окне выбора или строке **Разговор** для той же интеграции и проверенной метки документа, пока проект, разговор и поколение соединения остаются прежними. Повторное подключение требует явного подтверждения; переход или признание данных устаревшими удаляет подсказку. Авторитетные сведения о текущем подключении поступают из чтения интеграции для конкретного сеанса. - -Удаление из раздела интеграции или её строки Плагинов использует то же объявление и подтверждение области. Оно выполняется без переписи разговоров или автоматического отключения. +Удаление выполняется без переписи бесед и автоматического отсоединения. Перед удалением предупреждение называет плагин и точную область. Фокус получает **Отмена**; **Удалить (Глобально/Проект)** доступно через 600 мс и требует явного действия. Удаление может прервать доступность и подключения в использующих плагин беседах; глобальная область может затронуть другие проекты. Отмена, истечение срока или переход до отправки ничего не меняют. Удаляется только подтверждённое объявление; правила, кэш, файлы приложения и сохранённые подсказки подключения остаются. Изменение конфигурации требует нового выбора и подтверждения. Успех означает удаление объявления; состояние исполнения следует перезагрузке OpenCode. При потере ответа обновите плагины и проверьте конфигурацию перед новой попыткой. Переустановка может восстановить доступность; возможны перезагрузка или повторное подключение, а прерванные операции могут не возобновиться. ## Установить или обновить интеграцию приложения {#application-installation} -В **Статус → интеграция → Приложение** выберите **Установить в приложение…** или **Обновить приложение…**, когда свежий статус предлагает действие. Оно доступно без разговора или предложенного документа. Если приложение закрыто, откройте его для проверки части приложения; **i** показывает сведения о машине и требованиях. +В **Статус → Плагины** выберите **Установить в Blender** или **Обновить Blender** в строке состояния интеграции, когда её актуальное состояние предлагает это действие, или **Установить в приложение…**, **Обновить приложение…** либо **Переустановить в приложение…** в её меню **…**. Переустановка заново записывает часть в приложении, открыто оно или закрыто. Действие доступно без беседы и открытого документа. В подтверждении указаны приложение и **версия пакета интеграции**, предоставляющего установщик. Проверьте оба значения и предупреждение о машине: установка выполняется там, где работает OpenCode; машина может быть удалённой. Начальный фокус — на **Отмена**. Для продолжения требуется явное подтверждение. Смена проекта, Location или разговора, переподключение либо соответствующие нативные изменения до подтверждения отменяют ожидающее согласие; откройте действие снова для проверки свежих сведений. В WSL установка в приложение всегда отклоняется, даже если открытое приложение выглядит совместимым. Откройте приложение на поддерживаемой машине. -Результат сообщает, что интеграция установлена, обновлена, уже актуальна, установка отклонена или завершилась сбоем. После установки или обновления откройте приложение и проверьте его интеграцию; подключите разговор отдельно через [Подключить открытое приложение](#application-attachment). Успех установки описывает запрос установщика; доступность работающего приложения определяется его статусом. +Результат сообщает, что часть в приложении установлена, обновлена, уже актуальна, отклонена или не установлена из-за ошибки. После установки или обновления откройте приложение и проверьте его интеграцию. Успех установки описывает запрос к установщику; реальная доступность приложения определяется его состоянием. Запросы никогда не повторяются автоматически. После отказа или сбоя проверьте приложение перед выбором нового действия. Если ошибка оставляет результат неизвестным, не повторяйте этот запрос: сначала проверьте приложение, затем при необходимости начните новое действие с новым подтверждением. diff --git a/docs/help/ru/missions.md b/docs/help/ru/missions.md index 1bb7701dc1..ca76535893 100644 --- a/docs/help/ru/missions.md +++ b/docs/help/ru/missions.md @@ -42,7 +42,7 @@ ### Запускать автоматически {#automatic-start} -**Запускать автоматически** находится вне Расписания и по умолчанию выключено. Выключенное создаёт миссию на паузе для последующего ▶ запуска. Включённое запрашивает старт после подтверждения создания с обычными проверками и необходимым согласием на нативные настройки. +**Запускать автоматически** находится вне Расписания и по умолчанию выключено. Выключенное создаёт миссию на паузе для последующего ▶ запуска. Включённое запрашивает старт после подтверждения создания с обычными проверками и автоматической подготовкой расписания. Если подтверждение потеряно, чтение квитанции оставляет запуск ручным. Сохраняйте исходный неподтверждённый запрос; перед повторным созданием проверьте список и разговор. @@ -56,6 +56,8 @@ Доступны однократный запуск сейчас, каждые N часов, ежедневно, дни недели, день месяца и cron. Используется сохранённый пояс; поле пояса появляется при отличии от системного. Месяцы без выбранного дня пропускаются. Однократный запуск получает время при старте; условие может израсходовать единственную возможность без запуска. Нужны доступные служба OpenCode и узел исполнения. +При запуске или возобновлении расписание автоматически подготавливается в конфигурации OpenCode проекта. Явное OFF сохраняется: **Открыть настройки расписания**, если доступно, открывает ответственный файл; **i** показывает источник или сведения об окружении. Нажатая кнопка показывает загрузку только во время запроса. Неподтверждённый результат можно проверить; после восстановления активации запуск остаётся явным действием. + ### События и сочетания {#scheduling-conditions} Выберите **Активность репозитория → Событие**, затем дополнительные фильтры в той же карточке. Коммиты Git находятся в одном меню с событиями автоматически определённого репозитория GitHub, GitLab или Gitea, как в Contribute (`upstream`, затем `origin`). Все три поддерживают новые и объединённые PR/MR и новые задачи с необязательным **Автором**, включая `dependabot[bot]`. Выбор события фиксирует репозиторий; сохранённые критерии сохраняют цель. @@ -88,9 +90,11 @@ ### Цвета и состояния {#status-colours} -Флаг показывает миссию, шеврон — внимание её задач; повторяющиеся записи имеют значок повтора. Красный ждёт ответа, пульсирующий жёлтый означает наблюдаемую работу, оранжевый — паузу/прерывание, зелёный — непросмотренный результат, синий — подготовку или незапущенную задачу. +Флаг показывает миссию, шеврон — внимание её задач; повторяющиеся записи имеют значок повтора. Красный ждёт ответа, пульсирующий жёлтый означает наблюдаемую работу. Оранжевый символ паузы обозначает паузу, оранжевый предупреждающий треугольник — прерывание. Зелёный отмечает миссию, задачу или успешный запуск, ожидающий просмотра. + +Акцентный значок с небольшой неподвижной нейтральной чертой снизу означает **Ожидание запуска по расписанию**: следующее пробуждение подтверждено. Акцентный цвет зависит от палитры. Значок без черты обозначает подготовку или незапущенную задачу. Просмотренные завершения, остановленные расписания и **Состояние не подтверждено** нейтральны; читайте текст состояния. -Выбор, щелчок/проведение по зелёным значкам задач или отметка прочитанным в меню шеврона подтверждает результаты. Блокировка не всегда вопрос; отчёт не доказывает завершение всех нативных операций. Отозванные задачи остаются в истории. +Выбор или щелчок/проведение по зелёным значкам задач подтверждает результаты; меню шеврона предлагает **Отметить как прочитанное**. Для **Успешный запуск для просмотра** явно выберите повторяющуюся строку в активном окне или нажмите **Отметить как прочитанное**, подтверждая именно этот запуск. При активном расписании значок возвращается к ожиданию, иначе — к нейтральному виду. Восстановленный выбор и новые результаты в уже выбранной строке сохраняют новый результат непрочитанным. Исторические успехи при первой загрузке считаются прочитанными. Отозванные задачи остаются в истории. ### Вопросы и решения {#questions} diff --git a/docs/help/ru/mobile.md b/docs/help/ru/mobile.md index 76ba5835f2..33f5e9e9bf 100644 --- a/docs/help/ru/mobile.md +++ b/docs/help/ru/mobile.md @@ -42,3 +42,5 @@ | Работа без сети | Нет автономной серверной части или кэшированной истории API. Статические ресурсы интерфейса могут кэшироваться, но документы и ответы API не являются автономным рабочим пространством. | Поддерживайте доступность серверной части. Приостановка мобильной ОС или смена сети могут разорвать поток событий; возврат переподключает и читает текущее состояние без гарантированного повтора событий. Проверьте завершение действия перед повтором. Закрытие PWA не останавливает отдельную серверную часть; выход из настольного приложения хоста и его серверной части делает удалённое управление недоступным до следующего запуска. + +Каждая вкладка браузера, включая установленное PWA, хранит для себя открытые проекты, выбранные беседы, неотправленные черновики и позиции прокрутки: они возвращаются, когда страница перезагружается или когда мобильная ОС перезагружает её после переключения приложений или блокировки экрана. Новая вкладка или PWA, полностью закрытое системой, открывается на главной странице. Отключите это для вкладки в **Настройки → Общие → Восстанавливать предыдущее состояние**. diff --git a/docs/help/ru/opencode.md b/docs/help/ru/opencode.md index 2ce45a483a..505b96936d 100644 --- a/docs/help/ru/opencode.md +++ b/docs/help/ru/opencode.md @@ -19,8 +19,8 @@ CodeNomad подключается к общей службе OpenCode на хо | Классификация | Текущее требование | Значение | | --- | --- | --- | -| Минимум | OpenCode **2.2.3** | Инструмент генерации изображений, который используют настройки **Изображения** и расширение Design, а также правильный порядок выполнения задач JavaScript в Code Mode и нативный формат воспроизведения и сжатия; беседы, сохранённые более ранними версиями, остаются доступными после обновления. | -| Рекомендуемая | OpenCode **2.2.7** | Проверенная цель, отличная от технического минимума. | +| Минимум | OpenCode **2.3.0** | Инструмент генерации изображений, который используют настройки **Изображения** и расширение Design, а также правильный порядок выполнения задач JavaScript в Code Mode и нативный формат воспроизведения и сжатия; беседы, сохранённые более ранними версиями, остаются доступными после обновления. Она также передаёт результаты субагентов фоновыми отчётами, которые читают карточки субагентов и Миссии. | +| Рекомендуемая | OpenCode **2.3.0** | Проверенная цель; сейчас та же версия, что и минимум. | | Непроверенная | Новая или пользовательская версия, не прошедшая полную проверку | Не отклоняется лишь из-за отсутствия тестирования; проверяются реальные API-контракты подключённой службы. | Подключённая служба должна предоставлять необходимые контракты сессий, разрешений, форм, входящих и окружения сессий. Нативное расписание Миссий также проверяет API расписаний, комплект плагина/провайдера и действующую настройку `experimental.schedules`. Доступность определяется этими используемыми возможностями, включая совместимые будущие версии. Если настройка сообщает о неподдерживаемой работающей службе, выберите/установите поддерживаемый CLI и выполните явный перезапуск общей службы, когда будете готовы. diff --git a/docs/help/ru/projects.md b/docs/help/ru/projects.md index 63fc0d706a..bac8f8ecd8 100644 --- a/docs/help/ru/projects.md +++ b/docs/help/ru/projects.md @@ -34,7 +34,7 @@ | Закрыть вкладку | Убирает подключение CodeNomad к проекту этой вкладки; отдельно открытая вкладка той же папки не затрагивается | Не удаляет файлы проекта или нативную историю, не останавливает сессии и не выгружает Location из OpenCode | | Остановить сессию | Выполнение выбранного разговора | Не закрывает проект и не удаляет историю | -Если то же подключение проекта показано в другом окне, его вкладка тоже закрывается, и это окно показывает уведомление. Окно, начавшее закрытие, уведомления не показывает. Закрытие происходит сразу; если серверная часть не может закрыть проект, появляется ошибка, а **Перейти к открытому проекту** на главной странице по-прежнему ведёт к нему. Автоматического повтора нет. Неотправленные черновики закрытой вкладки не сохраняются для восстановления при запуске. +Если то же подключение проекта показано в другом окне, его вкладка тоже закрывается, и это окно показывает уведомление. Окно, начавшее закрытие, уведомления не показывает. Закрытие происходит сразу; если серверная часть не может закрыть проект, появляется ошибка, а **Перейти к открытому проекту** на главной странице по-прежнему ведёт к нему. Автоматического повтора нет. Неотправленные черновики и вложения закрытой вкладки возвращаются, когда вы снова открываете ту же папку в этом окне; окно хранит их для 16 последних закрытых проектов, пока его не перезагрузят или не закроют. В восстановление при запуске они не входят. Закрытие всего окна, выход или перезагрузка не закрывают его подключения проектов; обычное восстановление при запуске продолжает действовать. Если нужно убедиться в завершении выполнения, явно остановите соответствующие запуски. CodeNomad никогда не выгружает нативные Location; обслуживание общей службы описано в разделе [настройки OpenCode](opencode.md). @@ -59,7 +59,7 @@ | Выбор | Эффект | Восстановление | | --- | --- | --- | | Сохранить | Закрывает проект в CodeNomad, сохраняет папку и разговоры, убирает временный статус и добавляет недавний проект | Откройте из недавних; папка не перемещается | -| Удалить | Удаляет разговоры и файлы временного рабочего пространства | Отмены нет; сначала сохраните нужное в другом месте | +| Удалить | Удаляет разговоры, файлы и неотправленные черновики временного рабочего пространства | Отмены нет; сначала сохраните нужное в другом месте | | Отмена | Оставляет временное рабочее пространство открытым | Продолжайте работу или решите позже | Нетронутая временная вкладка без разговора, файлов и неотправленного черновика при закрытии удаляется без вопроса. Открытые временные вкладки участвуют в обычном восстановлении при запуске, но на главной странице нет отдельного списка для возврата к закрытым временным папкам. diff --git a/docs/help/ru/providers.md b/docs/help/ru/providers.md index ce82920158..dc220baaec 100644 --- a/docs/help/ru/providers.md +++ b/docs/help/ru/providers.md @@ -56,15 +56,15 @@ В [FAQ Antigravity](https://antigravity.google/docs/faq/) Google указывает, что использование стороннего ПО со входом Antigravity нарушает условия сервиса и может привести к приостановке или закрытию аккаунта. -Для платных моделей интеграции `opencode` раздел **OpenCode Console** показывает **Запросы** за **Сегодня (UTC)**, **7 дней (UTC)** и **30 дней (UTC)**. Это календарные периоды UTC, включая сегодня; они начинаются в 00:00 UTC сегодня, шесть дней назад и 29 дней назад соответственно. **Запросы по моделям · 30 дней** перечисляет каждую модель и её провайдера. Счётчики относятся к подключённому аккаунту Console, формат чисел соответствует языку приложения. В разделе **Бюджеты сервисных аккаунтов** отображается **Бюджеты недоступны.** OpenCode Go использует отдельный механизм чтения квоты. +Для платных моделей интеграции `opencode` раздел **OpenCode Console** показывает **Запросы** за **24 часа**, **7 дней** и **30 дней** в том виде, в каком их сообщает Console. **Запросы по моделям · 30 дней** перечисляет каждую модель и её провайдера. Счётчики относятся к подключённому аккаунту Console, формат чисел соответствует языку приложения. В разделе **Бюджеты сервисных аккаунтов** отображается **Бюджеты недоступны.** При включённом параметре **Баланс кредитов провайдера** баланс кредитов Console показывается как **Кредиты**. OpenCode Go использует отдельный механизм чтения квоты. Чтение использует сохранённый API-ключ `opencode` или, с приоритетом, подключение Console через OAuth. Для OAuth требуются `https://opencode.ai/console` и ID организации подключения; для доступа к Console нужно разрешение **Usage › Read**. CodeNomad никогда не обновляет эти учётные данные. Недействительное или просроченное OAuth-подключение нужно восстановить через его владельца, даже если также сохранён API-ключ. Ошибки Console различают отсутствие подключения, недействительные или просроченные данные (401), запрет доступа (403), некорректный ответ об использовании и сетевой сбой. При ошибках подключения откройте **Настройки → Провайдеры**, проверьте вход и разрешения, затем обновите **Использование**. Ошибка сводки или одной страницы моделей делает всё чтение Console недоступным. -Для бесплатных моделей OpenCode (`big-pickle` и ID с окончанием `-free`) раздел **Использование** суммирует только бесплатные запросы подключённого аккаунта Console с 00:00 UTC относительно дневного ориентира **800**. **Оценка** относится к квоте и сбросу в следующую полночь UTC; реальные лимиты могут отличаться. Счётчик включает другие клиенты аккаунта. Без подключения Console панель предлагает подключиться для бесплатных моделей и просмотра квот через **Настройки → Провайдеры**. При ошибке чтения Console счётчик остаётся недоступным. +Для бесплатных моделей OpenCode (`big-pickle` и ID с окончанием `-free`) раздел **Использование** показывает одну полосу: бесплатные запросы подключённого аккаунта Console за последние 24 часа по данным Console относительно ориентира **800**; реальные лимиты могут отличаться. Счётчик включает другие клиенты аккаунта и не имеет времени сброса. При включённом параметре **Баланс кредитов провайдера** баланс кредитов Console показывается как **Кредиты**. Без подключения Console панель предлагает подключить OpenCode Console через **Настройки → Провайдеры**. При ошибке чтения Console счётчик остаётся недоступным. -Ошибка квоты на бесплатном шаге помечает подключение OpenCode как **Лимит исчерпан** до 00:00 UTC. При доступном счётчике Console индикатор показывает 100%, сохраняя число запросов. Отметка хранится в памяти бэкенда для каждого подключения и очищается при перезапуске. Бесплатное использование, отметка исчерпания и платные счётчики Console служат только для отображения; автоматический выбор аккаунта использует отдельные механизмы и правила. +Бесплатное использование и платные счётчики Console служат только для отображения; автоматический выбор аккаунта использует отдельные механизмы и правила. Для одного способа входа ChatGPT OpenAI не предоставляет данные об использовании: панель «Использование» сообщает об этом вместо окон квоты. Выберите [Посмотреть использование ChatGPT](https://chatgpt.com/settings/usage), чтобы проверить использование приложений и управлять их доступом к вашему тарифу и кредитам в ChatGPT. Общение в чате продолжает работать, а повторное подключение того же входа не возвращает показания. diff --git a/docs/help/ru/remote-access.md b/docs/help/ru/remote-access.md index eb8ea1a996..077d18783c 100644 --- a/docs/help/ru/remote-access.md +++ b/docs/help/ru/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true Не рассчитывайте на порт 9898 или 9899: незаданные порты могут заменяться при занятости. Явный ненулевой `--https-port`, либо `--http-port` при включённом HTTP, фиксирует порт и даёт ошибку при невозможности привязки; `0` просит ОС назначить порт. Напечатанные **Local Connection URL** и **Remote Connection URL**, а также обновлённые **Доступные адреса** достоверны для данного запуска. См. полный [справочник CLI сервера](server.md). +## Политика администратора {#administrator-policy} + +Администратор может зафиксировать адрес прослушивания: задайте `CODENOMAD_LOCKED_HOST` для всей системы равным адресу, который должен использовать сервер, и перезапустите CodeNomad. Он имеет приоритет над `--host`, `CLI_HOST` и **Разрешить подключения с других IP**: переключатель показывает результат, но не может его изменить. Укажите адрес интрасети, чтобы коллеги подключались через сеть компании, или `127.0.0.1`, чтобы оставить сервер на этом компьютере. Чтобы весь доступ оставался внутри сети компании, задайте также `CODENOMAD_REMOTE_CONTROL=disabled` ([удалённое управление](remote-control.md#administrator-policy)). + ## Обновление {#upgrading} После обновления войдите снова. Для псевдонима хоста, обратного прокси или отдельно размещённого интерфейса задайте в серверной части `CODENOMAD_ALLOWED_ORIGINS` с доверенными источниками интерфейса (схема, имя хоста и порт). Нативные LAN-клиенты должны передавать разрешённый заголовок `Origin` в запросах изменения данных. Его HTTPS-источники также позволяют хосту сопрягать устройства без туннеля; см. [Сопряжение по прямому HTTPS](remote-control.md#direct-https). -Используйте loopback-подключение для операций, доступных только с хоста: содержимое SideCar (`/sidecars/`) и WebSocket, управление удалённым доступом через туннель (`/api/remote-control/`), мост плагинов (`/api/opencode-plugin/`), удалённые прокси (`/api/remote-proxy/`), управление сохранёнными серверами (`/api/remote-servers/`), изменение пароля и начальная настройка токеном. Для этих операций требуется loopback даже после входа через прямой LAN-доступ. Содержимое активных предпросмотров (`/previews/`) доступно через прямой LAN-доступ с действительным токеном доступа. +Используйте loopback-подключение для операций, доступных только с хоста: содержимое SideCar (`/sidecars/`) и WebSocket, управление удалённым доступом через туннель (`/api/remote-control/`), мост плагинов (`/api/opencode-plugin/`), удалённые прокси (`/api/remote-proxy/`), управление сохранёнными серверами (`/api/remote-servers/`), изменение пароля и начальная настройка токеном. Для этих операций требуется loopback даже после входа через прямой LAN-доступ. Исключение есть только для SideCars: настройка хоста **Открывать SideCars по HTTPS** открывает их содержимое и WebSocket браузерам, выполнившим вход через доверенный HTTPS-источник ([SideCars](browser-sidecars.md#register-sidecar)). Содержимое активных предпросмотров (`/previews/`) доступно через прямой LAN-доступ с действительным токеном доступа. API регистрации `/api/sidecars` остаются доступны аутентифицированным прямым LAN-клиентам и сопряжённым устройствам. Веб-предпросмотры удалённого управления остаются доступны с токеном доступа, пока они включены на хосте. diff --git a/docs/help/ru/remote-control.md b/docs/help/ru/remote-control.md index 47351f80d2..00fe638283 100644 --- a/docs/help/ru/remote-control.md +++ b/docs/help/ru/remote-control.md @@ -86,3 +86,7 @@ CodeNomad использует [OpenTunnel](https://github.com/anomalyco/opentun TLS завершается в серверной части CodeNomad. Ретранслятор передаёт шифротекст и не может читать содержимое приложения, но видит имена хостов, время соединений и объёмы трафика. Сертификат/закрытый ключ туннеля остаются на хосте. Защищайте хранилище туннеля хоста и конфигурацию CodeNomad как учётные данные; неугадываемый адрес — не авторизация. `CODENOMAD_REMOTE_CONTROL_API` выбирает собственный API OpenTunnel; без значения используется размещённая служба. Это меняет развёртывание туннеля, не требования сопряжения и не заблокированные поверхности. Обращение с учётными данными и диагностикой см. в разделе [Безопасность](security.md). + +## Политика администратора {#administrator-policy} + +Администратор может отключить удалённое управление для всех пользователей компьютера: задайте переменную среды `CODENOMAD_REMOTE_CONTROL=disabled` для всей системы и перезапустите CodeNomad. Бэкенд никогда не подключает туннель, отклоняет **Запустить удалённое управление** и ссылки сопряжения и не переподключается при запуске; в настройках отображается **Отключено администратором**. Ранее сопряжённые устройства не могут подключиться и остаются в списке, чтобы их можно было отозвать. Если переменная не задана или пуста, политики нет; любое другое значение, даже из одних пробелов, не даёт бэкенду запуститься. diff --git a/docs/help/ru/security.md b/docs/help/ru/security.md index 3a1c5dc7ea..6e67aa9f77 100644 --- a/docs/help/ru/security.md +++ b/docs/help/ru/security.md @@ -33,7 +33,7 @@ Выход отзывает текущую прямую сессию. Успешная смена пароля на хосте отзывает все прямые сессии пользователя, включая текущую; войдите заново. Сессии истекают после 24 часов без аутентифицированных запросов или семи дней с создания. Для изменения сроков задайте `CODENOMAD_SESSION_IDLE_SECONDS` и `CODENOMAD_SESSION_ABSOLUTE_SECONDS` в положительных целых секундах до запуска серверной части. Устройства удалённого управления отзываются отдельно. -Клиенты LAN могут входить, выходить и работать с проектами. Смена пароля, управление удалённым управлением, инструменты удалённых серверов/прокси и SideCars доступны на хосте через loopback. Изменения из браузера требуют разрешённый Origin либо Referer при его отсутствии. Объявленные источники сервера разрешены; для псевдонимов DNS, обратных прокси или отдельно размещённого интерфейса задайте `CODENOMAD_ALLOWED_ORIGINS` как точные HTTP(S)-источники через запятую, например `https://code.example.test,https://ui.example.test:8443`, и перезапустите. Пути и маски не допускаются. Это даёт браузерный доступ, а не права хоста. Нативные LAN-клиенты также должны передавать разрешённый Origin при изменениях. Доверенный прокси через loopback имеет права хоста и нуждается в собственном контроле доступа. Если сервер слушает loopback или все интерфейсы, интерфейс, открытый на хосте как `localhost` с той же схемой и портом, тоже работает. +Клиенты LAN могут входить, выходить и работать с проектами. Смена пароля, управление удалённым управлением, инструменты удалённых серверов/прокси и SideCars доступны на хосте через loopback. Настройка хоста **Открывать SideCars по HTTPS** открывает SideCars браузерам, выполнившим вход через доверенный HTTPS-источник; включайте её, только если всем пользователям этих адресов можно пользоваться вашими сервисами SideCar. Изменения из браузера требуют разрешённый Origin либо Referer при его отсутствии. Объявленные источники сервера разрешены; для псевдонимов DNS, обратных прокси или отдельно размещённого интерфейса задайте `CODENOMAD_ALLOWED_ORIGINS` как точные HTTP(S)-источники через запятую, например `https://code.example.test,https://ui.example.test:8443`, и перезапустите. Пути и маски не допускаются. Это даёт браузерный доступ, а не права хоста. Нативные LAN-клиенты также должны передавать разрешённый Origin при изменениях. Доверенный прокси через loopback имеет права хоста и нуждается в собственном контроле доступа. Если сервер слушает loopback или все интерфейсы, интерфейс, открытый на хосте как `localhost` с той же схемой и портом, тоже работает. При подозрении на компрометацию: diff --git a/docs/help/ru/server.md b/docs/help/ru/server.md index 6aca677732..b5de9db36d 100644 --- a/docs/help/ru/server.md +++ b/docs/help/ru/server.md @@ -8,7 +8,7 @@ 1. Установите Node.js 24 LTS и npm; среда сборки репозитория закреплена в `.node-version`. Настольные пакеты предоставляют свою среду: Electron использует встроенный Node, Tauri включает Node, оба включают npm. 2. Добавьте Git в **PATH процесса серверной части**. Одного Git внутри WSL недостаточно для серверной части Windows. -3. Установите или выберите OpenCode: минимум **2.2.3**, рекомендуемая проверенная цель — **2.2.7**. Новые или пользовательские сборки проходят проверку совместимости, а не список разрешённых проверенных версий. См. [настройку OpenCode](opencode.md). +3. Установите или выберите OpenCode: минимум **2.3.0**, рекомендуемая проверенная цель — **2.3.0**. Новые или пользовательские сборки проходят проверку совместимости, а не список разрешённых проверенных версий. См. [настройку OpenCode](opencode.md). 4. Выберите папку запуска сервера или явно передайте `--workspace-root`. Без Git разговоры доступны только в явно открытой физической папке; операции Git и worktree не работают. Установите Git и перезапустите серверную часть после изменения PATH. Корень рабочего пространства ограничивает открытие/просмотр, не выполнение агента: см. [безопасность](security.md). @@ -104,6 +104,8 @@ HTTPS предпочитает порт **9898**, HTTP — **9899**. Без пе | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; репозиторий предложений релизов. | | `CODENOMAD_REMOTE_CONTROL_API` | Не задана: размещённый API OpenTunnel. Укажите origin API для собственного ретранслятора. | +| `CODENOMAD_REMOTE_CONTROL` | Не задана: пользователи могут запускать удалённое управление. `disabled`: отключено администратором ([политика](remote-control.md#administrator-policy)); не задана или пуста — политики нет, любое другое значение (включая пробелы) не даёт запуститься. | +| `CODENOMAD_LOCKED_HOST` | Не задана или пуста: действует `--host`; одни пробелы не дают запуститься. Адрес: сервер слушает его независимо от `--host`, `CLI_HOST` и переключателя прослушивания ([политика](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | Необязательный дополнительный файл CA Node; передаётся с разрешённым окружением запуска при запуске отсутствующего демона OpenCode. Не меняет уже работающий демон. | Учётные данные использования провайдеров описаны в [провайдерах](providers.md). Выбор настольного профиля данных описан в [настольном приложении](desktop.md), а не управляется каналом релизов. diff --git a/docs/help/ru/settings.md b/docs/help/ru/settings.md index b89e5e6864..35823d30fe 100644 --- a/docs/help/ru/settings.md +++ b/docs/help/ru/settings.md @@ -70,7 +70,7 @@ 2. Откройте **Настроить правую панель** в правой панели. Флажками выберите встроенные вкладки и разделы статуса; хотя бы один раздел статуса остаётся видимым. Проведите с зажатой кнопкой по этим флажкам, чтобы настроить несколько сразу. 3. Перетаскивайте вкладки правой панели для изменения порядка. **Сбросить** восстанавливает встроенные варианты раскладки. -Распознанные [интеграции](integrations.md#integration-sections) также имеют разделы Статуса. Скрывайте их теми же флажками; меняйте порядок любого раздела Статуса перетаскиванием или клавишами Вверх/Вниз. Видимость и порядок сохраняются при перезагрузке и временном отсутствии интеграции. +Меняйте порядок любого раздела Статуса перетаскиванием или клавишами Вверх/Вниз. Видимость и порядок сохраняются при перезагрузке. Статус включает информацию о токенах, режим Yolo, использование провайдера, фоновые оболочки, MCP и плагины. Пока у разговора есть [цель](conversations.md#goal), её показывает строка цели над этими разделами; эта строка не является разделом, её нельзя скрыть или переместить. Скрытие раздела не отключает службу и не отзывает разрешения. Узкие раскладки закрывают панели, которые больше не помещаются, вместо сжатия разговора; панель, открытая в такой раскладке, плавает поверх него, а открытие одной плавающей панели закрывает другую. diff --git a/docs/help/ru/troubleshooting.md b/docs/help/ru/troubleshooting.md index 95f73d9824..9d6e6fd417 100644 --- a/docs/help/ru/troubleshooting.md +++ b/docs/help/ru/troubleshooting.md @@ -42,7 +42,7 @@ Electron использует Chromium и служит альтернативо ## Среда OpenCode и WSL {#opencode-runtime} 1. Откройте **Настройки → OpenCode** и проверьте карточку **Версия OpenCode** (установленная версия и статус работающей службы), затем выбранный исполняемый файл в **Бинарник OpenCode**. -2. При отсутствии нужной среды используйте поддерживаемую установку/обновление. Текущий минимум: **2.2.3**; рекомендуемая/проверенная версия: **2.2.7**. +2. При отсутствии нужной среды используйте поддерживаемую установку/обновление. Текущий минимум: **2.3.0**; рекомендуемая/проверенная версия: **2.3.0**. 3. Если установленный CLI отличается от службы, явно решите, перезапускать ли общую службу. **Перезапустить службу OpenCode** находится в **Устранение неполадок** и требует подтверждения. Прерывает активную работу всех клиентов, но сохраняет историю сессий. Перезагрузка конфигурации — отдельное действие: сохраняет процесс, но пересоздаёт загруженные Location и отменяет ожидающие вопросы/разрешения. Ни одно не является безобидным обновлением. diff --git a/docs/help/tr/browser-sidecars.md b/docs/help/tr/browser-sidecars.md index 7f0931bf32..ca85179dae 100644 --- a/docs/help/tr/browser-sidecars.md +++ b/docs/help/tr/browser-sidecars.md @@ -77,7 +77,7 @@ Ulaşılamıyorsa arka uçtaki işlemi ve bağlantı noktasını kontrol edin. H SideCar, korumalı alana alınmış bir önizleme değil, CodeNomad'ın güvenilir bir uzantısıdır: sayfası CodeNomad'ın kendi kaynağıyla (origin) çalışır, bu nedenle betikleri oturum açmış erişiminizle CodeNomad'ı kullanabilir. Yalnızca koduna güvendiğiniz hizmetleri kaydedin. CodeNomad kendi oturum açma çerezlerini hizmete iletmez; hizmetin kendi çerezleri ise korunur. -SideCar içeriği (`/sidecars/`) ve SideCar WebSocket'leri, ana bilgisayarda loopback bağlantısı gerektirir. `/api/sidecars` üzerinden kayıt, eşleştirilmiş cihazlar ve kimliği doğrulanmış doğrudan LAN istemcileri için kullanılabilir. Etkin önizleme içeriği (`/previews/`), geçerli bir yetenek belirteciyle doğrudan LAN erişiminde kullanılabilir; [Uzaktan Kontrol](remote-control.md#remote-surface) web önizlemeleri etkin oldukları sürece yetenek belirteçleriyle kullanılabilir kalır. Doğrudan erişim gereksinimleri için bkz. [Yükseltme](remote-access.md#upgrading). +SideCar içeriği (`/sidecars/`) ve SideCar WebSocket'leri, ana bilgisayarda loopback bağlantısı gerektirir. Bunları başka cihazlardan da açmak için ana bilgisayarda **Ayarlar → SideCars** içindeki **SideCars'ı HTTPS üzerinden aç** seçeneğini açın: bu sunucunun HTTPS adresleri veya TLS ters proxy gibi `CODENOMAD_ALLOWED_ORIGINS` içindeki bir HTTPS origin üzerinden oturum açmış tarayıcılar SideCars açabilir. Düz HTTP, `localhost` adresleri ve Uzaktan Kontrol yalnızca ana bilgisayarda kalır. `/api/sidecars` üzerinden kayıt, eşleştirilmiş cihazlar ve kimliği doğrulanmış doğrudan LAN istemcileri için kullanılabilir. Etkin önizleme içeriği (`/previews/`), geçerli bir yetenek belirteciyle doğrudan LAN erişiminde kullanılabilir; [Uzaktan Kontrol](remote-control.md#remote-surface) web önizlemeleri etkin oldukları sürece yetenek belirteçleriyle kullanılabilir kalır. Doğrudan erişim gereksinimleri için bkz. [Yükseltme](remote-access.md#upgrading). ## OpenVSCode Sunucu tarifi {#openvscode} diff --git a/docs/help/tr/conversations.md b/docs/help/tr/conversations.md index ba5be4dd9e..1b8252d95f 100644 --- a/docs/help/tr/conversations.md +++ b/docs/help/tr/conversations.md @@ -60,6 +60,12 @@ Masaüstünde gönderme, klavye odağını konuşmaya taşır; böylece oklar, s Taslaklar paylaşılan OpenCode mesajları değil, istemci çalışma durumudur. Başlangıçta geri yükleme desteklenen ileti düzenleyicisi durumunu koruyabilir; ancak gönderilmemiş taslak veya eki yedek saymayın ve başka cihazda göründüğünü varsaymayın. Başlangıç verilerini temizlemeden veya geri yüklemesi kapalı istemciyi kapatmadan önce önemli metni kaydedin; bkz. [Masaüstü](desktop.md). +## Yanıtlardan dosya açma {#open-files-from-replies} + +1. Aracı yanıtları proje dosyalarına göreli ve mutlak yollarla bağlantı verir. +2. Düz bir tıklama, bağlantılı dosyayı sohbetin worktree’sinden okuyarak dosya önizlemesinde açar. +3. Değiştirici tıklamalar (Ctrl/⌘, Shift, orta tıklama) ve oturumun worktree’si dışındaki bağlantılar normal bağlantı davranışını korur. + ## Komutlar ve Shell modu {#commands-shell} 1. `/` yazın ve bulunan özel bir komutu seçin, ardından bağımsız değişkenlerini sağlayın. diff --git a/docs/help/tr/install.md b/docs/help/tr/install.md index 0486796f41..6c1520bdbe 100644 --- a/docs/help/tr/install.md +++ b/docs/help/tr/install.md @@ -45,7 +45,7 @@ Electron Debian kurulumu, Chromium'un korumalı alanını yapılandırır. Kurul | Gereksinim | Nerede bulunması gerektiği | Mevcut gereksinim | | --- | --- | --- | -| OpenCode CLI | Geçerli olduğu yerde seçilen WSL dağıtımı da dahil olmak üzere seçilen yürütme ana bilgisayarı | Minimum **2.2.3**; **2.2.7** önerilen/uygun hedeftir. Daha yeni veya özel sürümler, test edilmemiş sürüm yasağı yerine sözleşme doğrulamasından geçer. | +| OpenCode CLI | Geçerli olduğu yerde seçilen WSL dağıtımı da dahil olmak üzere seçilen yürütme ana bilgisayarı | Minimum **2.3.0**; **2.3.0** önerilen/uygun hedeftir. Daha yeni veya özel sürümler, test edilmemiş sürüm yasağı yerine sözleşme doğrulamasından geçer. | | Git | CodeNomad arka uç hesabının `PATH`'si | Depo kimliği, Git işlemleri ve çalışma ağaçları için gereklidir. | | Node.js/npm | Bağımsız sunucu ve kaynak derleme ana bilgisayarı | Node.js 24 LTS; tekrarlanabilir kaynak derlemeleri `.node-version` dosyasında sabitlenen sürümü kullanır. Masaüstü sürümleri kendi çalışma zamanlarını içerir: Electron'un yerleşik Node'u veya Tauri'nin paketlediği Node, npm ile. | | Çalışma alanı klasörü | Arka uçtan erişilebilen disk | Uzak bir tarayıcı tarafından çıkarılan yerel cihaz klasörü değil, açıkça açılmış bir fiziksel klasör. | diff --git a/docs/help/tr/integrations.md b/docs/help/tr/integrations.md index 35969352b2..83fb906eb7 100644 --- a/docs/help/tr/integrations.md +++ b/docs/help/tr/integrations.md @@ -27,7 +27,7 @@ Hiçbir sunucu görünmüyorsa etkin Location bağlamını ve yerel yapılandır CodeNomad tarafından yönetilen eklentiler, normal eklenti listesinin ve bu listedeki etkinleştirme, güncelleme ve kaldırma denetimlerinin dışında tutulur. CodeNomad bunları doğrulanmış yükleyici girdisi ve içerik karmasıyla tanımlanan kodun konumu üzerinden tanır; aynı ada veya kimliğe sahip üçüncü taraf eklentiler normal denetimlerini korur. -Yönetilen bir eklenti devre dışıysa, yüklenemiyorsa veya yüklenmesi doğrulanmadıysa listenin üzerinde **CodeNomad eklentileri ilgilenmenizi gerektiriyor** görünür. Mevcut hatayı ve OpenCode günlüğündeki referansını görmek için **i** düğmesini (eklentinin **ayrıntıları**) açın. Yalnızca devre dışı eklentiler **Yeniden etkinleştir** sunar: bu işlem devre dışı bırakma kuralını koruyarak tam kimlik için pozitif bir etkinleştirme kuralı ekler. Devre dışı bırakma kuralının **Genel** veya **Proje** kapsamı yazılabiliyorsa oraya, aksi hâlde **Proje** kapsamına yazar. OpenCode çalışmaya devam eder; yerel olaylar veya **Plugin denetimlerini yenile** eklentinin etkin olduğunu doğrulayana kadar uyarı kalır. +Yönetilen bir eklenti devre dışıysa, yüklenemiyorsa veya yüklenmesi doğrulanmadıysa listenin üzerinde **CodeNomad eklentileri ilgilenmenizi gerektiriyor** görünür. Mevcut hatayı ve OpenCode günlüğündeki referansını görmek için **i** düğmesini (eklentinin **ayrıntıları**) açın. Yalnızca devre dışı eklentiler **Yeniden etkinleştir** sunar: bu işlem, eklentiyi yeniden etkinleştirmeye tek başına yetiyorsa o dosyadaki tam devre dışı bırakma kuralını kaldırır, aksi hâlde tam kimlik için pozitif bir kural ekler. Devre dışı bırakma kuralının **Genel** veya **Proje** kapsamı yazılabiliyorsa oraya, aksi hâlde **Proje** kapsamına yazar. OpenCode çalışmaya devam eder; yerel olaylar veya **Plugin denetimlerini yenile** eklentinin etkin olduğunu doğrulayana kadar uyarı kalır. Uyarı ve ayrıntıları, yapılandırma kaynağını uygun olduğunda **Devralınan / harici** veya **Sanal yapılandırma** olarak gösterir. Ayrı bir **Proje** etiketi, yeniden etkinleştirme hedefi devre dışı bırakma kuralının kaynağından farklı olduğunda bu hedefi belirtir. @@ -38,7 +38,7 @@ Uyarı ve ayrıntıları, yapılandırma kaynağını uygun olduğunda **Devral Genel, bağlı daemon'ın keşfedilen genel yapılandırmasını hedefler. Proje devralınmış üst dosyayı değil, etkin Location içindeki yapılandırmayı hedefler. Sonraki Proje kuralı Genel kuralı geçersiz kılabilir; Genel anahtarı Projenin son durumu yerine yine Genel kuralı gösterir. Proje kuralı yoksa Proje çözümlenen Genel durumu devralır. -Bu anahtarlar kaynak bildirimlerini ve ilgisiz yapılandırmayı koruyarak tam etkinleştirme kurallarını düzenler. Eklenti seçeneklerini düzenlemez, paket kurmaz veya dosya kaldırmaz. Yerleşik OpenCode eklentileri kullanıcı etkinleştirme anahtarı olarak sunulmaz. Hedefi Genel'den güvenli ayrılamıyorsa veya etkin Location dışına çıkabiliyorsa Proje devre dışı tutulur. +Her anahtar, kapsamının dosyasına eklenti için tek bir tam etkinleştirme kuralı yazar ve oradaki aynı eklentinin önceki tam kurallarını değiştirir; sonuç aynıysa yalnızca onları kaldırır. Kaynak bildirimleri, `*` gibi daha geniş kurallar ve ilgisiz yapılandırma korunur. Eklenti seçeneklerini düzenlemez, paket kurmaz veya dosya kaldırmaz. Yerleşik OpenCode eklentileri kullanıcı etkinleştirme anahtarı olarak sunulmaz. Hedefi Genel'den güvenli ayrılamıyorsa veya etkin Location dışına çıkabiliyorsa Proje devre dışı tutulur. Paket güncellemesi, araç ipucunda belirtildiği gibi, o paketi kullanan her Location için OpenCode'un paylaşılan önbelleğindeki paketi değiştirir; etkinleştirme kurallarını değiştirmez, OpenCode'u yeniden başlatmaz veya yapılandırmayı yeniden yüklemez. Yerel, yerleşik ve SDK tarafından sağlanan eklentilerin paket eylemi yoktur. Eklenti kimliğini bildirmeden önce başarısız olan bir paket, paket adıyla listelenir; hatası araç ipucunda yer alır ve denetleme/güncelleme eylemleri vardır, ancak etkinleştirme anahtarları yoktur. Başarısız bir denetleme veya güncelleme bildirilir ve asla otomatik olarak yeniden denenmez. @@ -78,38 +78,30 @@ Beceri kullanılabilirliği küresel bir CodeNomad beceri kataloğundan değil, Aktif Location için komutlar OpenCode'den keşfedilir. Kendi yerel tanımları yürütme davranışını seçebilir; menü bir paket yükleyicisi veya sınırsız bir yapılandırma düzenleyicisi değildir. CodeNomad, yerel özel komut gönderiminden önce profilin oturum ortamını uygular; başarısız bir ortam güncellemesi gönderimi engeller. `/btw`, sıradan bir özel komut değil, CodeNomad'in ayrı geçici soru akışıdır. Komut tanımları ve yerel konfigürasyon devralımı için [OpenCode komutları dokümantasyonu](https://opencode.ai/v2/docs/commands/)'yi kullanın. Yapılandırma değişikliklerinden sonra öncelikle ilgili yüzeyi yenileyin/yeniden açın; açık yapılandırma yeniden yüklemesini yalnızca çalışma zamanının hâlâ buna ihtiyacı varsa kullanın. Kabul edilmesi muhtemel bir komutu asla yalnızca ekranını yenilemek için tekrar oynatmayın. -## Durum içindeki entegrasyon bölümleri {#integration-sections} +## Eklentilerdeki entegrasyonlar {#integration-rows} **Durum → Eklentiler** içindeki **+**, **Entegrasyon ekle…** veya **Eklenti ekle…** seçeneklerini açar. Entegrasyon seçicisi incelenmiş katalogdaki kurulmamış girdileri listeler. Kapsamı ve **Kur** seçeneğini seçin: CodeNomad seçilen katalog kimliğini kurar. Yerel entegrasyonlar **Yalnızca genel** kapsamını kullanır. **Katalog kullanılamıyor**, **Yenile** sunar; **{date} tarihli katalog**, güncel olmayan son geçerli kataloğu belirtir. -Bildirimi veya yüklenmiş/başarısız eklentisi olan her tanınan entegrasyonun **Durum** içinde kendi bölümü vardır; devre dışı veya kuruluyor olması bunu değiştirmez. Belirsiz bir kaynak Eklentiler'de **Uyumsuz durum** gösterir. Her entegrasyon güncelleme, kaldırma ve yenileme işlemleriyle Eklentiler satırını korur. Sürümü ve eklenti denetimlerini gövdede görmek için bölümü açın; ad ve durum başlıkta **Belgeler** ve **i** yanında görünür kalır. **i** açılır penceresi ayrıntıları istek üzerine gösterir: Enter/Boşluk ile açın, Escape ile kapatın. +Tanınan bir entegrasyonun **Durum → Eklentiler** içinde adı (örneğin **OpenCode for Blender**) ve sürümüyle tek bir satırı vardır. **Genel** ve **Proje** anahtarları diğer anahtarlar gibi vurgu rengindedir, sıradan bir eklentininkiler yeşildir; bir uygulamanın içinde bölümü olan entegrasyon **Yalnızca genel** kapsamındadır. Adının üzerine gelin: ayrıntılar **Eklenti** yerine **Entegrasyon** ile başlar; ekran okuyucular bunları satırın açıklaması olarak okur. Belirsiz bir kaynak **Uyumsuz durum** gösterir. -Durum özelleştirmesinde tüm bölümleri gizleyebilir ve sürükleyerek ya da Yukarı/Aşağı tuşlarıyla sıralayabilirsiniz. Görünürlük ve sıra yeniden yüklemelerde ve entegrasyon geçici olarak yokken korunur. Odaklanmış bölüm kaybolursa odak Eklentiler'e, Eklentiler gizliyse başka bir görünür Durum bölümüne döner. +Adın altındaki durum satırı entegrasyonun ne durumda olduğunu her zaman söyler. Gri metin bilgi verir; vurgu rengindeki metin bir düğmedir. Bir uygulamanın içinde bölümü olan entegrasyonda en önemli durum gösterilir: bölümü eksik veya eskiyse **Blender içine kur** ya da **Blender güncelle** (kurulum onayıyla), uyumsuzluk uyarı renginde, görüntülenen konuşma bağlıysa zincir simgesi ve belge (bağlantıyı kesmek için seçin), **Blender kapalı**, **Blender: açık belge yok**, **Görüntülenen konuşma yok**, ardından belge adıyla **bağla** ya da birkaç belge arasından seçmek için **Bağla…**. Bir konuşma, aracısı entegrasyonu ilk kez kullandığında da kendiliğinden bağlanır. Düzenleyici MCP entegrasyonları **Sunucu algılandı** veya **Sunucu bulunamadı**, API entegrasyonları **Bağlı** veya **Bağlantı kesildi** gösterir. Uzun bir durum kısaltılır; tam metni görmek için üzerine gelin. Entegrasyonun bildirdiği değişiklikler ve yeniden bağlanmalar satırı yeniler. -Katalogdan kurulum, uygulama bölümünü kurma/güncelleme, bağlama ve kaldırma onay gerektirir. İlk odak **İptal** üzerindedir; onay işlemi 600 ms sonra kullanılabilir. Etkinleştirme ve eklenti güncellemeleri doğrudan çalışır. +Satırın **…** menüsü bağlantı durumuyla başlar, örneğin **Blender: 1 açık belge** veya **Blender kapalı**. Ardından **Belgeler**, **Uygulamaya kur…**, **Uygulamayı güncelle…** veya **Uygulamaya yeniden kur…** ([aşağıya bakın](#application-installation)), paketin güncelleme denetimi, **Genel kapsamından kaldır** veya **Proje kapsamından kaldır** ve **Plugin denetimlerini yenile** sunar. Bağlantıyı kesmek onay olmadan tek tıklamadır ve yalnızca bu konuşmayı etkiler: uygulama açık kalır, bölümü kurulu kalır ve diğer konuşmalar bağlantılarını korur. Yanıt kaybolursa satır durumu yeniden okur; istek asla tekrarlanmaz. -## Açık bir uygulamayı bağla {#application-attachment} +Katalogdan kurulum, uygulama bölümünün kurulumu/güncellenmesi ve kaldırma onay gerektirir. Önce **İptal** odaklanır; onay eylemi 600 ms sonra kullanılabilir olur. Etkinleştirme, eklenti güncellemeleri, bağlama ve bağlantıyı kesme doğrudan çalışır. -Belgeyi uygulamanın entegrasyonundan sunun, **Durum → entegrasyon → Konuşma** bölümünü açıp **Bağla…** seçeneğini kullanın. Bu bölüm görüntülenen konuşmanın bağlantısını denetler. Uygulama ve belgeyi seçin, hedef konuşmayı ve değişiklik uyarısını denetleyip **Bağla** ile onaylayın. Uygulama uzak bağlantılarda da OpenCode makinesinde çalışır. WSL dahil desteklenmeyen sunucular **i** üzerinden yardım sunar. - -**Konuşma** satırı görüntülenen konuşmanın bağlantısını okur. **Bağlantı bilinmiyor**, **Yenile** sunar. Güncel ve yetkili okuma bağlantıyı doğruladığında **Bağlantıyı kes**, **Bağla…** yerine geçer. Tek tıklama başka onay olmadan yalnızca bu konuşmayı ayırır; uygulama açık, uygulama bölümü kurulu kalır ve diğer konuşmalar bağlantılarını korur. Yerel değişiklikler ve yeniden bağlantılar durumu yeniler. - -Kabul edilmiş işlem hedef konuşma görüntülenirken sonucunu veya hatasını korur; gezinme işlem kaydını kapatır. Güncel bağlantı yetkili okumayı izler. Yanıt kaybı, zaman aşımı veya bağlantı kesilmesi sonrası **Durum belirsiz**, gerçek durumu okumak için **Yenile** sunar. Görünümü yenilemek için isteği asla tekrar göndermeyin. - -Seçicide açık uygulamalar açıkça okunduktan sonra kayıtlı Q8 meta verileri, proje, konuşma ve bağlantı nesli aynı kaldığı sürece aynı entegrasyon ve doğrulanmış belge etiketi için seçicide veya **Konuşma** satırında **Yeniden bağla** önerebilir. Yeniden bağlama açık onay gerektirir; gezinme veya verilerin geçersiz kılınması öneriyi temizler. Güncel bağlantının yetkili bilgisi, entegrasyonun oturum bazındaki okumasından gelir. - -Entegrasyon bölümünden veya Eklentiler satırından kaldırma aynı bildirimi ve kapsam onayını kullanır. Konuşma sayımı veya otomatik bağlantı kesme yapılmadan kaldırılır. +Kaldırma, konuşma sayımı veya otomatik bağlantı kesme olmadan yapılır. Kaldırma uyarısı eklentiyi ve tam kapsamı adlandırır. **İptal** odaklanır; **Genel/Proje kapsamından kaldır** 600 ms sonra kullanılabilir ve açık bir işlem gerektirir. Kullanan konuşmalarda kullanılabilirliği ve bağlantıları kesebilir; Genel kapsam diğer projeleri de etkileyebilir. Gönderimden önce iptal, süre dolması veya gezinme hiçbir şeyi değiştirmez. Yalnızca onaylanan bildirim kaldırılır; kurallar, önbellek, uygulama dosyaları ve kayıtlı bağlantı ipuçları korunur. Yapılandırma değişirse yeniden seçim ve onay gerekir. Başarı bildirimin kaldırıldığını belirtir; çalışma durumu OpenCode yeniden yüklemesini izler. Yanıt kaybolursa yeniden denemeden önce yenileyip yapılandırmayı kontrol edin. Yeniden kurulum kullanılabilirliği geri getirebilir; yeniden yükleme veya bağlama gerekebilir ve kesilen işlemler devam etmeyebilir. ## Uygulama entegrasyonunu kurun veya güncelleyin {#application-installation} -**Durum → entegrasyon → Uygulama** içinde güncel durum sunduğunda **Uygulamaya kur…** veya **Uygulamayı güncelle…** seçeneğini kullanın. Konuşma veya sunulan belge olmadan kullanılabilir. Uygulama kapalıysa uygulama bölümünü denetlemek için açın; **i** makine ve önkoşul ayrıntılarını gösterir. +**Durum → Eklentiler** içinde, güncel durumu eylemi sunduğunda entegrasyonun durum satırındaki **Blender içine kur** veya **Blender güncelle** seçeneğini, ya da **…** menüsündeki **Uygulamaya kur…**, **Uygulamayı güncelle…** veya **Uygulamaya yeniden kur…** seçeneğini seçin. Yeniden kurulum, uygulama açık veya kapalı olsun, uygulama bölümünü yeniden yazar. Konuşma veya açık belge olmadan da kullanılabilir. Onay, uygulamayı ve yükleyiciyi sağlayan **entegrasyon paketinin sürümünü** belirtir. İkisini ve makine uyarısını denetleyin: kurulum OpenCode'un çalıştığı makinede yapılır; bu uzak bir makine olabilir. İlk odak **İptal** üzerindedir. Devam etmek için açıkça onaylayın. Onaydan önce proje, Location veya konuşma değiştirmek, yeniden bağlanmak ya da ilgili yerel değişiklikleri almak bekleyen onayı iptal eder; güncel ayrıntıları incelemek için işlemi yeniden açın. WSL, açık bir uygulama uyumlu görünse bile uygulama içine kurulumu her zaman reddeder. Uygulamayı desteklenen bir makinede açın. -Sonuç, entegrasyonun kurulduğunu, güncellendiğini, zaten güncel olduğunu, reddedildiğini veya başarısız olduğunu bildirir. Kurulum veya güncellemeden sonra uygulamayı açıp entegrasyonunu denetleyin; konuşmayı [Açık bir uygulamayı bağla](#application-attachment) ile ayrıca bağlayın. Kurulum başarısı yükleyici isteğinin sonucunu anlatır; çalışan uygulamanın kullanılabilirliği uygulamanın durumundan anlaşılır. +Sonuç, uygulama bölümünün kurulduğunu, güncellendiğini, zaten güncel olduğunu, reddedildiğini veya başarısız olduğunu bildirir. Kurulum veya güncellemeden sonra uygulamayı açıp entegrasyonunu denetleyin. Kurulum başarısı yükleyici isteğini açıklar; uygulamanın gerçek kullanılabilirliği uygulamanın durumundan gelir. İstekler asla otomatik olarak yeniden denenmez. Ret veya başarısızlıktan sonra yeni bir işlem seçmeden önce uygulamayı kontrol edin. Bir hata sonucu belirsiz bırakırsa o isteği tekrarlamayın: önce uygulamayı inceleyin, ardından gerekirse yeni bir işlem ve onay başlatın. diff --git a/docs/help/tr/missions.md b/docs/help/tr/missions.md index 315e93739b..807df79df7 100644 --- a/docs/help/tr/missions.md +++ b/docs/help/tr/missions.md @@ -42,7 +42,7 @@ Takvim tabanlı zamanlama, koordinatör ve rehberin her rolü için açık bir a ### Otomatik başlat {#automatic-start} -**Otomatik başlat**, Zamanlama dışındadır ve varsayılan olarak kapalıdır. Kapalıyken görev duraklatılmış oluşturulur ve daha sonra ▶ ile başlatılır. Açıkken oluşturma doğrulanınca olağan kontroller ve gerekli yerel ayar onayıyla başlatma istenir. +**Otomatik başlat**, Zamanlama dışındadır ve varsayılan olarak kapalıdır. Kapalıyken görev duraklatılmış oluşturulur ve daha sonra ▶ ile başlatılır. Açıkken oluşturma doğrulanınca olağan kontroller ve otomatik zamanlama hazırlığıyla başlatma istenir. Oluşturma onayı kaybolursa makbuzu okumak otomatik başlatmaz. Doğrulanmamış asıl isteği koruyun; yeniden oluşturmadan önce listeyi ve konuşmayı kontrol edin. @@ -56,6 +56,8 @@ Alt ajan derinliği bilgileri etkin kaynağı **OpenCode yapılandırma dosyası Bir kez şimdi, N saatte bir, günlük, haftanın günleri, ayın günü ve cron seçenekleri vardır. Kayıtlı saat dilimi kullanılır; sistemden farklıysa dilim alanı görünür. Seçilen günün bulunmadığı ay atlanır. Bir kez şimdi, zamanı Başlat'ta alır; koşul bu tek fırsatı çalıştırmadan tüketebilir. OpenCode hizmeti ve yürütme makinesi kullanılabilir olmalıdır. +Başlatma veya sürdürme sırasında zamanlama projenin OpenCode yapılandırmasında otomatik hazırlanır. Açık OFF korunur: sunulduğunda **Zamanlama ayarlarını aç** sorumlu dosyayı açar; **i** kaynak veya ortam ayrıntılarını gösterir. Tıklanan düğme yalnızca istek sırasında yükleniyor durumunu gösterir. Onaylanmamış sonuç doğrulanabilir; etkinleştirme kurtarıldıktan sonra başlatma açık bir işlem olarak kalır. + ### Olaylar ve birleşimler {#scheduling-conditions} **Depo etkinliği → Olay** seçin, ardından aynı karttaki isteğe bağlı filtreleri kullanın. Git commit’leri, otomatik algılanan GitHub, GitLab veya Gitea deposunun olaylarıyla aynı menüdedir. Algılama Contribute ile ortaktır: önce `upstream`, sonra `origin`. Üçü de yeni ve birleştirilmiş PR/MR ile yeni issue olaylarını ve `dependabot[bot]` dahil isteğe bağlı **Yazar** filtresini destekler. Olay seçimi depoyu sabitler; kayıtlı ölçütler hedeflerini korur. @@ -88,9 +90,11 @@ Liste sonuna yaklaşınca yeni kayıtlar ve işler otomatik yüklenir. İş sayf ### Renkler ve durumlar {#status-colours} -Bayrak Görevin durumunu, şevron işlerinin dikkat durumunu gösterir; tekrarlanan kayıtta tekrar simgesi vardır. Kırmızı yanıt bekler, titreşen sarı gözlenen çalışmayı, turuncu duraklama/kesintiyi, yeşil görülmemiş sonucu, mavi hazırlığı veya başlamamış işi gösterir. +Bayrak Görevin durumunu, şevron işlerinin dikkat durumunu gösterir; tekrarlanan kayıtta tekrar simgesi vardır. Kırmızı yanıt bekler, titreşen sarı gözlenen çalışmayı gösterir. Turuncu duraklatma simgesi duraklamayı, turuncu uyarı üçgeni kesintiyi belirtir. Yeşil, incelenmeyi bekleyen bir Görevi, işi veya başarılı çalıştırmayı gösterir. + +Altında küçük, sabit ve nötr bir çizgi olan vurgu renkli simge **Zamanlanmış çalıştırma bekleniyor** demektir: sonraki uyanma doğrulanmıştır. Vurgu rengi palete bağlıdır. Çizgisiz vurgu simgesi hazırlığı veya başlamamış işi belirtir. İncelenmiş tamamlanmalar, durdurulmuş zamanlamalar ve **Durum doğrulanmadı** nötrdür; durum metnini okuyun. -Seçim, yeşil iş simgesine tıklama/süpürme veya şevron menüsünden okundu işaretleme sonuçları temizler. Engel her zaman insan sorusu değildir; rapor, tüm yerel işlemlerin sona erdiğini kanıtlamaz. Geri çekilen işin geçmişi tutulur. +Seçim veya yeşil iş simgesine tıklama/süpürme sonuçları onaylar; şevron menüsünde **Okundu olarak işaretle** bulunur. **İncelenecek başarılı çalıştırma** için etkin pencerede tekrarlanan satırı açıkça seçin veya **Okundu olarak işaretle** ile tam o çalıştırmayı onaylayın. Zamanlama etkinse simge beklemeye, aksi durumda nötre döner. Geri yüklenen seçim ve zaten seçili satıra gelen yeni sonuçlar okunmamış kalır. İlk yüklemedeki geçmiş başarılar okunmuş sayılır. Geri çekilen işin geçmişi tutulur. ### Sorular ve kararlar {#questions} diff --git a/docs/help/tr/mobile.md b/docs/help/tr/mobile.md index ec5ec37e13..dd06c5a53f 100644 --- a/docs/help/tr/mobile.md +++ b/docs/help/tr/mobile.md @@ -42,3 +42,5 @@ Gezinmeyi ve araçları açmak için **Sol panel** ve **Sağ panel** kontrolleri | Çevrimdışı çalışma | Çevrimdışı arka uç veya önbelleğe alınmış API geçmişi yok. Statik kullanıcı arayüzü varlıkları önbelleğe alınabilir ancak belgeler ve API yanıtları çevrimdışı bir çalışma alanı değildir. | Arka ucu erişilebilir tutun. Mobil işletim sisteminin askıya alması veya ağ değişimi olay akışını kesebilir; geri dönmek, garantili olay tekrarı olmadan yeniden bağlanıp güncel durumu getirir. Yeniden denemeden önce işlemin tamamlanıp tamamlanmadığını kontrol edin. PWA kapatmak bağımsız arka ucu durdurmaz; ana bilgisayardaki masaüstü uygulamasından ve arka uçtan çıkmak Uzaktan Kontrolü sonraki başlatmaya kadar kullanılamaz yapar. + +Yüklü PWA dahil her tarayıcı sekmesi, açık projelerini, seçili konuşmalarını, gönderilmemiş taslaklarını ve kaydırma konumlarını o sekme için saklar: sayfa yeniden yüklendiğinde veya mobil işletim sistemi onu uygulama değişikliği ya da ekran kilidinden sonra yeniden yüklediğinde geri gelirler. Yeni bir sekme veya işletim sisteminin tamamen kapattığı bir PWA ana sayfada açılır. Bunu sekme için **Ayarlar → Genel → Önceki durumu geri yükle** ile kapatın. diff --git a/docs/help/tr/opencode.md b/docs/help/tr/opencode.md index 4c7d239531..05eb6f6b22 100644 --- a/docs/help/tr/opencode.md +++ b/docs/help/tr/opencode.md @@ -19,8 +19,8 @@ Yüklü yürütülebilir dosya ve çalışan hizmetin farklı sürümleri olabil | Sınıflandırma | Mevcut gereksinim | Anlamı | | --- | --- | --- | -| Asgari | OpenCode **2.2.3** | **Görseller** ayarlarının ve Design uzantısının kullandığı görsel oluşturma aracı, Code Mode içindeki JavaScript görevlerinin doğru yürütme sırası ve yerel yeniden oynatma ve sıkıştırma biçimi; önceki sürümlerle kaydedilen konuşmalar güncellemeden sonra da okunabilir. | -| Önerilen | OpenCode **2.2.7** | Teknik alt sınırdan farklı, doğrulanan hedef. | +| Asgari | OpenCode **2.3.0** | **Görseller** ayarlarının ve Design uzantısının kullandığı görsel oluşturma aracı, Code Mode içindeki JavaScript görevlerinin doğru yürütme sırası ve yerel yeniden oynatma ve sıkıştırma biçimi; önceki sürümlerle kaydedilen konuşmalar güncellemeden sonra da okunabilir. Ayrıca alt ajan sonuçlarını arka plan raporları olarak iletir; bunları alt ajan kartları ve Görevler okur. | +| Önerilen | OpenCode **2.3.0** | Doğrulanan hedef; şu anda asgari sürümle aynı. | | Doğrulanmamış | Tam olarak doğrulanmamış daha yeni veya özel bir sürüm | Yalnızca denenmemiş olduğu için reddedilmez; bağlı hizmetin gerçek API sözleşmeleri kontrol edilir. | Bağlı hizmet gerekli oturum, izin, Form, gelen kutusu ve oturum ortamı sözleşmelerini sunmalıdır. Yerel Görev zamanlaması ayrıca zamanlama API'lerini, eklenti/sağlayıcı paketini ve etkin `experimental.schedules` ayarını denetler. Kullanılabilirlik, uyumlu gelecek sürümler dahil, kullanılan bu yeteneklere bağlıdır. Kurulum desteklenmeyen bir çalışan hizmet bildirirse desteklenen bir CLI seçin/yükleyin ve hazır olduğunuzda paylaşılan hizmeti açıkça yeniden başlatın. diff --git a/docs/help/tr/projects.md b/docs/help/tr/projects.md index 2aa5e6d30b..9dac23e864 100644 --- a/docs/help/tr/projects.md +++ b/docs/help/tr/projects.md @@ -34,7 +34,7 @@ Normal bir tıklama yine de tam ana sayfayı açar. Başlatıcı, yönetim yüze | Sekmeyi Kapat | O sekmenin CodeNomad proje bağlantısını kaldırır; aynı klasörde ayrı açılmış başka bir sekme etkilenmez | Proje dosyalarını veya yerel geçmişi silmez, oturumları durdurmaz veya OpenCode'un Location bağlamını kaldırmaz | | Oturumu durdur | Seçilen görüşmenin yürütülmesi | Projeyi kapatmaz veya geçmişini silmez | -Aynı proje bağlantısını başka bir pencere gösteriyorsa oradaki sekme de kapanır ve o pencere bir bildirim gösterir. Kapatmayı başlatan pencere bildirim göstermez. Kapatma hemen gerçekleşir; arka uç projeyi kapatamazsa bir hata görünür ve ana sayfadaki **Açık projeye geç** yine projeye ulaşır. Otomatik yeniden deneme yoktur. Kapatılan sekmenin gönderilmemiş taslakları başlangıç geri yüklemesinde korunmaz. +Aynı proje bağlantısını başka bir pencere gösteriyorsa oradaki sekme de kapanır ve o pencere bir bildirim gösterir. Kapatmayı başlatan pencere bildirim göstermez. Kapatma hemen gerçekleşir; arka uç projeyi kapatamazsa bir hata görünür ve ana sayfadaki **Açık projeye geç** yine projeye ulaşır. Otomatik yeniden deneme yoktur. Kapatılan sekmenin gönderilmemiş taslakları ve ekleri, aynı klasörü o pencerede yeniden açtığınızda geri gelir; pencere bunları yeniden yüklenene veya kapanana kadar en son kapatılan 16 proje için tutar. Başlangıç geri yüklemesine dahil değildir. Bir pencerenin tamamını kapatmak, uygulamadan çıkmak veya yeniden yüklemek proje bağlantılarını kapatmaz; normal başlangıç geri yüklemesi yine uygulanır. Yürütmenin bittiğini doğrulamak istiyorsanız ilgili çalıştırmaları açıkça durdurun. CodeNomad yerel Location bağlamlarını hiçbir zaman kaldırmaz; paylaşılan hizmetin bakımı [OpenCode kurulumu](opencode.md) bölümünde açıklanır. @@ -59,7 +59,7 @@ Sunucuyu kaldırmadan veya adresini değiştirmeden önce tüm pencerelerdeki pr | Seçim | Etki | Kurtarma | | --- | --- | --- | | Sakla | Projeyi CodeNomad'de kapatır, klasörü ve konuşmaları korur, geçici durumunu kaldırır ve son kullanılan projelere ekler | Son kullanılanlardan yeniden açın; klasör taşınmaz | -| At | Geçici çalışma alanının konuşmalarını ve dosyalarını siler | Geri alma yok; ihtiyaç duyulan her şeyi önce başka bir yere kaydedin | +| At | Geçici çalışma alanının konuşmalarını, dosyalarını ve gönderilmemiş taslaklarını siler | Geri alma yok; ihtiyaç duyulan her şeyi önce başka bir yere kaydedin | | İptal | Geçici çalışma alanını açık bırakır | Çalışmaya devam edin veya daha sonra karar verin | Hiçbir konuşma, dosya veya gönderilmemiş taslak içermeyen, dokunulmamış bir geçici sekme, kapatıldığında sessizce atılır. Açık geçici sekmeler normal başlangıç geri yüklemesine katılır, ancak ana sayfada kapatılan geçici klasörlerin devam ettirilmesi için ayrı bir liste yoktur. diff --git a/docs/help/tr/providers.md b/docs/help/tr/providers.md index e979f2ced0..47260831bf 100644 --- a/docs/help/tr/providers.md +++ b/docs/help/tr/providers.md @@ -56,15 +56,15 @@ OpenCode'un Gemini CLI kimlik doğrulama yöntemini kullanan Google bağlantıla Google'ın [Antigravity SSS](https://antigravity.google/docs/faq/) sayfası, Antigravity girişiyle üçüncü taraf yazılım kullanmanın hizmet koşullarını ihlal ettiğini ve hesabın askıya alınmasına veya kapatılmasına yol açabileceğini belirtir. -`opencode` entegrasyonunun ücretli modellerinde **OpenCode Console**, **Bugün (UTC)**, **7 gün (UTC)** ve **30 gün (UTC)** için **İstekler** gösterir. Bunlar bugünü içeren UTC takvim dönemleridir; sırasıyla bugün, altı gün önce ve 29 gün önce 00:00 UTC'de başlar. **Modele göre istekler · 30 gün** her modeli sağlayıcısıyla listeler. Sayaçlar bağlı Console hesabını kapsar ve sayılar uygulamanın diline göre biçimlendirilir. **Hizmet hesabı bütçeleri** altında **Bütçeler kullanılamıyor.** görünür. OpenCode Go kendi kota okuyucusunu kullanır. +`opencode` entegrasyonunun ücretli modellerinde **OpenCode Console**, Console'un bildirdiği şekilde **24 saat**, **7 gün** ve **30 gün** için **İstekler** gösterir. **Modele göre istekler · 30 gün** her modeli sağlayıcısıyla listeler. Sayaçlar bağlı Console hesabını kapsar ve sayılar uygulamanın diline göre biçimlendirilir. **Hizmet hesabı bütçeleri** altında **Bütçeler kullanılamıyor.** görünür. **Sağlayıcı kredi bakiyesi** açıkken Console kredi bakiyesi **Kredi** olarak görünür. OpenCode Go kendi kota okuyucusunu kullanır. Okuyucu kayıtlı `opencode` API anahtarını veya öncelikli olarak OAuth Console bağlantısını kullanır. OAuth için `https://opencode.ai/console` ve bağlantının kuruluş kimliği gerekir; Console erişimi **Usage › Read** izni gerektirir. CodeNomad bu kimlik bilgilerini asla yenilemez. Geçersiz veya süresi dolmuş OAuth bağlantısı, API anahtarı da kayıtlı olsa bile sahibi üzerinden düzeltilmelidir. Console hataları eksik bağlantı, geçersiz veya süresi dolmuş kimlik bilgisi (401), erişim reddi (403), geçersiz kullanım yanıtı ve ağ hatasını ayırır. Bağlantı hatalarında **Ayarlar → Provider'lar** üzerinden girişi ve izinleri kontrol edip **Kullanım** görünümünü yenileyin. Bir özet veya model sayfası başarısız olursa Console okumasının tamamı kullanılamaz olur. -Ücretsiz OpenCode modellerinde (`big-pickle` ve kimliği `-free` ile biten modeller) **Kullanım**, yalnızca bağlı Console hesabının 00:00 UTC'den beri ücretsiz isteklerini toplar ve günlük **800** referansıyla karşılaştırır. **Tahmini**, kota ve sonraki UTC gece yarısı sıfırlamasını belirtir; gerçek sınırlar değişebilir. Sayaç hesabın diğer istemcilerini de kapsar. Console bağlantısı yoksa panel ücretsiz modeller ve kota takibi için **Ayarlar → Sağlayıcılar** üzerinden bağlanmayı ister. Console okuması başarısız olursa sayaç kullanılamaz kalır. +Ücretsiz OpenCode modellerinde (`big-pickle` ve kimliği `-free` ile biten modeller) **Kullanım** tek bir çubuk gösterir: bağlı Console hesabının Console'a göre son 24 saatteki ücretsiz istekleri, **800** referansıyla karşılaştırılır; gerçek sınırlar değişebilir. Sayaç hesabın diğer istemcilerini de kapsar ve sıfırlanma zamanı yoktur. **Sağlayıcı kredi bakiyesi** açıkken Console kredi bakiyesi **Kredi** olarak görünür. Console bağlantısı yoksa panel **Ayarlar → Sağlayıcılar** üzerinden OpenCode Console'u bağlamanızı ister. Console okuması başarısız olursa sayaç kullanılamaz kalır. -Ücretsiz bir adımda kota hatası olursa OpenCode bağlantısı 00:00 UTC'ye kadar **Tükendi** olarak işaretlenir. Console sayacı varsa gösterge %100 olur ve sayı korunur. İşaret bağlantı başına backend belleğinde tutulur ve yeniden başlatmada silinir. Ücretsiz kullanım, tükenme ve ücretli Console sayaçları yalnızca görüntüleme içindir; otomatik hesap seçimi ayrı okuyucular ve kurallar kullanır. +Ücretsiz kullanım ve ücretli Console sayaçları yalnızca görüntüleme içindir; otomatik hesap seçimi ayrı okuyucular ve kurallar kullanır. OpenAI, ChatGPT oturum açma yöntemlerinden biri için kullanım verisi sağlamaz: Kullanım, kota pencereleri göstermek yerine bunu belirtir. ChatGPT'de uygulama kullanımını incelemek ve planınıza ve kredilerinize erişimi yönetmek için [ChatGPT kullanımını görüntüle](https://chatgpt.com/settings/usage) seçeneğini kullanın. Sohbet etmek yine çalışır ve aynı girişle yeniden bağlanmak bu okumayı geri getirmez. diff --git a/docs/help/tr/remote-access.md b/docs/help/tr/remote-access.md index d3d9ad0d6c..792dc8fbb0 100644 --- a/docs/help/tr/remote-access.md +++ b/docs/help/tr/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true 9898 veya 9899 portunu varsaymayın: belirtilmeyen portlar doluyken başka port kullanılabilir. Açıkça verilen sıfır olmayan `--https-port` veya HTTP etkinken `--http-port` portu sabitler ve bağlanamazsa başarısız olur; `0` işletim sisteminden port atamasını ister. Yazdırılan **Local Connection URL** ve **Remote Connection URL** ile yenilenen **Erişilebilir adresler** o çalıştırma için yetkili bilgidir. Tam [sunucu CLI başvurusuna](server.md) bakın. +## Yönetici ilkesi {#administrator-policy} + +Bir yönetici dinleme adresini sabitleyebilir: `CODENOMAD_LOCKED_HOST` değişkenini sistem genelinde sunucunun kullanması gereken adrese ayarlayın ve CodeNomad'ı yeniden başlatın. Bu adres `--host`, `CLI_HOST` ve **Diğer IP'lerden bağlantılara izin ver** üzerinde önceliklidir; anahtar sonucu gösterir ama değiştiremez. Çalışma arkadaşlarınızın sunucuya şirket ağı üzerinden ulaşması için bir intranet adresi, bu bilgisayarda tutmak için `127.0.0.1` kullanın. Tüm erişimin şirket ağı içinde kalması için ayrıca `CODENOMAD_REMOTE_CONTROL=disabled` ayarlayın ([Uzaktan Kontrol](remote-control.md#administrator-policy)). + ## Yükseltme {#upgrading} Yükseltmeden sonra yeniden oturum açın. Ana bilgisayar adı takma adı, ters proxy veya ayrı barındırılan arayüz için arka uçta `CODENOMAD_ALLOWED_ORIGINS` değerini arayüzün güvenilir origin adreslerine (şema, ana bilgisayar adı ve port) ayarlayın. Yerel LAN istemcileri, değişiklik isteklerinde izin verilen bir `Origin` başlığı göndermelidir. HTTPS origin adresleri, ana bilgisayarın cihazları tünel olmadan eşleştirmesine de olanak tanır; bkz. [Doğrudan HTTPS ile eşleştirin](remote-control.md#direct-https). -Ana bilgisayara özel işlemler için loopback bağlantısı kullanın: SideCar içeriği (`/sidecars/`) ve WebSocket'ler, Uzaktan Kontrol yönetimi (`/api/remote-control/`), eklenti köprüsü (`/api/opencode-plugin/`), uzak proxy'ler (`/api/remote-proxy/`), kayıtlı sunucu yönetimi (`/api/remote-servers/`), parola değişikliği ve belirteçle ilk kurulum. Doğrudan LAN erişimiyle oturum açıldığında da bu işlemler loopback gerektirir. Etkin önizleme içeriği (`/previews/`), geçerli bir yetenek belirteciyle doğrudan LAN erişiminde kullanılabilir. +Ana bilgisayara özel işlemler için loopback bağlantısı kullanın: SideCar içeriği (`/sidecars/`) ve WebSocket'ler, Uzaktan Kontrol yönetimi (`/api/remote-control/`), eklenti köprüsü (`/api/opencode-plugin/`), uzak proxy'ler (`/api/remote-proxy/`), kayıtlı sunucu yönetimi (`/api/remote-servers/`), parola değişikliği ve belirteçle ilk kurulum. Doğrudan LAN erişimiyle oturum açıldığında da bu işlemler loopback gerektirir. Tek istisna SideCars'tır: ana bilgisayardaki **SideCars'ı HTTPS üzerinden aç** ayarı, içeriklerini ve WebSocket'lerini güvenilir bir HTTPS origin üzerinden oturum açmış tarayıcılara açar ([SideCars](browser-sidecars.md#register-sidecar)). Etkin önizleme içeriği (`/previews/`), geçerli bir yetenek belirteciyle doğrudan LAN erişiminde kullanılabilir. `/api/sidecars` kayıt API'leri, kimliği doğrulanmış doğrudan LAN istemcileri ve eşleştirilmiş cihazlar için kullanılabilir kalır. Uzaktan Kontrol web önizlemeleri, ana bilgisayarda etkin oldukları sürece yetenek belirteçleriyle kullanılabilir. diff --git a/docs/help/tr/remote-control.md b/docs/help/tr/remote-control.md index 7760d32365..5487f602e1 100644 --- a/docs/help/tr/remote-control.md +++ b/docs/help/tr/remote-control.md @@ -86,3 +86,7 @@ CodeNomad [OpenTunnel](https://github.com/anomalyco/opentunnel) kullanır ve mak TLS, CodeNomad arka ucunda sonlanır. Röle şifreli metni iletir ve uygulama içeriğini okuyamaz ancak ana bilgisayar adlarını, bağlantı zamanlamasını ve trafik boyutlarını gözlemleyebilir. Tünel sertifikası/özel anahtar ana bilgisayarda kalır. Ana bilgisayarın tünel depolamasını ve CodeNomad yapılandırmasını kimlik bilgileri olarak koruyun; Tahmin edilemeyen bir adres yetkilendirme değildir. `CODENOMAD_REMOTE_CONTROL_API`, kendi barındırdığınız OpenTunnel API hizmetini seçer; tanımsızsa barındırılan hizmet kullanılır. Bu, eşleştirme gereksinimlerini veya engelli yüzeyleri değil, tünel kurulumunu değiştirir. Kimlik bilgileri ve tanılama işlemleri için [Güvenlik](security.md) sayfasına bakın. + +## Yönetici ilkesi {#administrator-policy} + +Bir yönetici, bir bilgisayardaki tüm kullanıcılar için Uzaktan Kontrol'ü kapatabilir: `CODENOMAD_REMOTE_CONTROL=disabled` ortam değişkenini sistem genelinde ayarlayın ve CodeNomad'ı yeniden başlatın. Arka uç hiçbir zaman tünel bağlamaz, **Uzaktan Kontrolü başlat** ve eşleştirme bağlantılarını reddeder ve açılışta yeniden bağlanmaz; ayarlarda **Yönetici tarafından devre dışı** görünür. Daha önce eşleştirilmiş cihazlar bağlanamaz ve iptal edebilmeniz için listede kalır. Ayarlanmamış veya boş değer ilke uygulamaz; yalnızca boşluk dahil başka herhangi bir değer arka ucun başlamasını engeller. diff --git a/docs/help/tr/security.md b/docs/help/tr/security.md index 90cb65658f..4b19bad744 100644 --- a/docs/help/tr/security.md +++ b/docs/help/tr/security.md @@ -33,7 +33,7 @@ Doğrudan giriş, arka uç belleğinde opak bir oturum ve `codenomad_session` ç Çıkış, mevcut doğrudan oturumu iptal eder. Ana bilgisayarda başarılı parola değişikliği, mevcut oturum dahil kullanıcının tüm doğrudan oturumlarını iptal eder; yeniden giriş yapın. Oturumlar, kimliği doğrulanmış istek olmadan 24 saat veya oluşturulduktan yedi gün sonra sona erer. Sınırları değiştirmek için arka uç başlamadan `CODENOMAD_SESSION_IDLE_SECONDS` ve `CODENOMAD_SESSION_ABSOLUTE_SECONDS` değişkenlerini pozitif tam sayı saniye olarak ayarlayın. Uzaktan Kontrol cihazları ayrı iptal edilir. -LAN istemcileri giriş, çıkış ve proje işlemlerini kullanabilir. Parola değişikliği, Uzaktan Kontrol yönetimi, uzak sunucu/proxy araçları ve SideCars, ana bilgisayarın loopback bağlantısından yönetilir. Tarayıcı değişiklikleri izin verilen Origin veya yoksa Referer gerektirir. Sunucunun duyurulan kaynaklarına izin verilir; DNS takma adları, ters proxy veya ayrı barındırılan arayüz için `CODENOMAD_ALLOWED_ORIGINS` değişkenine `https://code.example.test,https://ui.example.test:8443` gibi tam HTTP(S) kaynaklarını virgülle ayırarak yazıp yeniden başlatın. Yol veya joker karakter kullanmayın. Bu, tarayıcı erişimi verir; ana bilgisayar yetkisi vermez. Yerel LAN istemcileri de değişikliklerde izin verilen Origin göndermelidir. Loopback üzerinden bağlanan güvenilir proxy, ana bilgisayar yetkisine sahiptir ve kendi erişim denetimlerine ihtiyaç duyar. Sunucu loopback veya tüm arayüzlerde dinlediğinde, ana bilgisayarda aynı şema ve bağlantı noktasıyla `localhost` olarak açılan arayüz de çalışır. +LAN istemcileri giriş, çıkış ve proje işlemlerini kullanabilir. Parola değişikliği, Uzaktan Kontrol yönetimi, uzak sunucu/proxy araçları ve SideCars, ana bilgisayarın loopback bağlantısından yönetilir. Ana bilgisayardaki **SideCars'ı HTTPS üzerinden aç** ayarı, SideCars'ı güvenilir bir HTTPS origin üzerinden oturum açmış tarayıcılara açar; yalnızca bu adreslerin tüm kullanıcıları SideCar hizmetlerinizi kullanabilecekse açın. Tarayıcı değişiklikleri izin verilen Origin veya yoksa Referer gerektirir. Sunucunun duyurulan kaynaklarına izin verilir; DNS takma adları, ters proxy veya ayrı barındırılan arayüz için `CODENOMAD_ALLOWED_ORIGINS` değişkenine `https://code.example.test,https://ui.example.test:8443` gibi tam HTTP(S) kaynaklarını virgülle ayırarak yazıp yeniden başlatın. Yol veya joker karakter kullanmayın. Bu, tarayıcı erişimi verir; ana bilgisayar yetkisi vermez. Yerel LAN istemcileri de değişikliklerde izin verilen Origin göndermelidir. Loopback üzerinden bağlanan güvenilir proxy, ana bilgisayar yetkisine sahiptir ve kendi erişim denetimlerine ihtiyaç duyar. Sunucu loopback veya tüm arayüzlerde dinlediğinde, ana bilgisayarda aynı şema ve bağlantı noktasıyla `localhost` olarak açılan arayüz de çalışır. Yetkisiz erişimden şüpheleniyorsanız: diff --git a/docs/help/tr/server.md b/docs/help/tr/server.md index 93d08eec1a..8b896d9185 100644 --- a/docs/help/tr/server.md +++ b/docs/help/tr/server.md @@ -8,7 +8,7 @@ Aynı kullanıcı arayüzü [çoklu proje sekmeleri ve çalışma ağaçları](p 1. Node.js 24 LTS ve npm'yi yükleyin; havuzun derleme çalışma zamanı `.node-version` dosyasında sabitlenmiştir. Masaüstü paketleri kendi çalışma zamanlarını sağlar: Electron yerleşik Node'unu kullanır, Tauri Node'u paketler ve ikisi de npm içerir. 2. Git'i **arka uç sürecinin PATH** değişkenine ekleyin. Yalnızca WSL içindeki Git, Windows arka ucu için yeterli değildir. -3. OpenCode'u yükleyin veya seçin: **2.2.3** gerekli minimum değer, **2.2.7** ise önerilen yeterlilik hedefidir. Daha yeni veya özel derlemeler, test edilmiş sürüm izin verilenler listesine değil, uyumluluk denetimlerine tabi tutulur. Bkz. [OpenCode kurulumu](opencode.md). +3. OpenCode'u yükleyin veya seçin: **2.3.0** gerekli minimum değer, **2.3.0** ise önerilen yeterlilik hedefidir. Daha yeni veya özel derlemeler, test edilmiş sürüm izin verilenler listesine değil, uyumluluk denetimlerine tabi tutulur. Bkz. [OpenCode kurulumu](opencode.md). 4. Sunucunun başlatılacağı klasörü seçin veya `--workspace-root`'yi açıkça iletin. Git olmadan, konuşmalar yalnızca açıkça açılan fiziksel klasörde kullanılabilir durumda kalır; Git ve çalışma ağacı işlemleri başarısız oluyor. Git'i yükleyin ve PATH değişikliğinden sonra arka ucu yeniden başlatın. Çalışma alanı kökü, aracının yürütülmesini değil, açmayı/göz atmayı sınırlar: bkz. [Güvenlik](security.md). @@ -104,6 +104,8 @@ Genel referans, kullanıcıya yönelik seçenekleri listeler; masaüstü ana bil | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`; sürüm teklifleri için depo sorgulandı. | | `CODENOMAD_REMOTE_CONTROL_API` | Ayarlanmadı: barındırılan OpenTunnel API. Şirket içinde barındırılan geçiş dağıtımı için bir API kaynağı ayarlayın. | +| `CODENOMAD_REMOTE_CONTROL` | Ayarlanmamış: kullanıcılar Uzaktan Kontrol'ü başlatabilir. `disabled`: bir yönetici tarafından kapatıldı ([ilke](remote-control.md#administrator-policy)); ayarlanmamış veya boş: ilke yok, başka herhangi bir değer (boşluklar dahil) başlatmayı engeller. | +| `CODENOMAD_LOCKED_HOST` | Ayarlanmamış veya boş: `--host` geçerlidir; yalnızca boşluk başlatmayı engeller. Bir adres: sunucu `--host`, `CLI_HOST` veya dinleme anahtarından bağımsız olarak orada dinler ([ilke](remote-access.md#administrator-policy)). | | `NODE_EXTRA_CA_CERTS` | Node'un isteğe bağlı ek CA dosyası; eksik OpenCode daemon'ı başlatılırken izin verilen başlangıç ortamıyla iletilir. Çalışan daemon'ı değiştirmez. | Sağlayıcıya özel kullanım kimlik bilgileri, [Sağlayıcılar](providers.md) belgesinde ele alınmaktadır. Masaüstü veri profili seçimi [Masaüstü](desktop.md) kapsamındadır ve yayın akışı tarafından kontrol edilmez. diff --git a/docs/help/tr/settings.md b/docs/help/tr/settings.md index 78084e5eee..a80780685c 100644 --- a/docs/help/tr/settings.md +++ b/docs/help/tr/settings.md @@ -70,7 +70,7 @@ Sabitlenmiş bir paneli yeniden boyutlandırmak için iç kenarını sürükleyi 2. Sağ panelde **Sağ paneli özelleştir** öğesini açın. Yerleşik sekmeleri ve Durum bölümlerini seçmek için onay kutularını kullanın; en az bir Durum bölümü görünür durumda kalır. Birkaçını tek seferde ayarlamak için bu onay kutularının üzerinde sürükleyin. 3. Yeniden sıralamak için sağ panel sekmelerini sürükleyin. Yerleşik düzen seçeneklerini geri yüklemek için **Sıfırla** öğesini kullanın. -Tanınan [entegrasyonların](integrations.md#integration-sections) da Durum bölümleri vardır. Aynı onay kutularıyla gizleyin; tüm Durum bölümlerini sürükleyerek veya Yukarı/Aşağı tuşlarıyla sıralayın. Görünürlük ve sıra yeniden yüklemelerde ve entegrasyon geçici olarak yokken korunur. +Tüm Durum bölümlerini sürükleyerek veya Yukarı/Aşağı tuşlarıyla sıralayın. Görünürlük ve sıra yeniden yüklemelerde korunur. Durum; belirteç bilgilerini, Yolo modunu, sağlayıcı Kullanımı, arka plan kabuklarını, MCP ve Eklentileri içerir. Görüşmenin bir [hedefi](conversations.md#goal) olduğu sürece bu bölümlerin üzerindeki bir hedef satırı onu gösterir; bu satır bir bölüm değildir, gizlenemez ve taşınamaz. Bir bölümün gizlenmesi, o bölümün hizmetini devre dışı bırakmaz veya izinleri iptal etmez. Dar düzenler, konuşmayı sıkıştırmak yerine artık sığmayan panelleri kapatır; orada açılan bir panel konuşmanın üzerinde yüzer ve bir yüzer panelin açılması diğerini kapatır. diff --git a/docs/help/tr/troubleshooting.md b/docs/help/tr/troubleshooting.md index b04869b968..9a909ee9f7 100644 --- a/docs/help/tr/troubleshooting.md +++ b/docs/help/tr/troubleshooting.md @@ -42,7 +42,7 @@ Sahip olunan bir çalışma ağacı veya konuşma yerleşimi doğrulanamıyorsa, ## OpenCode çalışma zamanı ve WSL {#opencode-runtime} 1. **Preferences → OpenCode** öğesini açın ve **OpenCode sürümü** kartını (kurulu sürüm ve çalışan hizmet durumu), ardından **OpenCode Binary** altındaki seçili yürütülebilir dosyayı kontrol edin. -2. Gerekli çalışma zamanı yoksa desteklenen kurulum/güncelleme eylemini kullanın. Güncel alt sınır: **2.2.3**; önerilen/doğrulanan sürüm: **2.2.7**. +2. Gerekli çalışma zamanı yoksa desteklenen kurulum/güncelleme eylemini kullanın. Güncel alt sınır: **2.3.0**; önerilen/doğrulanan sürüm: **2.3.0**. 3. Kurulu CLI, çalışan hizmetten farklıysa, paylaşılan hizmetin yeniden başlatılıp başlatılmayacağına açıkça karar verin. **OpenCode hizmetini yeniden başlat**, **Sorun giderme** altında mevcuttur ve onay gerektirir. Bağlı her istemcideki aktif çalışmayı kesintiye uğratır ancak oturum geçmişini korur. Yapılandırmanın yeniden yüklenmesi ayrı bir eylemdir: süreci korur ancak yüklenen Konumları yeniden oluşturur ve bekleyen soruları/izinleri iptal eder. Zararsız bir yenileme de değildir. diff --git a/docs/help/zh-Hans/browser-sidecars.md b/docs/help/zh-Hans/browser-sidecars.md index 2ef14d624d..568798d987 100644 --- a/docs/help/zh-Hans/browser-sidecars.md +++ b/docs/help/zh-Hans/browser-sidecars.md @@ -77,7 +77,7 @@ SideCar 是 CodeNomad 的可信扩展,而不是沙箱预览:其页面以 CodeNomad 自身的源运行,因此其脚本可以凭借你的登录访问权限使用 CodeNomad。只注册你信任其代码的服务。CodeNomad 不会将自身的登录 cookie 转发给该服务,但会保留该服务自己的 cookie。 -SideCar 内容(`/sidecars/`)和 SideCar WebSocket 要求在主机上使用回环连接。通过 `/api/sidecars` 注册可供已配对设备和已认证的局域网直连客户端使用。持有有效能力令牌时,活动预览内容(`/previews/`)可通过局域网直接访问;[远程控制](remote-control.md#remote-surface)网页预览在启用时仍可通过其能力令牌访问。直接访问的要求请参阅[升级](remote-access.md#upgrading)。 +SideCar 内容(`/sidecars/`)和 SideCar WebSocket 要求在主机上使用回环连接。如需从其他设备打开,请在主机的**设置 → SideCars**中开启**通过 HTTPS 打开 SideCars**:通过此服务器的 HTTPS 地址或 `CODENOMAD_ALLOWED_ORIGINS` 中的 HTTPS 来源(例如 TLS 反向代理)登录的浏览器即可打开 SideCars。普通 HTTP、`localhost` 地址和远程控制仍仅限主机使用。通过 `/api/sidecars` 注册可供已配对设备和已认证的局域网直连客户端使用。持有有效能力令牌时,活动预览内容(`/previews/`)可通过局域网直接访问;[远程控制](remote-control.md#remote-surface)网页预览在启用时仍可通过其能力令牌访问。直接访问的要求请参阅[升级](remote-access.md#upgrading)。 ## OpenVSCode Server 示例 {#openvscode} diff --git a/docs/help/zh-Hans/conversations.md b/docs/help/zh-Hans/conversations.md index 5eedb3b0c0..5136b84e84 100644 --- a/docs/help/zh-Hans/conversations.md +++ b/docs/help/zh-Hans/conversations.md @@ -60,6 +60,12 @@ CodeNomad 将原生 OpenCode 会话呈现为对话,为委派工作提供层级 草稿是客户端工作状态,而非共享原生消息。启动恢复可以保留受支持的输入框状态,但不要将未发送草稿或附件视为备份,也不要假定它会出现在另一台设备。清除启动数据或关闭禁用了恢复策略的客户端之前,请保存重要文本;参阅[桌面](desktop.md)。 +## 从回复打开文件 {#open-files-from-replies} + +1. 智能体回复会用相对路径和绝对路径链接项目文件。 +2. 普通点击会在文件预览中打开链接的文件,内容从对话的工作树读取。 +3. 修饰键点击(Ctrl/Cmd、Shift、中键)以及指向会话工作树之外的链接保持普通链接行为。 + ## 命令和 Shell 模式 {#commands-shell} 1. 输入 `/` 并选择已发现的自定义命令,然后提供参数。 diff --git a/docs/help/zh-Hans/install.md b/docs/help/zh-Hans/install.md index 0724ac7401..2d888d6298 100644 --- a/docs/help/zh-Hans/install.md +++ b/docs/help/zh-Hans/install.md @@ -45,7 +45,7 @@ Electron Debian 安装过程会配置 Chromium 沙箱。不要通过禁用沙箱 | 要求 | 必须可用的位置 | 当前要求 | | --- | --- | --- | -| OpenCode CLI | 所选执行主机,适用时包括所选 WSL 发行版 | 最低 **2.2.3**;建议/已验证目标为 **2.2.7**。更新版本或自定义版本会接受契约验证,而非因未经测试就被禁止。 | +| OpenCode CLI | 所选执行主机,适用时包括所选 WSL 发行版 | 最低 **2.3.0**;建议/已验证目标为 **2.3.0**。更新版本或自定义版本会接受契约验证,而非因未经测试就被禁止。 | | Git | CodeNomad 后端账户的 `PATH` | 仓库身份识别、Git 操作和工作树必需。 | | Node.js/npm | 独立服务器和源码构建主机 | Node.js 24 LTS;可重现的源码构建使用 `.node-version` 中固定的版本。桌面发行包自带:Electron 内置 Node 或 Tauri 附带 Node,均含 npm。 | | 工作区文件夹 | 后端可访问的磁盘 | 显式打开的物理文件夹,而非远程浏览器推断出的设备本地文件夹。 | diff --git a/docs/help/zh-Hans/integrations.md b/docs/help/zh-Hans/integrations.md index 0f27cc266a..b1a0cb4914 100644 --- a/docs/help/zh-Hans/integrations.md +++ b/docs/help/zh-Hans/integrations.md @@ -27,7 +27,7 @@ CodeNomad 提供 OpenCode 的原生 MCP 连接、插件激活、技能和自定 CodeNomad 管理的插件不显示在普通插件列表中,也不提供列表中的激活、更新和移除控件。CodeNomad 通过经过验证的安装程序入口和以内容哈希标识的代码存储位置来识别它们;名称或 ID 相同的第三方插件仍保留普通控件。 -如果受管理的插件已禁用、加载失败或加载尚未确认,插件列表上方会显示 **CodeNomad 插件需要处理**。打开其 **i** 按钮(插件的“**详情**”)可查看已有的错误和 OpenCode 日志引用。只有已禁用的插件提供 **重新启用**:此操作会为精确 ID 追加一条启用规则,并保留禁用规则。如果禁用规则所在的 **全局** 或 **项目** 范围可写,就写入该范围,否则写入 **项目**。OpenCode 保持运行;直到原生事件或 **刷新插件控件** 确认插件已激活,警告才会消失。 +如果受管理的插件已禁用、加载失败或加载尚未确认,插件列表上方会显示 **CodeNomad 插件需要处理**。打开其 **i** 按钮(插件的“**详情**”)可查看已有的错误和 OpenCode 日志引用。只有已禁用的插件提供 **重新启用**:如果仅移除该插件的精确禁用规则即可重新启用,此操作会从该文件中移除它,否则为精确 ID 追加一条启用规则。如果禁用规则所在的 **全局** 或 **项目** 范围可写,就写入该范围,否则写入 **项目**。OpenCode 保持运行;直到原生事件或 **刷新插件控件** 确认插件已激活,警告才会消失。 警告及其详情会根据配置来源显示 **继承 / 外部** 或 **虚拟配置**。重新启用的写入目标与禁用规则来源不同时,会单独显示 **项目** 标签来标明目标。 @@ -38,7 +38,7 @@ CodeNomad 管理的插件不显示在普通插件列表中,也不提供列表 全局以所连接守护进程发现的全局配置为目标。项目以活动 Location 内的配置为目标,而非继承的祖先文件。后续项目规则可以覆盖全局;全局开关仍显示全局规则,而不会假装是最终项目状态。没有项目规则时,项目继承解析后的全局状态。 -这些开关追加精确激活规则,同时保留来源声明和无关配置。不会编辑插件选项、安装软件包或移除文件。内置 OpenCode 插件不会作为用户激活开关提供。项目目标无法安全地与全局分离,或会超出活动 Location 时,项目控件会禁用。 +每个开关会在其范围的文件中为插件写入一条精确激活规则,并替换该文件中同一插件之前的精确规则;如果结果相同,则只移除这些规则。来源声明、`*` 等更宽泛的规则以及无关配置都会保留。不会编辑插件选项、安装软件包或移除文件。内置 OpenCode 插件不会作为用户激活开关提供。项目目标无法安全地与全局分离,或会超出活动 Location 时,项目控件会禁用。 软件包更新会在 OpenCode 的共享缓存中更改该软件包,影响所有使用它的 Location,其工具提示中也会说明这一点;它不会更改激活规则、重启 OpenCode 或重新加载配置。本地、内置和 SDK 提供的插件没有软件包操作。在报告插件 ID 之前就加载失败的软件包会按软件包名称列出,其工具提示中包含失败信息,并提供检查/更新操作,但没有激活开关。检查或更新失败会被报告,且绝不会自动重试。 @@ -78,38 +78,30 @@ CodeNomad 管理的插件不显示在普通插件列表中,也不提供列表 命令由 OpenCode 针对活动 Location 发现。其自身的原生定义可以选择执行行为;菜单不是软件包安装程序或无限制配置编辑器。CodeNomad 会在提交原生自定义命令前应用配置文件的会话环境;环境更新失败会阻止发送。`/btw` 是 CodeNomad 独立的临时提问流程,而非普通自定义命令。 命令定义和原生配置继承请使用 [OpenCode 命令文档](https://opencode.ai/v2/docs/commands/)。配置更改后,先刷新/重新打开相关界面;仅当运行时仍需要时才显式重新加载配置。切勿仅为刷新显示而重放可能已接纳的命令。 -## 状态中的集成区域 {#integration-sections} +## 插件中的集成 {#integration-rows} **状态 → 插件**中的 **+** 提供**添加集成…**和**添加插件…**。集成选择器列出已审核目录中尚未安装的条目。选择范围和**安装**后,CodeNomad 按所选目录 ID 安装。原生集成**仅全局**可用。**目录不可用**提供**刷新**;**{date} 的目录**表示使用已过期的最后一个有效目录。 -每个有声明或已加载/加载失败插件的已识别集成都有自己的**状态**区域,包括已禁用或正在安装的集成。来源有歧义时,插件行显示**不符合规范**。每个集成都保留插件行,提供更新、移除和刷新操作。展开集成区域可在正文中查看版本和插件控件;名称和状态始终显示在标题中,旁边是**文档**和 **i**。**i** 弹出窗口按需显示详情:按 Enter/空格打开,按 Escape 关闭。 +已识别的集成在**状态 → 插件**中只有一行,显示其名称(例如 **OpenCode for Blender**)和版本。它的**全局**和**项目**开关与其他开关一样使用强调色,普通插件的开关为绿色;在应用中带有组件的集成**仅全局**可用。悬停其名称:详情以**集成**而不是**插件**开头;屏幕阅读器会把它们作为该行的描述读出。来源不明确时显示**不符合规范**。 -通过状态自定义菜单可隐藏所有状态区域,并通过拖动或上/下方向键调整顺序。可见性和顺序在重新加载或集成暂时缺失后仍会保留。如果当前聚焦的区域消失,焦点返回插件区域;插件区域隐藏时,则移至其他可见的状态区域。 +名称下方的状态行始终说明集成的当前情况。灰色文字用于提示;强调色文字是按钮。对于在应用中带有组件的集成,显示最重要的状态:组件缺失或过旧时显示**安装到 Blender** 或**更新 Blender**(带安装确认),不兼容时使用警告色,当前对话已连接时显示链条图标和文档(选择即可分离),**Blender 已关闭**,**Blender:没有打开的文档**,**未显示对话**,然后是带文档名的**连接**,或在多个文档间选择的**连接…**。对话的代理第一次使用该集成时,对话也会自动连接。编辑器 MCP 集成显示**已检测到服务器**或**未找到服务器**,API 集成显示**已连接**或**已断开**。过长的状态会被截断;悬停即可查看全文。集成报告的变化和重新连接会刷新该行。 -目录安装、应用部分安装/更新、连接和移除均须确认。初始焦点位于**取消**,确认操作在 600 毫秒后可用。激活和插件更新直接执行。 +该行的 **…** 菜单以连接状态开头,例如 **Blender:1 个打开的文档**或 **Blender 已关闭**。随后提供**文档**、**安装到应用…**、**更新应用…**或**重新安装到应用…**([见下文](#application-installation))、软件包更新检查、**从全局移除**或**从项目移除**以及**刷新插件控件**。分离只需单击一次,无需确认,并且只影响此对话:应用保持打开,其组件保持安装,其他对话保留各自的连接。如果响应丢失,该行会重新读取状态;请求绝不会重复发送。 -## 连接已打开的应用 {#application-attachment} +从目录安装、安装或更新应用组件以及移除都需要确认。**取消**首先获得焦点;确认操作在 600 毫秒后可用。启用、插件更新、连接和分离会直接执行。 -从应用的集成功能中提供文档,打开**状态 → 该集成 → 会话**,选择**连接…**。此区域控制当前显示会话的连接。选择应用和文档,检查目标会话及修改警告,然后用**连接**确认。应用运行在 OpenCode 所在的机器上,包括远程连接。不受支持的主机(包括 WSL)通过 **i** 提供帮助。 - -**会话**行读取当前显示会话的绑定状态。**绑定未知**提供**刷新**。当最新的权威读取确认连接后,**断开**取代**连接…**。单击即可断开此会话,无需再次确认;应用保持打开,应用部分保持安装,其他会话保留其绑定。原生变化和重新连接会刷新状态。 - -操作提交后,只要目标会话仍在显示,就会保留其结果或错误;导航会关闭回执。当前绑定以权威读取为准。响应丢失、超时或连接中断后的**状态不确定**提供**刷新**以读取实际状态。切勿为了刷新显示而重发请求。 - -在选择器中明确读取已打开的应用后,保存的 Q8 元数据可为相同集成和已验证的文档标签在选择器或**会话**行提供**重新连接**建议,前提是项目、会话和连接代次保持一致。重新连接需要明确确认;导航或数据失效会清除建议。当前绑定的权威信息来自集成针对该会话的读取。 - -从集成区域或其插件行移除时,使用同一声明及范围确认。移除无需普查会话,也不会自动断开连接。 +移除时不会统计对话,也不会自动分离。 移除前的警告会列出插件和确切范围。初始焦点位于 **取消**;**从全局/项目移除** 在 600 毫秒后可用,且需要明确操作。移除可能中断使用该插件的对话中的可用性和连接;全局范围也可能影响其他项目。提交前取消、过期或切换页面不会产生更改。仅移除确认的声明,保留规则、缓存、应用文件及保存的连接提示。配置变化后须重新选择并确认。成功表示声明已移除,运行状态随后由 OpenCode 重新加载更新。如果响应丢失,请先刷新插件核实实际配置,再重新尝试。重新安装可能恢复可用性,但可能需要重新加载或重新附加,中断的操作可能无法继续。 ## 安装或更新应用集成 {#application-installation} -在**状态 → 该集成 → 应用**中,当最新状态提供相应操作时,选择**安装到应用…**或**更新应用…**。无需会话或已提供的文档也可使用。应用关闭时,请打开它以检查应用部分;**i** 提供机器和前提条件的详情。 +在**状态 → 插件**中,当集成的最新状态提供该操作时,在其状态行中选择**安装到 Blender** 或**更新 Blender**,或在其 **…** 菜单中选择**安装到应用…**、**更新应用…**或**重新安装到应用…**。无论应用打开还是关闭,重新安装都会重写应用组件。没有对话或打开的文档时也可使用。 确认对话框会显示应用名称,以及提供安装程序的 **集成包版本**。请核对两者和机器警告:安装运行在 OpenCode 所在的机器上,该机器可能是远程机器。初始焦点位于 **取消**。必须明确确认才能继续。确认前切换项目、Location 或会话,重新连接,或收到相关原生变化,都会取消待定授权;请重新打开操作以核对最新详情。 WSL 始终拒绝应用内安装,即使已打开的应用看起来兼容。请在受支持的机器上打开应用。 -结果会报告集成已安装、已更新、已是最新版本、被拒绝或失败。安装或更新后,请打开应用并检查其集成;通过 [连接已打开的应用](#application-attachment) 单独连接会话。安装成功描述的是安装请求的结果;应用是否实际可用由应用状态反映。 +结果会报告应用组件已安装、已更新、已是最新、被拒绝或失败。安装或更新后,请打开应用并检查其集成。安装成功描述的是安装程序请求;应用的实际可用性取决于其状态。 请求绝不会自动重试。被拒绝或失败后,请先检查应用,再选择新操作。如果错误导致结果不确定,请勿重复该请求:先检查应用,再根据需要发起新操作并重新确认。 diff --git a/docs/help/zh-Hans/missions.md b/docs/help/zh-Hans/missions.md index 106a7d52bf..677af927e6 100644 --- a/docs/help/zh-Hans/missions.md +++ b/docs/help/zh-Hans/missions.md @@ -42,7 +42,7 @@ ### 自动启动 {#automatic-start} -**自动启动**位于计划之外,默认关闭。关闭时创建暂停的任务,之后用 ▶ 启动;开启时在创建确认后请求启动,仍执行通常的检查及所需的原生设置确认。 +**自动启动**位于计划之外,默认关闭。关闭时创建暂停的任务,之后用 ▶ 启动;开启时在创建确认后请求启动,并执行通常的检查和自动计划准备。 创建确认丢失后,读取回执仍需手动启动。保留原始未确认请求,再次创建前先检查列表和对话。 @@ -56,6 +56,8 @@ 可选一次现在、每 N 小时、每天、选定星期、每月某日和 cron。时间遵循保存的时区;与系统不同才显示时区字段。没有指定日期的月份会跳过。一次现在以启动时刻为准,只有一次机会,条件可能消耗机会而不启动。需要 OpenCode 服务和执行主机可用。 +启动或恢复时,会在项目的 OpenCode 配置中自动准备计划功能。明确的 OFF 设置会保留:如有**打开计划设置**操作,可打开负责该设置的文件;**i** 可显示来源或环境详情。只有请求期间,所点击的按钮才会显示加载状态。未确认的结果可进行核查;恢复启用状态后,仍需明确执行启动操作。 + ### 事件和组合 {#scheduling-conditions} 选择**仓库活动 → 事件**,再在同一卡片中填写可选筛选条件。Git 提交与自动检测到的 GitHub、GitLab 或 Gitea 仓库事件共用一个菜单,检测方式与 Contribute 相同:先 `upstream`,再 `origin`。三者都支持新建 PR/MR、已合并 PR/MR 和新建 Issue,并可按**作者(可选)**筛选,包括 `dependabot[bot]`。选择事件会固定其仓库;已保存条件保留原目标。 @@ -88,9 +90,11 @@ ### 颜色和状态 {#status-colours} -旗帜显示任务状态,箭头显示子任务的待关注状态;重复任务使用循环图标。红色等待回答,脉动黄色表示观察到工作,橙色表示暂停/中断,绿色表示未查看的完成结果,蓝色表示准备或尚未启动。 +旗帜显示任务状态,箭头显示子任务的待关注状态;重复任务使用循环图标。红色等待回答,脉动黄色表示观察到工作。橙色暂停符号表示暂停,橙色警告三角形表示中断。绿色表示待查看的任务、子任务或成功运行。 + +强调色图标下方的小型静止中性色横线表示**等待计划运行**:下一次唤醒已确认。强调色随调色板变化。单独的强调色图标表示已准备或尚未启动。已查看的完成结果、已停止的计划和**状态未确认**显示为中性色;请阅读状态文字。 -选择、点击/扫过绿色子任务图标,或用箭头菜单标记已读可确认结果。阻塞不一定是向你提问;报告不证明所有原生操作已结束。撤回子任务会保留历史。 +选择任务、点击/扫过绿色子任务图标,或使用箭头菜单中的**标为已读**可确认结果。对于**成功运行待查看**,在活动窗口中明确选择重复任务行,或使用**标为已读**确认该次运行。计划仍启用时图标恢复等待状态,否则恢复中性色。恢复的选择和已选中行收到的新结果会保留新结果的未读状态。首次加载时已有的历史成功视为已读。撤回子任务会保留历史。 ### 问题和决策 {#questions} diff --git a/docs/help/zh-Hans/mobile.md b/docs/help/zh-Hans/mobile.md index 1e2f37bc41..354e3bf556 100644 --- a/docs/help/zh-Hans/mobile.md +++ b/docs/help/zh-Hans/mobile.md @@ -42,3 +42,5 @@ | 离线工作 | 无离线后端或缓存 API 历史。静态界面资源可能缓存,但文档和 API 响应不是离线工作区。 | 请保持后端可达。移动操作系统挂起或网络切换可能断开事件流;返回后会重新连接并重新获取当前状态,不保证事件重放。重试操作前检查是否已完成。关闭 PWA 不会停止独立后端;退出主机桌面应用及其后端会使远程控制不可用,直到下次启动。 + +每个浏览器标签页(包括已安装的 PWA)都会为该标签页保留打开的项目、选中的对话、未发送的草稿和滚动位置:页面重新加载,或移动系统在切换应用或锁屏后重新加载页面时,它们都会恢复。新标签页,或被系统完全关闭的 PWA,会打开主页。要为该标签页关闭此功能,请使用 **设置 → 常规 → 恢复上次状态**。 diff --git a/docs/help/zh-Hans/opencode.md b/docs/help/zh-Hans/opencode.md index f3fb79882d..c6369d57e7 100644 --- a/docs/help/zh-Hans/opencode.md +++ b/docs/help/zh-Hans/opencode.md @@ -19,8 +19,8 @@ CodeNomad 连接到执行主机上的共享 OpenCode 服务。选择 CLI、更 | 分类 | 当前要求 | 含义 | | --- | --- | --- | -| 最低 | OpenCode **2.2.3** | **图像**设置和 Design 扩展使用的图像生成工具、Code Mode 中 JavaScript 任务的正确执行顺序,以及原生重放和压缩格式;旧版本保存的对话在更新后仍可读取。 | -| 推荐 | OpenCode **2.2.7** | 已验证目标,与技术最低要求不同。 | +| 最低 | OpenCode **2.3.0** | **图像**设置和 Design 扩展使用的图像生成工具、Code Mode 中 JavaScript 任务的正确执行顺序,以及原生重放和压缩格式;旧版本保存的对话在更新后仍可读取。它还以后台报告的形式传递子代理结果,供子代理卡片和任务读取。 | +| 推荐 | OpenCode **2.3.0** | 已验证目标;目前与最低版本相同。 | | 未验证 | 尚未完整验证的更新版本或自定义版本 | 不会仅因未经测试而拒绝;会检查所连接服务的实际 API 契约。 | 所连接的服务必须提供所需的会话、权限、Form、收件箱和会话环境契约。原生任务计划还会检查计划 API、插件/提供商包和实际生效的 `experimental.schedules` 设置。可用性取决于这些实际使用的能力,也适用于兼容的未来版本。如果设置报告运行中的服务不受支持,请选择/安装受支持的 CLI,并在准备好后显式重启共享服务。 diff --git a/docs/help/zh-Hans/projects.md b/docs/help/zh-Hans/projects.md index a354c0ec2d..9d8b6a3a4c 100644 --- a/docs/help/zh-Hans/projects.md +++ b/docs/help/zh-Hans/projects.md @@ -34,7 +34,7 @@ | 关闭标签页 | 移除该标签页的 CodeNomad 项目连接;在同一文件夹上单独打开的其他标签页不受影响 | 不会删除项目文件或原生历史记录,不会停止会话,也不会卸载 OpenCode 的 Location | | 停止会话 | 所选对话的执行 | 不会关闭项目或删除历史记录 | -若另一窗口显示的是同一个项目连接,其标签页也会关闭,并且该窗口会显示通知;发起关闭的窗口不显示通知。关闭会立即生效;如果后端无法关闭该项目,会显示错误,主页上的**切换到已打开的项目**仍可访问它。不会自动重试。已关闭标签页中的未发送草稿不会保留在启动恢复中。 +若另一窗口显示的是同一个项目连接,其标签页也会关闭,并且该窗口会显示通知;发起关闭的窗口不显示通知。关闭会立即生效;如果后端无法关闭该项目,会显示错误,主页上的**切换到已打开的项目**仍可访问它。不会自动重试。已关闭标签页中未发送的草稿和附件,会在同一窗口中重新打开同一文件夹时恢复;窗口会为最近关闭的 16 个项目保留它们,直到窗口重新加载或关闭。它们不属于启动恢复。 关闭整个窗口、退出或重新加载不会关闭其项目连接;正常的启动恢复仍然适用。如需确认执行已结束,请显式停止相关运行。CodeNomad 绝不会卸载原生 Location;共享服务维护请参阅 [OpenCode 设置](opencode.md)。 @@ -59,7 +59,7 @@ | 选择 | 影响 | 恢复方式 | | --- | --- | --- | | 保留 | 在 CodeNomad 中关闭该项目,保留文件夹和对话,移除临时状态并添加到最近项目 | 从最近列表重新打开;文件夹不会移动 | -| 丢弃 | 删除临时工作区的对话和文件 | 无法撤销;请先将所需内容另存到其他位置 | +| 丢弃 | 删除临时工作区的对话、文件和未发送的草稿 | 无法撤销;请先将所需内容另存到其他位置 | | 取消 | 保持临时工作区打开 | 继续工作或稍后决定 | 没有对话、文件或未发送草稿的未使用临时标签页会在关闭时静默丢弃。打开的临时标签页参与正常的启动恢复,但主页没有单独用于恢复已关闭临时文件夹的列表。 diff --git a/docs/help/zh-Hans/providers.md b/docs/help/zh-Hans/providers.md index 85544376aa..2ad6b6f58a 100644 --- a/docs/help/zh-Hans/providers.md +++ b/docs/help/zh-Hans/providers.md @@ -56,15 +56,15 @@ Google 的 [Antigravity 常见问题](https://antigravity.google/docs/faq/)指出,通过 Antigravity 登录使用第三方软件违反其服务条款,并可能导致账户被暂停或终止。 -对于 `opencode` 集成的付费模型,**OpenCode Console** 显示**今天(UTC)**、**7天(UTC)**和**30天(UTC)**的**请求数**。这些周期是包含今天的 UTC 日历日,分别从今天、六天前和 29 天前的 UTC 00:00 开始。**按模型统计请求数 · 30天**列出每个模型及其提供商。计数涵盖已连接的 Console 账户,数字按应用语言格式化。**服务账户预算**显示**预算不可用。** OpenCode Go 使用独立的配额读取器。 +对于 `opencode` 集成的付费模型,**OpenCode Console** 显示 Console 报告的**24小时**、**7天**和**30天**的**请求数**。**按模型统计请求数 · 30天**列出每个模型及其提供商。计数涵盖已连接的 Console 账户,数字按应用语言格式化。**服务账户预算**显示**预算不可用。** 启用**提供商额度余额**后,Console 额度余额显示为**额度**。OpenCode Go 使用独立的配额读取器。 读取器使用已保存的 `opencode` API 密钥,并优先使用其 Console OAuth 连接。OAuth 要求 `https://opencode.ai/console` 以及连接的组织 ID;访问 Console 需要 **Usage › Read** 权限。CodeNomad 从不刷新这些凭据。即使同时保存了 API 密钥,无效或过期的 OAuth 连接也必须通过其所属服务修复。 Console 错误区分未连接、凭据无效或过期(401)、访问被拒绝(403)、用量响应无效及网络故障。遇到连接错误时,前往**设置 → 提供商**检查登录及权限,然后刷新**用量**。任一摘要或模型分页读取失败都会使整次 Console 读取不可用。 -对于 OpenCode 免费模型(`big-pickle` 和 ID 以 `-free` 结尾的模型),**用量**仅汇总已连接 Console 账户自 UTC 00:00 起的免费请求,并与每日 **800** 次的参考值比较。**估算**指配额及下一个 UTC 午夜的重置时间;实际限制可能不同。计数包括同一账户的其他客户端。未连接 Console 时,面板提示通过**设置 → 提供商**连接以使用免费模型并查看配额。Console 读取失败时,计数保持不可用。 +对于 OpenCode 免费模型(`big-pickle` 和 ID 以 `-free` 结尾的模型),**用量**显示一个进度条:已连接 Console 账户在 Console 报告的最近 24 小时内的免费请求数,与 **800** 次的参考值比较;实际限制可能不同。计数包括同一账户的其他客户端,没有重置时间。启用**提供商额度余额**后,Console 额度余额显示为**额度**。未连接 Console 时,面板提示通过**设置 → 提供商**连接 OpenCode Console。Console 读取失败时,计数保持不可用。 -免费步骤发生配额错误后,该 OpenCode 连接标记为**已耗尽**,直到 UTC 00:00。Console 计数可用时,进度条显示 100% 并保留计数。该标记按连接保存在后端内存中,重启后清除。免费用量、耗尽标记及付费 Console 计数仅用于显示;自动账户选择使用独立的读取器和规则。 +免费用量和付费 Console 计数仅用于显示;自动账户选择使用独立的读取器和规则。 OpenAI 不为某一种 ChatGPT 登录方式提供用量:此时用量面板会说明这一点,而不显示配额窗口。选择[查看 ChatGPT 用量](https://chatgpt.com/settings/usage),即可在 ChatGPT 中查看应用用量,并管理应用对您的套餐和额度的访问。聊天仍可正常使用,重新连接同一登录也不会恢复该读数。 diff --git a/docs/help/zh-Hans/remote-access.md b/docs/help/zh-Hans/remote-access.md index 03ee446cfd..cf23b5e771 100644 --- a/docs/help/zh-Hans/remote-access.md +++ b/docs/help/zh-Hans/remote-access.md @@ -52,11 +52,15 @@ codenomad --host 127.0.0.1 --https=false --http=true 不要假定端口是 9898 或 9899:省略端口时,繁忙会回退。显式非零的 `--https-port`,或启用 HTTP 时的 `--http-port`,会固定端口,无法绑定则失败;`0` 请求操作系统分配。本次运行以打印的 **Local Connection URL**、**Remote Connection URL** 和刷新的**可访问地址**为准。参阅完整[服务器 CLI 参考](server.md)。 +## 管理员策略 {#administrator-policy} + +管理员可以固定监听地址:在系统范围将 `CODENOMAD_LOCKED_HOST` 设置为服务器必须使用的地址,然后重启 CodeNomad。它优先于 `--host`、`CLI_HOST` 和 **允许其他 IP 连接**;该开关会显示结果,但无法更改。使用内网地址可让同事通过公司网络访问服务器,使用 `127.0.0.1` 则仅限本机。若要让所有访问都留在公司网络内,还需设置 `CODENOMAD_REMOTE_CONTROL=disabled`([远程控制](remote-control.md#administrator-policy))。 + ## 升级 {#upgrading} 升级后请重新登录。使用主机名别名、反向代理或单独托管的界面时,请在后端设置 `CODENOMAD_ALLOWED_ORIGINS`,列出可信的界面来源(协议、主机名和端口)。局域网原生客户端必须在修改请求中提供允许的 `Origin` 请求头。其 HTTPS 来源还允许主机在没有隧道的情况下配对设备;参阅[通过直接 HTTPS 配对](remote-control.md#direct-https)。 -仅限主机的操作需要回环连接:SideCar 内容(`/sidecars/`)及 WebSocket、远程控制管理(`/api/remote-control/`)、插件桥接(`/api/opencode-plugin/`)、远程代理(`/api/remote-proxy/`)、已保存服务器管理(`/api/remote-servers/`)、密码更改和令牌初始化。即使通过局域网直接访问并已登录,这些操作也要求回环连接。持有有效能力令牌时,活动预览内容(`/previews/`)可通过局域网直接访问。 +仅限主机的操作需要回环连接:SideCar 内容(`/sidecars/`)及 WebSocket、远程控制管理(`/api/remote-control/`)、插件桥接(`/api/opencode-plugin/`)、远程代理(`/api/remote-proxy/`)、已保存服务器管理(`/api/remote-servers/`)、密码更改和令牌初始化。即使通过局域网直接访问并已登录,这些操作也要求回环连接。只有 SideCars 例外:主机的**通过 HTTPS 打开 SideCars**设置会向通过可信 HTTPS 来源登录的浏览器开放其内容和 WebSocket([SideCars](browser-sidecars.md#register-sidecar))。持有有效能力令牌时,活动预览内容(`/previews/`)可通过局域网直接访问。 `/api/sidecars` 注册 API 仍可供已认证的局域网直连客户端和已配对设备使用。远程控制网页预览在主机启用时,仍可通过其能力令牌访问。 diff --git a/docs/help/zh-Hans/remote-control.md b/docs/help/zh-Hans/remote-control.md index 30477bb89a..039c8fc8c7 100644 --- a/docs/help/zh-Hans/remote-control.md +++ b/docs/help/zh-Hans/remote-control.md @@ -86,3 +86,7 @@ CodeNomad 使用 [OpenTunnel](https://github.com/anomalyco/opentunnel),在机 TLS 在 CodeNomad 后端终止。中继转发密文,无法读取应用内容,但可观察主机名、连接时间和流量大小。隧道证书/私钥保留在主机上。请将主机隧道存储和 CodeNomad 配置作为凭据保护;难以猜测的地址不等于授权。 `CODENOMAD_REMOTE_CONTROL_API` 选择自托管 OpenTunnel API;未设置则使用托管服务。这改变隧道部署,而非配对要求或被阻止的界面。凭据和诊断信息处理请参阅[安全](security.md)。 + +## 管理员策略 {#administrator-policy} + +管理员可以为一台计算机上的所有用户关闭远程控制:在系统范围设置环境变量 `CODENOMAD_REMOTE_CONTROL=disabled`,然后重启 CodeNomad。后端将不会连接隧道,会拒绝 **启动远程控制** 和配对链接,启动时也不会重新连接;设置中显示 **已被管理员禁用**。之前配对的设备无法连接,并保留在列表中以便撤销。未设置或为空时不应用任何策略;任何其他值(包括仅含空格)都会阻止后端启动。 diff --git a/docs/help/zh-Hans/security.md b/docs/help/zh-Hans/security.md index 828782dec1..1eb91a3ba3 100644 --- a/docs/help/zh-Hans/security.md +++ b/docs/help/zh-Hans/security.md @@ -33,7 +33,7 @@ 退出登录会撤销当前直接会话。在主机成功更改密码会撤销该用户的所有直接会话,包括当前会话;请重新登录。会话在 24 小时没有经过认证的请求后,或创建七天后过期。要调整期限,请在启动后端前将 `CODENOMAD_SESSION_IDLE_SECONDS` 和 `CODENOMAD_SESSION_ABSOLUTE_SECONDS` 设为正整数秒。远程控制设备需单独撤销。 -LAN 客户端可以登录、退出和使用项目。密码更改、远程控制管理、远程服务器/代理工具和 SideCars 由主机通过回环连接管理。浏览器修改请求须提供允许的 Origin,缺少 Origin 时则检查 Referer。服务器公布的来源默认允许;如使用 DNS 别名、反向代理或单独托管的界面,请将 `CODENOMAD_ALLOWED_ORIGINS` 设为逗号分隔的精确 HTTP(S) 来源,例如 `https://code.example.test,https://ui.example.test:8443`,然后重启。不要包含路径或通配符。这仅授予浏览器访问权,不授予主机权限。原生 LAN 客户端修改请求也须发送允许的 Origin。通过回环连接的可信代理具有主机权限,须自行实施访问控制。当服务器监听回环地址或所有接口时,在主机上以相同协议和端口通过 `localhost` 打开的界面同样可用。 +LAN 客户端可以登录、退出和使用项目。密码更改、远程控制管理、远程服务器/代理工具和 SideCars 由主机通过回环连接管理。主机的**通过 HTTPS 打开 SideCars**设置会向通过可信 HTTPS 来源登录的浏览器开放 SideCars;仅当这些地址的所有用户都可以使用你的 SideCar 服务时才开启。浏览器修改请求须提供允许的 Origin,缺少 Origin 时则检查 Referer。服务器公布的来源默认允许;如使用 DNS 别名、反向代理或单独托管的界面,请将 `CODENOMAD_ALLOWED_ORIGINS` 设为逗号分隔的精确 HTTP(S) 来源,例如 `https://code.example.test,https://ui.example.test:8443`,然后重启。不要包含路径或通配符。这仅授予浏览器访问权,不授予主机权限。原生 LAN 客户端修改请求也须发送允许的 Origin。通过回环连接的可信代理具有主机权限,须自行实施访问控制。当服务器监听回环地址或所有接口时,在主机上以相同协议和端口通过 `localhost` 打开的界面同样可用。 怀疑被入侵时: diff --git a/docs/help/zh-Hans/server.md b/docs/help/zh-Hans/server.md index 1a739c843a..3c72cac0cc 100644 --- a/docs/help/zh-Hans/server.md +++ b/docs/help/zh-Hans/server.md @@ -8,7 +8,7 @@ 1. 安装 Node.js 24 LTS 和 npm;仓库构建运行时固定在 `.node-version` 中。桌面包提供自己的运行时:Electron 使用内置 Node,Tauri 附带 Node,两者均包含 npm。 2. 将 Git 加入**后端进程的 PATH**。仅 WSL 内的 Git 不满足 Windows 后端。 -3. 安装或选择 OpenCode:必需最低版本为 **2.2.3**,推荐验证目标为 **2.2.7**。更新或自定义构建会接受兼容检查,而非已测试版本白名单。参阅 [OpenCode 设置](opencode.md)。 +3. 安装或选择 OpenCode:必需最低版本为 **2.3.0**,推荐验证目标为 **2.3.0**。更新或自定义构建会接受兼容检查,而非已测试版本白名单。参阅 [OpenCode 设置](opencode.md)。 4. 选择启动服务器的文件夹,或显式传入 `--workspace-root`。 没有 Git 时,对话仅在显式打开的物理文件夹内可用;Git 和工作树操作失败。安装 Git,更改 PATH 后重启后端。工作区根目录限制打开/浏览,而非智能体执行:参阅[安全](security.md)。 @@ -104,6 +104,8 @@ HTTPS 首选端口 **9898**,HTTP 首选 **9899**。没有端口覆盖时,首 | --- | --- | | `CODENOMAD_GITHUB_REPO` | `NeuralNomadsAI/CodeNomad`;查询发行版本的仓库。 | | `CODENOMAD_REMOTE_CONTROL_API` | 未设置:托管 OpenTunnel API。自托管中继部署时设置 API 来源。 | +| `CODENOMAD_REMOTE_CONTROL` | 未设置:用户可以启动远程控制。`disabled`:已被管理员关闭([策略](remote-control.md#administrator-policy));未设置或为空表示无策略,任何其他值(包括空格)都会阻止启动。 | +| `CODENOMAD_LOCKED_HOST` | 未设置或为空:使用 `--host`;仅含空格会阻止启动。一个地址:无论 `--host`、`CLI_HOST` 或监听开关如何设置,服务器都在该地址监听([策略](remote-access.md#administrator-policy))。 | | `NODE_EXTRA_CA_CERTS` | Node 可选额外 CA 文件;启动缺失的 OpenCode 守护进程时与允许的启动环境一起传递。不改变已运行守护进程。 | 提供商专用用量凭据见[提供商](providers.md)。桌面数据配置文件选择见[桌面](desktop.md),不受发布通道控制。 diff --git a/docs/help/zh-Hans/settings.md b/docs/help/zh-Hans/settings.md index d1d106e407..b386d58e74 100644 --- a/docs/help/zh-Hans/settings.md +++ b/docs/help/zh-Hans/settings.md @@ -70,7 +70,7 @@ 2. 在右侧面板打开**自定义右侧面板**。使用复选框选择内置标签页和状态部分;至少一个状态部分须保持可见。在这些复选框上拖动可一次设置多个。 3. 拖动右侧面板标签页重新排序。使用**重置**恢复内置布局选择。 -已识别的[集成](integrations.md#integration-sections)也有状态区域。可通过相同的复选框隐藏,并通过拖动或上/下方向键调整任何状态区域的顺序。可见性和顺序在重新加载或集成暂时缺失后仍会保留。 +可以拖动或使用上/下方向键调整任何状态区域的顺序。可见性和顺序在重新加载后仍会保留。 状态包含 Token 信息、Yolo 模式、提供商用量、后台 Shell、MCP 和插件。只要对话有[目标](conversations.md#goal),这些部分上方就会有一行显示它;该行不是部分,无法隐藏或移动。隐藏部分不会禁用服务或撤销权限。窄布局会关闭放不下的面板,而非挤压对话;在此布局中打开的面板浮于对话之上,打开一个浮动面板会关闭另一个。 diff --git a/docs/help/zh-Hans/troubleshooting.md b/docs/help/zh-Hans/troubleshooting.md index 517ae9c2b7..9281740634 100644 --- a/docs/help/zh-Hans/troubleshooting.md +++ b/docs/help/zh-Hans/troubleshooting.md @@ -42,7 +42,7 @@ Electron 使用 Chromium,可作为同一主机上的替代方案。如果 AppI ## OpenCode 运行时与 WSL {#opencode-runtime} 1. 打开**偏好设置 → OpenCode**,检查 **OpenCode 版本**卡片(已安装版本和运行服务状态),然后检查 **OpenCode 可执行文件**下所选的可执行文件。 -2. 缺少必需运行时时,使用受支持安装/更新操作。当前最低版本:**2.2.3**;推荐/已验证版本:**2.2.7**。 +2. 缺少必需运行时时,使用受支持安装/更新操作。当前最低版本:**2.3.0**;推荐/已验证版本:**2.3.0**。 3. 已安装 CLI 与运行服务不同时,显式决定是否重启共享服务。 **故障排查**下提供**重启 OpenCode 服务**,需要确认。会中断所有已连接客户端的活动工作,但保留会话历史。重新加载配置是独立操作:保留进程,但重建已加载 Location 并取消待处理问题/权限。两者都不是无害刷新。 diff --git a/docs/screenshots/README.md b/docs/screenshots/README.md index ce44c72d97..f37dbe569e 100644 --- a/docs/screenshots/README.md +++ b/docs/screenshots/README.md @@ -35,12 +35,13 @@ and session/project names in the adjacent `readme-workspace-data.ts`. Update thi data when refreshing documentation; keep product layout and styling in the real components. -# Integration Status captures +# Integration Plugins captures -`integration-status-{light,dark,catalog,customization}.png` show the real Status components with synthetic -integration, plugin and conversation data. `packages/ui/tests/browser/integration-status-section.test.ts` -generates them when `CODENOMAD_INTEGRATION_SCREENSHOTS` names an output directory. The dark capture includes -the keyboard-opened information Popover; the other captures show the attached section, catalog and customization. +`integration-plugins-{light,dark}.png` show the real Plugins rows of two integrations and a plain plugin with +synthetic data: one integration's state line offers to install its application part, the other to attach a +document. The same test writes `integration-state--{light,dark}.png`, one Blender row per state line. +`packages/ui/tests/browser/integration-plugin-row.test.ts` generates them when `CODENOMAD_INTEGRATION_SCREENSHOTS` +names an output directory. # Help home tour diff --git a/docs/screenshots/integration-plugins-dark.png b/docs/screenshots/integration-plugins-dark.png new file mode 100644 index 0000000000..15fa9d2b78 Binary files /dev/null and b/docs/screenshots/integration-plugins-dark.png differ diff --git a/docs/screenshots/integration-plugins-light.png b/docs/screenshots/integration-plugins-light.png new file mode 100644 index 0000000000..2aed3d6ab2 Binary files /dev/null and b/docs/screenshots/integration-plugins-light.png differ diff --git a/docs/screenshots/integration-status-catalog.png b/docs/screenshots/integration-status-catalog.png deleted file mode 100644 index c83be1c684..0000000000 Binary files a/docs/screenshots/integration-status-catalog.png and /dev/null differ diff --git a/docs/screenshots/integration-status-customization.png b/docs/screenshots/integration-status-customization.png deleted file mode 100644 index 3b845f95e2..0000000000 Binary files a/docs/screenshots/integration-status-customization.png and /dev/null differ diff --git a/docs/screenshots/integration-status-dark.png b/docs/screenshots/integration-status-dark.png deleted file mode 100644 index 161000b360..0000000000 Binary files a/docs/screenshots/integration-status-dark.png and /dev/null differ diff --git a/docs/screenshots/integration-status-light.png b/docs/screenshots/integration-status-light.png deleted file mode 100644 index bc3ea7006e..0000000000 Binary files a/docs/screenshots/integration-status-light.png and /dev/null differ diff --git a/package-lock.json b/package-lock.json index 0dbd0f1b9a..a5f07e597f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -33,12 +33,6 @@ ] } }, - "node_modules/7zip-bin": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/7zip-bin/-/7zip-bin-5.2.0.tgz", - "integrity": "sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==", - "license": "MIT" - }, "node_modules/@ai-sdk/provider": { "version": "3.0.8", "resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.8.tgz", @@ -212,18 +206,18 @@ } }, "node_modules/@aws-sdk/core": { - "version": "3.979.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.979.0.tgz", - "integrity": "sha512-E3eeLhIOxlIc9NPsZbtpHuk8W/gEZ3YvFauNPrrrtNtF7Pq1cwSrFwA51Z1EIoUY6VFvTyltyLRNUhaa0aSKSA==", + "version": "3.981.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/core/-/core-3.981.0.tgz", + "integrity": "sha512-Mnu7gaDrC5UCdyH8uLxLfB2eWbjE/HbjKX1U1J2VQxG3TTATUDObW2wU3I8iH3e9YH5NN2CY6w1mlAIe2XJ3jg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "^3.975.0", - "@aws-sdk/xml-builder": "^3.972.42", + "@aws-sdk/types": "^3.975.1", + "@aws-sdk/xml-builder": "^3.972.43", "@aws/lambda-invoke-store": "^0.3.0", - "@smithy/core": "^3.37.0", - "@smithy/signature-v4": "^5.7.4", - "@smithy/types": "^4.19.0", + "@smithy/core": "^3.40.0", + "@smithy/signature-v4": "^5.7.5", + "@smithy/types": "^4.20.0", "bowser": "^2.11.0", "tslib": "^2.6.2" }, @@ -232,16 +226,16 @@ } }, "node_modules/@aws-sdk/credential-provider-cognito-identity": { - "version": "3.972.78", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.972.78.tgz", - "integrity": "sha512-oFab6FAl8EHhMkUR4VOOgVMYCSq0QSLTY3UpYXXAyoIYMinm0vYqTtfDWQuvWN2VjohTppeDPht1L7sCr7MnFg==", + "version": "3.972.83", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-cognito-identity/-/credential-provider-cognito-identity-3.972.83.tgz", + "integrity": "sha512-yaHdWS2q6N2eKG9yNftDB/W7uG0OqfViXBihZwb5XPyVIMXYffpEgWp/4haIURrMSCYkLfmfMrHZhFSoPKgmQA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/nested-clients": "^3.997.53", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -249,16 +243,16 @@ } }, "node_modules/@aws-sdk/credential-provider-env": { - "version": "3.972.79", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.79.tgz", - "integrity": "sha512-fhfGcGiY70EcH9H8N/K+K2NMW3wF2J/7slHYJo0u1mF7XBpU7dlaJ8xmc0jBYUzJLRbKz4+BtVwwqrH7eZNTNw==", + "version": "3.972.84", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-env/-/credential-provider-env-3.972.84.tgz", + "integrity": "sha512-akZJetiMVeLRHsKzYh3LamDCo74ZUCeo0XoyRKMEMZT5qP7ReM6LhpioBCyuqKP5Vav5gEOeCmaQV0VVQr1Meg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -266,18 +260,18 @@ } }, "node_modules/@aws-sdk/credential-provider-http": { - "version": "3.972.81", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.81.tgz", - "integrity": "sha512-bp2TG0g2seN4LMEOjIVxkDpb/ls4GsDiguteIFxxQUxFBoyhf0pmfGbZCddHORrg58K72c+7CMlaDEw921c/3Q==", + "version": "3.972.86", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-http/-/credential-provider-http-3.972.86.tgz", + "integrity": "sha512-U4mHaDRPWAn63yhl7FXIzbppNmW1F+4dSLeuiUpej2v3Xb6rGwvayEJ8SdlrdMV+/mZtd+GStTEP2HqurEzXtw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/fetch-http-handler": "^5.8.0", - "@smithy/node-http-handler": "^4.13.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/fetch-http-handler": "^5.8.1", + "@smithy/node-http-handler": "^4.14.2", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -285,24 +279,24 @@ } }, "node_modules/@aws-sdk/credential-provider-ini": { - "version": "3.973.24", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.24.tgz", - "integrity": "sha512-ULdPVLKR46qGsVCmbilDWWcry5qAR8nYm7RZewaNtCvVLPSIyb9zSWabTA9M07s10ZpEPUl67rcORyXE50Obog==", + "version": "3.973.30", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-ini/-/credential-provider-ini-3.973.30.tgz", + "integrity": "sha512-r6r6499GWoGN943NA5YEhBEQ6TEOGTf7tTOBhHd/zw0UbNvSzd1/zPCNcDkPmRarA+e24X7KgxutqxjoWcskBg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/credential-provider-env": "^3.972.79", - "@aws-sdk/credential-provider-http": "^3.972.81", - "@aws-sdk/credential-provider-login": "^3.972.86", - "@aws-sdk/credential-provider-process": "^3.972.79", - "@aws-sdk/credential-provider-sso": "^3.973.23", - "@aws-sdk/credential-provider-web-identity": "^3.972.85", - "@aws-sdk/nested-clients": "^3.997.53", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/credential-provider-env": "^3.972.84", + "@aws-sdk/credential-provider-http": "^3.972.86", + "@aws-sdk/credential-provider-login": "^3.972.92", + "@aws-sdk/credential-provider-process": "^3.972.84", + "@aws-sdk/credential-provider-sso": "^3.973.28", + "@aws-sdk/credential-provider-web-identity": "^3.972.90", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", - "@smithy/types": "^4.19.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -310,17 +304,17 @@ } }, "node_modules/@aws-sdk/credential-provider-login": { - "version": "3.972.86", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.86.tgz", - "integrity": "sha512-e6cD5PUesauIYxV4IaOLNfEh0FnhUeIxnY4AZzmEH9PsPGpScROmrdzA0MaaCxiDVzGPtxcJW7Ku7vKU+w2p9Q==", + "version": "3.972.92", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-login/-/credential-provider-login-3.972.92.tgz", + "integrity": "sha512-96bcp9Pe/Xd60OEwncZ+kAQTQSu+fJnpUGz1qE6ghF5jnETmrk8XMU86mIP3lolvnCgR61XbZ+Ht6hdBjiQOmQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/nested-clients": "^3.997.53", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -328,22 +322,22 @@ } }, "node_modules/@aws-sdk/credential-provider-node": { - "version": "3.972.91", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.91.tgz", - "integrity": "sha512-0j1oy7cFwsMaIpueqFGeQG0VpulcF61ucKKqZUha9rZXvRK91chmAxFfov6Q155TerBGgt1dvy9n9Y3O4HD/UQ==", + "version": "3.972.97", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-node/-/credential-provider-node-3.972.97.tgz", + "integrity": "sha512-E4a0IXXJVsIdo/K9roX4JAEfI0JJr7KTPymkbKgETRDqEcLygE4ZlLTe24+7Qkh8Dl5YpnPd+Tt0DOPJDFXIwA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/credential-provider-env": "^3.972.79", - "@aws-sdk/credential-provider-http": "^3.972.81", - "@aws-sdk/credential-provider-ini": "^3.973.24", - "@aws-sdk/credential-provider-process": "^3.972.79", - "@aws-sdk/credential-provider-sso": "^3.973.23", - "@aws-sdk/credential-provider-web-identity": "^3.972.85", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", + "@aws-sdk/credential-provider-env": "^3.972.84", + "@aws-sdk/credential-provider-http": "^3.972.86", + "@aws-sdk/credential-provider-ini": "^3.973.30", + "@aws-sdk/credential-provider-process": "^3.972.84", + "@aws-sdk/credential-provider-sso": "^3.973.28", + "@aws-sdk/credential-provider-web-identity": "^3.972.90", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", "@smithy/credential-provider-imds": "^4.5.2", - "@smithy/types": "^4.19.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -351,16 +345,16 @@ } }, "node_modules/@aws-sdk/credential-provider-process": { - "version": "3.972.79", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.79.tgz", - "integrity": "sha512-b9QnxJiZSccqpkSNNWkHRwU0XKbybD1p+j02m/qJc4mIwLkwQpJYfA/cbjg6hgGOoD7W1/imi+obSzDk/T1oNg==", + "version": "3.972.84", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-process/-/credential-provider-process-3.972.84.tgz", + "integrity": "sha512-199C6OpNejd0nq9GFAkEFIKids1FL0R6LJtL9c1OTiDOXki7S1OduuPxW4+hE0LwndcYJ7YHOuYTlqScfpCocA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -368,18 +362,18 @@ } }, "node_modules/@aws-sdk/credential-provider-sso": { - "version": "3.973.23", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.23.tgz", - "integrity": "sha512-KZiZ6RUQY4mahZVreo1pp5usUDOJAf613NLicgC0MQWA0rfdkRDaeT2K0WClYEHjMy9BKvXRxc087Kr1QjV9MA==", + "version": "3.973.28", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-sso/-/credential-provider-sso-3.973.28.tgz", + "integrity": "sha512-bGg7wH8wVDJQIcJggO9lg1ZYbG7l+PbLwHuM3Bi/e1TlCZhU712JS1W3tdRpyptdJD1UGyhBNGO/YrhrQCHKbg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/nested-clients": "^3.997.53", - "@aws-sdk/token-providers": "3.1160.0", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/token-providers": "3.1166.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -387,17 +381,17 @@ } }, "node_modules/@aws-sdk/credential-provider-web-identity": { - "version": "3.972.85", - "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.85.tgz", - "integrity": "sha512-r9bZrCczKj0V46yRpFZavTmPlqBPtziEBZnKVHcGZ5NwpUrzHwhzizc7ntMfw5KPWHmL35C2tChwPH3MIy2TMQ==", + "version": "3.972.90", + "resolved": "https://registry.npmjs.org/@aws-sdk/credential-provider-web-identity/-/credential-provider-web-identity-3.972.90.tgz", + "integrity": "sha512-duLeE3xlf0viHeH+1RM4z5duR3b32BCZTWVMu+MbxFPjQBxy7hmIGEqt5hekuFPRuXoyhMovjNl+PNNsb5oiGQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/nested-clients": "^3.997.53", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -434,19 +428,19 @@ } }, "node_modules/@aws-sdk/nested-clients": { - "version": "3.997.53", - "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.997.53.tgz", - "integrity": "sha512-JRcs7wwU/cMw62hbLUxlh/wyrHaL/4KOnJs/Hny0ZIo4GY8biBMEfLJrYDEBMF8wDIewtDZsBWT9Rna4uaRemw==", + "version": "3.998.3", + "resolved": "https://registry.npmjs.org/@aws-sdk/nested-clients/-/nested-clients-3.998.3.tgz", + "integrity": "sha512-acHTTzMB13CU6dU4sxABYExMI3PQM2zStWH2MiUwJp/7QKTrLg2f7mbzSXoegW2kYOk2tdqQYagsZrWB8Xv7eA==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/signature-v4-multi-region": "^3.996.50", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/fetch-http-handler": "^5.8.0", - "@smithy/node-http-handler": "^4.13.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/signature-v4-multi-region": "^3.996.52", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/fetch-http-handler": "^5.8.1", + "@smithy/node-http-handler": "^4.14.2", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -454,15 +448,15 @@ } }, "node_modules/@aws-sdk/signature-v4-multi-region": { - "version": "3.996.50", - "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.50.tgz", - "integrity": "sha512-Ob9GCZ3YnGPws696zTYW/rLFYHa9QLh6DgTCnkHb+0jhHNBgHWM8Ui2b+yrIjkfDsRVsglyrOey6tOOG/VWxMA==", + "version": "3.996.52", + "resolved": "https://registry.npmjs.org/@aws-sdk/signature-v4-multi-region/-/signature-v4-multi-region-3.996.52.tgz", + "integrity": "sha512-6W6SjGc8OXUhMzNxU1X922ghD+PP1XvzmCk5Scui0jaYsLezycMYR1RaLp5xTIOUrhTXyb4DnAbPr3fBgmdnzg==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/types": "^3.975.0", - "@smithy/signature-v4": "^5.7.4", - "@smithy/types": "^4.19.0", + "@aws-sdk/types": "^3.975.1", + "@smithy/signature-v4": "^5.7.5", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -470,17 +464,17 @@ } }, "node_modules/@aws-sdk/token-providers": { - "version": "3.1160.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1160.0.tgz", - "integrity": "sha512-KHT4W6fRqXEDYM0lIPQD55bvZSk1xmzShUcEcw0dZYiUsgFVmilnfwY8K+tn2V/MG1Lv+SX7wkbzq/ld4XiygQ==", + "version": "3.1166.0", + "resolved": "https://registry.npmjs.org/@aws-sdk/token-providers/-/token-providers-3.1166.0.tgz", + "integrity": "sha512-ngJ8mxXqtQ9mnp7QV6TWKJCxkpjVfPWxKQSc2FYhCyCfOVFIGdFv7P+/RqVffFrJAorwBPpktnv32gNlcEgF4g==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@aws-sdk/core": "^3.979.0", - "@aws-sdk/nested-clients": "^3.997.53", - "@aws-sdk/types": "^3.975.0", - "@smithy/core": "^3.37.0", - "@smithy/types": "^4.19.0", + "@aws-sdk/core": "^3.981.0", + "@aws-sdk/nested-clients": "^3.998.3", + "@aws-sdk/types": "^3.975.1", + "@smithy/core": "^3.40.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -488,13 +482,13 @@ } }, "node_modules/@aws-sdk/types": { - "version": "3.975.0", - "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.0.tgz", - "integrity": "sha512-WQlhs6juByzWOzj5fwxOx0mPJaEqMcG/sDpl3Id61B3XhKE63xY+0QWcnG+sWR/sCfprmreyUo1lM7IKZmHMzw==", + "version": "3.975.1", + "resolved": "https://registry.npmjs.org/@aws-sdk/types/-/types-3.975.1.tgz", + "integrity": "sha512-7rGxUkCB2QPoQOeJmonmAICTN2zrH+fpmi1p4Iwu72lnxNaMhOgqcbpyddifnM1DBb19TWQ1u6z/XjkaFNEDWw==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.19.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -515,13 +509,13 @@ } }, "node_modules/@aws-sdk/xml-builder": { - "version": "3.972.42", - "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.42.tgz", - "integrity": "sha512-smX8/gNP8Kjq+CWTBMZQLQ912vOQjiWExzwzvMO+eujPB5RY8IbtF0AGdUUXHKN7KoDWK9dIcuW0WG269kiP6w==", + "version": "3.972.43", + "resolved": "https://registry.npmjs.org/@aws-sdk/xml-builder/-/xml-builder-3.972.43.tgz", + "integrity": "sha512-rG8QVx4DOrJWptsogu1Aq+CDsnPKaBrAlJpKLxrJrIDXAq1ElnW0yQjjBnlWSXll0cDakCG6UDvaqwz0A9d9Og==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.19.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -2110,13 +2104,13 @@ } }, "node_modules/@effect/opentelemetry": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@effect/opentelemetry/-/opentelemetry-4.0.6.tgz", - "integrity": "sha512-xhLR1EN4ZNaKM7Bx59SCFiRNduFzgH8LZXDrCpPN8MpQ93V0GQcFHTBah5T3EXO2v+5HTEacdTgetIA0Creqvw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@effect/opentelemetry/-/opentelemetry-4.1.0.tgz", + "integrity": "sha512-j9bNzQaoQvcnimBFMG0i3piEW20E8HjkXAQHTJN/XqG2e4uJ9zCv53/HCNzD7+ooFn5S4nwQy/BOXeNReMIe+A==", "dev": true, "license": "MIT", "engines": { - "node": ">=18.0.0" + "node": ">=22.19.0" }, "peerDependencies": { "@opentelemetry/api": ">=1.9.0 <2.0.0", @@ -2128,7 +2122,7 @@ "@opentelemetry/sdk-trace-node": ">=2.0.0 <3.0.0", "@opentelemetry/sdk-trace-web": ">=2.0.0 <3.0.0", "@opentelemetry/semantic-conventions": ">=1.33.0 <2.0.0", - "effect": "^4.0.6" + "effect": "^4.1.0" }, "peerDependenciesMeta": { "@opentelemetry/api": { @@ -2158,27 +2152,27 @@ } }, "node_modules/@effect/platform-node": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@effect/platform-node/-/platform-node-4.0.6.tgz", - "integrity": "sha512-gXvGHAy0/8PZbWvMMguloDUyeSP+rzYEo3FSEqUuGduxo9ORcGioDxPI+GOLCIFfam7VuNkmSUxBOiRMIrMrBw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@effect/platform-node/-/platform-node-4.1.0.tgz", + "integrity": "sha512-v+X7moGVF9k5oMVvz0slA+NgtEod+W+oygeI285MDJgSlUCW3JcqElj+cD3rlijFZtpKhC7RLkU1GuCxjGHTpA==", "dev": true, "license": "MIT", "dependencies": { - "@effect/platform-node-shared": "^4.0.6", + "@effect/platform-node-shared": "^4.1.0", "undici": "^8.12.2" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.19.0" }, "peerDependencies": { - "effect": "^4.0.6", + "effect": "^4.1.0", "redis": ">=5.0.0 <7.0.0" } }, "node_modules/@effect/platform-node-shared": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/@effect/platform-node-shared/-/platform-node-shared-4.0.6.tgz", - "integrity": "sha512-0PhyC4uG30xGtsajnxjkcBWfTjNRzUh4ZKl1Kvo/MNyCTb+W2O+fBzf7wCRCoqt+nLudiq4V7vX40Q8XIBuMaQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/@effect/platform-node-shared/-/platform-node-shared-4.1.0.tgz", + "integrity": "sha512-uYQfFRoxWLo8fIhiSeBcmz/R1ooOfE3HF3cWHFgxz82tZMk2Wn02BGABcdLmaAch9VpDLbtWnuhSxNyBsGMUFg==", "dev": true, "license": "MIT", "dependencies": { @@ -2186,16 +2180,16 @@ "ws": "^8.22.0" }, "engines": { - "node": ">=18.0.0" + "node": ">=22.19.0" }, "peerDependencies": { - "effect": "^4.0.6" + "effect": "^4.1.0" } }, "node_modules/@effect/platform-node/node_modules/undici": { - "version": "8.12.3", - "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.3.tgz", - "integrity": "sha512-+fdndUTwBP86cVjihTp21hZHo7d6oj1c/47XPA3lL8mM0XHs+C4EkcjmgRsFnFk2f/UONGDy9ItBItmXsLOQHw==", + "version": "8.12.4", + "resolved": "https://registry.npmjs.org/undici/-/undici-8.12.4.tgz", + "integrity": "sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==", "dev": true, "license": "MIT", "engines": { @@ -3329,15 +3323,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@fastify/static/node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/@fastify/static/node_modules/minimatch": { "version": "11.0.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.5.tgz", @@ -3363,22 +3348,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/@fastify/static/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/@floating-ui/core": { "version": "1.7.3", "resolved": "https://registry.npmjs.org/@floating-ui/core/-/core-1.7.3.tgz", @@ -4262,14 +4231,6 @@ "node": ">=10" } }, - "node_modules/@neuralnomads/codenomad": { - "resolved": "packages/server", - "link": true - }, - "node_modules/@neuralnomads/codenomad-electron-app": { - "resolved": "packages/electron-app", - "link": true - }, "node_modules/@mermaid-js/tiny": { "version": "12.3.0", "resolved": "https://registry.npmjs.org/@mermaid-js/tiny/-/tiny-12.3.0.tgz", @@ -4279,6 +4240,14 @@ "node": ">=22.12.0" } }, + "node_modules/@neuralnomads/codenomad": { + "resolved": "packages/server", + "link": true + }, + "node_modules/@neuralnomads/codenomad-electron-app": { + "resolved": "packages/electron-app", + "link": true + }, "node_modules/@noble/hashes": { "version": "2.4.0", "resolved": "https://registry.npmjs.org/@noble/hashes/-/hashes-2.4.0.tgz", @@ -4346,44 +4315,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/agent/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/http-proxy-agent": { - "version": "7.0.2", - "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", - "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.0", - "debug": "^4.3.4" - }, - "engines": { - "node": ">= 14" - } - }, - "node_modules/@npmcli/agent/node_modules/https-proxy-agent": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", - "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", - "dev": true, - "license": "MIT", - "dependencies": { - "agent-base": "^7.1.2", - "debug": "4" - }, - "engines": { - "node": ">= 14" - } - }, "node_modules/@npmcli/agent/node_modules/lru-cache": { "version": "11.5.3", "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", @@ -4453,9 +4384,9 @@ } }, "node_modules/@npmcli/arborist/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -4506,9 +4437,9 @@ } }, "node_modules/@npmcli/arborist/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -4538,26 +4469,10 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/@npmcli/config/node_modules/ci-info": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.4.0.tgz", - "integrity": "sha512-77PSwercCZU2Fc4sX94eF8k8Pxte6JAwL4/ICZLFjJLqegs7kCuAsqqj/70NQF6TvDpgFjkubQB2FW2ZZddvQg==", - "dev": true, - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/sibiraj-s" - } - ], - "license": "MIT", - "engines": { - "node": ">=8" - } - }, "node_modules/@npmcli/config/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -4581,9 +4496,9 @@ } }, "node_modules/@npmcli/fs/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -4634,9 +4549,9 @@ } }, "node_modules/@npmcli/git/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -4706,9 +4621,9 @@ } }, "node_modules/@npmcli/map-workspaces/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -4736,16 +4651,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@npmcli/map-workspaces/node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/@npmcli/map-workspaces/node_modules/minimatch": { "version": "11.0.6", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.6.tgz", @@ -4763,33 +4668,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@npmcli/map-workspaces/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/@npmcli/map-workspaces/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "dev": true - }, "node_modules/@npmcli/metavuln-calculator": { "version": "9.0.3", "resolved": "https://registry.npmjs.org/@npmcli/metavuln-calculator/-/metavuln-calculator-9.0.3.tgz", @@ -4808,9 +4686,9 @@ } }, "node_modules/@npmcli/metavuln-calculator/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -4870,9 +4748,9 @@ } }, "node_modules/@npmcli/package-json/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -4924,9 +4802,9 @@ } }, "node_modules/@npmcli/package-json/node_modules/minimatch": { - "version": "11.0.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.6.tgz", - "integrity": "sha512-6NZbDPQIRnsJFjJ9wbd5659OKaTHCqpPHdldE3WwArjxr5wLxHIwnx4eTGcPebpVBZZQbITvQQIx8K0VGXoT3Q==", + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -4940,37 +4818,10 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@npmcli/package-json/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/@npmcli/package-json/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "dev": true - }, "node_modules/@npmcli/package-json/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -5033,13 +4884,12 @@ } }, "node_modules/@npmcli/query/node_modules/postcss-selector-parser": { - "version": "7.1.7", - "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.7.tgz", - "integrity": "sha512-wWBro/7hJ40ye6TPiXkUQoXKCw23xSsjriUvqd7Uls9Sso3oLiON1flc18cCdnjgCRXw4fBVqUJJeOdDTh3P3g==", + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.2.1.tgz", + "integrity": "sha512-GwxlMgTTXwIom+ebC7an3k6RaJDwklRQQnfiXsLPGicu8FYV/k/+1/9YY2OU2+r938H2t4X0TDxoif+HP2rjzQ==", "dev": true, "license": "MIT", "dependencies": { - "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" }, "engines": { @@ -5074,32 +4924,32 @@ } }, "node_modules/@opencode/ai": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@opencode/ai/-/ai-2.2.3.tgz", - "integrity": "sha512-fUMZmeRCK/lqjKtYlWu+3JvQ46U7x3kNwgyhB1wfR0GhXRX5KeXf/vfYupjS4IkOHWay/zBTP1ZUsRDmOGmlOA==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@opencode/ai/-/ai-2.3.0.tgz", + "integrity": "sha512-CsaY18G5cXtNvOgvONaxguFeaWf+gENSYKzDnYIIREpoSLjLm9oF2v+adaE4nUozM1qIMR4+s23VOViaRypFLw==", "dev": true, "license": "MIT", "dependencies": { "@aws-sdk/credential-providers": "3.1057.0", - "@opencode/schema": "2.2.3", + "@opencode/schema": "2.3.0", "@smithy/eventstream-codec": "4.2.14", "@smithy/util-utf8": "4.2.2", "aws4fetch": "1.0.20", - "effect": "4.0.6", + "effect": "4.1.0", "google-auth-library": "10.5.0" } }, "node_modules/@opencode/client": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@opencode/client/-/client-2.2.3.tgz", - "integrity": "sha512-ph1uIGrQl1bO6jZ9RCVfa/aBsz0nCq3pnpikExQ0W8oKUwS9mH5tQfpwG0e85V6W4KPeOQCwGUWB0WTzXnYO/Q==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@opencode/client/-/client-2.3.0.tgz", + "integrity": "sha512-xu74XGiYIqLZ2FzIrtjaR5UNWWXY3fRln0WLgZoQTR/wWMgG+T9XGQQGCl8ry8jnCFsJVokiHemBqft9oMzC1A==", "license": "MIT", "dependencies": { - "@opencode/protocol": "2.2.3", - "@opencode/schema": "2.2.3" + "@opencode/protocol": "2.3.0", + "@opencode/schema": "2.3.0" }, "peerDependencies": { - "effect": "4.0.6", + "effect": "4.1.0", "solid-js": ">=1.9.0" }, "peerDependenciesMeta": { @@ -5112,24 +4962,24 @@ } }, "node_modules/@opencode/plugin": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@opencode/plugin/-/plugin-2.2.3.tgz", - "integrity": "sha512-JK8FW4VHPHkQKgKi9m7kKdx9L1CRSNYpxNR1DtXC9SAe7f8huWoXEN+LH2vv38KEanOfY5OdcUhBUHKAwidyeg==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@opencode/plugin/-/plugin-2.3.0.tgz", + "integrity": "sha512-wfBz8UKpy1jb8EAuFqvqbmVG6+6X6B5B+54UAGmofuT7vZ6F6cC3OQwlw1ObEi4NTKG66y0x6Z6zz4AG0H2N9Q==", "dev": true, "license": "MIT", "dependencies": { "@ai-sdk/provider": "3.0.8", - "@opencode/ai": "2.2.3", - "@opencode/client": "2.2.3", - "@opencode/protocol": "2.2.3", - "@opencode/schema": "2.2.3", - "@opencode/util": "2.2.3", - "effect": "4.0.6" + "@opencode/ai": "2.3.0", + "@opencode/client": "2.3.0", + "@opencode/protocol": "2.3.0", + "@opencode/schema": "2.3.0", + "@opencode/util": "2.3.0", + "effect": "4.1.0" }, "peerDependencies": { - "@opencode/theme": "2.2.3", - "@opentui/core": ">=0.8.0", - "@opentui/solid": ">=0.8.0", + "@opencode/theme": "2.3.0", + "@opentui/core": ">=0.8.4", + "@opentui/solid": ">=0.8.4", "electron": "*", "solid-js": ">=1.9.0", "vite": ">=6", @@ -5160,35 +5010,35 @@ } }, "node_modules/@opencode/protocol": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@opencode/protocol/-/protocol-2.2.3.tgz", - "integrity": "sha512-4SBCchbfwMb2AK27vH+Qlwrnnbzw4tMT7LsFJRNwO/H7LPKbsMJJsAlRYjcyxQYEPDNYVXyFCF1rCkrA3OeCJg==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@opencode/protocol/-/protocol-2.3.0.tgz", + "integrity": "sha512-V37zTGXVa1j9aXUvUY01YN1EtfMMSWoT5pSCc6M0UsGdTUZX6QL/vMgGVGzPvbt7+Z8Vo40/0DFRPyqT4sdvnw==", "license": "MIT", "dependencies": { - "@opencode/schema": "2.2.3", - "effect": "4.0.6" + "@opencode/schema": "2.3.0", + "effect": "4.1.0" } }, "node_modules/@opencode/schema": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@opencode/schema/-/schema-2.2.3.tgz", - "integrity": "sha512-5Lm6Aw6E3nHigLJcSOteontUKv/9fzjfEXaBvaIHAageNvq0hYBgWSBv0ZikaAj1pJr5e1y9TSW6cbWqQcjMjg==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@opencode/schema/-/schema-2.3.0.tgz", + "integrity": "sha512-9CPS4+BXWUs3ELIWo68AA2q4XEPMkRYwpGYdqd/wNz3jRTOB8swef+2/z+igkCel+UtlX+dAlGTmSnid/JcoKw==", "license": "MIT", "dependencies": { "@standard-schema/spec": "1.1.0", - "effect": "4.0.6" + "effect": "4.1.0" } }, "node_modules/@opencode/util": { - "version": "2.2.3", - "resolved": "https://registry.npmjs.org/@opencode/util/-/util-2.2.3.tgz", - "integrity": "sha512-Xp9hb909LaYJ667Yzg5LkCBrj9h44umOiH9WF7Mj4ZZlOKQDr5H3a3LEw0r7a8ED8yfnXMrN8xFMeL6EojBmGQ==", + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/@opencode/util/-/util-2.3.0.tgz", + "integrity": "sha512-0OIjkq9EQ/p50Wft57yr2NIyuzz1zqaBydwu/5rzEy1+Bu5hJkr5oUqAvt1ye6zZdBW3K8kiFGXFQsChX4cNPg==", "dev": true, "license": "MIT", "dependencies": { - "@effect/opentelemetry": "4.0.6", - "@effect/platform-node": "4.0.6", - "@effect/platform-node-shared": "4.0.6", + "@effect/opentelemetry": "4.1.0", + "@effect/platform-node": "4.1.0", + "@effect/platform-node-shared": "4.1.0", "@npmcli/arborist": "9.4.0", "@npmcli/config": "10.8.1", "@opentelemetry/api": "1.9.0", @@ -5201,7 +5051,7 @@ "@opentelemetry/sdk-trace-base": "2.8.0", "@opentelemetry/sdk-trace-node": "2.8.0", "cross-spawn": "7.0.6", - "effect": "4.0.6", + "effect": "4.1.0", "glob": "13.0.5", "mime-types": "3.0.2", "minimatch": "10.2.5", @@ -5221,9 +5071,9 @@ } }, "node_modules/@opencode/util/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -5251,16 +5101,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@opencode/util/node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/@opencode/util/node_modules/mime-db": { "version": "1.54.0", "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.54.0.tgz", @@ -5305,33 +5145,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/@opencode/util/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/@opencode/util/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "dev": true - }, "node_modules/@opentelemetry/api": { "version": "1.9.0", "resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz", @@ -5534,9 +5347,9 @@ } }, "node_modules/@opentelemetry/semantic-conventions": { - "version": "1.44.0", - "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.44.0.tgz", - "integrity": "sha512-E3JkOlMBi3N8OGGkbl7tFyqk2MAS6/lySRZBK3Mu7AzjF1fT8oIChH9ChE48SUWzDn9Kdwta+G/p5LJ4xW4CLQ==", + "version": "1.45.0", + "resolved": "https://registry.npmjs.org/@opentelemetry/semantic-conventions/-/semantic-conventions-1.45.0.tgz", + "integrity": "sha512-aOP45mbcOKbQVvFWfQmgoOPT8R2iwbbbgl83k4CujGV9BrJhFr3qG55MFpwFs4YLabpuW3HhzUY9eQxPlDqaZw==", "dev": true, "license": "Apache-2.0", "engines": { @@ -5641,16 +5454,6 @@ "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", "license": "MIT" }, - "node_modules/@pkgjs/parseargs": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@pkgjs/parseargs/-/parseargs-0.11.0.tgz", - "integrity": "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=14" - } - }, "node_modules/@popperjs/core": { "version": "2.11.8", "resolved": "https://registry.npmjs.org/@popperjs/core/-/core-2.11.8.tgz", @@ -5674,6 +5477,85 @@ "url": "https://github.com/sponsors/sxzz" } }, + "node_modules/@redis/bloom": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-6.3.1.tgz", + "integrity": "sha512-dpF9j2yJDoPzSCaZn0MSB3xzmnXQVJeTSAWJcQVcgbmluwhpFeemmII0cF1t+WYfoVS+shEFq79+MmUItgzJLg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.1" + } + }, + "node_modules/@redis/client": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-6.3.1.tgz", + "integrity": "sha512-masbfVKULdoAofwddepZxRhWa4w6zvBHn6TRn90TRPrRkVIlGCur3pFqwWaCbMxtYI9twepkz63e/T/tEH8GjA==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@node-rs/xxhash": "^1.1.0", + "@opentelemetry/api": ">=1 <2" + }, + "peerDependenciesMeta": { + "@node-rs/xxhash": { + "optional": true + }, + "@opentelemetry/api": { + "optional": true + } + } + }, + "node_modules/@redis/json": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-6.3.1.tgz", + "integrity": "sha512-fMz4kUwJzEftcU9EMaqsjZcUwzpTQLOYRqhQsAD6uKvZWeamblK13ZhgO5SzVSZVk31jmwLeTRpU5GAl5egfUw==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.1" + } + }, + "node_modules/@redis/search": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-6.3.1.tgz", + "integrity": "sha512-T67pvPUpW82VrZLvihO8O2DFMC7eY2oMAzMzapCbiPZn7mdWqHMEIlohYim12gIawT5kn6qT/Cvmm4WulKB+kQ==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.1" + } + }, + "node_modules/@redis/time-series": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-6.3.1.tgz", + "integrity": "sha512-MNDgrm+i63M/1a+XA+HcDsScwt4uBh/fGGJ84swTQZTFK5K5wMmxdlTRa4ZgmNJzjxMaszW/ipPScMUGV3aAMg==", + "dev": true, + "license": "MIT", + "peer": true, + "engines": { + "node": ">= 20.0.0" + }, + "peerDependencies": { + "@redis/client": "^6.3.1" + } + }, "node_modules/@rolldown/binding-android-arm-eabi": { "version": "1.2.16", "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm-eabi/-/binding-android-arm-eabi-1.2.16.tgz", @@ -6645,13 +6527,13 @@ } }, "node_modules/@smithy/core": { - "version": "3.38.0", - "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.38.0.tgz", - "integrity": "sha512-aLyyCnK2p4yvNA2TaM+5owXqb+rZGSiUKEsNP329AzeYnERtAz7NrlTbRsaxqmZ0ooxwoID8LMm959UGQQDIsg==", + "version": "3.40.0", + "resolved": "https://registry.npmjs.org/@smithy/core/-/core-3.40.0.tgz", + "integrity": "sha512-DssGno52pzZ5m6RlDtyKuBIpZNPg9pqgs0CnNDKz9IatxCsmvNmJNn5Zn6rf77MthZo9wf89OvZFhTY/RwxhxQ==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@smithy/types": "^4.19.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -6690,14 +6572,14 @@ } }, "node_modules/@smithy/fetch-http-handler": { - "version": "5.8.0", - "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.0.tgz", - "integrity": "sha512-ycSJu3tFAQ4v04CBB0agqFMVsSQ1iG3yw+SpgxRqKfaURpQD4CZ8Wn0zPMmSnOuTpTh65Vz+EA0rMrw089wvkA==", + "version": "5.8.1", + "resolved": "https://registry.npmjs.org/@smithy/fetch-http-handler/-/fetch-http-handler-5.8.1.tgz", + "integrity": "sha512-h8BdMUrUBhMhMaeK7QqAdINRZezCGuYOCpcOZZ1ewxbHST9rdTd09xwNpvLTYfzDRehxQiReK4SKbdYZxBA+ew==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.33.3", - "@smithy/types": "^4.18.0", + "@smithy/core": "^3.39.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -6718,14 +6600,14 @@ } }, "node_modules/@smithy/node-http-handler": { - "version": "4.14.0", - "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.0.tgz", - "integrity": "sha512-j24RS5V9J52u0z81RpgF7H55p4bS6UCEIxF4ZYzTYh6M9hzXvjAIAYwgLobqf7vJq3xib5VXc7nX3YesV8Rx4A==", + "version": "4.14.2", + "resolved": "https://registry.npmjs.org/@smithy/node-http-handler/-/node-http-handler-4.14.2.tgz", + "integrity": "sha512-i1uORV1v3qBqP43ayRKzIdm1q5x14tf8N4Dd06/QUX1Szm6VxHMrTsu20X5E63UFsaNZCRjI4SXG0jDmqYa+3w==", "dev": true, "license": "Apache-2.0", "dependencies": { - "@smithy/core": "^3.38.0", - "@smithy/types": "^4.19.0", + "@smithy/core": "^3.39.0", + "@smithy/types": "^4.20.0", "tslib": "^2.6.2" }, "engines": { @@ -6748,9 +6630,9 @@ } }, "node_modules/@smithy/types": { - "version": "4.19.0", - "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.19.0.tgz", - "integrity": "sha512-r7jh49VJxGerfAcTQA6gXcKc+98zOp/tqRwzYjgOE+iSQsP6cEU1hq2QzbuipmP68QtYdY9wKEhiCQZIzHgZ4Q==", + "version": "4.20.0", + "resolved": "https://registry.npmjs.org/@smithy/types/-/types-4.20.0.tgz", + "integrity": "sha512-lCA6QG22dPk9ecHbv91jDQZsmtPUjdS1aE2Il6NNPqe7DrYc0dZQi6DhcESk2KYXH2sp5xbAcGdYMZDFnuzA2A==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -7371,9 +7253,9 @@ } }, "node_modules/@tufjs/models/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -7659,6 +7541,12 @@ "node": ">=10.0.0" } }, + "node_modules/7zip-bin": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/7zip-bin/-/7zip-bin-5.2.0.tgz", + "integrity": "sha512-ukTPVhqG4jNzMro2qA9HSCSSVJN3aN7tlb+hfqYCt3ER0yWroeA2VR38MNrOHLQ/cVj+DaIMad0kFCtWWowh/A==", + "license": "MIT" + }, "node_modules/abbrev": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-4.0.0.tgz", @@ -7692,6 +7580,7 @@ "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "dev": true, "license": "MIT", "engines": { "node": ">= 14" @@ -7701,6 +7590,7 @@ "version": "8.20.0", "resolved": "https://registry.npmjs.org/ajv/-/ajv-8.20.0.tgz", "integrity": "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA==", + "dev": true, "license": "MIT", "dependencies": { "fast-deep-equal": "^3.1.3", @@ -7772,6 +7662,7 @@ "version": "3.1.9", "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.9.tgz", "integrity": "sha512-hS/0Wt3Ya043oKXs0sIxrMpKQITXhMLIrVAKKXi4gozGC9v7YRWVnXIZzjNPTO02M9BdxLCWqK1yRXgNziVyJQ==", + "dev": true, "funding": [ { "type": "github", @@ -8422,6 +8313,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, "license": "MIT" }, "node_modules/base64-js": { @@ -8523,6 +8415,7 @@ "version": "2.1.7", "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", + "dev": true, "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" @@ -8706,9 +8599,9 @@ } }, "node_modules/cacache/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -8718,19 +8611,6 @@ "node": "20 || >=22" } }, - "node_modules/cacache/node_modules/fs-minipass": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", - "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, "node_modules/cacache/node_modules/glob": { "version": "14.0.4", "resolved": "https://registry.npmjs.org/glob/-/glob-14.0.4.tgz", @@ -8760,9 +8640,9 @@ } }, "node_modules/cacache/node_modules/minimatch": { - "version": "11.0.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.6.tgz", - "integrity": "sha512-6NZbDPQIRnsJFjJ9wbd5659OKaTHCqpPHdldE3WwArjxr5wLxHIwnx4eTGcPebpVBZZQbITvQQIx8K0VGXoT3Q==", + "version": "11.0.8", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.8.tgz", + "integrity": "sha512-nFQuYSTVrGvysVBps5Ih+0BdnYFN/Cj3C816r6+p7yK+FHrVLGE4O4N9AFwykrlNlvM2HYt+Rad1Uiro6h88Ig==", "dev": true, "license": "BlueOak-1.0.0", "dependencies": { @@ -8776,33 +8656,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/cacache/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/cacache/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "dev": true - }, "node_modules/cacheable-lookup": { "version": "5.0.4", "resolved": "https://registry.npmjs.org/cacheable-lookup/-/cacheable-lookup-5.0.4.tgz", @@ -9285,6 +9138,7 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, "license": "MIT", "dependencies": { "path-key": "^3.1.0", @@ -9305,19 +9159,6 @@ "node": ">=8" } }, - "node_modules/cssesc": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/cssesc/-/cssesc-3.0.0.tgz", - "integrity": "sha512-/Tb/JcjK111nNScGob5MNtsntNM1aCNUDipB/TkwZFhyDrrE47SOx/18wF2bbjgc3ZzCSKW1T5nt5EbFoAz/Vg==", - "dev": true, - "license": "MIT", - "bin": { - "cssesc": "bin/cssesc" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/csstype": { "version": "3.1.3", "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.1.3.tgz", @@ -9790,9 +9631,9 @@ } }, "node_modules/effect": { - "version": "4.0.6", - "resolved": "https://registry.npmjs.org/effect/-/effect-4.0.6.tgz", - "integrity": "sha512-Tc3mkzuLR6t6P9dhLt0D2GrxYtmU5td4XEJEiXCmILz53IRIfJyHsKZWjTA3xEjiwpNTtXBgI4iqYPxMztBDrw==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/effect/-/effect-4.1.0.tgz", + "integrity": "sha512-lGx2MJJyrXA8RZb2UpQ/0Nkb5Utaimby7oD92+18noBxLPE85IFOvptdzau8dvcxAOwfwHo9iqapbKeFzqQM/Q==", "license": "MIT" }, "node_modules/ejs": { @@ -10642,6 +10483,19 @@ "node": ">=12" } }, + "node_modules/fs-minipass": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", + "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", + "dev": true, + "license": "ISC", + "dependencies": { + "minipass": "^7.0.3" + }, + "engines": { + "node": "^14.17.0 || ^16.13.0 || >=18.0.0" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", @@ -11319,6 +11173,7 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dev": true, "license": "MIT", "dependencies": { "agent-base": "^7.1.2", @@ -11335,6 +11190,24 @@ "dev": true, "license": "MPL-2.0" }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, "node_modules/idb": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/idb/-/idb-7.1.1.tgz", @@ -11366,9 +11239,9 @@ } }, "node_modules/ignore-walk/node_modules/brace-expansion": { - "version": "5.0.12", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.12.tgz", - "integrity": "sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ==", + "version": "5.0.13", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.13.tgz", + "integrity": "sha512-Vh3dmFbc4wZeox7M9I/0L9GfFd83Su4+yCck/OF9Gi/P/dAHn0RT7X4K9R7gMNMhDck3DvhR6QXsnQdjjgwNvQ==", "dev": true, "license": "MIT", "dependencies": { @@ -11439,9 +11312,9 @@ } }, "node_modules/ip-address": { - "version": "10.7.5", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.5.tgz", - "integrity": "sha512-t2v0rkILYv9WXmSL7TpAaU3HXgaFYOPUcH3QHgwQ++gpJuH3bqyMy4Fvt/DJCTKwzH3Cf+bAp5W/mFL39KPLzA==", + "version": "10.7.6", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.6.tgz", + "integrity": "sha512-00LYkM6byILa9eQIx6qoaXCM40xTLd56AZ4vyaPW3YTyb49VZYPo5xsiAq4tuQ54GH4R7gVdYScJ1B7B77PuTg==", "dev": true, "license": "MIT", "engines": { @@ -12012,6 +11885,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, "license": "ISC" }, "node_modules/jake": { @@ -12141,6 +12015,7 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz", "integrity": "sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==", + "dev": true, "license": "MIT" }, "node_modules/json-stringify-nice": { @@ -12453,16 +12328,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/make-fetch-happen/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, "node_modules/marked": { "version": "12.0.2", "resolved": "https://registry.npmjs.org/marked/-/marked-12.0.2.tgz", @@ -12750,16 +12615,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/minipass-collect/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, "node_modules/minipass-fetch": { "version": "5.0.2", "resolved": "https://registry.npmjs.org/minipass-fetch/-/minipass-fetch-5.0.2.tgz", @@ -12778,47 +12633,6 @@ "iconv-lite": "^0.7.2" } }, - "node_modules/minipass-fetch/node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", - "dev": true, - "license": "MIT", - "optional": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/minipass-fetch/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/minipass-fetch/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/minipass-flush": { "version": "1.0.7", "resolved": "https://registry.npmjs.org/minipass-flush/-/minipass-flush-1.0.7.tgz", @@ -12898,16 +12712,6 @@ "node": ">=8" } }, - "node_modules/minipass-sized/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, "node_modules/minizlib": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", @@ -13297,9 +13101,9 @@ } }, "node_modules/npm-install-checks/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -13398,9 +13202,9 @@ } }, "node_modules/npm-pick-manifest/node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", "dev": true, "license": "ISC", "bin": { @@ -13430,29 +13234,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/npm-registry-fetch/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/npm-registry-fetch/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, "node_modules/object-assign": { "version": "4.1.1", "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", @@ -13703,79 +13484,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/pacote/node_modules/chownr": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", - "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, - "node_modules/pacote/node_modules/fs-minipass": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-3.0.3.tgz", - "integrity": "sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw==", - "dev": true, - "license": "ISC", - "dependencies": { - "minipass": "^7.0.3" - }, - "engines": { - "node": "^14.17.0 || ^16.13.0 || >=18.0.0" - } - }, - "node_modules/pacote/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, - "node_modules/pacote/node_modules/minizlib": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", - "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", - "dev": true, - "license": "MIT", - "dependencies": { - "minipass": "^7.1.2" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/pacote/node_modules/tar": { - "version": "7.5.22", - "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz", - "integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==", - "dev": true, - "license": "BlueOak-1.0.0", - "dependencies": { - "@isaacs/fs-minipass": "^4.0.0", - "chownr": "^3.0.0", - "minipass": "^7.1.2", - "minizlib": "^3.1.0", - "yallist": "^5.0.0" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/pacote/node_modules/yallist": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", - "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=18" - } - }, "node_modules/parse-conflict-json": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/parse-conflict-json/-/parse-conflict-json-5.0.1.tgz", @@ -13827,6 +13535,7 @@ "version": "3.1.1", "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -13839,6 +13548,31 @@ "dev": true, "license": "MIT" }, + "node_modules/path-scurry": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", + "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", + "license": "BlueOak-1.0.0", + "dependencies": { + "lru-cache": "^11.0.0", + "minipass": "^7.1.2" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/path-scurry/node_modules/lru-cache": { + "version": "11.5.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", + "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", + "license": "BlueOak-1.0.0", + "engines": { + "node": "20 || >=22" + } + }, "node_modules/pe-library": { "version": "0.4.1", "resolved": "https://registry.npmjs.org/pe-library/-/pe-library-0.4.1.tgz", @@ -14649,6 +14383,24 @@ "node": ">= 12.13.0" } }, + "node_modules/redis": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/redis/-/redis-6.3.1.tgz", + "integrity": "sha512-mV96ZKxQ4CGn3SyEGaY0Lb9YA443mdVey3c+mdr0NAUaBxiOZGoYCWX8PoM55kictSOmxlJRtZJxIsmZm3jL+w==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@redis/bloom": "6.3.1", + "@redis/client": "6.3.1", + "@redis/json": "6.3.1", + "@redis/search": "6.3.1", + "@redis/time-series": "6.3.1" + }, + "engines": { + "node": ">= 20.0.0" + } + }, "node_modules/reflect.getprototypeof": { "version": "1.0.10", "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", @@ -14946,15 +14698,6 @@ "url": "https://github.com/sponsors/isaacs" } }, - "node_modules/rimraf/node_modules/lru-cache": { - "version": "11.5.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.5.3.tgz", - "integrity": "sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==", - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/rimraf/node_modules/minimatch": { "version": "11.0.6", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.6.tgz", @@ -14980,22 +14723,6 @@ "node": ">=16 || 14 >=14.17" } }, - "node_modules/rimraf/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, "node_modules/roarr": { "version": "2.15.4", "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", @@ -15508,6 +15235,7 @@ "version": "2.0.0", "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, "license": "MIT", "dependencies": { "shebang-regex": "^3.0.0" @@ -15520,6 +15248,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, "license": "MIT", "engines": { "node": ">=8" @@ -15621,6 +15350,7 @@ "version": "4.1.0", "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "dev": true, "license": "ISC", "engines": { "node": ">=14" @@ -15721,16 +15451,6 @@ "node": ">= 14" } }, - "node_modules/socks-proxy-agent/node_modules/agent-base": { - "version": "7.1.4", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", - "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">= 14" - } - }, "node_modules/solid-js": { "version": "1.9.18", "resolved": "https://registry.npmjs.org/solid-js/-/solid-js-1.9.18.tgz", @@ -15895,16 +15615,6 @@ "node": "^20.17.0 || >=22.9.0" } }, - "node_modules/ssri/node_modules/minipass": { - "version": "7.1.3", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", - "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": ">=16 || 14 >=14.17" - } - }, "node_modules/stat-mode": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/stat-mode/-/stat-mode-1.0.0.tgz", @@ -15938,6 +15648,23 @@ "node": ">= 0.4" } }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dev": true, + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/string_decoder/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "dev": true, + "license": "MIT" + }, "node_modules/string-width": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", @@ -16039,23 +15766,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/string_decoder": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", - "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", - "dev": true, - "license": "MIT", - "dependencies": { - "safe-buffer": "~5.1.0" - } - }, - "node_modules/string_decoder/node_modules/safe-buffer": { - "version": "5.1.2", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", - "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", - "dev": true, - "license": "MIT" - }, "node_modules/stringify-entities": { "version": "4.0.4", "resolved": "https://registry.npmjs.org/stringify-entities/-/stringify-entities-4.0.4.tgz", @@ -17332,6 +17042,7 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, "license": "ISC", "dependencies": { "isexe": "^2.0.0" @@ -17644,16 +17355,6 @@ "graceful-fs": "^4.1.6" } }, - "node_modules/workbox-build/node_modules/lru-cache": { - "version": "11.2.5", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-11.2.5.tgz", - "integrity": "sha512-vFrFJkWtJvJnD5hg+hJvVE8Lh/TcMzKnTgCWmtBipwI5yLX/iX+5UB2tfuyODF5E7k9xEzMdYgGqaSb1c0c5Yw==", - "dev": true, - "license": "BlueOak-1.0.0", - "engines": { - "node": "20 || >=22" - } - }, "node_modules/workbox-build/node_modules/minimatch": { "version": "11.0.6", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-11.0.6.tgz", @@ -17675,28 +17376,11 @@ "version": "7.1.3", "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.3.tgz", "integrity": "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A==", + "dev": true, "license": "BlueOak-1.0.0", "engines": { "node": ">=16 || 14 >=14.17" - }, - "dev": true - }, - "node_modules/workbox-build/node_modules/path-scurry": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/path-scurry/-/path-scurry-3.0.0.tgz", - "integrity": "sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==", - "license": "BlueOak-1.0.0", - "dependencies": { - "lru-cache": "^11.0.0", - "minipass": "^7.1.2" - }, - "engines": { - "node": "18 || 20 || >=22" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - }, - "dev": true + } }, "node_modules/workbox-build/node_modules/pretty-bytes": { "version": "5.6.0", @@ -18188,11 +17872,11 @@ "@fastify/cors": "^11.4.1", "@fastify/reply-from": "^12.8.1", "@fastify/static": "^10.1.10", - "@opencode/client": "2.2.3", - "@opencode/schema": "2.2.3", + "@opencode/client": "2.3.0", + "@opencode/schema": "2.3.0", "commander": "^12.1.0", "dom-accessibility-api": "0.7.1", - "effect": "4.0.6", + "effect": "4.1.0", "fastify": "^5.12.8", "fuzzysort": "^2.0.4", "jsonc-parser": "^3.3.1", @@ -18210,7 +17894,7 @@ }, "devDependencies": { "@codenomad/remote-tunnel": "file:../remote-tunnel", - "@opencode/plugin": "2.2.3", + "@opencode/plugin": "2.3.0", "@types/node-forge": "^1.3.14", "@types/npm-package-arg": "^6.1.4", "@types/yauzl": "^2.10.0", @@ -18278,7 +17962,7 @@ "@kobalte/core": "0.13.11", "@mermaid-js/tiny": "12.3.0", "@noble/hashes": "2.4.0", - "@opencode/client": "2.2.3", + "@opencode/client": "2.3.0", "@solidjs/router": "^0.13.0", "@suid/material": "^0.19.0", "@suid/system": "^0.14.0", diff --git a/packages/server/package.json b/packages/server/package.json index 6de44c1ce3..27d47656c9 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -34,11 +34,11 @@ "@fastify/cors": "^11.4.1", "@fastify/reply-from": "^12.8.1", "@fastify/static": "^10.1.10", - "@opencode/client": "2.2.3", - "@opencode/schema": "2.2.3", + "@opencode/client": "2.3.0", + "@opencode/schema": "2.3.0", "commander": "^12.1.0", "dom-accessibility-api": "0.7.1", - "effect": "4.0.6", + "effect": "4.1.0", "fastify": "^5.12.8", "fuzzysort": "^2.0.4", "jsonc-parser": "^3.3.1", @@ -53,7 +53,7 @@ }, "devDependencies": { "@codenomad/remote-tunnel": "file:../remote-tunnel", - "@opencode/plugin": "2.2.3", + "@opencode/plugin": "2.3.0", "@types/node-forge": "^1.3.14", "@types/npm-package-arg": "^6.1.4", "@types/yauzl": "^2.10.0", diff --git a/packages/server/src/api-types-provider-usage.ts b/packages/server/src/api-types-provider-usage.ts index bb2828a2bb..753facdcbb 100644 --- a/packages/server/src/api-types-provider-usage.ts +++ b/packages/server/src/api-types-provider-usage.ts @@ -17,5 +17,4 @@ export interface OpenCodeConsoleUsage { export interface OpenCodeFreeEstimate { requests: number | null reference: number - exhausted: boolean } diff --git a/packages/server/src/api-types.ts b/packages/server/src/api-types.ts index 5a4d40f5ff..b23a8fbeff 100644 --- a/packages/server/src/api-types.ts +++ b/packages/server/src/api-types.ts @@ -21,8 +21,11 @@ export interface MissionScheduleCapability { api: { available: true } | { available: false; reason: "missing-api" | "incompatible-contract" } enabled: boolean origin: string | null + provenance?: "environment" | "experimental-block" | "all-flags" | "channel-default" activation: { available: true; targets: Array<{ path: string; scope: "global" | "project" }> } - | { available: false; reason: string; targets: [] } + | { available: false; reason: string; targets: []; code?: "schedule-activation-refused"; + refusal?: { reason: "explicit-off" | "masked"; provenance: "environment" | "experimental-block" | "all-flags" | "channel-default"; + layer: "environment" | "global" | "project" | "inherited" | "imposed"; path?: string; openable: boolean; configFileID?: string } } } export type { @@ -238,8 +241,6 @@ export interface ProviderUsageResponse { unavailableAction?: ProviderUsageUnavailableAction console?: import("./api-types-provider-usage").OpenCodeConsoleUsage freeEstimate?: import("./api-types-provider-usage").OpenCodeFreeEstimate - /** The allowance or reset is a local reference; request counts can come from Console. */ - estimated?: true } export type WorktreeKind = "root" | "worktree" @@ -829,6 +830,8 @@ export interface RemoteProxySessionCreateResponse { export interface RemoteControlStatus { /** False for requests arriving through Remote Control: only the host manages it. */ manageable: boolean + /** The administrator disabled Remote Control (CODENOMAD_REMOTE_CONTROL=disabled): it never starts. */ + disabledByAdministrator?: boolean enabled: boolean /** The user started Remote Control and has not stopped it: it reconnects at launch. */ startsOnLaunch: boolean @@ -964,6 +967,8 @@ export interface SupportMeta { export interface ServerMeta extends Partial { /** Whether this request has host-local privileges (loopback, outside Remote Control). */ localRequest?: boolean + /** Whether this request may open SideCars: local, or a verified direct HTTPS origin the host opted in. */ + sidecarsAllowed?: boolean /** URL desktop apps should use to connect (prefers loopback HTTP when enabled). */ localUrl: string /** URL direct remote clients should use (prefers HTTPS when enabled). */ @@ -974,6 +979,8 @@ export interface ServerMeta extends Partial { host: string /** Listening mode derived from host binding. */ listeningMode: "local" | "all" + /** The administrator fixed the listening address (CODENOMAD_LOCKED_HOST); the UI cannot change it. */ + listeningLocked?: boolean /** Actual local port in use after binding. */ localPort: number /** Actual direct remote port in use after binding (when remoteUrl is set). */ diff --git a/packages/server/src/cli-options.test.ts b/packages/server/src/cli-options.test.ts index 760fc11273..2a64b92579 100644 --- a/packages/server/src/cli-options.test.ts +++ b/packages/server/src/cli-options.test.ts @@ -19,6 +19,43 @@ beforeEach(() => { originalEnv = process.env process.env = { ...originalEnv } for (const [name] of switches) delete process.env[name] + for (const name of ["CODENOMAD_REMOTE_CONTROL", "CODENOMAD_LOCKED_HOST", "CLI_HOST"]) delete process.env[name] +}) + +it("an administrator-locked host wins over --host and CLI_HOST and is validated like --host", () => { + assert.deepEqual([parseCliOptions(["--https", "true", "--host", "0.0.0.0"])].map(({ host, hostLocked }) => ({ host, hostLocked })), + [{ host: "0.0.0.0", hostLocked: false }]) + process.env.CODENOMAD_LOCKED_HOST = " LOCALHOST " + process.env.CLI_HOST = "0.0.0.0" + for (const args of [[], ["--host", "0.0.0.0"], ["--host", "10.0.0.5"]]) { + const options = parseCliOptions(["--https", "true", ...args]) + assert.deepEqual({ host: options.host, hostLocked: options.hostLocked }, { host: "127.0.0.1", hostLocked: true }, args.join(" ")) + } + process.env.CODENOMAD_LOCKED_HOST = "10.20.0.7" + assert.equal(parseCliOptions(["--https", "true", "--host", "127.0.0.1"]).host, "10.20.0.7") + process.env.CODENOMAD_LOCKED_HOST = "fe80::1%eth0" + assert.throws(() => parseCliOptions(["--https", "true"]), /CODENOMAD_LOCKED_HOST/) + // A whitespace-only address never falls back to --host. + process.env.CODENOMAD_LOCKED_HOST = " \t " + assert.throws(() => parseCliOptions(["--https", "true", "--host", "0.0.0.0"]), /CODENOMAD_LOCKED_HOST must be an address/) + process.env.CODENOMAD_LOCKED_HOST = "" + assert.deepEqual([parseCliOptions(["--https", "true", "--host", "0.0.0.0"])].map(({ host, hostLocked }) => ({ host, hostLocked })), + [{ host: "0.0.0.0", hostLocked: false }], "exactly empty means no policy") +}) + +it("CODENOMAD_REMOTE_CONTROL accepts only disabled, and any other value refuses startup", () => { + assert.equal(parseCliOptions(["--https", "true"]).remoteControlDisabled, false) + for (const value of ["disabled", " DISABLED "]) { + process.env.CODENOMAD_REMOTE_CONTROL = value + assert.equal(parseCliOptions(["--https", "true"]).remoteControlDisabled, true) + } + process.env.CODENOMAD_REMOTE_CONTROL = "" + assert.equal(parseCliOptions(["--https", "true"]).remoteControlDisabled, false, "exactly empty means no policy") + for (const value of ["off", "false", "disable", "enabled", " ", " \t "]) { + process.env.CODENOMAD_REMOTE_CONTROL = value + assert.throws(() => parseCliOptions(["--https", "true"]), (error: unknown) => + error instanceof InvalidArgumentError && /CODENOMAD_REMOTE_CONTROL accepts only "disabled"/.test(error.message)) + } }) afterEach(() => { process.env = originalEnv }) diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts index 37bea7cb32..527ae0fe58 100644 --- a/packages/server/src/index.ts +++ b/packages/server/src/index.ts @@ -57,6 +57,7 @@ import { provisionDesktopPlugins } from "./opencode/desktop-plugin-provisioning" import { AUTOMATION_BRIDGE_PATH, createAutomationBridgeRegistration, publishAutomationBridge } from "./opencode/automation-plugin" import { RemoteDeviceRegistry } from "./remote-control/devices" import { RemoteControlManager } from "./remote-control/manager" +import { readNetworkPolicy, type NetworkPolicy } from "./server/network-policy" import { RemoteControlOwnerLease } from "./remote-control/owner-lease" import { WorktreeDeletionFence } from "./workspaces/worktree-session-evacuation" import { IntegrationCatalogSource } from "./opencode/integrations/catalog" @@ -96,6 +97,9 @@ interface CliOptions { generateToken: boolean dangerouslySkipAuth: boolean upgrade?: string | boolean + /** Administrator policy (`network-policy.ts`): the host comes from CODENOMAD_LOCKED_HOST. */ + hostLocked: boolean + remoteControlDisabled: boolean } const DEFAULT_HOST = "127.0.0.1" @@ -203,7 +207,10 @@ export function parseCliOptions(argv: string[]): CliOptions { const resolvedRoot = parsed.workspaceRoot ?? parsed.root ?? process.cwd() - const normalizedHost = resolveHost(parsed.host) + let policy: NetworkPolicy + try { policy = readNetworkPolicy() } catch (error) { throw new InvalidArgumentError((error as Error).message) } + // The administrator's address wins over --host, CLI_HOST and the desktop listening switch. + const normalizedHost = resolveHost(policy.lockedHost ?? parsed.host, policy.lockedHost ? "CODENOMAD_LOCKED_HOST" : "--host") const autoUpdateString = (parsed.uiAutoUpdate ?? "true").trim().toLowerCase() const uiAutoUpdate = autoUpdateString === "1" || autoUpdateString === "true" || autoUpdateString === "yes" @@ -242,6 +249,8 @@ export function parseCliOptions(argv: string[]): CliOptions { generateToken: parseBooleanSwitchEnv("CODENOMAD_GENERATE_TOKEN") || Boolean(parsed.generateToken), dangerouslySkipAuth: parseBooleanSwitchEnv("CODENOMAD_SKIP_AUTH") || Boolean(parsed.dangerouslySkipAuth), upgrade, + hostLocked: policy.lockedHost !== undefined, + remoteControlDisabled: policy.remoteControlDisabled, } } @@ -253,12 +262,12 @@ function parsePort(input: string): number { return value } -export function resolveHost(input: string | undefined): string { +export function resolveHost(input: string | undefined, source = "--host"): string { const trimmed = input?.trim() if (!trimmed) return DEFAULT_HOST if (hasIPv6Zone(trimmed)) { - throw new InvalidArgumentError("IPv6 zone identifiers are not supported in --host") + throw new InvalidArgumentError(`IPv6 zone identifiers are not supported in ${source}`) } const normalized = normalizeNetworkHost(trimmed) @@ -315,6 +324,7 @@ async function main() { eventsUrl: `/api/events`, host: options.host, listeningMode: isLoopbackHost(options.host) ? "local" : "all", + ...(options.hostLocked ? { listeningLocked: true } : {}), localPort: 0, remotePort: undefined, hostLabel: options.host, @@ -513,6 +523,7 @@ async function main() { previewUpgrade: () => remoteControlPreviewUpgrade, hasPreview: (token) => previewManager.get(token) !== undefined, tunnelApi: process.env.CODENOMAD_REMOTE_CONTROL_API?.trim() || undefined, + disabledByAdministrator: options.remoteControlDisabled, logger: logger.child({ component: "remote-control" }), }) const httpsPortExplicit = programHasArg(process.argv.slice(2), "--https-port") || Boolean(process.env.CLI_HTTPS_PORT) diff --git a/packages/server/src/integration-types.ts b/packages/server/src/integration-types.ts index 0b73af56f4..a09b808487 100644 --- a/packages/server/src/integration-types.ts +++ b/packages/server/src/integration-types.ts @@ -19,7 +19,7 @@ export type { export type { IntegrationCatalogState } from "./opencode/integrations/catalog" export type { IntegrationRuntimeState } from "./opencode/integrations/status" -/** One catalog integration in a Location, without the catalog's plugin ID, `rpc`, `sources` and `package`. */ +/** One catalog integration in a Location, with its recognized runtime identity and projected status. */ export interface IntegrationView { id: string displayName: string @@ -33,9 +33,10 @@ export interface IntegrationView { configured: boolean /** * `declared`: at least one recognised source declaration (Global, Project or inherited); `runtime`: the native - * inventory loaded it or it failed to load, absent otherwise. Activation rules alone set neither. + * inventory loaded it or it failed to load, absent otherwise. `runtimeId` identifies an unambiguous runtime + * entry for display correlation, independently of writable declarations. Activation rules alone set neither. */ - plugin: { declared: boolean; runtime?: "loaded" | "failed" } + plugin: { declared: boolean; runtime?: "loaded" | "failed"; runtimeId?: string } /** * A source designates another integration too or loaded under another plugin ID, a failure is shared by several * sources, or two runtime candidates exist: those sources and the runtime entry are attributed to none. diff --git a/packages/server/src/missions/mission-schedule-contract.ts b/packages/server/src/missions/mission-schedule-contract.ts index 504ecc4925..5bce654f9e 100644 --- a/packages/server/src/missions/mission-schedule-contract.ts +++ b/packages/server/src/missions/mission-schedule-contract.ts @@ -122,6 +122,10 @@ const result = { type: "object", properties: { document: { ...summary, type: ["o /** Native RPC validates the wire first; the strict domain codec and signed action * are revalidated before any document or native effect. */ export const missionScheduleRpcMethods = { + scheduleFlag: { input: { type: "object", properties: {}, additionalProperties: false }, + output: { type: "object", properties: { enabled: { type: "boolean" }, + provenance: { type: "string", enum: ["environment", "experimental-block", "all-flags", "channel-default"] } }, + required: ["enabled", "provenance"], additionalProperties: false } }, scheduleList: { input: { type: "object", properties: { after: text, limit: { type: "integer", minimum: 1, maximum: MISSION_SCHEDULE_PAGE_MAX } }, additionalProperties: false }, output: { type: "object", properties: { version: { const: 1 }, projectID: text, next: text, schedules: { type: "array", maxItems: MISSION_SCHEDULE_PAGE_MAX, items: summary } }, required: ["version", "projectID", "schedules"], additionalProperties: false } }, diff --git a/packages/server/src/opencode-update/legacy-installation.test.ts b/packages/server/src/opencode-update/legacy-installation.test.ts index 0252709a41..069f7e1244 100644 --- a/packages/server/src/opencode-update/legacy-installation.test.ts +++ b/packages/server/src/opencode-update/legacy-installation.test.ts @@ -110,7 +110,7 @@ test("OpenCode 1.x npm shims are identified by package manifest and shim target assert.deepEqual(legacyNpmInstallation(command, prefix, directory, process.platform), { command, prefix, binary: path.join(legacyNpmPackageRoot(prefix, process.platform), "bin", "opencode.exe"), version: "1.18.10" }) const manifest = path.join(legacyNpmPackageRoot(prefix, process.platform), "package.json") - await writeFile(manifest, JSON.stringify({ name: "opencode-ai", version: "2.2.3", bin: { opencode: "bin/opencode.exe" } })) + await writeFile(manifest, JSON.stringify({ name: "opencode-ai", version: "2.3.0", bin: { opencode: "bin/opencode.exe" } })) assert.equal(legacyNpmInstallation(command, prefix, directory, process.platform), undefined, "a supported version is never replaced") await writeFile(manifest, JSON.stringify({ name: "other", version: "1.18.10", bin: { opencode: "bin/opencode.exe" } })) assert.equal(legacyNpmInstallation(command, prefix, directory, process.platform), undefined) @@ -140,19 +140,19 @@ test("legacy npm OpenCode is replaced in its prefix only after explicit consent, let registered = 0 const options = { ...host, node: process.execPath, npm: "fixture-npm.js", execute: installer(prefix, calls), probe, registerPath: async () => { registered++ } } - await assert.rejects(installSharedOpenCode("2.2.3", options), + await assert.rejects(installSharedOpenCode("2.3.0", options), (error: unknown) => error instanceof LegacyReplacementError && error.code === "legacy_replacement_required") assert.deepEqual(calls, []) assert.ok(existsSync(command), "nothing changes without consent") for (const stale of [{ path: command, version: "1.18.9" }, { path: path.join(home, "other", "opencode.cmd"), version: "1.18.10" }]) { - await assert.rejects(installSharedOpenCode("2.2.3", { ...options, replaceLegacy: stale }), + await assert.rejects(installSharedOpenCode("2.3.0", { ...options, replaceLegacy: stale }), (error: unknown) => error instanceof LegacyReplacementError && error.code === "legacy_replacement_required") } assert.deepEqual(calls, [], "consent applies only to the exact installation shown") - assert.equal(await installSharedOpenCode("2.2.3", { ...options, replaceLegacy: { path: command, version: "1.18.10" } }), npmExecutable(prefix)) - assert.deepEqual(calls, ["uninstall opencode-ai", "install @opencode/cli@2.2.3"]) + assert.equal(await installSharedOpenCode("2.3.0", { ...options, replaceLegacy: { path: command, version: "1.18.10" } }), npmExecutable(prefix)) + assert.deepEqual(calls, ["uninstall opencode-ai", "install @opencode/cli@2.3.0"]) assert.equal(registered, 1) assert.equal(existsSync(path.join(prefix, ".codenomad-opencode-install.lock")), false) assert.equal(resolveDefaultInstallation(host).source, "path") @@ -169,14 +169,14 @@ test("an OpenCode 2 installation failure after removing 1.x is reported and rema let offline = true const options = { ...host, node: process.execPath, npm: "fixture-npm.js", probe, registerPath: async () => {}, execute: installer(prefix, calls, () => offline ? new Error("ENOTFOUND registry.npmjs.org") : undefined) } - await assert.rejects(installSharedOpenCode("2.2.3", { ...options, replaceLegacy: { path: command, version: "1.18.10" } }), (error: unknown) => + await assert.rejects(installSharedOpenCode("2.3.0", { ...options, replaceLegacy: { path: command, version: "1.18.10" } }), (error: unknown) => error instanceof LegacyReplacementError && error.code === "legacy_removed_install_failed" && /ENOTFOUND/.test(error.message)) - assert.deepEqual(calls, ["uninstall opencode-ai", "install @opencode/cli@2.2.3"], "never retried through another mechanism") + assert.deepEqual(calls, ["uninstall opencode-ai", "install @opencode/cli@2.3.0"], "never retried through another mechanism") assert.equal(existsSync(path.join(prefix, ".codenomad-opencode-install.lock")), false) assert.deepEqual(sharedInstallationPlan(host), { prefix }, "retry is an ordinary installation without the removed package") offline = false - await installSharedOpenCode("2.2.3", options) - assert.deepEqual(calls.slice(2), ["install @opencode/cli@2.2.3"]) + await installSharedOpenCode("2.3.0", options) + assert.deepEqual(calls.slice(2), ["install @opencode/cli@2.3.0"]) } finally { await rm(home, { recursive: true, force: true }) } }) @@ -196,9 +196,9 @@ for (const form of ["symlink", "hardlink"] as const) test(`winget OpenCode 1.x ( ...(form === "symlink" ? { packageId: "SST.opencode" } : {}) } }) const calls: string[] = [] - await installSharedOpenCode("2.2.3", { ...wingetHost, node: process.execPath, npm: "fixture-npm.js", probe, + await installSharedOpenCode("2.3.0", { ...wingetHost, node: process.execPath, npm: "fixture-npm.js", probe, execute: installer(prefix, calls), registerPath: async () => {} }) - assert.deepEqual(calls, ["install @opencode/cli@2.2.3"]) + assert.deepEqual(calls, ["install @opencode/cli@2.3.0"]) assert.deepEqual(resolveDefaultInstallation(wingetHost), { path: npmExecutable(prefix), source: "managed" }) assert.equal(sharedInstallationPlan(wingetHost).prefix, prefix, "the managed installation keeps receiving updates") assert.equal(await readFile(winget.target, "utf8"), "1.19.0") @@ -221,9 +221,9 @@ test("winget OpenCode first on PATH with npm OpenCode 1.x behind it replaces onl assert.equal(plan.foreign?.source, "winget") const calls: string[] = [] const options = { ...wingetHost, node: process.execPath, npm: "fixture-npm.js", probe, execute: installer(prefix, calls), registerPath: async () => {} } - await assert.rejects(installSharedOpenCode("2.2.3", options), /explicit confirmation/) - await installSharedOpenCode("2.2.3", { ...options, replaceLegacy: { path: plan.legacy!.command, version: "1.18.10" } }) - assert.deepEqual(calls, ["uninstall opencode-ai", "install @opencode/cli@2.2.3"]) + await assert.rejects(installSharedOpenCode("2.3.0", options), /explicit confirmation/) + await installSharedOpenCode("2.3.0", { ...options, replaceLegacy: { path: plan.legacy!.command, version: "1.18.10" } }) + assert.deepEqual(calls, ["uninstall opencode-ai", "install @opencode/cli@2.3.0"]) assert.deepEqual(resolveDefaultInstallation(wingetHost), { path: npmExecutable(prefix), source: "managed" }) assert.equal(await readFile(winget.target, "utf8"), "1.19.0") } finally { await rm(home, { recursive: true, force: true }) } @@ -232,13 +232,13 @@ test("winget OpenCode first on PATH with npm OpenCode 1.x behind it replaces onl test("valid foreign OpenCode 2 keeps PATH precedence; unusable foreign commands yield to managed OpenCode 2", async () => { const { home, env, host, prefix } = await environment("foreign-") try { - await cliFixture(prefix, "2.2.3") + await cliFixture(prefix, "2.3.0") const foreign = path.join(home, "tools", windows ? "opencode.exe" : "opencode") await mkdir(path.dirname(foreign), { recursive: true }) await writeFile(foreign, "foreign", { mode: 0o755 }) env.PATH = [path.dirname(foreign), npmCommandDirectory(prefix)].join(path.delimiter) // Valid OpenCode 2, custom labels and unknown (not yet probed or timed out) keep PATH precedence. - for (const probeForeign of [() => ({ valid: true, version: "2.2.4" }), () => ({ valid: true, version: "local-build" }), () => undefined]) { + for (const probeForeign of [() => ({ valid: true, version: "2.3.1" }), () => ({ valid: true, version: "local-build" }), () => undefined]) { assert.deepEqual(resolveDefaultInstallation({ ...host, probeForeign }), { path: foreign, source: "path" }) assert.deepEqual(sharedInstallationPlan({ ...host, probeForeign }), {}) } @@ -343,7 +343,7 @@ test("opencode-ai 1.0-1.15.0 Node-launcher installs are recognized and every nat await chmod(nested, 0o444) const calls: string[] = [] try { - await assert.rejects(installSharedOpenCode("2.2.3", { ...host, node: process.execPath, npm: "fixture-npm.js", probe, + await assert.rejects(installSharedOpenCode("2.3.0", { ...host, node: process.execPath, npm: "fixture-npm.js", probe, execute: installer(prefix, calls), registerPath: async () => {}, replaceLegacy: { path: command, version: "1.15.0" } }), (error: unknown) => error instanceof InstallationBusyError && error.code === "installation_in_use") } finally { await chmod(nested, 0o644) } @@ -358,7 +358,7 @@ test("npm uninstall failures report whether OpenCode 1.x is still installed", as const command = await legacyFixture(prefix) env.PATH = npmCommandDirectory(prefix) const consent = { path: command, version: "1.18.10" } - const attempt = (execute: (node: string, args: string[]) => Promise) => installSharedOpenCode("2.2.3", { + const attempt = (execute: (node: string, args: string[]) => Promise) => installSharedOpenCode("2.3.0", { ...host, node: process.execPath, npm: "fixture-npm.js", probe, execute, registerPath: async () => {}, replaceLegacy: consent }) const failure = (npmCode?: string) => Object.assign(new Error("OpenCode installation failed (1)"), npmCode ? { npmCode } : {}) for (const code of ["EBUSY", "EPERM"]) { @@ -384,9 +384,9 @@ test("foreign version probes are asynchronous, bounded and kill the process tree assert.deepEqual(cachedForeignProbe(quick), undefined, "a cache miss reports unknown without spawning synchronously") assert.deepEqual(await probeForeignCommand(quick), { valid: true, version: "1.19.0" }) assert.deepEqual(cachedForeignProbe(quick), { valid: true, version: "1.19.0" }) - await writeFile(quick, windows ? "@echo opencode 2.2.3 \r\n" : "#!/bin/sh\necho opencode 2.2.3 \n", { mode: 0o755 }) + await writeFile(quick, windows ? "@echo opencode 2.3.0 \r\n" : "#!/bin/sh\necho opencode 2.3.0 \n", { mode: 0o755 }) assert.equal(cachedForeignProbe(quick), undefined, "a changed file invalidates the cached decision") - assert.deepEqual(await probeForeignCommand(quick), { valid: true, version: "2.2.3" }) + assert.deepEqual(await probeForeignCommand(quick), { valid: true, version: "2.3.0" }) const pidFile = path.join(home, "grandchild.pid") const script = path.join(home, "hang.js") diff --git a/packages/server/src/opencode-update/native-upgrade.test.ts b/packages/server/src/opencode-update/native-upgrade.test.ts index fa21c869ca..52c9c9e928 100644 --- a/packages/server/src/opencode-update/native-upgrade.test.ts +++ b/packages/server/src/opencode-update/native-upgrade.test.ts @@ -99,7 +99,7 @@ test("native upgrade npm/npx commands override hostile caller PATH and cwd witho const env: NodeJS.ProcessEnv = { PATH: [hostile, process.platform === "win32" ? path.join(process.env.SystemRoot ?? "C:\\Windows", "System32") : "/bin"].join(path.delimiter), ...(process.platform === "win32" ? { SystemRoot: process.env.SystemRoot, ComSpec: process.env.ComSpec } : {}) } const original = { ...env } - await upgradeSharedOpenCode({ binary: "verified-opencode", version: "2.2.5", prefix, node: process.execPath, + await upgradeSharedOpenCode({ binary: "verified-opencode", version: "2.3.2", prefix, node: process.execPath, npm: path.join(bundled, "npm-cli.js"), env, platform: process.platform, execute: async (_file, _args, childEnv, options) => { assert.notEqual(options!.cwd, hostile, "the native command owns cwd as well as PATH") @@ -108,7 +108,7 @@ test("native upgrade npm/npx commands override hostile caller PATH and cwd witho ? spawnSync(process.env.ComSpec || "cmd.exe", ["/d", "/s", "/c", name], { cwd: options?.cwd ?? hostile, env: childEnv, windowsHide: true, encoding: "utf8" }) : spawnSync(name, [], { cwd: options?.cwd ?? hostile, env: childEnv, windowsHide: true, encoding: "utf8" }) assert.equal(result.status, 0, result.stderr) - assert.deepEqual(JSON.parse(result.stdout), { execPath: process.execPath, cli: path.join(bundled, name + "-cli.js"), prefix, allow: "@opencode/cli@2.2.5" }) + assert.deepEqual(JSON.parse(result.stdout), { execPath: process.execPath, cli: path.join(bundled, name + "-cli.js"), prefix, allow: "@opencode/cli@2.3.2" }) } } }) assert.deepEqual(env, original) @@ -164,9 +164,9 @@ test("shared update delegates to native CLI, verifies publication, and never ret assert.equal(calls, 1, "no downgrade or same-version native invocation") assert.equal(registrations, 2) assert.equal(await readFile(binary, "utf8"), minimum) - await writeFile(binary, "2.2.4") + await writeFile(binary, "2.3.1") await installSharedOpenCode(minimum, options) - assert.equal(await readFile(binary, "utf8"), "2.2.4", "never downgrade a newer verified installation") + assert.equal(await readFile(binary, "utf8"), "2.3.1", "never downgrade a newer verified installation") assert.equal(calls, 1) } finally { await rm(home, { recursive: true, force: true }) } }) diff --git a/packages/server/src/opencode-update/service.test.ts b/packages/server/src/opencode-update/service.test.ts index e456ce39da..294de8f51f 100644 --- a/packages/server/src/opencode-update/service.test.ts +++ b/packages/server/src/opencode-update/service.test.ts @@ -118,10 +118,10 @@ test("user npm PATH repair remains available without an update and never downgra let migrated = false, installs = 0 const service = new OpenCodeUpdateService(deps({ resolveBinary: () => ({ path: migrated ? "common" : source, label: "OpenCode", source: migrated ? "path" : source }), - probeBinary: () => ({ valid: true, version: "2.2.4" }), + probeBinary: () => ({ valid: true, version: "2.3.1" }), resolveLatestVersion: async () => minimum, upgradeBinary: async (_binary, target) => { - assert.equal(target, "2.2.4") + assert.equal(target, "2.3.1") installs++; migrated = true return { success: true, version: target } }, @@ -244,7 +244,7 @@ test("coalesces overlapping installations and never downgrades a newer version", release() await Promise.all([first, second]) assert.equal(upgrades, 1) - version = "2.2.999" + version = "2.3.999" assert.equal((await service.getStatus()).updateAvailable, false) assert.equal((await service.upgrade()).version, version) assert.equal(upgrades, 1) @@ -332,8 +332,8 @@ test("optional upgrades retain explicit activation for an admitted but older dae return value } const service = new OpenCodeUpdateService(deps({ - probeBinary: () => ({ valid: true, version: installed }), resolveLatestVersion: async () => "2.2.4", - upgradeBinary: async () => { installed = "2.2.4"; return { success: true, version: installed } }, + probeBinary: () => ({ valid: true, version: installed }), resolveLatestVersion: async () => "2.3.1", + upgradeBinary: async () => { installed = "2.3.1"; return { success: true, version: installed } }, lifecycle: async () => ({ discover: async () => endpoint(), ensure: async () => endpoint(), restart: async () => { restarts++; daemon = installed; return endpoint() } }), })) @@ -383,7 +383,7 @@ test("same-version troubleshooting restart is explicit for host and WSL; reload }) test("troubleshooting restart refuses unknown identity/builds and a newer daemon", async () => { - for (const version of [undefined, "custom-build", "2.2.4"]) { + for (const version of [undefined, "custom-build", "2.3.1"]) { const endpoint: Endpoint = { url: "http://127.0.0.1:9876" } if (version) rememberRuntime(endpoint, { version, pid: 123, discovery: "info" }) const service = new OpenCodeUpdateService(deps({ @@ -473,7 +473,7 @@ test("an in-flight native reload holds shared-service authority across binary ch rememberRuntime(endpoint, { version: minimum, pid: 123, discovery: "info" }) const service = new OpenCodeUpdateService(deps({ resolveBinary: () => ({ path: selected, label: "Fixture" }), - probeBinary: () => ({ valid: true, version: "2.2.4" }), + probeBinary: () => ({ valid: true, version: "2.3.1" }), lifecycle: async () => ({ discover: async () => endpoint, ensure: async () => endpoint, restart: async () => { restarts++; return endpoint } }), reload: async (_binary, assertCurrent) => { assertCurrent(); entered(); await gate }, @@ -495,27 +495,28 @@ test("beta version comparison remains numeric", () => { }) test("the native contract floor admits current and newer runtimes without a tested-version allowlist", async () => { - for (const version of ["2.2.3", "2.2.4", "2.2.5", "2.2.6", "2.2.7", "2.3.0", "3.0.0"]) { + const latest = "2.4.0" + for (const version of ["2.3.0", "2.3.1", "2.3.4", latest, "3.0.0"]) { const endpoint: Endpoint = { url: "http://127.0.0.1:9876" } rememberRuntime(endpoint, { version, pid: 123, discovery: "info" }) const service = new OpenCodeUpdateService(deps({ - probeBinary: () => ({ valid: true, version }), resolveLatestVersion: async () => recommended, + probeBinary: () => ({ valid: true, version }), resolveLatestVersion: async () => latest, lifecycle: async () => ({ discover: async () => endpoint, ensure: async () => { throw new Error("must retain daemon") } }), })) const status = await service.start() - assert.equal(status.minimumVersion, "2.2.3") + assert.equal(status.minimumVersion, "2.3.0") assert.equal(status.recommendedVersion, recommended) assert.equal(status.state, "ready") assert.equal(status.serviceState, "ready") assert.equal(status.versionAssessment, version === recommended ? "tested" : "untested", "only the current recommendation is release-qualified") assert.equal(status.incompatibilityReason, undefined) - assert.equal(status.canUpgrade, ["2.2.3", "2.2.4", "2.2.5", "2.2.6"].includes(version), "offer an optional upgrade below the latest release; never downgrade current or newer runtimes") + assert.equal(status.canUpgrade, ["2.3.0", "2.3.1", "2.3.4"].includes(version), "offer an optional upgrade below the latest release; never downgrade current or newer runtimes") assert.equal(status.canRestart, false) } }) test("older daemons require the minimum's native contracts without being started or replaced", async () => { - for (const version of ["2.0.27", "2.0.32", "2.1.2", "2.2.1", "2.2.2"]) { + for (const version of ["2.0.27", "2.0.32", "2.1.2", "2.2.2", "2.2.3", "2.2.7"]) { const endpoint: Endpoint = { url: "http://127.0.0.1:9876" } rememberRuntime(endpoint, { version, pid: 123, discovery: "info" }) const service = new OpenCodeUpdateService(deps({ @@ -527,7 +528,7 @@ test("older daemons require the minimum's native contracts without being started assert.equal(status.incompatibilityReason, "native_contract") assert.equal(status.versionAssessment, "incompatible") // Admission refuses the daemon itself; it is never started, restarted or replaced implicitly. - await assert.rejects(service.start(), /opencode_update_required.*experimental_image_generate tool contract.*of 2\.2\.3/) + await assert.rejects(service.start(), /opencode_update_required.*background subagent report contract.*of 2\.3\.0/) } }) @@ -562,7 +563,7 @@ test("custom labels are unverified, not an update demand; optional reload follow }) test("production stdout parsing preserves custom labels through discovery and activation", async () => { - for (const [stdout, label] of [["custom-build\n", "custom-build"], ["opencode v2.2.3+custom-build\n", "2.2.3+custom-build"], + for (const [stdout, label] of [["custom-build\n", "custom-build"], ["opencode v2.3.0+custom-build\n", "2.3.0+custom-build"], ["opencode2 vendor-build\n", "vendor-build"], ["", "unknown"]]) { const endpoint: Endpoint = { url: "http://127.0.0.1:9876" } rememberRuntime(endpoint, { version: label!, pid: 123, discovery: "info" }) diff --git a/packages/server/src/opencode-update/setup-reconnect.test.ts b/packages/server/src/opencode-update/setup-reconnect.test.ts index 9c77670364..1f74a19bec 100644 --- a/packages/server/src/opencode-update/setup-reconnect.test.ts +++ b/packages/server/src/opencode-update/setup-reconnect.test.ts @@ -16,14 +16,14 @@ test("optional setup rebinds real workspace ownership without restarting the sup const parent = path.join(os.tmpdir(), "opencode") await mkdir(parent, { recursive: true }) const root = await mkdtemp(path.join(parent, "codenomad-setup-reconnect-")) - const originalBinary = path.join(root, "2.2.3", "opencode.exe") - const installedBinary = path.join(root, "2.2.4", "opencode.exe") + const originalBinary = path.join(root, "2.3.0", "opencode.exe") + const installedBinary = path.join(root, "2.3.1", "opencode.exe") let selected = originalBinary let starts = 0 let restarts = 0 let reloads = 0 const endpoint: Endpoint = { url: "http://127.0.0.1:1" } - rememberRuntime(endpoint, { version: "2.2.3", pid: 123, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.0", pid: 123, discovery: "info" }) const lifecycle: OpenCodeServiceLifecycle = { discover: async () => endpoint, ensure: async () => { starts++; throw new Error("The existing daemon must not be started again") }, @@ -52,12 +52,12 @@ test("optional setup rebinds real workspace ownership without restarting the sup }) const updater = new OpenCodeUpdateService({ resolveBinary: () => ({ path: selected, label: "Fixture OpenCode" }), - probeBinary: binary => ({ valid: true, version: binary === installedBinary ? "2.2.4" : "2.2.3" }), - resolveLatestVersion: async () => "2.2.4", + probeBinary: binary => ({ valid: true, version: binary === installedBinary ? "2.3.1" : "2.3.0" }), + resolveLatestVersion: async () => "2.3.1", canUpgradeBinary: () => true, upgradeBinary: async () => { selected = installedBinary - return { success: true, version: "2.2.4" } + return { success: true, version: "2.3.1" } }, lifecycle: async binary => (await manager.setupServiceOptions(binary.path)).lifecycle, admitActivation: binary => manager.assertSetupExecutionHost(binary.path), @@ -78,8 +78,8 @@ test("optional setup rebinds real workspace ownership without restarting the sup const status = await updater.start(false) assert.equal(status.state, "ready") - assert.equal(status.currentVersion, "2.2.4") - assert.equal(status.daemonVersion, "2.2.3") + assert.equal(status.currentVersion, "2.3.1") + assert.equal(status.daemonVersion, "2.3.0") assert.equal(status.serviceState, "restart_available") assert.equal(status.canRestart, true, "non-disruptive reconnect retains explicit activation") assert.throws(() => originalConnection.assertCurrent(), /OpenCode connection changed/) diff --git a/packages/server/src/opencode-update/shared-installation.test.ts b/packages/server/src/opencode-update/shared-installation.test.ts index 91bbe6cad2..edeb3aa3f6 100644 --- a/packages/server/src/opencode-update/shared-installation.test.ts +++ b/packages/server/src/opencode-update/shared-installation.test.ts @@ -10,7 +10,7 @@ import { execFile } from "node:child_process" import { promisify } from "node:util" import { MINIMUM_OPENCODE_VERSION as minimum } from "../opencode/runtime-support" -const validV2 = () => ({ valid: true, version: "2.2.3" }) +const validV2 = () => ({ valid: true, version: "2.3.0" }) async function npmFixture(prefix: string, version: string) { const binary = npmExecutable(prefix) @@ -31,10 +31,10 @@ test("private copies and their receipts are ignored; PATH wins over the user npm const host = { home, env } try { const root = path.join(home, ".local/share/codenomad/opencode") - const legacy = path.join(root, "2.2.99/node_modules/@opencode/cli/bin/opencode.exe") + const legacy = path.join(root, "2.3.99/node_modules/@opencode/cli/bin/opencode.exe") await mkdir(path.dirname(legacy), { recursive: true }); await writeFile(legacy, "legacy") - await mkdir(path.join(root, "selected")); await writeFile(path.join(root, "selected/2.2.99"), "") - await writeFile(path.join(root, "current"), "2.2.99") + await mkdir(path.join(root, "selected")); await writeFile(path.join(root, "selected/2.3.99"), "") + await writeFile(path.join(root, "current"), "2.3.99") assert.deepEqual(resolveDefaultInstallation(host), { path: "opencode2" }) assert.equal(sharedInstallPrefix(host), userNpmPrefix(host)) const prefix = userNpmPrefix(host) @@ -58,7 +58,7 @@ test("normal global-user npm install publishes terminal command and retries PATH execute: async (_file: string, args: string[]) => { installs++ if (args[0] === "upgrade") { - assert.deepEqual(args, ["upgrade", "2.2.4", "--method", "npm"]) + assert.deepEqual(args, ["upgrade", "2.3.1", "--method", "npm"]) await npmFixture(prefix, args[1]!) return } @@ -86,15 +86,15 @@ test("normal global-user npm install publishes terminal command and retries PATH assert.equal(installs, 1) assert.equal(resolveDefaultInstallation(options).path, findPathOpenCode(options)) assert.equal(resolveDefaultInstallation(options).source, "path") - await installSharedOpenCode("2.2.4", options) + await installSharedOpenCode("2.3.1", options) assert.equal(installs, 2) await installSharedOpenCode(minimum, options) assert.equal(installs, 2, "never downgrade a newer common installation") - assert.equal((await options.probe(npmExecutable(prefix))).version, "2.2.4") + assert.equal((await options.probe(npmExecutable(prefix))).version, "2.3.1") await rm(findPathOpenCode(options)!) await installSharedOpenCode(minimum, options) assert.equal(installs, 3, "missing command is repaired at the newer installed version") - assert.equal((await options.probe(npmExecutable(prefix))).version, "2.2.4") + assert.equal((await options.probe(npmExecutable(prefix))).version, "2.3.1") } finally { await rm(home, { recursive: true, force: true }) } }) diff --git a/packages/server/src/opencode/compatibility/negotiate.test.ts b/packages/server/src/opencode/compatibility/negotiate.test.ts index 056c9f0e3e..0a7a98d413 100644 --- a/packages/server/src/opencode/compatibility/negotiate.test.ts +++ b/packages/server/src/opencode/compatibility/negotiate.test.ts @@ -8,7 +8,7 @@ import { UnsupportedOpenCodeError } from "../runtime-support" test("unknown contracts perform authenticated bounded read negotiation before any mutation", async () => { for (const kind of ["unauthorized", "unrecognized", "oversized"] as const) { const endpoint = { url: "http://127.0.0.1:4321", auth: { type: "basic" as const, username: "opencode", password: "fixture" } } - rememberRuntime(endpoint, { version: "2.2.100", pid: 1, discovery: "status" }) + rememberRuntime(endpoint, { version: "2.3.100", pid: 1, discovery: "status" }) let calls = 0, cancelled = false const transport = createRuntimeFetch(endpoint, async (input, init) => { calls++ @@ -53,7 +53,7 @@ test("unknown labels with an obsolete contract or missing environment fail for a test("shared negotiation has independent subscriber cancellation and never retries a mutation", async () => { const endpoint = { url: "http://127.0.0.1:4321" } - rememberRuntime(endpoint, { version: "2.2.100", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.100", pid: 1, discovery: "info" }) let complete!: (response: Response) => void let negotiationSignal: AbortSignal | null | undefined const calls: string[] = [] diff --git a/packages/server/src/opencode/compatibility/runtime.ts b/packages/server/src/opencode/compatibility/runtime.ts index b77cab0782..180567c419 100644 --- a/packages/server/src/opencode/compatibility/runtime.ts +++ b/packages/server/src/opencode/compatibility/runtime.ts @@ -25,6 +25,6 @@ export function contractProfile(identity: RuntimeIdentity | undefined): Contract // Publication contract reviewed and exercised by the isolated native suites // (minimum and qualification target). Unlisted versions still negotiate their // authenticated schema. - if (identity.version === "2.2.3" || identity.version === "2.2.5") return "modern" + if (identity.version === "2.3.0") return "modern" return "unknown" } diff --git a/packages/server/src/opencode/compatibility/transport.test.ts b/packages/server/src/opencode/compatibility/transport.test.ts index f63585da0f..a99b93176b 100644 --- a/packages/server/src/opencode/compatibility/transport.test.ts +++ b/packages/server/src/opencode/compatibility/transport.test.ts @@ -6,8 +6,8 @@ import { createRuntimeFetch } from "./transport" import { modernContractFixture } from "./contract-fixture" test("current and future supported releases preserve info, authentication and bounded negotiation", async () => { - const reviewed = ["2.2.3", "2.2.5"] - for (const version of [...reviewed, "2.2.4", "2.3.0", "2.2.100", "3.0.0", "2.2.0-dev.1", "custom-build"]) { + const reviewed = ["2.3.0"] + for (const version of [...reviewed, "2.3.1", "2.3.2", "2.4.0", "2.3.100", "3.0.0", "2.2.0-dev.1", "custom-build"]) { const endpoint = { url: "http://127.0.0.1:4321", auth: { type: "basic" as const, username: "opencode", password: "fixture" } } rememberRuntime(endpoint, { version, pid: 123, discovery: "info" }) const seen: string[] = [] @@ -26,7 +26,7 @@ test("current and future supported releases preserve info, authentication and bo test("info and status routes are forwarded unchanged and never probe alternate routes on failure", async () => { const endpoint = { url: "http://127.0.0.1:4321" } - rememberRuntime(endpoint, { version: "2.2.3", pid: 123, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.0", pid: 123, discovery: "info" }) const seen: string[] = [] const fetch = createRuntimeFetch(endpoint, async (input, init) => { const path = new URL(String(input)).pathname @@ -50,7 +50,7 @@ test("retired runtime contracts never dispatch even through the direct transport test("canonical mutations and inbox timestamps are forwarded unchanged", async () => { const endpoint = { url: "http://127.0.0.1:4321" } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.0", pid: 1, discovery: "info" }) const calls: Array<{ path: string; method: string; body: unknown }> = [] const client = OpenCode.make({ baseUrl: endpoint.url, fetch: createRuntimeFetch(endpoint, async (input, init) => { const request = new Request(input, init) @@ -71,7 +71,7 @@ test("canonical mutations and inbox timestamps are forwarded unchanged", async ( test("errors never retry mutations; native error envelopes, abort and origin fencing survive", async () => { const endpoint = { url: "http://127.0.0.1:4321" } - rememberRuntime(endpoint, { version: "2.2.3", pid: 2, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.0", pid: 2, discovery: "info" }) let calls = 0 for (const status of [400, 401, 404, 500]) { const envelope = { _tag: "NativeError", message: "fixture" } diff --git a/packages/server/src/opencode/desktop-plugin-readiness-ownership.test.ts b/packages/server/src/opencode/desktop-plugin-readiness-ownership.test.ts index 6a8a2a00c5..0a7dfea890 100644 --- a/packages/server/src/opencode/desktop-plugin-readiness-ownership.test.ts +++ b/packages/server/src/opencode/desktop-plugin-readiness-ownership.test.ts @@ -5,7 +5,7 @@ import path from "node:path" import os from "node:os" import { createHash, randomUUID } from "node:crypto" import { syncBuiltinESMExports } from "node:module" -import { setTimeout as delay } from "node:timers/promises" +import { setTimeout as delay, setImmediate as nextTurn } from "node:timers/promises" import { createServer } from "node:http" import { OpenCode } from "@opencode/client" import { ownReadiness, registeredReadiness } from "./desktop-plugin-readiness" @@ -25,6 +25,22 @@ async function until(read: () => Promise) { for (let i = 0; i < 200; i++) { if (await read()) return; await delay(5) } throw new Error("Fixture condition timed out") } +async function requestFile(lease: string) { + let file = "" + await until(async () => { + for (const name of await fs.readdir(`${lease}.prepare`).catch(() => [])) { + if (!name.endsWith(".json")) continue + const text = await fs.readFile(path.join(`${lease}.prepare`, name), "utf8").catch(() => "") + try { + if (JSON.parse(text).nonce !== name.slice(0, -5)) continue + file = path.join(`${lease}.prepare`, name) + return true + } catch { /* Exclusive creation exposes the name before its bytes are written. */ } + } + return false + }) + return file +} const scopeNamespace = (root: string, location = root) => path.join(root, "readiness", createHash("sha256").update(location).digest("hex")) test("real exclusive request collision preserves foreign request and ACK through owner close", async t => { @@ -108,17 +124,37 @@ test("partial owned write is cleaned, while request and ACK replacements stay fo assert.equal(await fs.stat(file).catch(() => undefined), undefined) } finally { t.mock.restoreAll(); syncBuiltinESMExports() } const scope = registeredReadiness(f.root, f.root, () => {}), controller = new AbortController() + let release!: () => void, enter!: () => void + const hold = new Promise(resolve => { release = resolve }), admitted = new Promise(resolve => { enter = resolve }) + t.mock.method(fs, "writeFile", async (...args: Parameters) => { + if (typeof args[0] === "object" && "fd" in args[0] && String(args[1]).includes('"nonce"')) { enter(); await hold } + return original(...args) + }) + // Keep the backend's request alive while testing foreign replacements. + t.mock.method(fs, "open", async (...args: Parameters) => { + if (String(args[0]).endsWith(".ack") && args[1] === "r") throw Object.assign(new Error("ACK read held"), { code: "ENOENT" }) + return originalOpen(...args) + }) + syncBuiltinESMExports() const pending = f.owner.prepare(f.root, controller.signal, () => {}) const settled = pending.catch(() => {}) - await until(async () => (await fs.readdir(`${f.lease}.prepare`)).some(name => name.endsWith(".json"))) - file = path.join(`${f.lease}.prepare`, (await fs.readdir(`${f.lease}.prepare`)).find(name => name.endsWith(".json"))!) - await scope.reconcile([path.basename(f.lease)]) - const ack = file.slice(0, -5) + ".ack" - await fs.rm(file); await fs.writeFile(file, "request replacement") - await fs.rm(ack); await fs.writeFile(ack, "ACK replacement") - controller.abort(); await settled; await scope.close(); await f.owner.close() - assert.equal(await fs.readFile(file, "utf8"), "request replacement") - assert.equal(await fs.readFile(ack, "utf8"), "ACK replacement") + try { + await admitted + await scope.reconcile([path.basename(f.lease)]) + assert.equal((await fs.readdir(`${f.lease}.prepare`)).some(name => name.endsWith(".ack")), false, "an incomplete request is not proof") + release() + file = await requestFile(f.lease) + await scope.reconcile([path.basename(f.lease)]) + const ack = file.slice(0, -5) + ".ack" + await fs.rm(file); await fs.writeFile(file, "request replacement") + await fs.rm(ack); await fs.writeFile(ack, "ACK replacement") + controller.abort(); await settled; await scope.close(); await f.owner.close() + assert.equal(await fs.readFile(file, "utf8"), "request replacement") + assert.equal(await fs.readFile(ack, "utf8"), "ACK replacement") + } finally { + release(); controller.abort(); await settled; await scope.close() + t.mock.restoreAll(); syncBuiltinESMExports() + } }) test("later lease overflow publishes no ACK, then a fresh request succeeds after removal", async t => { @@ -128,18 +164,19 @@ test("later lease overflow publishes no ACK, then a fresh request succeeds after await fs.writeFile(path.join(f.root, other), ""); await fs.mkdir(folder) for (let i = 0; i < 65; i++) await fs.writeFile(path.join(folder, `${randomUUID()}.json`), "{}") const controller = new AbortController() - const pending = f.owner.prepare(f.root, AbortSignal.any([controller.signal, AbortSignal.timeout(400)]), () => {}) + const pending = f.owner.prepare(f.root, controller.signal, () => {}) let accepted = false void pending.then(() => { accepted = true }, () => {}) const refused = assert.rejects(pending) - await until(async () => (await fs.readdir(`${f.lease}.prepare`).catch(() => [])).some(n => n.endsWith(".json"))) + await requestFile(f.lease) await assert.rejects(scope.reconcile([path.basename(f.lease), other]), /exceeds limit/) assert.equal((await fs.readdir(`${f.lease}.prepare`)).some(n => n.endsWith(".ack")), false) + controller.abort() await refused assert.equal(accepted, false, "the real backend must not accept partial proof from the refused reconciliation") await fs.rm(folder, { recursive: true }) const fresh = f.owner.prepare(f.root, AbortSignal.timeout(2_000), () => {}) - await until(async () => (await fs.readdir(`${f.lease}.prepare`)).some(n => n.endsWith(".json"))) + await requestFile(f.lease) await scope.reconcile([path.basename(f.lease), other]); await fresh await scope.reconcile([path.basename(f.lease)]); await scope.close(); await f.owner.close() assert.equal(await fs.stat(`${f.lease}.prepare`).catch(() => undefined), undefined) @@ -261,9 +298,8 @@ test("scope admission rechecks concurrent namespace growth and cleans only its o test("an ACK creation collision stays owned by its actual foreign creator", async t => { const f = await fixture(t), scope = registeredReadiness(f.root, f.root, () => {}), controller = new AbortController() const pending = f.owner.prepare(f.root, controller.signal, () => {}), refused = assert.rejects(pending) - await until(async () => (await fs.readdir(`${f.lease}.prepare`).catch(() => [])).some(n => n.endsWith(".json"))) - const request = (await fs.readdir(`${f.lease}.prepare`)).find(n => n.endsWith(".json"))! - const ack = path.join(`${f.lease}.prepare`, request.slice(0, -5) + ".ack") + const request = await requestFile(f.lease) + const ack = request.slice(0, -5) + ".ack" await fs.writeFile(ack, "foreign ACK", { flag: "wx" }) try { await scope.reconcile([path.basename(f.lease)]) } finally { controller.abort(); await refused; await scope.close(); await f.owner.close() } @@ -280,13 +316,15 @@ for (const mode of ["abort", "deadline", "replace"] as const) test(`catalogue ${ } } } } as unknown as ServiceConnection const prepared = await lifecycle.prepare({ config: path.join(f.root, "config"), data: path.join(f.root, "data") }, () => {}, connection) prepared.commit(); await prepared.release() + t.mock.timers.enable({ apis: ["Date", "setTimeout"], now: Date.now() }) const pending = lifecycle.ready({ connection, location: { directory: f.root }, signal: controller.signal, deadlineAt: Date.now() + (mode === "deadline" ? 60 : 2_000), assertCurrent() {} }) const refused = assert.rejects(pending, /cancelled|timed out|replaced/).then(() => { returned = true }) try { await admitted if (mode === "abort") controller.abort(new Error("cancelled")) if (mode === "replace") current = false - await delay(mode === "deadline" ? 90 : 30) + t.mock.timers.tick(mode === "deadline" ? 90 : 30) + await nextTurn() assert.equal(returned, false) if (mode !== "replace") assert.equal(transportSignal?.aborted, true) release(); await refused diff --git a/packages/server/src/opencode/integrations/integrations.ts b/packages/server/src/opencode/integrations/integrations.ts index 24aeca807e..68231fd440 100644 --- a/packages/server/src/opencode/integrations/integrations.ts +++ b/packages/server/src/opencode/integrations/integrations.ts @@ -72,6 +72,7 @@ export class IntegrationsReader { plugin: { declared: recognition.sources.length > 0, ...(recognition.runtime ? { runtime: recognition.runtime.state.status === "failed" ? "failed" as const : "loaded" as const } : {}), + ...(!recognition.ambiguous && recognition.runtime?.id ? { runtimeId: recognition.runtime.id } : {}), }, ...(recognition.ambiguous ? { ambiguous: true as const } : {}), scopes, diff --git a/packages/server/src/opencode/missions-plugin.ts b/packages/server/src/opencode/missions-plugin.ts index e2bba90ade..1a568af9c7 100644 --- a/packages/server/src/opencode/missions-plugin.ts +++ b/packages/server/src/opencode/missions-plugin.ts @@ -114,6 +114,7 @@ export interface MissionsPluginContext extends MissionCatalogClient { register( definition: typeof CODENOMAD_MISSIONS_RPC, handlers: { + scheduleFlag(input: unknown): Promise scheduleList(input: unknown): Promise scheduleRead(input: unknown): Promise scheduleControl(input: unknown): Promise @@ -227,6 +228,7 @@ export async function setupMissionsPlugin(context: MissionsPluginContext, transp try { await policy?.configure(control) const handlers: Parameters[1] = { + scheduleFlag: async () => { throw new Error("Native Mission schedule flag graph unavailable") }, scheduleList: async () => { throw new Error("Native Mission schedule graph unavailable") }, scheduleRead: async () => { throw new Error("Native Mission schedule graph unavailable") }, scheduleControl: async () => { throw new Error("Native Mission schedule graph unavailable") }, @@ -296,6 +298,7 @@ export async function setupMissionsPlugin(context: MissionsPluginContext, transp delete: async (input, context) => { assertActive(); return mutationResult(context, () => control.delete(parseDeleteMissionInput(input))) }, } rpcRegistration = await context.rpc.register(CODENOMAD_MISSIONS_RPC, { + scheduleFlag: tracked(handlers.scheduleFlag), scheduleList: tracked(handlers.scheduleList), scheduleRead: tracked(handlers.scheduleRead), scheduleControl: tracked(handlers.scheduleControl), scheduleCarrierRead: tracked(handlers.scheduleCarrierRead), diff --git a/packages/server/src/opencode/missions/native-mission-schedule-rpc.ts b/packages/server/src/opencode/missions/native-mission-schedule-rpc.ts index 7033abdb66..49df601750 100644 --- a/packages/server/src/opencode/missions/native-mission-schedule-rpc.ts +++ b/packages/server/src/opencode/missions/native-mission-schedule-rpc.ts @@ -11,6 +11,7 @@ import { acquireNativeMissionScheduleAuthority, NATIVE_MISSION_SCHEDULE_CONTROL_ import { controlNativeMissionSchedule } from "./native-mission-schedule-control" import { readMissionSchedulePage } from "../../missions/mission-schedule-list" import { nativeMissionScheduleObservation } from "./native-mission-schedule-display" +import { readNativeScheduleFlag } from "./native-schedule-flag" const readInput = z.object({ missionID: documentID, requestID: z.string().min(1).max(128).optional() }).strict() const carrierInput = z.object({ sessionID: nativeDocumentID }).strict() @@ -20,6 +21,7 @@ const carrierInput = z.object({ sessionID: nativeDocumentID }).strict() export function nativeMissionScheduleHandlers(ctx: Plugin.Context, artifacts?: NativeScheduleArtifacts) { const invocation = nativeInvocation(NATIVE_MISSION_SCHEDULE_CONTROL_TIMEOUT_MS) return { + scheduleFlag: () => readNativeScheduleFlag(ctx).pipe(Effect.orDie), scheduleList: (raw: unknown) => invocation.capture(Effect.tryPromise(() => invocation.check(run => readMissionSchedulePage({ scan: input => run(ctx.storage.scan(input)) }, ctx.location.project, raw, doc => nativeMissionScheduleObservation(ctx, doc, run)))).pipe(Effect.orDie)), diff --git a/packages/server/src/opencode/missions/native-schedule-calendar-service.test.ts b/packages/server/src/opencode/missions/native-schedule-calendar-service.test.ts index c635ba1dda..33b6a147bd 100644 --- a/packages/server/src/opencode/missions/native-schedule-calendar-service.test.ts +++ b/packages/server/src/opencode/missions/native-schedule-calendar-service.test.ts @@ -38,6 +38,7 @@ async function facade(t: test.TestContext, availability: (state: { enabled: bool Effect.provideService(Context.Service("@opencode/Location"), location), Effect.provideService(Context.Service("@opencode/LocationLifecycle"), { isClosed: () => state.closed }), Effect.provideService(Context.Service("@opencode/Config"), { entries: () => Effect.succeed([{ type: "document", info: { experimental: { schedules: state.enabled } } }]) }), + Effect.provideService(Context.Service("@opencode/Flag"), { resolve: () => ({ schedules: { enabled: state.enabled, source: "config" } }) }), Effect.provideService(Context.Service("@opencode/Session"), { remove: () => Effect.void, active: Effect.succeed(new Set()) }), Effect.provideService(Context.Service("@opencode/storage/Database"), { db: { $client: { unsafe: () => ({ withoutTransform: Effect.sync(() => state.row === undefined ? [] : [{ data: state.row }]) }) } } }), Effect.provideService(Scope.Scope, scope))) diff --git a/packages/server/src/opencode/missions/native-schedule-calendar-service.ts b/packages/server/src/opencode/missions/native-schedule-calendar-service.ts index ce70d6ad8e..8cbaf8be86 100644 --- a/packages/server/src/opencode/missions/native-schedule-calendar-service.ts +++ b/packages/server/src/opencode/missions/native-schedule-calendar-service.ts @@ -18,6 +18,7 @@ import type { MissionCalendarWhen } from "../../missions/mission-calendar-plan" import type { MissionWake } from "../../missions/mission-document" import { NATIVE_SCHEDULE_CARRIER_MODEL, NATIVE_SCHEDULE_CARRIER_TITLE } from "./native-schedule-carrier" import { NATIVE_SCHEDULE_CARRIER_MARKER, NATIVE_SCHEDULE_CARRIER_SIGNAL } from "./native-schedule-carrier-binding" +import { readNativeScheduleFlag } from "./native-schedule-flag" type NativeEffect = Effect.Effect type Target = { missionID: string; descriptor: MissionCalendarOwnerSlot } @@ -42,7 +43,7 @@ export const nativeScheduleCalendarMatches = (info: NativeScheduleCalendarInfo, info.sessionID === slot.sessionID && info.name === slot.name && canonicalAuthority(info.when) === canonicalAuthority(slot.when) && info.endsAt === slot.endsAt && info.remainingRuns === null && (slot.anchorAt === undefined || info.createdAt === slot.anchorAt) const tag = (id: string) => Context.Service(id) -const scheduleTag = tag("@opencode/Schedule"), locationTag = tag("@opencode/Location"), configTag = tag("@opencode/Config") +const scheduleTag = tag("@opencode/Schedule"), locationTag = tag("@opencode/Location") const sessionTag = tag("@opencode/Session"), databaseTag = tag("@opencode/storage/Database"), lifecycleTag = tag("@opencode/LocationLifecycle") const method = Schema.declare<(...args: any[]) => NativeEffect>((value): value is (...args: any[]) => NativeEffect => Predicate.isFunction(value)) const schedulesShape = Schema.Struct({ create: method, list: method, get: method, pause: method, resume: method, remove: method, enabled: method }) @@ -66,11 +67,10 @@ export const acquireNativeScheduleCalendarService = Effect.fn("missions.acquireS } const schedules = Schema.decodeUnknownSync(schedulesShape)(required(scheduleTag)) const location = Schema.decodeUnknownSync(Schema.toType(Schema.Struct(Location.Info.fields)))(required(locationTag)) - const config = required(configTag) as { entries(): NativeEffect } const sessions = required(sessionTag) as { remove(id: string): NativeEffect; active: NativeEffect } const database = required(databaseTag) as { db: { $client: SqlClient.SqlClient } } const lifecycle = required(lifecycleTag) as { isClosed(): boolean } - if (!Predicate.isFunction(config.entries) || !Predicate.isFunction(sessions.remove) || !Effect.isEffect(sessions.active) + if (!Predicate.isFunction(sessions.remove) || !Effect.isEffect(sessions.active) || !Predicate.isFunction(database.db?.$client?.unsafe) || !Predicate.isFunction(lifecycle.isClosed) || !carrierAgent) throw new Error("Native calendar cleanup/config contract unavailable") let active = true yield* Effect.addFinalizer(() => Effect.sync(() => { active = false })) @@ -99,10 +99,7 @@ export const acquireNativeScheduleCalendarService = Effect.fn("missions.acquireS }) const enabled = Effect.fnUntraced(function* () { assertCurrent() - const entries = yield* config.entries() - if (!Array.isArray(entries) || entries.length > 256) throw new Error("Native calendar configuration incomplete") - const latest = [...entries].reverse().find(entry => entry?.type === "document" && entry.info?.experimental !== undefined) - if (latest?.info.experimental?.schedules !== true) throw new Error("Native calendar schedules disabled") + if (!(yield* readNativeScheduleFlag(ctx)).enabled) throw new Error("Native calendar schedules disabled") assertCurrent() }) const carrier = Effect.fnUntraced(function* (target: Target) { diff --git a/packages/server/src/opencode/missions/native-schedule-flag.test.ts b/packages/server/src/opencode/missions/native-schedule-flag.test.ts new file mode 100644 index 0000000000..c91b25f772 --- /dev/null +++ b/packages/server/src/opencode/missions/native-schedule-flag.test.ts @@ -0,0 +1,34 @@ +import assert from "node:assert/strict" +import test from "node:test" +import { Context, Effect } from "effect" +import { readNativeScheduleFlag } from "./native-schedule-flag" + +test("native flag reader uses the acquired resolver and classifies only its bounded non-secret result", async () => { + const location = { directory: "/fixture", project: { id: "project", canonical: "/fixture" } } + let entries: any[] = [], state = { enabled: false, source: "default" }, closed = false + const read = () => Effect.runPromise(readNativeScheduleFlag({ location } as any).pipe( + Effect.provideService(Context.Service("@opencode/Config"), { entries: () => Effect.succeed(entries) }), + Effect.provideService(Context.Service("@opencode/Flag"), { resolve: (input: unknown) => { + assert.equal(input, entries); return { schedules: state, unrelated: { secret: "private" } } + } }), + Effect.provideService(Context.Service("@opencode/Location"), location), + Effect.provideService(Context.Service("@opencode/LocationLifecycle"), { isClosed: () => closed }), + )) + for (const enabled of [true, false]) { + state = { enabled, source: "default" } + assert.deepEqual(await read(), { enabled, provenance: "channel-default" }) + entries = [{ type: "document", info: { experimental: { schedules: !enabled } } }] + state = { enabled, source: "env" } + assert.deepEqual(await read(), { enabled, provenance: "environment" }) + state.source = "config" + assert.deepEqual(await read(), { enabled, provenance: "experimental-block" }) + } + entries = [{ type: "document", info: { experimental: { all_flags: true } } }, + { type: "document", info: { experimental: {} } }] + state = { enabled: true, source: "config" } + assert.deepEqual(await read(), { enabled: true, provenance: "all-flags" }) + state.source = "unknown"; await assert.rejects(read(), /resolution unavailable/) + state.source = "config"; entries = new Array(257).fill({ type: "directory", path: "/fixture" }) + await assert.rejects(read(), /configuration incomplete/) + entries = []; closed = true; await assert.rejects(read(), /Location retired/) +}) diff --git a/packages/server/src/opencode/missions/native-schedule-flag.ts b/packages/server/src/opencode/missions/native-schedule-flag.ts new file mode 100644 index 0000000000..aeff746b3c --- /dev/null +++ b/packages/server/src/opencode/missions/native-schedule-flag.ts @@ -0,0 +1,43 @@ +import { Context, Effect, Option } from "effect" +import type { Plugin } from "@opencode/plugin/effect" +import type { ConfigEntry } from "@opencode/client" + +export type NativeScheduleFlag = { enabled: boolean; provenance: "environment" | "experimental-block" | "all-flags" | "channel-default" } + +/** Read in the receiving Location graph, with the daemon's own overrides/channel. + * The private Flag.resolve/Config.entries shapes are checked before use. */ +export const readNativeScheduleFlag = Effect.fn("missions.readScheduleFlag")(function* (ctx: Pick) { + const graph = yield* Effect.context() + const required = (name: string) => { + const service = Context.getOption(graph, Context.Service(name)) + if (Option.isNone(service)) throw new Error("Native schedule flag contract unavailable") + return service.value + } + const config = required("@opencode/Config") as { entries(): Effect.Effect } + const flags = required("@opencode/Flag") as { resolve(entries: readonly ConfigEntry[]): Record } + const location = required("@opencode/Location") as { directory: string; workspaceID?: string; project: { id: string; canonical: string } } + const lifecycle = required("@opencode/LocationLifecycle") as { isClosed(): boolean } + const current = () => { + if (typeof lifecycle.isClosed !== "function" || lifecycle.isClosed() !== false + || location.directory !== ctx.location.directory || location.workspaceID !== ctx.location.workspaceID + || location.project?.id !== ctx.location.project.id || location.project?.canonical !== ctx.location.project.canonical) + throw new Error("Native schedule flag Location retired") + } + current() + if (typeof config.entries !== "function" || typeof flags.resolve !== "function") throw new Error("Native schedule flag contract unavailable") + const effect = config.entries() + if (!Effect.isEffect(effect)) throw new Error("Native schedule flag configuration unavailable") + const entries = yield* effect + if (!Array.isArray(entries) || entries.length > 256 || entries.some(entry => !entry + || entry.type !== "directory" && (entry.type !== "document" || !entry.info || typeof entry.info !== "object"))) + throw new Error("Native schedule flag configuration incomplete") + const state = flags.resolve(entries)?.schedules + if (!state || typeof state.enabled !== "boolean" || !["env", "config", "default"].includes(state.source)) + throw new Error("Native schedule flag resolution unavailable") + const block = [...entries].reverse().find(entry => entry.type === "document" && entry.info.experimental !== undefined) + const provenance: NativeScheduleFlag["provenance"] = state.source === "env" ? "environment" + : state.source === "default" ? "channel-default" + : block?.type === "document" && block.info.experimental?.schedules !== undefined ? "experimental-block" : "all-flags" + current() + return { enabled: state.enabled, provenance } satisfies NativeScheduleFlag +}) diff --git a/packages/server/src/opencode/native-experimental-settings.test.ts b/packages/server/src/opencode/native-experimental-settings.test.ts index 03659ae6e0..5de066ddfc 100644 --- a/packages/server/src/opencode/native-experimental-settings.test.ts +++ b/packages/server/src/opencode/native-experimental-settings.test.ts @@ -54,7 +54,7 @@ test("companion inheritance uses the block before the target, not the final proj entry("/project/.opencode/opencode.jsonc", { todo: true })] assert.deepEqual(inheritedMissionExperimental(entries, "/global/opencode.jsonc", "/project"), { schedules: true, subagent_depth: 2 }) assert.deepEqual(inheritedMissionExperimental(entries, "/project/.opencode/opencode.jsonc", "/project"), { subagent_depth: 8 }) - assert.deepEqual(effectiveMissionExperimental(entries), { origin: "/project/.opencode/opencode.jsonc" }) + assert.deepEqual(effectiveMissionExperimental(entries), { todo: true, origin: "/project/.opencode/opencode.jsonc" }) assert.deepEqual(inheritedMissionExperimental(entries.slice(0, -1), "/project/.opencode/opencode.jsonc", "/project"), { subagent_depth: 8 }) const globalWrite = editMissionExperimental(document("{}"), "schedules", true, inheritedMissionExperimental(entries, "/global/opencode.jsonc", "/project"), "global") @@ -70,6 +70,14 @@ test("companion inheritance uses the block before the target, not the final proj ], "/project/.opencode/opencode.jsonc", "/project"), {}, "POSIX case remains significant") }) +test("creating an activation block preserves all effective inherited experimental options", () => { + const inherited = { subagent_depth: 0, todo: true, background_compaction: false, all_flags: false, + image_generate: { model: "fixture/image" }, location_idle_timeout: "4 hours" } + const saved = editMissionExperimental(document('{\r\n\t// keep\r\n\t"model":"keep"\r\n}\r\n'), "schedules", true, inherited) + assert.deepEqual(value(saved), { model: "keep", experimental: { ...inherited, schedules: true } }) + assert.match(saved, /\r\n\t\/\/ keep/) +}) + test("both paths reject malformed or ambiguous parents and companion keys", () => { for (const text of ['{"experimental":false}', '{"experimental":null}', '{"experimental":{},"experimental":{}}', '{"experimental":{"schedules":true,"schedules":false}}', '{"experimental":{"subagent_depth":0,"subagent_depth":2}}', diff --git a/packages/server/src/opencode/native-experimental-settings.ts b/packages/server/src/opencode/native-experimental-settings.ts index ca8282b985..0547f50492 100644 --- a/packages/server/src/opencode/native-experimental-settings.ts +++ b/packages/server/src/opencode/native-experimental-settings.ts @@ -4,7 +4,7 @@ import type { ConfigEntry } from "@opencode/client" import { PluginControlDocumentError, type PluginControlDocument } from "./plugin-control-document" import { editNativeSetting, readNativeSetting, removeEmptyNativeObject } from "./native-setting-document" -export interface MissionExperimentalSettings { schedules?: boolean; subagent_depth?: number } +export interface MissionExperimentalSettings { [key: string]: unknown; schedules?: boolean; subagent_depth?: number } export function nativeSettingExpectation(document: PluginControlDocument): string { return createHash("sha256").update(JSON.stringify([ @@ -20,11 +20,10 @@ function settings(value: unknown): MissionExperimentalSettings { if (block.schedules !== undefined && typeof block.schedules !== "boolean" || block.subagent_depth !== undefined && (!Number.isSafeInteger(block.subagent_depth) || Number(block.subagent_depth) < 0)) throw new PluginControlDocumentError("Invalid Missions experimental setting", "invalid") - return { ...(block.schedules === undefined ? {} : { schedules: block.schedules as boolean }), - ...(block.subagent_depth === undefined ? {} : { subagent_depth: block.subagent_depth as number }) } + return { ...block } as MissionExperimentalSettings } -/** Native precedence selects one whole block. Only the two owned keys leave this reader. */ +/** Native precedence selects one whole block; authors preserve its inherited companions. */ export function effectiveMissionExperimental(entries: readonly ConfigEntry[]) { const entry = [...entries].reverse().find(entry => entry.type === "document" && entry.info.experimental !== undefined) return entry?.type === "document" @@ -78,7 +77,7 @@ export function inheritedMissionExperimental(entries: readonly ConfigEntry[], ta /** Both authors use one JSONC edit under the existing physical-file lock/byte expectation. */ export function editMissionExperimental( document: PluginControlDocument, - key: keyof MissionExperimentalSettings, + key: "schedules" | "subagent_depth", value: boolean | number | undefined, inherited: MissionExperimentalSettings, scope: "global" | "project" = "project", @@ -89,7 +88,7 @@ export function editMissionExperimental( throw new PluginControlDocumentError("OpenCode schedules are explicitly disabled in this document", "conflict") settings({ [key]: value }) let current = document - const apply = (field: keyof MissionExperimentalSettings, next: unknown) => { + const apply = (field: string, next: unknown) => { const updated = editNativeSetting(current, ["experimental", field], next) current = { ...current, text: current.byteOrderMark ? updated.slice(1) : updated } } @@ -99,9 +98,8 @@ export function editMissionExperimental( // still shadows it and needs the same companion preservation as a save. if (value !== undefined || block && Object.keys(block).some(field => field !== "subagent_depth")) apply("schedules", true) } - if (key === "schedules" && readNativeSetting(document, ["experimental"]) === undefined - && local.subagent_depth === undefined && inherited.subagent_depth !== undefined) - apply("subagent_depth", inherited.subagent_depth) + if (key === "schedules" && readNativeSetting(document, ["experimental"]) === undefined) + for (const [field, companion] of Object.entries(inherited)) if (field !== key) apply(field, companion) apply(key, value) return removeEmptyNativeObject(current, ["experimental"]) ?? `${current.byteOrderMark ? "\uFEFF" : ""}${current.text}` diff --git a/packages/server/src/opencode/native-schedule-capability.test.ts b/packages/server/src/opencode/native-schedule-capability.test.ts index a59bf907f0..28a945b24a 100644 --- a/packages/server/src/opencode/native-schedule-capability.test.ts +++ b/packages/server/src/opencode/native-schedule-capability.test.ts @@ -52,6 +52,7 @@ test("identical inline request/response structures qualify like refs, while malf test("read-only reader keeps API support, effective per-Location flag and origin separate and fences replacement", async () => { let current = true, owned = true, requests = 0, enabled = false const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("replaced") }, + client: { rpc: () => ({ scheduleFlag: async () => ({ enabled, provenance: enabled ? "experimental-block" : "channel-default" }) }) }, fetch: async (url: URL, options: RequestInit) => { requests++; assert.equal(url.pathname, "/openapi.json"); assert.equal(options.method, undefined) return Response.json(contract()) @@ -66,10 +67,29 @@ test("read-only reader keeps API support, effective per-Location flag and origin const reader = new NativeScheduleCapabilityReader(documents, { getSharedServiceConnection: async () => connection } as any) const snapshot = await reader.read("w", { directory: "/project" }) assert.deepEqual(snapshot.api, { available: true }); assert.equal(snapshot.enabled, false) - assert.equal(snapshot.origin, "/project/opencode.jsonc") + assert.equal(snapshot.origin, null) enabled = true; assert.equal((await reader.read("w", { directory: "/project" })).enabled, true) owned = false; const before = requests await assert.rejects(reader.read("w", { directory: "/other" }), /unowned/); assert.equal(requests, before) owned = true; current = false await assert.rejects(reader.read("w", { directory: "/project" }), /replaced/) }) + +test("capability trusts daemon environment, all-flags and channel defaults rather than document-only inference", async () => { + let flag = { enabled: true, provenance: "all-flags" } + const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() {}, + fetch: async () => Response.json(contract()), client: { rpc: () => ({ scheduleFlag: async () => flag }) } } + const documents: any = { readConfigDocuments: async () => ({ location: { directory: "/project" }, documents: [], entries: [ + { type: "document", path: "/global/opencode.jsonc", info: { experimental: { all_flags: true } } }, + { type: "document", path: "/project/opencode.jsonc", info: { experimental: {} } }, + ] }) } + const reader = new NativeScheduleCapabilityReader(documents, { getSharedServiceConnection: async () => connection } as any) + assert.equal((await reader.read("w", { directory: "/project" })).origin, "/global/opencode.jsonc") + for (const provenance of ["environment", "channel-default"]) for (const enabled of [true, false]) { + flag = { enabled, provenance } + const view = await reader.read("w", { directory: "/project" }) + assert.equal(view.enabled, enabled); assert.equal(view.origin, null); assert.equal(view.provenance, provenance) + } + flag = { enabled: true, provenance: "unknown" } + await assert.rejects(reader.read("w", { directory: "/project" })) +}) diff --git a/packages/server/src/opencode/native-schedule-capability.ts b/packages/server/src/opencode/native-schedule-capability.ts index 3ae270fb11..c1eb7ca938 100644 --- a/packages/server/src/opencode/native-schedule-capability.ts +++ b/packages/server/src/opencode/native-schedule-capability.ts @@ -1,7 +1,8 @@ import type { PluginControlLocation } from "../api-types" import type { WorkspaceManager } from "../workspaces/manager" import { readRuntimeContract } from "./compatibility/negotiate" -import { effectiveMissionExperimental, readMissionExperimental } from "./native-experimental-settings" +import { readMissionExperimental } from "./native-experimental-settings" +import { readNativeScheduleFlag, nativeScheduleFlagOrigin } from "./native-schedule-flag" import { PluginControlsError, type PluginControls } from "./plugin-controls" type ObjectValue = Record @@ -78,8 +79,8 @@ export class NativeScheduleCapabilityReader { for (const document of snapshot.documents) readMissionExperimental(document.document) const contract = await readRuntimeContract(connection.endpoint, connection.fetch, AbortSignal.timeout(5_000)) connection.assertCurrent() - const experimental = effectiveMissionExperimental(snapshot.entries) - return { location: snapshot.location, api: nativeScheduleCapability(contract), enabled: experimental.schedules === true, - origin: experimental.origin } + const flag = await readNativeScheduleFlag(connection, location) + return { location: snapshot.location, api: nativeScheduleCapability(contract), enabled: flag.enabled, + provenance: flag.provenance, origin: nativeScheduleFlagOrigin(snapshot.entries, flag) } } } diff --git a/packages/server/src/opencode/native-schedule-flag.ts b/packages/server/src/opencode/native-schedule-flag.ts new file mode 100644 index 0000000000..feac17d7c5 --- /dev/null +++ b/packages/server/src/opencode/native-schedule-flag.ts @@ -0,0 +1,26 @@ +import { z } from "zod" +import type { ConfigEntry } from "@opencode/client" +import type { ServiceConnection } from "../workspaces/opencode-service" +import type { PluginControlLocation } from "../api-types" +import { CODENOMAD_MISSIONS_RPC } from "../missions/rpc" +import { effectiveMissionExperimental } from "./native-experimental-settings" + +export const nativeScheduleFlagSchema = z.object({ enabled: z.boolean(), + provenance: z.enum(["environment", "experimental-block", "all-flags", "channel-default"]) }).strict() +export type NativeScheduleFlag = z.infer + +/** The daemon, rather than the desktop backend, owns environment and channel defaults. */ +export async function readNativeScheduleFlag(connection: ServiceConnection, location: PluginControlLocation) { + connection.assertCurrent() + const result = nativeScheduleFlagSchema.parse(await connection.client.rpc(CODENOMAD_MISSIONS_RPC).scheduleFlag({}, + { location, signal: AbortSignal.timeout(5_000) })) + connection.assertCurrent() + return result +} + +export function nativeScheduleFlagOrigin(entries: readonly ConfigEntry[], flag: NativeScheduleFlag): string | null { + if (flag.provenance === "experimental-block") return effectiveMissionExperimental(entries).origin + if (flag.provenance !== "all-flags") return null + const entry = [...entries].reverse().find(entry => entry.type === "document" && entry.info.experimental?.all_flags !== undefined) + return entry?.type === "document" ? entry.path ?? null : null +} diff --git a/packages/server/src/opencode/native-schedule-settings-activation.test.ts b/packages/server/src/opencode/native-schedule-settings-activation.test.ts index 589c299e5f..d327fac215 100644 --- a/packages/server/src/opencode/native-schedule-settings-activation.test.ts +++ b/packages/server/src/opencode/native-schedule-settings-activation.test.ts @@ -1,11 +1,12 @@ import assert from "node:assert/strict" +import { createHash } from "node:crypto" import { chmod, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises" import os from "node:os" import path from "node:path" import test from "node:test" import { parse } from "jsonc-parser" import { PluginControls } from "./plugin-controls" -import { editMissionExperimental, inheritedMissionExperimental } from "./native-experimental-settings" +import { editMissionExperimental, inheritedMissionExperimental, nativeSettingExpectation } from "./native-experimental-settings" import { nativeScheduleContractFixture } from "./native-schedule-capability-fixture" import { NativeScheduleSettingsActivation, type NativeScheduleActivationIntent, type NativeScheduleActivationJournal } from "./native-schedule-settings-activation" @@ -14,15 +15,26 @@ async function fixture(run: (value: any) => Promise) { const global = path.join(root, "global"), project = path.join(root, "project") await mkdir(global); await mkdir(project) const globalFile = path.join(global, "opencode.jsonc"), projectFile = path.join(project, "opencode.jsonc") - await writeFile(globalFile, '{"experimental":{"schedules":false,"subagent_depth":2}}\n') + await writeFile(globalFile, '{"experimental":{"subagent_depth":2}}\n') await writeFile(projectFile, '\uFEFF{\r\n\t// keep\r\n\t"experimental":{"subagent_depth":8,"todo":true}\r\n}\r\n') let current = true, extra: any[] = [], stale = false, selected: string | undefined, includeProject = true + let flag: { enabled: boolean; provenance: string } | undefined const entries = async () => [{ type: "document", path: globalFile, - info: stale ? { experimental: { schedules: false } } : parse(await readFile(globalFile, "utf8")) }, + info: stale ? { experimental: { subagent_depth: 2 } } : parse(await readFile(globalFile, "utf8")) }, { type: "directory", path: global }, ...(includeProject ? [{ type: "document", path: projectFile, - info: stale ? { experimental: { subagent_depth: 8 } } : parse((await readFile(projectFile, "utf8")).replace(/^\uFEFF/, "")) }] : []), ...extra] + info: stale ? { experimental: { subagent_depth: 8 } } : parse((await readFile(projectFile, "utf8")).replace(/^\uFEFF/, "")) }] + : await readFile(path.join(project, ".opencode", "opencode.jsonc"), "utf8").then(text => [{ + type: "document", path: path.join(project, ".opencode", "opencode.jsonc"), info: parse(text) }]).catch(() => [])), ...extra] const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("replaced") }, - fetch: async () => Response.json(nativeScheduleContractFixture()), client: { config: { get: entries }, plugin: { list: async () => ({ data: [] }) } } } + fetch: async () => Response.json(nativeScheduleContractFixture()), client: { config: { get: entries }, plugin: { list: async () => ({ data: [] }) }, + rpc: () => ({ scheduleFlag: async () => { + if (flag) return flag + const documents = (await entries()).filter(entry => entry.type === "document") + const block = [...documents].reverse().find(entry => entry.info.experimental !== undefined)?.info.experimental + const all = [...documents].reverse().find(entry => entry.info.experimental?.all_flags !== undefined)?.info.experimental.all_flags + return { enabled: block?.schedules ?? all === true, + provenance: block?.schedules !== undefined ? "experimental-block" : all === true ? "all-flags" : "channel-default" } + } }) } } const manager: any = { get: () => ({}), getSharedServiceConnection: async () => connection, getServiceDirectoryForPath: async (_id: string, directory: string) => directory === project ? directory : undefined, ownsLocation: async () => true, getWorktreeIdentityForPath: async () => "owned", @@ -40,7 +52,7 @@ async function fixture(run: (value: any) => Promise) { attempting: async scope => { stored.targets.find(target => target.scope === scope)!.attempted = true; await save() }, acknowledged: async (scope, digest) => { const target = stored.targets.find(target => target.scope === scope)! assert.equal(target.resultDigest, digest); target.acknowledged = true; await save() }, - ready: async origin => { assert.equal(origin, projectFile); assert.ok(stored.targets.every(target => target.acknowledged)); ready = true }, + ready: async () => { assert.ok(stored.targets.every(target => target.acknowledged)); ready = true }, } const prepare = async () => { const plan = await activation().prepare("w", location) stored = { ...plan, targets: plan.targets.map(target => ({ ...target, attempted: false, acknowledged: false })) }; await save(); return structuredClone(stored) } @@ -48,24 +60,25 @@ async function fixture(run: (value: any) => Promise) { reload: async () => JSON.parse(await readFile(journalFile, "utf8")), intent: () => stored, ready: () => ready, current: (value: boolean) => { current = value }, extra: (value: any[]) => { extra = value }, stale: (value: boolean) => { stale = value }, selected: (value: string) => { selected = value }, + flag: (value: typeof flag) => { flag = value }, missingProject: async () => { await rm(projectFile); includeProject = false } }) } finally { await chmod(globalFile, 0o600).catch(() => {}); await chmod(projectFile, 0o600).catch(() => {}); await rm(root, { recursive: true, force: true }) } } -test("two-document activation prepares both files, journals each effect and requires native effective acknowledgement", async () => fixture(async f => { +test("project-only activation journals its effect and requires native effective acknowledgement", async () => fixture(async f => { const before = await readFile(f.globalFile, "utf8") const intent = await f.prepare() assert.equal(await readFile(f.globalFile, "utf8"), before, "preparation creates no config effect") - assert.deepEqual(intent.targets.map((target: any) => target.scope), ["global", "project"]) + assert.deepEqual(intent.targets.map((target: any) => target.scope), ["project"]) await f.activation().apply("w", f.location, intent, f.journal) assert.equal(f.ready(), true) - assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).experimental, { schedules: true, subagent_depth: 2 }) + assert.equal(await readFile(f.globalFile, "utf8"), before) const project = await readFile(f.projectFile, "utf8") assert.match(project, /^\uFEFF/); assert.match(project, /\r\n\t\/\/ keep/) assert.deepEqual(parse(project.slice(1)).experimental, { subagent_depth: 8, todo: true, schedules: true }) })) -test("a read-only project refuses before the first global rename", async () => fixture(async f => { +test("a read-only project refuses before any effect", async () => fixture(async f => { await chmod(f.projectFile, 0o400) const intent = await f.prepare(), original = await readFile(f.globalFile, "utf8") await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /read-only|denied|permitted/i) @@ -74,17 +87,13 @@ test("a read-only project refuses before the first global rename", async () => f assert.equal(f.ready(), false) })) -test("a read-only global file and a newly required project target refuse the whole preparation", async () => fixture(async f => { +test("a read-only global file permits project-only activation", async () => fixture(async f => { await chmod(f.globalFile, 0o400) const intent = await f.prepare() - await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /read-only|denied|permitted/i) - await chmod(f.globalFile, 0o600) - await writeFile(f.projectFile, "{}") - const single = await f.prepare() - assert.equal(single.targets.length, 1) - await writeFile(f.projectFile, '{"experimental":{"subagent_depth":0}}') - await assert.rejects(f.activation().apply("w", f.location, single, f.journal), /targets changed/) - assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, false) + const original = await readFile(f.globalFile, "utf8") + await f.activation().apply("w", f.location, intent, f.journal) + assert.equal(f.ready(), true) + assert.equal(await readFile(f.globalFile, "utf8"), original) })) test("a concurrent depth author cannot overwrite the activation companion", { timeout: 5_000 }, async () => fixture(async f => { @@ -113,7 +122,7 @@ test("a concurrent depth author cannot overwrite the activation companion", { ti test("explicit OFF and changed targets refuse without a global side effect", async () => fixture(async f => { const intent = await f.prepare(), original = await readFile(f.globalFile, "utf8") await writeFile(f.projectFile, '{"experimental":{"schedules":false,"subagent_depth":0}}') - await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /explicitly disabled/) + await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), (error: any) => error.code === "schedule-activation-refused" && error.refusal.path === f.projectFile) assert.equal(await readFile(f.globalFile, "utf8"), original) await writeFile(f.projectFile, '{"experimental":{"subagent_depth":0}}') await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /changed/) @@ -122,8 +131,8 @@ test("explicit OFF and changed targets refuse without a global side effect", asy test("an imposed higher block is refused; a different selected host cannot reuse the same native paths", async () => fixture(async f => { const intent = await f.prepare() - f.extra([{ type: "document", info: { experimental: { subagent_depth: 4, schedules: false } } }]) - await assert.rejects(f.activation().prepare("w", f.location), /higher-priority/) + f.extra([{ type: "document", info: { experimental: { subagent_depth: 4 } } }]) + await assert.rejects(f.activation().prepare("w", f.location), (error: any) => error.refusal.reason === "masked") f.extra([]); f.selected("another-distro") await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /authority changed/) assert.equal(f.ready(), false) @@ -131,25 +140,24 @@ test("an imposed higher block is refused; a different selected host cannot reuse test("the first imposed block after an absent project insertion point refuses before any write", async () => fixture(async f => { await f.missingProject() - f.extra([{ type: "document", info: { experimental: { schedules: false } } }]) + f.extra([{ type: "document", info: { experimental: {} } }]) const original = await readFile(f.globalFile, "utf8") - await assert.rejects(f.activation().prepare("w", f.location), /higher-priority/) + await assert.rejects(f.activation().prepare("w", f.location), (error: any) => error.refusal.reason === "masked") assert.equal(await readFile(f.globalFile, "utf8"), original) await assert.rejects(readFile(path.join(f.project, ".opencode", "opencode.jsonc")), /ENOENT/) assert.equal(f.ready(), false) })) -test("lost global acknowledgement is adopted exactly after reload before the unattempted project write", async () => fixture(async f => { +test("lost project acknowledgement is adopted exactly after reload without rewriting", async () => fixture(async f => { const intent = await f.prepare() await assert.rejects(f.activation().apply("w", f.location, intent, { ...f.journal, - acknowledged: async (scope: "global" | "project", digest: string) => { if (scope === "global") throw Error("lost ACK"); await f.journal.acknowledged(scope, digest) }, + acknowledged: async () => { throw Error("lost ACK") }, }), /lost ACK/) - assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, true) - assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, undefined) + assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, undefined) + assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, true) assert.equal(f.ready(), false) const persisted = await f.reload() assert.equal(persisted.targets[0].attempted, true); assert.equal(persisted.targets[0].acknowledged, false) - assert.equal(persisted.targets[1].attempted, false) await f.activation().apply("w", f.location, persisted, f.journal) assert.equal(f.ready(), true) })) @@ -164,16 +172,92 @@ test("an uncertain attempted effect with original bytes is never resent", async assert.equal(f.ready(), false) })) -test("connection retirement after the global write preserves a partial intention without rollback", async () => fixture(async f => { +test("connection retirement after the project write preserves its intention without rollback", async () => fixture(async f => { const intent = await f.prepare() await assert.rejects(f.activation().apply("w", f.location, intent, { ...f.journal, acknowledged: async (scope: "global" | "project", digest: string) => { await f.journal.acknowledged(scope, digest); f.current(false) }, - }), /replaced|connection/) - assert.equal(parse(await readFile(f.globalFile, "utf8")).experimental.schedules, true) - assert.equal(f.intent().targets[1].attempted, false) + }), (error: any) => /replaced|connection/.test(error.message) || error.cause?.message === "replaced") + assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, true) + assert.equal(f.intent().targets[0].attempted, true) assert.equal(f.ready(), false) })) +test("already ON produces zero targets and zero file writes", async () => fixture(async f => { + await writeFile(f.projectFile, '{"experimental":{"schedules":true}}') + const original = await readFile(f.projectFile, "utf8"), global = await readFile(f.globalFile, "utf8") + const intent = await f.prepare() + assert.deepEqual(intent.targets, []) + await chmod(f.projectFile, 0o400); await chmod(f.globalFile, 0o400) + await f.activation().apply("w", f.location, intent, f.journal) + assert.equal(f.ready(), true) + await f.activation().verify("w", f.location, intent.authority) + assert.equal(await readFile(f.projectFile, "utf8"), original) + assert.equal(await readFile(f.globalFile, "utf8"), global) +})) + +for (const layer of ["global", "inherited", "project"]) test(`explicit ${layer} OFF refuses even when hidden by ON`, async () => fixture(async f => { + await writeFile(f.projectFile, '{"experimental":{"schedules":true}}') + if (layer === "global") await writeFile(f.globalFile, '{"experimental":{"schedules":false}}') + else if (layer === "project") await writeFile(f.projectFile, '{"experimental":{"schedules":false}}') + else f.extra([{ type: "document", path: path.join(f.root, "ancestor.jsonc"), info: { experimental: { schedules: false } } }, + { type: "document", info: { experimental: { schedules: true } } }]) + const before = await readFile(f.globalFile, "utf8") + await assert.rejects(f.prepare(), (error: any) => error.code === "schedule-activation-refused" && error.refusal.layer === layer) + assert.equal(await readFile(f.globalFile, "utf8"), before) +})) + +test("environment OFF refuses; channel defaults and all_flags:false permit a project activation", async () => fixture(async f => { + f.flag({ enabled: false, provenance: "environment" }) + await assert.rejects(f.prepare(), (error: any) => error.refusal.layer === "environment" && error.refusal.path === undefined) + f.flag({ enabled: false, provenance: "channel-default" }) + await writeFile(f.globalFile, '{"experimental":{"all_flags":false}}') + assert.deepEqual((await f.prepare()).targets.map((target: any) => target.scope), ["project"]) + for (const provenance of ["environment", "channel-default", "all-flags"]) { + f.flag({ enabled: true, provenance }) + assert.deepEqual((await f.prepare()).targets, []) + } +})) + +test("a global OFF appearing after preparation refuses before the project write attempt", async () => fixture(async f => { + const intent = await f.prepare(), original = await readFile(f.projectFile, "utf8") + await assert.rejects(f.activation().apply("w", f.location, intent, { ...f.journal, + prepared: async (plan: any) => { + await f.journal.prepared(plan) + await writeFile(f.globalFile, '{"experimental":{"schedules":false}}') + }, + }), (error: any) => error.code === "schedule-activation-refused") + assert.equal(await readFile(f.projectFile, "utf8"), original) + assert.equal(f.intent().targets[0].attempted, false) +})) + +test("an absent project config inherits all effective options into its new activation block", async () => fixture(async f => { + await f.missingProject() + const inherited = { subagent_depth: 0, todo: true, background_compaction: false, all_flags: false } + await writeFile(f.globalFile, JSON.stringify({ experimental: inherited })) + const intent = await f.prepare() + assert.deepEqual(intent.targets.map((target: any) => target.scope), ["project"]) + await f.activation().apply("w", f.location, intent, f.journal) + assert.deepEqual(parse(await readFile(intent.targets[0].path, "utf8")).experimental, { ...inherited, schedules: true }) +})) + +test("legacy global intentions observe attempted bytes only and never write an unattempted target", async () => fixture(async f => { + const single = await f.prepare() + const view = await f.controls.readConfigDocuments("w", f.location, undefined, true) + const global = view.documents.find((item: any) => item.scope === "global") + const updated = editMissionExperimental(global.document, "schedules", true, {}, "global") + const target = { scope: "global" as const, path: global.path, expectation: nativeSettingExpectation(global.document), + resultDigest: createHash("sha256").update(updated).digest("hex"), attempted: false, acknowledged: false } + const intent = { ...single, targets: [target, ...single.targets] } + const original = await readFile(f.globalFile, "utf8") + await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /observation/) + assert.equal(await readFile(f.globalFile, "utf8"), original) + await writeFile(f.globalFile, updated); target.attempted = true + await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /observation/) + assert.equal(parse((await readFile(f.projectFile, "utf8")).slice(1)).experimental.schedules, undefined) + target.attempted = false + await assert.rejects(f.activation().apply("w", f.location, intent, f.journal), /before this activation attempt/) +})) + test("watcher lag expires at ten seconds and can never publish readiness later", async () => fixture(async f => { const intent = await f.prepare(); f.stale(true) const started = performance.now() diff --git a/packages/server/src/opencode/native-schedule-settings-activation.ts b/packages/server/src/opencode/native-schedule-settings-activation.ts index 85712eb9e6..263cc0a012 100644 --- a/packages/server/src/opencode/native-schedule-settings-activation.ts +++ b/packages/server/src/opencode/native-schedule-settings-activation.ts @@ -3,9 +3,9 @@ import type { PluginControlLocation, PluginControlScope } from "../api-types" import type { WorkspaceManager } from "../workspaces/manager" import { readRuntimeContract } from "./compatibility/negotiate" import { encodePluginControlOriginal } from "./plugin-control-document" -import { readNativeSetting } from "./native-setting-document" -import { editMissionExperimental, effectiveMissionExperimental, inheritedMissionExperimental, +import { editMissionExperimental, inheritedMissionExperimental, nativeExperimentalTargetPosition, nativeSettingExpectation, readMissionExperimental } from "./native-experimental-settings" +import { readNativeScheduleFlag, nativeScheduleFlagOrigin, type NativeScheduleFlag } from "./native-schedule-flag" import { nativeScheduleCapability } from "./native-schedule-capability" import { PluginControlsError, type NativeConfigDocuments, type NativeConfigEdit, type PluginControls } from "./plugin-controls" @@ -22,30 +22,39 @@ export interface NativeScheduleActivationJournal { const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex") const digestPattern = /^[a-f0-9]{64}$/ +export type NativeScheduleActivationRefusal = { reason: "explicit-off" | "masked"; + provenance: NativeScheduleFlag["provenance"]; layer: "environment" | "global" | "project" | "inherited" | "imposed"; path?: string } +export class NativeScheduleActivationRefused extends PluginControlsError { + readonly code = "schedule-activation-refused" + constructor(readonly refusal: NativeScheduleActivationRefusal) { + super("Native schedule activation refused by configuration", "forbidden") + } +} + /** Plan only from acquired native discovery. Upper imposed blocks cannot be bypassed. */ -export function planNativeScheduleActivation(view: NativeConfigDocuments): NativeConfigEdit[] { - const global = view.documents.find(item => item.scope === "global") +export function planNativeScheduleActivation(view: NativeConfigDocuments, flag: NativeScheduleFlag): NativeConfigEdit[] { const project = view.documents.find(item => item.scope === "project") - if (!global) throw new PluginControlsError("Global OpenCode configuration is unavailable", "unavailable") - const local = project && readMissionExperimental(project.document) - if (local?.schedules === false) throw new PluginControlsError("Project schedules are explicitly disabled", "forbidden") - const effective = effectiveMissionExperimental(view.entries) - const target = project ?? global - const position = nativeExperimentalTargetPosition(view.entries, target.path, view.location.directory) - const imposed = view.entries.slice(position.after).some(entry => entry.type === "document" && entry.info.experimental !== undefined) - if (imposed && effective.schedules !== true) - throw new PluginControlsError("A higher-priority OpenCode configuration prevents schedule activation", "forbidden") - const edits: NativeConfigEdit[] = [] - const add = (item: typeof global, scope: PluginControlScope) => { - const updated = editMissionExperimental(item.document, "schedules", true, - inheritedMissionExperimental(view.entries, item.path, view.location.directory), scope) - edits.push({ scope, path: item.path, expectation: nativeSettingExpectation(item.document), updated }) + const refuse = (path: string | undefined, reason: NativeScheduleActivationRefusal["reason"] = "explicit-off"): never => { + const scope = view.documents.find(item => item.path === path)?.scope + throw new NativeScheduleActivationRefused({ reason, provenance: "experimental-block", + layer: reason === "masked" ? "imposed" : scope ?? (path ? "inherited" : "imposed"), ...(path ? { path } : {}) }) } - if (readMissionExperimental(global.document).schedules !== true) add(global, "global") - const block = project && readNativeSetting(project.document, ["experimental"]) - if (project && !imposed && local?.schedules !== true && (block !== undefined || effective.origin !== null && effective.origin !== global.path)) - add(project, "project") - return edits + // Inspect every discovered layer, including OFF hidden by a higher ON; the + // owned raw documents also fence native watcher lag before a write. + for (const entry of view.entries) + if (entry.type === "document" && entry.info.experimental?.schedules === false) refuse(entry.path) + for (const item of view.documents) + if (readMissionExperimental(item.document).schedules === false) refuse(item.path) + if (!flag.enabled && flag.provenance === "environment") + throw new NativeScheduleActivationRefused({ reason: "explicit-off", provenance: "environment", layer: "environment" }) + if (flag.enabled) return [] + if (!project) throw new PluginControlsError("Project OpenCode configuration is unavailable", "unavailable") + const position = nativeExperimentalTargetPosition(view.entries, project.path, view.location.directory) + const imposed = view.entries.slice(position.after).find(entry => entry.type === "document" && entry.info.experimental !== undefined) + if (imposed?.type === "document") refuse(imposed.path, "masked") + const updated = editMissionExperimental(project.document, "schedules", true, + inheritedMissionExperimental(view.entries, project.path, view.location.directory)) + return [{ scope: "project", path: project.path, expectation: nativeSettingExpectation(project.document), updated }] } /** Authenticated Play preparation owns the durable journal callbacks. This executor @@ -66,29 +75,40 @@ export class NativeScheduleSettingsActivation { const contract = await readRuntimeContract(connection.endpoint, connection.fetch, AbortSignal.timeout(5_000)) connection.assertCurrent() if (!nativeScheduleCapability(contract).available) throw new PluginControlsError("Native schedule API is unavailable", "unavailable") - return { view, connection } + const flag = await readNativeScheduleFlag(connection, location) + return { view, connection, flag } } async prepare(workspaceID: string, location: PluginControlLocation): Promise { - const { view } = await this.context(workspaceID, location) - return { authority: this.authority(workspaceID, view), targets: planNativeScheduleActivation(view).map(item => ({ + const { view, flag } = await this.context(workspaceID, location) + return { authority: this.authority(workspaceID, view), targets: planNativeScheduleActivation(view, flag).map(item => ({ scope: item.scope, path: item.path, expectation: item.expectation, resultDigest: hash(item.updated), })) } } + async verify(workspaceID: string, location: PluginControlLocation, authority: string): Promise { + const { view, flag } = await this.context(workspaceID, location) + if (this.authority(workspaceID, view) !== authority) + throw new PluginControlsError("OpenCode configuration authority changed", "conflict") + planNativeScheduleActivation(view, flag) + if (!flag.enabled) throw new PluginControlsError("Native schedule activation is not effective", "conflict") + } async apply(workspaceID: string, location: PluginControlLocation, intent: NativeScheduleActivationIntent, journal: NativeScheduleActivationJournal): Promise { if (!digestPattern.test(intent.authority) || intent.targets.length > 2 || new Set(intent.targets.map(item => item.scope)).size !== intent.targets.length || intent.targets.some(item => !["global", "project"].includes(item.scope) || !digestPattern.test(item.expectation) || !digestPattern.test(item.resultDigest) || typeof item.attempted !== "boolean" || typeof item.acknowledged !== "boolean")) throw new PluginControlsError("Invalid native schedule activation intent", "invalid") - const { connection } = await this.context(workspaceID, location) + const { connection, flag } = await this.context(workspaceID, location) + // Two-target persisted intentions keep their exact identity and digests; + // reconciliation observes effects already attempted and never resumes writes. + const legacy = intent.targets.some(target => target.scope === "global") const acknowledged: NativeScheduleActivationTarget[] = [] await this.documents.editConfigDocuments(workspaceID, location, view => { connection.assertCurrent() if (this.authority(workspaceID, view) !== intent.authority) throw new PluginControlsError("OpenCode configuration authority changed", "conflict") // Recheck OFF and imposed layers before any preparation/rename, even on replay. - const required = planNativeScheduleActivation(view) - if (required.some(edit => !intent.targets.some(target => target.scope === edit.scope && target.path === edit.path))) + const required = planNativeScheduleActivation(view, flag) + if (!legacy && required.some(edit => !intent.targets.some(target => target.scope === edit.scope && target.path === edit.path))) throw new PluginControlsError("OpenCode activation targets changed; refresh before saving", "conflict") return intent.targets.flatMap(target => { const actual = view.documents.find(item => item.scope === target.scope && item.path === target.path) @@ -101,6 +121,8 @@ export class NativeScheduleSettingsActivation { } if (target.attempted || target.acknowledged) throw new PluginControlsError("Native schedule configuration effect is uncertain", "conflict") + if (legacy) + throw new PluginControlsError("Original native schedule activation requires observation of its attempted effects", "conflict") if (nativeSettingExpectation(actual.document) !== target.expectation) throw new PluginControlsError("OpenCode configuration changed; activation remains paused", "conflict") const updated = editMissionExperimental(actual.document, "schedules", true, @@ -117,6 +139,14 @@ export class NativeScheduleSettingsActivation { }, beforeCommit: async edit => { connection.assertCurrent() + const fresh = await this.context(workspaceID, location) + connection.assertCurrent() + if (this.authority(workspaceID, fresh.view) !== intent.authority) + throw new PluginControlsError("OpenCode configuration authority changed", "conflict") + const required = planNativeScheduleActivation(fresh.view, fresh.flag) + if (!required.some(target => target.path === edit.path && target.scope === edit.scope + && target.expectation === edit.expectation && hash(target.updated) === hash(edit.updated))) + throw new PluginControlsError("OpenCode configuration changed before activation", "conflict") await journal.attempting(edit.scope, hash(edit.updated)) }, afterWrite: async edit => { @@ -139,11 +169,10 @@ export class NativeScheduleSettingsActivation { const view = await this.documents.readConfigDocuments(workspaceID, location, undefined, true) connection.assertCurrent(); controller.signal.throwIfAborted() if (this.authority(workspaceID, view) !== intent.authority) throw new PluginControlsError("OpenCode configuration authority changed", "conflict") - planNativeScheduleActivation(view) - const global = view.documents.find(item => item.scope === "global")! - const nativeGlobal = [...view.entries].reverse().find(entry => entry.type === "document" && entry.path === global.path && entry.info.experimental !== undefined) - const effective = effectiveMissionExperimental(view.entries) - if (nativeGlobal?.type === "document" && nativeGlobal.info.experimental?.schedules === true && effective.schedules === true) return effective.origin + const effective = await readNativeScheduleFlag(connection, location) + controller.signal.throwIfAborted() + planNativeScheduleActivation(view, effective) + if (effective.enabled) return nativeScheduleFlagOrigin(view.entries, effective) await new Promise(resolve => setTimeout(resolve, 100)) controller.signal.throwIfAborted() } diff --git a/packages/server/src/opencode/plugin-control-document.test.ts b/packages/server/src/opencode/plugin-control-document.test.ts index 1461519d65..d364d74bc1 100644 --- a/packages/server/src/opencode/plugin-control-document.test.ts +++ b/packages/server/src/opencode/plugin-control-document.test.ts @@ -9,6 +9,7 @@ import { PluginControlDocumentError, readPluginControlDocument, replacePluginControlDocument, + replacePluginControlRules, } from "./plugin-control-document" const temporaryDirectories = new Set() @@ -97,6 +98,38 @@ describe("plugin control JSONC document", () => { assert.deepEqual((parse(text.slice(1)) as any).plugins, ["acme", "-acme"]) }) + it("replaces earlier exact rules while keeping comments, other entries, BOM, CRLF and tabs", async () => { + const target = temporaryFile() + const original = `{\r\n\t// kept comment\r\n\t"plugins": [\r\n\t\t{ "package": "@acme/reviewer", "options": { "a": 1 } },\r\n` + + `\t\t"-acme.reviewer", // first toggle\r\n\t\t"other",\r\n\t\t"acme.reviewer",\r\n\t],\r\n\t"theme": "dark",\r\n}\r\n` + fs.writeFileSync(target, original, "utf8") + const document = await readPluginControlDocument(target) + + await replacePluginControlDocument(document, replacePluginControlRules(document, [1, 3], new Set(["acme.reviewer", "-acme.reviewer"]), "-acme.reviewer")) + + const written = fs.readFileSync(target) + assert.deepEqual([...written.subarray(0, 3)], [0xef, 0xbb, 0xbf]) + const text = written.toString("utf8") + assert.equal(text.replaceAll("\r\n", "").includes("\n"), false) + assert.match(text, /\/\/ kept comment/) + assert.match(text, /\r\n\t\t"-acme\.reviewer"/) + assert.deepEqual(parse(text.slice(1)), { plugins: [{ package: "@acme/reviewer", options: { a: 1 } }, "other", "-acme.reviewer"], theme: "dark" }) + + const removedOnly = await readPluginControlDocument(target) + assert.deepEqual((parse(replacePluginControlRules(removedOnly, [2], new Set(["-acme.reviewer"])).slice(1)) as any).plugins, + [{ package: "@acme/reviewer", options: { a: 1 } }, "other"]) + }) + + it("refuses to remove an entry that is no longer the expected rule", async () => { + const target = temporaryFile() + fs.writeFileSync(target, `{ "plugins": ["other", { "package": "acme.reviewer" }] }\n`) + const document = await readPluginControlDocument(target) + for (const index of [0, 1, 5]) { + assert.throws(() => replacePluginControlRules(document, [index], new Set(["acme.reviewer", "-acme.reviewer"]), "-acme.reviewer"), + (error: unknown) => error instanceof PluginControlDocumentError && error.kind === "conflict") + } + }) + it("never reads a configuration document beyond the 4 MiB limit", async () => { const target = temporaryFile() fs.writeFileSync(target, Buffer.alloc(4 * 1024 * 1024 + 1, 0x20)) diff --git a/packages/server/src/opencode/plugin-control-document.ts b/packages/server/src/opencode/plugin-control-document.ts index 81c3e056e3..0d0fd4001d 100644 --- a/packages/server/src/opencode/plugin-control-document.ts +++ b/packages/server/src/opencode/plugin-control-document.ts @@ -2,6 +2,7 @@ import { randomBytes } from "node:crypto" import { constants } from "node:fs" import { access, chmod, lstat, mkdir, open, readFile, readlink, realpath, rename, rm, writeFile } from "node:fs/promises" import path from "node:path" +import { isDeepStrictEqual } from "node:util" import { applyEdits, modify, parse, parseTree, type FormattingOptions, type Node as JsonNode, type ParseError } from "jsonc-parser" export const PLUGIN_CONTROL_MAX_CONFIG_BYTES = 4 * 1024 * 1024 @@ -107,6 +108,50 @@ export function appendPluginControlRule(document: PluginControlDocument, rule: s return document.byteOrderMark ? `\uFEFF${updated}` : updated } +/** + * Deletes the string entries at `removeIndexes`, which must still read `expected`, then appends `rule` when given. + * The result must parse to the original document with exactly those changes to `plugins`; comments, other entries, + * line endings and the BOM stay untouched. + */ +export function replacePluginControlRules( + document: PluginControlDocument, + removeIndexes: readonly number[], + expected: ReadonlySet, + rule?: string, +): string { + const removed = [...new Set(removeIndexes)].sort((left, right) => right - left) + if (removed.length === 0) { + if (rule === undefined) throw new PluginControlDocumentError("OpenCode plugins edit is empty", "invalid") + return appendPluginControlRule(document, rule) + } + for (const index of removed) { + const entry = document.plugins[index] + if (!Number.isSafeInteger(index) || typeof entry !== "string" || !expected.has(entry)) { + throw new PluginControlDocumentError("OpenCode plugin entry changed since it was read", "conflict") + } + } + const formattingOptions = inferPluginControlFormatting(document.text) + let updated = document.text + try { + for (const index of removed) updated = applyEdits(updated, modify(updated, ["plugins", index], undefined, { formattingOptions })) + if (rule !== undefined) { + updated = applyEdits(updated, modify(updated, ["plugins", document.plugins.length - removed.length], rule, { formattingOptions })) + } + } catch (error) { + throw new PluginControlDocumentError("Unable to update OpenCode plugins without replacing the document", "invalid", { cause: error }) + } + const original = parse(document.text, [], { allowTrailingComma: true }) as Record + const plugins = (original.plugins as unknown[]).filter((_, at) => !removed.includes(at)) + const target = { ...original, plugins: rule === undefined ? plugins : [...plugins, rule] } + const errors: ParseError[] = [] + const result = parse(updated, errors, { allowTrailingComma: true }) + if (errors.length || !isDeepStrictEqual(result, target)) { + throw new PluginControlDocumentError("Unable to update OpenCode plugins without changing other settings", "invalid") + } + if (!updated.endsWith("\n")) updated += formattingOptions.eol + return document.byteOrderMark ? `${updated}` : updated +} + export async function replacePluginControlDocument( document: PluginControlDocument, updated: string, diff --git a/packages/server/src/opencode/plugin-controls.test.ts b/packages/server/src/opencode/plugin-controls.test.ts index 35f8123d76..c3eb277848 100644 --- a/packages/server/src/opencode/plugin-controls.test.ts +++ b/packages/server/src/opencode/plugin-controls.test.ts @@ -152,7 +152,7 @@ describe("OpenCode V2 plugin activation controls", () => { assert.equal(linter.snapshot.controls.find((entry) => entry.id === "acme.linter")?.project, "disabled") }) - it("serializes same-target mutations while letting other scopes proceed", async () => { + it("serializes same-target mutations while letting other scopes proceed", { timeout: 5_000 }, async () => { const fixture = createFixture({ globalPlugins: [{ package: "@acme/reviewer", options: { strict: true } }], projectPlugins: [], @@ -161,30 +161,39 @@ describe("OpenCode V2 plugin activation controls", () => { const manager = (fixture.controls as any).options.workspaceManager const innerIdentity = manager.getWorktreeIdentityForPath.bind(manager) const gate = deferred() + const globalEntered = deferred() let identityCalls = 0 - let projectSettled = false manager.getWorktreeIdentityForPath = async (...args: [string, string]) => { identityCalls += 1 - // The first mutation (global scope) is held here; a per-target queue - // lets the project-scope mutation overtake it instead of blocking. - if (identityCalls === 1) await gate.promise + if (identityCalls === 1) { + globalEntered.resolve() + await gate.promise + } return innerIdentity(...args) } const global = fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "acme.reviewer", scope: "global", enabled: false }) + // Discovery includes filesystem IO: invocation order cannot identify which + // scope reaches the fence first. Admit Global before launching its siblings. + await globalEntered.promise + const nextGlobal = fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "acme.reviewer", scope: "global", enabled: true }) const project = fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "acme.reviewer", scope: "project", enabled: false }) - void project.then(() => { projectSettled = true }) - const deadline = Date.now() + 5_000 - while (!projectSettled && Date.now() < deadline) await tick() - assert.equal(projectSettled, true) - gate.resolve() - const [globalResponse, projectResponse] = await Promise.all([global, project]) + let projectResponse: Awaited + try { + projectResponse = await project + assert.equal(identityCalls, 2, "the second Global mutation stays queued while Project completes") + } finally { + gate.resolve() + await Promise.allSettled([global, nextGlobal, project]) + } + const [globalResponse, nextGlobalResponse] = await Promise.all([global, nextGlobal]) assert.equal(globalResponse.changed, true) + assert.equal(nextGlobalResponse.changed, true) assert.equal(projectResponse.changed, true) + // Re-enabling removes the disabling rule the first mutation wrote instead of appending another one. assert.deepEqual((parse(fs.readFileSync(fixture.globalFile, "utf8")) as any).plugins, [ { package: "@acme/reviewer", options: { strict: true } }, - "-acme.reviewer", ]) assert.deepEqual((parse(fs.readFileSync(fixture.projectFile, "utf8")) as any).plugins, ["-acme.reviewer"]) }) @@ -225,6 +234,65 @@ describe("OpenCode V2 plugin activation controls", () => { assert.deepEqual((parse(fs.readFileSync(fixture.projectFile, "utf8")) as any).plugins, ["-acme.reviewer", "acme.reviewer"]) }) + it("replaces the plugin's earlier exact rules instead of growing the file on each toggle", async () => { + const source = { package: "@neuralnomads/opencode-blender", options: {} } + const fixture = createFixture({ + globalPlugins: [source, "-neuralnomads.blender", "neuralnomads.blender", "-neuralnomads.blender", "neuralnomads.blender", "ponytail"], + runtime: [activePlugin("neuralnomads.blender", "@neuralnomads/opencode-blender"), activePlugin("ponytail", "ponytail")], + }) + const plugins = () => (parse(fs.readFileSync(fixture.globalFile, "utf8")) as any).plugins + const toggle = async (enabled: boolean) => { + const response = await fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "neuralnomads.blender", scope: "global", enabled }) + fixture.setGlobalPlugins(plugins()) + return response + } + + const disabled = await toggle(false) + assert.deepEqual(plugins(), [source, "ponytail", "-neuralnomads.blender"]) + assert.equal(disabled.snapshot.controls.find(entry => entry.id === "neuralnomads.blender")?.effective, "disabled") + const enabled = await toggle(true) + assert.deepEqual(plugins(), [source, "ponytail"], "re-enabling removes the disabling rule; no lone positive ID is left") + assert.notEqual(enabled.snapshot.controls.find(entry => entry.id === "neuralnomads.blender")?.effective, "disabled") + for (let round = 0; round < 3; round += 1) { await toggle(false); await toggle(true) } + assert.deepEqual(plugins(), [source, "ponytail"], "repeated toggles never grow the file") + assert.equal(fs.readFileSync(fixture.globalFile, "utf8").includes('"neuralnomads.blender"'), false) + }) + + it("keeps broad selectors and appends when removing alone would change the effective state", async () => { + const source = { package: "@acme/reviewer" } + const fixture = createFixture({ globalPlugins: [source, "-acme.*"], runtime: [activePlugin("acme.reviewer", "@acme/reviewer")] }) + const plugins = () => (parse(fs.readFileSync(fixture.globalFile, "utf8")) as any).plugins + const enable = await fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "acme.reviewer", scope: "global", enabled: true }) + assert.deepEqual(plugins(), [source, "-acme.*", "acme.reviewer"], "a later exact rule is needed past the prefix rule") + assert.equal(enable.snapshot.controls.find(entry => entry.id === "acme.reviewer")?.effective, "enabled") + fixture.setGlobalPlugins(plugins()) + const disable = await fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "acme.reviewer", scope: "global", enabled: false }) + assert.deepEqual(plugins(), [source, "-acme.*"], "the prefix rule already disables it: the exact rule is only removed") + assert.equal(disable.snapshot.controls.find(entry => entry.id === "acme.reviewer")?.effective, "disabled") + }) + + it("edits only the target file, keeping the state another scope gives", async () => { + const fixture = createFixture({ + globalPlugins: [{ package: "@acme/reviewer" }, "-acme.reviewer"], + projectPlugins: ["acme.reviewer", "-acme.reviewer", "acme.reviewer"], + runtime: [activePlugin("acme.reviewer", "@acme/reviewer")], + }) + const response = await fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "acme.reviewer", scope: "project", enabled: false }) + assert.deepEqual((parse(fs.readFileSync(fixture.projectFile, "utf8")) as any).plugins, [], "Global already disables it") + assert.deepEqual((parse(fs.readFileSync(fixture.globalFile, "utf8")) as any).plugins, [{ package: "@acme/reviewer" }, "-acme.reviewer"]) + const control = response.snapshot.controls.find(entry => entry.id === "acme.reviewer")! + assert.equal(control.effective, "disabled") + assert.equal(control.global, "disabled") + }) + + it("never removes a source declaration named like its plugin ID", async () => { + const fixture = createFixture({ globalPlugins: ["same.id", "-same.id"], runtime: [activePlugin("same.id", "same.id")] }) + const response = await fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "same.id", scope: "global", enabled: true }) + assert.deepEqual((parse(fs.readFileSync(fixture.globalFile, "utf8")) as any).plugins, ["same.id"]) + assert.deepEqual(response.snapshot.configured.sources.map(entry => entry.target), ["same.id"]) + assert.notEqual(response.snapshot.controls.find(entry => entry.id === "same.id")?.effective, "disabled") + }) + it("uses daemon-reported roots and host translation instead of process configuration", async () => { const host = temporaryDirectory() const globalHost = path.join(host, "daemon-global") @@ -801,6 +869,24 @@ describe("CodeNomad-managed plugin provenance and recovery", () => { }) }) +describe("CodeNomad-managed plugin re-enable with an exact disabling rule", () => { + it("removes the exact disabling rule instead of appending a positive ID", async () => { + for (const scope of ["global", "project"] as const) { + const fixture = createFixture({ + globalPlugins: scope === "global" ? ["-codenomad.automation"] : [], + projectPlugins: scope === "project" ? ["-codenomad.automation"] : [], + }) + await installManaged(fixture, "automation", "codenomad.automation") + const response = await fixture.controls.mutate("workspace", { location: fixture.location, pluginId: "codenomad.automation", scope, enabled: true }) + const control = response.snapshot.controls.find(entry => entry.id === "codenomad.automation")! + assert.equal(response.changed, true) + assert.equal(control.managedBy, "codenomad") + assert.notEqual(control.effective, "disabled") + assert.deepEqual((parse(fs.readFileSync(scope === "global" ? fixture.globalFile : fixture.projectFile, "utf8")) as any).plugins, []) + } + }) +}) + async function installManaged(fixture: ReturnType, feature: DesktopPluginFeature, id: string) { const stop = await installDesktopPluginPresence(feature, Buffer.from(`// CodeNomad plugin IDs: ${JSON.stringify([id])}\nexport const desktopPlugin = () => {}\n`), { config: fixture.globalDirectory, data: path.join(path.dirname(fixture.globalDirectory), "managed-data"), @@ -929,7 +1015,3 @@ function deferred(): { promise: Promise; resolve: (value: T | Promi const promise = new Promise((accept) => { resolve = accept }) return { promise, resolve } } - -function tick(): Promise { - return new Promise((resolve) => setImmediate(resolve)) -} diff --git a/packages/server/src/opencode/plugin-controls.ts b/packages/server/src/opencode/plugin-controls.ts index 2607fe782d..a13de52e7d 100644 --- a/packages/server/src/opencode/plugin-controls.ts +++ b/packages/server/src/opencode/plugin-controls.ts @@ -23,10 +23,10 @@ import type { WorkspaceManager } from "../workspaces/manager" import type { ServiceConnection } from "../workspaces/opencode-service" import { locationRequestOptions } from "./compatibility/location" import { - appendPluginControlRule, hostPluginControlDocumentFileSystem, readPluginControlDocument, replacePluginControlDocument, + replacePluginControlRules, type PluginConfigEntry, type PluginControlDocument, type PluginControlDocumentFileSystem, @@ -298,7 +298,25 @@ export class PluginControls { } const rule = request.enabled ? request.pluginId : `-${request.pluginId}` - const updated = appendPluginControlRule(document, rule) + const overlay = (plugins: readonly PluginConfigEntry[]) => controlsForDocuments(base, context, { + servicePath: target.path, + plugins, + scope: request.scope, + }) + // The state appending the rule would produce is the contract; a smaller edit must reproduce it exactly. + const appended = overlay([...projection.plugins, rule]) + const removable = projection.noOpSafe + ? replaceableRuleIndexes(document.plugins, projection.plugins, before, target.path, request.scope, request.pluginId, context.paths) : [] + const kept = projection.plugins.filter((_, index) => !removable.includes(index)) + // Prefer removing the earlier rules alone (re-enabling a plugin active without them), then replacing them. + let edit: { remove: number[]; rule?: string; snapshot: PluginControlsSnapshot } = { remove: [], rule, snapshot: appended } + if (removable.length > 0) { + for (const candidate of [{ remove: removable }, { remove: removable, rule }]) { + const snapshot = overlay(candidate.rule === undefined ? kept : [...kept, candidate.rule]) + if (sameActivation(snapshot, appended)) { edit = { ...candidate, snapshot }; break } + } + } + const updated = replacePluginControlRules(document, edit.remove, new Set([request.pluginId, `-${request.pluginId}`]), edit.rule) try { await replacePluginControlDocument(document, updated, { beforeCommit: () => assertCurrentConnection(context.connection), @@ -307,13 +325,9 @@ export class PluginControls { throw mapDocumentError(error) } target.exists = true - const snapshot = controlsForDocuments(base, context, { - servicePath: target.path, - plugins: [...projection.plugins, rule], - scope: request.scope, - }) - this.options.logger.info({ workspaceId, scope: request.scope, pluginId: request.pluginId }, "Updated OpenCode plugin activation rule") - return { snapshot, rule, target: publicTarget(target), changed: true, reloadPending: true } + this.options.logger.info({ workspaceId, scope: request.scope, pluginId: request.pluginId, removed: edit.remove.length, + appended: edit.rule !== undefined }, "Updated OpenCode plugin activation rule") + return { snapshot: edit.snapshot, rule, target: publicTarget(target), changed: true, reloadPending: true } } finally { release() } @@ -632,6 +646,44 @@ function mutationTargetPlugins( return { plugins: [...normalized, ...pendingRules], noOpSafe: noOpSafe && normalizedIndex === normalized.length } } +/** + * Entries of the target document that are exact `id`/`-id` activation rules for `pluginId`, safe to delete: the raw + * document must equal the daemon's projection entry by entry (callers also require a no-op-safe projection, so + * placeholders and watcher lag keep the plain append), and an entry the snapshot + * reads as a source declaration (a package named like its ID) is never a rule. + */ +function replaceableRuleIndexes( + rawPlugins: readonly PluginConfigEntry[], + projected: readonly PluginConfigEntry[], + snapshot: PluginControlsSnapshot, + servicePath: string, + scope: PluginControlScope, + pluginId: string, + paths: path.PlatformPath, +): number[] { + if (rawPlugins.length !== projected.length) return [] + if (rawPlugins.some((entry, index) => !pluginEntriesEqual(entry, projected[index]))) return [] + const sources = new Set(snapshot.configured.sources + .filter(source => source.scope === scope && source.path && samePath(paths, source.path, servicePath)) + .map(source => source.entryIndex)) + return rawPlugins.flatMap((entry, index) => + (entry === pluginId || entry === `-${pluginId}`) && projected[index] === entry && !sources.has(index) ? [index] : []) +} + +/** What a user and OpenCode observe: every control's effective state, its displayed switches, and the sources. */ +function sameActivation(left: PluginControlsSnapshot, right: PluginControlsSnapshot): boolean { + const checked = (control: PluginActivationControl, scope: PluginControlScope): boolean => { + const state = control[scope] + if (state !== "default") return state === "enabled" + return scope === "project" ? checked(control, "global") : true + } + const view = (snapshot: PluginControlsSnapshot) => JSON.stringify([ + snapshot.controls.map(control => [control.id, control.effective === "disabled" ? "disabled" : "enabled", control.managedBy ?? "", checked(control, "global"), checked(control, "project")]), + snapshot.configured.sources.map(source => [source.scope, source.path ?? "", source.target, source.pluginId ?? "", source.managedBy ?? ""]).sort(), + ]) + return view(left) === view(right) +} + function pluginEntriesEqual(left: PluginConfigEntry, right: PluginConfigEntry | undefined): boolean { if (typeof left !== typeof right) return false if (typeof left === "string" || typeof right === "string") return left === right diff --git a/packages/server/src/opencode/plugin-sources.test.ts b/packages/server/src/opencode/plugin-sources.test.ts index 577769b313..72e0bc7ae2 100644 --- a/packages/server/src/opencode/plugin-sources.test.ts +++ b/packages/server/src/opencode/plugin-sources.test.ts @@ -4,6 +4,7 @@ import os from "node:os" import path from "node:path" import { describe, it } from "node:test" import { pathToFileURL } from "node:url" +import { setImmediate as nextTurn } from "node:timers/promises" import Fastify from "fastify" import { parse } from "jsonc-parser" import { PluginControls } from "./plugin-controls" @@ -21,13 +22,16 @@ async function fixture(options: { sameScopes?: boolean; catalog?: IntegrationCat const globalFile = path.join(global, "opencode.jsonc") const projectFile = path.join(project, ".opencode", "opencode.jsonc") const state = { runtime: [] as unknown[], hideProject: false, current: true, gate: undefined as Promise | undefined, normalized: undefined as unknown, - rpcOutput: undefined as unknown, rpcError: undefined as unknown, rpcCalls: [] as string[] } + rpcOutput: undefined as unknown, rpcError: undefined as unknown, rpcCalls: [] as string[], + onConfigRead: undefined as (() => void) | undefined } const documentEntry = async (file: string) => readFile(file, "utf8").then(text => [{ type: "document", path: file, info: state.normalized ?? parse(text) }], () => []) const connection: any = { assertCurrent: () => { if (!state.current) throw new Error("replaced connection") }, client: { config: { get: async () => { - await state.gate + const gate = state.gate + state.onConfigRead?.() + await gate return [{ type: "directory", path: global }, ...await documentEntry(globalFile), ...(options.sameScopes || state.hideProject ? [] : await documentEntry(projectFile))] } }, @@ -144,23 +148,35 @@ describe("plugin source mutations", () => { } finally { await f.cleanup() } }) - it("refuses an add whose OpenCode reads stall, releases the queue, and never writes it later", async () => { + it("refuses an add whose OpenCode reads stall, releases the queue, and never writes it later", async t => { const f = await fixture() try { await writeFile(f.globalFile, "{}") + t.mock.timers.enable({ apis: ["setTimeout"] }) // This fake client ignores the abort signal: the grace period still releases the queue. const sources = new PluginSources({ documents: f.controls, logger: { info() {} } as any, addTimeoutMs: 500, abortGraceMs: 50 }) - let release!: () => void + let release!: () => void, enter!: () => void, reads = 0 + const admitted = new Promise(resolve => { enter = resolve }) + f.state.onConfigRead = () => { if (++reads === 2) enter() } + const pendingReads: Promise[] = [] + const track = (pending: Promise) => { pendingReads.push(pending); return pending } + const read = f.controls.read.bind(f.controls), readDocuments = f.controls.readConfigDocuments.bind(f.controls) + t.mock.method(f.controls, "read", (...args: Parameters) => track(read(...args))) + t.mock.method(f.controls, "readConfigDocuments", (...args: Parameters) => track(readDocuments(...args))) f.state.gate = new Promise(resolve => { release = resolve }) const stalled = sources.add("w", { location: f.location, scope: "global", spec: "stalled-plugin" }) - // Let the queued turn start its daemon reads before later reads stop stalling. - await new Promise(resolve => setTimeout(resolve, 10)) + const refused = assert.rejects(stalled, code("timeout", "unavailable")) + // Both parallel reads must hold the old gate before the next turn can proceed. + await admitted f.state.gate = undefined const next = sources.add("w2", { location: f.location, scope: "global", spec: "next-plugin" }) - await assert.rejects(stalled, code("timeout", "unavailable")) + t.mock.timers.tick(500) + t.mock.timers.tick(50) + await refused await next release() - await new Promise(resolve => setTimeout(resolve, 50)) + await Promise.allSettled(pendingReads) + await nextTurn() assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).plugins, ["next-plugin"], "the abandoned add never writes") } finally { await f.cleanup() } }) diff --git a/packages/server/src/opencode/runtime-support.test.ts b/packages/server/src/opencode/runtime-support.test.ts index 09f6a2e838..2b9bcc0641 100644 --- a/packages/server/src/opencode/runtime-support.test.ts +++ b/packages/server/src/opencode/runtime-support.test.ts @@ -6,16 +6,16 @@ import { rememberRuntime } from "./compatibility/runtime" import { OpenCodeSharedService } from "../workspaces/opencode-service" test("native plugin runtime minimum does not become an allowlist of tested labels", () => { - assert.equal(MINIMUM_OPENCODE_VERSION, "2.2.3") - assert.equal(RECOMMENDED_OPENCODE_VERSION, "2.2.7") - for (const version of ["2.2.3", "2.2.3+custom", "2.2.4", "2.2.5", "2.2.6", "2.2.7", "2.3.0", "2.2.0-dev.1", "3.0.0", "custom-build"]) { + assert.equal(MINIMUM_OPENCODE_VERSION, "2.3.0") + assert.equal(RECOMMENDED_OPENCODE_VERSION, "2.3.0") + for (const version of ["2.3.0", "2.3.0+custom", "2.3.1", "2.4.0", "2.2.0-dev.1", "3.0.0", "custom-build"]) { assert.equal(isBelowOpenCodeMinimum(version), false, version) } - for (const version of ["2.0.0", "2.0.32", "2.1.0", "2.1.2", "2.1.4", "2.2.0", "2.2.1", "2.2.2", "2.2.2+custom", "0.0.0-beta-19507"]) assert.equal(isBelowOpenCodeMinimum(version), true, version) + for (const version of ["2.0.0", "2.0.32", "2.1.4", "2.2.0", "2.2.2", "2.2.3", "2.2.7", "2.2.7+custom", "0.0.0-beta-19507"]) assert.equal(isBelowOpenCodeMinimum(version), true, version) }) test("refuses old authenticated daemons before client calls or plugin preparation", async () => { - for (const version of ["2.0.32", "2.1.2", "2.2.1", "2.2.2"]) { + for (const version of ["2.0.32", "2.1.2", "2.2.3", "2.2.7"]) { let constructed = 0, prepared = 0 const endpoint: Endpoint = { url: "http://127.0.0.1:4321" } rememberRuntime(endpoint, { version, pid: 1, discovery: "info" }) @@ -25,8 +25,8 @@ test("refuses old authenticated daemons before client calls or plugin preparatio prepareDesktopPlugins: async () => { prepared++; return true }, } await assert.rejects(service.client(options), (error: unknown) => error instanceof UnsupportedOpenCodeError - && error.actualVersion === version && error.minimumVersion === "2.2.3" && error.reason === "native_contract" - && /experimental_image_generate tool contract.*of 2\.2\.3/.test(error.message)) + && error.actualVersion === version && error.minimumVersion === "2.3.0" && error.reason === "native_contract" + && /background subagent report contract.*of 2\.3\.0/.test(error.message)) assert.equal(constructed, 0) assert.equal(prepared, 0) } diff --git a/packages/server/src/opencode/runtime-support.ts b/packages/server/src/opencode/runtime-support.ts index a0663ae514..c81df7f861 100644 --- a/packages/server/src/opencode/runtime-support.ts +++ b/packages/server/src/opencode/runtime-support.ts @@ -7,12 +7,15 @@ * replay contract read by the pinned client reducer and codecs (`native` provider * data, `metadata.keepID` compactions, `native.messages` windows) and Code Mode * jobs that keep JavaScript run-to-completion (scripts/test-codemode-jobs-native.mjs). + * CodeNomad qualifies only the 2.3 subagent contract: every subagent runs in the + * background and delivers synthetic `` reports to its parent + * (scripts/test-missions-native-trajectory.mjs, scripts/test-subagent-nesting-native.mjs). * OpenCode reads data stored by older releases. See * dev-docs/OPENCODE_COMPATIBILITY.md for the demonstrated boundary. */ -export const MINIMUM_OPENCODE_VERSION = "2.2.3" +export const MINIMUM_OPENCODE_VERSION = "2.3.0" /** Qualification target, independent of the technically required minimum. */ -export const RECOMMENDED_OPENCODE_VERSION = "2.2.7" +export const RECOMMENDED_OPENCODE_VERSION = "2.3.0" export const OPENCODE_UPDATE_REQUIRED = "opencode_update_required" export function isBelowOpenCodeMinimum(version: string): boolean { @@ -36,7 +39,7 @@ export class UnsupportedOpenCodeError extends Error { readonly minimumVersion = MINIMUM_OPENCODE_VERSION constructor(readonly actualVersion: string, readonly reason: OpenCodeIncompatibility = "native_contract") { super(`${OPENCODE_UPDATE_REQUIRED}: OpenCode ${actualVersion}; ${reason === "native_contract" - ? `requires the experimental_image_generate tool contract, native replay and compaction contract (native, metadata.keepID) and Code Mode job ordering of ${MINIMUM_OPENCODE_VERSION}` + ? `requires the background subagent report contract, experimental_image_generate tool contract, native replay and compaction contract (native, metadata.keepID) and Code Mode job ordering of ${MINIMUM_OPENCODE_VERSION}` : reason === "session_environment" ? "requires PUT /api/session/{sessionID}/environment with variables" : "does not expose the canonical session, permission, Form and inbox API contract"}`) this.name = "UnsupportedOpenCodeError" diff --git a/packages/server/src/opencode/session-media-fetch.test.ts b/packages/server/src/opencode/session-media-fetch.test.ts index 47d5373f84..df1d4977b9 100644 --- a/packages/server/src/opencode/session-media-fetch.test.ts +++ b/packages/server/src/opencode/session-media-fetch.test.ts @@ -4,6 +4,7 @@ import { setImmediate } from "node:timers/promises" import { OpenCode } from "@opencode/client" import { OpenCodeSharedService } from "../workspaces/opencode-service" import { rememberRuntime } from "./compatibility/runtime" +import { MINIMUM_OPENCODE_VERSION } from "./runtime-support" import { createSessionMediaFetch } from "./session-media-fetch" import { MESSAGE_LIMIT } from "./session-media-contract" import { createServer } from "node:http" @@ -11,7 +12,7 @@ import { gzipSync, brotliCompressSync, deflateSync } from "node:zlib" async function connected() { const endpoint = { url: "http://127.0.0.1:4321", auth: { type: "basic" as const, username: "media", password: "fixture" } } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() await service.endpoint({ kind: "lifecycle", identity: "bounded-media", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }) return { service, connection: await service.acquire() } @@ -19,7 +20,7 @@ async function connected() { test("media processor receives the original non-JSON error before compatibility cancellation", async t => { const endpoint = { url: "http://127.0.0.1:4321" } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) let cancel = 0, processed = 0, release!: () => void const cleanup = new Promise(resolve => { release = resolve }) const original = new Response(new ReadableStream({ cancel() { cancel++; return cleanup } }), { status: 400 }) @@ -48,7 +49,7 @@ test("media processor receives the original non-JSON error before compatibility test("ordinary non-JSON errors still await their sole cancel and preserve its rejection", async t => { const endpoint = { url: "http://127.0.0.1:4321" } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) let cancel = 0, reject!: (error: Error) => void, settled = false const cleanup = new Promise((_, fail) => { reject = fail }) const failure = new Error("original cancel rejected") @@ -167,7 +168,7 @@ test("real loopback gzip, br and deflate bodies obey the decompressed limit for }) await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)) const endpoint = { url: `http://127.0.0.1:${(server.address() as { port: number }).port}` } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() try { await service.endpoint({ kind: "lifecycle", identity: "compressed-media", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }) @@ -248,7 +249,7 @@ test("real fragmented gzip non-JSON errors bound decompressed bytes before norma }) await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)) const endpoint = { url: `http://127.0.0.1:${(server.address() as { port: number }).port}` } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() try { await service.endpoint({ kind: "lifecycle", identity: "gzip-error-boundary", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }) @@ -279,7 +280,7 @@ test("real under/overdeclared and absent HTTP length obey framing or reject befo }) await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)) const endpoint = { url: `http://127.0.0.1:${(server.address() as { port: number }).port}` } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() try { await service.endpoint({ kind: "lifecycle", identity: "framing-boundary", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }) diff --git a/packages/server/src/opencode/session-pruning/package.json b/packages/server/src/opencode/session-pruning/package.json index bddc322775..71c9ed55c4 100644 --- a/packages/server/src/opencode/session-pruning/package.json +++ b/packages/server/src/opencode/session-pruning/package.json @@ -21,8 +21,8 @@ "transaction.ts", "message-storage.ts", "native-assistant-content.ts" ], "dependencies": { - "@opencode/plugin": "2.2.3", - "@opencode/schema": "2.2.3", + "@opencode/plugin": "2.3.0", + "@opencode/schema": "2.3.0", "zod": "^4.6.6" } } diff --git a/packages/server/src/provider-accounts/quota-observer.ts b/packages/server/src/provider-accounts/quota-observer.ts index 5ff4b34c0b..3e8869e475 100644 --- a/packages/server/src/provider-accounts/quota-observer.ts +++ b/packages/server/src/provider-accounts/quota-observer.ts @@ -35,8 +35,7 @@ function limitName(body: unknown): { limitName?: string } { * and failures are dropped silently (native errors can contain credentials). */ export function observeProviderQuotaFailures(bus: EventBus, accounts: Pick, - observeFree?: (connection: ServiceConnection, event: unknown) => void) { + "observeSwitch" | "observeStepStart" | "markQuotaFailure" | "switchWatermark">) { const seen = new Set() const recent = new Map() const queues = new WeakMap; pending: number }>() @@ -52,8 +51,6 @@ export function observeProviderQuotaFailures(bus: EventBus, accounts: Pick ({ windows: { "5h": { usedPercent: used, remainingPercent: 100 - used, windowSeconds: 18_000, resetAt: Date.now() + 3_600_000 } } }) const goKey = (id: string, active = false): CredentialEntry => ({ id, integrationID: "opencode-go", label: id, active, value: { type: "key", key: `secret-${id}` } }) @@ -68,14 +67,13 @@ async function goFixture(options: { integrationID?: string; providerID?: string; }, }), 50) const bus = new EventBus() - const exhaustion = createOpenCodeFreeExhaustion() - const stop = observeProviderQuotaFailures(bus, service, exhaustion.observe) + const stop = observeProviderQuotaFailures(bus, service) const emit = (event: Record) => { nativeEventConnections.set(event, connection) bus.publish({ type: "instance.event", instanceId: "w", event } as never) } const activations = () => state.calls.filter(call => call.endsWith("/activate")).length - return { state, service, connection, emit, activations, integrationID, exhaustion, + return { state, service, connection, emit, activations, integrationID, send: () => service.beforeSend(connection, "ses_go", AbortSignal.timeout(3000), async directory => directory === "/project"), mark: (failedAt = Date.now(), limitName = "5 hour", watermark?: number) => service.markQuotaFailure(connection, { sessionID: "ses_go", failedAt, limitName, ...(watermark === undefined ? {} : { watermark }) }, AbortSignal.timeout(3000)), @@ -102,12 +100,10 @@ test("Go rotates from an exhausted account to an unknown-but-unmarked candidate" } finally { await f.close() } }) -test("free display marks with auto selection disabled and no credentials, without marking or activating accounts", async () => { +test("free-model quota failures with auto selection disabled and no credentials never mark or activate accounts", async () => { const f = await goFixture({ integrationID: "opencode", providerID: "opencode", entries: [] }) try { const now = Date.now() - // Reused event IDs and two close failures exercise the independent free path - // before the rotation observer's global/event and per-session time dedupe. f.emit({ id: "same", type: "session.step.started", created: now - 2, data: { sessionID: "ses_go", assistantMessageID: "paid", model: { providerID: "opencode", id: "paid" } } }) f.emit({ id: "paid-failure", type: "session.step.failed", created: now - 1, data: { @@ -116,7 +112,6 @@ test("free display marks with auto selection disabled and no credentials, withou sessionID: "ses_go", assistantMessageID: "free", model: { providerID: "opencode", id: "big-pickle" } } }) f.emit({ id: "same", type: "session.step.failed", created: now, data: { sessionID: "ses_go", assistantMessageID: "free", error: { type: "provider.quota" } } }) - assert.equal(f.exhaustion.exhausted(f.connection), true) assert.equal(await f.mark(), false, "disabled policy cannot mark accounts") await f.send() assert.ok(f.state.calls.every(call => call.startsWith("GET /api/session/") || call.startsWith("GET /api/provider/")), diff --git a/packages/server/src/remote-control/direct-https.test.ts b/packages/server/src/remote-control/direct-https.test.ts index cca2cb671e..a2f7358d48 100644 --- a/packages/server/src/remote-control/direct-https.test.ts +++ b/packages/server/src/remote-control/direct-https.test.ts @@ -1,6 +1,11 @@ import assert from "node:assert/strict" +import fs from "node:fs" import http from "node:http" +import os from "node:os" +import path from "node:path" import test from "node:test" +import { resolveConfigLocation } from "../config/location" +import { SettingsService } from "../settings/service" import { DEVICE_COOKIE_NAME } from "./gate" import { verifiedDirectHttpsOrigin, verifiedHttpsOrigins } from "./direct-https" import { SERVER_PAIR_PATH } from "./server-pairing" @@ -16,16 +21,18 @@ const PROXY_PEERS = ["127.0.0.1", "192.0.2.20"] type Surface = Awaited> +function configureInjectedSockets(app: Surface["app"]) { + // Inject sockets lack destroy(); revocation closes them like real sockets. + app.addHook("onRequest", (request, _reply, done) => { + const socket = request.raw.socket as unknown as { destroy?: () => void; emit(event: string): void } + socket.destroy ??= () => socket.emit("close") + done() + }) +} + async function surface(t: test.TestContext, options: Parameters[1] = {}) { const allowedOrigins = [PUBLIC, LAN_HTTP, "https://localhost:8443"] - const f = await startRemoteSurface(t, { allowedOrigins, ...options, configureApp: app => { - // Inject sockets lack destroy(); revocation closes them like real sockets. - app.addHook("onRequest", (request, _reply, done) => { - const socket = request.raw.socket as unknown as { destroy?: () => void; emit(event: string): void } - socket.destroy ??= () => socket.emit("close") - done() - }) - } }) + const f = await startRemoteSurface(t, { allowedOrigins, ...options, configureApp: configureInjectedSockets }) // Direct pairing and admission never need the tunnel. await f.manager.stop() const session = `${f.authManager.getCookieName()}=${f.authManager.createSession("codenomad").id}` @@ -45,6 +52,7 @@ async function pairDirect(f: Surface, remoteAddress = "127.0.0.1") { const id = response.json().device.id as string return { cookie: setCookie.split(";")[0]!, setCookie, id, response } } +const LAN_PEER = "192.0.2.20" test("the verified direct HTTPS origin set and request predicate", () => { assert.deepEqual(verifiedHttpsOrigins({ localUrl: "https://127.0.0.1:9898", remoteUrl: "https://192.0.2.10:9898", @@ -287,3 +295,109 @@ for (const action of ["revoke", "evict"] as const) { assert.equal((await f.app.inject({ url: "/api/test/echo", headers: { host: PUBLIC_HOST, cookie } })).statusCode, 401) }) } +/** The real application and settings service; the host's opt-in lives in its `config.yaml`. */ +async function sidecarSurface(t: test.TestContext, enabled: boolean) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-direct-https-")) + t.after(() => fs.rmSync(root, { recursive: true, force: true })) + const location = resolveConfigLocation(root) + const setOptIn = (value: boolean) => fs.writeFileSync(location.configYamlPath, `server:\n sidecarsOverDirectHttps: ${value}\n`) + setOptIn(enabled) + const settings = new SettingsService(location, undefined, { child() { return this }, warn() {}, info() {} } as never) + // The tunnel origin is listed too: Remote Control ingress must never qualify, even then. + const f = await startRemoteSurface(t, { settings, configureApp: configureInjectedSockets, + allowedOrigins: [PUBLIC, LAN_HTTP, "https://localhost:8443", `https://${FAKE_TUNNEL_HOST}`] }) + const cookie = `${f.authManager.getCookieName()}=${f.authManager.createSession("codenomad").id}` + return { ...f, setOptIn, cookie } +} + +test("the opt-in opens no other host-only path to a verified direct HTTPS origin", async t => { + const f = await sidecarSurface(t, true) + for (const [method, url] of [["POST", "/api/auth/password"], ["POST", "/api/auth/token"], ["GET", "/auth/token"], + ["GET", "/api/remote-control/devices"], ["POST", "/api/remote-control/start"], ["PUT", "/api/remote-control/previews"], + ["POST", "/api/remote-proxy/sessions"], ["GET", "/api/remote-servers"], ["POST", "/api/opencode-plugin/automation"], + ["GET", "/api/backends/x/api/meta"], ["POST", "/api/backends/x/preview-capabilities"], + ["GET", "/previews/missing/"], + ["GET", "/sidecars"], ["GET", "/api/remote-%63ontrol/devices"]] as const) { + for (const headers of [{ host: PUBLIC_HOST, origin: PUBLIC }, { host: PUBLIC_HOST }]) { + const response = await f.app.inject({ method, url, remoteAddress: LAN_PEER, headers: { ...headers, cookie: f.cookie } }) + assert.equal(response.statusCode, 404, `${method} ${url} ${JSON.stringify(headers)}: ${response.body}`) + } + } +}) + +test("SideCar opt-in retains direct HTTPS device scope and local previews without granting backend relay privileges", async t => { + const f = await sidecarSurface(t, true) + const { cookie } = await pairDirect(f) + for (const remoteAddress of PROXY_PEERS) { + const meta = await f.app.inject({ url: "/api/meta", remoteAddress, headers: { host: PUBLIC_HOST, cookie } }) + assert.equal(meta.statusCode, 200, meta.body) + assert.equal(meta.json().localRequest, false) + assert.equal(meta.json().sidecarsAllowed, true) + const preview = await f.app.inject({ method: "POST", url: "/api/previews", remoteAddress, + headers: { host: PUBLIC_HOST, origin: PUBLIC, cookie }, payload: { sessionId: "device-local", url: "http://localhost:3000/" } }) + assert.equal(preview.statusCode, 200, preview.body) + const token = preview.json().token as string + assert.equal(f.previewManager.get(token)?.sessionId, "device-local") + const removed = await f.app.inject({ method: "DELETE", url: `/api/previews/${token}`, remoteAddress, + headers: { host: PUBLIC_HOST, origin: PUBLIC, cookie } }) + assert.equal(removed.statusCode, 204, removed.body) + for (const [method, url] of [["GET", "/api/backends/x/api/meta"], ["POST", "/api/backends/x/preview-capabilities"], + ["GET", "/api/backends/x/previews/remote-token/"], ["POST", "/api/backends/x/api/memory"], + ["POST", "/api/memory"], ["GET", "/api/memory/settings"], + ["POST", "/api/%62ackends/x/preview-capabilities"], + ["GET", "/api/%62ackends/x/api/meta"], ["POST", "/api/%6demory"]] as const) { + const response = await f.app.inject({ method, url, remoteAddress, headers: { host: PUBLIC_HOST, origin: PUBLIC, cookie } }) + assert.equal(response.statusCode, 404, `${remoteAddress} ${method} ${url}: ${response.body}`) + } + } +}) + +test("/api/meta reports sidecarsAllowed for local clients and opted-in verified direct HTTPS origins only", async t => { + const f = await sidecarSurface(t, false) + const meta = async (remoteAddress: string, headers: Record) => { + const response = await f.app.inject({ url: "/api/meta", remoteAddress, headers: { ...headers, cookie: f.cookie } }) + assert.equal(response.statusCode, 200, response.body) + return response.json() as { localRequest: boolean; sidecarsAllowed: boolean } + } + const verified: Record[] = [{ host: PUBLIC_HOST }, { host: "127.0.0.1:9899", referer: `${PUBLIC}/` }, { host: PUBLIC_HOST, origin: PUBLIC }] + const refused: Record[] = [{ host: "lan.example.test:9899" }, { host: PUBLIC_HOST, origin: LAN_HTTP }, { host: PUBLIC_HOST, referer: `${LAN_HTTP}/` }, + { host: "localhost:8443" }, { host: PUBLIC_HOST, origin: "https://foreign.test" }, { host: "127.0.0.1:9899" }] + for (const enabled of [false, true]) { + f.setOptIn(enabled) + const local = await meta("127.0.0.1", { host: "127.0.0.1:9899" }) + assert.deepEqual([local.localRequest, local.sidecarsAllowed], [true, true]) + for (const headers of verified) assert.equal((await meta(LAN_PEER, headers)).sidecarsAllowed, enabled, JSON.stringify(headers)) + for (const headers of refused) assert.equal((await meta(LAN_PEER, headers)).sidecarsAllowed, false, JSON.stringify(headers)) + for (const headers of [...verified, ...refused]) assert.equal((await meta(LAN_PEER, headers)).localRequest, false) + } + // Unauthenticated clients learn nothing. + assert.equal((await f.app.inject({ url: "/api/meta", remoteAddress: LAN_PEER, headers: { host: PUBLIC_HOST } })).statusCode, 401) +}) + +function ingress(target: string, pathname: string, cookie: string): Promise<{ status: number; body: string }> { + const [hostname, port] = target.split(":") + return new Promise((resolve, reject) => { + http.get({ hostname, port: Number(port), path: pathname, agent: false, headers: { host: FAKE_TUNNEL_HOST, cookie } }, response => { + let body = "" + response.setEncoding("utf8").on("data", chunk => { body += chunk }).on("end", () => resolve({ status: response.statusCode ?? 0, body })) + }).on("error", reject) + }) +} + +test("Remote Control ingress never gains SideCars through the opt-in, even with its origin listed", async t => { + const f = await sidecarSurface(t, true) + const paired = await new Promise((resolve, reject) => { + const [hostname, port] = f.target().split(":") + const request = http.request({ hostname, port: Number(port), path: "/api/remote-control/pair", method: "POST", agent: false, + headers: { host: FAKE_TUNNEL_HOST, origin: `https://${FAKE_TUNNEL_HOST}`, "content-type": "application/json" } }, response => { + response.resume() + response.statusCode === 200 ? resolve(String(response.headers["set-cookie"]).split(";")[0]!) : reject(new Error(`pairing ${response.statusCode}`)) + }) + request.on("error", reject) + request.end(JSON.stringify({ code: f.code })) + }) + assert.equal((await ingress(f.target(), "/sidecars/fixture/", paired)).status, 404) + const meta = await ingress(f.target(), "/api/meta", paired) + assert.equal(meta.status, 200, meta.body) + assert.equal(JSON.parse(meta.body).sidecarsAllowed, false) +}) diff --git a/packages/server/src/remote-control/gate.ts b/packages/server/src/remote-control/gate.ts index 801ed6ed93..009198e02a 100644 --- a/packages/server/src/remote-control/gate.ts +++ b/packages/server/src/remote-control/gate.ts @@ -106,6 +106,8 @@ export interface RemoteGateDeps { /** A browser device paired on this verified direct HTTPS origin, independent of the tunnel. */ authenticateDirect?(token: string | undefined, origin: string): RemoteControlDevice | null assignDirectDevice?(socket: Socket, deviceId: string): void + /** The host's opt-in for SideCar content on verified direct HTTPS origins only. */ + allowsDirectSidecar?(request: FastifyRequest): boolean } /** @@ -215,7 +217,8 @@ function gateDirectHttpsDevice(request: FastifyRequest, reply: FastifyReply, tok else reject(reply, 401, "This device is not paired") return true } - if ((isHostOnlyPath(pathname, method) || pathname === "/api/memory" || pathname.startsWith("/api/memory/")) && !PUBLIC_PATHS.has(pathname)) { + const directSidecar = pathname.startsWith("/sidecars/") && deps.allowsDirectSidecar?.(request) === true + if ((isHostOnlyPath(pathname, method) && !directSidecar || pathname === "/api/memory" || pathname.startsWith("/api/memory/")) && !PUBLIC_PATHS.has(pathname)) { reject(reply, 404, "Not found") return true } diff --git a/packages/server/src/remote-control/manager.test.ts b/packages/server/src/remote-control/manager.test.ts index b582151399..54821acda2 100644 --- a/packages/server/src/remote-control/manager.test.ts +++ b/packages/server/src/remote-control/manager.test.ts @@ -23,10 +23,11 @@ function fixture(t: test.TestContext) { const alive = new Set() let nextPid = 100 // Each launch is a new manager over the same config directory, as after a restart. - const launch = () => { + const launch = (disabledByAdministrator = false) => { const pid = nextPid++ alive.add(pid) const manager = new RemoteControlManager({ + disabledByAdministrator, registry: new RemoteDeviceRegistry(file), lease: new RemoteControlOwnerLease(path.join(directory, "remote-control.owner"), pid, (candidate) => alive.has(candidate)), router: () => null, @@ -71,6 +72,30 @@ test("only one backend sharing the configuration resumes, until it goes away", a assert.equal(next.status().state, "connected") }) +test("an administrator-disabled Remote Control never opens a tunnel, resumes or pairs", async (t) => { + const { opened, launch } = fixture(t) + // A user left Remote Control on and paired a device before the policy applied. + const before = launch() + const { pairing } = await before.start() + const device = before.exchangePairing(new URL(pairing.url).hash.slice(1), undefined) + assert(device) + await before.shutdown() + before.exit() + + const disabled = launch(true) + await disabled.resume() + await assert.rejects(disabled.start(), /disabled by the administrator/) + assert.throws(() => disabled.createPairing(), /not connected/) + assert.equal(opened.length, 1, "no tunnel after the policy applied") + assert.deepEqual(disabled.status(), { manageable: true, disabledByAdministrator: true, enabled: false, startsOnLaunch: false, + previews: true, state: "stopped", pairedDevices: 1 }) + assert.equal(disabled.isDeviceAuthorized(device.device.id), false) + assert.equal(disabled.gate().publicHost(), null) + // Devices stay listed and revocable on the host. + assert.equal(disabled.revokeDevice(device.device.id), true) + assert.equal(disabled.status().pairedDevices, 0) +}) + test("a started Remote Control reconnects at the next launch without a pairing link", async (t) => { const { opened, launch } = fixture(t) const first = launch() @@ -155,4 +180,36 @@ test("a connected tunnel is not tied to any start deadline", async (t) => { assert.equal(opened?.signal, undefined, "no signal can later close the connected tunnel") await new Promise((resolve) => setTimeout(resolve, 20)) assert.deepEqual({ enabled: manager.status().enabled, state: manager.status().state }, { enabled: true, state: "connected" }) -}) \ No newline at end of file +}) + +test("administrator policy refuses direct HTTPS devices and pairing while preserving origin classification and revocation", async (t) => { + const { file, opened } = fixture(t) + const origin = "https://code.example.test" + const registry = new RemoteDeviceRegistry(file) + const device = registry.exchange(registry.createPairing(origin).code, "direct device", origin) + assert(device) + const pendingCode = registry.createPairing(origin).code + + const disabled = new RemoteControlManager({ + disabledByAdministrator: true, directHttpsOrigins: () => [origin], + registry, router: () => null, logger, + openTunnel: async (options) => { opened.push(options); throw new Error("must never open") }, + }) + t.after(() => disabled.shutdown()) + await disabled.resume() + await assert.rejects(disabled.start(), /disabled by the administrator/) + assert.throws(() => disabled.createDirectPairing(origin), /disabled by the administrator/) + assert.equal(disabled.exchangeDirectPairing(pendingCode, origin, undefined), null) + assert.equal(disabled.exchangePairing(pendingCode, undefined), null) + assert.equal(disabled.isDeviceAuthorized(device.device.id), false) + assert.equal(disabled.gate().authenticate(device.token), null) + assert.equal(disabled.gate().authenticateDirect!(device.token, origin), null) + assert.deepEqual(disabled.gate().directHttpsOrigins!(), [origin], "classify the cookie and refuse it, without password fallback") + assert.deepEqual(disabled.devices().map(value => value.id), [device.device.id]) + assert.equal(opened.length, 0) + assert(disabled.revokeDevice(device.device.id)) + await disabled.shutdown() + + assert(registry.exchange(pendingCode, "new device", origin), "refused exchanges and shutdown preserve the direct code") + assert.equal(registry.isPaired(device.device.id, origin), false) +}) diff --git a/packages/server/src/remote-control/manager.ts b/packages/server/src/remote-control/manager.ts index 13f901e40c..88559c0f25 100644 --- a/packages/server/src/remote-control/manager.ts +++ b/packages/server/src/remote-control/manager.ts @@ -31,8 +31,12 @@ interface ManagerOptions { lease?: RemoteControlOwnerLease /** Verified direct HTTPS origins (`direct-https.ts`) that pair and admit browser devices. */ directHttpsOrigins?: () => readonly string[] + /** Administrator policy: no tunnel, pairing or launch resume; paired devices stay revocable. */ + disabledByAdministrator?: boolean } +export const REMOTE_CONTROL_DISABLED = "Remote Control is disabled by the administrator" + export class RemoteControlManager { private readonly ingress: RemoteIngress // Sockets of tunnel-authorized devices, including server devices on the direct listener. @@ -69,8 +73,9 @@ export class RemoteControlManager { : tunnelState ?? "connecting" return { manageable: true, + ...(this.options.disabledByAdministrator ? { disabledByAdministrator: true } : {}), enabled: this.enabled, - startsOnLaunch: this.options.registry.startsOnLaunch(), + startsOnLaunch: !this.options.disabledByAdministrator && this.options.registry.startsOnLaunch(), previews: this.options.registry.previewsAllowed(), state, ...(tunnel ? { remoteUrl: tunnel.url } : {}), @@ -86,6 +91,7 @@ export class RemoteControlManager { } async start(): Promise { + if (this.options.disabledByAdministrator) throw new Error(REMOTE_CONTROL_DISABLED) this.enabled = true this.error = undefined this.options.registry.setStartsOnLaunch(true) @@ -97,6 +103,10 @@ export class RemoteControlManager { /** Reconnects at launch when the user left Remote Control on. Issues no pairing code. */ async resume(): Promise { + if (this.options.disabledByAdministrator) { + if (this.options.registry.startsOnLaunch()) this.options.logger.info(REMOTE_CONTROL_DISABLED + "; not resuming") + return + } if (this.enabled || !this.options.registry.startsOnLaunch()) return if (this.options.lease && !this.options.lease.tryAcquire()) { this.options.logger.info("Remote Control runs in another CodeNomad backend with this configuration; not resuming") @@ -133,11 +143,13 @@ export class RemoteControlManager { /** A code for one verified direct HTTPS origin; the tunnel need not run. */ createDirectPairing(origin: string): RemoteControlPairing { + if (this.options.disabledByAdministrator) throw new Error(REMOTE_CONTROL_DISABLED) if (!this.directHttpsOrigins().includes(origin)) throw new Error("This origin cannot pair devices") return pairingFromCode(origin, this.options.registry.createPairing(origin)) } exchangeDirectPairing(code: string, origin: string, userAgent: string | undefined): { device: RemoteControlDevice; token: string } | null { + if (this.options.disabledByAdministrator) return null if (!this.directHttpsOrigins().includes(origin)) return null const paired = this.options.registry.exchange(code, deviceNameFromUserAgent(userAgent), origin) if (!paired) return null @@ -154,6 +166,7 @@ export class RemoteControlManager { * its channel is available: the connected tunnel, or its still-verified direct HTTPS origin. */ isDeviceAuthorized(id: string): boolean { + if (this.options.disabledByAdministrator) return false return this.enabled && this.tunnel !== null && this.options.registry.isPaired(id) || this.directHttpsOrigins().some((origin) => this.options.registry.isPaired(id, origin)) } @@ -183,7 +196,7 @@ export class RemoteControlManager { assignDevice: (socket, deviceId) => trackSocket(this.deviceSockets, socket, deviceId), servesPreview: (token) => this.options.registry.previewsAllowed() && this.options.hasPreview?.(token) === true, directHttpsOrigins: () => this.directHttpsOrigins(), - authenticateDirect: (token, origin) => this.directHttpsOrigins().includes(origin) ? this.options.registry.authenticate(token, origin) : null, + authenticateDirect: (token, origin) => !this.options.disabledByAdministrator && this.directHttpsOrigins().includes(origin) ? this.options.registry.authenticate(token, origin) : null, assignDirectDevice: (socket, deviceId) => trackSocket(this.directDeviceSockets, socket, deviceId), } } diff --git a/packages/server/src/remote-control/multi-backend-network-policy.test.ts b/packages/server/src/remote-control/multi-backend-network-policy.test.ts new file mode 100644 index 0000000000..dd90feaca2 --- /dev/null +++ b/packages/server/src/remote-control/multi-backend-network-policy.test.ts @@ -0,0 +1,457 @@ +import assert from "node:assert/strict" +import { createHash, randomBytes } from "node:crypto" +import dns from "node:dns" +import fs from "node:fs" +import http from "node:http" +import type { Socket } from "node:net" +import os from "node:os" +import path from "node:path" +import test, { type TestContext } from "node:test" +import pino from "pino" +import { AuthManager } from "../auth/manager" +import { RELAY_AUTHORITY_HEADER as AUTHORITY, RELAY_BOOTSTRAP } from "../codenomad-servers/relay-authority" +import { startFakeCodeNomad } from "../codenomad-servers/test-support/fake-codenomad" +import { PreviewManager } from "../previews/manager" +import { createHttpServer } from "../server/http-server" +import { readNetworkPolicy } from "../server/network-policy" +import { SideCarManager } from "../sidecars/manager" +import { RemoteDeviceRegistry } from "./devices" +import { RemoteIngress } from "./ingress" +import { RemoteControlManager } from "./manager" +import { FAKE_TUNNEL_HOST } from "./test-support/surface" + +const PUBLIC = "https://code.example.test" +const REMOTE = `https://${FAKE_TUNNEL_HOST}` +const TOKEN = "11111111-1111-4111-8111-111111111111" +const logger = pino({ level: "silent" }) +const PREFIX = "/api/backends/saved" + +function send(source: string, options: { method?: string; headers?: Record; body?: string } = {}) { + const url = new URL(source) + return new Promise<{ status: number; headers: http.IncomingHttpHeaders; body: string }>((resolve, reject) => { + // Connect locally even for the isolated preview's per-capability hostname. + const request = http.request({ hostname: "127.0.0.1", port: url.port, path: `${url.pathname}${url.search}`, + method: options.method, agent: false, headers: { host: url.host, ...options.headers } }, response => { + let body = "" + response.setEncoding("utf8") + response.on("data", chunk => { body += chunk }) + response.on("end", () => resolve({ status: response.statusCode!, headers: response.headers, body })) + response.on("error", reject) + }) + request.setTimeout(5000, () => request.destroy(new Error("Request timed out"))) + request.on("error", reject) + request.end(options.body) + }) +} + +async function fixture(t: TestContext, disabled: boolean, locked: boolean, skipAuth = false) { + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "multi-backend-network-policy-")) + t.after(() => fs.rmSync(directory, { recursive: true, force: true })) + const uiStaticDir = path.join(directory, "ui") + fs.mkdirSync(uiStaticDir) + fs.writeFileSync(path.join(uiStaticDir, "index.html"), "Test UI") + const remote = await startFakeCodeNomad({ anonymous: true }) + t.after(() => remote.close()) + remote.state.overrides.set("/api/meta", { status: 200, body: { serverId: "remote-A", apiContract: 1 } }) + remote.state.overrides.set("/api/memory/settings", { status: 200, body: { enabled: true } }) + remote.state.overrides.set("/api/previews", { status: 200, body: { + token: TOKEN, sessionId: "session", targetUrl: "http://app.invalid/start", + proxyUrl: `/previews/${TOKEN}/start`, createdAt: new Date().toISOString(), + } }) + remote.state.handlers.set(`/previews/${TOKEN}/start`, (_request, reply) => reply.end("isolated remote content")) + remote.state.handlers.set("/ordinary", (_request, reply) => reply.end("ordinary local preview")) + remote.state.handlers.set("/sidecar", (_request, reply) => reply.end("direct HTTPS SideCar")) + remote.state.handlers.set("/assets/probe.json", (_request, reply) => reply.end("ordinary preview asset")) + remote.state.handlers.set(`/previews/${TOKEN}/assets/probe.json`, (_request, reply) => reply.end("isolated remote asset")) + + const policy = readNetworkPolicy({ + ...(disabled ? { CODENOMAD_REMOTE_CONTROL: "disabled" } : {}), + ...(locked ? { CODENOMAD_LOCKED_HOST: "127.0.0.1" } : {}), + }) + const config = path.join(directory, "config.yaml") + const settings = { + getOwner: () => ({ remoteServers: [{ id: "saved", baseUrl: remote.origin }] }), + configYamlPathForAuthority: () => config, + serverFlag: (key: string) => key === "sidecarsOverDirectHttps", + } + const stub = new Proxy({}, { get: () => () => undefined }) as never + const authManager = new AuthManager({ + configPath: config, username: "codenomad", password: "local-password", generateToken: false, + dangerouslySkipAuth: skipAuth, + }, logger) + const registry = new RemoteDeviceRegistry(path.join(directory, "devices.json")) + // A persisted launch choice and device must not override administrator disable. + registry.setStartsOnLaunch(true) + const previewManager = new PreviewManager() + let app: ReturnType["instance"] + let previewUpgrade: ReturnType["previewUpgrade"] + let target = "" + let opens = 0 + const manager = new RemoteControlManager({ + registry, logger, disabledByAdministrator: policy.remoteControlDisabled, + directHttpsOrigins: () => [PUBLIC], + router: () => (request, reply) => app.routing(request, reply), + previewUpgrade: () => previewUpgrade, + hasPreview: token => previewManager.get(token) !== undefined, + openTunnel: async options => { + opens++ + target = options.target + let close!: () => void + const closed = new Promise(resolve => { close = () => resolve(undefined) }) + return { url: REMOTE, hostname: FAKE_TUNNEL_HOST, status: () => ({ state: "connected", connections: 0 }), + closed, close: async () => close() } + }, + }) + const meta = { + localUrl: "http://127.0.0.1:0", eventsUrl: "/api/events", host: policy.lockedHost ?? "0.0.0.0", + listeningMode: "all", listeningLocked: locked, localPort: 0, hostLabel: "test", workspaceRoot: directory, addresses: [], + } + const sidecar = { id: "fixture", kind: "port", name: "fixture", port: Number(new URL(remote.origin).port), + insecure: true, prefixMode: "strip", status: "running" } + let sidecarTarget = `${remote.origin}/sidecar` + const server = createHttpServer({ + bindHost: policy.lockedHost ?? "0.0.0.0", bindPort: 0, defaultPort: 0, protocol: "http", + allowedOrigins: [PUBLIC], serverMeta: meta as never, + workspaceManager: stub, settings: settings as never, fileSystemBrowser: stub, eventBus: stub, + instanceStore: stub, speechService: stub, clientConnectionManager: stub, remoteProxySessionManager: stub, + yoloManager: stub, nativeParent: stub, authManager, previewManager, remoteControlManager: manager, + sidecarManager: { + get: async () => sidecar, buildProxyBasePath: () => "/sidecars/fixture", + buildTargetOrigin: () => SideCarManager.prototype.buildTargetOrigin(sidecar), + buildTargetPath: () => new URL(sidecarTarget).pathname, + } as never, + logger, automationBridgeToken: "test-bridge", uiStaticDir, + }) + app = server.instance + app.addHook("onRequest", (request, _reply, done) => { + const socket = request.raw.socket as unknown as { destroy?: () => void; emit(event: string): void } + socket.destroy ??= () => socket.emit("close") + done() + }) + previewUpgrade = server.previewUpgrade + const started = await server.start() + // Match production's publication of the actual bound origin. + const origin = `http://127.0.0.1:${started.port}` + meta.localUrl = origin + const cookie = `${authManager.getCookieName()}=${authManager.createSession("codenomad").id}` + t.after(async () => { await manager.shutdown(); await server.stop() }) + let device = "" + if (!disabled) { + const { pairing } = await manager.start() + const response = await send(`http://${target}/api/remote-control/pair`, { + method: "POST", headers: { host: FAKE_TUNNEL_HOST, origin: REMOTE, "content-type": "application/json" }, + body: JSON.stringify({ code: new URL(pairing.url).hash.slice(1) }), + }) + assert.equal(response.status, 200, response.body) + device = String(response.headers["set-cookie"]).split(";")[0]! + } else { + // Exercise physical ingress marking without starting a policy-forbidden tunnel. + const ingress = new RemoteIngress((request, reply) => app.routing(request, reply)) + target = await ingress.start() + t.after(() => ingress.stop()) + } + const call = (pathname: string, options: Parameters[1] = {}) => send(`${origin}${pathname}`, { + ...options, headers: { origin, cookie, ...options.headers }, + }) + const admitted = await call(`${PREFIX}/api/meta`, { headers: { [AUTHORITY]: RELAY_BOOTSTRAP } }) + assert.equal(admitted.status, 200, admitted.body) + const proof = String(admitted.headers[AUTHORITY]) + assert.match(proof, /^[A-Za-z0-9_-]{43}$/) + return { app, remote, manager, registry, previewManager, origin, cookie, proof, target, device, call, opens: () => opens, + retargetSidecar: (url: string) => { sidecarTarget = url; sidecar.port = Number(new URL(url).port) } } +} + +for (const [method, pathname] of [ + ["GET", `${PREFIX}/api/filesystem`], + ["GET", `${PREFIX}/api/memory/settings`], + ["POST", `${PREFIX}/preview-capabilities`], +] as const) test(`an RC-created ordinary preview cannot rebound into ${method} ${pathname}`, async t => { + const f = await fixture(t, false, true, true) + const created = await send(`http://${f.target}/api/previews`, { + method: "POST", headers: { host: FAKE_TUNNEL_HOST, origin: REMOTE, cookie: f.device, "content-type": "application/json" }, + body: JSON.stringify({ sessionId: "remote-device", url: f.origin }), + }) + assert.equal(created.status, 200, created.body) + const token = JSON.parse(created.body).token + const before = f.remote.state.requests.length + const response = await send(`http://${f.target}/previews/${token}${pathname}`, { + method, headers: { host: FAKE_TUNNEL_HOST, [AUTHORITY]: f.proof, "content-type": "application/json" }, + body: method === "POST" ? JSON.stringify({ sessionId: "session", url: "http://app.invalid/start" }) : undefined, + }) + assert.equal(response.status, 404, `${pathname}: ${response.body}`) + assert.equal(f.remote.state.requests.length, before, "a preview proxy must not manufacture local backend authority") +}) + +async function capability(f: Awaited>) { + const response = await f.call(`${PREFIX}/preview-capabilities`, { + method: "POST", headers: { [AUTHORITY]: f.proof, "content-type": "application/json" }, + body: JSON.stringify({ sessionId: "session", url: "http://app.invalid/start" }), + }) + assert.equal(response.status, 200, response.body) + return JSON.parse(response.body) as { capability: string; contentUrl: string } +} + +function resolveCapability(t: TestContext, contentUrl: string) { + const hostname = new URL(contentUrl).hostname + const lookup = dns.lookup + // Chromium resolves *.localhost internally; give the real Node proxy the same deterministic DNS. + return t.mock.method(dns, "lookup", ((host: string, ...args: unknown[]) => { + if (host !== hostname) return Reflect.apply(lookup, dns, [host, ...args]) + const callback = args.at(-1) as (...values: unknown[]) => void + const options = args[0] as { all?: boolean } | undefined + if (options?.all) callback(null, [{ address: "127.0.0.1", family: 4 }]) + else callback(null, "127.0.0.1", 4) + }) as typeof dns.lookup) +} + +test("an RC-created ordinary preview cannot rebound into an isolated remote capability origin", async t => { + const f = await fixture(t, false, true) + const cap = await capability(f) + assert.equal((await send(cap.contentUrl)).body, "isolated remote content") + resolveCapability(t, cap.contentUrl) + const created = await send(`http://${f.target}/api/previews`, { + method: "POST", headers: { host: FAKE_TUNNEL_HOST, origin: REMOTE, cookie: f.device, "content-type": "application/json" }, + body: JSON.stringify({ sessionId: "remote-device", url: cap.contentUrl }), + }) + assert.equal(created.status, 200, created.body) + const before = f.remote.state.requests.length + const response = await send(`http://${f.target}/previews/${JSON.parse(created.body).token}${new URL(cap.contentUrl).pathname}`, { + headers: { host: FAKE_TUNNEL_HOST }, + }) + assert.equal(response.status, 404, response.body) + assert.equal(f.remote.state.requests.length, before, "remote preview content must retain its exclusive origin through ordinary proxies") +}) + +test("direct HTTPS SideCar opt-in cannot proxy an isolated remote capability origin", async t => { + const f = await fixture(t, false, true) + const cap = await capability(f) + assert.equal((await send(cap.contentUrl)).body, "isolated remote content") + f.retargetSidecar(cap.contentUrl) + const before = f.remote.state.requests.length + const response = await f.app.inject({ url: "/sidecars/fixture/", remoteAddress: "192.0.2.20", + headers: { host: "code.example.test", origin: PUBLIC, cookie: f.cookie } }) + assert.equal(response.statusCode, 404, response.body) + assert.equal(f.remote.state.requests.length, before) +}) + +for (const pathname of [`${PREFIX}/api/filesystem`, `${PREFIX}/api/memory/settings`]) { + test(`direct HTTPS SideCar opt-in cannot rebound into ${pathname}`, async t => { + const f = await fixture(t, false, true, true) + f.retargetSidecar(`${f.origin}${pathname}`) + const before = f.remote.state.requests.length + const response = await f.app.inject({ url: `/sidecars/fixture${pathname}`, remoteAddress: "192.0.2.20", + headers: { host: "code.example.test", origin: PUBLIC, cookie: f.cookie, [AUTHORITY]: f.proof } }) + assert.equal(response.statusCode, 404, response.body) + assert.equal(f.remote.state.requests.length, before) + }) +} + +for (const locked of [false, true]) test(`paired direct HTTPS devices retain only SideCar opt-in (locked=${locked})`, async t => { + const f = await fixture(t, false, locked) + const pairing = f.manager.createDirectPairing(PUBLIC) + const paired = await f.app.inject({ method: "POST", url: "/api/remote-control/pair", remoteAddress: "192.0.2.20", + headers: { host: "code.example.test", origin: PUBLIC }, payload: { code: new URL(pairing.url).hash.slice(1) } }) + assert.equal(paired.statusCode, 200, paired.body) + const headers = { host: "code.example.test", origin: PUBLIC, cookie: String(paired.headers["set-cookie"]).split(";")[0]!, + [AUTHORITY]: f.proof } + const sidecar = await f.app.inject({ url: "/sidecars/fixture/", remoteAddress: "192.0.2.20", headers }) + assert.equal(sidecar.statusCode, 200, sidecar.body) + assert.equal(sidecar.body, "direct HTTPS SideCar") + const before = f.remote.state.requests.length + for (const pathname of [`${PREFIX}/api/filesystem`, `${PREFIX}/api/memory/settings`, "/api/memory/settings"]) { + assert.equal((await f.app.inject({ url: pathname, remoteAddress: "192.0.2.20", headers })).statusCode, 404, pathname) + } + assert.equal((await f.app.inject({ method: "POST", url: `${PREFIX}/preview-capabilities`, + remoteAddress: "192.0.2.20", headers, payload: { sessionId: "session", url: "http://app.invalid/start" } })).statusCode, 404) + assert.equal((await send(`http://${f.target}/sidecars/fixture/`, { headers: { + host: FAKE_TUNNEL_HOST, origin: REMOTE, cookie: f.device, + } })).status, 404, "the direct HTTPS opt-in never admits an ingress device") + assert.equal(f.remote.state.requests.length, before) +}) + +function upgrade(source: string, headers: Record = {}) { + const url = new URL(source) + return new Promise((resolve, reject) => { + const request = http.request({ hostname: "127.0.0.1", port: url.port, path: `${url.pathname}${url.search}`, agent: false, + headers: { host: url.host, connection: "Upgrade", upgrade: "websocket", "sec-websocket-version": "13", + "sec-websocket-key": randomBytes(16).toString("base64"), ...headers } }) + request.setTimeout(5000, () => request.destroy(new Error("Upgrade timed out"))) + request.on("response", response => { response.resume(); resolve(response.statusCode!) }) + request.on("upgrade", (response, socket) => { socket.destroy(); resolve(response.statusCode!) }) + request.on("error", reject) + request.end() + }) +} + +async function websocketApp(t: TestContext) { + const upgrades: string[] = [] + const sockets = new Set() + const server = http.createServer((_request, reply) => reply.end("ordinary application")) + server.on("connection", socket => { sockets.add(socket); socket.once("close", () => sockets.delete(socket)) }) + server.on("upgrade", (request, socket: Socket) => { + upgrades.push(request.url!) + const accept = createHash("sha1").update(`${request.headers["sec-websocket-key"]}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64") + socket.write(`HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: ${accept}\r\n\r\n`) + socket.once("end", () => socket.end()) + }) + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)) + t.after(async () => { + for (const socket of sockets) socket.destroy() + await new Promise(resolve => server.close(() => resolve())) + }) + return { origin: `http://127.0.0.1:${(server.address() as { port: number }).port}`, upgrades } +} + +test("RC preview WebSockets admit ordinary apps but refuse capability and own-control rebounds before IO", async t => { + const f = await fixture(t, false, true, true) + const app = await websocketApp(t) + const ordinary = f.previewManager.create("ordinary", app.origin) + const headers = { host: FAKE_TUNNEL_HOST } + assert.equal(await upgrade(`http://${f.target}/previews/${ordinary.token}/ws`, headers), 101) + assert.deepEqual(app.upgrades, ["/ws"]) + + const cap = await capability(f) + const isolated = f.previewManager.create("isolated", cap.contentUrl) + const lookup = resolveCapability(t, cap.contentUrl) + const before = f.remote.state.requests.length + assert.equal(await upgrade(`http://${f.target}/previews/${isolated.token}/ws`, headers), 404) + assert.equal(lookup.mock.callCount(), 0, "refuse capability targets before DNS or a remote WebSocket attempt") + assert.equal(f.remote.state.requests.length, before) + + const self = f.previewManager.create("self", f.origin) + assert.equal(await upgrade(`http://${f.target}/previews/${self.token}${PREFIX}/api/events`, { + ...headers, [AUTHORITY]: f.proof, + }), 404) + assert.equal(f.remote.state.requests.length, before) +}) + +test("SideCar WebSockets admit ordinary apps but refuse own-backend control targets", async t => { + const f = await fixture(t, false, true, true) + const app = await websocketApp(t) + const headers = { host: "code.example.test", origin: PUBLIC, cookie: f.cookie, [AUTHORITY]: f.proof } + f.retargetSidecar(`${app.origin}/ws`) + assert.equal(await upgrade(`${f.origin}/sidecars/fixture/ws`, headers), 101) + assert.deepEqual(app.upgrades, ["/ws"]) + f.retargetSidecar(`${f.origin}${PREFIX}/api/events`) + const before = f.remote.state.requests.length + assert.equal(await upgrade(`${f.origin}/sidecars/fixture${PREFIX}/api/events`, headers), 404) + assert.equal(f.remote.state.requests.length, before) +}) + +test("Referer asset fallback preserves ordinary RC previews and refuses isolated capability origins", async t => { + const f = await fixture(t, false, true) + const ordinary = f.previewManager.create("ordinary", f.remote.origin) + const headers = { host: FAKE_TUNNEL_HOST, cookie: f.device, + referer: `${REMOTE}/previews/${ordinary.token}/page` } + const asset = await send(`http://${f.target}/assets/probe.json`, { headers }) + assert.equal(asset.status, 200, asset.body) + assert.equal(asset.body, "ordinary preview asset") + const cap = await capability(f) + const isolated = f.previewManager.create("isolated", cap.contentUrl) + const lookup = resolveCapability(t, cap.contentUrl) + const before = f.remote.state.requests.length + const refused = await send(`http://${f.target}/assets/probe.json`, { headers: { + ...headers, referer: `${REMOTE}/previews/${isolated.token}/page`, + } }) + assert.equal(refused.status, 404, refused.body) + assert.equal(lookup.mock.callCount(), 0, "fallback refuses capability targets before DNS") + assert.equal(f.remote.state.requests.length, before) +}) + +test("Referer fallback cannot reinterpret an encoded own-backend control path", async t => { + const f = await fixture(t, false, true, true) + const preview = f.previewManager.create("self", f.origin) + const before = f.remote.state.requests.length + // The fallback uses the raw URL; the control boundary judges the routed path. + assert.equal((await f.call("/%61pi/meta")).status, 200) + const refused = await f.call("/%61pi/meta", { headers: { + referer: `${f.origin}/previews/${preview.token}/page`, [AUTHORITY]: f.proof, + } }) + assert.equal(refused.status, 404, refused.body) + assert.equal(f.remote.state.requests.length, before) +}) + +// #1438: transport provenance; #1493: admin disable/listener lock; #1497: SideCar-only HTTPS opt-in. +for (const disabled of [false, true]) { + for (const locked of [false, true]) { + test(`multi-backend authority stays local (admin disabled=${disabled}, listener locked=${locked})`, async t => { + const f = await fixture(t, disabled, locked) + assert.equal(f.manager.status().previews, true, "ordinary local RC previews retain the host's enabled contract") + assert.equal((await f.call("/api/meta")).body.includes('"listeningLocked":true'), locked) + if (disabled) { + await f.manager.resume() + await assert.rejects(f.manager.start(), /disabled by the administrator/) + for (const pathname of ["/api/remote-control/start", "/api/remote-control/pairings"]) { + const response = await f.call(pathname, { method: "POST", headers: { "content-type": "application/json" }, body: "{}" }) + assert.equal(response.status, 403, response.body) + assert.equal(JSON.parse(response.body).code, "remote_control_disabled") + } + assert.equal(f.opens(), 0) + assert.equal(f.registry.startsOnLaunch(), true, "administrator disable preserves the host's saved launch choice") + } else { + assert.equal(f.opens(), 1, "a listening lock alone does not disable RC") + const local = f.previewManager.create("ordinary", `${f.remote.origin}/ordinary`) + const response = await send(`http://${f.target}/previews/${local.token}/ordinary`, { headers: { host: FAKE_TUNNEL_HOST } }) + assert.equal(response.status, 200, response.body) + assert.equal(response.body, "ordinary local preview") + } + + const created = await f.call(`${PREFIX}/preview-capabilities`, { + method: "POST", headers: { [AUTHORITY]: f.proof, "content-type": "application/json" }, + body: JSON.stringify({ sessionId: "session", url: "http://app.invalid/start" }), + }) + assert.equal(created.status, 200, created.body) + const cap = JSON.parse(created.body) as { capability: string; contentUrl: string } + const content = new URL(cap.contentUrl) + assert.notEqual(content.port, new URL(f.origin).port, "the lock governs the ordinary listener, not the isolated content listener") + assert.equal((await send(cap.contentUrl)).body, "isolated remote content") + assert.equal((await f.call(`${PREFIX}/api/memory/settings`, { headers: { [AUTHORITY]: f.proof } })).status, 200) + + const before = f.remote.state.requests.length + const boundaryPaths = [ + ["GET", `${PREFIX}/api/meta`], ["GET", "/api/backends/saved/api/memory/settings"], + ["POST", `${PREFIX}/api/memory`], ["GET", "/api/memory/settings"], ["POST", "/api/memory"], + ["POST", `${PREFIX}/preview-capabilities`], ["DELETE", `${PREFIX}/preview-capabilities/${cap.capability}`], + ["GET", `${PREFIX}/previews/${TOKEN}/start`], + ["POST", `${PREFIX}/api/previews`], ["GET", `${PREFIX}/api/backends/other/api/meta`], + ] as const + for (const [method, pathname] of boundaryPaths) { + const response = await send(`http://${f.target}${pathname}`, { + method, headers: { host: FAKE_TUNNEL_HOST, origin: REMOTE, cookie: f.device, + [AUTHORITY]: f.proof, "content-type": "application/json" }, body: method === "POST" ? "{}" : undefined, + }) + assert.equal(response.status, disabled ? 421 : 404, `${method} ${pathname}: ${response.body}`) + } + // Knowing a valid content URL or relay proof cannot rebind RC to its exclusive origin. + for (const origin of [REMOTE, PUBLIC, f.origin, "null"]) { + assert.equal((await send(cap.contentUrl, { headers: { origin, cookie: f.device, [AUTHORITY]: f.proof } })).status, 404, origin) + } + assert.equal((await send(`http://${f.target}${content.pathname}`, { + headers: { host: content.host, cookie: f.device, [AUTHORITY]: f.proof }, + })).status, 421) + assert.equal(f.remote.state.requests.length, before, "refusals perform no upstream IO") + + const directHeaders = { host: "code.example.test", origin: PUBLIC, cookie: f.cookie, [AUTHORITY]: f.proof } + const directMeta = await f.app.inject({ url: "/api/meta", remoteAddress: "192.0.2.20", headers: directHeaders }) + assert.equal(directMeta.statusCode, 200) + assert.equal(directMeta.json().sidecarsAllowed, true) + assert.equal(directMeta.json().localRequest, false) + const sidecar = await f.app.inject({ url: "/sidecars/fixture/", remoteAddress: "192.0.2.20", headers: directHeaders }) + assert.equal(sidecar.statusCode, 200, sidecar.body) + assert.equal(sidecar.body, "direct HTTPS SideCar") + const afterSidecar = f.remote.state.requests.length + for (const [method, pathname] of boundaryPaths) { + const response = await f.app.inject({ method, url: pathname, remoteAddress: "192.0.2.20", + headers: directHeaders, ...(method === "POST" ? { payload: {} } : {}) }) + assert.equal(response.statusCode, 404, `${method} ${pathname}: ${response.body}`) + } + assert.equal(f.remote.state.requests.length, afterSidecar, "SideCar opt-in grants no relay, memory or preview-management authority") + assert.equal((await send(cap.contentUrl)).status, 200, "refused remote revocation preserves the local capability") + assert.equal((await f.call(`${PREFIX}/preview-capabilities/${cap.capability}`, { + method: "DELETE", headers: { [AUTHORITY]: f.proof }, + })).status, 204) + assert.equal((await send(cap.contentUrl)).status, 404) + if (disabled) assert.equal(f.opens(), 0, "local multi-backend preview use never reopens RC") + }) + } +} diff --git a/packages/server/src/remote-control/test-support/surface.ts b/packages/server/src/remote-control/test-support/surface.ts index 41a479ae1c..4db7f952b2 100644 --- a/packages/server/src/remote-control/test-support/surface.ts +++ b/packages/server/src/remote-control/test-support/surface.ts @@ -27,6 +27,8 @@ export async function startRemoteSurface(t: TestContext, options: { browse?: boolean bindHost?: string allowedOrigins?: string[] + /** Settings service in place of the stub, such as one that reads the host's SideCar opt-in. */ + settings?: unknown configureApp?: (app: ReturnType["instance"]) => void openTunnel?: (options: OpenRemoteTunnelOptions) => Promise /** Real panel extension routes over this store, with `workspaceManager` in place of the stub. */ @@ -86,7 +88,7 @@ export async function startRemoteSurface(t: TestContext, options: { protocol: "http", workspaceManager: (options.panelExtensions?.workspaceManager ?? stub) as never, panelExtensions: options.panelExtensions?.store, - settings: options.browse ? { getOwner: () => ({ recentFolders: [] }) } as never : stub, + settings: (options.settings ?? (options.browse ? { getOwner: () => ({ recentFolders: [] }) } : stub)) as never, fileSystemBrowser: options.browse ? { browse: () => ({ entries: [{ name: "app", path: "/srv/app", type: "directory" }], metadata: { scope: "unrestricted", pathKind: "absolute", currentPath: "/srv", rootPath: "/", homePath: "/srv", displayPath: "/srv" } }) } as never : stub, eventBus: stub, diff --git a/packages/server/src/server/__tests__/instance-proxy-legacy.test.ts b/packages/server/src/server/__tests__/instance-proxy-legacy.test.ts index 9c9e7402df..5fe933e772 100644 --- a/packages/server/src/server/__tests__/instance-proxy-legacy.test.ts +++ b/packages/server/src/server/__tests__/instance-proxy-legacy.test.ts @@ -17,7 +17,7 @@ test("modern proxy preserves Forms scope and rejects obsolete selectors in curso upstream.all("/*", async request => { forwarded++; return { method: request.method, url: request.url, body: request.body, headers: request.headers } }) await upstream.listen({ host: "127.0.0.1", port: 0 }) const endpoint: Endpoint = { url: `http://127.0.0.1:${(upstream.server.address() as { port: number }).port}`, auth: { type: "basic", username: "opencode", password: "fixture" } } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.0", pid: 1, discovery: "info" }) const client = { session: { get: async ({ sessionID }: { sessionID: string }) => ({ location: { directory: sessionID === "foreign" ? "/foreign" : "/native" } }) } } as unknown as OpenCodeClient const connection = { endpoint, client, fetch: createRuntimeFetch(endpoint), assertCurrent() {}, invalidate() {}, profile: async () => "modern" as const } const directories = new Set(["/host", "/native"]) @@ -89,7 +89,7 @@ test("future releases advertising retired schemas are refused before functional }) await upstream.listen({ host: "127.0.0.1", port: 0 }) const endpoint = { url: `http://127.0.0.1:${(upstream.server.address() as { port: number }).port}` } - rememberRuntime(endpoint, { version: "2.2.100", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.100", pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() try { await assert.rejects(service.client({ kind: "lifecycle", identity: "isolated-test", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }), { code: "opencode_update_required" }) diff --git a/packages/server/src/server/__tests__/sidecar-proxy.test.ts b/packages/server/src/server/__tests__/sidecar-proxy.test.ts index 2298360053..5f65186ec9 100644 --- a/packages/server/src/server/__tests__/sidecar-proxy.test.ts +++ b/packages/server/src/server/__tests__/sidecar-proxy.test.ts @@ -12,6 +12,8 @@ import type { SideCar } from "../../api-types" import { AuthManager } from "../../auth/manager" import { PreviewManager } from "../../previews/manager" import { createHttpServer } from "../http-server" +import { resolveConfigLocation } from "../../config/location" +import { SettingsService } from "../../settings/service" const WEBSOCKET_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11" @@ -147,7 +149,9 @@ function webSocketUpgrade(port: number, pathname: string, headers: Record () => undefined }) as never + const configYamlPath = resolveConfigLocation(path.join(directory, "settings")).configYamlPath + await fs.mkdir(path.dirname(configYamlPath), { recursive: true }) + const realSettings = options.realSettings ? new SettingsService(resolveConfigLocation(path.dirname(configYamlPath)), undefined, logger) : undefined + const settings = (realSettings ?? stub) as never const previewManager = new PreviewManager() const preview = previewManager.create("fixture", `http://127.0.0.1:${port}`) const { instance: app } = createHttpServer({ bindHost: "127.0.0.1", bindPort: 0, defaultPort: 0, protocol: "http", - workspaceManager: stub, settings: stub, fileSystemBrowser: stub, eventBus: stub, + workspaceManager: stub, settings, fileSystemBrowser: stub, eventBus: stub, serverMeta: { localUrl: "http://localhost:0", eventsUrl: "/api/events", listeningMode: "local", localPort: 0, hostLabel: "test", workspaceRoot: directory, addresses: [] } as never, instanceStore: stub, speechService: stub, sidecarManager: sidecarManager as never, previewManager, clientConnectionManager: stub, remoteProxySessionManager: stub, yoloManager: stub, @@ -206,6 +214,8 @@ async function startServer(options: UpstreamOptions & { cookieName?: string; pre received, preview, cleanupDirectory: directory, + settings: realSettings, + configYamlPath, } } @@ -248,6 +258,118 @@ it("non-local SideCar upgrades are refused even with a valid host session and sp } finally { await fs.rm(server.cleanupDirectory, { recursive: true, force: true }) } }) +// A TLS-terminating reverse proxy forwards the public Host and the browser's Origin from another machine. +const PUBLIC = "https://code.example.test" +const PUBLIC_HOST = "code.example.test" +const LAN_HTTP = "http://lan.example.test:9899" +const LOOPBACK_HTTPS = "https://localhost:8443" +const LAN_PEER = "192.0.2.20" + +/** The real settings service over a `config.yaml` that each test edits as the host would. */ +async function startDirectHttpsServer(enabled: boolean) { + const server = await startServer({ realSettings: true, allowedOrigins: [PUBLIC, LAN_HTTP, LOOPBACK_HTTPS] }) + // A deterministic non-loopback transport peer for raw upgrades, as app.inject's remoteAddress for HTTP. + server.app.server.prependListener("connection", socket => { Object.defineProperty(socket, "remoteAddress", { value: LAN_PEER }) }) + const host = (content: string) => fs.writeFile(server.configYamlPath, content) + const setOptIn = (value: boolean) => host(`server:\n logLevel: INFO\n sidecarsOverDirectHttps: ${value}\n`) + await setOptIn(enabled) + return { ...server, host, setOptIn } +} + +it("the host's opt-in admits SideCar content for authenticated verified direct HTTPS origins only", async () => { + const server = await startDirectHttpsServer(false) + try { + const get = (headers: Record, method: "GET" | "POST" = "GET") => server.app.inject({ method, url: "/sidecars/fixture/token", + remoteAddress: LAN_PEER, headers: { cookie: server.cookie, "content-type": "text/plain", ...headers }, ...(method === "POST" ? { payload: "x" } : {}) }) + // Navigations and same-origin fetches send the public Host, a Referer or an Origin. + const verified: Record[] = [{ host: PUBLIC_HOST }, { host: `${PUBLIC_HOST}:443` }, { host: `127.0.0.1:${server.port}`, referer: `${PUBLIC}/` }, { host: PUBLIC_HOST, origin: PUBLIC }] + for (const headers of verified) assert.equal((await get(headers)).statusCode, 404, `off: ${JSON.stringify(headers)}`) + assert.equal((await get({ origin: PUBLIC }, "POST")).statusCode, 404) + assert.equal(server.received.length, 0) + + await server.setOptIn(true) + for (const headers of verified) { + const response = await get(headers) + assert.equal(response.statusCode, 200, `${JSON.stringify(headers)}: ${response.body}`) + assert.equal(response.body, "{\"ok\":true}") + } + assert.equal((await get({ host: PUBLIC_HOST, origin: PUBLIC }, "POST")).statusCode, 200, "a mutation with its own verified Origin") + assert.equal(server.received.length, verified.length + 1) + const refused: Record[] = [ + // Plain-HTTP LAN, loopback-alias and unlisted pages. + { host: "lan.example.test:9899" }, { host: PUBLIC_HOST, origin: LAN_HTTP }, { host: PUBLIC_HOST, referer: `${LAN_HTTP}/` }, + { host: "localhost:8443" }, { host: PUBLIC_HOST, origin: LOOPBACK_HTTPS }, { host: `127.0.0.1:${server.port}` }, + { host: PUBLIC_HOST, origin: "https://foreign.test" }, { host: PUBLIC_HOST, origin: "https://code.example.test.evil.test" }, + { host: `user@${PUBLIC_HOST}` }, { host: "lan.example.test:9899", "x-forwarded-proto": "https", "x-forwarded-host": PUBLIC_HOST }, + // An opaque frame. + { host: PUBLIC_HOST, origin: "null" }, + ] + for (const headers of refused) assert.equal((await get(headers)).statusCode, 404, JSON.stringify(headers)) + // Mutations need their own verified Origin, never a Referer or Host. + for (const headers of [{ host: PUBLIC_HOST }, { host: PUBLIC_HOST, referer: `${PUBLIC}/` }] as Record[]) { + assert.equal((await get(headers, "POST")).statusCode, 404, `POST ${JSON.stringify(headers)}`) + } + // Authentication still applies. + const anonymous = await server.app.inject({ url: "/sidecars/fixture/token", remoteAddress: LAN_PEER, headers: { host: PUBLIC_HOST } }) + assert.equal(anonymous.statusCode, 401) + assert.equal(server.received.length, verified.length + 1) + } finally { await fs.rm(server.cleanupDirectory, { recursive: true, force: true }) } +}) + +it("the host's opt-in admits SideCar WebSockets from verified direct HTTPS origins, with the source and session checks", async () => { + const server = await startDirectHttpsServer(false) + try { + const upgrade = (headers: Record) => webSocketUpgrade(server.port, "/sidecars/fixture/ws", headers, true) + const credentials = { cookie: server.cookie } + assert.equal((await upgrade({ ...credentials, host: PUBLIC_HOST, origin: PUBLIC })).status, 404, "off by default") + await server.setOptIn(true) + for (const host of [PUBLIC_HOST, `127.0.0.1:${server.port}`]) { + const response = await upgrade({ ...credentials, host, origin: PUBLIC }) + assert.equal(response.status, 101, host) + assert.equal(response.echo, "sidecar-origin-check") + } + for (const origin of [LAN_HTTP, LOOPBACK_HTTPS, "https://foreign.test", "null", `http://127.0.0.1:${server.port}`]) { + assert.equal((await upgrade({ ...credentials, host: PUBLIC_HOST, origin })).status, 404, origin) + } + // Without an Origin the public Host qualifies, but the non-local source policy still refuses it. + assert.equal((await upgrade({ ...credentials, host: PUBLIC_HOST })).status, 403) + assert.equal((await upgrade({ host: PUBLIC_HOST, origin: PUBLIC })).status, 401) + assert.deepEqual(server.upgrades, ["/ws", "/ws"]) + } finally { await fs.rm(server.cleanupDirectory, { recursive: true, force: true }) } +}) + +it("a host edit of config.yaml revokes the opt-in on the next request, even after the display cache loaded it", async () => { + const server = await startDirectHttpsServer(true) + try { + const content = () => server.app.inject({ url: "/sidecars/fixture/token", remoteAddress: LAN_PEER, headers: { host: PUBLIC_HOST, cookie: server.cookie } }) + const upgrade = () => webSocketUpgrade(server.port, "/sidecars/fixture/ws", { cookie: server.cookie, host: PUBLIC_HOST, origin: PUBLIC }, true) + const admitted = async (expected: boolean, label: string) => { + assert.equal((await content()).statusCode, expected ? 200 : 404, `content: ${label}`) + assert.equal((await upgrade()).status, expected ? 101 : 404, `upgrade: ${label}`) + } + // The display cache holds `true` from here on, as any settings read would leave it. + assert.equal(server.settings!.getOwner("config", "server").sidecarsOverDirectHttps, true) + await admitted(true, "on") + await server.setOptIn(false) + assert.equal(server.settings!.getOwner("config", "server").sidecarsOverDirectHttps, true, "the display cache is stale by design") + await admitted(false, "host turned it off") + await server.setOptIn(true) + await admitted(true, "host turned it on again") + // Unreadable, invalid or missing documents read as off. + for (const [label, write] of [ + ["invalid YAML", () => server.host("server: [sidecarsOverDirectHttps: true\n")], + ["non-object server owner", () => server.host("server: true\n")], + ["a directory in its place", async () => { await fs.rm(server.configYamlPath); await fs.mkdir(server.configYamlPath) }], + ["missing", () => fs.rm(server.configYamlPath, { recursive: true })], + ] as const) { + await write() + await admitted(false, label) + } + await server.setOptIn(true) + await admitted(true, "restored") + } finally { await fs.rm(server.cleanupDirectory, { recursive: true, force: true }) } +}) + for (const skipAuth of [false, true]) { it(`SideCar WS enforces the shared source policy before any upstream connection (skip auth: ${skipAuth})`, async () => { const allowed = "https://ui.example.test:8443" diff --git a/packages/server/src/server/http-server.ts b/packages/server/src/server/http-server.ts index 86f7971f7c..f761d367b3 100644 --- a/packages/server/src/server/http-server.ts +++ b/packages/server/src/server/http-server.ts @@ -103,6 +103,7 @@ import { gateRemoteRequest, isHostOnlyPath, PAIR_EXCHANGE_PATH, PAIR_PAGE_PATH } import { isLocalRequest, isRemoteRequest } from "../remote-control/request-origin" import { registerDirectOriginPolicy } from "./direct-origin" import { verifiedDirectHttpsOrigin } from "../remote-control/direct-https" +import { createSideCarDirectHttpsAccess, isSideCarContentPath, sidecarsOverDirectHttpsEnabled } from "./sidecar-direct-https" import { framesNoBody } from "./bodiless-request" import { addProxiedHttpMethods } from "./proxied-http-methods" import { ROUTER_OPTIONS, routedPath } from "./routed-path" @@ -130,7 +131,6 @@ import { validatePromptAttachmentBudget } from "./prompt-attachment-budget" import { ProviderAccountsService, AccountSelectionFailed } from "../provider-accounts/service" import { registerProviderAccountsRoutes } from "./routes/provider-accounts" import { observeProviderQuotaFailures } from "../provider-accounts/quota-observer" -import { createOpenCodeFreeExhaustion } from "../usage/opencode-free-exhaustion" import { createOpenCodeFreeUsage } from "../usage/opencode-free-usage" import { deferPendingDiscovery, grantPendingReconciliation, PENDING_DISCOVERY_DEFERRED, PENDING_RECONCILIATION_HEADER } from "../workspaces/pending-discovery" @@ -185,6 +185,13 @@ export function shouldRetryPreferredPort(error: unknown, autoPortRequested: bool return code === "EADDRINUSE" || (platform === "win32" && code === "EACCES") } +// One boundary per application listener; plugin routes share this raw server. +const hostProxyTargets = new WeakMap boolean>() + +function blocksHostProxyTarget(server: object, target: URL): boolean { + return hostProxyTargets.get(server)?.(target) ?? true +} + export function createHttpServer(deps: HttpServerDeps) { // Fastify's type-level RawServer inference gets noisy when toggling HTTP vs HTTPS. // We keep the runtime behavior correct and cast the instance to a generic FastifyInstance. @@ -239,6 +246,10 @@ export function createHttpServer(deps: HttpServerDeps) { // Remote Control admission runs before CORS, authentication and routing. const remoteGate = deps.remoteControlManager.gate() + const sidecarOverDirectHttps = createSideCarDirectHttpsAccess({ + meta: deps.serverMeta, allowedOrigins: deps.allowedOrigins, enabled: () => sidecarsOverDirectHttpsEnabled(deps.settings), + }) + const requestGate = { ...remoteGate, allowsDirectSidecar: sidecarOverDirectHttps } const getSelfOrigins = (): Set => { const origins = new Set() for (const candidate of [deps.serverMeta.localUrl, deps.serverMeta.remoteUrl, ...(deps.serverMeta.addresses ?? []).map(address => address.remoteUrl)]) { @@ -246,9 +257,23 @@ export function createHttpServer(deps: HttpServerDeps) { } return origins } + hostProxyTargets.set(app.server, target => { + // A capability's exclusive origin must never be exposed through another proxy. + if (parsePreviewCapabilityHost(target.host)) return true + const pathname = routedPath(target.pathname) + if (pathname !== null && !pathname.startsWith("/api/") && pathname !== "/api" + && !pathname.startsWith("/workspaces/") && !isHostOnlyPath(pathname, "GET")) return false + const address = app.server.address() + const samePort = address && typeof address === "object" + && Number(target.port || (target.protocol === "https:" ? 443 : 80)) === address.port + const hostname = target.hostname.replace(/\.$/, "") + const loopback = isLoopbackHost(hostname) || isWildcardHost(hostname) || hostname.endsWith(".localhost") + return Boolean(samePort && loopback) || getSelfOrigins().has(target.origin) + || deps.allowedOrigins?.includes(target.origin) === true + }) app.addHook("onRequest", (request, reply, done) => { if (guardServerPairRequest(request, reply)) return - if (!gateRemoteRequest(request, reply, remoteGate)) done() + if (!gateRemoteRequest(request, reply, requestGate)) done() }) const isLivePreview = (request: FastifyRequest) => { @@ -267,7 +292,8 @@ export function createHttpServer(deps: HttpServerDeps) { if (pathname === null) return reply.header("connection", "close").code(400).send({ error: "Invalid request path" }) // Browser pairing also answers on verified direct HTTPS origins; its route rechecks the origin. const directPairing = pathname === PAIR_EXCHANGE_PATH && verifiedDirectHttpsOrigin(request, remoteGate?.directHttpsOrigins?.() ?? []) !== null - if (isHostOnlyPath(pathname, request.method, true) && !isLivePreview(request) && !directPairing) { + if (isHostOnlyPath(pathname, request.method, true) && !isLivePreview(request) + && !directPairing && !(isSideCarContentPath(pathname) && sidecarOverDirectHttps(request))) { return reply.header("connection", "close").code(404).send({ error: "Not found" }) } done() @@ -388,10 +414,9 @@ export function createHttpServer(deps: HttpServerDeps) { registerSettingsRoutes(app, { settings: deps.settings, logger: apiLogger, refreshLoginStart: () => loginStart.refresh(), withConfigLock: memory ? action => memory.withSettingsLock(action) : undefined }) const accounts = new ProviderAccountsService(deps.settings) - const freeExhaustion = createOpenCodeFreeExhaustion() - const freeUsage = createOpenCodeFreeUsage(freeExhaustion) - const stopQuotaObserver = observeProviderQuotaFailures(deps.eventBus, accounts, freeExhaustion.observe) - app.addHook("onClose", async () => { stopQuotaObserver(); freeExhaustion.dispose(); freeUsage.dispose() }) + const freeUsage = createOpenCodeFreeUsage() + const stopQuotaObserver = observeProviderQuotaFailures(deps.eventBus, accounts) + app.addHook("onClose", async () => { stopQuotaObserver(); freeUsage.dispose() }) registerProviderAccountsRoutes(app, { accounts, workspaceManager: deps.workspaceManager, worktreeDeletionFence }) registerOpenCodeUpdateRoutes(app, { service: createOpenCodeUpdateService(deps.settings, deps.workspaceManager, loginStart), @@ -402,7 +427,7 @@ export function createHttpServer(deps: HttpServerDeps) { registerFilesystemRoutes(app, { fileSystemBrowser: deps.fileSystemBrowser }) registerConfigFileRoutes(app) const remotePreviewsAllowed = () => deps.remoteControlManager.previewsAllowed() - registerMetaRoutes(app, { serverMeta: deps.serverMeta, remotePreviewsAllowed }) + registerMetaRoutes(app, { serverMeta: deps.serverMeta, remotePreviewsAllowed, sidecarsOverDirectHttps: sidecarOverDirectHttps }) registerEventRoutes(app, { eventBus: deps.eventBus, registerClient: registerSseClient, @@ -470,6 +495,7 @@ export function createHttpServer(deps: HttpServerDeps) { authManager: deps.authManager, logger: proxyLogger, allowsSource: request => allowsDirectSource({ raw: request, headers: request.headers }), + overDirectHttps: request => sidecarOverDirectHttps({ raw: request, method: request.method ?? "GET", headers: request.headers }), }) const previewUpgrade = setupPreviewWebSocketProxy(app, { previewManager: deps.previewManager, @@ -583,6 +609,8 @@ interface SideCarProxyDeps { interface SideCarWebSocketProxyDeps extends SideCarProxyDeps { allowsSource(request: import("http").IncomingMessage): boolean + /** The host's opt-in for non-local upgrades from a verified direct HTTPS origin. */ + overDirectHttps(request: import("http").IncomingMessage): boolean } interface PreviewProxyDeps { @@ -703,7 +731,7 @@ function setupSideCarWebSocketProxy(app: FastifyInstance, deps: SideCarWebSocket if (!parsed) { return } - if (!isLocalRequest({ raw: request })) { + if (!isLocalRequest({ raw: request }) && !deps.overDirectHttps(request)) { rejectUpgrade(socket as Socket, 404, "Not Found") return } @@ -723,6 +751,7 @@ function setupSideCarWebSocketProxy(app: FastifyInstance, deps: SideCarWebSocket sidecarManager: deps.sidecarManager, authManager: deps.authManager, logger: deps.logger, + server: app.server, }) }) } @@ -742,6 +771,7 @@ function setupPreviewWebSocketProxy(app: FastifyInstance, deps: PreviewWebSocket previewManager: deps.previewManager, authManager: deps.authManager, logger: deps.logger, + server: app.server, }) } app.server.on("upgrade", (request, socket, head) => { @@ -2156,6 +2186,9 @@ async function proxySideCarRequest(args: { const targetPath = args.sidecarManager.buildTargetPath(sidecarId, requestPath, search) const targetOrigin = args.sidecarManager.buildTargetOrigin(sidecar) const targetUrl = `${targetOrigin}${targetPath}` + if (blocksHostProxyTarget(args.request.server.server, new URL(targetUrl))) { + return args.reply.code(404).send({ error: "Not found" }) + } args.logger.debug({ sidecarId: sidecar.id, targetUrl, pathname, prefixMode: sidecar.prefixMode }, "Proxying request to SideCar") await proxyTargetRequest({ @@ -2254,6 +2287,9 @@ async function proxyPreviewTargetRequest(args: { errorMessage: string rewriteHeaders: (headers: Record) => Record }) { + if (blocksHostProxyTarget(args.request.server.server, new URL(args.targetUrl))) { + return args.reply.code(404).send({ error: "Not found" }) + } let responseKind: "html" | "css" | "js" | null = null const target = withoutQuery(args.targetUrl) await args.reply.from(target.url, { @@ -2359,6 +2395,7 @@ export function parsePreviewCapabilityHost(host: string | undefined): string | n } async function proxySideCarWebSocketUpgrade(args: { + server: object request: import("http").IncomingMessage socket: Socket head: Buffer @@ -2394,6 +2431,7 @@ async function proxySideCarWebSocketUpgrade(args: { logger.debug({ sidecarId, targetUrl: targetUrl.toString(), prefixMode: sidecar.prefixMode }, "Proxying websocket to SideCar") proxyTargetWebSocketUpgrade({ + server: args.server, request, socket, head, @@ -2406,6 +2444,7 @@ async function proxySideCarWebSocketUpgrade(args: { } async function proxyPreviewWebSocketUpgrade(args: { + server: object request: import("http").IncomingMessage socket: Socket head: Buffer @@ -2437,6 +2476,7 @@ async function proxyPreviewWebSocketUpgrade(args: { logger.debug({ previewToken: token, targetUrl: targetUrl.toString() }, "Proxying websocket to preview") proxyTargetWebSocketUpgrade({ + server: args.server, request, socket, head, @@ -2449,6 +2489,7 @@ async function proxyPreviewWebSocketUpgrade(args: { } function proxyTargetWebSocketUpgrade(args: { + server: object request: import("http").IncomingMessage socket: Socket head: Buffer @@ -2459,6 +2500,9 @@ function proxyTargetWebSocketUpgrade(args: { stripCookies?: boolean sessionCookie?: string }) { + if (blocksHostProxyTarget(args.server, args.targetUrl)) { + return rejectUpgrade(args.socket, 404, "Not Found") + } const headers = sanitizeSideCarProxyRequestHeaders(args.request.headers, args.targetUrl.origin, args.sessionCookie) if (args.stripCookies) delete headers.cookie proxyWebSocket({ ...args, headers, responseHeaders: incoming => { diff --git a/packages/server/src/server/network-policy.test.ts b/packages/server/src/server/network-policy.test.ts new file mode 100644 index 0000000000..4d5765833d --- /dev/null +++ b/packages/server/src/server/network-policy.test.ts @@ -0,0 +1,67 @@ +import assert from "node:assert/strict" +import { spawn } from "node:child_process" +import { mkdtemp, rm } from "node:fs/promises" +import os from "node:os" +import path from "node:path" +import test, { type TestContext } from "node:test" +import { fileURLToPath } from "node:url" + +const entry = fileURLToPath(new URL("../index.ts", import.meta.url)) + +// The real entry point as a standalone server with an administrator policy in its environment. +async function launch(t: TestContext, policy: Record, args: string[]) { + const root = await mkdtemp(path.join(os.tmpdir(), "codenomad-network-policy-")) + const env: NodeJS.ProcessEnv = {} + for (const [key, value] of Object.entries(process.env)) if (!/^(CODENOMAD_|CLI_|OPENCODE_|XDG_)/i.test(key)) env[key] = value + Object.assign(env, { HOME: root, USERPROFILE: root, APPDATA: root, LOCALAPPDATA: root, XDG_RUNTIME_DIR: root, XDG_CONFIG_HOME: root }, policy) + const child = spawn(process.execPath, ["--import", "tsx", entry, ...args, "--config", path.join(root, "config", "config.yaml"), + "--workspace-root", root, "--ui-no-update", "--dangerously-skip-auth"], { cwd: path.dirname(entry), env, stdio: ["pipe", "pipe", "pipe"], windowsHide: true }) + let output = "" + child.stdout.on("data", chunk => { output += chunk }) + child.stderr.on("data", chunk => { output += chunk }) + const exited = new Promise(resolve => child.once("exit", code => resolve(code))) + t.after(async () => { + if (child.exitCode === null) child.kill() + await exited + await rm(root, { recursive: true, force: true }) + }) + return { child, exited, output: () => output } +} + +test("an administrator policy locks the listening address and disables Remote Control in the real server", { timeout: 90_000 }, async t => { + const server = await launch(t, { CODENOMAD_LOCKED_HOST: "127.0.0.1", CODENOMAD_REMOTE_CONTROL: "disabled" }, + ["--host", "0.0.0.0", "--https", "false", "--http", "true", "--http-port", "0"]) + const deadline = Date.now() + 60_000 + let announced: RegExpExecArray | null + while (!(announced = /Local Connection URL : http:\/\/(.+):(\d+)/.exec(server.output()))) { + assert.ok(server.child.exitCode === null, `server exited early:\n${server.output()}`) + assert.ok(Date.now() < deadline, `server did not start:\n${server.output()}`) + await new Promise(resolve => setTimeout(resolve, 100)) + } + // --host 0.0.0.0 was requested; the administrator's loopback address is what listens. + assert.equal(announced[1], "127.0.0.1") + const base = `http://127.0.0.1:${announced[2]}` + const meta = await (await fetch(`${base}/api/meta`)).json() as { host: string; listeningMode: string; listeningLocked?: boolean } + assert.deepEqual({ host: meta.host, listeningMode: meta.listeningMode, listeningLocked: meta.listeningLocked }, + { host: "127.0.0.1", listeningMode: "local", listeningLocked: true }) + + const start = await fetch(`${base}/api/remote-control/start`, { method: "POST" }) + assert.equal(start.status, 403) + assert.deepEqual(await start.json(), { error: "Remote Control is disabled by the administrator", code: "remote_control_disabled" }) + const status = await (await fetch(`${base}/api/remote-control/status`)).json() as { disabledByAdministrator?: boolean; state: string } + assert.deepEqual({ disabled: status.disabledByAdministrator, state: status.state }, { disabled: true, state: "stopped" }) + + server.child.stdin.write("codenomad:shutdown\n") + assert.equal(await server.exited, 0, server.output()) +}) + +for (const [name, value, message] of [["CODENOMAD_REMOTE_CONTROL", "off", /CODENOMAD_REMOTE_CONTROL accepts only "disabled"/], + ["CODENOMAD_REMOTE_CONTROL", " \t ", /CODENOMAD_REMOTE_CONTROL accepts only "disabled"/], + ["CODENOMAD_LOCKED_HOST", " ", /CODENOMAD_LOCKED_HOST must be an address/]] as const) { + test(`${name}=${JSON.stringify(value)} refuses startup`, { timeout: 90_000 }, async t => { + const server = await launch(t, { [name]: value }, ["--https", "false", "--http", "true", "--http-port", "0"]) + assert.notEqual(await server.exited, 0) + assert.match(server.output(), message) + assert.doesNotMatch(server.output(), /Local Connection URL/) + }) +} diff --git a/packages/server/src/server/network-policy.ts b/packages/server/src/server/network-policy.ts new file mode 100644 index 0000000000..883bc1197b --- /dev/null +++ b/packages/server/src/server/network-policy.ts @@ -0,0 +1,31 @@ +/** + * Administrator network policy, read from the environment the backend inherits (machine-wide + * variables reach every desktop launch). Users cannot change it from the UI, and an unknown value + * refuses startup rather than leaving a feature open. + * + * - `CODENOMAD_REMOTE_CONTROL=disabled`: Remote Control never connects a tunnel or pairs a device. + * - `CODENOMAD_LOCKED_HOST=
`: the listening address, whatever `--host` or the listening + * switch request (an intranet address for shared use, `127.0.0.1` for this machine only). + */ +export interface NetworkPolicy { + remoteControlDisabled: boolean + /** Raw administrator address; resolved and validated like `--host`. */ + lockedHost?: string +} + +export class NetworkPolicyError extends Error { + override readonly name = "NetworkPolicyError" +} + +export function readNetworkPolicy(env: NodeJS.ProcessEnv = process.env): NetworkPolicy { + // Only an unset or exactly empty variable means "no policy"; anything else, whitespace included, must be valid. + const remoteControl = env.CODENOMAD_REMOTE_CONTROL ?? "" + if (remoteControl !== "" && remoteControl.trim().toLowerCase() !== "disabled") { + throw new NetworkPolicyError("CODENOMAD_REMOTE_CONTROL accepts only \"disabled\"") + } + const lockedHost = env.CODENOMAD_LOCKED_HOST ?? "" + if (lockedHost !== "" && lockedHost.trim() === "") { + throw new NetworkPolicyError("CODENOMAD_LOCKED_HOST must be an address") + } + return { remoteControlDisabled: remoteControl !== "", ...(lockedHost ? { lockedHost: lockedHost.trim() } : {}) } +} diff --git a/packages/server/src/server/routes/config-files.ts b/packages/server/src/server/routes/config-files.ts index d1854966bd..0ac398e5f6 100644 --- a/packages/server/src/server/routes/config-files.ts +++ b/packages/server/src/server/routes/config-files.ts @@ -60,6 +60,12 @@ function defaultConfigFileEntries(): ConfigFileEntry[] { return resolveOpenCodeGlobalConfigPaths() } +/** Exact inventory membership only; a supplied path never grants file access. */ +export function configFileEditorID(filePath: string): string | undefined { + const same = (value: string) => process.platform === "win32" ? path.normalize(value).toLowerCase() : path.normalize(value) + return defaultConfigFileEntries().find(file => same(file.absolutePath) === same(filePath))?.id +} + function listConfigFiles(files: ConfigFileEntry[]): ConfigFileDescriptor[] { return files.map(({ absolutePath: _absolutePath, ...file }) => file) } diff --git a/packages/server/src/server/routes/integrations.test.ts b/packages/server/src/server/routes/integrations.test.ts index 19b6e49e42..90d69f3387 100644 --- a/packages/server/src/server/routes/integrations.test.ts +++ b/packages/server/src/server/routes/integrations.test.ts @@ -66,13 +66,14 @@ describe("integrations route", () => { assert.deepEqual(body.integrations[0]!.configuredSources, [{ scope: "global", entryIndex: 0, expectedRevision: "a".repeat(64) }]) assert.deepEqual(body.integrations[1]!.configuredSources, [], "only the scope's writable target is correlated") assert.deepEqual(body.integrations.map(item => item.plugin), [ - { declared: true, runtime: "loaded" }, { declared: true, runtime: "loaded" }, { declared: false }, + { declared: true, runtime: "loaded", runtimeId: "neuralnomads.fixture" }, + { declared: true, runtime: "loaded", runtimeId: "neuralnomads.slow" }, { declared: false }, ]) assert.deepEqual(body.integrations.map(item => item.ambiguous), [undefined, undefined, undefined]) assert.deepEqual(body.ambiguousSources, []) assert.equal(body.integrations[0]!.docs, "https://github.com/NeuralNomadsAI/opencode-integrations/tree/main/integrations/fixture") for (const field of ["rpc", "sources", "package"]) assert.equal(field in body.integrations[0]!, false, `${field} stays on the server`) - assert.equal(JSON.stringify(body).includes("neuralnomads."), false, "plugin and RPC IDs stay on the server") + assert.deepEqual(Object.keys(body.integrations[0]!.plugin), ["declared", "runtime", "runtimeId"]) assert.equal(JSON.stringify(body.integrations).includes("/config/"), false, "configuration paths stay on the server") assert.equal(JSON.stringify(body.integrations).includes("@neuralnomads/"), false, "source specs stay on the server") assert.deepEqual(calls.map(call => [call.rpcID, call.method, call.input, call.location]), @@ -108,8 +109,9 @@ describe("integrations route", () => { const { app, calls } = harness({ snapshot: () => snapshot, ...(kind === "marker-mismatch" ? { status: { contract: 1, integration: { id: "fixture-other", version: "0.1.0", family: "native", spec: 0 } } } : {}) }) const item = (await app.inject({ method: "GET", url: "/api/workspaces/w1/integrations?directory=%2Fwork" })).json().integrations[0] - assert.deepEqual(item.plugin, kind === "rule" || kind === "runtime-only" ? kind === "rule" ? { declared: false } : { declared: false, runtime: "loaded" } - : { declared: true, ...(kind === "ambiguous" ? {} : { runtime: kind === "failed" ? "failed" : "loaded" }) }, kind) + assert.deepEqual(item.plugin, { declared: kind !== "rule" && kind !== "runtime-only", + ...(kind === "rule" || kind === "ambiguous" ? {} : { runtime: kind === "failed" ? "failed" : "loaded" }), + ...(kind === "runtime-only" || kind === "marker-mismatch" ? { runtimeId: "neuralnomads.fixture" } : {}) }, kind) assert.equal(item.configured, true, kind) assert.equal(item.ambiguous, kind === "ambiguous" ? true : undefined, kind) assert.equal(item.state, kind === "rule" ? "inactive" : kind === "failed" ? "failed" @@ -119,6 +121,23 @@ describe("integrations route", () => { } }) + it("projects the recognized runtime ID for inherited, virtual and runtime-only display independently of writable authority", async () => { + for (const origin of ["other", "virtual", "runtime-only"] as const) { + const snapshot = loadedSnapshot() + snapshot.runtime = [{ ...snapshot.runtime[0]!, id: "acme.render" }] + snapshot.configured.sources = origin === "runtime-only" ? [] : [{ ...snapshot.configured.sources[0]!, + pluginId: "acme.render", scope: origin, path: origin === "other" ? "/ancestor/opencode.jsonc" : undefined }] + const { app } = harness({ snapshot: () => snapshot, catalog: { state: "fresh", + catalog: catalogOf(catalogEntry("fixture", { plugin: "acme.render" })) } }) + const item = (await app.inject({ method: "GET", url: "/api/workspaces/w1/integrations?directory=%2Fwork" })).json().integrations[0] + assert.equal(item.state, "ok") + assert.deepEqual(item.plugin, { declared: origin !== "runtime-only", runtime: "loaded", runtimeId: "acme.render" }) + assert.deepEqual(item.configuredSources, []) + assert.deepEqual(item.configuredRules, []) + await app.close() + } + }) + it("correlates only the writable activation rules of a non-ambiguous integration's plugin", async () => { const snapshot = loadedSnapshot() snapshot.configured.rules = [ diff --git a/packages/server/src/server/routes/meta-contract.test.ts b/packages/server/src/server/routes/meta-contract.test.ts index 69d9985f47..6cd15fcd24 100644 --- a/packages/server/src/server/routes/meta-contract.test.ts +++ b/packages/server/src/server/routes/meta-contract.test.ts @@ -43,9 +43,10 @@ test("metadata identity persists across HTTP server restarts and separates confi assert.deepEqual(meta.capabilities, ["workspaces", "workspace-files", "workspace-git", "events"]) assert.match(meta.serverId, /^[0-9a-f-]{36}$/) assert.equal(meta.localRequest, true) + assert.equal(meta.sidecarsAllowed, true) assert.deepEqual(Object.keys(meta).sort(), [ "serverId", "apiContract", "capabilities", "localUrl", "eventsUrl", "host", "listeningMode", - "localPort", "hostLabel", "workspaceRoot", "addresses", "system", "localRequest", + "localPort", "hostLabel", "workspaceRoot", "addresses", "system", "localRequest", "sidecarsAllowed", ].sort()) return meta.serverId as string } finally { await app.close() } diff --git a/packages/server/src/server/routes/meta.ts b/packages/server/src/server/routes/meta.ts index 3ab9e6827a..dd63d2a908 100644 --- a/packages/server/src/server/routes/meta.ts +++ b/packages/server/src/server/routes/meta.ts @@ -1,4 +1,4 @@ -import { FastifyInstance } from "fastify" +import type { FastifyInstance, FastifyRequest } from "fastify" import { ServerMeta } from "../../api-types" import { isLocalRequest, isRemoteRequest } from "../../remote-control/request-origin" import { isLoopbackHost, isWildcardHost } from "../network-host" @@ -8,12 +8,15 @@ interface RouteDeps { serverMeta: ServerMeta /** Whether the host lets Remote Control serve web previews. */ remotePreviewsAllowed: () => boolean + /** Whether a non-local request may open SideCars (the host's direct HTTPS opt-in). */ + sidecarsOverDirectHttps?: (request: FastifyRequest) => boolean } export function registerMetaRoutes(app: FastifyInstance, deps: RouteDeps) { app.get("/api/meta", async (request) => ({ ...buildMetaResponse(deps.serverMeta), localRequest: isLocalRequest(request), + sidecarsAllowed: isLocalRequest(request) || deps.sidecarsOverDirectHttps?.(request) === true, ...(isRemoteRequest(request) && !deps.remotePreviewsAllowed() ? { previewsUnavailable: true as const } : {}), })) } diff --git a/packages/server/src/server/routes/mission-schedule-activation-refusal.test.ts b/packages/server/src/server/routes/mission-schedule-activation-refusal.test.ts new file mode 100644 index 0000000000..3d00dd063b --- /dev/null +++ b/packages/server/src/server/routes/mission-schedule-activation-refusal.test.ts @@ -0,0 +1,24 @@ +import assert from "node:assert/strict" +import os from "node:os" +import path from "node:path" +import test from "node:test" +import { NativeScheduleActivationRefused } from "../../opencode/native-schedule-settings-activation" +import { missionScheduleActivationRefusal } from "./mission-schedule-activation-refusal" + +test("refusal exposes editor actions only for exact existing global inventory membership", () => { + for (const extension of ["json", "jsonc"]) { + const file = path.join(os.homedir(), ".config", "opencode", `opencode.${extension}`) + const refusal = missionScheduleActivationRefusal(new NativeScheduleActivationRefused({ + reason: "explicit-off", provenance: "experimental-block", layer: "global", path: file })) + assert.equal(refusal?.openable, true) + assert.equal(refusal?.configFileID, extension === "json" ? "opencode-global-config" : "opencode-global-config-jsonc") + } + for (const file of [path.resolve("project/.opencode/opencode.jsonc"), "/remote/config/opencode.json"]) { + const refusal = missionScheduleActivationRefusal(new NativeScheduleActivationRefused({ + reason: "explicit-off", provenance: "experimental-block", layer: "inherited", path: file })) + assert.equal(refusal?.openable, false); assert.equal(refusal?.configFileID, undefined) + } + assert.deepEqual(missionScheduleActivationRefusal(new NativeScheduleActivationRefused({ + reason: "explicit-off", provenance: "environment", layer: "environment" })), + { reason: "explicit-off", provenance: "environment", layer: "environment", openable: false }) +}) diff --git a/packages/server/src/server/routes/mission-schedule-activation-refusal.ts b/packages/server/src/server/routes/mission-schedule-activation-refusal.ts new file mode 100644 index 0000000000..5d2767d8d4 --- /dev/null +++ b/packages/server/src/server/routes/mission-schedule-activation-refusal.ts @@ -0,0 +1,8 @@ +import { NativeScheduleActivationRefused } from "../../opencode/native-schedule-settings-activation" +import { configFileEditorID } from "./config-files" + +export function missionScheduleActivationRefusal(error: unknown) { + if (!(error instanceof NativeScheduleActivationRefused)) return undefined + const configFileID = error.refusal.path && configFileEditorID(error.refusal.path) + return { ...error.refusal, openable: Boolean(configFileID), ...(configFileID ? { configFileID } : {}) } +} diff --git a/packages/server/src/server/routes/mission-schedule-activation.test.ts b/packages/server/src/server/routes/mission-schedule-activation.test.ts index 7317ddc98a..e3acb5ffc1 100644 --- a/packages/server/src/server/routes/mission-schedule-activation.test.ts +++ b/packages/server/src/server/routes/mission-schedule-activation.test.ts @@ -19,7 +19,7 @@ async function fixture(run: (f: any) => Promise) { const global = path.join(root, "global"), project = path.join(root, "project") await mkdir(global); await mkdir(project) const globalFile = path.join(global, "opencode.jsonc"), projectFile = path.join(project, "opencode.jsonc") - await writeFile(globalFile, '{"experimental":{"schedules":false,"subagent_depth":2},"private":"must-stay-out-of-document"}') + await writeFile(globalFile, '{"experimental":{"subagent_depth":2},"private":"must-stay-out-of-document"}') await writeFile(projectFile, '{"experimental":{"subagent_depth":8}}') const values = new Map(), phases: string[] = [] const documents = new NativeMissionDocumentStore({ get: async key => structuredClone(values.get(key)), @@ -36,16 +36,21 @@ async function fixture(run: (f: any) => Promise) { launch: { timing: { kind: "every", intervalMs: 900_000 }, condition: null, ends: { at: null, afterMs: null, maxLaunches: null } }, }, Date.now(), () => true) let owned = true, current = true, lose = false + let afterPhase: ((action: string) => Promise) | undefined const connection: any = { endpoint: { url: "http://127.0.0.1:1234" }, assertCurrent() { if (!current) throw Error("retired") }, fetch: async () => Response.json(nativeScheduleContractFixture()), client: { location: { get: async () => ({ directory: project, project: { id: "project", canonical: project, directory: project } }) }, plugin: { list: async () => ({ data: [{ id: "codenomad.missions", state: { status: "active" } }] }) }, config: { get: async () => [{ type: "document", path: globalFile, info: parse(await readFile(globalFile, "utf8")) }, { type: "directory", path: global }, { type: "document", path: projectFile, info: parse(await readFile(projectFile, "utf8")) }] }, - rpc: () => ({ documentCapabilities: async () => ({ version: 1 }), documentActivation: async (input: any) => { + rpc: () => ({ documentCapabilities: async () => ({ version: 1 }), + scheduleFlag: async () => ({ enabled: parse(await readFile(projectFile, "utf8")).experimental?.schedules === true, + provenance: parse(await readFile(projectFile, "utf8")).experimental?.schedules === undefined ? "channel-default" : "experimental-block" }), + documentActivation: async (input: any) => { phases.push(input.action) const result = await applyMissionDocumentActivation(documents, input, () => true, project) - if (lose && input.action === "acknowledged" && input.scope === "global") { lose = false; throw Error("lost native reply") } + await afterPhase?.(input.action) + if (lose && input.action === "acknowledged" && input.scope === "project") { lose = false; throw Error("lost native reply") } return result } }), } } @@ -62,18 +67,19 @@ async function fixture(run: (f: any) => Promise) { const url = "/api/workspaces/w/missions/msn_scheduled/schedule-settings" const headers = { authorization: "Bearer fixture" }, payload = { requestID: "activate-original", expectedDocumentRevision: 0 } try { await run({ app, url, headers, payload, documents, values, phases, globalFile, projectFile, + afterPhase: (callback: typeof afterPhase) => { afterPhase = callback }, owned: (value: boolean) => { owned = value }, current: (value: boolean) => { current = value }, lose: () => { lose = true } }) } finally { await app.close(); await chmod(globalFile, 0o600).catch(() => {}); await rm(root, { recursive: true, force: true }) } } -test("HTTP preparation composes actual durable RPC phases with both config effects and keeps the mission paused", async () => fixture(async f => { +test("HTTP preparation composes durable RPC phases with only the project effect and keeps the mission paused", async () => fixture(async f => { const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) assert.equal(response.statusCode, 200, response.body) const doc = response.json().document assert.equal(doc.state, "paused"); assert.equal(doc.firstPlayedAt, null); assert.equal(doc.launchedCount, 0) assert.equal(doc.scheduleActivation.state, "ready") assert.ok(doc.scheduleActivation.targets.every((target: any) => target.attempted && target.acknowledged)) - assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).experimental, { schedules: true, subagent_depth: 2 }) + assert.deepEqual(parse(await readFile(f.globalFile, "utf8")).experimental, { subagent_depth: 2 }) assert.deepEqual(parse(await readFile(f.projectFile, "utf8")).experimental, { subagent_depth: 8, schedules: true }) assert.ok(!JSON.stringify([...f.values]).includes("must-stay-out-of-document")) const repeat = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) @@ -85,20 +91,99 @@ test("HTTP preparation composes actual durable RPC phases with both config effec assert.equal(JSON.stringify([...f.values]), before, "status is read-only") })) -test("lost native acknowledgement exposes a partial intention and explicit same-request reconciliation finishes only the remaining write", async () => fixture(async f => { +test("lost native acknowledgement retains the original intention and exact reconciliation only observes its project write", async () => fixture(async f => { f.lose() const first = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) assert.equal(first.statusCode, 503) const partial = await f.documents.read("msn_scheduled") assert.equal(partial.state, "paused"); assert.equal(partial.scheduleActivation.state, "failed") assert.equal(partial.scheduleActivation.targets[0].acknowledged, true) - assert.equal(partial.scheduleActivation.targets[1].attempted, false) - assert.equal(parse(await readFile(f.projectFile, "utf8")).experimental.schedules, undefined) + assert.equal(partial.scheduleActivation.targets.length, 1) + assert.equal(parse(await readFile(f.projectFile, "utf8")).experimental.schedules, true) const retry = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) assert.equal(retry.statusCode, 200, retry.body) assert.equal(retry.json().document.scheduleActivation.state, "ready") })) +test("already ON creates an empty ready proof and a fresh preparation preserves it read-only", async () => fixture(async f => { + await writeFile(f.projectFile, '{"experimental":{"schedules":true,"todo":true}}') + const original = await readFile(f.projectFile, "utf8") + const first = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(first.statusCode, 200, first.body) + const before = first.json().document + assert.equal(before.scheduleActivation.state, "ready") + assert.deepEqual(before.scheduleActivation.targets, []) + const next = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, + payload: { requestID: "fresh-request", expectedDocumentRevision: before.revision } }) + assert.equal(next.statusCode, 200, next.body) + assert.deepEqual(next.json().document, before) + assert.equal(await readFile(f.projectFile, "utf8"), original) + await writeFile(f.projectFile, '{"experimental":{"schedules":false}}') + const refused = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(refused.statusCode, 403, refused.body) + assert.equal(refused.json().code, "schedule-activation-refused") + assert.equal(refused.json().notApplied, undefined, "the ready original identity remains retained") + assert.deepEqual((await f.documents.read("msn_scheduled")).scheduleActivation, before.scheduleActivation) +})) + +test("an explicit hidden global OFF returns its layer/path without editor authorization or writes", async () => fixture(async f => { + await writeFile(f.globalFile, '{"experimental":{"schedules":false}}') + await writeFile(f.projectFile, '{"experimental":{"schedules":true}}') + const before = await f.documents.read("msn_scheduled") + const files = await Promise.all([f.globalFile, f.projectFile].map(file => readFile(file, "utf8"))) + const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(response.statusCode, 403, response.body) + assert.equal(response.json().code, "schedule-activation-refused") + assert.deepEqual(response.json().refusal, { reason: "explicit-off", provenance: "experimental-block", + layer: "global", path: f.globalFile, openable: false }) + assert.deepEqual(response.json().notApplied, { requestID: f.payload.requestID, expectedRevision: 0 }) + assert.deepEqual(await f.documents.read("msn_scheduled"), before) + assert.deepEqual(f.phases, ["read"], "no mutation is attempted for a definitive refusal") + assert.deepEqual(await Promise.all([f.globalFile, f.projectFile].map(file => readFile(file, "utf8"))), files) + await writeFile(f.globalFile, '{"experimental":{"subagent_depth":2}}') + const next = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, + payload: { requestID: "explicit-after-correction", expectedDocumentRevision: 0 } }) + assert.equal(next.statusCode, 200, next.body) + assert.equal(next.json().document.state, "paused") +})) + +test("OFF after intent preparation and on its exact retry retains uncertainty without no-effect proof", async () => fixture(async f => { + f.afterPhase(async (action: string) => { + if (action === "prepare") await writeFile(f.projectFile, '{"experimental":{"schedules":false}}') + }) + const response = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(response.statusCode, 403, response.body) + assert.equal(response.json().code, "schedule-activation-refused") + assert.equal(response.json().notApplied, undefined) + const doc = await f.documents.read("msn_scheduled") + assert.equal(doc.scheduleActivation.requestID, f.payload.requestID) + assert.equal(doc.scheduleActivation.state, "failed") + const retry = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(retry.statusCode, 403, retry.body) + assert.equal(retry.json().notApplied, undefined) +})) + +test("a ready legacy two-target proof retains its original identity and digests on fresh preparation", async () => fixture(async f => { + await writeFile(f.globalFile, '{"experimental":{"schedules":true}}') + await writeFile(f.projectFile, '{"experimental":{"schedules":true}}') + const first = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, payload: f.payload }) + assert.equal(first.statusCode, 200, first.body) + const doc = await f.documents.read("msn_scheduled") + const legacy = await f.documents.change(doc.id, doc.revision, () => true, (next: any) => { + next.scheduleActivation.targets = [ + { scope: "global", path: f.globalFile }, { scope: "project", path: f.projectFile }, + ].map(target => ({ ...target, expectation: "a".repeat(64), resultDigest: "b".repeat(64), attempted: true, acknowledged: true })) + }) + const global = await readFile(f.globalFile, "utf8"), project = await readFile(f.projectFile, "utf8") + const refreshed = await f.app.inject({ method: "POST", url: f.url, headers: f.headers, + payload: { requestID: "new-ready-verification", expectedDocumentRevision: legacy.revision } }) + assert.equal(refreshed.statusCode, 200, refreshed.body) + assert.deepEqual(refreshed.json().document.scheduleActivation, legacy.scheduleActivation) + assert.equal(refreshed.json().document.revision, legacy.revision) + assert.equal(await readFile(f.globalFile, "utf8"), global) + assert.equal(await readFile(f.projectFile, "utf8"), project) +})) + test("route ownership, authentication, revision and input boundaries refuse before any config effect", async () => fixture(async f => { const before = await readFile(f.globalFile, "utf8") assert.equal((await f.app.inject({ method: "POST", url: f.url, payload: f.payload })).statusCode, 401) diff --git a/packages/server/src/server/routes/mission-schedule-activation.ts b/packages/server/src/server/routes/mission-schedule-activation.ts index 5dd43fa024..a213e01fca 100644 --- a/packages/server/src/server/routes/mission-schedule-activation.ts +++ b/packages/server/src/server/routes/mission-schedule-activation.ts @@ -7,11 +7,12 @@ import { PluginControlsError } from "../../opencode/plugin-controls" import { requestAdmission } from "../request-admission" import { MissionMapMutationError, prepareMissionMapMutation, type MissionMapMutationManager } from "./mission-map-mutation" import { missionScheduleActivationJournal } from "./mission-schedule-activation-journal" +import { missionScheduleActivationRefusal } from "./mission-schedule-activation-refusal" const params = z.object({ id: z.string().min(1).max(200), missionID: z.string().regex(/^[A-Za-z0-9_-]{3,100}$/) }).strict() const identity = z.object({ requestID: z.string().min(1).max(128), expectedDocumentRevision: z.number().int().nonnegative().safe() }).strict() type Deps = { workspaceManager: MissionMapMutationManager; worktreeDeletionFence?: WorktreeDeletionFence; - scheduleSettingsActivation?: Pick } + scheduleSettingsActivation?: Pick } /** Authenticated preparation only. The calendar owner performs Play/arming after * its own complete capability, admission and fresh effective-setting checks. */ @@ -25,11 +26,13 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De ? { ...raw, expectedDocumentRevision: Number((raw as Record).expectedDocumentRevision) } : raw) if (!selected.success || !input.success) return reply.code(400).send({ error: "Invalid Mission activation request" }) const lifetime = requestAdmission(request, reply) + let noEffect = false try { const owned = await prepareMissionMapMutation({ manager: deps.workspaceManager, fence: deps.worktreeDeletionFence, workspaceID: selected.data.id, signal: lifetime.signal, wait: lifetime.wait }) return await owned.run(async (rpc, options) => { const guarded = { documentActivation: async (...args: Parameters) => { + if ((args[0] as { action?: unknown } | undefined)?.action !== "read") noEffect = false await owned.refresh() return rpc.documentActivation(...args) } } @@ -41,6 +44,14 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De return reply.code(409).send({ error: "Mission schedule preparation unavailable", code: "schedule-activation-unavailable" }) const previous = before.scheduleActivation const same = previous?.requestID === input.data.requestID && previous.expectedRevision === input.data.expectedDocumentRevision + noEffect = !same + if (previous?.state === "ready" && (same || before.revision === input.data.expectedDocumentRevision)) { + await deps.scheduleSettingsActivation.verify(selected.data.id, options.location, previous.authority) + await owned.refresh() + const after = await adapter.read() + if (after.revision !== before.revision) throw new PluginControlsError("Mission activation changed during verification", "conflict") + return { document: after } + } if (!same && (before.revision !== input.data.expectedDocumentRevision || previous && (previous.state !== "failed" || previous.targets.some(target => target.attempted)))) return reply.code(409).send({ error: "Original Mission activation remains unresolved", code: "schedule-activation-conflict" }) @@ -54,6 +65,7 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De await deps.scheduleSettingsActivation.apply(selected.data.id, options.location, intent, adapter.journal) return { document: await adapter.read() } } catch (error) { + if (noEffect && missionScheduleActivationRefusal(error)) throw error const code = error instanceof PluginControlsError ? `configuration-${error.kind}` : "configuration-unconfirmed" // This records metadata only. Attempt markers and successful writes // survive failure; an uncertain target is never rolled back/replayed. @@ -64,7 +76,10 @@ export function registerMissionScheduleActivation(app: FastifyInstance, deps: De } catch (error) { const status = error instanceof MissionMapMutationError ? error.status : error instanceof PluginControlsError ? error.kind === "forbidden" ? 403 : error.kind === "invalid" ? 400 : error.kind === "conflict" ? 409 : 503 : 503 - return reply.code(status).send({ error: "Mission schedule configuration remains unconfirmed", code: "schedule-activation-pending" }) + const refusal = missionScheduleActivationRefusal(error) + return reply.code(status).send({ error: "Mission schedule configuration remains unconfirmed", + code: refusal ? "schedule-activation-refused" : "schedule-activation-pending", ...(refusal ? { refusal, + ...(noEffect ? { notApplied: { requestID: input.data.requestID, expectedRevision: input.data.expectedDocumentRevision } } : {}) } : {}) }) } finally { lifetime.dispose() } }, }) diff --git a/packages/server/src/server/routes/mission-schedule-list.test.ts b/packages/server/src/server/routes/mission-schedule-list.test.ts index 30f64e09dd..afea6ec9c8 100644 --- a/packages/server/src/server/routes/mission-schedule-list.test.ts +++ b/packages/server/src/server/routes/mission-schedule-list.test.ts @@ -2,7 +2,7 @@ import assert from "node:assert/strict" import test from "node:test" import Fastify from "fastify" import { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" -import { PluginControlsError } from "../../opencode/plugin-controls" +import { NativeScheduleActivationRefused } from "../../opencode/native-schedule-settings-activation" import { registerMissionScheduleList } from "./mission-schedule-list" async function fixture(t: test.TestContext) { @@ -25,7 +25,8 @@ async function fixture(t: test.TestContext) { enabled: state.enabled, origin: "/config/opencode.jsonc" }) }, scheduleSettingsActivation: { prepare: async () => { calls.push("prepare-read-only"); state.prepare?.() - if (state.forbidden) throw new PluginControlsError("Explicit project OFF", "forbidden") + if (state.forbidden) throw new NativeScheduleActivationRefused({ reason: "explicit-off", provenance: "experimental-block", + layer: "project", path: "/project/opencode.jsonc" }) return { authority: "a".repeat(64), targets: [{ scope: "project", path: "/project/opencode.jsonc", expectation: "secret-expectation", resultDigest: "secret-result" }] } } }, } as never) @@ -57,6 +58,9 @@ test("capability distinguishes missing API, activable OFF and explicit refusal w f.state.forbidden = true response = await f.get("", true) assert.equal(response.json().activation.reason, "forbidden") + assert.equal(response.json().activation.code, "schedule-activation-refused") + assert.deepEqual(response.json().activation.refusal, { reason: "explicit-off", provenance: "experimental-block", + layer: "project", path: "/project/opencode.jsonc", openable: false }) f.state.api = false response = await f.get("", true) assert.equal(response.json().api.reason, "missing-api") diff --git a/packages/server/src/server/routes/mission-schedule-list.ts b/packages/server/src/server/routes/mission-schedule-list.ts index 66cf8551a4..4488872f42 100644 --- a/packages/server/src/server/routes/mission-schedule-list.ts +++ b/packages/server/src/server/routes/mission-schedule-list.ts @@ -8,6 +8,7 @@ import { PluginControlsError } from "../../opencode/plugin-controls" import type { WorktreeDeletionFence } from "../../workspaces/worktree-session-evacuation" import { requestAdmission } from "../request-admission" import { MissionMapMutationError, prepareMissionMapMutation, type MissionMapMutationManager } from "./mission-map-mutation" +import { missionScheduleActivationRefusal } from "./mission-schedule-activation-refusal" const params = z.object({ id: z.string().min(1).max(200) }).strict() const directory = z.string().min(1).max(4096).refine(value => !value.includes("\0")).optional() @@ -48,7 +49,9 @@ export function registerMissionScheduleList(app: FastifyInstance, deps: Deps) { const plan = await lifetime.wait(deps.scheduleSettingsActivation.prepare(selected.data.id, owned.location)) activation = { available: true, targets: plan.targets.map(({ path, scope }) => ({ path, scope })) } } catch (error) { - activation = { available: false, reason: error instanceof PluginControlsError ? error.kind : "unavailable", targets: [] } + const refusal = missionScheduleActivationRefusal(error) + activation = { available: false, reason: error instanceof PluginControlsError ? error.kind : "unavailable", targets: [], + ...(refusal ? { code: "schedule-activation-refused", refusal } : {}) } } } await owned.refresh() diff --git a/packages/server/src/server/routes/missions.ts b/packages/server/src/server/routes/missions.ts index a86f2581a4..f2d1146822 100644 --- a/packages/server/src/server/routes/missions.ts +++ b/packages/server/src/server/routes/missions.ts @@ -37,7 +37,7 @@ import type { NativeScheduleCapabilityReader } from "../../opencode/native-sched interface MissionRouteDeps { scheduleCapability?: Pick - scheduleSettingsActivation?: Pick + scheduleSettingsActivation?: Pick workspaceManager: Pick diff --git a/packages/server/src/server/routes/pending-requests.test.ts b/packages/server/src/server/routes/pending-requests.test.ts index 0f53095902..312f943ffe 100644 --- a/packages/server/src/server/routes/pending-requests.test.ts +++ b/packages/server/src/server/routes/pending-requests.test.ts @@ -81,7 +81,7 @@ test("raw pending adapter retains the bound service authentication and fails clo const h = await harness() try { const endpoint = { url: "http://127.0.0.1:4321", auth: { type: "basic" as const, username: "opencode", password: "isolated-fixture" } } - rememberRuntime(endpoint, { version: "2.2.3", pid: 123, discovery: "info" }) + rememberRuntime(endpoint, { version: "2.3.0", pid: 123, discovery: "info" }) h.connection.endpoint = endpoint h.connection.fetch = createRuntimeFetch(endpoint, async (input, init) => { h.state.calls.push(new URL(String(input))) diff --git a/packages/server/src/server/routes/remote-control.test.ts b/packages/server/src/server/routes/remote-control.test.ts index b85c207124..c9afa733f5 100644 --- a/packages/server/src/server/routes/remote-control.test.ts +++ b/packages/server/src/server/routes/remote-control.test.ts @@ -33,6 +33,22 @@ test("pairing links require a connected tunnel", async () => { await app.close() }) +test("an administrator policy refuses Start and pairing links with a stable code", async () => { + const app = Fastify() + let started = 0 + const disabled = { ...manager(), status: () => ({ ...manager().status(), disabledByAdministrator: true }), + start: async () => { started += 1 } } as unknown as RemoteControlManager + registerRemoteControlRoutes(app, { manager: disabled }) + for (const url of ["/api/remote-control/start", "/api/remote-control/pairings"]) { + const response = await app.inject({ method: "POST", url }) + assert.equal(response.statusCode, 403, url) + assert.deepEqual(response.json(), { error: "Remote Control is disabled by the administrator", code: "remote_control_disabled" }) + } + assert.equal(started, 0) + assert.equal((await app.inject({ method: "GET", url: "/api/remote-control/status" })).json().disabledByAdministrator, true) + await app.close() +}) + test("pairing routes do not answer on local listeners", async () => { const app = Fastify() registerRemoteControlRoutes(app, { manager: manager() }) diff --git a/packages/server/src/server/routes/remote-control.ts b/packages/server/src/server/routes/remote-control.ts index 97fef89e69..bf1f22d45d 100644 --- a/packages/server/src/server/routes/remote-control.ts +++ b/packages/server/src/server/routes/remote-control.ts @@ -1,7 +1,7 @@ import fs from "node:fs" import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify" import { z } from "zod" -import type { RemoteControlManager } from "../../remote-control/manager" +import { REMOTE_CONTROL_DISABLED, type RemoteControlManager } from "../../remote-control/manager" import { deviceCookie, PAIR_EXCHANGE_PATH, PAIR_PAGE_PATH } from "../../remote-control/gate" import { verifiedDirectHttpsOrigin } from "../../remote-control/direct-https" import { isLocalRequest, isRemoteRequest, isRemoteSocket } from "../../remote-control/request-origin" @@ -54,7 +54,7 @@ export function registerRemoteControlRoutes(app: FastifyInstance, deps: RouteDep }) app.post("/api/remote-control/start", async (request, reply) => { - if (!requireLocalControl(request, reply)) return + if (!requireLocalControl(request, reply) || !requireAllowed(deps, reply)) return try { return await deps.manager.start() } catch (error) { @@ -64,7 +64,7 @@ export function registerRemoteControlRoutes(app: FastifyInstance, deps: RouteDep }) app.post("/api/remote-control/pairings", { bodyLimit: 4096 }, async (request, reply) => { - if (!requireLocalControl(request, reply)) return + if (!requireLocalControl(request, reply) || !requireAllowed(deps, reply)) return // Without a body, a tunnel link; with an origin, a link for that verified direct HTTPS origin. const parsed = request.body === undefined || request.body === null ? null : PairingBody.safeParse(request.body) if (parsed && !parsed.success) { @@ -143,6 +143,12 @@ export function registerRemoteControlRoutes(app: FastifyInstance, deps: RouteDep }) } +function requireAllowed(deps: RouteDeps, reply: FastifyReply): boolean { + if (!deps.manager.status().disabledByAdministrator) return true + reply.code(403).send({ error: REMOTE_CONTROL_DISABLED, code: "remote_control_disabled" }) + return false +} + function requireLocalControl(request: FastifyRequest, reply: FastifyReply): boolean { if (!isLocalRequest(request)) { reply.code(403).send({ error: "Remote Control settings are available on the host only" }) diff --git a/packages/server/src/server/routes/session-media-boundary.test.ts b/packages/server/src/server/routes/session-media-boundary.test.ts index 8a0a180df8..2f7175a2d4 100644 --- a/packages/server/src/server/routes/session-media-boundary.test.ts +++ b/packages/server/src/server/routes/session-media-boundary.test.ts @@ -8,6 +8,7 @@ import { registerSessionMediaRoutes } from "./session-media" import { mediaDigest } from "../../opencode/session-media" import { OpenCodeSharedService } from "../../workspaces/opencode-service" import { rememberRuntime } from "../../opencode/compatibility/runtime" +import { MINIMUM_OPENCODE_VERSION } from "../../opencode/runtime-support" function deferred() { let resolve!: () => void @@ -33,7 +34,7 @@ async function fixture(stage: string) { }) await upstream.listen({ host: "127.0.0.1", port: 0 }) const endpoint = { url: `http://127.0.0.1:${(upstream.server.address() as { port: number }).port}`, auth: { type: "basic" as const, username: "fixture", password: "fixture" } } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() await service.endpoint({ kind: "lifecycle", identity: "media-boundary", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }) const connection = await service.acquire() diff --git a/packages/server/src/server/routes/session-media-ownership.test.ts b/packages/server/src/server/routes/session-media-ownership.test.ts index 254c1094ff..7063942601 100644 --- a/packages/server/src/server/routes/session-media-ownership.test.ts +++ b/packages/server/src/server/routes/session-media-ownership.test.ts @@ -13,6 +13,7 @@ import pino from "pino" import { OpenCode } from "@opencode/client" import { deferToolMedia, INLINE_MEDIA_LIMIT, mediaDigest } from "../../opencode/session-media" import { MESSAGE_LIMIT, parseSessionMediaPath } from "../../opencode/session-media-contract" +import { MINIMUM_OPENCODE_VERSION } from "../../opencode/runtime-support" function deferred() { let resolve!: (value: T) => void, reject!: (error: unknown) => void @@ -111,7 +112,7 @@ test("media ownership retains real manager, physical worktrees and connection cu await app.listen({ host: "127.0.0.1", port: 0 }) const endpoint = { url: `http://127.0.0.1:${(app.server.address() as { port: number }).port}`, auth: { type: "basic" as const, username: label, password: "fixture" } } - rememberRuntime(endpoint, { version: "2.2.3", pid: label === "A" ? 1 : 2, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: label === "A" ? 1 : 2, discovery: "info" }) return endpoint } const a = await host("A"), b = await host("B") diff --git a/packages/server/src/server/routes/session-media.test.ts b/packages/server/src/server/routes/session-media.test.ts index 3b83488363..3e7781e401 100644 --- a/packages/server/src/server/routes/session-media.test.ts +++ b/packages/server/src/server/routes/session-media.test.ts @@ -5,6 +5,7 @@ import { mediaDigest } from "../../opencode/session-media" import { registerSessionMediaRoutes } from "./session-media" import { OpenCodeSharedService } from "../../workspaces/opencode-service" import { rememberRuntime } from "../../opencode/compatibility/runtime" +import { MINIMUM_OPENCODE_VERSION } from "../../opencode/runtime-support" const bytes = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aWQAAAABJRU5ErkJggg==", "base64") const uri = `data:image/png;base64,${bytes.toString("base64")}` @@ -25,7 +26,7 @@ async function fixture() { }) await upstream.listen({ host: "127.0.0.1", port: 0 }) const endpoint = { url: `http://127.0.0.1:${(upstream.server.address() as { port: number }).port}` } - rememberRuntime(endpoint, { version: "2.2.3", pid: 1, discovery: "info" }) + rememberRuntime(endpoint, { version: MINIMUM_OPENCODE_VERSION, pid: 1, discovery: "info" }) const service = new OpenCodeSharedService() await service.endpoint({ kind: "lifecycle", identity: "media-route", lifecycle: { discover: async () => endpoint, ensure: async () => endpoint } }) const occurrence = new AbortController() diff --git a/packages/server/src/server/routes/settings.test.ts b/packages/server/src/server/routes/settings.test.ts index 7cf9a7bd28..ecb29cb98c 100644 --- a/packages/server/src/server/routes/settings.test.ts +++ b/packages/server/src/server/routes/settings.test.ts @@ -135,6 +135,86 @@ for (const url of ["/api/storage/config", "/api/storage/config/server"]) { }) } +it("only host-local requests change the SideCar direct HTTPS opt-in, through either config route", async t => { + const root = mkdtempSync(path.join(tmpdir(), "codenomad-host-only-setting-")) + const logger = { child() { return this }, warn() {}, info() {} } as unknown as Logger + const location = resolveConfigLocation(root), app = Fastify() + t.after(async () => { await app.close(); rmSync(root, { recursive: true, force: true }) }) + writeFileSync(location.configYamlPath, stringify({ server: { logLevel: "INFO" } })) + const settings = new RealSettingsService(location, undefined, logger) + registerSettingsRoutes(app, { settings, logger }) + const stored = () => parse(readFileSync(location.configYamlPath, "utf8")).server?.sidecarsOverDirectHttps + const patch = (remoteAddress: string, url: string, payload: unknown) => app.inject({ method: "PATCH", url, remoteAddress, payload: payload as object }) + const lan = "192.0.2.20" + const enable = [["/api/storage/config/server", { sidecarsOverDirectHttps: true }], ["/api/storage/config", { server: { sidecarsOverDirectHttps: true } }]] as const + for (const [url, payload] of enable) { + const refused = await patch(lan, url, payload) + assert.equal(refused.statusCode, 403, `${url}: ${refused.body}`) + assert.equal(stored(), undefined) + } + // Other server settings stay writable remotely, and writing the current value is no change. + assert.equal((await patch(lan, "/api/storage/config/server", { logLevel: "WARN", sidecarsOverDirectHttps: false })).statusCode, 200) + assert.equal((await patch("127.0.0.1", ...enable[0])).statusCode, 200) + assert.equal(stored(), true) + for (const [url, payload] of [["/api/storage/config/server", { sidecarsOverDirectHttps: false }], ["/api/storage/config/server", { sidecarsOverDirectHttps: null }], + ["/api/storage/config", { server: null }], ["/api/storage/config", { server: { sidecarsOverDirectHttps: "yes" } }]] as const) { + assert.equal((await patch(lan, url, payload)).statusCode, 403, `${url} ${JSON.stringify(payload)}`) + assert.equal(stored(), true) + } + assert.equal((await patch(lan, "/api/storage/config", { server: { logLevel: "ERROR" } })).statusCode, 200) + assert.deepEqual(parse(readFileSync(location.configYamlPath, "utf8")).server, { logLevel: "ERROR", sidecarsOverDirectHttps: true }) + assert.equal((await patch("127.0.0.1", "/api/storage/config", { server: { sidecarsOverDirectHttps: false } })).statusCode, 200) + assert.equal(stored(), false) +}) + +it("config writes for any owner start from the file on disk, so a stale cached opt-in is never written back", async t => { + const root = mkdtempSync(path.join(tmpdir(), "codenomad-stale-config-")) + const logger = { child() { return this }, warn() {}, info() {} } as unknown as Logger + const location = resolveConfigLocation(root), app = Fastify() + t.after(async () => { await app.close(); rmSync(root, { recursive: true, force: true }) }) + const settings = new RealSettingsService(location, undefined, logger) + registerSettingsRoutes(app, { settings, logger }) + const lan = "192.0.2.20" + const onDisk = () => parse(readFileSync(location.configYamlPath, "utf8")) + const patch = (remoteAddress: string, url: string, payload: object) => app.inject({ method: "PATCH", url, remoteAddress, payload }) + for (const [index, [url, payload]] of ([ + ["/api/storage/config/ui", { theme: "dark" }], + ["/api/storage/config", { ui: { theme: "light" } }], + ["/api/storage/config/providerAccounts", { autoSelect: { openai: true } }], + ["/api/storage/config/server", { logLevel: "WARN" }], + ] as const).entries()) { + // The host turns the opt-in on through Settings (the display cache now holds `true`), + // then off by editing the file. + assert.equal((await patch("127.0.0.1", "/api/storage/config/server", { sidecarsOverDirectHttps: true })).statusCode, 200) + assert.equal(settings.getOwner("config", "server").sidecarsOverDirectHttps, true) + writeFileSync(location.configYamlPath, stringify({ server: { sidecarsOverDirectHttps: false }, external: { revision: index } })) + for (const remoteAddress of [lan, "127.0.0.1"]) { + const response = await patch(remoteAddress, url, payload) + assert.equal(response.statusCode, 200, `${remoteAddress} ${url}: ${response.body}`) + const saved = onDisk() + assert.equal(saved.server.sidecarsOverDirectHttps, false, `${remoteAddress} ${url} wrote the stale value back`) + assert.deepEqual(saved.external, { revision: index }, "the host's other edits survive") + } + } + // The guard judges the file too: a non-local request cannot turn the opt-in back on whatever the cache says. + assert.equal((await patch(lan, "/api/storage/config/server", { sidecarsOverDirectHttps: true })).statusCode, 403) + assert.equal(onDisk().server.sidecarsOverDirectHttps, false) + // Reading the document normalizes what is on disk now, never a stale cache: a raw read leaves + // a non-normalized document cached, then the host turns the opt-in off. + writeFileSync(location.configYamlPath, stringify({ server: { logLevel: "info", sidecarsOverDirectHttps: true } })) + assert.equal((await app.inject({ url: "/api/storage/config/ui" })).statusCode, 200) + writeFileSync(location.configYamlPath, stringify({ server: { logLevel: "info", sidecarsOverDirectHttps: false } })) + const read = await app.inject({ url: "/api/storage/config", remoteAddress: lan }) + assert.equal(read.statusCode, 200) + assert.deepEqual(onDisk().server, { logLevel: "INFO", sidecarsOverDirectHttps: false }) + // A document that cannot be read is never overwritten from the cache. + writeFileSync(location.configYamlPath, "server: [sidecarsOverDirectHttps: false\n") + for (const [url, payload] of [["/api/storage/config/ui", { theme: "dark" }], ["/api/storage/config", { ui: { theme: "dark" } }]] as const) { + assert.equal((await patch("127.0.0.1", url, payload)).statusCode, 503, url) + assert.equal(readFileSync(location.configYamlPath, "utf8"), "server: [sidecarsOverDirectHttps: false\n") + } +}) + it("both explicit executable settings paths refresh the login start after save; unrelated settings and reads stay passive", async t => { const app = Fastify(), order: string[] = [] t.after(() => app.close()) diff --git a/packages/server/src/server/routes/settings.ts b/packages/server/src/server/routes/settings.ts index 8c15d4d303..b4f77449db 100644 --- a/packages/server/src/server/routes/settings.ts +++ b/packages/server/src/server/routes/settings.ts @@ -8,6 +8,8 @@ import { sanitizeConfigDoc, sanitizeConfigOwner } from "../../settings/public-co import { resolveDefaultInstallation } from "../../opencode-update/shared-installation" import { applyConditionalMissionPreferences, MissionPreferenceConflictError } from "../../settings/mission-preference-condition" import { SettingsReadError } from "../../settings/yaml-doc-store" +import { HostOnlySettingError, hostOnlyServerCheck } from "../../settings/host-only-settings" +import { isLocalRequest } from "../../remote-control/request-origin" interface RouteDeps { settings: SettingsService @@ -76,13 +78,13 @@ export function registerSettingsRoutes(app: FastifyInstance, deps: RouteDeps) { } body = bodyObj } - return deps.settings.mergePatchDoc("config", body) + return deps.settings.mergePatchDoc("config", body, hostOnlyServerCheck(isLocalRequest(request))) }) if (body && typeof body === "object" && "server" in body && body.server && typeof body.server === "object" && "opencodeBinary" in body.server) await refreshLoginStart(deps) return sanitizeConfigDoc(saved) } catch (error) { - reply.code(400) + reply.code(error instanceof HostOnlySettingError ? 403 : error instanceof SettingsReadError ? 503 : 400) return { error: error instanceof Error ? error.message : "Invalid patch" } } }) @@ -116,13 +118,14 @@ export function registerSettingsRoutes(app: FastifyInstance, deps: RouteDeps) { const processed = request.params.owner === "server" ? enforceSpeechCredentialPairing(request.body ?? {}, currentOwner) : request.body ?? {} - return deps.settings.mergePatchOwner("config", request.params.owner, processed) + return deps.settings.mergePatchOwner("config", request.params.owner, processed, hostOnlyServerCheck(isLocalRequest(request))) }) if (request.params.owner === "server" && request.body && typeof request.body === "object" && "opencodeBinary" in request.body) await refreshLoginStart(deps) return sanitizeConfigOwner(request.params.owner, saved) } catch (error) { - reply.code(error instanceof MissionPreferenceConflictError ? 409 : error instanceof SettingsReadError ? 503 : 400) + reply.code(error instanceof MissionPreferenceConflictError ? 409 : error instanceof SettingsReadError ? 503 + : error instanceof HostOnlySettingError ? 403 : 400) return { error: error instanceof Error ? error.message : "Invalid patch" } } }) diff --git a/packages/server/src/server/routes/usage-console-display.test.ts b/packages/server/src/server/routes/usage-console-display.test.ts new file mode 100644 index 0000000000..4b4d8a01d2 --- /dev/null +++ b/packages/server/src/server/routes/usage-console-display.test.ts @@ -0,0 +1,42 @@ +import assert from "node:assert/strict" +import test from "node:test" +import Fastify from "fastify" +import { registerUsageRoutes } from "./usage" +import { clearProviderUsageCache } from "../../usage/service" +import { createOpenCodeFreeUsage } from "../../usage/opencode-free-usage" + +test("free Console models keep their aggregate bar and optional credits without reset or detailed tables", async t => { + clearProviderUsageCache() + const summary = { totalRequests: "42", totalInputTokens: "0", totalOutputTokens: "0", totalCacheReadTokens: "0", + totalCacheWrite5mTokens: "0", totalCacheWrite1hTokens: "0", totalCostMicroCents: "0", services: [] } + t.mock.method(globalThis, "fetch", async (input: unknown) => { + const url = new URL(String(input)) + return Response.json(url.pathname.endsWith("/billing/status") ? { availableMicroCents: "125000000" } : url.pathname.endsWith("/summary") ? summary + : { items: [{ ...summary, provider: "vendor", model: "big-pickle" }], pageInfo: { page: 1, pageSize: 50, total: 1, pageCount: 1 } }) + }) + const workspace = {} + const connection = { assertCurrent() {}, client: { + session: { get: async () => ({ location: { directory: "/repo" } }), stats: async () => { assert.fail("No local usage estimate") } }, + credential: { list: async () => [{ active: true, integrationID: "opencode", value: { type: "key", key: "synthetic" } }] }, + } } + const app = Fastify() + const freeUsage = createOpenCodeFreeUsage() + registerUsageRoutes(app, { workspaceManager: { get: () => workspace, getSharedServiceConnection: async () => connection, + ownsLocation: async () => true }, freeUsage } as never) + try { + for (const model of ["big-pickle", "example-free"]) { + const result = await app.inject(`/api/usage/opencode?instanceId=fixture&sessionId=session&modelId=${model}`) + assert.equal(result.statusCode, 200) + assert.equal(result.json().console, undefined) + assert.deepEqual(result.json().freeEstimate, { requests: 42, reference: 800 }) + assert.equal(result.json().windows.daily.valueLabel, "42 / 800") + assert.equal(result.json().windows.daily.usedPercent, 5.25) + assert.equal(result.json().windows.daily.resetAt, null) + assert.deepEqual(Object.keys(result.json().windows), ["daily", "credits_balance"]) + assert.deepEqual(result.json().windows.credits_balance, { + usedPercent: null, remainingPercent: null, resetAt: null, windowSeconds: null, balanceUSD: { remaining: 1.25 }, + }) + assert.equal(result.json().estimated, undefined) + } + } finally { await app.close(); freeUsage.dispose(); clearProviderUsageCache() } +}) diff --git a/packages/server/src/server/routes/usage-google.test.ts b/packages/server/src/server/routes/usage-google.test.ts index 4d68e4e774..5bbe9e2b50 100644 --- a/packages/server/src/server/routes/usage-google.test.ts +++ b/packages/server/src/server/routes/usage-google.test.ts @@ -6,7 +6,6 @@ import type { ServiceConnection } from "../../workspaces/opencode-service" import { clearProviderUsageCache } from "../../usage/service" import { registerUsageRoutes, type UsageRouteDeps } from "./usage" import { googleOAuthClients } from "../../usage/google-credential" -import { createOpenCodeFreeExhaustion } from "../../usage/opencode-free-exhaustion" import { createOpenCodeFreeUsage } from "../../usage/opencode-free-usage" const fakeClients = { @@ -61,7 +60,7 @@ function harness(methodID = "gemini-cli") { getSessionEnvironment: async () => ({}), getServiceWslDistro: () => undefined, getHostPathForServicePath: async () => undefined, } - registerUsageRoutes(app, { workspaceManager: manager, freeUsage: createOpenCodeFreeUsage(createOpenCodeFreeExhaustion()) }) + registerUsageRoutes(app, { workspaceManager: manager, freeUsage: createOpenCodeFreeUsage() }) const fetchUpstream = async (input: RequestInfo | URL, init?: RequestInit) => { state.outbound.push({ url: String(input), init }) assert.equal(init?.method, "POST") diff --git a/packages/server/src/server/routes/usage.test.ts b/packages/server/src/server/routes/usage.test.ts index b30d81ef6e..3115e92ca6 100644 --- a/packages/server/src/server/routes/usage.test.ts +++ b/packages/server/src/server/routes/usage.test.ts @@ -9,7 +9,6 @@ import type { ServiceConnection } from "../../workspaces/opencode-service" import { registerUsageRoutes, type UsageRouteDeps } from "./usage" import { clearProviderUsageCache, getProviderUsage, resolveUsageProvider } from "../../usage/service" import type { ProviderReadContext } from "../../usage/types" -import { createOpenCodeFreeExhaustion } from "../../usage/opencode-free-exhaustion" import { createOpenCodeFreeUsage } from "../../usage/opencode-free-usage" import { readUsageCredentials } from "../../usage/native-credentials" @@ -63,11 +62,10 @@ function harness() { getServiceWslDistro: () => "Ubuntu", getHostPathForServicePath: async (_id, servicePath) => state.hostFiles.get(servicePath)?.path, } - const exhaustion = createOpenCodeFreeExhaustion() - const freeUsage = createOpenCodeFreeUsage(exhaustion) + const freeUsage = createOpenCodeFreeUsage() registerUsageRoutes(app, { workspaceManager: manager, freeUsage }) - app.addHook("onClose", async () => { exhaustion.dispose(); freeUsage.dispose() }) - return { app, state, logs, exhaustion, connection } + app.addHook("onClose", async () => { freeUsage.dispose() }) + return { app, state, logs, connection } } const url = "/api/usage/openai?instanceId=instance&sessionId=session&modelId=gpt-5" const freeUrl = "/api/usage/opencode?instanceId=instance&sessionId=session&modelId=big-pickle" @@ -86,7 +84,7 @@ test("free quota requires Console login and validates ownership before credentia assert.equal(response.json().ok, false) assert.equal(response.json().unavailableReason, "opencode-console-missing-credential") assert.equal(response.json().providerName, "OpenCode Console") - assert.deepEqual(response.json().freeEstimate, { requests: null, reference: 800, exhausted: false }) + assert.deepEqual(response.json().freeEstimate, { requests: null, reference: 800 }) assert.deepEqual(response.json().windows, {}) assert.ok(state.nativeCalls.every(path => path.startsWith("/api/session/") || path === "/api/credential")) } finally { await app.close() } @@ -113,26 +111,7 @@ test("free quota fences session movement and reconnect during the Console read", } }) -test("exhaustion evidence without Console credentials keeps counts unknown and the login action available", async () => { - const { app, state, connection, exhaustion } = harness() - state.consoleConnected = false - try { - const now = Date.now() - exhaustion.observe(connection, { type: "session.step.started", created: now - 1, - data: { sessionID: "another-session", assistantMessageID: "m", model: { providerID: "opencode", id: "big-pickle" } } }) - exhaustion.observe(connection, { type: "session.step.failed", created: now, - data: { sessionID: "another-session", assistantMessageID: "m", error: { type: "provider.quota" } } }) - const response = await app.inject(freeUrl.replace("big-pickle", "example-free")) - assert.equal(response.statusCode, 200) - assert.equal(response.json().ok, false) - assert.deepEqual(response.json().freeEstimate, { requests: null, reference: 800, exhausted: true }) - assert.deepEqual(response.json().windows, {}) - assert.equal(response.json().unavailableReason, "opencode-console-missing-credential") - assert.equal(state.nativeCalls.includes("/api/credential"), true) - } finally { await app.close() } -}) - -test("exact UTC midnight still reads the authoritative Console count", async t => { +test("a read at UTC midnight reports the Console count without a local reset", async t => { t.mock.method(Date, "now", () => Date.UTC(2026, 10, 3)) const { app, state } = harness() t.mock.method(globalThis, "fetch", async () => Response.json({ items: [], pageInfo: { page: 1, pageSize: 50, total: 0, pageCount: 0 } })) @@ -141,19 +120,21 @@ test("exact UTC midnight still reads the authoritative Console count", async t = assert.equal(response.statusCode, 200, response.body) assert.equal(response.json().windows.daily.usedPercent, 0) assert.equal(response.json().windows.daily.valueLabel, "0 / 800") + assert.equal(response.json().windows.daily.resetAt, null) assert.equal(state.nativeCalls.includes("/api/experimental/session/stats"), false) } finally { await app.close() } }) -test("connected free usage reads only Console counts without exposing the credential", async t => { +test("connected free usage reads Console counts and credits without exposing the credential", async t => { const { app, state, logs } = harness() t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { - state.quotaCalls++ const target = new URL(String(input)) assert.equal(target.origin, "https://opencode.ai") + assert.equal(new Headers(init?.headers).get("authorization"), "Bearer secret-console") + if (target.pathname === "/console/api/billing/status") return Response.json({ availableMicroCents: 125_000_000 }) + state.quotaCalls++ assert.equal(target.pathname, "/console/api/usage/models") assert.equal(target.searchParams.get("range"), "24h") - assert.equal(new Headers(init?.headers).get("authorization"), "Bearer secret-console") return Response.json({ items: [{ provider: "vendor", model: "big-pickle", totalRequests: "80", totalInputTokens: "0", totalOutputTokens: "0", totalCacheReadTokens: "0", totalCacheWrite5mTokens: "0", totalCacheWrite1hTokens: "0", totalCostMicroCents: "0" }], @@ -162,9 +143,11 @@ test("connected free usage reads only Console counts without exposing the creden try { const response = await app.inject(freeUrl) assert.equal(response.statusCode, 200) - assert.deepEqual(response.json().freeEstimate, { requests: 80, reference: 800, exhausted: false }) + assert.deepEqual(response.json().freeEstimate, { requests: 80, reference: 800 }) assert.equal(response.json().windows.daily.usedPercent, 10) - assert.equal(response.json().estimated, true) + assert.equal(response.json().estimated, undefined) + assert.equal(response.json().windows.daily.resetAt, null) + assert.deepEqual(response.json().windows.credits_balance.balanceUSD, { remaining: 1.25 }) assert.equal(state.quotaCalls, 1) assert.equal([response.body, ...logs].join("").includes("secret-console"), false) } finally { await app.close() } @@ -173,7 +156,7 @@ test("connected free usage reads only Console counts without exposing the creden for (const stalled of ["credentials", "Console"] as const) { for (const boundary of ["unchanged", "move", "reconnect"] as const) { test(`free Console read stalled at ${stalled} reports unknown and revalidates (${boundary})`, async t => { - const { app, state, connection, exhaustion } = harness() + const { app, state, connection } = harness() const timeout = globalThis.setTimeout t.mock.method(globalThis, "setTimeout", (callback: (...args: any[]) => void, delay?: number, ...args: any[]) => timeout(callback, delay === 12_000 ? 30 : delay === 15_000 ? 1000 : delay, ...args)) @@ -183,17 +166,14 @@ for (const stalled of ["credentials", "Console"] as const) { if (stalled === "credentials") { t.mock.method(connection.client.credential, "list", async () => { entered(); await gate; return [] }) } - t.mock.method(globalThis, "fetch", async (_input: unknown, init?: RequestInit) => { - calls++; entered() + t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + // The optional balance read runs beside the count; only usage reads count here. + if (!new URL(String(input)).pathname.endsWith("/billing/status")) calls++ + entered() return new Promise((_resolve, reject) => { init!.signal!.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }) }) }) - const now = Date.now() - exhaustion.observe(connection, { type: "session.step.started", created: now - 1, - data: { sessionID: "session", assistantMessageID: "m", model: { providerID: "opencode", id: "big-pickle" } } }) - exhaustion.observe(connection, { type: "session.step.failed", created: now, - data: { sessionID: "session", assistantMessageID: "m", error: { type: "provider.quota" } } }) try { const pending = app.inject(freeUrl) await started @@ -202,11 +182,10 @@ for (const stalled of ["credentials", "Console"] as const) { const response = await pending assert.equal(response.statusCode, boundary === "unchanged" ? 200 : boundary === "move" ? 403 : 503) if (boundary === "unchanged") { - assert.deepEqual(response.json().freeEstimate, { requests: null, reference: 800, exhausted: true }) + assert.deepEqual(response.json().freeEstimate, { requests: null, reference: 800 }) assert.deepEqual(response.json().windows, {}) assert.equal(response.json().ok, false) assert.equal(response.json().unavailableReason, "opencode-console-network-error") - assert.equal(response.json().estimated, true) } assert.equal(calls, stalled === "credentials" ? 0 : 1) } finally { release(); await app.close() } @@ -442,9 +421,10 @@ test("paid opencode sessions read Console counters, never the Go cookie endpoint assert.equal(response.json().providerName, "OpenCode Console") assert.deepEqual(response.json().console.requests, { "24h": 12, "7d": 12, "30d": 12 }) assert.deepEqual(response.json().console.budgets, { status: "unavailable", items: [] }) - assert.equal(requests.length, 4) - assert.ok(requests.every(r => r.url.startsWith("https://opencode.ai/console/api/usage/") && - r.authorization === "Bearer secret-console" && r.cookie === null)) + assert.equal(requests.length, 5, "three summaries, the model page and the credit balance") + assert.equal(requests.filter(r => r.url === "https://opencode.ai/console/api/billing/status").length, 1) + assert.ok(requests.every(r => (r.url.startsWith("https://opencode.ai/console/api/usage/") + || r.url === "https://opencode.ai/console/api/billing/status") && r.authorization === "Bearer secret-console" && r.cookie === null)) assert.equal([response.body, ...logs].join("").includes("secret-"), false) } finally { globalThis.fetch = previousFetch @@ -466,7 +446,14 @@ for (const boundary of ["unchanged", "move", "reconnect", "evict"] as const) { const cleanup = new AbortController() let transportSignal: AbortSignal | undefined, entered!: () => void, calls = 0 const started = new Promise(resolve => { entered = resolve }) - t.mock.method(globalThis, "fetch", async (_input: unknown, init?: RequestInit) => { + t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + // The optional balance read runs beside the usage reads; it stays out of this count. + if (new URL(String(input)).pathname.endsWith("/billing/status")) { + const signal = AbortSignal.any([init!.signal!, cleanup.signal]) + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(new DOMException("aborted", "AbortError")), { once: true }) + }) + } calls++ transportSignal = init!.signal! if (boundary === "move") state.directory = "/foreign" @@ -511,7 +498,11 @@ for (const status of [401, 403]) { test(`Console HTTP ${status} reason reaches the route without upstream secrets or Go fallback`, async t => { const { app, logs } = harness() let calls = 0 - t.mock.method(globalThis, "fetch", async () => { calls++; return new Response("secret-upstream", { status }) }) + t.mock.method(globalThis, "fetch", async (input: unknown) => { + // The optional balance read runs beside the first usage read; only usage reads count. + if (!String(input).endsWith("/billing/status")) calls++ + return new Response("secret-upstream", { status }) + }) clearProviderUsageCache() try { const response = await app.inject(url.replace("/usage/openai", "/usage/opencode")) diff --git a/packages/server/src/server/routes/usage.ts b/packages/server/src/server/routes/usage.ts index 1b93662c40..a499020ead 100644 --- a/packages/server/src/server/routes/usage.ts +++ b/packages/server/src/server/routes/usage.ts @@ -116,7 +116,7 @@ export function registerUsageRoutes(app: FastifyInstance, deps: UsageRouteDeps) } signal.throwIfAborted() connection.assertCurrent() - return free ? freeUsage.refreshExhaustion(connection, usage) : usage + return usage } if (provider?.id === "opencode-console") consoleTimeout = publicationSignal => publish({ requestedProviderId: params.data.providerId, providerId: provider.id, providerName: provider.name, modelId, diff --git a/packages/server/src/server/sidecar-direct-https.ts b/packages/server/src/server/sidecar-direct-https.ts new file mode 100644 index 0000000000..a9aeefdbc0 --- /dev/null +++ b/packages/server/src/server/sidecar-direct-https.ts @@ -0,0 +1,40 @@ +import type { FastifyRequest } from "fastify" +import type { ServerMeta } from "../api-types" +import { verifiedDirectHttpsOrigin, verifiedHttpsOrigins } from "../remote-control/direct-https" +import type { SettingsService } from "../settings/service" + +/** Host setting (`config.yaml` server owner) that opens SideCars to verified direct HTTPS origins. Off unless `true`. */ +export const SIDECARS_OVER_DIRECT_HTTPS = "sidecarsOverDirectHttps" + +type AccessRequest = Pick + +/** + * Whether the host opted in, read from the configuration file as it is now (never the display + * cache): a host edit takes effect on the next request; an unreadable document keeps SideCars host-only. + */ +export function sidecarsOverDirectHttpsEnabled(settings: Pick): boolean { + try { + return settings.serverFlag(SIDECARS_OVER_DIRECT_HTTPS) === true + } catch { + return false + } +} + +/** + * The host's opt-in exception to host-only SideCar content and WebSockets: a direct-listener + * request whose origin is a verified direct HTTPS origin (`remote-control/direct-https.ts`). + * Remote Control ingress, plain-HTTP and loopback-alias origins never qualify. Callers keep + * authentication, the direct source policy and every other host-only path unchanged. + */ +export function createSideCarDirectHttpsAccess(deps: { + meta: Pick + allowedOrigins?: readonly string[] + enabled: () => boolean +}): (request: AccessRequest) => boolean { + return request => verifiedDirectHttpsOrigin(request, verifiedHttpsOrigins(deps.meta, deps.allowedOrigins)) !== null && deps.enabled() +} + +/** SideCar content paths, as routed; the bare `/sidecars` path stays host-only. */ +export function isSideCarContentPath(pathname: string): boolean { + return pathname.startsWith("/sidecars/") +} diff --git a/packages/server/src/settings/host-only-settings.ts b/packages/server/src/settings/host-only-settings.ts new file mode 100644 index 0000000000..7bd2d9b2ba --- /dev/null +++ b/packages/server/src/settings/host-only-settings.ts @@ -0,0 +1,32 @@ +import { isPlainObject } from "./merge-patch" +import type { ConfigWriteCheck } from "./service" +import type { SettingsDoc } from "./yaml-doc-store" +import { SIDECARS_OVER_DIRECT_HTTPS } from "../server/sidecar-direct-https" + +/** Server-owner settings that widen host-only access: only the host itself may change them. */ +const HOST_ONLY_SERVER_KEYS = [SIDECARS_OVER_DIRECT_HTTPS] as const + +export class HostOnlySettingError extends Error { + constructor() { + super("This setting can be changed on the host only") + } +} + +/** + * The config write check for a request: a non-local request may not change a host-only + * setting, by any route or owner, including by deleting the whole server owner. It compares + * the authoritative document a write starts from with its result, so neither a stale cache + * nor a concurrent host edit lets the request flip one. Other keys stay writable. + */ +export function hostOnlyServerCheck(localRequest: boolean): ConfigWriteCheck | undefined { + if (localRequest) return undefined + return (before: SettingsDoc, after: SettingsDoc) => { + for (const key of HOST_ONLY_SERVER_KEYS) { + if (enabled(before.server, key) !== enabled(after.server, key)) throw new HostOnlySettingError() + } + } +} + +function enabled(owner: unknown, key: string): boolean { + return isPlainObject(owner) && owner[key] === true +} diff --git a/packages/server/src/settings/server-flag-reader.test.ts b/packages/server/src/settings/server-flag-reader.test.ts new file mode 100644 index 0000000000..52646c7a50 --- /dev/null +++ b/packages/server/src/settings/server-flag-reader.test.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { test } from "node:test" +import { ServerFlagReader } from "./server-flag-reader" + +function configFile(t: { after: (fn: () => void) => void }, content: string) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "codenomad-flag-reader-")) + t.after(() => fs.rmSync(dir, { recursive: true, force: true })) + const file = path.join(dir, "config.yaml") + fs.writeFileSync(file, content) + return file +} + +test("a read that fails while the file is locked is retried on the next call", t => { + const file = configFile(t, "server:\n sidecarsOverDirectHttps: true\n") + const read = fs.readFileSync + let locked = true + t.mock.method(fs, "readFileSync", (...args: Parameters) => { + if (locked && args[0] === file) throw Object.assign(new Error("resource busy or locked"), { code: "EBUSY" }) + return read(...args) + }) + const reader = new ServerFlagReader(file) + assert.equal(reader.enabled("sidecarsOverDirectHttps"), false) + locked = false + assert.equal(reader.enabled("sidecarsOverDirectHttps"), true) +}) + +test("an invalid document reads as false until the file changes", t => { + const file = configFile(t, "server: [unclosed\n") + const reader = new ServerFlagReader(file) + assert.equal(reader.enabled("sidecarsOverDirectHttps"), false) + fs.writeFileSync(file, "server:\n sidecarsOverDirectHttps: true\n") + assert.equal(reader.enabled("sidecarsOverDirectHttps"), true) +}) diff --git a/packages/server/src/settings/server-flag-reader.ts b/packages/server/src/settings/server-flag-reader.ts new file mode 100644 index 0000000000..8c90858112 --- /dev/null +++ b/packages/server/src/settings/server-flag-reader.ts @@ -0,0 +1,57 @@ +import fs from "node:fs" +import { parse as parseYaml } from "yaml" +import { isPlainObject } from "./merge-patch" + +const MAX_CONFIG_BYTES = 1024 * 1024 + +/** + * Authoritative boolean server settings for access decisions: the configuration file as it + * is now, never the display cache. The file is parsed again only when its stat signature + * changes, so a per-request read costs one stat. A missing, unreadable, oversized, non-file or + * invalid document reads every flag as false. + */ +export class ServerFlagReader { + private signature: string | null = null + private server: Record = {} + + constructor(private readonly filePath: string) {} + + enabled(key: string): boolean { + let stat: fs.BigIntStats + try { + stat = fs.statSync(this.filePath, { bigint: true }) + } catch { + this.signature = null + this.server = {} + return false + } + const signature = `${stat.dev}:${stat.ino}:${stat.size}:${stat.mtimeNs}:${stat.ctimeNs}` + if (signature !== this.signature) { + // Read after stat: a write in between yields newer content under the older signature, + // which the next call's stat replaces. + const server = readServerOwner(this.filePath, stat) + // A failed read (a transient lock, for example) reads as false and is retried on the + // next call instead of being cached under this signature. + this.server = server ?? {} + this.signature = server ? signature : null + } + return this.server[key] === true + } +} + +/** The document's server owner, `{}` when the file is unusable, or null when reading failed. */ +function readServerOwner(filePath: string, stat: fs.BigIntStats): Record | null { + if (!stat.isFile() || stat.size > BigInt(MAX_CONFIG_BYTES)) return {} + let text: string + try { + text = fs.readFileSync(filePath, "utf-8") + } catch { + return null + } + try { + const doc: unknown = parseYaml(text) + return isPlainObject(doc) && isPlainObject(doc.server) ? doc.server : {} + } catch { + return {} + } +} diff --git a/packages/server/src/settings/service.test.ts b/packages/server/src/settings/service.test.ts index 3585fdc663..8458048cd7 100644 --- a/packages/server/src/settings/service.test.ts +++ b/packages/server/src/settings/service.test.ts @@ -83,7 +83,8 @@ describe("SettingsService config persistence", () => { it("normalizes and persists a document patch once", () => { let writes = 0 const service = serviceWithStore({ - get: () => ({ server: { logLevel: "info" } }), + reloadAuthoritative: () => ({ server: { logLevel: "info" } }), + get: () => assert.fail("a write starts from the authoritative document, never the cache"), replace: (value: unknown) => { writes += 1 return value @@ -99,6 +100,7 @@ describe("SettingsService config persistence", () => { it("normalizes and persists a server-owner patch once", () => { let writes = 0 const service = serviceWithStore({ + reloadAuthoritative: () => ({}), getOwner: () => ({ logLevel: "info", opencodeBinary: "opencode", sidecars: [] }), replaceOwner: (_owner: string, value: unknown) => { writes += 1 @@ -114,6 +116,7 @@ describe("SettingsService config persistence", () => { it("keeps only known update feeds", () => { const owner = (updateFeed: unknown) => serviceWithStore({ + reloadAuthoritative: () => ({}), getOwner: () => ({}), replaceOwner: (_owner: string, value: unknown) => value, }).mergePatchOwner("config", "server", { updateFeed }) @@ -126,8 +129,9 @@ describe("SettingsService config persistence", () => { it("does not report a persisted patch as failed when an event listener throws", () => { let warnings = 0 const service = serviceWithStore({ + reloadAuthoritative: () => ({}), getOwner: () => ({}), - mergePatchOwner: (_owner: string, patch: unknown) => patch, + replaceOwner: (_owner: string, value: unknown) => value, }) Object.assign(service as any, { eventBus: { publish: () => { throw new Error("listener failed") } }, diff --git a/packages/server/src/settings/service.ts b/packages/server/src/settings/service.ts index 5dd3be47a4..bde67a5f35 100644 --- a/packages/server/src/settings/service.ts +++ b/packages/server/src/settings/service.ts @@ -8,6 +8,7 @@ import type { WorkspaceEventPayload } from "../api-types" import { sanitizeConfigOwner } from "./public-config" import { applyMergePatch } from "./merge-patch" import { readAdmissionEnvironment } from "./admission-environment" +import { ServerFlagReader } from "./server-flag-reader" import { canonicalScope } from "../host-lifetime/protocol" import { createHash } from "node:crypto" import fs from "node:fs" @@ -15,6 +16,8 @@ import { claimServerIdentity } from "./server-identity" import path from "node:path" export type DocKind = "config" | "state" +/** Refuses a config write by throwing, given the authoritative document and the would-be result. */ +export type ConfigWriteCheck = (before: SettingsDoc, after: SettingsDoc) => void const CanonicalLogLevelSchema = z.preprocess( (value) => (typeof value === "string" ? value.trim().toUpperCase() : value), @@ -74,6 +77,7 @@ function normalizeConfigDoc(doc: SettingsDoc): SettingsDoc { export class SettingsService { private readonly configStore: YamlDocStore private readonly stateStore: YamlDocStore + private readonly serverFlags: ServerFlagReader constructor( private readonly location: ConfigLocation, @@ -91,6 +95,7 @@ export class SettingsService { logger.child({ component: "settings-state" }), { throwOnPersistError: true }, ) + this.serverFlags = new ServerFlagReader(location.configYamlPath) } /** Identity failures disable native backend admission while startup continues. */ @@ -154,11 +159,26 @@ export class SettingsService { const current = this.configStore.get() const normalized = normalizeConfigDoc(current) if (!isDeepEqual(current, normalized)) { - this.configStore.replace(normalized) + // Normalize what is on disk now; an unreadable document is displayed, never rewritten. + let fresh: SettingsDoc + try { + fresh = this.configStore.reloadAuthoritative() + } catch (error) { + if (error instanceof SettingsReadError) return normalized + throw error + } + const repaired = normalizeConfigDoc(fresh) + if (!isDeepEqual(fresh, repaired)) this.configStore.replace(repaired) + return repaired } return normalized } + /** Authoritative boolean server setting for access decisions; see `ServerFlagReader`. */ + serverFlag(key: string): boolean { + return this.serverFlags.enabled(key) + } + readEnvironmentForAdmission(signal?: AbortSignal): Promise> { return readAdmissionEnvironment(this.location, signal) } @@ -168,14 +188,24 @@ export class SettingsService { return this.location.configYamlPath } - mergePatchDoc(kind: DocKind, patch: unknown): SettingsDoc { + /** + * Config writes start from the document as it is on disk now (`reloadAuthoritative`), so a + * stale cache is never written back; an unreadable or invalid document refuses the write + * with `SettingsReadError`. `check` sees that base and the result before anything persists. + */ + mergePatchDoc(kind: DocKind, patch: unknown, check?: ConfigWriteCheck): SettingsDoc { if (!isPlainObject(patch)) { throw new Error("Patch must be a JSON object") } - const updated = - kind === "config" - ? this.configStore.replace(normalizeConfigDoc(applyMergePatch(this.configStore.get(), patch) as SettingsDoc)) - : this.stateStore.mergePatch(patch) + let updated: SettingsDoc + if (kind === "config") { + const before = this.configStore.reloadAuthoritative() + const after = normalizeConfigDoc(applyMergePatch(before, patch) as SettingsDoc) + check?.(before, after) + updated = this.configStore.replace(after) + } else { + updated = this.stateStore.mergePatch(patch) + } this.publish(kind, "*") return updated } @@ -197,19 +227,21 @@ export class SettingsService { return value } - mergePatchOwner(kind: DocKind, owner: string, patch: unknown): SettingsDoc { + /** See `mergePatchDoc` for the config write base and `check`. */ + mergePatchOwner(kind: DocKind, owner: string, patch: unknown, check?: ConfigWriteCheck): SettingsDoc { if (!isPlainObject(patch)) { throw new Error("Patch must be a JSON object") } - const updated = - kind === "config" - ? owner === "server" - ? this.configStore.replaceOwner( - owner, - normalizeServerConfigOwner(applyMergePatch(this.configStore.getOwner(owner), patch) as SettingsDoc), - ) - : this.configStore.mergePatchOwner(owner, patch) - : this.stateStore.mergePatchOwner(owner, patch) + let updated: SettingsDoc + if (kind === "config") { + const before = this.configStore.reloadAuthoritative() + const merged = applyMergePatch(this.configStore.getOwner(owner), patch) as SettingsDoc + const next = owner === "server" ? normalizeServerConfigOwner(merged) : merged + check?.(before, { ...before, [owner]: next }) + updated = this.configStore.replaceOwner(owner, next) + } else { + updated = this.stateStore.mergePatchOwner(owner, patch) + } this.publish(kind, owner, updated) return updated } diff --git a/packages/server/src/settings/yaml-doc-store.ts b/packages/server/src/settings/yaml-doc-store.ts index 975cde39bf..c7b3537105 100644 --- a/packages/server/src/settings/yaml-doc-store.ts +++ b/packages/server/src/settings/yaml-doc-store.ts @@ -116,6 +116,27 @@ export class YamlDocStore { /** Fresh, read-only authority; the forgiving display cache is not a CAS base. */ getAuthoritativeOwner(owner: string): SettingsDoc { + const doc = this.readAuthoritative() + if (Object.prototype.hasOwnProperty.call(doc, owner) && !isPlainObject(doc[owner])) throw new SettingsReadError() + // Publish a refreshed cache only after a successful, valid document read. + // The following synchronous owner merge therefore retains external fields. + this.cache = doc + this.loaded = true + return doc[owner] as SettingsDoc ?? {} + } + + /** + * The document as it is on disk now, published as the cache: the base of a write, so a + * stale display cache is never written back. Unreadable or invalid documents throw. + */ + reloadAuthoritative(): SettingsDoc { + const doc = this.readAuthoritative() + this.cache = doc + this.loaded = true + return doc + } + + private readAuthoritative(): SettingsDoc { let content: string try { content = fs.readFileSync(this.filePath, "utf-8") @@ -126,11 +147,7 @@ export class YamlDocStore { try { fs.lstatSync(this.filePath) } catch (statError: any) { - if (statError?.code === "ENOENT") { - this.cache = {} - this.loaded = true - return {} - } + if (statError?.code === "ENOENT") return {} } } throw new SettingsReadError() @@ -143,12 +160,7 @@ export class YamlDocStore { throw new SettingsReadError() } if (!isPlainObject(doc)) throw new SettingsReadError() - if (Object.prototype.hasOwnProperty.call(doc, owner) && !isPlainObject(doc[owner])) throw new SettingsReadError() - // Publish a refreshed cache only after a successful, valid document read. - // The following synchronous owner merge therefore retains external fields. - this.cache = doc - this.loaded = true - return doc[owner] as SettingsDoc ?? {} + return doc } replaceOwner(owner: string, value: unknown): SettingsDoc { diff --git a/packages/server/src/usage/opencode-free-estimate.test.ts b/packages/server/src/usage/opencode-free-estimate.test.ts index 003f542c5a..88ddd83400 100644 --- a/packages/server/src/usage/opencode-free-estimate.test.ts +++ b/packages/server/src/usage/opencode-free-estimate.test.ts @@ -1,6 +1,6 @@ import assert from "node:assert/strict" import { test } from "node:test" -import { OPENCODE_FREE_DAILY_REQUESTS, isOpenCodeFreeModel, openCodeFreeWindow } from "./opencode-free-estimate" +import { OPENCODE_FREE_DAILY_REQUESTS, isOpenCodeFreeModel } from "./opencode-free-estimate" test("only OpenCode Console free models use the 800-request reference", () => { assert.equal(OPENCODE_FREE_DAILY_REQUESTS, 800) @@ -12,10 +12,3 @@ test("only OpenCode Console free models use the 800-request reference", () => { assert.equal(isOpenCodeFreeModel(" OPENCODE ", " Example-FREE "), true) assert.equal(isOpenCodeFreeModel("opencode-go", "example-free"), false) }) - -test("Console's calendar day begins at 00:00 UTC and resets at the next UTC midnight", () => { - const now = Date.UTC(2026, 10, 3, 21, 30) - const window = openCodeFreeWindow(now) - assert.deepEqual(window, { from: Date.UTC(2026, 10, 3), to: now, resetAt: Date.UTC(2026, 10, 4) }) - assert.equal(openCodeFreeWindow(Date.UTC(2026, 10, 3)).to, Date.UTC(2026, 10, 3), "midnight has no elapsed activity") -}) diff --git a/packages/server/src/usage/opencode-free-estimate.ts b/packages/server/src/usage/opencode-free-estimate.ts index d367b545f7..4031a998f8 100644 --- a/packages/server/src/usage/opencode-free-estimate.ts +++ b/packages/server/src/usage/opencode-free-estimate.ts @@ -1,15 +1,8 @@ // ponytail: the daily reference is observed, not supplied by the Console API. // Replace it with an upstream allowance when that contract becomes available. export const OPENCODE_FREE_DAILY_REQUESTS = 800 -const DAY_MS = 86_400_000 export function isOpenCodeFreeModel(providerId: string, modelId?: string): boolean { const model = modelId?.trim().toLowerCase() return providerId.trim().toLowerCase() === "opencode" && !!model && (model === "big-pickle" || model.endsWith("-free")) } - -/** UTC calendar day used by Console's 24h range. */ -export function openCodeFreeWindow(now: number) { - const from = Math.floor(now / DAY_MS) * DAY_MS - return { from, to: now, resetAt: from + DAY_MS } -} diff --git a/packages/server/src/usage/opencode-free-exhaustion.test.ts b/packages/server/src/usage/opencode-free-exhaustion.test.ts deleted file mode 100644 index a0195a8d5c..0000000000 --- a/packages/server/src/usage/opencode-free-exhaustion.test.ts +++ /dev/null @@ -1,75 +0,0 @@ -import assert from "node:assert/strict" -import test from "node:test" -import type { ServiceConnection } from "../workspaces/opencode-service" -import { createOpenCodeFreeExhaustion } from "./opencode-free-exhaustion" - -const midnight = Date.UTC(2026, 10, 6) -const connection = () => ({}) as ServiceConnection -const start = (created: number, model = "big-pickle", message = "m", session = "s", providerID = "opencode") => ({ - type: "session.step.started", created, data: { sessionID: session, assistantMessageID: message, model: { providerID, id: model } }, -}) -const fail = (created: number, message = "m", session = "s", type = "provider.quota") => ({ - type: "session.step.failed", created, data: { sessionID: session, assistantMessageID: message, error: { type } }, -}) - -test("exhaustion expires exactly at next UTC midnight; duplicates and old failures never extend it", () => { - const state = createOpenCodeFreeExhaustion(), c = connection() - state.observe(c, start(midnight - 3), midnight - 1) - state.observe(c, fail(midnight - 2), midnight - 1) - assert.equal(state.exhausted(c, midnight - 1), true) - assert.equal(state.exhausted(c, midnight), false) - state.observe(c, fail(midnight + 1), midnight + 1) - assert.equal(state.exhausted(c, midnight + 1), false, "duplicate message cannot extend") - state.observe(c, start(midnight - 4, "x-free", "late"), midnight + 1) - state.observe(c, fail(midnight - 3, "late"), midnight + 1) - assert.equal(state.exhausted(c, midnight + 1), false, "previous UTC day ended") - state.observe(c, start(midnight, "x-free", "new"), midnight + 1) - state.observe(c, fail(midnight + 1, "new"), midnight + 1) - state.observe(c, fail(midnight - 2), midnight + 1) - assert.equal(state.exhausted(c, midnight + 86_400_000 - 1), true) - assert.equal(state.exhausted(c, midnight + 86_400_000), false) - assert.equal(state.exhausted(c, midnight + 86_400_001), false) -}) - -test("capture is per connection/session/message and ignores the session's subsequent model", () => { - const state = createOpenCodeFreeExhaustion(), a = connection(), b = connection() - state.observe(a, start(midnight), midnight + 5) - state.observe(a, { type: "session.model.selected", data: { model: { providerID: "opencode", id: "paid" } } }, midnight + 5) - state.observe(a, fail(midnight + 1, "other"), midnight + 5) - state.observe(b, fail(midnight + 1), midnight + 5) - assert.equal(state.exhausted(a, midnight + 5), false) - state.observe(a, fail(midnight + 1), midnight + 5) - assert.equal(state.exhausted(a, midnight + 5), true) - assert.equal(state.exhausted(b, midnight + 5), false) - state.observe(b, start(midnight, "paid"), midnight + 5) - state.observe(b, fail(midnight + 1), midnight + 5) - assert.equal(state.exhausted(b, midnight + 5), false) - state.observe(b, start(midnight, "x-free", "another", "another-session"), midnight + 5) - state.observe(b, fail(midnight + 2, "another", "another-session"), midnight + 5) - assert.equal(state.exhausted(b, midnight + 5), true) - state.dispose() - assert.equal(state.exhausted(a, midnight + 5), false) -}) - -test("paid/auth/network/execution-only/missing/ambiguous/malformed attribution never marks", () => { - for (const variant of ["paid", "auth", "network", "execution", "missing", "ambiguous", "oversize", "foreign", "before-start", "future"]) { - const state = createOpenCodeFreeExhaustion(), c = connection() - if (variant !== "missing") state.observe(c, start(midnight, variant === "paid" ? "paid" : "big-pickle", "m", "s", - variant === "foreign" ? "other" : "opencode"), midnight + 5) - if (variant === "ambiguous") state.observe(c, start(midnight, "paid"), midnight + 5) - const event = fail(variant === "before-start" ? midnight - 1 : variant === "future" ? midnight + 6 : midnight + 1, - variant === "oversize" ? "m".repeat(513) : "m", "s", variant === "auth" ? "provider.auth" : variant === "network" ? "provider.network" : "provider.quota") - if (variant === "execution") event.type = "session.execution.failed" - state.observe(c, event, midnight + 5) - assert.equal(state.exhausted(c, midnight + 5), false, variant) - } -}) - -test("bounded step memo evicts old attribution conservatively", () => { - const state = createOpenCodeFreeExhaustion(), c = connection() - for (let i = 0; i <= 1024; i++) state.observe(c, start(midnight, "big-pickle", String(i)), midnight + 5) - state.observe(c, fail(midnight + 1, "0"), midnight + 5) - assert.equal(state.exhausted(c, midnight + 5), false) - state.observe(c, fail(midnight + 1, "1024"), midnight + 5) - assert.equal(state.exhausted(c, midnight + 5), true) -}) diff --git a/packages/server/src/usage/opencode-free-exhaustion.ts b/packages/server/src/usage/opencode-free-exhaustion.ts deleted file mode 100644 index 52a2973b85..0000000000 --- a/packages/server/src/usage/opencode-free-exhaustion.ts +++ /dev/null @@ -1,51 +0,0 @@ -import type { ServiceConnection } from "../workspaces/opencode-service" -import { isOpenCodeFreeModel, openCodeFreeWindow } from "./opencode-free-estimate" - -const MAX_STEPS = 1024 -const id = (value: unknown): value is string => typeof value === "string" && value.length > 0 && value.length <= 512 -type Step = { model: string | null; free: boolean; started: number; failed: boolean } -type State = { steps: Map; failedAt?: number; resetAt?: number } - -/** Display-only evidence, shared by free models on one native connection. */ -export function createOpenCodeFreeExhaustion() { - let states = new WeakMap() - return { - observe(connection: ServiceConnection, input: unknown, now = Date.now()) { - const event = input as { type?: unknown; created?: unknown; data?: { - sessionID?: unknown; assistantMessageID?: unknown; model?: { providerID?: unknown; id?: unknown }; error?: { type?: unknown } - } } | undefined - if (event?.type !== "session.step.started" && event?.type !== "session.step.failed") return - const data = event.data - if (!id(data?.sessionID) || !id(data?.assistantMessageID) || typeof event.created !== "number" || - !Number.isSafeInteger(event.created) || event.created < 0 || event.created > now) return - let state = states.get(connection) - if (!state) { state = { steps: new Map() }; states.set(connection, state) } - const key = JSON.stringify([data.sessionID, data.assistantMessageID]) - const previous = state.steps.get(key) - if (event.type === "session.step.started") { - const model = data.model - const identity = id(model?.providerID) && id(model?.id) ? JSON.stringify([model.providerID, model.id]) : null - if (previous) { - if (previous.model !== identity) { previous.model = null; previous.free = false } - return - } - if (state.steps.size >= MAX_STEPS) state.steps.delete(state.steps.keys().next().value!) - state.steps.set(key, { model: identity, free: identity !== null && isOpenCodeFreeModel(model!.providerID as string, model!.id as string), - started: event.created, failed: false }) - return - } - if (data.error?.type !== "provider.quota" || !previous?.free || previous.failed || event.created < previous.started) return - previous.failed = true - const { resetAt } = openCodeFreeWindow(event.created) - if (resetAt <= now || (state.failedAt !== undefined && event.created <= state.failedAt)) return - state.failedAt = event.created - state.resetAt = resetAt - }, - exhausted(connection: ServiceConnection, now = Date.now()) { - return (states.get(connection)?.resetAt ?? 0) > now - }, - dispose() { states = new WeakMap() }, - } -} - -export type OpenCodeFreeExhaustion = ReturnType diff --git a/packages/server/src/usage/opencode-free-usage.test.ts b/packages/server/src/usage/opencode-free-usage.test.ts index 74ae308006..76ef0dade8 100644 --- a/packages/server/src/usage/opencode-free-usage.test.ts +++ b/packages/server/src/usage/opencode-free-usage.test.ts @@ -6,12 +6,12 @@ import { createOpenCodeFreeUsage } from "./opencode-free-usage" const day = Date.UTC(2026, 10, 6) const signal = () => AbortSignal.timeout(3000) function fixture() { - const state = { key: "synthetic-one", exhausted: false } + const state = { key: "synthetic-one" } const connection = { client: { session: { stats: async () => { assert.fail("free quota must never read local stats") } }, credential: { list: async () => [{ active: true, integrationID: "opencode", value: { type: "key", key: state.key } }] }, } } as unknown as ServiceConnection - return { state, connection, exhaustion: { exhausted: () => state.exhausted } } + return { state, connection } } const row = (model: string, requests: number, index = 0) => ({ provider: `vendor-${index}`, model, totalRequests: String(requests), totalInputTokens: "0", totalOutputTokens: "0", totalCacheReadTokens: "0", totalCacheWrite5mTokens: "0", @@ -20,7 +20,7 @@ const page = (requests: number) => ({ items: [row("big-pickle", requests)], page test("Console counts are authoritative, including zero and counts above 800", async t => { t.mock.method(Date, "now", () => day + 1000) - const f = fixture(), usage = createOpenCodeFreeUsage(f.exhaustion) + const f = fixture(), usage = createOpenCodeFreeUsage() let count = 0 t.mock.method(globalThis, "fetch", async () => Response.json(page(count))) try { @@ -28,23 +28,22 @@ test("Console counts are authoritative, including zero and counts above 800", as f.state.key = `synthetic-${count}` const result = await usage.read(f.connection, "opencode", "big-pickle", signal()) assert.equal(result.ok, true) - assert.deepEqual(result.freeEstimate, { requests: count, reference: 800, exhausted: false }) + assert.deepEqual(result.freeEstimate, { requests: count, reference: 800 }) assert.equal(result.windows.daily.valueLabel, `${count} / 800`) assert.equal(result.windows.daily.usedPercent, Math.min(100, count / 800 * 100)) - f.state.exhausted = true - const marked = usage.refreshExhaustion(f.connection, result) - assert.equal(marked.freeEstimate?.requests, count) - assert.equal(marked.windows.daily.usedPercent, 100) - f.state.exhausted = false + assert.equal(result.windows.daily.resetAt, null) } } finally { usage.dispose() } }) -test("cache shares reads per credential/day, expires after 60 seconds and preserves Console zero at midnight", async t => { +test("cache shares reads per credential, expires after 60 seconds and keeps Console counts across midnight", async t => { let now = day + 1000, count = 250, calls = 0 t.mock.method(Date, "now", () => now) - t.mock.method(globalThis, "fetch", async () => { calls++; return Response.json(page(count)) }) - const f = fixture(), usage = createOpenCodeFreeUsage(f.exhaustion) + t.mock.method(globalThis, "fetch", async (input: unknown) => { + if (new URL(String(input)).pathname.endsWith("/billing/status")) return Response.json({}) + calls++; return Response.json(page(count)) + }) + const f = fixture(), usage = createOpenCodeFreeUsage() const read = () => usage.read(f.connection, "opencode", "big-pickle", signal()) try { const [a, b] = await Promise.all([read(), read()]) @@ -64,7 +63,7 @@ test("cache shares reads per credential/day, expires after 60 seconds and preser } finally { usage.dispose() } }) -test("any failed Console page discards the full count and the gauge, even with exhaustion", async t => { +test("any failed Console page discards the full count and the gauge", async t => { t.mock.method(Date, "now", () => day + 1000) for (const status of [401, 403, 500, 200]) { t.mock.method(globalThis, "fetch", async (input: unknown) => { @@ -73,12 +72,11 @@ test("any failed Console page discards the full count and the gauge, even with e return Response.json({ items: Array.from({ length: 50 }, (_, i) => row(i === 0 ? "big-pickle" : `paid-${i}`, 100, i)), pageInfo: { page: 1, pageSize: 50, total: 51, pageCount: 2 } }) }) - const f = fixture(); f.state.exhausted = true - const usage = createOpenCodeFreeUsage(f.exhaustion) + const f = fixture() + const usage = createOpenCodeFreeUsage() try { const result = await usage.read(f.connection, "opencode", "big-pickle", signal()) assert.equal(result.freeEstimate?.requests, null) - assert.equal(result.freeEstimate?.exhausted, true) assert.equal(result.ok, false) assert.deepEqual(result.windows, {}) assert.equal(result.unavailableReason, status === 401 ? "opencode-console-invalid-credential" : status === 403 @@ -92,7 +90,7 @@ test("missing or expired Console login never fetches or fabricates a count", asy t.mock.method(Date, "now", () => day + 1000) t.mock.method(globalThis, "fetch", async () => { assert.fail("Console must not be called") }) for (const expired of [false, true]) { - const f = fixture(), usage = createOpenCodeFreeUsage(f.exhaustion) + const f = fixture(), usage = createOpenCodeFreeUsage() t.mock.method(f.connection.client.credential, "list", async () => expired ? [{ active: true, integrationID: "opencode", value: { type: "oauth", access: "secret", expires: day, metadata: { server: "https://opencode.ai/console", orgID: "org_fixture" } } }] : []) try { @@ -110,11 +108,12 @@ test("a caller's deadline reports unknown without cancelling another caller's sh t.mock.method(Date, "now", () => day + 1000) let entered!: () => void, release!: (response: Response) => void, calls = 0, transport: AbortSignal | undefined const started = new Promise(resolve => { entered = resolve }) - t.mock.method(globalThis, "fetch", async (_input: unknown, init?: RequestInit) => { + t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + if (new URL(String(input)).pathname.endsWith("/billing/status")) return Response.json({}) calls++; transport = init!.signal!; entered() return new Promise(resolve => { release = resolve }) }) - const f = fixture(), usage = createOpenCodeFreeUsage(f.exhaustion), deadline = new AbortController() + const f = fixture(), usage = createOpenCodeFreeUsage(), deadline = new AbortController() try { const first = usage.read(f.connection, "opencode", "big-pickle", signal(), deadline.signal) await started @@ -136,6 +135,7 @@ test("sums only free models across sequential 24h pages", async t => { t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { const url = new URL(String(input)), n = Number(url.searchParams.get("page")) assert.equal(url.origin, "https://opencode.ai") + if (url.pathname === "/console/api/billing/status") return Response.json({}) assert.equal(url.pathname, "/console/api/usage/models") assert.equal(url.searchParams.get("range"), "24h") assert.equal(init?.redirect, "error") @@ -144,23 +144,44 @@ test("sums only free models across sequential 24h pages", async t => { ? Array.from({ length: 50 }, (_, i) => row(i === 0 ? "big-pickle" : `paid-${i}`, 100, i)) : [row("beam-free", 160), row("longcat-2.5-free", 40)], pageInfo: { page: n, pageSize: 50, total: 52, pageCount: 2 } }) }) - const f = fixture(), usage = createOpenCodeFreeUsage(f.exhaustion) + const f = fixture(), usage = createOpenCodeFreeUsage() try { assert.equal((await usage.read(f.connection, "opencode", "big-pickle", signal())).freeEstimate?.requests, 300) assert.deepEqual(pages, [1, 2]) } finally { usage.dispose() } }) -test("cross-midnight reads discard yesterday's count before publication", async t => { - let now = day + 86_400_000 - 1 +test("a read crossing midnight publishes the Console count and the credit balance", async t => { + let now = day - 1 t.mock.method(Date, "now", () => now) - const f = fixture(), usage = createOpenCodeFreeUsage(f.exhaustion) - t.mock.method(globalThis, "fetch", async () => { now++; return Response.json(page(250)) }) + t.mock.method(globalThis, "fetch", async (input: unknown) => { + now++ + return new URL(String(input)).pathname.endsWith("/billing/status") + ? Response.json({ availableMicroCents: 125_000_000 }) : Response.json(page(250)) + }) + const f = fixture(), usage = createOpenCodeFreeUsage() try { const result = await usage.read(f.connection, "opencode", "big-pickle", signal()) - assert.deepEqual(result.freeEstimate, { requests: null, reference: 800, exhausted: false }) - assert.deepEqual(result.windows, {}) - assert.equal(result.ok, false) - assert.equal((await usage.read(f.connection, "opencode", "big-pickle", signal())).freeEstimate?.requests, 250) + assert.deepEqual(result.freeEstimate, { requests: 250, reference: 800 }) + assert.equal(result.ok, true) + assert.equal(result.windows.daily.valueLabel, "250 / 800") + assert.deepEqual(result.windows.credits_balance?.balanceUSD, { remaining: 1.25 }) } finally { usage.dispose() } }) + +test("a stalled balance never holds back the free count beyond a short grace", async t => { + t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + if (new URL(String(input)).pathname.endsWith("/billing/status")) { + return new Promise((_resolve, reject) => init!.signal!.addEventListener("abort", + () => reject(new DOMException("aborted", "TimeoutError")), { once: true })) + } + return Response.json(page(70)) + }) + const f = fixture(), usage = createOpenCodeFreeUsage(), started = Date.now() + try { + const result = await usage.read(f.connection, "opencode", "big-pickle", signal()) + assert.equal(result.freeEstimate?.requests, 70) + assert.equal(result.windows.credits_balance, undefined) + assert.ok(Date.now() - started < 1500, "the three-second balance bound is not awaited") + } finally { usage.dispose() } +}) \ No newline at end of file diff --git a/packages/server/src/usage/opencode-free-usage.ts b/packages/server/src/usage/opencode-free-usage.ts index 3cc790c01b..8d294f7351 100644 --- a/packages/server/src/usage/opencode-free-usage.ts +++ b/packages/server/src/usage/opencode-free-usage.ts @@ -2,52 +2,45 @@ import { createHash } from "node:crypto" import type { ProviderUsageResponse } from "../api-types" import type { ServiceConnection } from "../workspaces/opencode-service" import { openCodeConsoleCredential, readUsageCredentials } from "./native-credentials" -import { OPENCODE_FREE_DAILY_REQUESTS, openCodeFreeWindow } from "./opencode-free-estimate" -import type { OpenCodeFreeExhaustion } from "./opencode-free-exhaustion" -import { openCodeConsoleError, readOpenCodeConsoleFreeRequests } from "./providers/opencode-console" +import { OPENCODE_FREE_DAILY_REQUESTS } from "./opencode-free-estimate" +import { openCodeConsoleError, readOpenCodeConsoleFreeRequests, startOpenCodeConsoleCredits } from "./providers/opencode-console" import type { AuthEntry } from "./types" -type ConsoleReading = Pick & { requests: number | null } +type Credits = ProviderUsageResponse["windows"][string] +type Counts = { requests: number; credits?: Credits } +type ConsoleReading = Pick & { requests: number | null; credits?: Credits } -export function createOpenCodeFreeUsage(exhaustion: Pick) { - const cache = new Map }>() +/** + * Free OpenCode models show the Console's own free-model request count (its + * rolling 24 hours) against the observed reference, plus the Console credit + * balance. Nothing is estimated locally: no reset time, no exhaustion state. + */ +export function createOpenCodeFreeUsage() { + const cache = new Map }>() const lifetime = new AbortController() - async function consoleRequests(connection: ServiceConnection, day: number, signal: AbortSignal): Promise { + async function consoleRequests(connection: ServiceConnection, signal: AbortSignal): Promise { const auth = await readUsageCredentials(connection, signal) signal.throwIfAborted() const credential = openCodeConsoleCredential(auth) if ("reason" in credential) return { requests: null, configured: credential.configured, unavailableReason: credential.reason } const entry = auth.opencode as AuthEntry - const key = `${day}:${createHash("sha256").update(JSON.stringify(entry)).digest("hex")}` + const key = createHash("sha256").update(JSON.stringify(entry)).digest("hex") const cached = cache.get(key) - if (cached && cached.expiresAt > Date.now()) return { requests: await cached.read, configured: true } + if (cached && cached.expiresAt > Date.now()) return { ...await cached.read, configured: true } if (cache.size >= 32) cache.delete(cache.keys().next().value!) const expiry = entry.type === "oauth" && typeof entry.expires === "number" ? entry.expires : Infinity - const record = { expiresAt: Math.min(openCodeFreeWindow(day).resetAt, expiry, Date.now() + 60_000), - read: readOpenCodeConsoleFreeRequests(auth, AbortSignal.any([lifetime.signal, AbortSignal.timeout(15_000)])) + const bounded = AbortSignal.any([lifetime.signal, AbortSignal.timeout(15_000)]) + const credits = startOpenCodeConsoleCredits(auth, bounded) + const record = { expiresAt: Math.min(expiry, Date.now() + 60_000), + read: readOpenCodeConsoleFreeRequests(auth, bounded) + .then(async requests => ({ requests, credits: await credits.settle() })) .catch(error => { if (cache.get(key) === record) cache.delete(key); throw error }) } cache.set(key, record) - return { requests: await record.read, configured: true } - } - function refreshExhaustion(connection: ServiceConnection, usage: ProviderUsageResponse): ProviderUsageResponse { - if (!usage.freeEstimate) return usage - const now = Date.now(), exhausted = exhaustion.exhausted(connection, now) - const sameDay = openCodeFreeWindow(usage.fetchedAt).from === openCodeFreeWindow(now).from - const requests = sameDay ? usage.freeEstimate.requests : null - const reference = OPENCODE_FREE_DAILY_REQUESTS - const usedPercent = exhausted ? 100 : Math.min(100, (requests ?? 0) / reference * 100) - return { ...usage, fetchedAt: now, ok: requests !== null, - freeEstimate: { requests, reference, exhausted }, - windows: requests === null ? {} : { daily: { - usedPercent, remainingPercent: 100 - usedPercent, windowSeconds: 86_400, - resetAt: openCodeFreeWindow(now).resetAt, - valueLabel: `${requests} / ${reference}`, - } } } + return { ...await record.read, configured: true } } return { async read(connection: ServiceConnection, providerId: string, modelId: string | undefined, signal: AbortSignal, - readSignal: AbortSignal = AbortSignal.timeout(12_000)) { - const now = Date.now(), { from } = openCodeFreeWindow(now) + readSignal: AbortSignal = AbortSignal.timeout(12_000)): Promise { const unavailable: ConsoleReading = { requests: null, configured: true, unavailableReason: "opencode-console-network-error" } const bounded = AbortSignal.any([signal, readSignal]) let abort!: () => void @@ -58,19 +51,27 @@ export function createOpenCodeFreeUsage(exhaustion: Pick { - assert.equal(++active, 1) const url = new URL(String(input)); urls.push(url.pathname + url.search) assert.equal(url.origin, "https://opencode.ai") assert.equal(init?.redirect, "error") assert.ok(init?.signal) assert.equal(new Headers(init?.headers).get("authorization"), "Bearer secret-access") assert.equal(new Headers(init?.headers).get("x-org-id"), "wrk_fixture") + // The optional balance runs beside the usage reads, which stay strictly sequential. + if (url.pathname.endsWith("/billing/status")) return Response.json({ availableMicroCents: "250000000" }) + assert.equal(++active, 1) + await Promise.resolve() active-- return Response.json(url.pathname.endsWith("summary") ? summary("0") : page(Number(url.searchParams.get("page")), 51)) }) @@ -72,12 +75,67 @@ test("reader uses fixed bounded transport, mandatory summaries and sequential pa assert.deepEqual(result.usage?.console?.requests, { "24h": 0, "7d": 0, "30d": 0 }) assert.equal(result.usage?.console?.models.length, 51) assert.deepEqual(result.usage?.console?.budgets, { status: "unavailable", items: [] }) - assert.deepEqual(urls, ["/console/api/usage/summary?range=24h", "/console/api/usage/summary?range=7d", - "/console/api/usage/summary?range=30d", "/console/api/usage/models?range=30d&page=1&pageSize=50", - "/console/api/usage/models?range=30d&page=2&pageSize=50"]) + assert.deepEqual(urls.filter(url => url !== "/console/api/billing/status"), ["/console/api/usage/summary?range=24h", + "/console/api/usage/summary?range=7d", "/console/api/usage/summary?range=30d", + "/console/api/usage/models?range=30d&page=1&pageSize=50", "/console/api/usage/models?range=30d&page=2&pageSize=50"]) + assert.equal(urls.filter(url => url === "/console/api/billing/status").length, 1) + assert.deepEqual(result.usage?.windows.credits_balance?.balanceUSD, { remaining: 2.5 }) assert.equal(JSON.stringify(result).includes("secret-"), false) }) +test("a stalled optional balance never fails usage reads finishing near the deadline", async t => { + const timeout = AbortSignal.timeout.bind(AbortSignal) + // Scaled deadlines: 15 s overall becomes 300 ms, the 3 s balance bound 100 ms. + t.mock.method(AbortSignal, "timeout", (ms: number) => timeout(ms === 15_000 ? 300 : ms === 3000 ? 100 : ms)) + const started = Date.now() + t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + const url = new URL(String(input)) + if (url.pathname.endsWith("/billing/status")) { + return new Promise((_resolve, reject) => init!.signal!.addEventListener("abort", + () => reject(new DOMException("aborted", "TimeoutError")), { once: true })) + } + // The usage reads finish at about 220 ms, after the balance's own bound. + await new Promise(resolve => setTimeout(resolve, Math.max(0, started + 220 - Date.now()))) + return Response.json(url.pathname.endsWith("summary") ? summary() : page()) + }) + const result = await openCodeConsole.fetchQuota(key) + assert.equal(result.ok, true, result.unavailableReason) + assert.equal(result.usage?.windows.credits_balance, undefined) +}) + +test("completed usage reads return within the caller's remaining budget while the balance stalls", async t => { + const timeout = AbortSignal.timeout.bind(AbortSignal) + // The caller's budget (400 ms) ends before the balance's own bound (3 s, scaled to 1 s). + t.mock.method(AbortSignal, "timeout", (ms: number) => timeout(ms === 3000 ? 1000 : ms)) + t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + if (new URL(String(input)).pathname.endsWith("/billing/status")) { + return new Promise((_resolve, reject) => init!.signal!.addEventListener("abort", + () => reject(new DOMException("aborted", "TimeoutError")), { once: true })) + } + return Response.json(new URL(String(input)).pathname.endsWith("summary") ? summary() : page()) + }) + const result = await openCodeConsole.fetchQuota(key, { signal: AbortSignal.timeout(400) } as never) + assert.equal(result.ok, true, result.unavailableReason) + assert.equal(result.usage?.windows.credits_balance, undefined) +}) + +for (const delay of [0, 450]) { + test(`a billing 401 ${delay ? "after the grace" : "at once"} only omits the balance`, async t => { + t.mock.method(globalThis, "fetch", async (input: unknown) => { + const url = new URL(String(input)) + if (url.pathname.endsWith("/billing/status")) { + await new Promise(resolve => setTimeout(resolve, delay)) + return new Response("secret-upstream", { status: 401 }) + } + return Response.json(url.pathname.endsWith("summary") ? summary() : page()) + }) + const result = await openCodeConsole.fetchQuota(key) + assert.equal(result.ok, true, result.unavailableReason) + assert.equal(result.usage?.windows.credits_balance, undefined) + assert.equal(JSON.stringify(result).includes("secret"), false) + }) +} + test("API key uses only Authorization; missing/invalid OAuth and third-party credentials send nothing", async t => { let calls = 0 t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { @@ -87,7 +145,7 @@ test("API key uses only Authorization; missing/invalid OAuth and third-party cre return Response.json(String(input).includes("summary") ? summary() : page()) }) assert.equal((await openCodeConsole.fetchQuota(key)).ok, true) - assert.equal(calls, 4) + assert.equal(calls, 5, "three summaries, the model page and the credit balance") for (const [auth, reason, configured] of [ [{}, "missing-credential", false], [oauth({ expires: 1 }), "invalid-credential", true], @@ -102,13 +160,17 @@ test("API key uses only Authorization; missing/invalid OAuth and third-party cre assert.equal(result.unavailableReason, `opencode-console-${reason}`) assert.equal(result.configured, configured) } - assert.equal(calls, 4) + assert.equal(calls, 5, "rejected credentials add no request") }) for (const [status, reason] of [[401, "invalid-credential"], [403, "access-denied"], [500, "network-error"]] as const) { test(`HTTP ${status} is a redacted ${reason} without fallback`, async t => { let calls = 0 - t.mock.method(globalThis, "fetch", async () => { calls++; return new Response("secret-upstream", { status }) }) + t.mock.method(globalThis, "fetch", async (input: unknown) => { + // The optional balance read runs beside the first usage read; only usage reads count. + if (!String(input).endsWith("/billing/status")) calls++ + return new Response("secret-upstream", { status }) + }) const result = await openCodeConsole.fetchQuota(oauth()) assert.equal(result.unavailableReason, `opencode-console-${reason}`) assert.equal(result.usage, null) @@ -136,6 +198,8 @@ for (const failure of ["unsafe", "oversize", "json", "bound", "changed", "sum", const controller = new AbortController() let calls = 0 t.mock.method(globalThis, "fetch", async (input: unknown, init?: RequestInit) => { + // Each failure applies to the usage reads; the optional balance stays neutral. + if (String(input).endsWith("/billing/status")) return Response.json({}) calls++ if (failure === "redirect") { assert.equal(init?.redirect, "error"); throw new TypeError("secret redirect") } if (failure === "network") throw new Error("secret network") @@ -182,6 +246,7 @@ test("the permitted 1,000-row boundary reads exactly 20 sequential pages", async calls++ const url = new URL(String(input)) if (url.pathname.endsWith("summary")) return Response.json(summary()) + if (url.pathname.endsWith("/billing/status")) return Response.json({}) const number = Number(url.searchParams.get("page")) assert.equal(number, expectedPage++) return Response.json(page(number, 1000)) @@ -189,6 +254,6 @@ test("the permitted 1,000-row boundary reads exactly 20 sequential pages", async const result = await openCodeConsole.fetchQuota(key) assert.equal(result.ok, true) assert.equal(result.usage?.console?.models.length, 1000) - assert.equal(calls, 23) + assert.equal(calls, 24) assert.equal(expectedPage, 21) }) diff --git a/packages/server/src/usage/providers/opencode-console.ts b/packages/server/src/usage/providers/opencode-console.ts index 30ec067004..bad646c4b0 100644 --- a/packages/server/src/usage/providers/opencode-console.ts +++ b/packages/server/src/usage/providers/opencode-console.ts @@ -1,9 +1,11 @@ import type { OpenCodeConsoleUsage, ProviderUsageUnavailableReason } from "../../api-types-provider-usage" +import type { ProviderUsageWindow } from "../../api-types" import { BoundedResponseError, fetchBoundedJson } from "../bounded-fetch" import { openCodeConsoleCredential } from "../native-credentials" import { ProviderHttpError } from "../shared" import type { AuthFile, ProviderResult, UsageProvider } from "../types" import { isOpenCodeFreeModel } from "../opencode-free-estimate" +import { parseOpenCodeConsoleBalance } from "../opencode-go-quota" const BASE = "https://opencode.ai/console" const PAGE_SIZE = 50 @@ -83,7 +85,7 @@ async function readModels(range: "24h" | "30d", read: (path: string) => Promise< return models } -/** Console's 24h range begins at UTC midnight. Failure stays unknown, never zero. */ +/** Sum the Console's free-model counts. Failure stays unknown, never zero. */ export async function readOpenCodeConsoleFreeRequests(auth: AuthFile, signal: AbortSignal): Promise { const credential = openCodeConsoleCredential(auth) if ("reason" in credential) throw new Error("Console credential unavailable") @@ -95,6 +97,44 @@ export async function readOpenCodeConsoleFreeRequests(auth: AuthFile, signal: Ab .reduce((sum, row) => integer(sum + row.requests), 0) } +/** + * The optional Console credit balance. Every failure (including 401: the usage + * reads already authenticate the same credential) only omits it. + */ +async function readOpenCodeConsoleCredits(auth: AuthFile, signal: AbortSignal): Promise { + const credential = openCodeConsoleCredential(auth) + if ("reason" in credential) return undefined + try { + return parseOpenCodeConsoleBalance(await fetchBoundedJson(`${BASE}/api/billing/status`, credential.headers, + AbortSignal.any([signal, AbortSignal.timeout(3000)]))) + } catch { + return undefined + } +} + +const BALANCE_GRACE_MS = 250 + +/** + * Starts the optional balance read beside the usage reads. `settle` is awaited + * once those reads are complete: it waits at most a short grace (or until + * cancellation) and then omits the balance, so the optional read never spends + * the caller's remaining budget or changes the reading's outcome. + */ +export function startOpenCodeConsoleCredits(auth: AuthFile, signal: AbortSignal) { + const credits = readOpenCodeConsoleCredits(auth, signal) + return { + settle: () => new Promise(resolve => { + const done = (value: ProviderUsageWindow | undefined) => { + clearTimeout(timer); signal.removeEventListener("abort", omit); resolve(value) + } + const omit = () => done(undefined) + const timer = setTimeout(omit, BALANCE_GRACE_MS) + signal.addEventListener("abort", omit, { once: true }) + void credits.then(done) + }), + } +} + // Only stable codes survive; never retain upstream bodies or messages. export function openCodeConsoleError(error: unknown): ProviderUsageUnavailableReason { return error instanceof ProviderHttpError @@ -114,14 +154,19 @@ export const openCodeConsole: UsageProvider = { if ("reason" in credential) return { ...base, configured: credential.configured, unavailableReason: credential.reason } const bounded = context?.signal ? AbortSignal.any([context.signal, AbortSignal.timeout(15_000)]) : AbortSignal.timeout(15_000) const read = (path: string) => fetchBoundedJson(`${BASE}/api/${path}`, credential.headers, bounded) + const credits = startOpenCodeConsoleCredits(auth, bounded) try { const requests = {} as OpenCodeConsoleUsage["requests"] for (const range of ["24h", "7d", "30d"] as const) { requests[range] = parseOpenCodeConsoleSummary(await read(`usage/summary?range=${range}`)).requests } const models = await readModels("30d", read) + const windows: NonNullable["windows"] = {} + bounded.throwIfAborted() + const balance = await credits.settle() + if (balance) windows.credits_balance = balance bounded.throwIfAborted() - return { ...base, ok: true, usage: { windows: {}, console: { + return { ...base, ok: true, usage: { windows, console: { requests, models, budgets: { status: "unavailable", items: [] }, } } } } catch (error) { diff --git a/packages/server/src/usage/service.test.ts b/packages/server/src/usage/service.test.ts index b09b429fa8..a33399bb97 100644 --- a/packages/server/src/usage/service.test.ts +++ b/packages/server/src/usage/service.test.ts @@ -510,6 +510,6 @@ test("a cached Console success expires with its OAuth credential, without anothe assert.equal(expired.ok, false) assert.equal(expired.console, undefined) assert.equal(expired.unavailableReason, "opencode-console-invalid-credential") - assert.equal(calls, 4) + assert.equal(calls, 5, "one cached read: three summaries, the model page and the credit balance") } finally { clearProviderUsageCache() } }) diff --git a/packages/server/src/workspaces/instance-events.test.ts b/packages/server/src/workspaces/instance-events.test.ts index 824911a47e..686b59ffd9 100644 --- a/packages/server/src/workspaces/instance-events.test.ts +++ b/packages/server/src/workspaces/instance-events.test.ts @@ -849,7 +849,7 @@ describe("InstanceEventBridge", () => { const connectionFor = (pid: number) => ({ endpoint: Object.assign( { url: "http://127.0.0.1:4010", auth: { username: "u", password: "p" } }, - { [runtimeKey]: Object.freeze({ version: "2.2.3", pid, contract: {} }) }, + { [runtimeKey]: Object.freeze({ version: "2.3.0", pid, contract: {} }) }, ), }) const first = serverConnected() @@ -888,7 +888,7 @@ describe("InstanceEventBridge", () => { // The relayed identity must not be a digest a subscriber can recompute // from known fields: that would be an offline verifier for the password. const verifiable = createHash("sha256").update(JSON.stringify([ - "http://127.0.0.1:4010", "2.2.3", 4242, "u", "p", + "http://127.0.0.1:4010", "2.3.0", 4242, "u", "p", ])).digest("hex") assert.notEqual(received[0].data.daemon, verifiable, "the token is server-held, not a recomputable digest") for (const digest of [received[0].data.daemon, received[2].data.daemon]) { @@ -904,7 +904,7 @@ describe("InstanceEventBridge", () => { const connection = { endpoint: Object.assign( { url: "http://127.0.0.1:4011" }, - { [runtimeKey]: Object.freeze({ version: "2.2.3", pid: 4242, contract: {} }) }, + { [runtimeKey]: Object.freeze({ version: "2.3.0", pid: 4242, contract: {} }) }, ), } const firstSubscription = serverConnected() @@ -944,7 +944,7 @@ describe("InstanceEventBridge", () => { const connectionFor = (pid: number) => ({ endpoint: Object.assign( { url: "http://127.0.0.1:4012" }, - { [runtimeKey]: Object.freeze({ version: "2.2.3", pid, contract: {} }) }, + { [runtimeKey]: Object.freeze({ version: "2.3.0", pid, contract: {} }) }, ), }) const before = serverConnected() @@ -982,7 +982,7 @@ describe("InstanceEventBridge", () => { const connection = { endpoint: Object.assign( { url: "http://127.0.0.1:4013" }, - { [runtimeKey]: Object.freeze({ version: "2.2.3", pid: 3333, contract: {} }) }, + { [runtimeKey]: Object.freeze({ version: "2.3.0", pid: 3333, contract: {} }) }, ), } const attributedStream = () => { diff --git a/packages/tauri-app/src-tauri/examples/menu-layout-linux.rs b/packages/tauri-app/src-tauri/examples/menu-layout-linux.rs new file mode 100644 index 0000000000..7b5784ff4f --- /dev/null +++ b/packages/tauri-app/src-tauri/examples/menu-layout-linux.rs @@ -0,0 +1,146 @@ +//! Linux native regression: a window whose menu bar stays visible (remote windows) +//! keeps its page inside the space below the menu, initially, after maximizing and +//! after a child webview (browser preview) joins it at its requested rectangle. +//! Run in an unlocked graphical session with `GDK_BACKEND=x11` and +//! `GDK_BACKEND=wayland`: `cargo run --example menu-layout-linux`. Exits 1 when the +//! page viewport differs from the webview's GTK allocation or that allocation +//! leaves the window. + +#[cfg(not(target_os = "linux"))] +fn main() {} + +/// WebKit views below `widget`, depth first: the primary view precedes children. +#[cfg(target_os = "linux")] +fn webkit_views(widget: >k::Widget, found: &mut Vec) { + use gtk::prelude::*; + if widget.is::() { + found.push(widget.clone()); + } else if let Some(container) = widget.downcast_ref::() { + for child in container.children() { + webkit_views(&child, found); + } + } +} + +/// Serves `body` on a loopback port for the trial's lifetime; returns its URL. +#[cfg(target_os = "linux")] +fn serve(body: &'static str) -> String { + use std::io::{Read, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("loopback listener"); + let url = format!( + "http://{}/", + listener.local_addr().expect("listener address") + ); + std::thread::spawn(move || { + for mut stream in listener.incoming().flatten() { + let _ = stream.read(&mut [0; 4096]); + let _ = write!( + stream, + "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ); + } + }); + url +} + +#[cfg(target_os = "linux")] +fn main() { + use gtk::prelude::*; + use std::sync::atomic::{AtomicI32, Ordering}; + use std::sync::Arc; + use std::time::{Duration, Instant}; + + const CHILD: (i32, i32, i32, i32) = (10, 20, 200, 100); + let viewport = Arc::new(AtomicI32::new(-1)); + let page = serve(""); + tauri::Builder::default() + .setup(move |app| { + let item = tauri::menu::MenuItem::with_id(app, "noop", "Noop", true, None::<&str>)?; + let file = tauri::menu::Submenu::with_items(app, "File", true, &[&item])?; + app.set_menu(tauri::menu::Menu::with_items(app, &[&file])?)?; + let reported = viewport.clone(); + let url: tauri::Url = page.parse()?; + let window = tauri::WebviewWindowBuilder::new( + app, + "menu-layout", + tauri::WebviewUrl::External(url.clone()), + ) + .title("CodeNomad menu layout") + .inner_size(760.0, 540.0) + .on_document_title_changed(move |_, title| { + if let Some(height) = title.strip_prefix('h').and_then(|h| h.parse().ok()) { + reported.store(height, Ordering::Release); + } + }) + .build()?; + let deadline = Instant::now() + Duration::from_secs(30); + let (mut phase, mut stable, mut first_height) = ("initial", 0, 0); + gtk::glib::timeout_add_local(Duration::from_millis(100), move || { + let vbox = window.default_vbox().expect("GTK content box"); + let menu = vbox + .children() + .into_iter() + .find(|child| child.is::() && child.is_visible()) + .map_or(0, |bar| bar.allocated_height()); + let mut views = Vec::new(); + webkit_views(vbox.upcast_ref(), &mut views); + let view = views.first().expect("primary WebKit view"); + let (_, top) = view.translate_coordinates(&vbox, 0, 0).unwrap_or((0, -1)); + let (height, total) = (view.allocated_height(), vbox.allocated_height()); + let page = viewport.load(Ordering::Acquire); + // The child rectangle is relative to the content below the menu bar. + let child = views.get(1).map(|child| { + let (x, y) = child.translate_coordinates(&vbox, 0, 0).unwrap_or((-1, -1)); + (x, y - menu, child.allocated_width(), child.allocated_height()) + }); + let state = format!( + "menu {menu}, view y {top} h {height}, content {total}, page {page}, child {child:?}" + ); + let fits = menu > 0 && top >= menu && top + height <= total && page == height; + let ready = match phase { + "initial" => fits, + "maximized" => fits && total > first_height, + _ => fits && child == Some(CHILD), + }; + stable = if ready { stable + 1 } else { 0 }; + if stable >= 3 { + println!("PASS {phase}: {state}"); + stable = 0; + match phase { + "initial" => { + first_height = total; + // Wayland compositors may ignore client size requests, + // never maximization; both reach Tauri's auto-resize. + let _ = window.maximize(); + phase = "maximized"; + } + "maximized" => { + let builder = tauri::webview::WebviewBuilder::new( + "menu-layout-child", + tauri::WebviewUrl::External(url.clone()), + ); + window + .as_ref() + .window() + .add_child( + builder, + tauri::LogicalPosition::new(CHILD.0, CHILD.1), + tauri::LogicalSize::new(CHILD.2, CHILD.3), + ) + .expect("child webview"); + phase = "child"; + } + _ => std::process::exit(0), + } + } else if Instant::now() > deadline { + eprintln!("FAIL {phase}: {state}"); + std::process::exit(1); + } + gtk::glib::ControlFlow::Continue + }); + Ok(()) + }) + .run(tauri::test::mock_context(tauri::test::noop_assets())) + .expect("menu layout trial"); +} diff --git a/packages/tauri-app/vendor/README.md b/packages/tauri-app/vendor/README.md index df30040c3f..ea262e2562 100644 --- a/packages/tauri-app/vendor/README.md +++ b/packages/tauri-app/vendor/README.md @@ -16,8 +16,10 @@ MIT/Apache-2.0 crates, including licenses, selected through `[patch.crates-io]`. `patches/wry-browser-private-preview.patch` and `patches/runtime-browser-private-preview.patch`; native trials ship beside the runtime examples. - GTK: the runtime lazily installs a window-owned `GtkOverlay` inside Tao's - content box, below its menu bar. Primary content stays boxed; child webviews use - `GtkFixed`. The overlay passes uncovered input through to the primary view. + content box, below its menu bar. Primary content stays boxed, including a + window's own webview in Tauri's multi-webview mode (it requests no bounds), so a + visible menu bar never pushes it past the window; child webviews use `GtkFixed`. + The overlay passes uncovered input through to the primary view. Primary-only windows keep their ordinary box. Reparenting uses the destination window's own child container. - Wry stores child positions in `GtkFixed` and sizes in GTK size requests, alongside @@ -80,6 +82,12 @@ module and vendored Wry, then exercises Wayland and X11 with native input: rectangles, relayout, menus, reparenting, hide/show, independent owning windows, destruction, permission/download denial and distinct persistent data managers. Full application checks additionally exercise Tauri's dispatch integration. +`cargo run --example menu-layout-linux` (from `packages/tauri-app`, in an unlocked +X11 and Wayland session) runs the runtime itself with a visible menu bar: the +window's page must match its allocation below the menu initially, after maximizing +and after a child webview joins at its requested rectangle. Its negative control +builds the window's own webview into the child `GtkFixed`, which overflows by the +menu bar's height. The Tauri workspace's `[patch.crates-io]` (`packages/tauri-app/Cargo.toml`) diff --git a/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch b/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch index 3b9055f488..613ebbbcc4 100644 --- a/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch +++ b/packages/tauri-app/vendor/patches/tauri-runtime-wry-gtk.patch @@ -84,19 +84,40 @@ } else { Err(wry::Error::MessageSender) } -@@ -5169,9 +5178,9 @@ +@@ -4896,6 +4905,13 @@ + }); + } + ++ #[cfg(not(any( ++ target_os = "windows", ++ target_os = "macos", ++ target_os = "ios", ++ target_os = "android" ++ )))] ++ let fills_window = webview_attributes.bounds.is_none(); + let webview_bounds = if let Some(bounds) = webview_attributes.bounds { + let bounds: RectWrapper = bounds.into(); + let bounds = bounds.0; +@@ -5169,9 +5185,16 @@ target_os = "android" )))] WebviewKind::WindowChild => { - // only way to account for menu bar height, and also works for multiwebviews :) let vbox = window.default_vbox().unwrap(); - webview_builder.build_gtk(vbox) -+ let (_, children) = gtk_child_layout::containers(vbox); -+ webview_builder.build_gtk(&children) ++ // The window's own webview has no requested bounds: it is primary content, ++ // laid out below the menu bar, never a fixed rectangle of the window's size. ++ if fills_window { ++ let content = gtk_child_layout::content(vbox); ++ webview_builder.build_gtk(&content) ++ } else { ++ let (_, children) = gtk_child_layout::containers(vbox); ++ webview_builder.build_gtk(&children) ++ } } #[cfg(any( target_os = "windows", -@@ -5196,7 +5205,8 @@ +@@ -5196,7 +5219,8 @@ )))] let builder = { let vbox = window.default_vbox().unwrap(); diff --git a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs index c0d93f4184..933e42ac69 100644 --- a/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs +++ b/packages/tauri-app/vendor/tauri-runtime-wry-2.12.3/src/lib.rs @@ -4906,6 +4906,13 @@ You may have it installed on another user account, but it is not available for t }); } + #[cfg(not(any( + target_os = "windows", + target_os = "macos", + target_os = "ios", + target_os = "android" + )))] + let fills_window = webview_attributes.bounds.is_none(); let webview_bounds = if let Some(bounds) = webview_attributes.bounds { let bounds: RectWrapper = bounds.into(); let bounds = bounds.0; @@ -5192,8 +5199,15 @@ You may have it installed on another user account, but it is not available for t )))] WebviewKind::WindowChild => { let vbox = window.default_vbox().unwrap(); - let (_, children) = gtk_child_layout::containers(vbox); - webview_builder.build_gtk(&children) + // The window's own webview has no requested bounds: it is primary content, + // laid out below the menu bar, never a fixed rectangle of the window's size. + if fills_window { + let content = gtk_child_layout::content(vbox); + webview_builder.build_gtk(&content) + } else { + let (_, children) = gtk_child_layout::containers(vbox); + webview_builder.build_gtk(&children) + } } #[cfg(any( target_os = "windows", diff --git a/packages/ui/package.json b/packages/ui/package.json index c0b9d2b43e..2276d9ff98 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -18,7 +18,7 @@ "@kobalte/core": "0.13.11", "@mermaid-js/tiny": "12.3.0", "@noble/hashes": "2.4.0", - "@opencode/client": "2.2.3", + "@opencode/client": "2.3.0", "@solidjs/router": "^0.13.0", "@suid/material": "^0.19.0", "@suid/system": "^0.14.0", diff --git a/packages/ui/src/components/backend-view-lifetime.test.ts b/packages/ui/src/components/backend-view-lifetime.test.ts index ec1fda66c7..a92dd737d4 100644 --- a/packages/ui/src/components/backend-view-lifetime.test.ts +++ b/packages/ui/src/components/backend-view-lifetime.test.ts @@ -5,6 +5,7 @@ import ts from "typescript" import { createEffect, createMemo, createRoot, createSignal, on, onCleanup, untrack } from "solid-js" import { z } from "zod" import { BackgroundReadQueue } from "../lib/background-read-queue" +import { integrationAttachChoice, integrationLink } from "../lib/integration-row-state" // Execute the real view functions, with imports supplied explicitly. No JSX or // application singleton is needed to test their asynchronous authority boundary. @@ -138,11 +139,71 @@ test("integrations: old consent cannot admit an installation on a new attachment close() }) +test("integrations: reinstall stays confirmed for open and closed applications", async () => { + const backend = attachment(), titles: string[] = [] + let installs = 0, close!: () => void + const [host, setHost] = createSignal({ state: "available" }) + const { createIntegrationHostInstallation } = view("./integration-host-installation.ts", { ...solid, + captureBackendOperation: backend.capture, useI18n: () => ({ t: (key: string) => key }), + integrationEpoch: () => "epoch", integrations: { refreshDemanded: () => {} }, + confirmIntegrationAction: async (_warning: string, options: { title: string }) => { titles.push(options.title); return true }, + integrationAttachmentRequest: async () => { installs++; return { outcome: "unchanged" } }, + showToastNotification: () => {}, HttpResponseError: Error, document: { activeElement: null }, HTMLElement: class {}, + }) + const installation = createRoot(dispose => { close = dispose; return createIntegrationHostInstallation({ + instanceId: "i", directory: "/repo", entries: () => [ + { id: "integration", family: "native", state: "ok", app: { name: "App" }, status: { version: "1", host: host() } }, + ], + }) }) + for (const state of ["available", "unknown"]) { + setHost({ state }) + assert.equal(installation.action("integration"), "reinstall") + await installation.open("integration") + } + setHost({ state: "unsupported" }) + assert.equal(installation.action("integration"), undefined) + await installation.open("integration") + assert.deepEqual(titles, ["integrations.installHost.reinstall", "integrations.installHost.reinstall"]) + assert.equal(installs, 2) + close() +}) + +test("integrations: state-line document reads reacquire and fence late backend replies", async () => { + const backend = attachment(), reads: ReturnType>[] = [] + let close!: () => void + const { createIntegrationRowBinding } = view("./integration-row-binding.ts", { ...solid, + captureBackendOperation: backend.capture, + backendEvents: { signalForInstance: () => backend.capture("i").signal }, + integrationEpoch: () => "epoch", integrationLink, integrationAttachChoice, + integrationBindings: { demand: () => () => {}, state: () => ({ state: "none" }), busy: () => false }, + useI18n: () => ({ t: (key: string) => key }), showToastNotification: () => {}, + integrationAttachmentRequest: () => { const read = deferred(); reads.push(read); return read.promise }, + }) + const row = createRoot(dispose => { close = dispose; return createIntegrationRowBinding({ + instanceId: () => "i", directory: () => "/repo", sessionId: () => "ses_1", active: () => true, + integration: () => ({ id: "integration", family: "native", state: "ok", status: { host: { state: "available" }, connection: { offers: 1 } } }), + }) }) + assert.equal(reads.length, 1) + backend.replace() + assert.equal(reads.length, 2) + const current = [{ offerID: "new", protocol: "ok", label: "Current" }] + reads[1].resolve({ offers: current }); await flush() + assert.deepEqual(row.offers(), current) + reads[0].resolve({ offers: [{ offerID: "old", protocol: "ok", label: "Old" }] }); await flush() + assert.deepEqual(row.offers(), current) + backend.replace() + assert.equal(row.offers(), undefined) + assert.equal(reads.length, 3) + close() + reads[2].resolve({ offers: current }); await flush() + assert.equal(row.offers(), undefined) +}) + test("providers: an old quota response cannot publish or perform its coalesced follow-up", async () => { const backend = attachment(), response = deferred(), published: unknown[] = [] let reads = 0 const { createProviderUsageState } = view("./session/provider-usage-state.ts", {}) - const state = createProviderUsageState(() => { reads++; return response.promise }, (value: unknown) => published.push(value), Date.now, () => backend.capture("i")) + const state = createProviderUsageState(() => { reads++; return response.promise }, (value: unknown) => published.push(value), () => backend.capture("i")) state.select({ instanceId: "i", sessionId: "s", directory: "/repo", providerId: "p", modelId: "m" }) const pending = state.refresh(); state.refresh() backend.revoke(); response.resolve({ account: "old" }); await pending diff --git a/packages/ui/src/components/folder-selection-view.tsx b/packages/ui/src/components/folder-selection-view.tsx index 15d8ac83ab..6fedc24076 100644 --- a/packages/ui/src/components/folder-selection-view.tsx +++ b/packages/ui/src/components/folder-selection-view.tsx @@ -19,7 +19,7 @@ import { renameProject } from "../stores/project-names" import { LocaleSelector } from "./locale-selector" import { createNewInstanceDialogs } from "./new-instance-dialogs" import { useRemoteServerProfiles } from "../lib/hooks/use-remote-server-profiles" -import { getServerMeta, localRequest } from "../lib/server-meta" +import { getServerMeta, localRequest, sidecarsAllowed } from "../lib/server-meta" import { formatRelativeTime, getDisplayPath, getProjectDisplayName } from "../lib/recent-folder-display" import { preferences } from "../stores/preferences" import { selectRemoteServer } from "../stores/remote-project-open" @@ -795,7 +795,7 @@ const FolderSelectionView: Component = (props) => { - } - - - - }>{captured => <> -

{captured().integration.app.name} {captured().host.label} {captured().host.document}

-

{t("integrations.working")}

-

{t("integrations.observed", { label: captured().host.label })}

- } -

{error() ?? ""}

- -
- - -
- - - } - return { - entries, open, picker, canOpen, detach, refresh, binding, hintLabel, matchedHintLabel, - /** A mutation for the displayed conversation is in flight. */ - busy: (integrationId: string) => integrationBindings.busy(target(integrationId)), - /** A submitted action's effect is unknown until the next explicit read. */ - uncertain: (integrationId: string) => receipts().get(integrationId) === identity(), - } -} diff --git a/packages/ui/src/components/integration-catalog-window.tsx b/packages/ui/src/components/integration-catalog-window.tsx index 98a84b8ac9..f57148c326 100644 --- a/packages/ui/src/components/integration-catalog-window.tsx +++ b/packages/ui/src/components/integration-catalog-window.tsx @@ -11,7 +11,7 @@ import { integrationEpoch, integrations } from "../stores/integrations" import { pluginSourcesStore } from "../stores/plugin-sources" import { InfoPopoverButton } from "./info-popover-button" import { confirmIntegrationAction } from "./integration-confirmation" -import { integrationSummary } from "./integration-section" +import { integrationSummary } from "../lib/integration-row-state" import WindowCloseButton from "./window-close-button" /** Catalogue entries that can be installed here: neither declared nor loaded, and not ambiguous. */ diff --git a/packages/ui/src/components/integration-confirmation.ts b/packages/ui/src/components/integration-confirmation.ts index ed2c4dbc10..ee214dbb91 100644 --- a/packages/ui/src/components/integration-confirmation.ts +++ b/packages/ui/src/components/integration-confirmation.ts @@ -1,6 +1,6 @@ import { showConfirmDialog, type AlertDialogState } from "../stores/alerts" -/** Install, host install, attach and remove confirmations enable their action this long after they are shown. */ +/** Install, host install and remove confirmations enable their action this long after they are shown. */ export const INTEGRATION_CONFIRM_DELAY_MS = 600 let claimed = false @@ -9,7 +9,7 @@ let claimed = false * Reserves the single open integration or plugin-source confirmation. `undefined` while another one is open: the * new request shows nothing and sends nothing. The release is idempotent. */ -export function claimIntegrationConfirmation(): (() => void) | undefined { +function claimIntegrationConfirmation(): (() => void) | undefined { if (claimed) return undefined claimed = true let released = false diff --git a/packages/ui/src/components/integration-host-installation.ts b/packages/ui/src/components/integration-host-installation.ts index 756a2ffea9..99aa4f542d 100644 --- a/packages/ui/src/components/integration-host-installation.ts +++ b/packages/ui/src/components/integration-host-installation.ts @@ -16,9 +16,11 @@ export function createIntegrationHostInstallation(props: { const [pending, setPending] = createSignal(false) const identity = createMemo(() => JSON.stringify([props.instanceId, props.directory, props.sessionId, props.active !== false])) const epoch = createMemo(() => integrationEpoch(props.instanceId, props.sessionId)) + // Without an expected action the part can still be reinstalled, the application open or closed. const eligible = (id: string) => props.active !== false ? props.entries().find(entry => entry.id === id - && entry.family === "native" && entry.state === "ok" && entry.status?.host?.state !== "unsupported" - && entry.status?.host?.state !== "unknown" && entry.status?.host?.action && entry.status.version) : undefined + && entry.family === "native" && entry.state === "ok" && entry.status?.host && entry.status.host.state !== "unsupported" + && entry.status.version) : undefined + const actionOf = (entry: IntegrationView): "install" | "update" | "reinstall" => entry.status?.host?.action ?? "reinstall" const signature = (id: string) => JSON.stringify(eligible(id)) let confirmation: AbortController | undefined let disposed = false @@ -44,7 +46,7 @@ export function createIntegrationHostInstallation(props: { const operation = captureBackendOperation(instanceId, confirmation.signal, () => !disposed && identity() === owner) const signal = operation.signal if (!operation.current()) { cancel(); return } - const action = entry.status!.host!.action! + const action = actionOf(entry) const accepted = await confirmIntegrationAction(t("integrations.installHost.warning", { app: entry.app.name, name: entry.displayName, version: entry.status!.version }), { title: t(`integrations.installHost.${action}`), confirmLabel: t(`integrations.installHost.${action}`), variant: "warning", @@ -81,5 +83,5 @@ export function createIntegrationHostInstallation(props: { if (operation.current()) void integrations.refreshDemanded(instanceId) } } - return { pending, action: (id: string) => !pending() ? eligible(id)?.status?.host?.action : undefined, open } + return { pending, action: (id: string) => { const entry = !pending() ? eligible(id) : undefined; return entry ? actionOf(entry) : undefined }, open } } diff --git a/packages/ui/src/components/integration-row-binding.ts b/packages/ui/src/components/integration-row-binding.ts new file mode 100644 index 0000000000..b73996c08e --- /dev/null +++ b/packages/ui/src/components/integration-row-binding.ts @@ -0,0 +1,150 @@ +import { createEffect, createMemo, createSignal, on, onCleanup } from "solid-js" +import type { + IntegrationAttachResponse, + IntegrationDetachResponse, + IntegrationHostOffer, + IntegrationHostsResponse, + IntegrationView, +} from "../../../server/src/integration-types" +import { useI18n } from "../lib/i18n" +import { integrationAttachChoice, integrationLink, type IntegrationLink } from "../lib/integration-row-state" +import { integrationAttachmentRequest } from "../lib/integrations-api" +import { captureBackendOperation } from "../lib/backend-operation" +import { backendEvents } from "../lib/server-events" +import { showToastNotification } from "../lib/notifications" +import { integrationBindings, integrationEpoch } from "../stores/integrations" +import type { IntegrationBindingTarget } from "../stores/integration-bindings-store" + +const sameTarget = (left?: IntegrationBindingTarget, right?: IntegrationBindingTarget) => left === right || (!!left && !!right + && left.instanceId === right.instanceId && left.directory === right.directory && left.sessionID === right.sessionID && left.integrationId === right.integrationId) +const OUTCOMES = new Set(["busy", "gone", "refused"]) +interface AttachIntent { target: IntegrationBindingTarget; epoch: string; controller: AbortController; authority: ReturnType } + +/** + * The displayed conversation's attachment to one integration of a Plugins row: its authoritative read and the open + * documents, both demanded while the row is shown, and the user's explicit attach and detach. The integration also attaches a conversation + * itself at its first use. Every request is sent once and the binding is read again afterwards. + */ +export function createIntegrationRowBinding(options: { + instanceId: () => string + directory: () => string + sessionId: () => string | undefined + integration: () => IntegrationView | undefined + active: () => boolean +}) { + const { t } = useI18n() + const target = createMemo(() => { + const entry = options.integration(), sessionID = options.sessionId() + return entry && sessionID && options.directory() && entry.family === "native" && entry.state === "ok" && !entry.ambiguous + ? { instanceId: options.instanceId(), directory: options.directory(), sessionID, integrationId: entry.id } : undefined + }, undefined, { equals: sameTarget }) + createEffect(() => { + const value = target() + if (!value || !options.active()) return + onCleanup(integrationBindings.demand(value)) + }) + const link = createMemo(() => { + const entry = options.integration(), value = target() + return entry ? integrationLink(entry, value ? integrationBindings.state(value) : undefined) : undefined + }) + const [reading, setReading] = createSignal(false) + /** The documents offered to choose from, while that menu is open. */ + const [choices, setChoices] = createSignal void }>>() + const epoch = createMemo(() => integrationEpoch(options.instanceId(), options.sessionId())) + let intent: AttachIntent | undefined + let disposed = false + const revoke = () => { + intent?.controller.abort(); intent = undefined + setChoices(undefined); setReading(false) + } + createEffect(on(() => [target(), options.active(), epoch()] as const, revoke, { defer: true })) + createEffect(on(() => backendEvents.signalForInstance(options.instanceId()), revoke, { defer: true })) + onCleanup(() => { disposed = true; revoke() }) + const owns = (captured: AttachIntent) => captured.authority.current() && !disposed && intent === captured && !captured.controller.signal.aborted + && options.active() && sameTarget(target(), captured.target) && epoch() === captured.epoch + const busy = () => { const value = target(); return reading() || (value ? integrationBindings.busy(value) : false) } + const fail = (value: IntegrationBindingTarget, key = "integrations.error.retry", vars?: Record) => { + if (!disposed && options.active() && sameTarget(target(), value)) showToastNotification({ category: "opencode", variant: "error", message: t(key, vars) }) + } + /** The open documents, read while the row is shown with at least one offer; a native event reads them again. */ + const [offers, setOffers] = createSignal() + const offersKey = createMemo(() => { + const value = target(), entry = options.integration(), count = entry?.status?.connection?.offers ?? 0 + return value && options.active() && count > 0 && entry?.status?.host?.state !== "unsupported" + ? JSON.stringify([value.instanceId, value.directory, value.integrationId, count, epoch()]) : undefined + }) + createEffect(on(() => [offersKey(), backendEvents.signalForInstance(options.instanceId())] as const, ([key]) => { + const value = target() + setOffers(undefined) + if (!key || !value) return + const controller = new AbortController() + onCleanup(() => controller.abort()) + const authority = captureBackendOperation(value.instanceId, controller.signal) + if (!authority.current()) return + void integrationAttachmentRequest(value.instanceId, value.directory, value.integrationId, "hosts", authority.signal) + .then(result => { if (authority.current()) setOffers(Array.isArray(result?.offers) ? result.offers : undefined) }) + .catch(() => { if (authority.current()) setOffers(undefined) }) + })) + + /** At most one `detachHost` for the displayed conversation. */ + const detach = async () => { + const value = target() + if (disposed || !value || link()?.state !== "attached" || busy() || !options.active()) return + const authority = captureBackendOperation(value.instanceId, undefined, () => !disposed && options.active() && sameTarget(target(), value)) + if (!authority.current()) return + await integrationBindings.run(value, async () => { + if (!authority.current()) return + try { + const result = await integrationAttachmentRequest(value.instanceId, value.directory, value.integrationId, + "detach", authority.signal, { sessionID: value.sessionID }) + if (result?.outcome !== "detached" && result?.outcome !== "none") throw new Error("Invalid detach result") + } catch { if (authority.current()) fail(value) } + }) + } + /** At most one `attachHost` of the displayed conversation to the chosen offer. */ + const attach = async (captured: AttachIntent, offerID: string) => { + if (!owns(captured) || busy() || link()?.state === "attached") return + const value = captured.target + await integrationBindings.run(value, async () => { + if (!owns(captured)) return + // Consume consent at dispatch; the admitted mutation has its own lifetime and is never replayed. + revoke() + try { + const result = await integrationAttachmentRequest(value.instanceId, value.directory, value.integrationId, + "attach", captured.authority.signal, { sessionID: value.sessionID, offerID }) + if (!captured.authority.current()) return + if (result?.outcome === "attached") return + if (OUTCOMES.has(result?.outcome)) fail(value, `integrations.outcome.${result.outcome}`) + else throw new Error("Invalid attach result") + } catch { if (captured.authority.current()) fail(value) } + }) + } + /** + * Attach from the state line: read the documents afresh, attach the shown one when it is still the only one, + * otherwise offer the choice. + */ + const activate = async (expectedOfferID?: string) => { + const value = target(), entry = options.integration() + if (disposed || !value || !entry || link()?.state === "attached" || busy() || !options.active()) return + const authority = captureBackendOperation(value.instanceId) + if (!authority.current()) return + const captured: AttachIntent = { target: value, epoch: epoch(), controller: new AbortController(), authority } + intent = captured + setReading(true) + try { + const result = await integrationAttachmentRequest(value.instanceId, value.directory, value.integrationId, + "hosts", AbortSignal.any([captured.controller.signal, authority.signal])) + if (!owns(captured)) return + if (!Array.isArray(result?.offers)) throw new Error("Invalid hosts result") + const choice = integrationAttachChoice(result.offers) + if (choice.kind === "none") { fail(value, "integrations.connection.noOffer", { app: entry.app.name }); revoke() } + else if (choice.kind === "attach" && (!expectedOfferID || choice.offerID === expectedOfferID)) { setReading(false); await attach(captured, choice.offerID) } + else if (choice.kind === "attach") setChoices(result.offers.filter(offer => offer.protocol === "ok").map(offer => ({ ...offer, attach: () => void attach(captured, offer.offerID) }))) + else setChoices(choice.offers.map(offer => ({ ...offer, attach: () => void attach(captured, offer.offerID) }))) + } catch { if (owns(captured)) { fail(value); revoke() } } + finally { if (intent === captured) setReading(false) } + } + return { link, offers, busy, choices, closeChoices: () => { if (choices()) revoke() }, activate, detach } +} + +export type IntegrationRowBinding = ReturnType diff --git a/packages/ui/src/components/integration-section-state.test.ts b/packages/ui/src/components/integration-section-state.test.ts deleted file mode 100644 index 672d6ea9ad..0000000000 --- a/packages/ui/src/components/integration-section-state.test.ts +++ /dev/null @@ -1,146 +0,0 @@ -import assert from "node:assert/strict" -import { describe, it } from "node:test" -import { deriveIntegrationSectionState, integrationAutoExpandKey, type IntegrationSectionInput } from "./integration-section-state" - -type Entry = IntegrationSectionInput["entry"] -const native = (status: NonNullable = { version: "0.1.0", host: { state: "ok" }, connection: { offers: 0 } }, extra: Partial = {}): Entry => - ({ id: "blender", family: "native", state: "ok", status, ...extra }) -const input = (entry: Entry, extra: Partial> = {}, - conversation: Partial = {}): IntegrationSectionInput => ({ - entry, disabled: false, ...extra, - conversation: { present: true, binding: { state: "none" }, uncertain: false, ...conversation }, -}) -const derive = (value: IntegrationSectionInput) => deriveIntegrationSectionState(value) -const labelOf = (value: IntegrationSectionInput) => derive(value).label - -describe("integration section state (spec change §5.2)", () => { - it("installing while the install hint is pending", () => { - assert.equal(labelOf(input(native(undefined, { state: "inactive", status: undefined }), { installation: "pending" })), "installing") - }) - - it("install not confirmed once the pending window closed, or while declared and not loaded", () => { - assert.equal(labelOf(input({ id: "blender", family: "native", state: "inactive" }, { installation: "unconfirmed" })), "unconfirmed") - assert.equal(labelOf(input({ id: "blender", family: "native", state: "inactive" })), "unconfirmed") - }) - - it("failed when the runtime failed to load it", () => { - assert.equal(labelOf(input({ id: "blender", family: "native", state: "failed" }, { installation: "failed" })), "failed") - }) - - it("disabled under an effective -id rule, before install hints", () => { - assert.equal(labelOf(input({ id: "blender", family: "native", state: "inactive" }, { disabled: true, installation: "unconfirmed" })), "disabled") - }) - - it("non-conforming on a marker mismatch", () => { - assert.equal(labelOf(input({ id: "blender", family: "native", state: "non-conforming" })), "nonConforming") - }) - - it("unsupported on a missing status method or an unsupported (WSL) host", () => { - assert.equal(labelOf(input({ id: "blender", family: "native", state: "unsupported" })), "unsupported") - const wsl = derive(input(native({ version: "0.1.0", host: { state: "unsupported" }, connection: { offers: 1 } }))) - assert.equal(wsl.label, "unsupported") - assert.deepEqual(wsl.conversation, { state: "unsupported" }) - }) - - it("application absent, closed, outdated and incompatible from the host state", () => { - const host = (state: "absent" | "unknown" | "outdated" | "incompatible", action?: "install" | "update") => - derive(input(native({ version: "0.1.0", host: { state, ...(action ? { action } : {}) }, connection: { offers: 0 } }))) - assert.equal(host("absent", "install").label, "hostAbsent") - assert.deepEqual(host("absent", "install").application, { state: "absent", action: "install" }) - assert.equal(host("unknown").label, "hostClosed") - assert.equal(host("outdated", "update").label, "hostOutdated") - assert.equal(host("incompatible").label, "incompatible") - }) - - it("legacy install from its notice", () => { - assert.equal(labelOf(input(native({ version: "0.1.0", host: { state: "ok" }, notices: ["legacy_install"] }))), "legacy") - }) - - it("ready without offers, application available with offers, attached from the authoritative read", () => { - assert.equal(labelOf(input(native())), "ready") - assert.equal(labelOf(input(native({ version: "0.1.0", host: { state: "ok" }, connection: { offers: 2 } }))), "available") - assert.equal(labelOf(input(native({ version: "0.1.0", host: { state: "ok" }, connection: { offers: 1 } }), {}, - { binding: { state: "attached", label: "scene.blend" } })), "attached") - }) - - it("uncertain after a submitted action until it is read again, over every other state", () => { - const state = derive(input(native({ version: "0.1.0", host: { state: "ok" }, connection: { offers: 1 } }), {}, - { binding: { state: "attached", label: "scene.blend" }, uncertain: true })) - assert.equal(state.label, "uncertain") - assert.deepEqual(state.conversation, { state: "uncertain" }) - }) - - it("update available is cumulative with the label", () => { - const state = derive(input(native(undefined, { outdated: true }))) - assert.equal(state.label, "ready") - assert.equal(state.updateAvailable, true) - }) - - it("an unknown status read stays unverifiable", () => { - assert.equal(labelOf(input({ id: "blender", family: "native", state: "unknown" })), "unknown") - }) - - it("expects an action, and expands, only for the §5.1 states or an attached conversation", () => { - const expected = ["hostAbsent", "hostOutdated", "incompatible", "unconfirmed", "failed"] - const states = [ - derive(input(native({ version: "0.1.0", host: { state: "absent" } }))), - derive(input(native({ version: "0.1.0", host: { state: "outdated" } }))), - derive(input(native({ version: "0.1.0", host: { state: "incompatible" } }))), - derive(input({ id: "blender", family: "native", state: "inactive" })), - derive(input({ id: "blender", family: "native", state: "failed" })), - ] - assert.deepEqual(states.map(state => state.label), expected) - assert.ok(states.every(state => state.expectsAction && integrationAutoExpandKey(state) === state.label)) - const attached = derive(input(native({ version: "0.1.0", host: { state: "ok" }, connection: { offers: 1 } }), {}, { binding: { state: "attached", label: "a" } })) - assert.equal(integrationAutoExpandKey(attached), "attached") - const closedAttached = derive(input(native({ version: "0.1.0", host: { state: "unknown" } }), {}, { binding: { state: "attached", label: "a" } })) - assert.equal(closedAttached.label, "hostClosed") - assert.equal(integrationAutoExpandKey(closedAttached), "attached", "the authoritative displayed binding expands even with a different header state") - for (const quiet of [derive(input(native())), derive(input({ id: "blender", family: "native", state: "inactive" }, { disabled: true }))]) { - assert.equal(quiet.expectsAction, false) - assert.equal(integrationAutoExpandKey(quiet), undefined) - } - }) -}) - -describe("integration Conversation line (spec change §5.1)", () => { - const offers = (count: number) => native({ version: "0.1.0", host: { state: "ok" }, connection: { offers: count } }) - const row = (entry: Entry, conversation: Partial) => derive(input(entry, {}, conversation)).conversation - - it("no displayed conversation", () => { - assert.deepEqual(row(offers(1), { present: false, binding: { state: "unknown" } }), { state: "noConversation" }) - }) - - it("no offer, an available offer and a reattach hint", () => { - assert.deepEqual(row(offers(0), {}), { state: "noOffer" }) - assert.deepEqual(row(offers(1), {}), { state: "available" }) - assert.deepEqual(row(offers(1), { hint: "scene.blend" }), { state: "reattach", label: "scene.blend" }) - }) - - it("attached only from the authoritative binding; a hint without a live binding never attaches", () => { - assert.deepEqual(row(offers(1), { binding: { state: "attached", label: "scene.blend" } }), { state: "attached", label: "scene.blend" }) - assert.deepEqual(row(offers(0), { binding: { state: "attached", label: "scene.blend" } }), { state: "attached", label: "scene.blend" }) - assert.deepEqual(row(offers(1), { hint: "scene.blend", binding: { state: "none" } }), { state: "reattach", label: "scene.blend" }) - }) - - it("an unknown binding is never reported as no open application", () => { - assert.deepEqual(row(offers(0), { binding: { state: "unknown" } }), { state: "unknown" }) - assert.deepEqual(row(offers(1), { binding: { state: "unknown" }, hint: "scene.blend" }), { state: "unknown" }) - }) - - it("uncertain after a lost response, and unsupported under WSL", () => { - assert.deepEqual(row(offers(1), { uncertain: true, binding: { state: "none" } }), { state: "uncertain" }) - assert.deepEqual(row(native({ version: "0.1.0", host: { state: "unsupported" }, connection: { offers: 1 } }), { present: false }), { state: "unsupported" }) - }) - - it("only native integrations in the ok state have a Conversation and Application line", () => { - assert.equal(row({ id: "blender", family: "native", state: "failed" }, {}), undefined) - const resolve = derive(input({ id: "resolve", family: "vendor-mcp", state: "ok", status: { version: "1.0.0", connection: { state: "connected" } } })) - assert.equal(resolve.conversation, undefined) - assert.equal(resolve.application, undefined) - assert.equal(resolve.connection, "detected") - assert.equal(derive(input({ id: "resolve", family: "vendor-mcp", state: "ok", status: { version: "1.0.0", connection: { state: "none" } } })).connection, "absent") - assert.equal(derive(input({ id: "m365", family: "api", state: "ok", status: { version: "1.0.0", connection: { state: "connected" } } })).connection, "connected") - assert.equal(derive(input({ id: "m365", family: "api", state: "ok", status: { version: "1.0.0", connection: { state: "signed_out" } } })).connection, "disconnected") - }) -}) diff --git a/packages/ui/src/components/integration-section-state.ts b/packages/ui/src/components/integration-section-state.ts deleted file mode 100644 index e3157e4054..0000000000 --- a/packages/ui/src/components/integration-section-state.ts +++ /dev/null @@ -1,118 +0,0 @@ -import type { IntegrationBindingResponse, IntegrationView } from "../../../server/src/integration-types" -import type { IntegrationInstallState } from "../stores/plugin-sources" - -/** The section's state label (spec change §5.2), highest precedence first. */ -export type IntegrationSectionLabel = - | "uncertain" | "installing" | "failed" | "disabled" | "unconfirmed" | "nonConforming" | "unsupported" | "unknown" - | "hostAbsent" | "incompatible" | "hostOutdated" | "hostClosed" | "legacy" | "attached" | "available" | "ready" - -/** The Conversation line (spec change §5.1), for the displayed conversation only. */ -export type IntegrationConversationRow = - | { state: "unsupported" } - | { state: "noConversation" } - | { state: "uncertain" } - | { state: "attached"; label: string } - | { state: "unknown" } - | { state: "reattach"; label: string } - | { state: "available" } - | { state: "noOffer" } - -export type IntegrationApplicationState = "ok" | "absent" | "outdated" | "incompatible" | "unknown" | "unsupported" -export type IntegrationConnectionState = "detected" | "absent" | "connected" | "disconnected" - -export interface IntegrationSectionInput { - entry: Pick - /** The install hint of this Location (`PluginSourcesStore.installation`). */ - installation?: IntegrationInstallState - /** An effective `-id` rule disables its plugin. */ - disabled: boolean - conversation: { - /** A conversation of this Location is displayed. */ - present: boolean - /** The authoritative binding read of the displayed conversation. */ - binding: IntegrationBindingResponse - /** A submitted action whose effect was not read again yet. */ - uncertain: boolean - /** A validated saved hint matched to a fresh offer of this integration. */ - hint?: string - } -} - -export interface IntegrationSectionState { - label: IntegrationSectionLabel - /** `outdated` plugin, shown beside the label (cumulative). */ - updateAvailable: boolean - /** The label asks for an action: such a section is expanded. */ - expectsAction: boolean - application?: { state: IntegrationApplicationState; action?: "install" | "update" } - conversation?: IntegrationConversationRow - connection?: IntegrationConnectionState -} - -const EXPECTED_ACTIONS: ReadonlySet = new Set(["hostAbsent", "hostOutdated", "incompatible", "unconfirmed", "failed"]) - -export function deriveIntegrationSectionState(input: IntegrationSectionInput): IntegrationSectionState { - const { entry } = input - const ok = entry.state === "ok" - const host = ok && entry.family === "native" ? entry.status?.host : undefined - const application = host ? { state: host.state, ...(host.action ? { action: host.action } : {}) } : undefined - const conversation = ok && entry.family === "native" ? conversationRow(input) : undefined - const connection = ok ? connectionState(entry) : undefined - const label = sectionLabel(input, conversation) - return { - label, - updateAvailable: entry.outdated === true, - expectsAction: EXPECTED_ACTIONS.has(label), - ...(application ? { application } : {}), - ...(conversation ? { conversation } : {}), - ...(connection ? { connection } : {}), - } -} - -/** Expands a section once per key: an expected action, or the displayed conversation attached. */ -export function integrationAutoExpandKey(state: IntegrationSectionState): string | undefined { - return state.expectsAction ? state.label : state.conversation?.state === "attached" ? "attached" : undefined -} - -function sectionLabel(input: IntegrationSectionInput, conversation: IntegrationConversationRow | undefined): IntegrationSectionLabel { - const { entry } = input - if (input.conversation.uncertain) return "uncertain" - if (input.installation === "pending") return "installing" - if (entry.state === "failed" || input.installation === "failed") return "failed" - if (input.disabled) return "disabled" - if (entry.state === "inactive" || entry.state === "absent") return "unconfirmed" - if (entry.state === "non-conforming") return "nonConforming" - if (entry.state === "unsupported") return "unsupported" - if (entry.state !== "ok") return "unknown" - if (entry.family === "native") { - const host = entry.status?.host?.state - if (host === "unsupported") return "unsupported" - if (host === "absent") return "hostAbsent" - if (host === "incompatible") return "incompatible" - if (host === "outdated") return "hostOutdated" - if (host === "unknown") return "hostClosed" - } - if (entry.status?.notices?.includes("legacy_install")) return "legacy" - if (conversation?.state === "attached") return "attached" - if ((entry.status?.connection?.offers ?? 0) > 0) return "available" - return "ready" -} - -function conversationRow(input: IntegrationSectionInput): IntegrationConversationRow { - const { entry, conversation } = input - if (entry.status?.host?.state === "unsupported") return { state: "unsupported" } - if (!conversation.present) return { state: "noConversation" } - if (conversation.uncertain) return { state: "uncertain" } - // Only the authoritative read attaches; a hint or a receipt never does. - if (conversation.binding.state === "attached") return { state: "attached", label: conversation.binding.label } - if (conversation.binding.state === "unknown") return { state: "unknown" } - if ((entry.status?.connection?.offers ?? 0) === 0) return { state: "noOffer" } - return conversation.hint ? { state: "reattach", label: conversation.hint } : { state: "available" } -} - -function connectionState(entry: IntegrationSectionInput["entry"]): IntegrationConnectionState | undefined { - const state = entry.status?.connection?.state - if (entry.family === "vendor-mcp") return state === "connected" ? "detected" : "absent" - if (entry.family === "api") return state === "connected" ? "connected" : "disconnected" - return undefined -} diff --git a/packages/ui/src/components/integration-section.tsx b/packages/ui/src/components/integration-section.tsx deleted file mode 100644 index 5822378d55..0000000000 --- a/packages/ui/src/components/integration-section.tsx +++ /dev/null @@ -1,221 +0,0 @@ -import { Show, createMemo, type Accessor, type JSX } from "solid-js" -import { BookOpen, RefreshCw } from "lucide-solid" -import type { PluginControlLocation, PluginControlScope } from "../../../server/src/api-types" -import type { IntegrationView } from "../../../server/src/integration-types" -import { openExternalUrl } from "../lib/external-url" -import { useI18n } from "../lib/i18n" -import { integrationPlugin } from "../lib/integration-rows" -import { pluginControlsCache } from "../stores/plugin-controls" -import { pluginSourcesStore, removableSources } from "../stores/plugin-sources" -import { integrations } from "../stores/integrations" -import type { createIntegrationAttachment } from "./integration-attachment" -import type { createIntegrationHostInstallation } from "./integration-host-installation" -import { deriveIntegrationSectionState, type IntegrationSectionState } from "./integration-section-state" -import { InfoPopoverButton } from "./info-popover-button" -import { PluginActivationSwitch } from "./plugin-activation-switch" -import { PluginRowActions } from "./plugin-row-actions" - -type Translate = (key: string, vars?: Record) => string - -/** What every section of one Status tab shares: its Location, displayed conversation and single attachment. */ -export interface IntegrationSectionContext { - instanceId: string - location: Accessor - session: Accessor<{ id: string } | undefined> - active: Accessor - attachment: ReturnType - installation: ReturnType - /** The Plugins accordion trigger, focus fallback of controls that disappear. */ - pluginsTrigger: () => HTMLElement | null | undefined -} - -/** The plugin-controls facts and the derived state of one integration, read on demand. */ -export function integrationSectionFacts(context: IntegrationSectionContext, entry: IntegrationView) { - const snapshot = pluginControlsCache.state(context.instanceId, context.location()).snapshot - const plugin = integrationPlugin(snapshot, entry) - const read = integrations.state(context.instanceId, context.location().directory) - const binding = context.attachment.binding(entry.id) - const fresh = read.status === "ready" && !read.stale - const state = deriveIntegrationSectionState({ - entry, - installation: pluginSourcesStore.installation(context.instanceId, context.location(), entry), - disabled: plugin.control?.effective === "disabled", - conversation: { - present: Boolean(context.session()), - binding: binding.state === "none" && !fresh ? { state: "unknown" } : binding, - uncertain: context.attachment.uncertain(entry.id), - hint: context.attachment.matchedHintLabel(entry.id), - }, - }) - return { snapshot, plugin, state } -} - -/** The catalogue summary in the current language, else English. */ -export function integrationSummary(entry: IntegrationView, locale: string): string { - return entry.summary[locale] ?? entry.summary[locale.split("-")[0]!] ?? entry.summary.en ?? Object.values(entry.summary)[0] ?? "" -} - -const STATE_HINTS: Partial> = { - uncertain: "integrations.hint.uncertain", unconfirmed: "integrations.hint.unconfirmed", failed: "integrations.hint.failed", - nonConforming: "integrations.hint.nonConforming", unsupported: "integrations.hint.unsupported", unknown: "integrations.hint.unknown", - hostClosed: "integrations.hint.hostClosed", incompatible: "integrations.hint.incompatible", legacy: "integrations.hint.legacy", -} - -/** The header's state label and cumulative update label, always visible. */ -export function IntegrationSectionStatus(props: { t: Translate; state: IntegrationSectionState }) { - return - {props.t(`integrations.state.${props.state.label}`)} - - {props.t("integrations.section.updateAvailable")} - - -} - -/** The header's Documentation icon, opened outside the application. */ -export function IntegrationDocsButton(props: { t: Translate; docs?: string }) { - return {docs => ( - - )} -} - -/** The header's "i": the catalogue summary and the state's help. */ -export function IntegrationInfoButton(props: { t: Translate; entry: IntegrationView; state: IntegrationSectionState }) { - const { locale } = useI18n() - const hint = () => STATE_HINTS[props.state.label] - return -

{integrationSummary(props.entry, locale())}

- {key =>

{props.t(key(), { app: props.entry.app.name })}

}
-
-} - -function Line(props: { name: string; label: string; children: JSX.Element }) { - return
- {props.label} -
{props.children}
-
-} - -/** The body of one integration's Status section: Plugin, Application, Conversation and Connection lines. */ -export function IntegrationSection(props: { t: Translate; entry: Accessor; context: IntegrationSectionContext }) { - return {entry => } -} - -function IntegrationSectionBody(props: { t: Translate; entry: Accessor; context: IntegrationSectionContext }) { - const t = props.t - const context = props.context - const facts = createMemo(() => integrationSectionFacts(context, props.entry())) - const state = () => facts().state - const name = () => props.entry().displayName - const scopeLabel = (scope: PluginControlScope) => t(`instanceServiceStatus.plugins.scope.${scope}`) - const removable = createMemo(() => removableSources(facts().snapshot, source => facts().plugin.sources.includes(source)), [], { - equals: (left, right) => left.length === right.length && left.every((source, index) => source.scope === right[index]!.scope - && source.target === right[index]!.target && source.entryIndex === right[index]!.entryIndex && source.expectedRevision === right[index]!.expectedRevision), - }) - const consentEpoch = () => pluginControlsCache.state(context.instanceId, context.location()).invalidationRevision - const projectAvailable = () => facts().snapshot?.targets.some(target => target.scope === "project") === true - const refresh = () => { - void pluginControlsCache.load(context.instanceId, context.location(), { force: true }) - void integrations.refreshDemanded(context.instanceId) - } - const renderSwitch = (scope: PluginControlScope) => - - const conversationAction = () => { - const row = state().conversation - if (!row) return undefined - const integrationId = props.entry().id - if (row.state === "noConversation") return { label: t("integrations.attach"), disabled: true, title: t("integrations.conversation.openOne") } - if (row.state === "available") return { label: t("integrations.attach"), run: () => void context.attachment.open(integrationId) } - if (row.state === "reattach") return { label: t("integrations.reattach", { label: row.label }), run: () => void context.attachment.open(integrationId) } - if (row.state === "attached") return { label: t("integrations.detach"), run: () => void context.attachment.detach(integrationId) } - if (row.state === "unknown" || row.state === "uncertain") return { label: t("integrations.refresh"), run: () => context.attachment.refresh(integrationId) } - return undefined - } - const conversationText = () => { - const row = state().conversation - if (!row) return "" - if (row.state === "attached") return t("integrations.conversation.attached", { label: row.label }) - if (row.state === "reattach") return t("integrations.conversation.available") - return t(`integrations.conversation.${row.state}`) - } - const actionIdentity = () => { - const row = state().conversation - return row ? JSON.stringify([context.session()?.id, row.state === "attached" ? [row.state, row.label] : "unattached"]) : undefined - } - - return ( -
- - {version => {t("integrations.section.version", { version: version() })}} - {t("integrations.section.updateAvailable")} - - - - - - - - - {renderSwitch("global")} - {renderSwitch("project")} - - - - - {application => ( - - {t(`integrations.application.${application().state}`)} - {action => ( - - )} - -

{t("integrations.installHost.machine")}

-

{t("integrations.hint.hostClosed", { app: props.entry().app.name })}

-
-
- )}
- {row => ( - - {conversationText()} - {identity => {action => ( - - )}} - - -

{t("integrations.conversation.noOfferHint", { app: props.entry().app.name })}

-
-
- -

{t("integrations.hint.unsupported")}

-
-
- )}
- {connection => ( - - {t(`integrations.connection.${connection()}`)} - {versions => ( - -

{t("integrations.connection.requires", { app: props.entry().app.name, versions: versions() })}

-
- )}
-
- )}
-
- ) -} diff --git a/packages/ui/src/components/integration-state-line.tsx b/packages/ui/src/components/integration-state-line.tsx new file mode 100644 index 0000000000..a8f0ac494e --- /dev/null +++ b/packages/ui/src/components/integration-state-line.tsx @@ -0,0 +1,58 @@ +import { For, Show } from "solid-js" +import { DropdownMenu } from "@kobalte/core/dropdown-menu" +import { Link2 } from "lucide-solid" +import { useI18n } from "../lib/i18n" +import type { IntegrationStateLine } from "../lib/integration-row-state" +import type { IntegrationRowBinding } from "./integration-row-binding" + +/** + * The state line under an integration's name: muted text that informs, or an accent button that installs, updates, + * attaches (directly or through the choice of documents) or detaches. Long text is truncated; the native `title` + * holds it in full, and the accessible name carries it for keyboard and screen-reader users. + */ +export function IntegrationStateLineView(props: { + line: IntegrationStateLine + /** Absent for rows without a loaded integration: their line only informs. */ + binding?: IntegrationRowBinding + install?: () => void +}) { + const { t } = useI18n() + const text = () => t(props.line.key, props.line.vars) + const busy = () => props.binding?.busy() ?? false + const hint = () => props.line.action === "detach" ? t("integrations.detachConversation") : undefined + const run = () => { + if (busy()) return + const action = props.line.action + if (action === "install" || action === "update") props.install?.() + else if (action === "detach") void props.binding?.detach() + else if (action === "attach") void props.binding?.activate(props.line.offerID) + } + const content = () => <> + + {text()} + + return
+ {content()}}> + { if (!open) props.binding?.closeChoices(); else run() }}> + + {content()} + + + + + {t("integrations.attachChoose")} + {offer => ( + void offer.attach()}> + + {offer.document ?? offer.label} + + )} + + + + + +
+} diff --git a/packages/ui/src/components/markdown-session-links.ts b/packages/ui/src/components/markdown-session-links.ts new file mode 100644 index 0000000000..0c5dbc0cf2 --- /dev/null +++ b/packages/ui/src/components/markdown-session-links.ts @@ -0,0 +1,137 @@ +import { tGlobal } from "../lib/i18n" +import { captureBackendOperation } from "../lib/backend-operation" +import { projectScope } from "../lib/backend-identity" +import { resolveProjectLinkPath } from "../lib/markdown-project-links" +import { showAlertDialog } from "../stores/alerts" +import { instances } from "../stores/instances" +import { openFilePreview } from "../stores/files-preview" +import { getWorktreeForDirectory } from "../stores/worktrees" +import { openSessionPreview, getSessionPreview, showSessionChat } from "../stores/session-previews" +import { sessions } from "../stores/session-state" +import { isLoopbackHttpUrl } from "./browser-frame-security" + +// A loopback link click opens the session preview on the instance owning +// the session; failures surface through the shared alert dialog. +const openLoopbackPreview = (instanceId: string, sessionId: string, url: string) => { + const instance = instances().get(instanceId) + if (!instance) return + const operation = captureBackendOperation(instanceId) + void openSessionPreview(sessionId, url, projectScope(instance), instanceId).catch((error) => { + if (!operation.current()) return + showAlertDialog(tGlobal("sessionPreview.open.title"), { + title: tGlobal("sessionPreview.open.title"), + detail: error instanceof Error ? error.message : String(error), + variant: "error", + }) + }) +} + +export interface SessionProjectLink { + slug: string + directory: string + serviceDirectory?: string + path: string +} + +/** Where session links resolve: the session's worktree root, the session's own + * directory while the worktree inventory does not know it yet, or the instance + * folder. Reads the stores synchronously, so calling it inside an effect also + * tracks inventory loads for the decoration pass. */ +export interface SessionLinkBase { + slug: string + directory: string + serviceDirectory?: string + /** The root hrefs resolve against: the service namespace path when the + * worktree is known (notably WSL), else the directory itself. */ + base: string +} + +export function sessionLinkBase(instanceId: string, sessionId: string): SessionLinkBase | undefined { + if (!captureBackendOperation(instanceId).current()) return undefined + // The session's own location: an independently moved child carries its own + // directory, never its parent's. + const sessionDirectory = sessions().get(instanceId)?.get(sessionId)?.location.directory + // Inventory by directory, never by a fallback slug: a populated inventory + // holding only the root checkout must not capture unmatched sessions. + const worktree = sessionDirectory !== undefined ? getWorktreeForDirectory(instanceId, sessionDirectory) : undefined + const directory = worktree?.directory + ?? sessionDirectory + ?? instances().get(instanceId)?.folder + if (!directory) return undefined + return { slug: worktree?.slug ?? "root", directory, serviceDirectory: worktree?.serviceDirectory, base: worktree?.serviceDirectory ?? directory } +} + +/** The file-reader target a link href resolves to inside the session's + * worktree, or undefined when it points anywhere else. */ +export function resolveSessionProjectLink(instanceId: string, sessionId: string, href: string): SessionProjectLink | undefined { + const root = sessionLinkBase(instanceId, sessionId) + if (root === undefined) return undefined + const path = resolveProjectLinkPath(href, root.base) + if (path === undefined) return undefined + return { slug: root.slug, directory: root.directory, serviceDirectory: root.serviceDirectory, path } +} + +/** The plain-click dispatch for session-bound markdown links: a loopback URL + * opens the session preview on the instance owning the session (browser-accessed + * frontends cannot reach the backend host's localhost), and a path inside the + * session's worktree opens the file reader. Returns whether the click was + * handled; modified clicks never reach this. Availability comes from the + * mounted owner's createProjectServerMeta reader. */ +export function routeSessionLink(instanceId: string, sessionId: string, href: string, loopbackLinksOpenPreview: boolean): boolean { + const instance = instances().get(instanceId) + if (!instance || !captureBackendOperation(instanceId).current()) return false + if (loopbackLinksOpenPreview && isLoopbackHttpUrl(href)) { + openLoopbackPreview(instanceId, sessionId, href) + return true + } + const resolution = resolveSessionProjectLink(instanceId, sessionId, href) + if (resolution) { + // A browser preview owning the central surface steps aside for the reader. + const preview = getSessionPreview(sessionId, projectScope(instance)) + if (preview) showSessionChat(preview.storageKey) + openFilePreview(instanceId, { kind: "workspace", sessionId, ...resolution }) + return true + } + return false +} + +/** The titles decorated links carry, computed from the reactive availability + * and locale signals: call this synchronously inside an effect so their + * changes re-run the decoration pass. */ +export function sessionLinkTitles(instanceId: string | undefined, sessionId: string | undefined, + loopbackLinksOpenPreview: boolean): { preview: string; file: string } { + const sessionBound = Boolean(instanceId && sessionId && captureBackendOperation(instanceId).current()) + return { + preview: sessionBound && loopbackLinksOpenPreview ? tGlobal("markdown.link.previewOpens") : "", + file: sessionBound ? tGlobal("markdown.link.fileOpens") : "", + } +} + +/** Decorates exactly the links that intercept: loopback links while previews + * are known available, and links resolving inside the session's worktree; + * never over an author's own title attribute. Pure DOM pass: the caller + * computes `titles` and `base` inside its reactive effect, so availability, + * locale and inventory changes re-run it. */ +export function decorateSessionLinks(container: ParentNode, titles: { preview: string; file: string }, + base: SessionLinkBase | undefined): void { + const previewTitle = titles.preview + const fileTitle = Boolean(base) && titles.file + for (const anchor of container.querySelectorAll("a[href]")) { + const href = anchor.getAttribute("href") ?? "" + const loopback = Boolean(previewTitle) && isLoopbackHttpUrl(href) + const file = Boolean(fileTitle) && resolveProjectLinkPath(href, base!.base) !== undefined + const title = loopback ? previewTitle : file ? titles.file : "" + if (title) { + if (anchor.getAttribute("data-preview-link-title") === "true") { + // Our own tooltip follows locale changes; an author's title never does. + if (anchor.getAttribute("title") !== title) anchor.setAttribute("title", title) + } else if (!anchor.hasAttribute("title")) { + anchor.setAttribute("title", title) + anchor.setAttribute("data-preview-link-title", "true") + } + } else if (anchor.getAttribute("data-preview-link-title") === "true") { + anchor.removeAttribute("title") + anchor.removeAttribute("data-preview-link-title") + } + } +} diff --git a/packages/ui/src/components/markdown.tsx b/packages/ui/src/components/markdown.tsx index 5dfb53b78b..f64cc32cc4 100644 --- a/packages/ui/src/components/markdown.tsx +++ b/packages/ui/src/components/markdown.tsx @@ -12,17 +12,13 @@ import { type TextSource, } from "../lib/render-text-window" import type { RecordTextRevealTarget } from "../stores/message-v2/record-display-cache" +import { scheduleDeferredHighlight } from "../lib/markdown-highlight-schedule" import { HiddenTextNotice, createTextWindow } from "./hidden-text" -import { isLoopbackHttpUrl } from "./browser-frame-security" +import { decorateSessionLinks, routeSessionLink, sessionLinkBase, sessionLinkTitles } from "./markdown-session-links" import { matchLocalImage, messageImageCandidates, resolveLocalImages } from "../lib/markdown-local-images" import { createMediaSource } from "../lib/media-source" import { messageStoreBus } from "../stores/message-v2/bus" -import { openSessionPreview } from "../stores/session-previews" -import { instances } from "../stores/instances" -import { showAlertDialog } from "../stores/alerts" import { createProjectServerMeta } from "../lib/project-server-meta" -import { captureBackendOperation } from "../lib/backend-operation" -import { projectScope } from "../lib/backend-identity" import { backendOf } from "../lib/backend-client" import { useMarkdownMermaid } from "./markdown-mermaid" @@ -142,22 +138,6 @@ interface MarkdownProps { export function Markdown(props: MarkdownProps) { const { t } = useI18n() - // A loopback link click opens the session preview on the instance owning - // the session; failures surface through the shared alert dialog. - const openLoopbackPreview = (instanceId: string, sessionId: string, url: string) => { - const instance = instances().get(instanceId) - if (!instance) return - const operation = captureBackendOperation(instanceId) - void openSessionPreview(sessionId, url, projectScope(instance), instanceId).catch((error) => { - if (!operation.current()) return - showAlertDialog(t("sessionPreview.open.title"), { - title: t("sessionPreview.open.title"), - detail: error instanceof Error ? error.message : String(error), - variant: "error", - }) - }) - } - // Whether clicking a loopback link opens the web preview on this client. // Availability must be known first: through Remote Control with previews // off the default false would otherwise open a dead preview before the @@ -320,7 +300,7 @@ export function Markdown(props: MarkdownProps) { notifyRendered() } - const renderSnapshot = async (snapshot: ResolvedMarkdownSnapshot, request: number): Promise => { + const renderSnapshot = async (snapshot: ResolvedMarkdownSnapshot, request: number, highlight = snapshot.highlightEnabled): Promise => { const markdown = await loadMarkdownModule() // Awaiting even a warm module suspends this invocation. Skip stale work before // entering the synchronous parser, including retries with the same key. @@ -328,7 +308,7 @@ export function Markdown(props: MarkdownProps) { markdown.setMarkdownTheme(snapshot.themeKey === "dark") const diagrams: MermaidCodeBlock[] = [] const rendered = await markdown.renderMarkdown(snapshot.text, { - suppressHighlight: !snapshot.highlightEnabled, + suppressHighlight: !highlight, escapeRawHtml: snapshot.escapeRawHtml, literalRawHtml: snapshot.literalRawHtml, originRelativeImages: snapshot.originRelativeImages, @@ -337,21 +317,35 @@ export function Markdown(props: MarkdownProps) { truncated: snapshot.truncated, }) if (!isCurrentRender(request)) return - const shouldCache = !snapshot.highlightEnabled || !markdown.hasPendingCodeHighlight(snapshot.text) + // A deferred plain pass never publishes under a cache key that promises + // highlighting; a highlight-disabled snapshot still caches its plain render. + const shouldCache = highlight + ? !markdown.hasPendingCodeHighlight(snapshot.text) + : !snapshot.highlightEnabled if (isCurrentRender(request)) { commitCacheEntry(snapshot, rendered, { cache: shouldCache, mermaid: diagrams }) } } - const startRender = (snapshot: ResolvedMarkdownSnapshot, request: number) => { + const startRender = (snapshot: ResolvedMarkdownSnapshot, request: number, highlight = snapshot.highlightEnabled) => { lastRenderStartedAt = performance.now() - void renderSnapshot(snapshot, request).catch((error) => { - log.error("Failed to render markdown:", error) - if (isCurrentRender(request)) { - commitCacheEntry(snapshot, renderFallbackHtml(snapshot.text)) - } - }) + void renderSnapshot(snapshot, request, highlight) + .catch((error) => { + log.error("Failed to render markdown:", error) + if (isCurrentRender(request)) { + commitCacheEntry(snapshot, renderFallbackHtml(snapshot.text)) + } + }) + .then(() => { + // A first render that held highlighting back schedules its highlighted + // pass for idle time: a mounting burst of blocks must not run every + // Shiki highlight inside the mounting task. + if (highlight || !snapshot.highlightEnabled || !isCurrentRender(request)) return + scheduleDeferredHighlight(() => { + if (isCurrentRender(request)) startRender(snapshot, request, true) + }) + }) } // At most one render per interval, always of the latest snapshot. @@ -412,7 +406,9 @@ export function Markdown(props: MarkdownProps) { setRendered(false) notifyRendered() } - startRender(snapshot, request) + // A block's first render commits plain Markdown and takes up highlighting + // in idle time; every later render of the component renders immediately. + startRender(snapshot, request, previous === undefined && snapshot.highlightEnabled ? false : snapshot.highlightEnabled) }) createEffect(() => { @@ -422,29 +418,19 @@ export function Markdown(props: MarkdownProps) { createEffect(() => { html() - // Decorate exactly the links that intercept: only session-bound loopback - // links while previews are known available, and never over an author's - // own title attribute. - const decorate = Boolean(props.instanceId && props.sessionId) && loopbackLinksOpenPreview() - const title = decorate ? t("markdown.link.previewOpens") : "" + // Decorate exactly the links that intercept (see markdown-session-links): + // loopback links while previews are known available, and project-file + // links; never over an author's own title attribute. The titles and the + // resolution base are read synchronously so availability, locale and + // worktree-inventory changes re-run this pass. + const sessionBound = Boolean(props.instanceId && props.sessionId) + const titles = sessionLinkTitles(props.instanceId, props.sessionId, loopbackLinksOpenPreview()) + const base = sessionBound ? sessionLinkBase(props.instanceId!, props.sessionId!) : undefined Promise.resolve().then(() => { if (disposed || !containerRef) { return } - for (const anchor of containerRef.querySelectorAll("a[href]")) { - if (!isLoopbackHttpUrl(anchor.getAttribute("href") ?? "")) { - continue - } - if (title) { - if (!anchor.hasAttribute("title")) { - anchor.setAttribute("title", title) - anchor.setAttribute("data-preview-link-title", "true") - } - } else if (anchor.getAttribute("data-preview-link-title") === "true") { - anchor.removeAttribute("title") - anchor.removeAttribute("data-preview-link-title") - } - } + decorateSessionLinks(containerRef, titles, base) }) }) @@ -478,20 +464,18 @@ export function Markdown(props: MarkdownProps) { onMount(() => { const handleClick = async (event: Event) => { const target = event.target as HTMLElement - // A plain click on a loopback URL opens the session preview instead of - // a dead browser tab: browser-accessed frontends cannot reach the - // backend host's localhost. Modified clicks keep browser defaults, and - // clients without a working preview surface keep the link behavior. const anchor = target.closest("a[href]") as HTMLAnchorElement | null if (anchor && props.instanceId && props.sessionId) { const href = anchor.getAttribute("href") ?? "" const mouseEvent = event as MouseEvent // Firefox fires `click` for the middle button too; only a primary - // left click without modifiers opens the preview. + // left click without modifiers routes to an app surface. const plainClick = mouseEvent.button === 0 && !mouseEvent.ctrlKey && !mouseEvent.metaKey && !mouseEvent.shiftKey && !mouseEvent.altKey - if (plainClick && loopbackLinksOpenPreview() && isLoopbackHttpUrl(href)) { + // A plain click on a loopback URL opens the session preview, and one + // on a path inside the session's worktree opens the file reader; + // modified clicks keep browser defaults (see markdown-session-links). + if (plainClick && routeSessionLink(props.instanceId, props.sessionId, href, loopbackLinksOpenPreview())) { event.preventDefault() - openLoopbackPreview(props.instanceId, props.sessionId, href) return } } diff --git a/packages/ui/src/components/message-block.tsx b/packages/ui/src/components/message-block.tsx index 43ee5390a8..a8edc52eb5 100644 --- a/packages/ui/src/components/message-block.tsx +++ b/packages/ui/src/components/message-block.tsx @@ -49,6 +49,7 @@ import { createTextWindow, HiddenTextNotice } from "./hidden-text" import type { RecordTextRevealTarget } from "../stores/message-v2/record-display-cache" import { accountSessionTranscript } from "../stores/session-transcript-memory" import { parseReasoningSummary } from "../lib/reasoning-summary" +import { assistantAgentMeta, assistantAgentMetaTooltip } from "../lib/assistant-meta" import { getFormQueue } from "../stores/forms" import { backgroundSession, deleteMessagePart, deleteTechnicalPartGroup } from "../stores/session-actions" import { showAlertDialog } from "../stores/alerts" @@ -561,6 +562,7 @@ export default function MessageBlock(props: MessageBlockProps) { messageItems: Map toolItems: Map messageBlocks: Map + releasedToolBodies: Set } const [blockRef, setBlockRef] = createSignal() const [systemDisclosureRevision, setSystemDisclosureRevision] = createSignal(0) @@ -1372,6 +1374,10 @@ function ReasoningGroupCard(props: { const expanded = () => props.expanded?.() ?? localExpanded() const setExpanded = (value: boolean) => props.onExpandedChange ? props.onExpandedChange(value) : setLocalExpanded(value) const summaryParts = () => props.summaryParts ?? props.parts + const agentMeta = () => assistantAgentMeta(props.instanceId, props.parts[0]?.messageInfo) + const agentMetaTooltip = () => assistantAgentMetaTooltip(props.instanceId, props.parts[0]?.messageInfo) + /** The group header carries the meta itself, so its cards must not repeat it. */ + const headerShowsMeta = () => summaryParts().length > 1 && props.showHeader !== false && Boolean(props.showAgentMeta) const totalDuration = createMemo(() => summaryParts().reduce((total, item) => total + (item.durationMs ?? 0), 0)) const latestTitle = createMemo(() => { const latest = summaryParts().at(-1) @@ -1428,7 +1434,7 @@ function ReasoningGroupCard(props: { sessionId={props.sessionId} messageId={item().messageId} status={props.status} - showAgentMeta={props.showAgentMeta} + showAgentMeta={props.showAgentMeta && !headerShowsMeta()} defaultExpanded={summaryParts().length > 1 || props.defaultExpanded} forceExpanded={props.activePartId === item().partId} technicalCleanupSelected={() => props.technicalCleanupPartKeys().has(key)} @@ -1454,6 +1460,11 @@ function ReasoningGroupCard(props: { >