比较提交
4 提交
6a1eeabea8
...
2154c3b5ee
| 作者 | SHA1 | 提交日期 | |
|---|---|---|---|
| 2154c3b5ee | |||
| 5672585591 | |||
| 907a8a38da | |||
| 02fd25afaf |
共有 21 个文件被更改,包括 1806 次插入 和 122 次删除
|
|
@ -22,9 +22,15 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and
|
|||
- Strict Zod validation for the Rust bootstrap IPC payload, including the active database schema version.
|
||||
- Redacting tracing output writer with structured-field, bearer-token, URL-credential, private-key, and known-secret coverage.
|
||||
- P01 migration, logging, IPC validation, real Tauri startup, and production-build verification.
|
||||
- SQLite schema v2 for persistent non-sensitive ConnectionProfile metadata.
|
||||
- Bounded Rust-owned Profile list/create/update/delete IPC with generated UUIDs and timestamps.
|
||||
- Strict frontend ConnectionProfile Schemas and a basic Profile management UI.
|
||||
- Migration, five-Profile CRUD, persistent reopen, secret-field rejection, and browser fallback tests.
|
||||
|
||||
### Security
|
||||
|
||||
- Kept credentials and native capabilities in Rust; the React capability set remains `core:default` only.
|
||||
- Added secret redaction and repository scans; no arbitrary PowerShell, CMD, shell, input-injection, registry-write, or unrestricted filesystem API is exposed.
|
||||
- Kept real UNC writes, signing keys, updater keys, and release secrets outside P00.
|
||||
- Rejected Token, password, API Key, URL credential, query-string credential, and unknown fields at the Profile IPC boundary.
|
||||
- Required explicit approval for insecure HTTP and kept slots, connections, and credential enrollment outside P01.
|
||||
|
|
|
|||
6
Cargo.lock
自动生成
6
Cargo.lock
自动生成
|
|
@ -105,7 +105,7 @@ checksum = "7d902e3d592a523def97af8f317b08ce16b7ab854c1985a0c671e6f15cebc236"
|
|||
|
||||
[[package]]
|
||||
name = "astrbot-desktop"
|
||||
version = "0.1.0-alpha.0"
|
||||
version = "0.1.0-alpha.1"
|
||||
dependencies = [
|
||||
"desktop-protocol",
|
||||
"eventsource-stream",
|
||||
|
|
@ -989,7 +989,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "desktop-protocol"
|
||||
version = "0.1.0-alpha.0"
|
||||
version = "0.1.0-alpha.1"
|
||||
dependencies = [
|
||||
"schemars 1.2.1",
|
||||
"serde",
|
||||
|
|
@ -2470,7 +2470,7 @@ dependencies = [
|
|||
|
||||
[[package]]
|
||||
name = "mock-gateway"
|
||||
version = "0.1.0-alpha.0"
|
||||
version = "0.1.0-alpha.1"
|
||||
dependencies = [
|
||||
"async-stream",
|
||||
"axum",
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ members = [
|
|||
resolver = "3"
|
||||
|
||||
[workspace.package]
|
||||
version = "0.1.0-alpha.0"
|
||||
version = "0.1.0-alpha.1"
|
||||
edition = "2024"
|
||||
rust-version = "1.97.1"
|
||||
license = "MIT OR Apache-2.0"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,64 @@
|
|||
# ADR-0004: Profile lifecycle and secret boundary
|
||||
|
||||
- Status: accepted
|
||||
- Date: 2026-07-18
|
||||
- Decision owner: project owner
|
||||
|
||||
## Background
|
||||
|
||||
The architecture document assigns Profile CRUD to stage 1, while the implementation task document groups ConnectionProfile CRUD with the stage 2 dual-connection slots. The conflict affects the SQLite schema, Tauri IPC surface, frontend state, and stage acceptance boundary.
|
||||
|
||||
The project owner selected option A from PD-0008:
|
||||
|
||||
- P01 owns basic ConnectionProfile metadata CRUD.
|
||||
- P02 owns active slot assignment and all runtime connection behavior.
|
||||
|
||||
## Options considered
|
||||
|
||||
### Option A: basic metadata CRUD in P01
|
||||
|
||||
Create, list, update, and delete non-sensitive Profile metadata in P01. Keep companion/operations slot assignment, active connections, auto-connect validation, switching protection, and duplicate server-instance detection in P02.
|
||||
|
||||
### Option B: defer all Profile CRUD to P02
|
||||
|
||||
Keep P01 limited to application bootstrap, persistent SQLite, logging, tray, single-instance, and tests.
|
||||
|
||||
## Decision
|
||||
|
||||
Use option A.
|
||||
|
||||
P01 persists the canonical non-sensitive ConnectionProfile fields and exposes bounded Tauri commands for:
|
||||
|
||||
- listing Profiles;
|
||||
- creating a Profile;
|
||||
- updating user-editable metadata;
|
||||
- deleting a Profile.
|
||||
|
||||
The P01 IPC input does not accept Token, password, API Key, Cookie, Authorization header, NAS credential, or arbitrary extra fields. Rust creates Profile IDs and timestamps. React may receive only non-sensitive metadata and an opaque credential reference.
|
||||
|
||||
The following remain explicitly out of P01:
|
||||
|
||||
- credential value enrollment or retrieval;
|
||||
- companion/operations slot assignment;
|
||||
- connection activation and cancellation;
|
||||
- auto-connect behavior;
|
||||
- switching protection;
|
||||
- server_instance_id conflict detection;
|
||||
- REST/SSE runtime state.
|
||||
|
||||
## Reasons
|
||||
|
||||
- AGENTS.md gives the architecture document higher priority.
|
||||
- A saved Profile is a durable application-foundation concept and can be implemented without activating a connection.
|
||||
- Separating metadata from runtime connection state preserves the Rust-owned security boundary.
|
||||
- The narrow IPC input makes accidental secret transfer to React or SQLite rejectable at deserialization time.
|
||||
|
||||
## Trade-offs
|
||||
|
||||
- P01 can select an authentication type but cannot enroll the corresponding credential value.
|
||||
- The UI is intentionally a foundation form, not a full connection settings experience.
|
||||
- Credential deletion and transactional cleanup must be added with the formal credential lifecycle before credential references can be created by production flows.
|
||||
|
||||
## Follow-up
|
||||
|
||||
P02 must consume this metadata model without widening the P01 commands to accept secret values. It must add slots, connection state, auto-connect rules, profile-switch guards, duplicate server-instance warnings, and credential lifecycle integration as separate reviewed increments.
|
||||
|
|
@ -53,12 +53,11 @@
|
|||
|
||||
## PD-0008: Profile CRUD stage ownership
|
||||
|
||||
- Status: unresolved; blocks Profile CRUD implementation only
|
||||
- Status: resolved; option A selected by the project owner on 2026-07-18
|
||||
- Conflict: `docs/01_Architecture_Design.md` lists Profile CRUD in stage 1, while `docs/02_Codex_Implementation_Tasks.md` lists ConnectionProfile CRUD in Batch 2.
|
||||
- Impact: resolving this changes the database schema, Tauri IPC surface, frontend state model, and the acceptance boundary between `feat/p01-foundation` and `feat/p02-dual-connections`.
|
||||
- Safe current action: complete only the unambiguous P01 foundation work<72><6B>persistent migrations, validated bootstrap IPC, redacted logging, tray, single-instance, exit flow, and tests.
|
||||
- Paused work: profile tables, Profile CRUD commands, profile forms, and profile-to-slot assignment.
|
||||
- Required decision:
|
||||
- Option A: architecture document wins; implement basic Profile CRUD in P01 and leave slot assignment/connection behavior for P02.
|
||||
- Option B: implementation task batching wins; keep all ConnectionProfile CRUD in P02.
|
||||
- Recommendation: Option A is the literal higher-priority document, but the implementation remains paused because AGENTS.md requires explicit reporting for conflicts affecting database structure or public interfaces.
|
||||
- Decision: implement basic non-sensitive Profile metadata CRUD in P01.
|
||||
- P01 scope: Profile list, create, update, and delete; SQLite schema v2; bounded Tauri IPC; strict frontend Schema; basic management UI.
|
||||
- P02 scope: companion/operations slot assignment, active connection state, auto-connect validation, switching protection, and `server_instance_id` conflict detection.
|
||||
- Secret boundary: P01 commands accept no Token, password, API Key, Cookie, Authorization header, or NAS credential fields. SQLite stores only non-sensitive metadata and future opaque credential references.
|
||||
- Rationale: AGENTS.md gives the architecture document higher priority, and the selected split keeps runtime connection behavior out of P01.
|
||||
- ADR: `ADR-0004-profile-lifecycle-and-secret-boundary.md`.
|
||||
|
|
|
|||
|
|
@ -41,7 +41,7 @@ Establish a reproducible Tauri 2 + React + TypeScript + Rust baseline and comple
|
|||
|
||||
### Objective
|
||||
|
||||
Turn the P00 Spike skeleton into a durable application foundation without pulling Batch 2 connection-profile behavior forward across an unresolved document boundary.
|
||||
Turn the P00 Spike skeleton into a durable application foundation. Under the project owner's option A decision, P01 includes basic non-sensitive Profile metadata CRUD while P02 retains all slot and runtime connection behavior.
|
||||
|
||||
### Ordered work
|
||||
|
||||
|
|
@ -49,11 +49,26 @@ Turn the P00 Spike skeleton into a durable application foundation without pullin
|
|||
2. Apply versioned, transactional, idempotent migrations and refuse unknown future schema versions.
|
||||
3. Validate Rust-to-TypeScript bootstrap payloads at runtime.
|
||||
4. Ensure tracing output passes through the shared redaction rules before it reaches a writer.
|
||||
5. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, and production build behavior.
|
||||
6. Record the Profile CRUD stage conflict before changing its schema or IPC.
|
||||
5. Add SQLite schema v2 for canonical non-sensitive ConnectionProfile metadata.
|
||||
6. Add bounded Tauri list/create/update/delete commands that generate IDs and timestamps in Rust.
|
||||
7. Reject secret values, URL credentials, query-string credentials, unknown IPC fields, and implicit insecure HTTP.
|
||||
8. Add strict frontend Profile Schemas and a basic management UI without Token/password/API Key inputs.
|
||||
9. Test five saved Profiles, CRUD, persistent reopen, v1-to-v2 migration, future-version rejection, and browser fallback.
|
||||
10. Re-verify tray, single-instance, explicit exit, frontend, Rust, E2E, development startup, Schema export, and production build behavior.
|
||||
11. Record the decision in PD-0008 and ADR-0004, then commit and push the verified branch normally.
|
||||
|
||||
### Paused boundary
|
||||
### P01 boundary
|
||||
|
||||
- `docs/01_Architecture_Design.md` places Profile CRUD in stage 1.
|
||||
- `docs/02_Codex_Implementation_Tasks.md` places ConnectionProfile CRUD in Batch 2.
|
||||
- Because this changes database structure and public IPC, Profile CRUD remains paused under PD-0008 until the stage boundary is explicitly resolved.
|
||||
- Included: durable application database, schema migration, redacted logging, validated bootstrap IPC, basic Profile metadata CRUD, basic Profile management UI, tray, single-instance, and build/test foundations.
|
||||
- Excluded: slot assignment, active REST/SSE connections, auto-connect behavior, Profile switching protection, duplicate `server_instance_id` handling, and formal credential enrollment.
|
||||
|
||||
### Verification status
|
||||
|
||||
- Frontend formatting, ESLint, TypeScript, 3 Vitest tests, and Vite production build passed.
|
||||
- Playwright Chromium passed 1/1.
|
||||
- Rust fmt, Clippy with warnings denied, tests, and check passed.
|
||||
- Rust test suite passed 50 normal tests; 2 explicit manual tests remained ignored.
|
||||
- Protocol Schema export completed without drift.
|
||||
- Real Tauri development startup reached the Windows executable and was then deliberately terminated.
|
||||
- Windows release and NSIS bundling passed.
|
||||
- Forgejo CI remains unverified because a compatible runner/jobs endpoint is unavailable.
|
||||
|
|
|
|||
|
|
@ -2,43 +2,42 @@
|
|||
|
||||
## Current phase
|
||||
|
||||
P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work is implemented, while Profile CRUD is paused on a documented stage-boundary conflict.
|
||||
P01 foundation is active on `feat/p01-foundation`. The option A boundary is resolved: basic non-sensitive Profile metadata CRUD belongs to P01, while slots and runtime connection behavior remain in P02.
|
||||
|
||||
## Completed
|
||||
|
||||
- Read `AGENTS.md` and all authoritative architecture, implementation, and Forgejo workflow documents.
|
||||
- Read `AGENTS.md`, the architecture, implementation task, and Forgejo predevelopment workflow documents in full.
|
||||
- Verified the Windows, Git, Node.js, package-manager, WebView2, Rust, Tauri, and MSVC environment.
|
||||
- Initialized a local Git repository on `main`.
|
||||
- Configured `origin` as `ssh://git@localhost:18086/YokiiroBW/AstrBot-Desktop.git`.
|
||||
- Verified through authenticated Forgejo API and HTTP Git that the remote repository existed, was empty, used `main`, and granted push permission before the baseline push.
|
||||
- Reauthenticated through Git Credential Manager and non-forced pushed the `main` baseline to Forgejo at `0d12b94`.
|
||||
- Created and switched to `feat/p00-bootstrap` from the pushed `main` baseline.
|
||||
- Built the Tauri 2 + React + TypeScript + Rust skeleton with tray, single-instance, CSP, and minimal `core:default` capability.
|
||||
- Implemented independent companion/operations REST and SSE clients and passed the corrected 30-minute soak.
|
||||
- Implemented and tested Windows Credential Manager, UI Automation, selected-window capture, Event Log, process, port, foreground-window, authorized log-tail, configuration parsing, and redaction Spikes.
|
||||
- Implemented and tested composite-key SQLite isolation and recoverable local file transactions with source preservation.
|
||||
- Added provisional protocol types, ten JSON Schemas, TypeScript exports, drift checks, and two loopback-only Mock Gateway instances.
|
||||
- Added frontend, Playwright, Rust, integration, Windows-provider, soak, and Forgejo CI entry points.
|
||||
- Built the Windows release executable and SHA-256-recorded NSIS installer.
|
||||
- Added dependency, Spike, progress, changelog, and pending-decision records.
|
||||
- Verified Forgejo PR #1 merged into `main` as `b3420e4`.
|
||||
- Fast-forwarded local `main` and created `feat/p01-foundation` from the merged baseline.
|
||||
- Added persistent SQLite startup initialization with WAL, busy timeout, transactional `user_version` migration, idempotent reopen, and future-version rejection.
|
||||
- Added strict Zod validation for the Rust bootstrap IPC payload and exposed the active database schema version.
|
||||
- Added a redacting tracing writer that sanitizes structured fields and rendered message content before output.
|
||||
- Verified a real Tauri development start created the application database in the Windows app-data directory.
|
||||
- Built the P01 Windows release executable and NSIS installer.
|
||||
- Committed the implementation, test, and CI increments with Conventional Commit subjects.
|
||||
- Initialized and normalized Git, established `main`, and pushed the baseline without force.
|
||||
- Completed and merged P00 through Forgejo PR #1 at `b3420e4`.
|
||||
- Created `feat/p01-foundation` from the merged `main`.
|
||||
- Added persistent SQLite startup initialization with WAL, busy timeout, foreign-key enforcement, and transactional migrations.
|
||||
- Added schema v2 with canonical non-sensitive `connection_profiles` metadata.
|
||||
- Added fresh-database, v1-to-v2, future-version, idempotent reopen, five-Profile, CRUD, and persistent-reopen coverage.
|
||||
- Added bounded Tauri Profile list/create/update/delete commands.
|
||||
- Kept UUID and timestamp creation in Rust.
|
||||
- Rejected credential-bearing URLs, URL query/fragment data, implicit HTTP, invalid certificate fingerprints, malformed IDs, unknown fields, and Token/password/API Key fields.
|
||||
- Preserved credential references and runtime-managed fields outside the editable P01 input.
|
||||
- Added strict Zod Schemas for bootstrap and ConnectionProfile IPC payloads.
|
||||
- Added a basic React Profile management UI for non-sensitive metadata only.
|
||||
- Added explicit deletion confirmation and browser-safe Tauri IPC fallback.
|
||||
- Added a redacting tracing writer that sanitizes structured fields and rendered message content.
|
||||
- Retained tray, close-to-tray, explicit quit, and single-instance behavior.
|
||||
- Re-exported protocol Schemas without drift.
|
||||
- Re-ran a real Tauri development startup and reached the Windows executable.
|
||||
- Rebuilt the Windows release executable and NSIS installer.
|
||||
- Recorded the Profile boundary in PD-0008 and ADR-0004.
|
||||
|
||||
## In progress
|
||||
|
||||
- Recording the Profile CRUD stage conflict and preparing the verified P01 foundation increment for remote review.
|
||||
- Final documentation review, focused Conventional Commits, and normal Forgejo push.
|
||||
|
||||
## Remaining
|
||||
|
||||
- Resolve whether Profile CRUD belongs in P01 (architecture document) or P02/Batch 2 (implementation task document) before changing its database schema or public IPC.
|
||||
- After resolution, complete the selected stage scope and open a PR without automatically merging `main`.
|
||||
- Run the Forgejo workflow when a compatible runner is available.
|
||||
- Commit the verified backend, frontend, test, and documentation increments.
|
||||
- Push `feat/p01-foundation` normally to Forgejo.
|
||||
- Generate the P01 Forgejo PR title and body; do not merge `main`.
|
||||
- Run Forgejo CI when a compatible runner is available.
|
||||
- Execute a real UNC transaction only after an authorized disposable fixture is supplied.
|
||||
- Add the combined end-to-end test that keeps configured streams active while the real Tauri window is hidden to tray.
|
||||
|
||||
|
|
@ -46,22 +45,23 @@ P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work i
|
|||
|
||||
- Configured Forgejo SSH `localhost:18086` refuses connections.
|
||||
- LAN SSH `192.168.31.210:18086` responds but rejects the available public key.
|
||||
- HTTP Git push is operational after Git Credential Manager reauthentication and is no longer a blocker.
|
||||
- Profile CRUD stage ownership conflicts between the architecture and implementation task documents; implementation is paused because it affects database structure and public IPC.
|
||||
- Approved HTTP Git push remains operational and is not blocked.
|
||||
- Forgejo runner labels/jobs could not be verified; the jobs API endpoint returned 404.
|
||||
- No blocker remains for the selected P01 scope.
|
||||
|
||||
## Test status
|
||||
|
||||
- `npm run check:frontend`: passed; 2 Vitest tests and production Vite build.
|
||||
- `pnpm test:e2e`: passed; 1 Chromium smoke test.
|
||||
- `npm run check:frontend`: passed; Prettier, ESLint, TypeScript, 3 Vitest tests, and Vite production build.
|
||||
- `npm run test:e2e`: passed; 1 Chromium smoke test.
|
||||
- Rust fmt/check/Clippy with warnings denied: passed.
|
||||
- `cargo test --workspace`: 44 passed, 2 explicit manual tests ignored.
|
||||
- Controlled Windows UIA/PrintWindow smoke: 1 passed.
|
||||
- Corrected dual-SSE soak: 1800.02 seconds, 1800 companion events, 1801 operations events, passed.
|
||||
- Protocol Schema drift check: passed.
|
||||
- P01 Tauri development startup and application-data SQLite creation: passed.
|
||||
- P01 release executable and NSIS installer: passed after repairing the missing official `libsqlite3-sys` binding cache; installer SHA-256 `B8858CBE2F4673FAF40799C1243BCAB0748D194FA3AD67FBD33DDCF26CF27189`.
|
||||
- pnpm 11.9.0 frozen lockfile-only validation: passed using a local temporary store to avoid the pnpm UNC project-registry limitation.
|
||||
- `cargo test --workspace`: passed; 50 normal tests, 2 explicit manual tests ignored.
|
||||
- Profile persistence: passed; five Profile CRUD, close/reopen persistence, and v1-to-v2 migration preserve existing messages.
|
||||
- Secret boundary: passed; unknown Token, password, and API Key input fields are rejected.
|
||||
- Protocol Schema export: passed; no generated drift.
|
||||
- Tauri development startup: passed; executable launched, then was deliberately terminated after verification.
|
||||
- Tauri Windows release executable: passed.
|
||||
- NSIS installer: passed; `0.1.0-alpha.1`, 3,827,899 bytes.
|
||||
- NSIS SHA-256: `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740`.
|
||||
- Forgejo CI and a real UNC transaction were not executed and are not claimed successful.
|
||||
|
||||
## Current branch
|
||||
|
|
@ -70,16 +70,10 @@ P01 foundation is active on `feat/p01-foundation`; unambiguous foundation work i
|
|||
|
||||
## Recent commits
|
||||
|
||||
- `5e6e8d5 docs(project): add architecture and implementation specifications`
|
||||
- `0d12b94 chore(repo): initialize repository and ignore rules`
|
||||
- `01607c6 feat(p00): add Tauri desktop spike foundation`
|
||||
- `69b432b test(p00): add frontend browser rust and windows checks`
|
||||
- `d4af979 ci(forgejo): add portable and windows quality workflows`
|
||||
- `72a16cb docs(p00): record Forgejo branch publication`
|
||||
- `b3420e4 Merge pull request 'feat(p00): bootstrap Tauri desktop and validate high-risk spikes' (#1)`
|
||||
- `ed74342 feat(foundation): add persistent bootstrap safeguards`
|
||||
- `353a439 docs(p00): record spike results and unresolved boundaries`
|
||||
- `6a1eeab docs(p01): record foundation progress and profile boundary`
|
||||
|
||||
## Next step
|
||||
|
||||
Obtain an explicit decision for PD-0008 before implementing Profile CRUD. Continue other P01 work only if it does not change the disputed profile database or public IPC boundary.
|
||||
Create focused commits for Profile persistence/IPC, Profile UI/tests, and P01 decision/report documentation. Re-run the proportional checks for each commit, push the branch normally, and prepare the Forgejo PR without merging `main`.
|
||||
|
|
|
|||
|
|
@ -4,58 +4,84 @@ Date: 2026-07-18
|
|||
|
||||
## Status
|
||||
|
||||
P01 foundation work is partially complete on `feat/p01-foundation`. The unambiguous Batch 1 foundation items are implemented and verified. Profile CRUD is intentionally paused under PD-0008 because the architecture and implementation task documents assign it to different stages.
|
||||
P01 implementation and local verification are complete on `feat/p01-foundation`. The branch still requires focused commits and a normal Forgejo push before the stage can be handed off for review.
|
||||
|
||||
PD-0008 was resolved by the project owner with option A:
|
||||
|
||||
- P01 includes basic non-sensitive Profile metadata CRUD.
|
||||
- P02 retains slots, active connections, auto-connect, switching protection, duplicate server-instance handling, and credential enrollment.
|
||||
|
||||
## Completed
|
||||
|
||||
- Verified P00 PR #1 merged into `main` at `b3420e4`.
|
||||
- Fast-forwarded local `main` and created `feat/p01-foundation`.
|
||||
- Added a persistent SQLite database under the Tauri application-data directory.
|
||||
- Added WAL mode, a bounded busy timeout, foreign-key enforcement, and transactional `user_version` migration.
|
||||
- Added idempotent reopen/persistence tests and rejection of databases newer than the supported schema.
|
||||
- Added the database schema version to the bootstrap IPC response.
|
||||
- Added strict frontend Zod validation for the IPC payload and a malformed-payload test.
|
||||
- Created `feat/p01-foundation` from the merged baseline.
|
||||
- Added persistent SQLite under the Tauri application-data directory.
|
||||
- Added WAL, a bounded busy timeout, foreign-key enforcement, and transactional `user_version` migrations.
|
||||
- Added schema v2 for `connection_profiles`.
|
||||
- Verified fresh creation and v1-to-v2 migration without losing existing messages.
|
||||
- Verified five saved Profiles, full CRUD, and persistence after reopening the database.
|
||||
- Added bounded Tauri list/create/update/delete commands.
|
||||
- Added Rust-owned UUIDs and RFC 3339 timestamps.
|
||||
- Added URL normalization and rejection of embedded credentials, query strings, fragments, implicit HTTP, and invalid fingerprints.
|
||||
- Added strict IPC rejection for unknown Token, password, and API Key fields.
|
||||
- Added strict frontend ConnectionProfile Schemas.
|
||||
- Added a basic React Profile manager with list/create/edit/delete and explicit deletion confirmation.
|
||||
- Added no Token, password, API Key, Cookie, or NAS credential input.
|
||||
- Added a tracing writer that redacts output before writing.
|
||||
- Retained the existing tray menu, close-to-tray, explicit quit, and single-instance focus behavior.
|
||||
- Retained tray, close-to-tray, explicit quit, and single-instance focus behavior.
|
||||
- Added ADR-0004 for the Profile lifecycle and secret boundary.
|
||||
|
||||
## Verification
|
||||
|
||||
| Check | Result |
|
||||
| ------------------------------------------------------- | ------------------------------------------------------------------ |
|
||||
| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 2 Vitest tests |
|
||||
| Playwright Chromium | Passed; 1 test |
|
||||
| Rust fmt, Clippy with warnings denied, check | Passed |
|
||||
| Rust tests | Passed; 44 normal tests, 2 explicit manual tests ignored |
|
||||
| Persistent SQLite reopen and migration tests | Passed |
|
||||
| Logging redaction writer test | Passed |
|
||||
| Tauri development startup | Passed |
|
||||
| Windows application-data SQLite creation | Passed; database created at startup |
|
||||
| Tauri release executable | Passed |
|
||||
| NSIS installer | Passed; 3,793,884 bytes |
|
||||
| NSIS SHA-256 | `B8858CBE2F4673FAF40799C1243BCAB0748D194FA3AD67FBD33DDCF26CF27189` |
|
||||
| Check | Result |
|
||||
| ------------------------------------------------------- | --------------------------------------------------------------------------- |
|
||||
| Frontend format, ESLint, TypeScript, Vitest, Vite build | Passed; 3 Vitest tests |
|
||||
| Playwright Chromium | Passed; 1 test |
|
||||
| Rust fmt, Clippy with warnings denied, check | Passed |
|
||||
| Rust tests | Passed; 50 normal tests, 2 explicit manual tests ignored |
|
||||
| SQLite fresh schema v2 | Passed |
|
||||
| SQLite v1-to-v2 migration | Passed; existing message preserved |
|
||||
| Five Profile CRUD | Passed |
|
||||
| Profile close/reopen persistence | Passed |
|
||||
| Unknown secret IPC fields | Passed; rejected |
|
||||
| Protocol Schema export | Passed; no drift |
|
||||
| Tauri development startup | Passed; executable launched and was deliberately stopped after verification |
|
||||
| Tauri release executable | Passed |
|
||||
| NSIS installer | Passed; `0.1.0-alpha.1`, 3,827,899 bytes |
|
||||
| NSIS SHA-256 | `90EB68CDB5EAEDEA675050DA0F30DDAB5E8A0345FF176690A31FA5F66C818740` |
|
||||
|
||||
## Security boundary
|
||||
|
||||
- React never receives or submits credential values.
|
||||
- P01 IPC accepts only non-sensitive Profile fields.
|
||||
- Unknown input fields are rejected by Serde.
|
||||
- SQLite stores non-sensitive Profile metadata and reserves only an opaque `credential_reference`.
|
||||
- HTTP requires an explicit insecure-transport flag.
|
||||
- URLs containing credentials, query strings, or fragments are rejected.
|
||||
- No arbitrary command, unrestricted filesystem, registry-write, input-injection, or destructive file API was added.
|
||||
|
||||
## Build environment note
|
||||
|
||||
The first release attempts failed because the `libsqlite3-sys` release output directory did not contain `bindgen.rs`, although the crate build script had produced the SQLite static library. Cleaning only that package did not restore the file.
|
||||
|
||||
The official pre-generated `bindgen_bundled_version.rs` from the installed `libsqlite3-sys 0.38.1` crate source was copied to the exact `OUT_DIR/bindgen.rs` location expected by the crate's own `build.rs`. Source and destination SHA-256 values matched:
|
||||
The prior P01 release attempt found a missing generated `bindgen.rs` in the local `libsqlite3-sys 0.38.1` release cache. The official cached `bindgen_bundled_version.rs` was copied to the exact expected build-cache location, and the matching SHA-256 was recorded:
|
||||
|
||||
`5B5A37A74DC728FB0BCD041867EB577C03C95E2FE46285262C589A3B1CD4BBAC`
|
||||
|
||||
The production build and NSIS bundle then completed. This is recorded as an environment cache repair, not a repository or dependency change.
|
||||
This was an environment cache repair only. No repository file or dependency version was changed. The current production build completed successfully using the repaired cache.
|
||||
|
||||
## Paused boundary
|
||||
## Deferred to P02
|
||||
|
||||
Profile CRUD is not implemented in this increment.
|
||||
|
||||
- Architecture stage 1 includes Profile CRUD.
|
||||
- Implementation Batch 2 includes ConnectionProfile CRUD.
|
||||
- The conflict affects database structure and public IPC.
|
||||
- PD-0008 requires an explicit stage-boundary decision before work resumes.
|
||||
- companion and operations slot assignment;
|
||||
- maximum two active connections;
|
||||
- REST/SSE activation and cancellation;
|
||||
- auto-connect validation;
|
||||
- Profile switching protection;
|
||||
- duplicate `server_instance_id` warnings;
|
||||
- formal credential enrollment, lookup, rotation, and deletion.
|
||||
|
||||
## Not claimed
|
||||
|
||||
- P01 is not declared complete while PD-0008 is unresolved.
|
||||
- Forgejo CI has not run.
|
||||
- No Profile CRUD, profile UI, or slot assignment was added.
|
||||
- No real credential or destructive file operation was used.
|
||||
- No real AstrBot gateway compatibility is claimed.
|
||||
- No real credential was used.
|
||||
- No real UNC file transaction was executed.
|
||||
- No automatic merge to `main` was performed.
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "astrbot-desktop",
|
||||
"version": "0.1.0-alpha.0",
|
||||
"version": "0.1.0-alpha.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"packageManager": "pnpm@11.9.0",
|
||||
|
|
|
|||
|
|
@ -1,9 +1,11 @@
|
|||
mod profiles;
|
||||
|
||||
use std::{path::Path, sync::Mutex, time::Duration};
|
||||
|
||||
use rusqlite::{Connection, OptionalExtension, params};
|
||||
use thiserror::Error;
|
||||
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 1;
|
||||
pub const CURRENT_SCHEMA_VERSION: u32 = 2;
|
||||
|
||||
pub struct ApplicationDatabase {
|
||||
store: Mutex<ProfileMessageStore>,
|
||||
|
|
@ -16,6 +18,13 @@ impl ApplicationDatabase {
|
|||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn in_memory() -> Result<Self, DatabaseError> {
|
||||
Ok(Self {
|
||||
store: Mutex::new(ProfileMessageStore::in_memory()?),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn schema_version(&self) -> Result<u32, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
|
|
@ -143,6 +152,38 @@ fn migrate(connection: &mut Connection) -> Result<(), DatabaseError> {
|
|||
transaction.commit()?;
|
||||
}
|
||||
|
||||
if found <= 1 {
|
||||
let transaction = connection.transaction()?;
|
||||
transaction.execute_batch(
|
||||
"
|
||||
CREATE TABLE connection_profiles (
|
||||
id TEXT PRIMARY KEY NOT NULL,
|
||||
display_name TEXT NOT NULL CHECK(length(display_name) BETWEEN 1 AND 80),
|
||||
role TEXT NOT NULL CHECK(role IN ('companion', 'operations', 'general')),
|
||||
base_url TEXT NOT NULL,
|
||||
event_stream_url TEXT,
|
||||
authentication_type TEXT NOT NULL CHECK(authentication_type IN ('device-token', 'api-key')),
|
||||
credential_reference TEXT,
|
||||
allow_insecure_http INTEGER NOT NULL DEFAULT 0 CHECK(allow_insecure_http IN (0, 1)),
|
||||
pinned_certificate_fingerprint TEXT,
|
||||
auto_connect_slot TEXT CHECK(auto_connect_slot IS NULL OR auto_connect_slot IN ('companion', 'operations')),
|
||||
auto_connect INTEGER NOT NULL DEFAULT 0 CHECK(auto_connect IN (0, 1)),
|
||||
server_instance_id TEXT,
|
||||
server_version TEXT,
|
||||
protocol_version TEXT,
|
||||
local_tool_policy_id TEXT,
|
||||
last_connected_at TEXT,
|
||||
created_at TEXT NOT NULL,
|
||||
updated_at TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX connection_profiles_role_idx
|
||||
ON connection_profiles(role);
|
||||
PRAGMA user_version = 2;
|
||||
",
|
||||
)?;
|
||||
transaction.commit()?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -154,6 +195,10 @@ pub enum DatabaseError {
|
|||
UnsupportedSchemaVersion { found: u32, supported: u32 },
|
||||
#[error("database state lock is unavailable")]
|
||||
LockPoisoned,
|
||||
#[error("database contains invalid profile data")]
|
||||
InvalidStoredProfile,
|
||||
#[error("connection profile was not found")]
|
||||
ProfileNotFound,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
|
@ -196,6 +241,62 @@ mod tests {
|
|||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn migrates_v1_to_v2_without_losing_messages() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("v1.sqlite3");
|
||||
let connection = Connection::open(&path).expect("create v1 database");
|
||||
connection
|
||||
.execute_batch(
|
||||
"
|
||||
CREATE TABLE messages (
|
||||
profile_id TEXT NOT NULL,
|
||||
server_instance_id TEXT NOT NULL,
|
||||
conversation_id TEXT NOT NULL,
|
||||
message_id TEXT NOT NULL,
|
||||
content TEXT NOT NULL,
|
||||
PRIMARY KEY (profile_id, server_instance_id, conversation_id, message_id)
|
||||
);
|
||||
INSERT INTO messages (
|
||||
profile_id,
|
||||
server_instance_id,
|
||||
conversation_id,
|
||||
message_id,
|
||||
content
|
||||
) VALUES (
|
||||
'profile-a',
|
||||
'server-a',
|
||||
'conversation-a',
|
||||
'message-a',
|
||||
'preserved'
|
||||
);
|
||||
PRAGMA user_version = 1;
|
||||
",
|
||||
)
|
||||
.expect("create v1 schema");
|
||||
drop(connection);
|
||||
|
||||
let store = ProfileMessageStore::open(&path).expect("migrate database");
|
||||
assert_eq!(store.schema_version().expect("schema version"), 2);
|
||||
assert_eq!(
|
||||
store
|
||||
.message_content("profile-a", "server-a", "conversation-a", "message-a")
|
||||
.expect("query preserved message")
|
||||
.as_deref(),
|
||||
Some("preserved")
|
||||
);
|
||||
let profile_table_count: u32 = store
|
||||
.connection
|
||||
.query_row(
|
||||
"SELECT COUNT(*) FROM sqlite_master
|
||||
WHERE type = 'table' AND name = 'connection_profiles'",
|
||||
[],
|
||||
|row| row.get(0),
|
||||
)
|
||||
.expect("query profile table");
|
||||
assert_eq!(profile_table_count, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_database_from_a_newer_schema_version() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
|
|
@ -209,7 +310,7 @@ mod tests {
|
|||
assert!(matches!(
|
||||
ProfileMessageStore::open(path),
|
||||
Err(DatabaseError::UnsupportedSchemaVersion {
|
||||
found: 2,
|
||||
found: 3,
|
||||
supported: CURRENT_SCHEMA_VERSION
|
||||
})
|
||||
));
|
||||
|
|
|
|||
349
src-tauri/src/database/profiles.rs
普通文件
349
src-tauri/src/database/profiles.rs
普通文件
|
|
@ -0,0 +1,349 @@
|
|||
use desktop_protocol::{ActiveSlotKind, AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||
use rusqlite::{Row, params};
|
||||
|
||||
use super::{ApplicationDatabase, DatabaseError, ProfileMessageStore};
|
||||
|
||||
const PROFILE_COLUMNS: &str = "
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type,
|
||||
credential_reference,
|
||||
allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect_slot,
|
||||
auto_connect,
|
||||
server_instance_id,
|
||||
server_version,
|
||||
protocol_version,
|
||||
local_tool_policy_id,
|
||||
last_connected_at,
|
||||
created_at,
|
||||
updated_at
|
||||
";
|
||||
|
||||
impl ApplicationDatabase {
|
||||
pub fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.list_profiles()
|
||||
}
|
||||
|
||||
pub fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.profile(id)
|
||||
}
|
||||
|
||||
pub fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.create_profile(profile)
|
||||
}
|
||||
|
||||
pub fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.update_profile(profile)
|
||||
}
|
||||
|
||||
pub fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|_| DatabaseError::LockPoisoned)?
|
||||
.delete_profile(id)
|
||||
}
|
||||
}
|
||||
|
||||
impl ProfileMessageStore {
|
||||
fn list_profiles(&self) -> Result<Vec<ConnectionProfile>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(&format!(
|
||||
"SELECT {PROFILE_COLUMNS}
|
||||
FROM connection_profiles
|
||||
ORDER BY display_name COLLATE NOCASE, id"
|
||||
))?;
|
||||
let mut rows = statement.query([])?;
|
||||
let mut profiles = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
profiles.push(profile_from_row(row)?);
|
||||
}
|
||||
Ok(profiles)
|
||||
}
|
||||
|
||||
fn profile(&self, id: &str) -> Result<Option<ConnectionProfile>, DatabaseError> {
|
||||
let mut statement = self.connection.prepare(&format!(
|
||||
"SELECT {PROFILE_COLUMNS}
|
||||
FROM connection_profiles
|
||||
WHERE id = ?1"
|
||||
))?;
|
||||
let mut rows = statement.query(params![id])?;
|
||||
match rows.next()? {
|
||||
Some(row) => Ok(Some(profile_from_row(row)?)),
|
||||
None => Ok(None),
|
||||
}
|
||||
}
|
||||
|
||||
fn create_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
self.connection.execute(
|
||||
"
|
||||
INSERT INTO connection_profiles (
|
||||
id,
|
||||
display_name,
|
||||
role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type,
|
||||
credential_reference,
|
||||
allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
auto_connect_slot,
|
||||
auto_connect,
|
||||
server_instance_id,
|
||||
server_version,
|
||||
protocol_version,
|
||||
local_tool_policy_id,
|
||||
last_connected_at,
|
||||
created_at,
|
||||
updated_at
|
||||
) VALUES (
|
||||
?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9,
|
||||
?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18
|
||||
)
|
||||
",
|
||||
params![
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
role_to_str(profile.role),
|
||||
profile.base_url,
|
||||
profile.event_stream_url,
|
||||
authentication_to_str(profile.authentication_type),
|
||||
profile.credential_reference,
|
||||
profile.allow_insecure_http,
|
||||
profile.pinned_certificate_fingerprint,
|
||||
profile.auto_connect_slot.map(slot_to_str),
|
||||
profile.auto_connect,
|
||||
profile.server_instance_id,
|
||||
profile.server_version,
|
||||
profile.protocol_version,
|
||||
profile.local_tool_policy_id,
|
||||
profile.last_connected_at,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn update_profile(&self, profile: &ConnectionProfile) -> Result<(), DatabaseError> {
|
||||
let changed = self.connection.execute(
|
||||
"
|
||||
UPDATE connection_profiles
|
||||
SET display_name = ?2,
|
||||
role = ?3,
|
||||
base_url = ?4,
|
||||
event_stream_url = ?5,
|
||||
authentication_type = ?6,
|
||||
credential_reference = ?7,
|
||||
allow_insecure_http = ?8,
|
||||
pinned_certificate_fingerprint = ?9,
|
||||
auto_connect_slot = ?10,
|
||||
auto_connect = ?11,
|
||||
server_instance_id = ?12,
|
||||
server_version = ?13,
|
||||
protocol_version = ?14,
|
||||
local_tool_policy_id = ?15,
|
||||
last_connected_at = ?16,
|
||||
created_at = ?17,
|
||||
updated_at = ?18
|
||||
WHERE id = ?1
|
||||
",
|
||||
params![
|
||||
profile.id,
|
||||
profile.display_name,
|
||||
role_to_str(profile.role),
|
||||
profile.base_url,
|
||||
profile.event_stream_url,
|
||||
authentication_to_str(profile.authentication_type),
|
||||
profile.credential_reference,
|
||||
profile.allow_insecure_http,
|
||||
profile.pinned_certificate_fingerprint,
|
||||
profile.auto_connect_slot.map(slot_to_str),
|
||||
profile.auto_connect,
|
||||
profile.server_instance_id,
|
||||
profile.server_version,
|
||||
profile.protocol_version,
|
||||
profile.local_tool_policy_id,
|
||||
profile.last_connected_at,
|
||||
profile.created_at,
|
||||
profile.updated_at,
|
||||
],
|
||||
)?;
|
||||
if changed == 0 {
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn delete_profile(&self, id: &str) -> Result<(), DatabaseError> {
|
||||
if self
|
||||
.connection
|
||||
.execute("DELETE FROM connection_profiles WHERE id = ?1", params![id])?
|
||||
== 0
|
||||
{
|
||||
return Err(DatabaseError::ProfileNotFound);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_from_row(row: &Row<'_>) -> Result<ConnectionProfile, DatabaseError> {
|
||||
let role = match row.get::<_, String>(2)?.as_str() {
|
||||
"companion" => AstrBotProfileRole::Companion,
|
||||
"operations" => AstrBotProfileRole::Operations,
|
||||
"general" => AstrBotProfileRole::General,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let authentication_type = match row.get::<_, String>(5)?.as_str() {
|
||||
"device-token" => AuthenticationType::DeviceToken,
|
||||
"api-key" => AuthenticationType::ApiKey,
|
||||
_ => return Err(DatabaseError::InvalidStoredProfile),
|
||||
};
|
||||
let auto_connect_slot = match row.get::<_, Option<String>>(9)?.as_deref() {
|
||||
Some("companion") => Some(ActiveSlotKind::Companion),
|
||||
Some("operations") => Some(ActiveSlotKind::Operations),
|
||||
Some(_) => return Err(DatabaseError::InvalidStoredProfile),
|
||||
None => None,
|
||||
};
|
||||
|
||||
Ok(ConnectionProfile {
|
||||
id: row.get(0)?,
|
||||
display_name: row.get(1)?,
|
||||
role,
|
||||
base_url: row.get(3)?,
|
||||
event_stream_url: row.get(4)?,
|
||||
authentication_type,
|
||||
credential_reference: row.get(6)?,
|
||||
allow_insecure_http: row.get(7)?,
|
||||
pinned_certificate_fingerprint: row.get(8)?,
|
||||
auto_connect_slot,
|
||||
auto_connect: row.get(10)?,
|
||||
server_instance_id: row.get(11)?,
|
||||
server_version: row.get(12)?,
|
||||
protocol_version: row.get(13)?,
|
||||
local_tool_policy_id: row.get(14)?,
|
||||
last_connected_at: row.get(15)?,
|
||||
created_at: row.get(16)?,
|
||||
updated_at: row.get(17)?,
|
||||
})
|
||||
}
|
||||
|
||||
fn role_to_str(role: AstrBotProfileRole) -> &'static str {
|
||||
match role {
|
||||
AstrBotProfileRole::Companion => "companion",
|
||||
AstrBotProfileRole::Operations => "operations",
|
||||
AstrBotProfileRole::General => "general",
|
||||
}
|
||||
}
|
||||
|
||||
fn authentication_to_str(authentication_type: AuthenticationType) -> &'static str {
|
||||
match authentication_type {
|
||||
AuthenticationType::DeviceToken => "device-token",
|
||||
AuthenticationType::ApiKey => "api-key",
|
||||
}
|
||||
}
|
||||
|
||||
fn slot_to_str(slot: ActiveSlotKind) -> &'static str {
|
||||
match slot {
|
||||
ActiveSlotKind::Companion => "companion",
|
||||
ActiveSlotKind::Operations => "operations",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn profile(index: usize) -> ConnectionProfile {
|
||||
ConnectionProfile {
|
||||
id: format!("00000000-0000-4000-8000-{index:012}"),
|
||||
display_name: format!("Profile {index}"),
|
||||
role: AstrBotProfileRole::General,
|
||||
base_url: format!("https://example-{index}.test/"),
|
||||
event_stream_url: None,
|
||||
authentication_type: AuthenticationType::DeviceToken,
|
||||
credential_reference: None,
|
||||
allow_insecure_http: false,
|
||||
pinned_certificate_fingerprint: None,
|
||||
auto_connect_slot: None,
|
||||
auto_connect: false,
|
||||
server_instance_id: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
local_tool_policy_id: None,
|
||||
last_connected_at: None,
|
||||
created_at: "2026-07-18T00:00:00Z".into(),
|
||||
updated_at: "2026-07-18T00:00:00Z".into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stores_lists_updates_and_deletes_five_profiles() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
for index in 0..5 {
|
||||
database
|
||||
.create_profile(&profile(index))
|
||||
.expect("create profile");
|
||||
}
|
||||
assert_eq!(database.list_profiles().expect("list profiles").len(), 5);
|
||||
|
||||
let mut updated = database
|
||||
.profile(&profile(2).id)
|
||||
.expect("read profile")
|
||||
.expect("existing profile");
|
||||
updated.display_name = "Updated Profile".into();
|
||||
updated.updated_at = "2026-07-18T01:00:00Z".into();
|
||||
database.update_profile(&updated).expect("update profile");
|
||||
assert_eq!(
|
||||
database
|
||||
.profile(&updated.id)
|
||||
.expect("read updated profile")
|
||||
.expect("existing profile")
|
||||
.display_name,
|
||||
"Updated Profile"
|
||||
);
|
||||
|
||||
database
|
||||
.delete_profile(&updated.id)
|
||||
.expect("delete profile");
|
||||
assert_eq!(database.list_profiles().expect("list profiles").len(), 4);
|
||||
assert!(matches!(
|
||||
database.delete_profile(&updated.id),
|
||||
Err(DatabaseError::ProfileNotFound)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_metadata_persists_after_reopening_database() {
|
||||
let directory = tempfile::tempdir().expect("temporary directory");
|
||||
let path = directory.path().join("profiles.sqlite3");
|
||||
let expected = profile(7);
|
||||
|
||||
{
|
||||
let store = ProfileMessageStore::open(&path).expect("open database");
|
||||
store.create_profile(&expected).expect("create profile");
|
||||
}
|
||||
|
||||
let reopened = ProfileMessageStore::open(&path).expect("reopen database");
|
||||
let actual = reopened
|
||||
.profile(&expected.id)
|
||||
.expect("read profile")
|
||||
.expect("persisted profile");
|
||||
assert_eq!(actual, expected);
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ pub mod diagnostics;
|
|||
pub mod file_transfer;
|
||||
pub mod logging;
|
||||
pub mod networking;
|
||||
pub mod profiles;
|
||||
pub mod secure_store;
|
||||
pub mod windows;
|
||||
|
||||
|
|
@ -85,7 +86,13 @@ pub fn run() {
|
|||
let _ = window.hide();
|
||||
}
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![bootstrap_status])
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
bootstrap_status,
|
||||
profiles::list_connection_profiles,
|
||||
profiles::create_connection_profile,
|
||||
profiles::update_connection_profile,
|
||||
profiles::delete_connection_profile,
|
||||
])
|
||||
.run(tauri::generate_context!())
|
||||
.expect("failed to run AstrBot Desktop");
|
||||
}
|
||||
|
|
|
|||
353
src-tauri/src/profiles.rs
普通文件
353
src-tauri/src/profiles.rs
普通文件
|
|
@ -0,0 +1,353 @@
|
|||
use desktop_protocol::{AstrBotProfileRole, AuthenticationType, ConnectionProfile};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
|
||||
use url::Url;
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::database::{ApplicationDatabase, DatabaseError};
|
||||
|
||||
const MAX_DISPLAY_NAME_CHARS: usize = 80;
|
||||
const MAX_URL_CHARS: usize = 2048;
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct ConnectionProfileInput {
|
||||
pub display_name: String,
|
||||
pub role: AstrBotProfileRole,
|
||||
pub base_url: String,
|
||||
#[serde(default)]
|
||||
pub event_stream_url: Option<String>,
|
||||
pub authentication_type: AuthenticationType,
|
||||
#[serde(default)]
|
||||
pub allow_insecure_http: bool,
|
||||
#[serde(default)]
|
||||
pub pinned_certificate_fingerprint: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Deserialize)]
|
||||
#[serde(rename_all = "camelCase", deny_unknown_fields)]
|
||||
pub struct UpdateConnectionProfileRequest {
|
||||
pub id: String,
|
||||
#[serde(flatten)]
|
||||
pub profile: ConnectionProfileInput,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct ProfileCommandError {
|
||||
code: &'static str,
|
||||
message: &'static str,
|
||||
}
|
||||
|
||||
impl ProfileCommandError {
|
||||
fn validation(message: &'static str) -> Self {
|
||||
Self {
|
||||
code: "validationFailed",
|
||||
message,
|
||||
}
|
||||
}
|
||||
|
||||
fn database(error: DatabaseError) -> Self {
|
||||
match error {
|
||||
DatabaseError::ProfileNotFound => Self {
|
||||
code: "notFound",
|
||||
message: "The connection profile no longer exists.",
|
||||
},
|
||||
_ => Self {
|
||||
code: "databaseUnavailable",
|
||||
message: "The local profile database is unavailable.",
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn list_connection_profiles(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||
list_profiles(&database)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn create_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
create_profile(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn update_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
request: UpdateConnectionProfileRequest,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
update_profile(&database, request)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
pub fn delete_connection_profile(
|
||||
database: tauri::State<'_, ApplicationDatabase>,
|
||||
id: String,
|
||||
) -> Result<(), ProfileCommandError> {
|
||||
delete_profile(&database, &id)
|
||||
}
|
||||
|
||||
fn list_profiles(
|
||||
database: &ApplicationDatabase,
|
||||
) -> Result<Vec<ConnectionProfile>, ProfileCommandError> {
|
||||
database
|
||||
.list_profiles()
|
||||
.map_err(ProfileCommandError::database)
|
||||
}
|
||||
|
||||
fn create_profile(
|
||||
database: &ApplicationDatabase,
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
let normalized = normalize_input(request)?;
|
||||
let now = timestamp()?;
|
||||
let profile = ConnectionProfile {
|
||||
id: Uuid::new_v4().to_string(),
|
||||
display_name: normalized.display_name,
|
||||
role: normalized.role,
|
||||
base_url: normalized.base_url,
|
||||
event_stream_url: normalized.event_stream_url,
|
||||
authentication_type: normalized.authentication_type,
|
||||
credential_reference: None,
|
||||
allow_insecure_http: normalized.allow_insecure_http,
|
||||
pinned_certificate_fingerprint: normalized.pinned_certificate_fingerprint,
|
||||
auto_connect_slot: None,
|
||||
auto_connect: false,
|
||||
server_instance_id: None,
|
||||
server_version: None,
|
||||
protocol_version: None,
|
||||
local_tool_policy_id: None,
|
||||
last_connected_at: None,
|
||||
created_at: now.clone(),
|
||||
updated_at: now,
|
||||
};
|
||||
database
|
||||
.create_profile(&profile)
|
||||
.map_err(ProfileCommandError::database)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
fn update_profile(
|
||||
database: &ApplicationDatabase,
|
||||
request: UpdateConnectionProfileRequest,
|
||||
) -> Result<ConnectionProfile, ProfileCommandError> {
|
||||
validate_id(&request.id)?;
|
||||
let normalized = normalize_input(request.profile)?;
|
||||
let mut profile = database
|
||||
.profile(&request.id)
|
||||
.map_err(ProfileCommandError::database)?
|
||||
.ok_or_else(|| ProfileCommandError::database(DatabaseError::ProfileNotFound))?;
|
||||
|
||||
profile.display_name = normalized.display_name;
|
||||
profile.role = normalized.role;
|
||||
profile.base_url = normalized.base_url;
|
||||
profile.event_stream_url = normalized.event_stream_url;
|
||||
profile.authentication_type = normalized.authentication_type;
|
||||
profile.allow_insecure_http = normalized.allow_insecure_http;
|
||||
profile.pinned_certificate_fingerprint = normalized.pinned_certificate_fingerprint;
|
||||
profile.updated_at = timestamp()?;
|
||||
|
||||
database
|
||||
.update_profile(&profile)
|
||||
.map_err(ProfileCommandError::database)?;
|
||||
Ok(profile)
|
||||
}
|
||||
|
||||
fn delete_profile(database: &ApplicationDatabase, id: &str) -> Result<(), ProfileCommandError> {
|
||||
validate_id(id)?;
|
||||
database
|
||||
.delete_profile(id)
|
||||
.map_err(ProfileCommandError::database)
|
||||
}
|
||||
|
||||
fn normalize_input(
|
||||
request: ConnectionProfileInput,
|
||||
) -> Result<ConnectionProfileInput, ProfileCommandError> {
|
||||
let display_name = request.display_name.trim().to_owned();
|
||||
if display_name.is_empty()
|
||||
|| display_name.chars().count() > MAX_DISPLAY_NAME_CHARS
|
||||
|| display_name.chars().any(char::is_control)
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Display name must contain 1 to 80 visible characters.",
|
||||
));
|
||||
}
|
||||
|
||||
let base_url = normalize_url(&request.base_url, request.allow_insecure_http)?;
|
||||
let event_stream_url = request
|
||||
.event_stream_url
|
||||
.as_deref()
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
.map(|value| normalize_url(value, request.allow_insecure_http))
|
||||
.transpose()?;
|
||||
let pinned_certificate_fingerprint =
|
||||
normalize_fingerprint(request.pinned_certificate_fingerprint)?;
|
||||
|
||||
Ok(ConnectionProfileInput {
|
||||
display_name,
|
||||
role: request.role,
|
||||
base_url,
|
||||
event_stream_url,
|
||||
authentication_type: request.authentication_type,
|
||||
allow_insecure_http: request.allow_insecure_http,
|
||||
pinned_certificate_fingerprint,
|
||||
})
|
||||
}
|
||||
|
||||
fn normalize_url(value: &str, allow_insecure_http: bool) -> Result<String, ProfileCommandError> {
|
||||
let value = value.trim();
|
||||
if value.is_empty() || value.chars().count() > MAX_URL_CHARS {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URL is empty or too long.",
|
||||
));
|
||||
}
|
||||
|
||||
let mut url = Url::parse(value)
|
||||
.map_err(|_| ProfileCommandError::validation("Connection URL is invalid."))?;
|
||||
if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URL must use HTTP or HTTPS and include a host.",
|
||||
));
|
||||
}
|
||||
if !url.username().is_empty() || url.password().is_some() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Credentials must not be embedded in a connection URL.",
|
||||
));
|
||||
}
|
||||
if url.query().is_some() || url.fragment().is_some() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection URLs must not contain query parameters or fragments.",
|
||||
));
|
||||
}
|
||||
if url.scheme() == "http" && !allow_insecure_http {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"HTTP requires explicit insecure-transport approval.",
|
||||
));
|
||||
}
|
||||
url.set_fragment(None);
|
||||
Ok(url.to_string())
|
||||
}
|
||||
|
||||
fn normalize_fingerprint(value: Option<String>) -> Result<Option<String>, ProfileCommandError> {
|
||||
let Some(value) = value else {
|
||||
return Ok(None);
|
||||
};
|
||||
let normalized = value
|
||||
.trim()
|
||||
.chars()
|
||||
.filter(|character| *character != ':')
|
||||
.flat_map(char::to_uppercase)
|
||||
.collect::<String>();
|
||||
if normalized.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
if normalized.len() != 64
|
||||
|| !normalized
|
||||
.chars()
|
||||
.all(|character| character.is_ascii_hexdigit())
|
||||
{
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Pinned certificate fingerprint must be a SHA-256 hex value.",
|
||||
));
|
||||
}
|
||||
Ok(Some(normalized))
|
||||
}
|
||||
|
||||
fn validate_id(id: &str) -> Result<(), ProfileCommandError> {
|
||||
if Uuid::parse_str(id).is_err() {
|
||||
return Err(ProfileCommandError::validation(
|
||||
"Connection profile ID is invalid.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn timestamp() -> Result<String, ProfileCommandError> {
|
||||
OffsetDateTime::now_utc()
|
||||
.format(&Rfc3339)
|
||||
.map_err(|_| ProfileCommandError {
|
||||
code: "clockUnavailable",
|
||||
message: "The system clock could not produce a profile timestamp.",
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn request(base_url: &str) -> ConnectionProfileInput {
|
||||
ConnectionProfileInput {
|
||||
display_name: " Test Profile ".into(),
|
||||
role: AstrBotProfileRole::General,
|
||||
base_url: base_url.into(),
|
||||
event_stream_url: None,
|
||||
authentication_type: AuthenticationType::DeviceToken,
|
||||
allow_insecure_http: false,
|
||||
pinned_certificate_fingerprint: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn creates_updates_lists_and_deletes_profile_metadata() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
let created =
|
||||
create_profile(&database, request("https://example.test")).expect("create profile");
|
||||
assert_eq!(created.display_name, "Test Profile");
|
||||
assert_eq!(created.base_url, "https://example.test/");
|
||||
assert!(created.credential_reference.is_none());
|
||||
assert!(!created.auto_connect);
|
||||
assert!(created.auto_connect_slot.is_none());
|
||||
|
||||
let updated = update_profile(
|
||||
&database,
|
||||
UpdateConnectionProfileRequest {
|
||||
id: created.id.clone(),
|
||||
profile: ConnectionProfileInput {
|
||||
display_name: "Updated".into(),
|
||||
role: AstrBotProfileRole::Companion,
|
||||
base_url: "https://updated.example.test".into(),
|
||||
event_stream_url: Some("https://updated.example.test/events".into()),
|
||||
authentication_type: AuthenticationType::ApiKey,
|
||||
allow_insecure_http: false,
|
||||
pinned_certificate_fingerprint: None,
|
||||
},
|
||||
},
|
||||
)
|
||||
.expect("update profile");
|
||||
assert_eq!(updated.display_name, "Updated");
|
||||
assert_eq!(list_profiles(&database).expect("list profiles").len(), 1);
|
||||
|
||||
delete_profile(&database, &created.id).expect("delete profile");
|
||||
assert!(list_profiles(&database).expect("list profiles").is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_insecure_or_credential_bearing_urls() {
|
||||
let database = ApplicationDatabase::in_memory().expect("database");
|
||||
assert!(create_profile(&database, request("http://example.test")).is_err());
|
||||
assert!(create_profile(&database, request("https://user:password@example.test")).is_err());
|
||||
assert!(create_profile(&database, request("https://example.test?token=fake")).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_secret_values_and_unknown_fields_at_the_ipc_boundary() {
|
||||
let result = serde_json::from_value::<ConnectionProfileInput>(serde_json::json!({
|
||||
"displayName": "Test Profile",
|
||||
"role": "general",
|
||||
"baseUrl": "https://example.test",
|
||||
"authenticationType": "device-token",
|
||||
"allowInsecureHttp": false,
|
||||
"token": "[REDACTED]",
|
||||
"password": "[REDACTED]",
|
||||
"apiKey": "[REDACTED]"
|
||||
}));
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
}
|
||||
|
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "AstrBot Desktop",
|
||||
"version": "0.1.0-alpha.0",
|
||||
"version": "0.1.0-alpha.1",
|
||||
"identifier": "com.yokiirobw.astrbot-desktop",
|
||||
"build": {
|
||||
"beforeDevCommand": "npm run dev",
|
||||
|
|
|
|||
141
src/App.test.tsx
141
src/App.test.tsx
|
|
@ -1,21 +1,36 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { App } from "./App";
|
||||
import type {
|
||||
ConnectionProfile,
|
||||
ConnectionProfileInput,
|
||||
UpdateConnectionProfileRequest,
|
||||
} from "./types/profile";
|
||||
|
||||
vi.mock("@tauri-apps/api/core", () => ({
|
||||
invoke: vi.fn(),
|
||||
}));
|
||||
|
||||
const bootstrapStatus = {
|
||||
appVersion: "0.1.0-alpha.0",
|
||||
platform: "windows",
|
||||
rustCore: "ready",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 2,
|
||||
};
|
||||
|
||||
describe("App", () => {
|
||||
beforeEach(() => {
|
||||
vi.mocked(invoke).mockResolvedValue({
|
||||
appVersion: "0.1.0-alpha.0",
|
||||
platform: "windows",
|
||||
rustCore: "ready",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 1,
|
||||
vi.mocked(invoke).mockImplementation(async (command) => {
|
||||
if (command === "bootstrap_status") {
|
||||
return bootstrapStatus;
|
||||
}
|
||||
if (command === "list_connection_profiles") {
|
||||
return [];
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -24,15 +39,21 @@ describe("App", () => {
|
|||
|
||||
expect(await screen.findByText("ready")).toBeInTheDocument();
|
||||
expect(screen.getByText("desktop-v1alpha1")).toBeInTheDocument();
|
||||
expect(screen.getByText("连接 Profile")).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("rejects an invalid Rust IPC payload", async () => {
|
||||
vi.mocked(invoke).mockResolvedValueOnce({
|
||||
appVersion: "0.1.0-alpha.0",
|
||||
platform: "windows",
|
||||
rustCore: "unexpected",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 1,
|
||||
vi.mocked(invoke).mockImplementation(async (command) => {
|
||||
if (command === "bootstrap_status") {
|
||||
return {
|
||||
...bootstrapStatus,
|
||||
rustCore: "unexpected",
|
||||
};
|
||||
}
|
||||
if (command === "list_connection_profiles") {
|
||||
return [];
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`);
|
||||
});
|
||||
|
||||
render(<App />);
|
||||
|
|
@ -40,4 +61,98 @@ describe("App", () => {
|
|||
expect(await screen.findByText(/IPC unavailable:/)).toBeInTheDocument();
|
||||
expect(screen.queryByText("unexpected")).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("creates, edits, and deletes non-sensitive profile metadata", async () => {
|
||||
let profiles: ConnectionProfile[] = [];
|
||||
vi.mocked(invoke).mockImplementation(async (command, args) => {
|
||||
if (command === "bootstrap_status") {
|
||||
return bootstrapStatus;
|
||||
}
|
||||
if (command === "list_connection_profiles") {
|
||||
return profiles;
|
||||
}
|
||||
if (command === "create_connection_profile") {
|
||||
const { request } = args as { request: ConnectionProfileInput };
|
||||
const created: ConnectionProfile = {
|
||||
id: "2bdedc10-d804-4da5-8e92-39dd7f175d7a",
|
||||
...request,
|
||||
autoConnect: false,
|
||||
createdAt: "2026-07-18T02:00:00Z",
|
||||
updatedAt: "2026-07-18T02:00:00Z",
|
||||
};
|
||||
profiles = [created];
|
||||
return created;
|
||||
}
|
||||
if (command === "update_connection_profile") {
|
||||
const { request } = args as {
|
||||
request: UpdateConnectionProfileRequest;
|
||||
};
|
||||
const existing = profiles.find((profile) => profile.id === request.id);
|
||||
if (!existing) {
|
||||
throw new Error("Profile not found");
|
||||
}
|
||||
const updated: ConnectionProfile = {
|
||||
...existing,
|
||||
...request.profile,
|
||||
updatedAt: "2026-07-18T02:10:00Z",
|
||||
};
|
||||
profiles = [updated];
|
||||
return updated;
|
||||
}
|
||||
if (command === "delete_connection_profile") {
|
||||
const { id } = args as { id: string };
|
||||
profiles = profiles.filter((profile) => profile.id !== id);
|
||||
return undefined;
|
||||
}
|
||||
throw new Error(`Unexpected command: ${command}`);
|
||||
});
|
||||
vi.spyOn(window, "confirm").mockReturnValue(true);
|
||||
|
||||
render(<App />);
|
||||
expect(await screen.findByText("尚未保存 Profile。")).toBeInTheDocument();
|
||||
|
||||
fireEvent.change(screen.getByLabelText("显示名称"), {
|
||||
target: { value: "家庭运维" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("角色"), {
|
||||
target: { value: "operations" },
|
||||
});
|
||||
fireEvent.change(screen.getByLabelText("REST 基础 URL"), {
|
||||
target: { value: "https://ops.example.test" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "保存 Profile" }));
|
||||
|
||||
expect(
|
||||
await screen.findByText("已创建 Profile:家庭运维"),
|
||||
).toBeInTheDocument();
|
||||
expect(screen.getByLabelText("编辑 家庭运维")).toBeEnabled();
|
||||
|
||||
fireEvent.click(screen.getByLabelText("编辑 家庭运维"));
|
||||
fireEvent.change(screen.getByLabelText("显示名称"), {
|
||||
target: { value: "家庭运维(主)" },
|
||||
});
|
||||
fireEvent.click(screen.getByRole("button", { name: "更新 Profile" }));
|
||||
|
||||
expect(
|
||||
await screen.findByText("已更新 Profile:家庭运维(主)"),
|
||||
).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByLabelText("删除 家庭运维(主)"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(
|
||||
screen.getByText("已删除 Profile:家庭运维(主)"),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
expect(screen.getByText("尚未保存 Profile。")).toBeInTheDocument();
|
||||
expect(invoke).toHaveBeenCalledWith(
|
||||
"create_connection_profile",
|
||||
expect.objectContaining({
|
||||
request: expect.not.objectContaining({
|
||||
token: expect.anything(),
|
||||
password: expect.anything(),
|
||||
apiKey: expect.anything(),
|
||||
}),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
|
||||
import { ProfileManager } from "./features/profiles/ProfileManager";
|
||||
import { bootstrapStatusSchema, type BootstrapStatus } from "./types/bootstrap";
|
||||
|
||||
const initialStatus: BootstrapStatus = {
|
||||
|
|
@ -8,7 +9,7 @@ const initialStatus: BootstrapStatus = {
|
|||
platform: "unknown",
|
||||
rustCore: "pending",
|
||||
protocolVersion: "desktop-v1alpha1",
|
||||
databaseSchemaVersion: 1,
|
||||
databaseSchemaVersion: 2,
|
||||
};
|
||||
|
||||
export function App() {
|
||||
|
|
@ -32,7 +33,7 @@ export function App() {
|
|||
return (
|
||||
<main className="app-shell">
|
||||
<header className="hero">
|
||||
<p className="eyebrow">P00 · bootstrap</p>
|
||||
<p className="eyebrow">P01 · foundation</p>
|
||||
<h1>AstrBot Desktop</h1>
|
||||
<p className="subtitle">
|
||||
双实例陪伴与本机助手的安全 Windows 客户端工程底座。
|
||||
|
|
@ -61,6 +62,7 @@ export function App() {
|
|||
<li>文件事务默认保留源文件,且不会静默覆盖。</li>
|
||||
</ul>
|
||||
</section>
|
||||
<ProfileManager />
|
||||
|
||||
<button type="button" onClick={() => void refreshStatus()}>
|
||||
重新检查 IPC
|
||||
|
|
|
|||
|
|
@ -0,0 +1,396 @@
|
|||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { useCallback, useEffect, useState, type FormEvent } from "react";
|
||||
|
||||
import {
|
||||
connectionProfileListSchema,
|
||||
connectionProfileSchema,
|
||||
type AuthenticationType,
|
||||
type ConnectionProfile,
|
||||
type ConnectionProfileInput,
|
||||
type ProfileRole,
|
||||
type UpdateConnectionProfileRequest,
|
||||
} from "../../types/profile";
|
||||
|
||||
interface ProfileFormState {
|
||||
displayName: string;
|
||||
role: ProfileRole;
|
||||
baseUrl: string;
|
||||
eventStreamUrl: string;
|
||||
authenticationType: AuthenticationType;
|
||||
allowInsecureHttp: boolean;
|
||||
pinnedCertificateFingerprint: string;
|
||||
}
|
||||
|
||||
const emptyForm: ProfileFormState = {
|
||||
displayName: "",
|
||||
role: "general",
|
||||
baseUrl: "https://",
|
||||
eventStreamUrl: "",
|
||||
authenticationType: "device-token",
|
||||
allowInsecureHttp: false,
|
||||
pinnedCertificateFingerprint: "",
|
||||
};
|
||||
|
||||
export function ProfileManager() {
|
||||
const [profiles, setProfiles] = useState<ConnectionProfile[]>([]);
|
||||
const [form, setForm] = useState<ProfileFormState>(emptyForm);
|
||||
const [editingId, setEditingId] = useState<string | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
|
||||
const loadProfiles = useCallback(async () => {
|
||||
try {
|
||||
const result = await invoke<unknown>("list_connection_profiles");
|
||||
setProfiles(connectionProfileListSchema.parse(result));
|
||||
setError(null);
|
||||
} catch (reason) {
|
||||
setError(`Profile storage unavailable: ${errorMessage(reason)}`);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
void loadProfiles();
|
||||
}, [loadProfiles]);
|
||||
|
||||
async function submitProfile(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
|
||||
try {
|
||||
const profileInput = toProfileInput(form);
|
||||
const result = editingId
|
||||
? await invoke<unknown>("update_connection_profile", {
|
||||
request: {
|
||||
id: editingId,
|
||||
profile: profileInput,
|
||||
} satisfies UpdateConnectionProfileRequest,
|
||||
})
|
||||
: await invoke<unknown>("create_connection_profile", {
|
||||
request: profileInput,
|
||||
});
|
||||
const saved = connectionProfileSchema.parse(result);
|
||||
setProfiles((current) =>
|
||||
sortProfiles([
|
||||
...current.filter((profile) => profile.id !== saved.id),
|
||||
saved,
|
||||
]),
|
||||
);
|
||||
setNotice(
|
||||
editingId
|
||||
? `已更新 Profile:${saved.displayName}`
|
||||
: `已创建 Profile:${saved.displayName}`,
|
||||
);
|
||||
resetForm();
|
||||
} catch (reason) {
|
||||
setError(`Profile save failed: ${errorMessage(reason)}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function editProfile(profile: ConnectionProfile) {
|
||||
setEditingId(profile.id);
|
||||
setForm({
|
||||
displayName: profile.displayName,
|
||||
role: profile.role,
|
||||
baseUrl: profile.baseUrl,
|
||||
eventStreamUrl: profile.eventStreamUrl ?? "",
|
||||
authenticationType: profile.authenticationType,
|
||||
allowInsecureHttp: profile.allowInsecureHttp,
|
||||
pinnedCertificateFingerprint: profile.pinnedCertificateFingerprint ?? "",
|
||||
});
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
}
|
||||
|
||||
async function deleteProfile(profile: ConnectionProfile) {
|
||||
if (
|
||||
!window.confirm(
|
||||
`删除 Profile“${profile.displayName}”?此操作不会删除凭据值,因为 P01 不接触凭据。`,
|
||||
)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
setBusy(true);
|
||||
setError(null);
|
||||
setNotice(null);
|
||||
try {
|
||||
await invoke("delete_connection_profile", { id: profile.id });
|
||||
setProfiles((current) =>
|
||||
current.filter((item) => item.id !== profile.id),
|
||||
);
|
||||
if (editingId === profile.id) {
|
||||
resetForm();
|
||||
}
|
||||
setNotice(`已删除 Profile:${profile.displayName}`);
|
||||
} catch (reason) {
|
||||
setError(`Profile deletion failed: ${errorMessage(reason)}`);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
setEditingId(null);
|
||||
setForm(emptyForm);
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="profile-manager" aria-labelledby="profile-heading">
|
||||
<div className="section-heading">
|
||||
<div>
|
||||
<p className="eyebrow">P01 · foundation</p>
|
||||
<h2 id="profile-heading">连接 Profile</h2>
|
||||
</div>
|
||||
<p>
|
||||
这里只管理非敏感连接元数据。Token、密码和 API Key 不会进入 React 或
|
||||
SQLite 普通字段。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="profile-layout">
|
||||
<form className="profile-form" onSubmit={submitProfile}>
|
||||
<h3>{editingId ? "编辑 Profile" : "新建 Profile"}</h3>
|
||||
|
||||
<label>
|
||||
<span>显示名称</span>
|
||||
<input
|
||||
name="displayName"
|
||||
required
|
||||
maxLength={80}
|
||||
value={form.displayName}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
displayName: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<span>角色</span>
|
||||
<select
|
||||
name="role"
|
||||
value={form.role}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
role: event.target.value as ProfileRole,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="general">通用</option>
|
||||
<option value="companion">陪伴</option>
|
||||
<option value="operations">运维</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<span>REST 基础 URL</span>
|
||||
<input
|
||||
name="baseUrl"
|
||||
type="url"
|
||||
required
|
||||
value={form.baseUrl}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
baseUrl: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<span>SSE URL(可选)</span>
|
||||
<input
|
||||
name="eventStreamUrl"
|
||||
type="url"
|
||||
value={form.eventStreamUrl}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
eventStreamUrl: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<span>认证类型</span>
|
||||
<select
|
||||
name="authenticationType"
|
||||
value={form.authenticationType}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
authenticationType: event.target.value as AuthenticationType,
|
||||
}))
|
||||
}
|
||||
>
|
||||
<option value="device-token">设备 Token</option>
|
||||
<option value="api-key">API Key</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label>
|
||||
<span>证书 SHA-256 指纹(可选)</span>
|
||||
<input
|
||||
name="pinnedCertificateFingerprint"
|
||||
inputMode="text"
|
||||
placeholder="64 位十六进制"
|
||||
value={form.pinnedCertificateFingerprint}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
pinnedCertificateFingerprint: event.target.value,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="checkbox-field">
|
||||
<input
|
||||
name="allowInsecureHttp"
|
||||
type="checkbox"
|
||||
checked={form.allowInsecureHttp}
|
||||
onChange={(event) =>
|
||||
setForm((current) => ({
|
||||
...current,
|
||||
allowInsecureHttp: event.target.checked,
|
||||
}))
|
||||
}
|
||||
/>
|
||||
<span>明确允许不安全 HTTP(仅限受信任网络)</span>
|
||||
</label>
|
||||
|
||||
<p className="form-note">
|
||||
槽位分配、自动连接和连接切换保护将在 P02 实现。
|
||||
</p>
|
||||
|
||||
<div className="button-row">
|
||||
<button type="submit" disabled={busy}>
|
||||
{editingId ? "更新 Profile" : "保存 Profile"}
|
||||
</button>
|
||||
{editingId ? (
|
||||
<button
|
||||
type="button"
|
||||
className="button-secondary"
|
||||
disabled={busy}
|
||||
onClick={resetForm}
|
||||
>
|
||||
取消编辑
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div className="profile-list" aria-label="已保存 Profile">
|
||||
<h3>已保存 ({profiles.length})</h3>
|
||||
{profiles.length === 0 ? (
|
||||
<p className="empty-state">尚未保存 Profile。</p>
|
||||
) : (
|
||||
profiles.map((profile) => (
|
||||
<article className="profile-card" key={profile.id}>
|
||||
<div>
|
||||
<strong>{profile.displayName}</strong>
|
||||
<span>{roleLabel(profile.role)}</span>
|
||||
</div>
|
||||
<code>{profile.baseUrl}</code>
|
||||
<p>
|
||||
{profile.authenticationType === "api-key"
|
||||
? "API Key 引用"
|
||||
: "设备 Token 引用"}
|
||||
{" · "}
|
||||
{profile.credentialReference ? "已登记" : "待登记"}
|
||||
</p>
|
||||
<div className="button-row">
|
||||
<button
|
||||
type="button"
|
||||
className="button-secondary"
|
||||
disabled={busy}
|
||||
aria-label={`编辑 ${profile.displayName}`}
|
||||
onClick={() => editProfile(profile)}
|
||||
>
|
||||
编辑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="button-danger"
|
||||
disabled={busy}
|
||||
aria-label={`删除 ${profile.displayName}`}
|
||||
onClick={() => void deleteProfile(profile)}
|
||||
>
|
||||
删除
|
||||
</button>
|
||||
</div>
|
||||
</article>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{notice ? (
|
||||
<p className="notice-banner" aria-live="polite">
|
||||
{notice}
|
||||
</p>
|
||||
) : null}
|
||||
{error ? (
|
||||
<p className="error-banner" role="alert">
|
||||
{error}
|
||||
</p>
|
||||
) : null}
|
||||
</section>
|
||||
);
|
||||
}
|
||||
|
||||
function toProfileInput(form: ProfileFormState): ConnectionProfileInput {
|
||||
const eventStreamUrl = form.eventStreamUrl.trim();
|
||||
const fingerprint = form.pinnedCertificateFingerprint.trim();
|
||||
return {
|
||||
displayName: form.displayName.trim(),
|
||||
role: form.role,
|
||||
baseUrl: form.baseUrl.trim(),
|
||||
eventStreamUrl: eventStreamUrl || undefined,
|
||||
authenticationType: form.authenticationType,
|
||||
allowInsecureHttp: form.allowInsecureHttp,
|
||||
pinnedCertificateFingerprint: fingerprint || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function sortProfiles(profiles: ConnectionProfile[]) {
|
||||
return [...profiles].sort((left, right) =>
|
||||
left.displayName.localeCompare(right.displayName, "zh-CN"),
|
||||
);
|
||||
}
|
||||
|
||||
function roleLabel(role: ProfileRole) {
|
||||
switch (role) {
|
||||
case "companion":
|
||||
return "陪伴";
|
||||
case "operations":
|
||||
return "运维";
|
||||
case "general":
|
||||
return "通用";
|
||||
}
|
||||
}
|
||||
|
||||
function errorMessage(reason: unknown) {
|
||||
if (reason instanceof Error) {
|
||||
return reason.message;
|
||||
}
|
||||
if (
|
||||
typeof reason === "object" &&
|
||||
reason !== null &&
|
||||
"message" in reason &&
|
||||
typeof reason.message === "string"
|
||||
) {
|
||||
return reason.message;
|
||||
}
|
||||
return String(reason);
|
||||
}
|
||||
190
src/styles.css
190
src/styles.css
|
|
@ -43,8 +43,13 @@ button:hover {
|
|||
background: #204b88;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.58;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
width: min(920px, calc(100% - 2rem));
|
||||
width: min(1120px, calc(100% - 2rem));
|
||||
margin: 0 auto;
|
||||
padding: 4rem 0;
|
||||
}
|
||||
|
|
@ -123,6 +128,158 @@ h1 {
|
|||
border-color: rgb(255 115 115 / 45%);
|
||||
}
|
||||
|
||||
.profile-manager {
|
||||
margin: 2rem 0;
|
||||
padding: 1.5rem;
|
||||
border: 1px solid rgb(137 175 232 / 28%);
|
||||
border-radius: 1rem;
|
||||
background: rgb(13 29 52 / 78%);
|
||||
box-shadow: 0 1rem 3rem rgb(0 0 0 / 18%);
|
||||
}
|
||||
|
||||
.section-heading {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 0.8fr) minmax(280px, 1.2fr);
|
||||
gap: 2rem;
|
||||
align-items: end;
|
||||
margin-bottom: 1.25rem;
|
||||
}
|
||||
|
||||
.section-heading h2,
|
||||
.profile-form h3,
|
||||
.profile-list h3 {
|
||||
margin: 0.3rem 0 0;
|
||||
}
|
||||
|
||||
.section-heading > p,
|
||||
.form-note,
|
||||
.empty-state,
|
||||
.profile-card p {
|
||||
color: #aebfda;
|
||||
}
|
||||
|
||||
.profile-layout {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(300px, 0.95fr) minmax(320px, 1.05fr);
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.profile-form,
|
||||
.profile-list {
|
||||
padding: 1.2rem;
|
||||
border: 1px solid rgb(137 175 232 / 24%);
|
||||
border-radius: 0.9rem;
|
||||
background: rgb(7 18 34 / 52%);
|
||||
}
|
||||
|
||||
.profile-form {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.profile-form label:not(.checkbox-field) {
|
||||
display: grid;
|
||||
gap: 0.45rem;
|
||||
}
|
||||
|
||||
.profile-form label > span {
|
||||
color: #c7d4e9;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 650;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
width: 100%;
|
||||
padding: 0.72rem 0.8rem;
|
||||
border: 1px solid rgb(137 175 232 / 38%);
|
||||
border-radius: 0.65rem;
|
||||
color: inherit;
|
||||
background: #0b1b31;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
input:focus,
|
||||
select:focus {
|
||||
outline: 2px solid #6aa3ff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.checkbox-field {
|
||||
display: flex;
|
||||
gap: 0.7rem;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.checkbox-field input {
|
||||
width: auto;
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
|
||||
.form-note {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.button-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
.button-secondary {
|
||||
border-color: rgb(157 181 218 / 48%);
|
||||
background: #20314b;
|
||||
}
|
||||
|
||||
.button-danger {
|
||||
border-color: rgb(255 122 122 / 65%);
|
||||
background: #5a2430;
|
||||
}
|
||||
|
||||
.profile-list {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.profile-card {
|
||||
display: grid;
|
||||
gap: 0.7rem;
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(137 175 232 / 22%);
|
||||
border-radius: 0.75rem;
|
||||
background: rgb(20 42 72 / 72%);
|
||||
}
|
||||
|
||||
.profile-card > div:first-child {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.profile-card span {
|
||||
color: #8db9ff;
|
||||
}
|
||||
|
||||
.profile-card code {
|
||||
color: #dbe8ff;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.profile-card p {
|
||||
margin: 0;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.notice-banner {
|
||||
padding: 1rem;
|
||||
border: 1px solid rgb(96 211 153 / 42%);
|
||||
border-radius: 0.8rem;
|
||||
color: #c8f7dc;
|
||||
background: rgb(20 83 57 / 45%);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root {
|
||||
color: #102039;
|
||||
|
|
@ -141,10 +298,17 @@ h1 {
|
|||
|
||||
.status-card,
|
||||
.boundaries,
|
||||
.profile-manager,
|
||||
.error-banner {
|
||||
background: rgb(255 255 255 / 86%);
|
||||
}
|
||||
|
||||
.profile-form,
|
||||
.profile-list,
|
||||
.profile-card {
|
||||
background: rgb(245 249 255 / 90%);
|
||||
}
|
||||
|
||||
.status-card strong {
|
||||
color: #102039;
|
||||
}
|
||||
|
|
@ -153,4 +317,28 @@ h1 {
|
|||
.subtitle {
|
||||
color: #405775;
|
||||
}
|
||||
|
||||
input,
|
||||
select {
|
||||
color: #102039;
|
||||
background: #ffffff;
|
||||
}
|
||||
|
||||
.section-heading > p,
|
||||
.form-note,
|
||||
.empty-state,
|
||||
.profile-card p {
|
||||
color: #405775;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
.section-heading,
|
||||
.profile-layout {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
padding: 2rem 0;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1 +1,8 @@
|
|||
import "@testing-library/jest-dom/vitest";
|
||||
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach } from "vitest";
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
|
|
|||
54
src/types/profile.ts
普通文件
54
src/types/profile.ts
普通文件
|
|
@ -0,0 +1,54 @@
|
|||
import { z } from "zod";
|
||||
|
||||
export const profileRoleSchema = z.enum(["companion", "operations", "general"]);
|
||||
|
||||
export const authenticationTypeSchema = z.enum(["device-token", "api-key"]);
|
||||
|
||||
const optionalIdentifier = z.string().min(1).optional();
|
||||
|
||||
export const connectionProfileSchema = z
|
||||
.object({
|
||||
id: z.uuid(),
|
||||
displayName: z.string().min(1).max(80),
|
||||
role: profileRoleSchema,
|
||||
baseUrl: z.url(),
|
||||
eventStreamUrl: z.url().optional(),
|
||||
authenticationType: authenticationTypeSchema,
|
||||
credentialReference: optionalIdentifier,
|
||||
allowInsecureHttp: z.boolean(),
|
||||
pinnedCertificateFingerprint: z
|
||||
.string()
|
||||
.regex(/^[A-F0-9]{64}$/)
|
||||
.optional(),
|
||||
autoConnectSlot: z.enum(["companion", "operations"]).optional(),
|
||||
autoConnect: z.boolean(),
|
||||
serverInstanceId: optionalIdentifier,
|
||||
serverVersion: optionalIdentifier,
|
||||
protocolVersion: optionalIdentifier,
|
||||
localToolPolicyId: optionalIdentifier,
|
||||
lastConnectedAt: optionalIdentifier,
|
||||
createdAt: z.string().min(1),
|
||||
updatedAt: z.string().min(1),
|
||||
})
|
||||
.strict();
|
||||
|
||||
export const connectionProfileListSchema = z.array(connectionProfileSchema);
|
||||
|
||||
export type ProfileRole = z.infer<typeof profileRoleSchema>;
|
||||
export type AuthenticationType = z.infer<typeof authenticationTypeSchema>;
|
||||
export type ConnectionProfile = z.infer<typeof connectionProfileSchema>;
|
||||
|
||||
export interface ConnectionProfileInput {
|
||||
displayName: string;
|
||||
role: ProfileRole;
|
||||
baseUrl: string;
|
||||
eventStreamUrl?: string;
|
||||
authenticationType: AuthenticationType;
|
||||
allowInsecureHttp: boolean;
|
||||
pinnedCertificateFingerprint?: string;
|
||||
}
|
||||
|
||||
export interface UpdateConnectionProfileRequest {
|
||||
id: string;
|
||||
profile: ConnectionProfileInput;
|
||||
}
|
||||
|
|
@ -12,5 +12,13 @@ test("renders the bootstrap shell and safe browser fallback", async ({
|
|||
await expect(
|
||||
page.getByText("IPC unavailable:", { exact: false }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByRole("button")).toBeEnabled();
|
||||
await expect(
|
||||
page.getByRole("heading", { name: "连接 Profile" }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByText("Profile storage unavailable:", { exact: false }),
|
||||
).toBeVisible();
|
||||
await expect(
|
||||
page.getByRole("button", { name: "重新检查 IPC" }),
|
||||
).toBeEnabled();
|
||||
});
|
||||
|
|
|
|||
正在加载…
添加表格
在新工单中引用