diff --git a/.agents/skills/api-and-interface-design/SKILL.md b/.agents/skills/api-and-interface-design/SKILL.md new file mode 100644 index 0000000..3e2e37f --- /dev/null +++ b/.agents/skills/api-and-interface-design/SKILL.md @@ -0,0 +1,367 @@ +--- +name: api-and-interface-design +description: Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend. +--- + +# API and Interface Design + +## Overview + +Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another. + +## When to Use + +- Designing new API endpoints +- Defining module boundaries or contracts between teams +- Creating component prop interfaces +- Establishing database schema that informs API shape +- Changing existing public interfaces + +## Core Principles + +### Hyrum's Law + +> With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract. + +This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications: + +- **Be intentional about what you expose.** Every observable behavior is a potential commitment. +- **Don't leak implementation details.** If users can observe it, they will depend on it. +- **Plan for deprecation at design time.** See `deprecation-and-migration` for how to safely remove things users depend on. +- **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior. + +### The One-Version Rule + +Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork. + +### 1. Contract First + +Define the interface before implementing it. The contract is the spec — implementation follows. + +```typescript +// Define the contract first +interface TaskAPI { + // Creates a task and returns the created task with server-generated fields + createTask(input: CreateTaskInput): Promise; + + // Returns paginated tasks matching filters + listTasks(params: ListTasksParams): Promise>; + + // Returns a single task or throws NotFoundError + getTask(id: string): Promise; + + // Partial update — only provided fields change + updateTask(id: string, input: UpdateTaskInput): Promise; + + // Idempotent delete — succeeds even if already deleted + deleteTask(id: string): Promise; +} +``` + +### 2. Consistent Error Semantics + +Pick one error strategy and use it everywhere: + +```typescript +// REST: HTTP status codes + structured error body +// Every error response follows the same shape +interface APIError { + error: { + code: string; // Machine-readable: "VALIDATION_ERROR" + message: string; // Human-readable: "Email is required" + details?: unknown; // Additional context when helpful + }; +} + +// Status code mapping +// 400 → Client sent invalid data +// 401 → Not authenticated +// 403 → Authenticated but not authorized +// 404 → Resource not found +// 409 → Conflict (duplicate, version mismatch) +// 422 → Validation failed (semantically invalid) +// 500 → Server error (never expose internal details) +``` + +**Don't mix patterns.** If some endpoints throw, others return null, and others return `{ error }` — the consumer can't predict behavior. + +### 3. Validate at Boundaries + +Trust internal code. Validate at system edges where external input enters: + +```typescript +// Validate at the API boundary +app.post('/api/tasks', async (req, res) => { + const result = CreateTaskSchema.safeParse(req.body); + if (!result.success) { + return res.status(422).json({ + error: { + code: 'VALIDATION_ERROR', + message: 'Invalid task data', + details: result.error.flatten(), + }, + }); + } + + // After validation, internal code trusts the types + const task = await taskService.create(result.data); + return res.status(201).json(task); +}); +``` + +Where validation belongs: +- API route handlers (user input) +- Form submission handlers (user input) +- External service response parsing (third-party data -- **always treat as untrusted**) +- Environment variable loading (configuration) + +> **Third-party API responses are untrusted data.** Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text. + +Where validation does NOT belong: +- Between internal functions that share type contracts +- In utility functions called by already-validated code +- On data that just came from your own database + +### 4. Prefer Addition Over Modification + +Extend interfaces without breaking existing consumers: + +```typescript +// Good: Add optional fields +interface CreateTaskInput { + title: string; + description?: string; + priority?: 'low' | 'medium' | 'high'; // Added later, optional + labels?: string[]; // Added later, optional +} + +// Bad: Change existing field types or remove fields +interface CreateTaskInput { + title: string; + // description: string; // Removed — breaks existing consumers + priority: number; // Changed from string — breaks existing consumers +} +``` + +### 5. Predictable Naming + +| Pattern | Convention | Example | +|---------|-----------|---------| +| REST endpoints | Plural nouns, no verbs | `GET /api/tasks`, `POST /api/tasks` | +| Query params | camelCase | `?sortBy=createdAt&pageSize=20` | +| Response fields | camelCase | `{ createdAt, updatedAt, taskId }` | +| Boolean fields | is/has/can prefix | `isComplete`, `hasAttachments` | +| Enum values | UPPER_SNAKE | `"IN_PROGRESS"`, `"COMPLETED"` | + +### 6. Honouring an Idempotency Key + +Accepting an `Idempotency-Key` is the contract. Honouring it is the implementation, and it is where the money is lost — a key the server accepts but handles carelessly is worse than no key at all, because the client now believes retrying is safe. + +**Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents: + +```typescript +crypto.randomUUID() // ✗ new key per attempt — every retry is a new charge +`${userId}:${amount}` // ✗ two legitimate $50 charges collapse into one +`${orderId}:${Date.now()}` // ✗ a timestamp is randomUUID() wearing a hat + +req.headers['idempotency-key'] // ✓ client generates once, reuses on retry +`charge:v1:${orderId}` // ✓ derived from an immutable identifier +``` + +The key comes from the client or the initiating event — never from the layer doing the retrying. + +**Claim atomically. A check followed by an act is a race:** + +```typescript +// ✗ TOCTOU: two concurrent retries both read "not seen", both charge +if (!(await db.exists(key))) { + await chargeCard(amount); + await db.insert(key); +} + +// ✓ let the unique constraint pick the winner +try { + await db.insert({ key, state: 'in_progress', requestHash }); +} catch (e) { + if (isUniqueViolation(e)) return replayOrReject(key); + throw e; +} +const result = await chargeCard(amount); +await db.update({ key, state: 'succeeded', response: result }); +``` + +The unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this. + +**Guard the payload.** Same key with a different body is a client bug, and must fail loudly rather than serving the first response to a second request: + +```typescript +if (existing.requestHash !== hash(req.body)) { + return res.status(422).json({ error: 'idempotency key reused with a different payload' }); +} +``` + +**Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms: + +| Strategy | Response | Use when | +|---|---|---| +| Reject | `409 Conflict` | Client can retry later; simplest and safest | +| Wait | Block for the result, bounded | Caller needs it synchronously | +| Return pending | `202` + status URL | Long-running effects | + +Never let the second caller through because the first "seems stuck". A stalled attempt whose fate is unknown is exactly when duplicating costs most. + +**Every call has three outcomes, not two: success, failure, and _unknown_.** A timeout tells you nothing about whether the effect applied. Record the intent *before* calling out, so a crash between the call and the response leaves evidence something must resolve later — rather than a silently retried charge. + +**Set retention from the longest retry chain**, not from disk cost. Keys must outlive every path that can re-deliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 24-hour key TTL behind a 7-day DLQ is a duplicate waiting to happen. + +## REST API Patterns + +### Resource Design + +``` +GET /api/tasks → List tasks (with query params for filtering) +POST /api/tasks → Create a task +GET /api/tasks/:id → Get a single task +PATCH /api/tasks/:id → Update a task (partial) +DELETE /api/tasks/:id → Delete a task + +GET /api/tasks/:id/comments → List comments for a task (sub-resource) +POST /api/tasks/:id/comments → Add a comment to a task +``` + +### Pagination + +Paginate list endpoints: + +```typescript +// Request +GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc + +// Response +{ + "data": [...], + "pagination": { + "page": 1, + "pageSize": 20, + "totalItems": 142, + "totalPages": 8 + } +} +``` + +### Filtering + +Use query parameters for filters: + +``` +GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01 +``` + +### Partial Updates (PATCH) + +Accept partial objects — only update what's provided: + +```typescript +// Only title changes, everything else preserved +PATCH /api/tasks/123 +{ "title": "Updated title" } +``` + +## TypeScript Interface Patterns + +### Use Discriminated Unions for Variants + +```typescript +// Good: Each variant is explicit +type TaskStatus = + | { type: 'pending' } + | { type: 'in_progress'; assignee: string; startedAt: Date } + | { type: 'completed'; completedAt: Date; completedBy: string } + | { type: 'cancelled'; reason: string; cancelledAt: Date }; + +// Consumer gets type narrowing +function getStatusLabel(status: TaskStatus): string { + switch (status.type) { + case 'pending': return 'Pending'; + case 'in_progress': return `In progress (${status.assignee})`; + case 'completed': return `Done on ${status.completedAt}`; + case 'cancelled': return `Cancelled: ${status.reason}`; + } +} +``` + +### Input/Output Separation + +```typescript +// Input: what the caller provides +interface CreateTaskInput { + title: string; + description?: string; +} + +// Output: what the system returns (includes server-generated fields) +interface Task { + id: string; + title: string; + description: string | null; + createdAt: Date; + updatedAt: Date; + createdBy: string; +} +``` + +### Use Branded Types for IDs + +```typescript +type TaskId = string & { readonly __brand: 'TaskId' }; +type UserId = string & { readonly __brand: 'UserId' }; + +// Prevents accidentally passing a UserId where a TaskId is expected +function getTask(id: TaskId): Promise { ... } +``` + +## Common Rationalizations + +| Rationalization | Reality | +|---|---| +| "We'll document the API later" | The types ARE the documentation. Define them first. | +| "We don't need pagination for now" | You will the moment someone has 100+ items. Add it from the start. | +| "PATCH is complicated, let's just use PUT" | PUT requires the full object every time. PATCH is what clients actually want. | +| "We'll version the API when we need to" | Breaking changes without versioning break consumers. Design for extension from the start. | +| "Nobody uses that undocumented behavior" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. | +| "We can just maintain two versions" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. | +| "Internal APIs don't need contracts" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. | +| "Accepting the Idempotency-Key header is enough" | The header is the contract; storing the key against the result is the implementation. A key you accept but don't honour tells the client retrying is safe when it isn't. | +| "Our queue guarantees exactly-once delivery" | No queue does across a consumer crash — the broker's ack and your side effect are not in one transaction. Design for at-least-once with idempotent processing. | +| "Duplicate requests are rare" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. | + +## Red Flags + +- Endpoints that return different shapes depending on conditions +- Inconsistent error formats across endpoints +- Validation scattered throughout internal code instead of at boundaries +- Breaking changes to existing fields (type changes, removals) +- List endpoints without pagination +- Verbs in REST URLs (`/api/createTask`, `/api/getUsers`) +- Third-party API responses used without validation or sanitization +- A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard +- An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt +- The same key accepted with a different request body, silently returning the first response +- A key retention window shorter than the longest path that can re-deliver the request + +## Verification + +After designing an API: + +- [ ] Every endpoint has typed input and output schemas +- [ ] Error responses follow a single consistent format +- [ ] Validation happens at system boundaries only +- [ ] List endpoints support pagination +- [ ] New fields are additive and optional (backward compatible) +- [ ] Naming follows consistent conventions across all endpoints +- [ ] API documentation or types are committed alongside the implementation +- [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry +- [ ] The key is claimed in one atomic operation, guarded by a unique constraint +- [ ] A reused key with a different payload fails loudly rather than replaying the wrong response +- [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out +- [ ] Key retention outlives the longest retry path, including dead-letter replay diff --git a/.claude/skills/api-and-interface-design/SKILL.md b/.claude/skills/api-and-interface-design/SKILL.md new file mode 100644 index 0000000..3e2e37f --- /dev/null +++ b/.claude/skills/api-and-interface-design/SKILL.md @@ -0,0 +1,367 @@ +--- +name: api-and-interface-design +description: Guides stable API and interface design. Use when designing APIs, module boundaries, or any public interface. Use when creating REST or GraphQL endpoints, defining type contracts between modules, or establishing boundaries between frontend and backend. +--- + +# API and Interface Design + +## Overview + +Design stable, well-documented interfaces that are hard to misuse. Good interfaces make the right thing easy and the wrong thing hard. This applies to REST APIs, GraphQL schemas, module boundaries, component props, and any surface where one piece of code talks to another. + +## When to Use + +- Designing new API endpoints +- Defining module boundaries or contracts between teams +- Creating component prop interfaces +- Establishing database schema that informs API shape +- Changing existing public interfaces + +## Core Principles + +### Hyrum's Law + +> With a sufficient number of users of an API, all observable behaviors of your system will be depended on by somebody, regardless of what you promise in the contract. + +This means: every public behavior — including undocumented quirks, error message text, timing, and ordering — becomes a de facto contract once users depend on it. Design implications: + +- **Be intentional about what you expose.** Every observable behavior is a potential commitment. +- **Don't leak implementation details.** If users can observe it, they will depend on it. +- **Plan for deprecation at design time.** See `deprecation-and-migration` for how to safely remove things users depend on. +- **Tests are not enough.** Even with perfect contract tests, Hyrum's Law means "safe" changes can break real users who depend on undocumented behavior. + +### The One-Version Rule + +Avoid forcing consumers to choose between multiple versions of the same dependency or API. Diamond dependency problems arise when different consumers need different versions of the same thing. Design for a world where only one version exists at a time — extend rather than fork. + +### 1. Contract First + +Define the interface before implementing it. The contract is the spec — implementation follows. + +```typescript +// Define the contract first +interface TaskAPI { + // Creates a task and returns the created task with server-generated fields + createTask(input: CreateTaskInput): Promise; + + // Returns paginated tasks matching filters + listTasks(params: ListTasksParams): Promise>; + + // Returns a single task or throws NotFoundError + getTask(id: string): Promise; + + // Partial update — only provided fields change + updateTask(id: string, input: UpdateTaskInput): Promise; + + // Idempotent delete — succeeds even if already deleted + deleteTask(id: string): Promise; +} +``` + +### 2. Consistent Error Semantics + +Pick one error strategy and use it everywhere: + +```typescript +// REST: HTTP status codes + structured error body +// Every error response follows the same shape +interface APIError { + error: { + code: string; // Machine-readable: "VALIDATION_ERROR" + message: string; // Human-readable: "Email is required" + details?: unknown; // Additional context when helpful + }; +} + +// Status code mapping +// 400 → Client sent invalid data +// 401 → Not authenticated +// 403 → Authenticated but not authorized +// 404 → Resource not found +// 409 → Conflict (duplicate, version mismatch) +// 422 → Validation failed (semantically invalid) +// 500 → Server error (never expose internal details) +``` + +**Don't mix patterns.** If some endpoints throw, others return null, and others return `{ error }` — the consumer can't predict behavior. + +### 3. Validate at Boundaries + +Trust internal code. Validate at system edges where external input enters: + +```typescript +// Validate at the API boundary +app.post('/api/tasks', async (req, res) => { + const result = CreateTaskSchema.safeParse(req.body); + if (!result.success) { + return res.status(422).json({ + error: { + code: 'VALIDATION_ERROR', + message: 'Invalid task data', + details: result.error.flatten(), + }, + }); + } + + // After validation, internal code trusts the types + const task = await taskService.create(result.data); + return res.status(201).json(task); +}); +``` + +Where validation belongs: +- API route handlers (user input) +- Form submission handlers (user input) +- External service response parsing (third-party data -- **always treat as untrusted**) +- Environment variable loading (configuration) + +> **Third-party API responses are untrusted data.** Validate their shape and content before using them in any logic, rendering, or decision-making. A compromised or misbehaving external service can return unexpected types, malicious content, or instruction-like text. + +Where validation does NOT belong: +- Between internal functions that share type contracts +- In utility functions called by already-validated code +- On data that just came from your own database + +### 4. Prefer Addition Over Modification + +Extend interfaces without breaking existing consumers: + +```typescript +// Good: Add optional fields +interface CreateTaskInput { + title: string; + description?: string; + priority?: 'low' | 'medium' | 'high'; // Added later, optional + labels?: string[]; // Added later, optional +} + +// Bad: Change existing field types or remove fields +interface CreateTaskInput { + title: string; + // description: string; // Removed — breaks existing consumers + priority: number; // Changed from string — breaks existing consumers +} +``` + +### 5. Predictable Naming + +| Pattern | Convention | Example | +|---------|-----------|---------| +| REST endpoints | Plural nouns, no verbs | `GET /api/tasks`, `POST /api/tasks` | +| Query params | camelCase | `?sortBy=createdAt&pageSize=20` | +| Response fields | camelCase | `{ createdAt, updatedAt, taskId }` | +| Boolean fields | is/has/can prefix | `isComplete`, `hasAttachments` | +| Enum values | UPPER_SNAKE | `"IN_PROGRESS"`, `"COMPLETED"` | + +### 6. Honouring an Idempotency Key + +Accepting an `Idempotency-Key` is the contract. Honouring it is the implementation, and it is where the money is lost — a key the server accepts but handles carelessly is worse than no key at all, because the client now believes retrying is safe. + +**Derive the key from the intent, not the attempt.** The key must be stable across retries of one intent and different across distinct intents: + +```typescript +crypto.randomUUID() // ✗ new key per attempt — every retry is a new charge +`${userId}:${amount}` // ✗ two legitimate $50 charges collapse into one +`${orderId}:${Date.now()}` // ✗ a timestamp is randomUUID() wearing a hat + +req.headers['idempotency-key'] // ✓ client generates once, reuses on retry +`charge:v1:${orderId}` // ✓ derived from an immutable identifier +``` + +The key comes from the client or the initiating event — never from the layer doing the retrying. + +**Claim atomically. A check followed by an act is a race:** + +```typescript +// ✗ TOCTOU: two concurrent retries both read "not seen", both charge +if (!(await db.exists(key))) { + await chargeCard(amount); + await db.insert(key); +} + +// ✓ let the unique constraint pick the winner +try { + await db.insert({ key, state: 'in_progress', requestHash }); +} catch (e) { + if (isUniqueViolation(e)) return replayOrReject(key); + throw e; +} +const result = await chargeCard(amount); +await db.update({ key, state: 'succeeded', response: result }); +``` + +The unique constraint *is* the mechanism. A store that cannot enforce uniqueness in one operation cannot back this. + +**Guard the payload.** Same key with a different body is a client bug, and must fail loudly rather than serving the first response to a second request: + +```typescript +if (existing.requestHash !== hash(req.body)) { + return res.status(422).json({ error: 'idempotency key reused with a different payload' }); +} +``` + +**Decide what an in-flight duplicate gets.** The first request is still running when the second arrives — the common case under retry storms: + +| Strategy | Response | Use when | +|---|---|---| +| Reject | `409 Conflict` | Client can retry later; simplest and safest | +| Wait | Block for the result, bounded | Caller needs it synchronously | +| Return pending | `202` + status URL | Long-running effects | + +Never let the second caller through because the first "seems stuck". A stalled attempt whose fate is unknown is exactly when duplicating costs most. + +**Every call has three outcomes, not two: success, failure, and _unknown_.** A timeout tells you nothing about whether the effect applied. Record the intent *before* calling out, so a crash between the call and the response leaves evidence something must resolve later — rather than a silently retried charge. + +**Set retention from the longest retry chain**, not from disk cost. Keys must outlive every path that can re-deliver the same intent, including a dead-letter queue replayed a week later and any provider dispute window. A 24-hour key TTL behind a 7-day DLQ is a duplicate waiting to happen. + +## REST API Patterns + +### Resource Design + +``` +GET /api/tasks → List tasks (with query params for filtering) +POST /api/tasks → Create a task +GET /api/tasks/:id → Get a single task +PATCH /api/tasks/:id → Update a task (partial) +DELETE /api/tasks/:id → Delete a task + +GET /api/tasks/:id/comments → List comments for a task (sub-resource) +POST /api/tasks/:id/comments → Add a comment to a task +``` + +### Pagination + +Paginate list endpoints: + +```typescript +// Request +GET /api/tasks?page=1&pageSize=20&sortBy=createdAt&sortOrder=desc + +// Response +{ + "data": [...], + "pagination": { + "page": 1, + "pageSize": 20, + "totalItems": 142, + "totalPages": 8 + } +} +``` + +### Filtering + +Use query parameters for filters: + +``` +GET /api/tasks?status=in_progress&assignee=user123&createdAfter=2025-01-01 +``` + +### Partial Updates (PATCH) + +Accept partial objects — only update what's provided: + +```typescript +// Only title changes, everything else preserved +PATCH /api/tasks/123 +{ "title": "Updated title" } +``` + +## TypeScript Interface Patterns + +### Use Discriminated Unions for Variants + +```typescript +// Good: Each variant is explicit +type TaskStatus = + | { type: 'pending' } + | { type: 'in_progress'; assignee: string; startedAt: Date } + | { type: 'completed'; completedAt: Date; completedBy: string } + | { type: 'cancelled'; reason: string; cancelledAt: Date }; + +// Consumer gets type narrowing +function getStatusLabel(status: TaskStatus): string { + switch (status.type) { + case 'pending': return 'Pending'; + case 'in_progress': return `In progress (${status.assignee})`; + case 'completed': return `Done on ${status.completedAt}`; + case 'cancelled': return `Cancelled: ${status.reason}`; + } +} +``` + +### Input/Output Separation + +```typescript +// Input: what the caller provides +interface CreateTaskInput { + title: string; + description?: string; +} + +// Output: what the system returns (includes server-generated fields) +interface Task { + id: string; + title: string; + description: string | null; + createdAt: Date; + updatedAt: Date; + createdBy: string; +} +``` + +### Use Branded Types for IDs + +```typescript +type TaskId = string & { readonly __brand: 'TaskId' }; +type UserId = string & { readonly __brand: 'UserId' }; + +// Prevents accidentally passing a UserId where a TaskId is expected +function getTask(id: TaskId): Promise { ... } +``` + +## Common Rationalizations + +| Rationalization | Reality | +|---|---| +| "We'll document the API later" | The types ARE the documentation. Define them first. | +| "We don't need pagination for now" | You will the moment someone has 100+ items. Add it from the start. | +| "PATCH is complicated, let's just use PUT" | PUT requires the full object every time. PATCH is what clients actually want. | +| "We'll version the API when we need to" | Breaking changes without versioning break consumers. Design for extension from the start. | +| "Nobody uses that undocumented behavior" | Hyrum's Law: if it's observable, somebody depends on it. Treat every public behavior as a commitment. | +| "We can just maintain two versions" | Multiple versions multiply maintenance cost and create diamond dependency problems. Prefer the One-Version Rule. | +| "Internal APIs don't need contracts" | Internal consumers are still consumers. Contracts prevent coupling and enable parallel work. | +| "Accepting the Idempotency-Key header is enough" | The header is the contract; storing the key against the result is the implementation. A key you accept but don't honour tells the client retrying is safe when it isn't. | +| "Our queue guarantees exactly-once delivery" | No queue does across a consumer crash — the broker's ack and your side effect are not in one transaction. Design for at-least-once with idempotent processing. | +| "Duplicate requests are rare" | They're *correlated*. Retries spike exactly when a dependency is degraded — the moment duplicates are most likely and most expensive. | + +## Red Flags + +- Endpoints that return different shapes depending on conditions +- Inconsistent error formats across endpoints +- Validation scattered throughout internal code instead of at boundaries +- Breaking changes to existing fields (type changes, removals) +- List endpoints without pagination +- Verbs in REST URLs (`/api/createTask`, `/api/getUsers`) +- Third-party API responses used without validation or sanitization +- A `SELECT` for an idempotency key followed by an `INSERT` — that's a race, not a guard +- An idempotency key derived from a UUID, timestamp, or anything else regenerated per attempt +- The same key accepted with a different request body, silently returning the first response +- A key retention window shorter than the longest path that can re-deliver the request + +## Verification + +After designing an API: + +- [ ] Every endpoint has typed input and output schemas +- [ ] Error responses follow a single consistent format +- [ ] Validation happens at system boundaries only +- [ ] List endpoints support pagination +- [ ] New fields are additive and optional (backward compatible) +- [ ] Naming follows consistent conventions across all endpoints +- [ ] API documentation or types are committed alongside the implementation +- [ ] State-changing endpoints either honour an idempotency key or are documented as unsafe to retry +- [ ] The key is claimed in one atomic operation, guarded by a unique constraint +- [ ] A reused key with a different payload fails loudly rather than replaying the wrong response +- [ ] The in-flight-duplicate response is a deliberate choice (409, wait, or 202) rather than whatever falls out +- [ ] Key retention outlives the longest retry path, including dead-letter replay diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..f20aa36 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,16 @@ +.git +.github +.codegraph +.agents +.claude +.atl +odd +target +release +**/node_modules +**/dist +**/.env +.env +apps/desktop +**/*.log +apps/api/src/generated diff --git a/.env.example b/.env.example index 5099357..8a2eea6 100644 --- a/.env.example +++ b/.env.example @@ -1,12 +1,20 @@ -# Variables de `docker compose up -d --build`. Copiar a `.env` (ignorado por git). -# Todas las no comentadas son OBLIGATORIAS: si falta alguna, el server no arranca -# (`docker compose logs server` dice cuál). +# ============================================================================== +# Variables de entorno de OpenCollab (Docker, Servidor/API, Web y Desktop) +# ============================================================================== +# Copiar a `.env` (archivo ignorado por git). +# +# Para `docker compose up -d --build`, todas las variables no comentadas son +# OBLIGATORIAS. Si falta alguna, el contenedor de la API no arranca +# (`docker compose logs api` indicará cuál falta). +# ============================================================================== -# Mínimo 32 caracteres. Generar con: +# --- Autenticación y Seguridad (API / Relay) --- +# Secreto para firmar tokens JWT (mínimo 32 caracteres). Generar por ejemplo con: # openssl rand -base64 48 JWT_SECRET= -# OAuth de GitHub y Google. Callback a registrar en cada proveedor: +# --- Proveedores OAuth (API / Relay) --- +# Credenciales OAuth de GitHub y Google. Callbacks a registrar en cada proveedor: # /auth/oauth/github/callback # /auth/oauth/google/callback GITHUB_CLIENT_ID= @@ -14,7 +22,38 @@ GITHUB_CLIENT_SECRET= GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= -# Origen público de la web y base de los callbacks de OAuth. Deben coincidir con -# la URL desde donde se abre la web. -#WEB_ORIGIN=http://localhost:8080 -#PUBLIC_BASE_URL=http://localhost:8080 +# --- URLs de Web, API y Desktop --- +# Origen de la aplicación web: +# - En Docker (Nginx): http://localhost:8080 +# - En desarrollo local con Vite: http://localhost:1421 +# La API lo usa para redirigir tras el login web, y el Desktop lo usa para abrir el navegador en Sign In. +WEB_ORIGIN=http://localhost:8080 + +# URL pública de la API donde se reciben los callbacks de OAuth: +# - En Docker (Nginx proxea /auth): http://localhost:8080 +# - En desarrollo local sin proxy: http://127.0.0.1:8787 +PUBLIC_BASE_URL=http://localhost:8080 + +# (Opcional) Sobrescribe el origen de la web EXCLUSIVAMENTE para la app de Desktop. +# Si no está definida, el Desktop usa WEB_ORIGIN o por defecto http://localhost:1421. +#OPENCOLLAB_WEB_ORIGIN=http://localhost:8080 + +# Dirección donde escucha el servidor Relay (API) y donde conecta el Desktop. +# - Por defecto en desarrollo local: 127.0.0.1:8787 +# - En Docker Compose se configura en 0.0.0.0:8787 y se publica en 127.0.0.1:8787. +#RELAY_ADDR=127.0.0.1:8787 + +# (Opcional) Dirección del relay para el proxy de desarrollo de `apps/web` (Vite). +# Por defecto: http://127.0.0.1:8787 +#OPENCOLLAB_API=http://127.0.0.1:8787 + +# --- Base de Datos PostgreSQL --- +# En Docker Compose se configura automáticamente apuntando al servicio `postgres`. +# Si corres la API standalone fuera de Docker, descomentar y configurar: +#DATABASE_URL=postgresql://opencollab:opencollab@127.0.0.1:5432/opencollab + +# --- Reverse Proxy --- +# Configuración `trust proxy` de Express (opcional): +# - En Docker (detrás de Nginx): 1 +# - En desarrollo directo: false +#TRUST_PROXY=1 diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d1c416c..991722d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,32 +22,32 @@ jobs: frontend: name: Frontend · unit + E2E runs-on: windows-latest - defaults: - run: - working-directory: apps/desktop steps: - uses: actions/checkout@v7 - uses: pnpm/action-setup@v6 with: - package_json_file: apps/desktop/package.json + package_json_file: package.json - uses: actions/setup-node@v7 with: node-version: 24 cache: pnpm - cache-dependency-path: apps/desktop/pnpm-lock.yaml + cache-dependency-path: pnpm-lock.yaml - - run: pnpm install --frozen-lockfile + - run: pnpm install --frozen-lockfile --filter @opencollab/desktop... + + - name: Build dependencias de workspace + run: pnpm --filter @opencollab/desktop^... build - name: Tests unitarios (Vitest) - run: pnpm test + run: pnpm --filter @opencollab/desktop test - name: Typecheck + build - run: pnpm build + run: pnpm --filter @opencollab/desktop build - name: Tests E2E de la interfaz (Chrome headless, núcleo simulado) - run: pnpm test:e2e + run: pnpm --filter @opencollab/desktop test:e2e # El crate de la app desktop embebe dist/ al compilar: el job de Rust lo necesita. - uses: actions/upload-artifact@v7 @@ -61,9 +61,6 @@ jobs: # Linux: GitHub service containers (Postgres) do not run on Windows # runners, and the server is not Windows-bound. runs-on: ubuntu-latest - defaults: - run: - working-directory: apps/server env: DATABASE_URL: postgresql://opencollab:opencollab@localhost:5432/opencollab services: @@ -85,60 +82,57 @@ jobs: - uses: pnpm/action-setup@v6 with: - package_json_file: apps/server/package.json + package_json_file: package.json - uses: actions/setup-node@v7 with: node-version: 24 cache: pnpm - cache-dependency-path: apps/server/pnpm-lock.yaml + cache-dependency-path: pnpm-lock.yaml - - run: pnpm install --frozen-lockfile + - run: pnpm install --frozen-lockfile --filter @opencollab/server... - - name: Prisma client - run: pnpm db:generate + - name: Build dependencias de workspace + run: pnpm --filter @opencollab/server^... build - name: Migraciones - run: pnpm db:deploy + run: pnpm --filter @opencollab/server db:deploy - name: Tests unitarios (Vitest) - run: pnpm test + run: pnpm --filter @opencollab/server test - name: Tests de integración (Postgres) - run: pnpm test:integration + run: pnpm --filter @opencollab/server test:integration - name: Typecheck - run: pnpm typecheck + run: pnpm --filter @opencollab/server typecheck - name: Build - run: pnpm build + run: pnpm --filter @opencollab/server build web: name: Web · unit + build - runs-on: windows-latest - defaults: - run: - working-directory: apps/web + runs-on: ubuntu-latest steps: - uses: actions/checkout@v7 - uses: pnpm/action-setup@v6 with: - package_json_file: apps/web/package.json + package_json_file: package.json - uses: actions/setup-node@v7 with: node-version: 24 cache: pnpm - cache-dependency-path: apps/web/pnpm-lock.yaml + cache-dependency-path: pnpm-lock.yaml - - run: pnpm install --frozen-lockfile + - run: pnpm install --frozen-lockfile --filter @opencollab/web... - name: Tests unitarios (Vitest) - run: pnpm test + run: pnpm --filter @opencollab/web test - name: Typecheck + build - run: pnpm build + run: pnpm --filter @opencollab/web build rust: name: Rust · fmt, clippy, unit + E2E @@ -175,6 +169,9 @@ jobs: - name: Tests E2E (PTY real + shell integration) run: cargo test -p infrastructure --test shell_integration_e2e -- --ignored --test-threads=1 - - name: Versión consistente + - name: Versión consistente (desktop, server y web) shell: pwsh - run: ./scripts/check-version.ps1 + run: | + ./scripts/check-version.ps1 -Package desktop + ./scripts/check-version.ps1 -Package server + ./scripts/check-version.ps1 -Package web diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 84b4b62..f70f056 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,19 +1,21 @@ -# Release: al pushear un tag vX.Y.Z (sobre main, ver Git Flow en AGENTS.md). +# Release del desktop: al pushear un tag desktop-vX.Y.Z (sobre main, ver Git Flow en AGENTS.md). # 1. Corre todo el CI (unit + E2E). Si falla, no se construye nada. -# 2. Verifica que el tag coincida con la versión de la app. +# 2. Verifica que el tag coincida con la versión del desktop. # 3. Construye los instaladores de Windows con Tauri. -# 4. Los renombra a _., calcula sus SHA-256 y publica la +# 4. Los renombra a opencollab--., calcula sus SHA-256 y publica la # release de GitHub con los archivos, los .sha256 y SHA256SUMS.txt. name: Release on: push: - tags: ["v*.*.*"] + tags: ["desktop-v*.*.*"] permissions: contents: write jobs: + # Los tags server-vX.Y.Z y web-vX.Y.Z no disparan este workflow: el patrón + # desktop-v*.*.* exige el prefijo "desktop-". Solo el desktop publica releases. # Primero lo barato: un tag mal puesto falla en segundos, sin correr el CI. version: name: Versión del tag = versión de la app @@ -24,7 +26,7 @@ jobs: - uses: actions/checkout@v7 - id: check shell: pwsh - run: ./scripts/check-version.ps1 -Tag "${{ github.ref_name }}" + run: ./scripts/check-version.ps1 -Package desktop -Tag "${{ github.ref_name }}" ci: needs: version @@ -41,25 +43,26 @@ jobs: - uses: pnpm/action-setup@v6 with: - package_json_file: apps/desktop/package.json + package_json_file: package.json - uses: actions/setup-node@v7 with: node-version: 24 cache: pnpm - cache-dependency-path: apps/desktop/pnpm-lock.yaml + cache-dependency-path: pnpm-lock.yaml - uses: dtolnay/rust-toolchain@stable - uses: Swatinem/rust-cache@v2 - name: Instalar dependencias del frontend - working-directory: apps/desktop - run: pnpm install --frozen-lockfile + run: pnpm install --frozen-lockfile --filter @opencollab/desktop... + + - name: Build dependencias de workspace + run: pnpm --filter @opencollab/desktop^... build - name: Build de Tauri (NSIS + MSI) - working-directory: apps/desktop - run: pnpm tauri build + run: pnpm --filter @opencollab/desktop tauri build - name: Renombrar y calcular hashes shell: pwsh @@ -67,18 +70,18 @@ jobs: - uses: actions/upload-artifact@v7 with: - name: windows_${{ env.VERSION }} + name: opencollab-windows-${{ env.VERSION }} path: release/ - name: Publicar release uses: softprops/action-gh-release@v3 with: - name: OpenCollab ${{ github.ref_name }} + name: OpenCollab v${{ env.VERSION }} body_path: release/release-notes.md - # Versiones con sufijo (v1.0.0-beta.1) salen como pre-release. - prerelease: ${{ contains(github.ref_name, '-') }} + # Versiones con sufijo (desktop-v1.0.0-beta.1) salen como pre-release. + prerelease: ${{ contains(env.VERSION, '-') }} files: | - release/windows_*.exe - release/windows_*.msi + release/opencollab-windows-*.exe + release/opencollab-windows-*.msi release/*.sha256 release/SHA256SUMS.txt diff --git a/.gitignore b/.gitignore index 1485bff..cb09684 100644 --- a/.gitignore +++ b/.gitignore @@ -31,5 +31,5 @@ Thumbs.db /.env # Server: local env and generated Prisma client -apps/server/.env -apps/server/src/generated/ +apps/api/.env +apps/api/src/generated/ diff --git a/.husky/pre-push b/.husky/pre-push new file mode 100644 index 0000000..d669437 --- /dev/null +++ b/.husky/pre-push @@ -0,0 +1 @@ +pnpm pre-push diff --git a/AGENTS.md b/AGENTS.md index 4f61b0b..6df803b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,190 +1,106 @@ -# AGENTS.md +# Agent guidance for OpenCollab -This file provides guidance to AI coding agents (Claude Code, OpenCode, Codex, etc.) when working with code in this repository. +Guidance for AI coding agents working on OpenCollab. -## Estado del proyecto +## Product overview -Scaffolding inicial. Implementado: modelo de dominio completo con permisos y tests, casos de uso de lanzar / escribir / redimensionar / cerrar terminal y cambiar permisos, adaptador PTY real, y app desktop con la UI de referencia (shells locales reales), con agentes que se lanzan como perfil desde el menú `+` (corren dentro de la shell) y estado de agente como `AgentEvent`s. Login del desktop vía la web (PKCE + deep link). Pendiente: cliente WebSocket (`CollabTransport` real), lógica del server (hoy `/ws` en NestJS autentica el upgrade con el access JWT, enruta por sesión con `join_session` y filtra por el permiso vigente), persistencia, comandos del núcleo para workspaces/sesiones, UI de permisos e invitaciones, y los adaptadores ricos por agente (Claude Code, OpenCode: hoy solo rige el genérico). La sesión del desktop es por ahora una sesión local fija creada en `apps/desktop/src-tauri/src/state.rs`. +OpenCollab is a desktop application that centralizes terminal-based AI agents (Claude Code, OpenCode, Codex, Gemini CLI) in a flexible grid for parallel monitoring and real-time collaboration. -## Producto +- **Workspace:** top-level project container grouping sessions. Persisted locally in appdata or on the server depending on the desktop storage mode (`local` vs `cloud`). +- **Session:** live shared unit displaying multiple terminal panes in a grid. +- **Terminal:** single PTY process running an agent profile or shell. +- **Storage modes (desktop):** + - *Local (`appdata`):* workspaces, sessions, and terminal launch profiles (`workspaces.json`) are stored locally on disk via `FsSnapshotStore`. Collaboration controls remain visible in the UI with an inactive state (`data-collab-inactive="true"`), and relay polling is short-circuited. + - *Cloud (`API`):* workspaces, sessions, and terminal launch profiles synchronize with the authenticated NestJS REST API (`CloudSnapshotStore`). Chosen during first-run Onboarding or switched later in Settings (`storage.json`). Switching from Local to Cloud migrates existing local workspaces to the cloud account one workspace at a time while preserving local files on disk. +- **Collaboration model:** + - *Workspace member:* persistent team access across workspace sessions. View access enabled by default. + - *Session guest:* temporary, session-scoped access. +- **Access control:** ordered level `AccessLevel { None < View < Write }`. Disabling View revokes all access; Write implies View. Enforced on the server and verified fail-closed on the host machine. Permissions update dynamically during active sessions. -OpenCollab es una app desktop que centraliza agentes de IA de terminal (Claude Code, OpenCode, Codex, Gemini CLI o cualquier CLI). Permite abrir múltiples terminales dispuestas en una grilla para ver en paralelo qué hace cada agente. +## Architecture and package boundaries -El diferencial es la **colaboración en tiempo real**: un usuario puede sumar compañeros a un workspace o a una sesión puntual y todos ven sus terminales en vivo. - -### Modelo de dominio: Workspace → Session → Terminal - -- **Workspace:** contenedor de organización (por ejemplo, un proyecto). Tiene un dueño y agrupa sesiones. -- **Session:** grupo de **varias terminales** que se ven juntas en una grilla. Es la unidad que se comparte en vivo. -- **Terminal:** un PTY dentro de una sesión, que ejecuta un `AgentProfile` o una shell. - -### Dos formas de colaborar: miembro del workspace vs. invitado de sesión - -| | **Miembro del workspace** | **Invitado de sesión** | -|---|---|---| -| Para qué | Equipo estable del proyecto | Colaboración puntual | -| Duración | Permanente, hasta que el dueño lo quite | Temporal: vale solo para esa sesión | -| Alcance | Las sesiones del workspace | Únicamente la sesión a la que fue invitado; no ve el resto del workspace | -| Se invita desde | El workspace | La sesión | - -Son conceptos distintos en el dominio (no modelar al invitado como un miembro con fecha de vencimiento, ni al miembro como invitado de todas las sesiones). Un miembro del workspace no necesita ser re-invitado a cada sesión nueva. - -**Permiso base "Ver":** - -- Al crearse una sesión, cada miembro del workspace tiene **Ver activo por defecto**. El dueño puede desactivarlo para un miembro en una sesión concreta. -- **Ver es el permiso mínimo para compartir:** un participante sin Ver no tiene acceso a la sesión (no recibe streams ni la ve listada). Cualquier permiso superior (por ejemplo, Escribir) requiere Ver; desactivar Ver quita también los superiores, y activar Escribir activa Ver. -- Se modela como un único nivel ordenado `AccessLevel { None < View < Write }` (`crates/domain/src/permission.rs`), no como flags independientes: así "Escribir sin Ver" es irrepresentable. `Session` resuelve el permiso efectivo de cada usuario (override de la sesión o `View` por defecto para miembros) y expone `can_view` / `can_write` como única fuente de verdad. -- Este invariante vive en `domain` (no en la UI ni en el relay) y debe estar cubierto por tests: un miembro nuevo arranca con Ver activo, no existe un estado con Escribir sin Ver, y quitar Ver revoca el acceso. -- La UI debe mostrar explícitamente que Ver viene activo por defecto y que es el mínimo para que la sesión esté compartida con esa persona (por ejemplo, el toggle de Ver marcado de entrada y un texto que lo indique al desactivarlo). - -**Permisos en vivo:** los permisos (ver / escribir) de cualquier participante de una sesión, sea miembro o invitado, se pueden **modificar en cualquier momento mientras la sesión está activa**, y el cambio aplica en caliente a quien ya está conectado (quitarle la escritura corta su input de inmediato; revocar el acceso lo desconecta). No asumir que los permisos se fijan al unirse ni cachearlos por conexión: cada input entrante se valida contra el permiso vigente. - -Evitar nombrar "sesión" a otra cosa (por ejemplo, la sesión de login o el PTY) para no confundir el concepto central. - -Los agentes son **agnósticos**: el sistema no debe tener lógica específica de un agente en el dominio. Un agente es un perfil (comando, args, env, cwd) que se lanza dentro de un PTY. - -## Stack - -- **Desktop:** Tauri 2, backend en Rust (PTYs con `portable-pty`). -- **Frontend:** React + TypeScript, terminales con `xterm.js`. -- **Colaboración:** servidor relay en NestJS sobre WebSockets (autenticación, sesiones compartidas, invitaciones y retransmisión de streams de PTY). -- **Web:** Vite + React + TypeScript (`apps/web`), puerta de autenticación del navegador; mismo toolchain que el desktop. -- **Monorepo:** Cargo workspace para el core Rust del desktop + paquetes pnpm para el server Nest y los frontends; desktop y server comparten el wire como contrato versionado, no como código. - -## Arquitectura (Clean Architecture) - -Regla de dependencias: las dependencias apuntan siempre hacia adentro. `domain` no depende de nada; `application` solo de `domain`; la infraestructura y los adaptadores implementan los puertos definidos en `application`. - -Estructura: +Clean architecture with inward-pointing dependencies: ``` -crates/ - domain/ # Entidades y reglas puras: Workspace, Session, Terminal, WorkspaceMember, SessionGuest, Invitation, AgentProfile. Sin I/O, sin Tauri, sin tokio. - application/ # Casos de uso + puertos (traits): PtyPort, WorkspaceRepository, CollabTransport, etc. - protocol/ # Mensajes del wire (serde) compartidos entre desktop y relay. Versionados. - infrastructure/ # Adaptadores concretos: portable-pty, persistencia, cliente WebSocket. apps/ desktop/ - src-tauri/ # Composition root de la app: wiring de dependencias + comandos/eventos Tauri (adaptadores de entrada delgados). - src/ # Frontend React: grilla de terminales, xterm.js, UI de workspaces. - server/ # Servidor NestJS: auth, sesiones compartidas, invitaciones y fan-out WebSocket (paridad de wire con protocol/). - web/ # Web React: login, registro, cuenta y entrega de sesión al desktop. Habla solo con /auth del server (mismo origen). + core/ # Rust desktop domain, use cases, wire protocol, and PTY/OS adapters + src-tauri/ # Tauri 2 commands, state wiring, and event bridges + src/ # React 19 frontend (terminal grid, xterm.js, workspaces) + api/ # NestJS 11 relay (auth, sessions, Prisma 7 + PostgreSQL, WebSockets) + web/ # Vite 8 + React 19 auth portal (/login, /register, desktop handoff) +packages/ + domain/ # @opencollab/domain: pure TypeScript collaborative business logic + contracts/ # @opencollab/contracts: canonical wire contract (Zod schemas, parity with Rust) + ui/ # @opencollab/ui: presentational components (Panel, Sidebar, StatusBar, TopBar) + config/ # Shared TypeScript and tooling configs ``` -Principios clave: - -- Los comandos Tauri solo traducen entrada/salida y delegan en casos de uso; no contienen lógica de negocio. Los handlers del server Nest traducen el wire y obedecen las reglas del dominio (definidas en Rust). -- El frontend no conoce detalles de PTY ni del relay: habla con el backend vía comandos/eventos Tauri. -- Todo lo que cruza la red se define en `protocol`; desktop y server nunca serializan tipos de dominio directamente. - -### Flujos principales - -- **Terminal local:** caso de uso lanza un `AgentProfile` vía `PtyPort` → la salida del PTY se emite como evento Tauri → el frontend la escribe en la instancia de xterm.js correspondiente. El input del usuario sigue el camino inverso. -- **Sesión compartida:** el host, además de emitir localmente, envía el stream de cada terminal de la sesión al relay vía `CollabTransport`; el relay lo retransmite solo a los miembros de esa sesión. Los permisos (quién puede ver / escribir en una terminal) se deciden en `application`, no en el transporte. -- **Cambio de permisos en vivo:** el dueño modifica el permiso de un miembro → caso de uso en `application` actualiza la sesión → se propaga por `protocol` al relay y a los clientes conectados (para que la UI refleje el nuevo estado) → desde ese momento el input del miembro se acepta o rechaza según el permiso nuevo. La validación final ocurre en la máquina del host antes de escribir en el PTY; el relay también filtra, pero no es la única barrera. - -## Flujo de ramas: Git Flow - -El repo se maneja con **Git Flow**: - -- `main`: solo código liberado. Cada merge a `main` es una versión y se etiqueta (`vX.Y.Z`). Nunca se commitea directo. -- `develop`: rama de integración; de acá salen y acá vuelven las features. -- `feature/`: sale de `develop`, vuelve a `develop`. Una por funcionalidad (p. ej. `feature/relay-websocket`). -- `release/`: sale de `develop` para preparar una versión (solo ajustes, versión y fixes); se mergea a `main` (con tag) **y** de vuelta a `develop`. -- `hotfix/`: sale de `main` para un arreglo urgente; se mergea a `main` (con tag) **y** a `develop`. - -No trabajar ni commitear directo en `main` ni en `develop`: antes de cambiar código, crear o usar la rama `feature/*` (o `hotfix/*`) que corresponda. - -Remoto: `origin` → https://github.com/facyndev/opencollab (licencia MIT). - -## Versionado +### Package roles and import rules -**Versionado semántico** (`MAJOR.MINOR.PATCH`), con tag `vX.Y.Z` en `main` por cada versión liberada. +- **`@opencollab/domain`:** single authority for collaborative rules (workspaces, sessions, permissions). Zero external runtime dependencies. +- **`@opencollab/contracts`:** wire protocol schemas and DTOs with byte parity to `apps/desktop/core/protocol`. +- **`@opencollab/ui`:** pure presentational components and styles. Zero business logic and zero `@tauri-apps/api` imports. +- **`apps/web`:** isolated authentication client. Does not import `@opencollab/ui` or desktop modules. +- **Import convention:** applications (`apps/*`) must consume shared packages strictly via `@opencollab/*` from their built `dist/` outputs. Relative cross-package file imports are prohibited. -- `PATCH`: arreglos sin cambios de comportamiento visibles (lo típico de un `hotfix/*`). -- `MINOR`: funcionalidades nuevas compatibles. -- `MAJOR`: cambios incompatibles. Mientras estemos en `0.y.z` (antes de la 1.0), un cambio incompatible sube `MINOR`. +## Tooling and workflow -La versión de la app vive en **tres lugares que tienen que coincidir** (hoy `0.1.0`): +- **Transitive builds:** build internal dependencies automatically with `pnpm --filter ^... build`. +- **Task runner:** Turborepo handles task orchestration (`turbo.json`). +- **Prisma:** schema located at `apps/api/prisma/schema.prisma`. Running `pnpm install` automatically triggers `postinstall: prisma generate`. +- **Development commands:** run `pnpm dev` from the root to start all apps in parallel (`api`, `web`, `desktop`), or run an individual app via `pnpm desktop:dev`, `pnpm api:dev`, or `pnpm web:dev` (every `apps/*` package also exposes `pnpm dev` locally). Desktop development uses `tauri.dev.conf.json` with identifier `com.opencollab.desktop.dev` and deep-link scheme `opencollab-dev://` registered at runtime to run alongside production instances without WebView2 lock or auth redirect contention. -- `Cargo.toml` raíz → `[workspace.package] version` (todos los crates la heredan con `version.workspace = true`). -- `apps/desktop/package.json` → `version`. -- `apps/desktop/src-tauri/tauri.conf.json` → `version` (es la que muestra el instalador). +### Verification commands -La versión se sube **solo** en la rama `release/*` o `hotfix/*`, como un commit propio, nunca dentro de una feature. El tag se crea sobre el merge a `main`. +- **TypeScript tests:** `pnpm -r test` +- **Typecheck:** `pnpm -r typecheck` +- **Build all:** `pnpm -r build` +- **Rust tests:** `cargo test --workspace` +- **Rust linting:** `cargo clippy --workspace --all-targets -- -D warnings` +- **Rust formatting:** `cargo fmt --all --check` +- **Package versions:** `pwsh ./scripts/check-version.ps1 -Package desktop` (or `server`, `web`) -`pwsh scripts/check-version.ps1` verifica que las tres coincidan (y con `-Tag vX.Y.Z`, que coincidan con el tag); el CI lo corre en cada push. +### Git flow and versioning -## CI/CD (GitHub Actions) +- **Branches:** `main` (production releases), `develop` (integration), `feature/*`, `release/*`, `hotfix/*`. +- **Package versioning:** independent semantic versions: + - `desktop`: tracked in root `Cargo.toml`, `apps/desktop/package.json`, and `tauri.conf.json`. Tag: `desktop-vX.Y.Z`. + - `server`: tracked in `apps/api/package.json`. Tag: `server-vX.Y.Z`. + - `web`: tracked in `apps/web/package.json`. Tag: `web-vX.Y.Z`. + - Wire protocol: `PROTOCOL_VERSION` in `protocol` and `@opencollab/contracts`. -- **`.github/workflows/ci.yml`**: en cada push a las ramas de Git Flow y en cada PR, sobre `windows-latest`. Job `frontend`: Vitest → `pnpm build` (typecheck + Vite) → E2E de la interfaz. Job `rust` (usa el `dist/` del anterior, porque la app desktop lo embebe al compilar): `fmt --check` → clippy → `cargo test --workspace` → E2E de PTY real (`shell_integration_e2e`) → consistencia de versión. Job `server`: Vitest + typecheck + build del relay Nest. -- **`.github/workflows/release.yml`**: al pushear un tag `vX.Y.Z` (sobre `main`). Verifica tag = versión de la app, corre **todo el CI** (si falla no se construye nada), hace `pnpm tauri build` y `scripts/package-release.ps1`, y publica la release de GitHub. Tags con sufijo (`v1.0.0-beta.1`) salen como pre-release. -- **Releases: solo Windows** por ahora. Convención de nombre de todo build: **`_.`** → `windows_0.1.0.exe` (NSIS) y `windows_0.1.0.msi`. Junto a cada uno va `.sha256` y un `SHA256SUMS.txt` con todos (formato de `sha256sum`, finales LF: con CRLF `sha256sum -c` falla). La tabla de descargas con los hashes queda en el cuerpo de la release. -- Para publicar una versión: `release/X.Y.Z` desde `develop` → subir la versión en las tres fuentes → merge a `main` → `git tag vX.Y.Z` → `git push origin vX.Y.Z` → merge de vuelta a `develop`. +## Technical specifics -El **protocolo de red** tiene su propia versión, independiente de la de la app: `PROTOCOL_VERSION` en `crates/protocol/src/lib.rs`. Se incrementa solo cuando cambia el formato de los mensajes de forma incompatible (desktop y server rechazan mensajes de otra versión). +### Terminal and process handling -## Comandos +- **ConPTY:** Windows ConPTY emits a cursor position query (`ESC[6n`) requiring an xterm response before output flows. Raw PTY readers must reply to this query. +- **Process termination:** closing a terminal kills the full process tree (`taskkill /T /F` on Windows, `kill -KILL -` on Unix) to prevent orphaned agent child processes. +- **Shell exit:** typing `exit` or child process exit triggers `terminal-exit`, closing the pane cleanly. -Rust (desde la raíz del repo): +### Agent detection and activity -- `cargo build --workspace` -- `cargo test --workspace` -- Test puntual: `cargo test -p domain removing_view_revokes_write_and_access` (el filtro es un substring del nombre; `cargo test -p -- --list` lista los tests) -- `cargo clippy --workspace --all-targets -- -D warnings` -- `cargo fmt --all` (en CI: `cargo fmt --all --check`) +- **Detection:** `agent_watcher.rs` polls every 1 second via `sysinfo`, inspecting child processes beneath the shell. Stops at instances matching `current_exe()` to prevent recursion. +- **Activity tracking:** `ActivityTracker` records PTY byte output (3 seconds of silence transitions to `idle`). +- **Git branch tracking:** `FsRepositoryInspector` reads `.git/HEAD` directly upwards from the current working directory every 3 seconds. -Desktop (desde `apps/desktop`, usa pnpm): +### Shell integration and current directory tracking -- `pnpm install` -- `cargo tauri dev`: levanta Vite en `localhost:1420` y abre la ventana. -- `pnpm build`: typecheck (`tsc --noEmit`) + build de Vite. -- `pnpm test`: tests unitarios del frontend (Vitest, archivos `src/**/*.test.ts`). Uno puntual: `pnpm test -- -t "parseOsc7"`. -- `pnpm test:e2e`: E2E de la interfaz sobre el build de producción (correr `pnpm build` antes). Levanta `vite preview` en el puerto 4173, abre Chrome headless (el del sistema, o `CHROME_PATH`) e inyecta un **núcleo de Tauri simulado** (`e2e/tauri-mock.js`) que responde los mismos comandos y eventos que el real. Escenarios en `e2e/scenarios/`; para sumar uno, registrarlo en `e2e/run.mjs`. Si cambia un comando o evento del núcleo, actualizar también el mock. -- `cargo tauri build`: instaladores en `target/release/bundle/{nsis,msi}`; `pwsh scripts/package-release.ps1 -Version X.Y.Z` los deja en `release/` con el nombre y los hashes de release. +- **PowerShell OSC 7:** the default Windows shell wraps the prompt to emit `ESC]7;file://localhost/ ESC\`. `xterm.js` reads this sequence to update the path display. +- **Directory switcher:** `CwdSwitcher.tsx` sends `cd` commands to the shell; disabled while an agent process is running. -Server: corre solo en Docker (ver abajo; no hay `.env` para correrlo suelto). Escucha en `127.0.0.1:8787` (dentro del contenedor, `RELAY_ADDR=0.0.0.0:8787`); expone `/health` y `/ws`; el cliente WS manda `Sec-WebSocket-Protocol: opencollab.v1, bearer.` y sin token válido se rechaza el upgrade con 401. Tests: `pnpm --dir apps/server test` (Vitest). +### Rich agent adapters -Web: `pnpm --dir apps/web dev` (puerto 1421, hace proxy de `/auth` al server en `127.0.0.1:8787`, o a `OPENCOLLAB_API`), `pnpm --dir apps/web test` (Vitest + Testing Library), `pnpm --dir apps/web build` (typecheck + Vite). +- **Claude Code:** launched with `--settings ` targeting a local HTTP hook receiver on `127.0.0.1` with per-launch UUID security tokens. Translates hook events to `AgentEvent`s. +- **OpenCode:** launched with `--port

` and authenticated via `OPENCODE_SERVER_PASSWORD`. Consumes `GET /event` SSE stream. -Docker (server + web + Postgres; el desktop **no** va en contenedor: se instala la release y corre nativo contra este server): +### Authentication and desktop handoff -- `cp .env.example .env`, completar `JWT_SECRET` (32+ caracteres: `openssl rand -base64 48`) y las credenciales OAuth de **GitHub y Google** (`GITHUB_CLIENT_ID`/`_SECRET`, `GOOGLE_CLIENT_ID`/`_SECRET`; callback a registrar en cada proveedor: `/auth/oauth//callback`), y `docker compose up -d --build`. El `.env` raíz está ignorado. Todas son obligatorias: si falta alguna, el contenedor del server sale al arrancar (`docker compose logs server` dice cuál). Las migraciones de Prisma se aplican al iniciar el contenedor del server (`prisma migrate deploy`). -- Puertos, todos solo en `127.0.0.1`: web `8080` (nginx: SPA con fallback a `index.html`, proxy de `/auth` y `/ws` al server, misma CSP que `vite preview`), server `8787` (`/health`, `/auth/desktop/token`; el desktop habla directo con él), Postgres `5432`. -- El server corre con `TRUST_PROXY=1` (nginx es un salto) y `WEB_ORIGIN`/`PUBLIC_BASE_URL` = `http://localhost:8080`: los callbacks de OAuth pasan por la web. -- Apuntar el desktop a la web del contenedor: `OPENCOLLAB_WEB_ORIGIN=http://localhost:8080` (la dirección del server por defecto, `127.0.0.1:8787`, ya coincide). -- `docker compose up -d postgres` levanta solo la base para los tests de integración del server: `DATABASE_URL=postgresql://opencollab:opencollab@127.0.0.1:5432/opencollab pnpm --dir apps/server test:integration` (usan la base `opencollab_test`, nunca la de desarrollo). -- La CSP vive en dos lugares (`CSP` en `apps/web/vite.config.ts` y `apps/web/nginx.conf`); `apps/web/src/nginx.test.ts` falla si divergen. +- **Web client:** routes `/login`, `/register`, `/auth/complete`, and `/account`. Stores access token in memory and refresh token in an `httpOnly` cookie (`oc_refresh`). +- **Desktop handoff:** desktop generates PKCE S256 challenge, opens `/login?client=desktop&code_challenge=...`, and web returns authorization code via `opencollab://auth/callback?code=...` (or `opencollab-dev://` in dev). Desktop exchanges code for tokens, keeps the short-lived `access_token` strictly in Rust memory, and persists the rotating `refresh_token` + user profile in the OS credential store (`keyring`: Windows Credential Manager / macOS Keychain / Linux Secret Service, isolated between `opencollab` and `opencollab-dev`). -### Particularidades +### UI rules and component guidelines -- En Windows, ConPTY envía una consulta de posición de cursor (`ESC[6n`) y retiene la salida hasta recibir respuesta. En la app la contesta xterm.js vía `onData` → `write_terminal`. Cualquier test o cliente que lea un PTY sin xterm debe responderla (ver el test de `crates/infrastructure/src/pty.rs`). -- **Detección de agentes:** el panel muestra qué agente corre en cada terminal (Claude Code, OpenCode, Codex, Antigravity CLI, Grok). No se parsea lo que el usuario escribe: `agent_watcher.rs` (desktop) llama cada 1 s a `DetectTerminalAgents`, que toma una foto de procesos (`ProcessInspector`, implementado con `sysinfo`) y recorre en anchura los descendientes de la shell de cada terminal. `detect_agents` devuelve un `AgentTree`: `primary` es el agente más cercano a la shell (el que lanzó el usuario, y el que muestra el ícono del panel) y `nested` son los agentes conocidos que ese tiene corriendo debajo, sin repetir. El recorrido **se detiene en otra instancia de OpenCollab** (proceso con el mismo nombre de ejecutable que la app, tomado de `current_exe()` en el composition root y pasado con `DetectTerminalAgents::stopping_at`; sin distinguir mayúsculas ni `.exe`): esa instancia aloja sus propias terminales, así que sus agentes no se cuentan como anidados del agente que la lanzó (p. ej. Claude Code corriendo `cargo tauri dev`). El sidebar **no lista los anidados**: cada terminal muestra solo su agente principal; el evento `terminal-agent` igual lleva la lista completa (principal + anidados) y solo se emite cuando cambia. El catálogo (`crates/application/src/agent_detection.rs`) reconoce por nombre de ejecutable (`claude`, `opencode`, `codex`, `agy`/`antigravity`, `grok`) o, si el proceso es `node`/`bun`/`deno`, por el paquete npm en los argumentos (`@openai/codex`, `@xai-official/grok`, etc.). Para sumar un agente: agregarlo al enum `KnownAgent` en Rust y al catálogo de `apps/desktop/src/agents.ts` con el mismo id. - - Ojo con el nombre: son agentes **anidados**, no los subagentes internos de un agente. Claude Code, OpenCode y Codex corren sus subagentes (Task tool y similares) **dentro del mismo proceso**, así que no aparecen en el árbol de procesos y esta detección no los ve. Lo que sí aparece son otros CLIs que el agente lanza como herramienta. Los MCP servers son otro tema: son procesos hijos reales, pero hoy no se listan. -- **Info agnóstica en cada terminal del hilo** (`ThreadMeta.tsx`): no depende de ningún agente. El **estado** (`ThreadState`) va junto al título (`Claude Code · Working`, con el color/ícono del tono de `describeAgent`) y reemplaza al punto cuando hay un agente con estado conocido; sin agente queda el punto. La línea secundaria (`ThreadMeta`) lleva solo herramienta en curso/detalle de error y tiempo corriendo. La **rama** (`ThreadBranch`) cuelga del hilo como hijo, como único hijo del hilo. - - **Actividad** (`working` / `idle` / `needs attention`): sale del adaptador genérico. `ActivityTracker` (`application/src/activity.rs`, puro, con instante inyectado) registra cuándo emitió bytes cada terminal (`TauriOutputSink::output`); `agent_watcher.rs` hace `tick` cada 1 s y lo traduce a un `AgentEvent::StatusChanged` (sin salida por 3 s = `idle`). "Needs attention" es estado de UI (`src/activity.ts`, testeado): working -> idle sin que el usuario esté mirando el panel, hasta que lo mira. "Enfocado" significa `isWatching`: panel enfocado, visible (su sesión activa, sin minimizar) y con la ventana de la app en primer plano (`useWindowFocus`); volver a la ventana, a su sesión o restaurarlo también lo limpia. Solo se muestra si la terminal tiene un agente detectado (junto al título). El genérico no distingue "terminó" de "pide aprobación": eso lo informan los adaptadores ricos (ver abajo). - - **Tiempo corriendo del agente**: `ProcessInspector` expone el arranque de cada proceso (`ProcessInfo.started_at`, de `sysinfo::Process::start_time`, segundos Unix; `None` si no se conoce) y `detect_agents` lo copia del proceso del agente principal a `AgentTree.primary_started_at`. El evento `terminal-agent` lleva `startedAt` (`null` sin agente). El frontend lo formatea con `src/duration.ts` (`45s`, `12m`, `1h 05m`) y se actualiza con un único temporizador compartido (`src/useNow.ts`) que solo re-renderiza el fragmento de uptime. - - **Rama de git de la carpeta actual** (cualquier terminal, con o sin agente): puerto `RepositoryInspector` (`application/src/ports.rs`), caso de uso `InspectBranch`, y adaptador `FsRepositoryInspector` (`infrastructure/src/repository_inspector.rs`) que sube desde la carpeta hasta el primer `.git` (carpeta, o archivo `gitdir: ` de worktrees/submódulos) y lee `HEAD` sin el binario `git`. `application::git::parse_head` (puro): `ref: refs/heads/` es la rama; un SHA crudo es HEAD desacoplado y se muestra con 7 caracteres. Comando `git_branch(path)` -> `{ name, detached }` o `null` fuera de un repo. El frontend (`useGitBranch.ts` + `branchWatch.ts`, puro y testeado con timers falsos) lo consulta al cambiar el cwd (OSC 7 o carpeta inicial), al pasar a `idle` y **cada 3 s** (`BRANCH_POLL_MS`): OSC 7 solo se emite en el prompt, así que un cambio de rama mientras corre un agente, o hecho desde otra terminal en la misma carpeta, no avisa por otro lado. Las consultas pueden superponerse, así que una respuesta más vieja que la última aplicada se ignora; si una consulta falla se conserva la última rama conocida (solo se informa `null` si todavía no se conoce ninguna), para que un error transitorio no la haga parpadear. Mock de e2e: `window.__mock.branches`. -- **Status bar con estado real:** nada está hardcodeado. El núcleo sondea al relay (`HttpRelayProbe`, `GET /health` con `std::net`, timeout total de 1 s, éxito solo con `200` y cuerpo `ok`; caso de uso `CheckRelay`) y cuenta los participantes de la sesión con acceso (`SessionCollaborators`, `Session::participants` filtrado por `can_view`). `collab_status.rs` (desktop) lo expone como comando `collab_status` y como evento `collab-status` (`{ connected, syncMs, collaborators }`), emitido por un hilo propio que sondea cada 3 s. Regla de emisión (`should_emit`): siempre que cambie conectado o colaboradores; la latencia solo si se movió más de 5 ms y más de 25 % respecto de la última emitida, para no emitir en cada sondeo. La dirección sale de `RELAY_ADDR` o de `protocol::DEFAULT_RELAY_ADDR` (el server Nest usa el mismo default). En el frontend, `useCollabStatus` alimenta `StatusBar`; el valor inicial y los defaults son honestos (`DEFAULT_COLLAB_STATUS`: desconectado, sin latencia, 1 colaborador). Es la única señal real hasta que exista el `CollabTransport` WebSocket, que la reemplazará. El mock de Tauri responde `collab_status` desconectado; los E2E emiten `collab-status` con `window.__mock.emit`. -- **Directorio actual de cada terminal (shell integration):** la shell por defecto (`crates/infrastructure/src/shell.rs`) arranca PowerShell con `-NoExit -Command` envolviendo su `prompt` para emitir `OSC 7` (`ESC]7;file://localhost/C:/ruta ESC\`) antes de cada prompt; xterm lo lee (`registerOscHandler(7)`) y el header muestra la carpeta real en vivo. No se puede leer desde afuera porque PowerShell no cambia el cwd del proceso al hacer `cd`. Test real: `cargo test -p infrastructure --test shell_integration_e2e -- --ignored`. En Unix todavía no hay integración (solo se muestra la carpeta inicial). -- **Cambiador de ruta** (`CwdSwitcher.tsx`): menú con subcarpetas (adelante, vía `list_subdirectories` → `ListSubdirectories` → `DirectoryBrowser`), `..` y directorios padre (atrás). Navegar = escribirle un `cd` a la shell (`cdCommand` en `src/cwd.ts`, según la shell), así que se desactiva mientras corre un agente: el texto le llegaría al agente. El menú va en un portal con posición fija porque el panel tiene `overflow: hidden`, y se cierra con `resize`. -- **Nueva terminal desde otra** (`NewTerminalMenu.tsx`, botón `+` del header): abre otra al lado de la de origen, en su carpeta actual (la última que reportó OSC 7) o en la por defecto; `Ctrl/⌘+Shift+T` hace lo primero con la terminal enfocada. La carpeta viaja como `cwd` opcional de `open_shell` → `default_shell_profile(cwd)`, que cae al home si la carpeta ya no existe. Cada panel guarda su carpeta inicial en `Pane.initialCwd` y reporta la actual en `PaneMeta.cwd`. -- **`Panel`** (`components/Panel.tsx`): wrapper visual reutilizable (marco + barra de título + bloque interno oscuro con radio). Lo usan el panel de una terminal y la sesión del sidebar; cualquier contenedor nuevo con ese look debe usarlo en vez de copiar estilos. Se ajusta con variables CSS (`--panel-pad`, `--panel-bg`, `--panel-border`, `--panel-body-radius`) y `plain` lo deja sin marco. -- **Hilo de terminales en el sidebar:** cada sesión lista sus terminales en el orden de la grilla, con el mismo `TerminalIcon` que el header (logo del agente detectado o ícono de la shell). Cada panel reporta qué corre en él con `onMeta` hacia `App`. Clic en una terminal del hilo → va a su sesión y la enfoca. -- Logos de agentes: `apps/desktop/src/assets/agents/{claudecode,opencode,codex,antigravitycli,grok-xai}-logo.svg`. Se cargan con `import.meta.glob`, así que si falta uno el build no falla y el panel muestra un badge de texto. Se pintan como máscara CSS (`.pane-logo`: `mask` + `background-color: var(--text)`), no con ``: el SVG solo aporta la forma y el color sale siempre del token, sin importar el `fill` del archivo. -- **`AgentEvent` y adaptadores de agentes:** todo lo que se sabe de un agente llega como `AgentEvent`s (`application/src/agent_event.rs`: `status_changed`, `tool_started`, `tool_finished`, `approval_required`, `message`, `completed`, `error`; `AgentStatus` es solo `working`/`idle`, "necesita aprobación" es un dato aparte). `AgentState::reduce` (`agent_state.rs`, puro, con las reglas documentadas arriba) los reduce a un estado por terminal (estado, herramienta con resumen de su entrada, aprobación pendiente, último mensaje truncado, completado / error). `AgentStates` lo guarda por terminal y `TauriAgentEvents` (`src-tauri/src/agent_events.rs`, un `AgentEventSink`) emite **un solo evento**, `terminal-agent-state { terminalId, state }`, con el estado ya reducido y solo si cambió: el frontend no duplica el reductor (`src/agentState.ts` solo decide cómo mostrarlo, con tests). Un `AgentAdapter` (`agent_adapter.rs`) aporta args/env al lanzar su agente (`prepare`) y produce eventos una vez creada la terminal (`bind`); se registra en `AgentAdapters`. Sin adaptador rige el genérico (`activity_event`, `exit_event`). El puerto del PTY todavía no expone el código de salida: `terminal-exit` se informa como `completed`. -- **Lanzar un agente como perfil:** el menú `+` del header (`NewTerminalMenu.tsx`) ofrece, además de la shell, los agentes conocidos instalados (`available_agents`: comando de `KnownAgent::launch_command` encontrado en el `PATH`, con `PATHEXT` en Windows). Elegir uno llama a `open_shell` con `agent` (id de `KnownAgent`). El agente corre **dentro de la shell por defecto** (`infrastructure/src/agent_launch.rs`, `agent_shell_profile`): en PowerShell se encadena `; ''` al `-Command` de la integración OSC 7; en Unix, `-c '; exec $SHELL'`. Así al salir del agente el panel vuelve a la shell y la carpeta actual sigue reportándose. El dominio sigue agnóstico: es un `AgentProfile` más. La costura para los adaptadores es `AgentAdapters::prepare(agent)` en `open_shell` (agrega args/env antes de lanzar y devuelve un `PreparedLaunch` cuyo `bind(terminal, sink)` se llama con la terminal ya creada); `AppState.adapters` (registro en `state.rs::agent_adapters`) tiene los adaptadores ricos; sumar uno es implementar `AgentAdapter` y registrarlo ahí. Test real: `cargo test -p infrastructure --test shell_integration_e2e -- --ignored`. -- **Adaptador rico = fuente autoritativa:** si la terminal se lanzó con un adaptador (`PreparedLaunch::is_rich`), `open_shell` la marca con `AgentStates::mark_rich` y los `status_changed` del camino genérico (actividad del PTY, que entra por `apply_generic` / `TauriAgentEvents::emit_generic`) se ignoran para ella; la salida del proceso (`completed`) sigue valiendo. Al cerrarse la terminal, `AgentAdapters::release` deja que cada adaptador suelte lo suyo. Límite conocido: si el agente rico termina pero la terminal (shell) sigue, la marca persiste hasta cerrarla y un agente lanzado a mano ahí no tiene estado genérico. -- **Adaptador de Claude Code** (`infrastructure/src/claude_adapter.rs`, `claude_hooks.rs`, `hook_receiver.rs`): Claude se lanza con `--settings `, que **suma** hooks HTTP a la configuración del usuario sin tocarla (nada en `~/.claude` ni en el proyecto). `prepare` escribe `claude-settings-.json` en `/opencollab/` (archivo y no JSON en línea, por el entrecomillado de PowerShell; se borra al cerrar la terminal y los de más de 24 h, al arrancar) con un hook `type: "http"` por evento (`UserPromptSubmit`, `PreToolUse`, `PermissionRequest`, `Notification`, `PostToolUse`, `Stop`, `StopFailure`; timeout de 2 s). `HookReceiver` es un único listener HTTP en `127.0.0.1`, puerto aleatorio, sin runtime async (un hilo por conexión, tope de 16, plazos de 5 s). **Seguridad:** el secreto por lanzamiento (UUID v4) va en la URL `/hook/`; sin token registrado responde 401 antes de leer el cuerpo; cuerpo máximo 256 KiB (413), encabezado 16 KiB; al cerrar la terminal el token se da de baja. Siempre responde `{}` para no frenar al agente. `ClaudeHookTranslator::translate` es puro: `UserPromptSubmit` -> working; `PreToolUse` -> `tool_started`; `PermissionRequest` -> `approval_required` (`Bash: `; este hook no trae `tool_use_id`, el id sale de lo pedido) y `Notification(permission_prompt)` solo si no hay una aprobación pendiente; `PostToolUse` -> `tool_finished`; `Stop` -> `message` + idle (fin de turno, no `completed`); `StopFailure` -> `error`. Test real (consume un turno mínimo): `cargo test -p infrastructure --test claude_adapter_e2e -- --ignored --nocapture`. -- **Adaptador de OpenCode** (`infrastructure/src/opencode_adapter.rs`, `opencode_events.rs`, `sse.rs`): `opencode --port

--hostname 127.0.0.1` mantiene la TUI y expone su API HTTP. `prepare` elige un puerto libre de localhost (hay una ventana mínima hasta que OpenCode lo toma) y una **clave por lanzamiento** (UUID v4) que pasa por el entorno del proceso en `OPENCODE_SERVER_PASSWORD` (verificado: el servidor exige autenticación básica, usuario `opencode`, y la TUI sigue funcionando con la clave; sin clave o con una mala responde 401); nunca va en la línea de comandos ni en logs. `bind` lanza un hilo con un cliente SSE de `std::net` (sin dependencias nuevas: base64, `Transfer-Encoding: chunked` y separación de líneas están en `sse.rs`, con tests) que reintenta `GET /event` hasta 90 s mientras la TUI levanta el servidor, reconecta 10 s si se corta y se rinde ante un 401; se detiene al cerrar la terminal (`release`) y, si el servidor se va (OpenCode salió) pero la terminal sigue, informa `idle`. Líneas de más de 1 MiB se descartan. `OpenCodeTranslator::translate` (puro, con memoria mínima): `session.status` busy/idle y `session.idle` -> working/idle (las sesiones hijas, o sea subagentes, se ignoran); `message.part.updated` de tipo `tool` -> `tool_started` (en `pending` sin entrada y de nuevo en `running` con ella) y `tool_finished` (`completed`/`error`); `permission.asked` -> `approval_required` (`bash: `), `permission.replied` -> working (limpia la aprobación); texto final (`time.end`) de mensajes del asistente (el rol sale de `message.updated`) -> `message`; `session.error` -> `error`. Test real con la TUI en un PTY (consume un turno mínimo): `cargo test -p infrastructure --test opencode_adapter_e2e -- --ignored --nocapture`. -- Test end-to-end de detección con los CLIs reales instalados: `cargo test -p infrastructure --test agent_detection_e2e -- --ignored --nocapture --test-threads=1` (está `#[ignore]` porque depende de la máquina). -- Cerrar una terminal mata el **árbol de procesos completo** por pid (`taskkill /T /F` en Windows, `kill -KILL -` en Unix), para que el agente que corre dentro de la shell no quede huérfano. No usar `ChildKiller::kill` de portable-pty: en Windows falla con "handle inválido" (os error 6) o devuelve un falso error con código 0. -- El frontend no usa `React.StrictMode`: su doble montaje en dev abriría un PTY extra por terminal (un panel solo cierra su PTY con el botón ✕ → `close_terminal`, no al desmontarse). -- **Salir desde la shell** (`exit` o cualquier forma de terminar el proceso): el núcleo emite `terminal-exit` y el panel sigue el mismo camino que el ✕ (`close_terminal` + se quita de la grilla). `close` es idempotente porque el ✕ también dispara `terminal-exit` al matar el PTY. E2E: `e2e/scenarios/exit-closes-pane.mjs`. -- **Web como puerta de autenticación** (`apps/web`): sin router ni estado global, cuatro rutas (`/login`, `/register`, `/auth/complete`, `/account`). El access token vive solo en memoria (`authClient.ts`); el refresh token es la cookie httpOnly `oc_refresh` (`Path=/auth`) que la página nunca ve, y toda llamada a `/auth/web/*` lleva `X-OpenCollab-CSRF: 1` y `credentials: 'same-origin'`. Nada va a `localStorage`/URL. El refresh es single-flight por pestaña y se serializa entre pestañas con Web Locks (`opencollab-refresh`; sin `navigator.locks` queda el single-flight local), y se renueva solo poco antes de `expiresIn`; un 401 deja la sesión cerrada. Web y API comparten origen (proxy de Vite en dev; reverse proxy en producción), por eso no hay CORS. **Entrega al desktop:** `/login?client=desktop&code_challenge=`; solo el challenge se guarda en `sessionStorage` (sobrevive al viaje OAuth) y, tras autenticar (contraseña, registro o `/auth/complete`), se pide `POST /auth/web/desktop-code` y se navega al deep link `opencollab://` (cualquier otro destino se rechaza). Si ya había sesión, se ofrece "Continue as ". **CSP:** `vite preview` sirve `Content-Security-Policy` estricta (`default-src 'self'`, sin inline, `frame-ancestors 'none'`; definida en `apps/web/vite.config.ts`); en producción el reverse proxy debe enviar **la misma cabecera**. El dev server no la lleva (Fast Refresh necesita scripts inline). No usar `dangerouslySetInnerHTML` ni estilos en línea. -- Frontend: los workspaces y las sesiones del sidebar son por ahora estado de UI (`apps/desktop/src/model.ts`), porque el núcleo todavía no expone comandos para ellos; todas las terminales corren dentro de la única sesión del núcleo. Las terminales de sesiones no activas quedan montadas y ocultas (atributo `hidden`) para no perder sus PTY; xterm solo hace `fit()` si su contenedor tiene tamaño. Al agregar comandos de workspaces/sesiones en el núcleo, reemplazar ese estado local en lugar de duplicarlo. -- **Arrastrar paneles** (`apps/desktop/src/usePaneDrag.ts`): se arrastran por el header y se intercambian en vivo con el panel que está bajo el puntero, con animación FLIP. Regla clave: **nunca reordenar el DOM de los paneles** (mover el nodo de una xterm puede resetear su scroll/estado). El DOM se renderiza siempre por `Pane.seq` (orden de creación) y la posición visual sale del orden de `Session.panes` aplicado con la propiedad CSS `order`. El hit-testing usa `offsetLeft/Top` (posición de layout, sin transforms) para no oscilar mientras los demás paneles se animan. El arrastre se desactiva con un solo panel visible (maximizado o layout single). -- Íconos: los de UI genéricos vienen de `react-icons` (set Codicons, `react-icons/vsc`): `VscTerminal` en el contador de terminales de cada sesión, y en el header del panel el ícono de la shell (`VscTerminalPowershell`, `VscTerminalCmd`, `VscTerminalBash` o `VscTerminal`) cuando no corre un agente conocido. Los trazos simples propios están en `src/icons.tsx`; SVGs propios del proyecto en `src/assets/opencollab/` (pintados como máscara CSS para heredar el color del texto). -- Tipografía: **Google Sans**, empaquetada con la app vía `@fontsource-variable/google-sans` (funciona sin conexión; pesos 400–700). Se usa por el token `--font`; el código monoespaciado sigue con `--mono`. -- Diseño de referencia: tema oscuro, tipografía Google Sans, acento violeta (`--accent: #7c5cff`), sidebar (selector de workspace, búsqueda, sesiones, usuario), topbar (breadcrumb, Invite, layouts grid/columns/single, New terminal), paneles con header (badge, nombre, cwd, estado, controles) y status bar con atajos (`Ctrl/⌘+T`, `+1-4`, `+Shift+M`, `+K`). -- **Login del desktop vía la web** (`src-tauri/src/auth.rs`, `src/auth.ts`, `src/useAuth.ts`): la tarjeta de cuenta del sidebar (`AuthCard`) ofrece *Sign in*; el frontend genera el par PKCE S256 (WebCrypto) y llama `auth_begin_login`, que guarda el verifier y abre el navegador en `/login?client=desktop&code_challenge=…` (`OPENCOLLAB_WEB_ORIGIN`, por defecto `http://localhost:1421`). La web vuelve con `opencollab://auth/callback?code=…` (plugins `deep-link` + `single-instance`: el deep link que llega como argumento de un segundo proceso se reenvía a la instancia abierta) y `auth_finish` lo canjea en `POST /auth/desktop/token`. Los tokens viven **solo en memoria del núcleo Rust** (el `fetch` del webview chocaría con CORS, que el server tiene apagado); la UI recibe el usuario por `auth_status` y el evento `auth-changed`. El scheme `opencollab://` se registra al instalar el `.msi`/`.exe`: correr el binario suelto no lo registra. El avatar del topbar y el avatar host de cada panel siguen con `hidden` y `localUser` (`src/model.ts`) hasta que haya sesiones compartidas reales. E2E: `e2e/scenarios/auth-signin.mjs`. +- **Component framing:** structural panels must reuse `Panel` from `@opencollab/ui`. +- **Drag-and-drop:** reorders visually via CSS `order`. Underlying DOM order strictly preserves `Pane.seq` to avoid resetting `xterm.js` buffers. +- **No `React.StrictMode`:** disabled in development to prevent duplicate PTY spawns. diff --git a/Cargo.lock b/Cargo.lock index 3dc3f1d..75680fa 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -49,7 +49,7 @@ checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" [[package]] name = "application" -version = "0.3.0" +version = "0.4.0" dependencies = [ "domain", "serde", @@ -537,6 +537,16 @@ dependencies = [ "version_check", ] +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "core-foundation" version = "0.10.1" @@ -560,7 +570,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics-types", "foreign-types", "libc", @@ -573,7 +583,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" dependencies = [ "bitflags 2.13.2", - "core-foundation", + "core-foundation 0.10.1", "libc", ] @@ -700,6 +710,16 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "dbus-secret-service" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "708b509edf7889e53d7efb0ffadd994cc6c2345ccb62f55cfd6b0682165e4fa6" +dependencies = [ + "dbus", + "zeroize", +] + [[package]] name = "defmt" version = "1.1.1" @@ -763,11 +783,12 @@ dependencies = [ [[package]] name = "desktop" -version = "0.3.0" +version = "0.4.0" dependencies = [ "application", "domain", "infrastructure", + "keyring", "protocol", "serde", "serde_json", @@ -880,7 +901,7 @@ dependencies = [ [[package]] name = "domain" -version = "0.3.0" +version = "0.4.0" dependencies = [ "thiserror 2.0.21", "uuid", @@ -1811,13 +1832,15 @@ dependencies = [ [[package]] name = "infrastructure" -version = "0.3.0" +version = "0.4.0" dependencies = [ "application", "domain", "portable-pty", + "serde", "serde_json", "sysinfo", + "ureq", "uuid", ] @@ -1997,6 +2020,21 @@ dependencies = [ "serde", ] +[[package]] +name = "keyring" +version = "3.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eebcc3aff044e5944a8fbaf69eb277d11986064cba30c468730e8b9909fb551c" +dependencies = [ + "byteorder", + "dbus-secret-service", + "log", + "security-framework 2.11.1", + "security-framework 3.7.0", + "windows-sys 0.60.2", + "zeroize", +] + [[package]] name = "lazy_static" version = "1.5.1" @@ -2814,7 +2852,7 @@ dependencies = [ [[package]] name = "protocol" -version = "0.3.0" +version = "0.4.0" dependencies = [ "serde", "serde_json", @@ -2958,6 +2996,20 @@ dependencies = [ "web-sys", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rust-ini" version = "0.21.3" @@ -2996,6 +3048,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "log", + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -3068,6 +3155,42 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.9.4", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation 0.10.1", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + [[package]] name = "selectors" version = "0.38.0" @@ -3267,6 +3390,12 @@ dependencies = [ "stable_deref_trait", ] +[[package]] +name = "sha1_smol" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d" + [[package]] name = "sha2" version = "0.10.9" @@ -3428,6 +3557,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "swift-rs" version = "1.0.8" @@ -3526,7 +3661,7 @@ checksum = "f37f381f4e048e6cdf038b5705f8cf14ad108279d46eb968140a7b291aba9400" dependencies = [ "bitflags 2.13.2", "block2", - "core-foundation", + "core-foundation 0.10.1", "core-graphics", "crossbeam-channel", "dbus", @@ -4221,6 +4356,41 @@ version = "1.13.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a7ac20be9b7726e0bbdbf974c059676d9acb1cd414961f570a4e8231cacd7fc" +dependencies = [ + "base64 0.23.1", + "flate2", + "log", + "percent-encoding", + "rustls", + "rustls-pki-types", + "ureq-proto", + "utf8-zero", + "webpki-roots", +] + +[[package]] +name = "ureq-proto" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841583fc36089d7d59419568ae157f43a5a03a2e5a81ba87c77d1596ef46e922" +dependencies = [ + "base64 0.23.1", + "http", + "httparse", + "log", +] + [[package]] name = "url" version = "2.5.8" @@ -4246,6 +4416,12 @@ dependencies = [ "url", ] +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + [[package]] name = "utf8_iter" version = "1.0.4" @@ -4261,6 +4437,7 @@ dependencies = [ "getrandom 0.4.3", "js-sys", "serde_core", + "sha1_smol", "wasm-bindgen", ] @@ -4475,6 +4652,15 @@ dependencies = [ "system-deps", ] +[[package]] +name = "webpki-roots" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c1c8e20c8a38fc7d65abfe74eb7280e4aa667e8eec8bc84996d2874810748d9" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webview2-com" version = "0.39.1" @@ -4677,6 +4863,15 @@ dependencies = [ "windows-targets 0.42.2", ] +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.59.0" @@ -4686,6 +4881,15 @@ dependencies = [ "windows-targets 0.52.6", ] +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + [[package]] name = "windows-sys" version = "0.61.2" @@ -4719,13 +4923,30 @@ dependencies = [ "windows_aarch64_gnullvm 0.52.6", "windows_aarch64_msvc 0.52.6", "windows_i686_gnu 0.52.6", - "windows_i686_gnullvm", + "windows_i686_gnullvm 0.52.6", "windows_i686_msvc 0.52.6", "windows_x86_64_gnu 0.52.6", "windows_x86_64_gnullvm 0.52.6", "windows_x86_64_msvc 0.52.6", ] +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + [[package]] name = "windows-threading" version = "0.2.1" @@ -4756,6 +4977,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -4768,6 +4995,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -4780,12 +5013,24 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -4798,6 +5043,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -4810,6 +5061,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + [[package]] name = "windows_x86_64_gnullvm" version = "0.42.2" @@ -4822,6 +5079,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -4834,6 +5097,12 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + [[package]] name = "winnow" version = "0.5.40" @@ -5062,6 +5331,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "zerotrie" version = "0.2.5" diff --git a/Cargo.toml b/Cargo.toml index 5053998..37e9eea 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,28 +1,31 @@ [workspace] resolver = "2" members = [ - "crates/domain", - "crates/application", - "crates/protocol", - "crates/infrastructure", + "apps/desktop/core/domain", + "apps/desktop/core/application", + "apps/desktop/core/protocol", + "apps/desktop/core/infrastructure", "apps/desktop/src-tauri", ] [workspace.package] -version = "0.3.0" +version = "0.4.0" edition = "2021" license = "UNLICENSED" publish = false [workspace.dependencies] # Internal crates -domain = { path = "crates/domain" } -application = { path = "crates/application" } -protocol = { path = "crates/protocol" } -infrastructure = { path = "crates/infrastructure" } +domain = { path = "apps/desktop/core/domain" } +application = { path = "apps/desktop/core/application" } +protocol = { path = "apps/desktop/core/protocol" } +infrastructure = { path = "apps/desktop/core/infrastructure" } # External -uuid = { version = "1", features = ["v4"] } +uuid = { version = "1", features = ["v4", "v5"] } +# Cliente HTTP bloqueante con TLS (modo nube del snapshot): rustls + ring por +# defecto, sin runtime async. +ureq = "3" thiserror = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" @@ -34,3 +37,4 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } tauri = { version = "2", features = [] } tauri-build = { version = "2", features = [] } +keyring = { version = "3", features = ["apple-native", "windows-native", "sync-secret-service"] } diff --git a/README.md b/README.md index 322c88b..6266346 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,170 @@ -# opencollab - +# OpenCollab

+

Unified workspace for terminal-based AI agents with real-time collaboration

+ Built with Gentle-AI
+ +--- + +## What is OpenCollab? + +**OpenCollab** is a desktop application designed to centralize, monitor, and collaborate in real time with terminal-based AI agents (such as Claude Code, OpenCode, Codex, Gemini CLI, and standard shells) in a flexible multi-pane grid. + +### Key features + +- **Flexible terminal grid:** dynamic panes with accelerated rendering powered by [xterm.js](https://xtermjs.org/) and native PTYs managed in Rust. +- **Dual storage modes (Local & Cloud):** choose during first-run onboarding or anytime in Settings whether to persist workspaces, sessions, and terminal profiles locally in OS appdata (`workspaces.json`) or synchronize them with the Cloud REST API, with automatic local-to-cloud migration when switching to Cloud. +- **Intelligent agent detection:** periodic inspection of child processes and direct hooks to detect active agents and report their lifecycle (working, idle, awaiting approval, running tools). +- **Real-time collaboration:** + - **Workspaces and sessions:** project containers and shared rooms where multiple collaborators observe terminal streams. + - **Strict access control:** hierarchical access levels (`none < view < write`) verified on the server and enforced fail-closed on the local host. +- **Decoupled authentication and handoff:** secure web sign-in via OAuth providers (GitHub, Google) with desktop handoff using PKCE S256 and `opencollab://` deep links. + +--- + +## Architecture and monorepo structure + +The project is organized as a monorepo managed with **pnpm workspaces** and **Turborepo**, following clean architecture principles with strict inward-pointing dependencies. + +```text +opencollab/ +├── apps/ +│ ├── api/ # Relay server with NestJS 11 (WebSocket, auth, Prisma 7 + PostgreSQL) +│ ├── desktop/ # Desktop application with Tauri 2 (React 19 frontend + native Rust core) +│ └── web/ # Authentication portal and web client (Vite 8 + React 19) +├── packages/ +│ ├── contracts/ # @opencollab/contracts: Zod wire schemas and protocol DTOs +│ ├── domain/ # @opencollab/domain: pure TypeScript collaborative business authority +│ ├── ui/ # @opencollab/ui: presentational components (Panel, Sidebar, etc.) +│ └── config/ # Shared TypeScript and tooling configurations +└── docker-compose.yml +``` + +### Package roles and boundaries + +- **`@opencollab/domain`**: single authority for collaborative business rules (workspaces, sessions, invitations, permissions). Zero external runtime dependencies. +- **`@opencollab/contracts`**: canonical wire protocol schemas with byte parity to the Rust core (`apps/desktop/core`). +- **`@opencollab/ui`**: presentational components decoupled from Tauri and business logic. +- **Package consumption**: applications (`apps/*`) consume shared libraries strictly via `@opencollab/*` through their compiled output (`dist/`). + +### System flow and communication + +```mermaid +flowchart TD + subgraph Packages ["packages/ (shared libraries)"] + Domain["packages/domain
business authority
(pure TS: workspace, session, access level)"] + Contracts["packages/contracts
wire protocol
(Zod: envelope, message, PROTOCOL_VERSION)"] + UI["packages/ui
shared presentation
(pure React, no Tauri or business logic)"] + end + + subgraph Apps ["apps/ (applications)"] + API["apps/api (NestJS)
WS relay, auth, Prisma DB"] + Desktop["apps/desktop (Tauri + React)
native PTYs (Rust) + xterm.js"] + Web["apps/web (Vite + React)
auth portal, web UI"] + end + + %% Relationships + Domain -->|rules and invariants| API + Domain -.->|base inference/types| Contracts + + Contracts -->|wire Zod validation| API + Contracts -->|WS message types| Desktop + Contracts -->|message types| Web + + UI -->|visual components| Desktop + UI -->|visual components| Web + + Desktop <-->|WebSocket: envelope/message| API + Web <-->|HTTP auth / REST| API +``` + +--- + +## Prerequisites + +To build and run the project locally, make sure you have: + +- **Node.js**: version 24.x LTS recommended. +- **pnpm**: version 11 or higher (`corepack enable && corepack prepare pnpm@latest --activate`). +- **Rust**: stable toolchain with `cargo`, `rustfmt`, and `clippy` (`rustup update stable`). +- **Docker and Docker Compose**: for running PostgreSQL and containerized services. +- **Linux Tauri dependencies (if applicable)**: `libwebkit2gtk-4.1-dev`, `build-essential`, `curl`, `wget`, `file`, `libssl-dev`, `libgtk-3-dev`, `libayatana-appindicator3-dev`, `librsvg2-dev`. + +--- + +## Getting started locally + +### 1. Clone the repository and configure environment variables + +```bash +git clone https://github.com/facyndev/opencollab.git +cd opencollab +cp .env.example .env +``` + +Edit the `.env` file to set your `JWT_SECRET` (at least 32 characters) and optional OAuth credentials for GitHub/Google sign-in. + +### 2. Install dependencies + +```bash +pnpm install +``` +*(Note: installation automatically triggers Prisma client generation in `apps/api`).* + +### 3. Start the PostgreSQL database + +You can start a PostgreSQL instance with Docker: + +```bash +docker compose up -d postgres +``` + +Or run the full stack (PostgreSQL + API + Web behind Nginx on port 8080): + +```bash +docker compose up -d --build +``` + +### 4. Run applications in development mode + +Start the entire stack in parallel (API + Web + Desktop Tauri) from the repository root: + +```bash +pnpm dev +``` + +Or run each application individually using the `:dev` convention (or `pnpm dev` inside each app directory): + +#### Desktop (Tauri) +```bash +pnpm desktop:dev +``` + +#### Relay server / API (NestJS) +```bash +pnpm api:dev +``` + +#### Web portal (Vite) +```bash +pnpm web:dev +``` + +--- + +## Testing and code quality + +The repository includes automated validation pipelines and comprehensive test suites: + +| Command | Description | +|---|---| +| `pnpm test` | Run all TypeScript unit tests (Vitest) | +| `pnpm typecheck` | Check types across all workspace projects (`tsc --noEmit`) | +| `pnpm build` | Build all shared packages and applications | +| `pnpm check:rust` | Run Rust formatting check (`cargo fmt`), linter (`clippy`), and unit tests | +| `pnpm pre-push` | Run the fast verification pipeline prior to git push | +| `pnpm --filter @opencollab/desktop test:e2e` | Run UI end-to-end tests with headless Chromium | diff --git a/apps/server/.dockerignore b/apps/api/.dockerignore similarity index 100% rename from apps/server/.dockerignore rename to apps/api/.dockerignore diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile new file mode 100644 index 0000000..c8643db --- /dev/null +++ b/apps/api/Dockerfile @@ -0,0 +1,39 @@ +# syntax=docker/dockerfile:1 +# Relay server image. Build context: the repo root (single pnpm workspace and lockfile). +# docker build -f apps/api/Dockerfile . + +FROM node:24-slim AS build +WORKDIR /app +RUN corepack enable +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./ +COPY packages/domain ./packages/domain +COPY packages/contracts ./packages/contracts +COPY apps/api/package.json ./apps/api/ +COPY apps/api/prisma ./apps/api/prisma +COPY apps/api/prisma.config.ts apps/api/tsconfig.json apps/api/tsconfig.build.json ./apps/api/ +# postinstall runs `prisma generate`: it needs the schema, config and tsconfig (the latter decides the import extensions it emits). +RUN pnpm install --frozen-lockfile --filter @opencollab/server... +RUN pnpm --filter @opencollab/domain build +RUN pnpm --filter @opencollab/contracts build +COPY apps/api/src ./apps/api/src +RUN pnpm --filter @opencollab/server build +# Self-contained node_modules for the runtime. The Prisma CLI (a devDependency) +# stays in it: it applies the migrations on startup, so nothing is pruned. +RUN pnpm --filter @opencollab/server deploy --legacy /deploy + +FROM node:24-slim +ENV NODE_ENV=production \ + RELAY_ADDR=0.0.0.0:8787 +# Prisma detects the libssl version through openssl, which slim images lack. +RUN apt-get update && apt-get install -y --no-install-recommends openssl \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /app +COPY --from=build --chown=node:node /deploy/node_modules ./node_modules +COPY --from=build --chown=node:node /app/apps/api/dist ./dist +COPY --from=build --chown=node:node /app/apps/api/prisma ./prisma +COPY --from=build --chown=node:node /app/apps/api/prisma.config.ts /app/apps/api/package.json ./ +USER node +EXPOSE 8787 +HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \ + CMD ["node", "-e", "fetch('http://127.0.0.1:8787/health').then(r=>r.text()).then(t=>process.exit(t==='ok'?0:1)).catch(()=>process.exit(1))"] +CMD ["sh", "-c", "node_modules/.bin/prisma migrate deploy && exec node dist/main.js"] diff --git a/apps/server/package.json b/apps/api/package.json similarity index 78% rename from apps/server/package.json rename to apps/api/package.json index accb9df..26d35b1 100644 --- a/apps/server/package.json +++ b/apps/api/package.json @@ -2,13 +2,13 @@ "name": "@opencollab/server", "version": "0.1.0", "private": true, - "packageManager": "pnpm@11.1.1", "description": "Servidor de colaboración de OpenCollab (relay): autenticación, sesiones compartidas y retransmisión de streams de PTY.", "scripts": { + "dev": "tsx watch --env-file-if-exists=.env --env-file-if-exists=../../.env src/main.ts", "build": "tsc -p tsconfig.build.json", "typecheck": "tsc --noEmit -p tsconfig.json", - "start": "node --env-file-if-exists=.env dist/main.js", - "start:dev": "tsx watch --env-file-if-exists=.env src/main.ts", + "start": "node --env-file-if-exists=.env --env-file-if-exists=../../.env dist/main.js", + "start:dev": "tsx watch --env-file-if-exists=.env --env-file-if-exists=../../.env src/main.ts", "test": "vitest run", "test:integration": "vitest run -c vitest.integration.config.mts", "db:generate": "prisma generate", @@ -23,6 +23,8 @@ "@nestjs/platform-ws": "^11.2.7", "@nestjs/throttler": "^6.7.1", "@nestjs/websockets": "^11.0.0", + "@opencollab/contracts": "workspace:*", + "@opencollab/domain": "workspace:*", "@prisma/adapter-pg": "7.10.0", "@prisma/client": "7.10.0", "argon2": "^0.45.1", @@ -44,10 +46,5 @@ "tsx": "^4.0.0", "typescript": "~5.9.0", "vitest": "^5.0.0" - }, - "pnpm": { - "onlyBuiltDependencies": [ - "esbuild" - ] } } diff --git a/apps/server/prisma.config.ts b/apps/api/prisma.config.ts similarity index 100% rename from apps/server/prisma.config.ts rename to apps/api/prisma.config.ts diff --git a/apps/server/prisma/migrations/20261006000000_init/migration.sql b/apps/api/prisma/migrations/20261006000000_init/migration.sql similarity index 100% rename from apps/server/prisma/migrations/20261006000000_init/migration.sql rename to apps/api/prisma/migrations/20261006000000_init/migration.sql diff --git a/apps/api/prisma/migrations/20261019000000_terminal_agent_minimized/migration.sql b/apps/api/prisma/migrations/20261019000000_terminal_agent_minimized/migration.sql new file mode 100644 index 0000000..adfdff8 --- /dev/null +++ b/apps/api/prisma/migrations/20261019000000_terminal_agent_minimized/migration.sql @@ -0,0 +1,4 @@ +-- Terminal snapshot metadata (S7): which agent a pane launches (null = plain +-- shell) and its collapsed state, so the desktop's cloud snapshot round-trips. +ALTER TABLE "Terminal" ADD COLUMN "agent" TEXT; +ALTER TABLE "Terminal" ADD COLUMN "minimized" BOOLEAN NOT NULL DEFAULT false; diff --git a/apps/server/prisma/migrations/migration_lock.toml b/apps/api/prisma/migrations/migration_lock.toml similarity index 100% rename from apps/server/prisma/migrations/migration_lock.toml rename to apps/api/prisma/migrations/migration_lock.toml diff --git a/apps/server/prisma/schema.prisma b/apps/api/prisma/schema.prisma similarity index 96% rename from apps/server/prisma/schema.prisma rename to apps/api/prisma/schema.prisma index a9e5da0..0fb2894 100644 --- a/apps/server/prisma/schema.prisma +++ b/apps/api/prisma/schema.prisma @@ -172,6 +172,10 @@ model Terminal { command String args String[] cwd String? + // Snapshot metadata (S7): which agent the pane launches (null = plain + // shell) and its collapsed state, so the cloud snapshot round-trips fully. + agent String? + minimized Boolean @default(false) // Always written as [] by the repository: env may hold secrets. env Json @default("[]") diff --git a/apps/server/src/app.module.ts b/apps/api/src/app.module.ts similarity index 90% rename from apps/server/src/app.module.ts rename to apps/api/src/app.module.ts index 32c22bc..88121ea 100644 --- a/apps/server/src/app.module.ts +++ b/apps/api/src/app.module.ts @@ -1,6 +1,7 @@ import { Module } from '@nestjs/common'; import { AuthModule } from './auth/auth.module'; +import { CollabModule } from './collab/collab.module'; import { CollabGateway } from './collab.gateway'; import { HealthController } from './health.controller'; import { SESSION_STORE, SessionHub, type SessionStore } from './hub'; @@ -10,7 +11,7 @@ import { SessionRepository } from './persistence/session.repository'; import { WorkspaceRepository } from './persistence/workspace.repository'; @Module({ - imports: [AuthModule, PersistenceModule], + imports: [AuthModule, CollabModule, PersistenceModule], controllers: [HealthController], providers: [ { diff --git a/apps/api/src/app.routes.int.spec.ts b/apps/api/src/app.routes.int.spec.ts new file mode 100644 index 0000000..e96ca76 --- /dev/null +++ b/apps/api/src/app.routes.int.spec.ts @@ -0,0 +1,82 @@ +import type { INestApplication } from '@nestjs/common'; +import { afterAll, beforeAll, describe, expect, it } from 'vitest'; +import { Test } from '@nestjs/testing'; +import { WsAdapter } from '@nestjs/platform-ws'; + +import { AUTH_CONFIG, type AuthConfig } from './auth/config'; +import { applyHttpConfig } from './auth/http-config'; +import { CLOCK } from './auth/clock'; +import { OAUTH_PROVIDERS } from './auth/oauth-provider'; +import { TestClock } from './auth/test-app'; +import { PRISMA } from './persistence/persistence.module'; +import { openTestClient } from './persistence/test-db'; +import type { PrismaClient } from './generated/prisma/client'; +import { AppModule } from './app.module'; + +// Boots the REAL AppModule (not the CollabModule-only test app) to prove the +// collab REST surface is wired into the production module graph and that its +// routes stay behind AccessGuard (S14: unauthenticated -> 401, not 404). +describe('AppModule collab route wiring (int)', () => { + let app: INestApplication; + let prisma: PrismaClient; + let baseUrl: string; + + beforeAll(async () => { + prisma = openTestClient(); + const config: AuthConfig = { + jwtSecret: 'test-secret-test-secret-test-secret-test', + databaseUrl: 'unused', + publicBaseUrl: 'http://api.test', + webOrigin: 'http://web.test', + oauth: {}, + rateLimitEnabled: false, + trustProxy: false, + }; + const moduleRef = await Test.createTestingModule({ imports: [AppModule] }) + .overrideProvider(PRISMA) + .useValue(prisma) + .overrideProvider(AUTH_CONFIG) + .useValue(config) + .overrideProvider(OAUTH_PROVIDERS) + .useValue({}) + .overrideProvider(CLOCK) + .useValue(new TestClock()) + .compile(); + app = moduleRef.createNestApplication(); + applyHttpConfig(app, config); + app.useWebSocketAdapter(new WsAdapter(app)); + await app.listen(0, '127.0.0.1'); + baseUrl = await app.getUrl(); + }); + + afterAll(async () => { + await app.close(); + await prisma.$disconnect(); + }); + + async function statusOf(method: string, path: string): Promise { + const res = await fetch(`${baseUrl}${path}`, { method }); + return res.status; + } + + it('still serves the existing health route', async () => { + expect(await statusOf('GET', '/health')).toBe(200); + }); + + it('registers workspaces routes behind the access guard (S14)', async () => { + expect(await statusOf('GET', '/workspaces')).toBe(401); + }); + + it('registers nested sessions routes behind the access guard (S14)', async () => { + expect(await statusOf('GET', '/workspaces/00000000-0000-0000-0000-000000000000/sessions')).toBe(401); + }); + + it('registers terminals routes behind the access guard (S14)', async () => { + expect(await statusOf('POST', '/sessions/00000000-0000-0000-0000-000000000000/terminals')).toBe(401); + }); + + it('registers invitations routes behind the access guard (S14)', async () => { + expect(await statusOf('GET', '/invitations')).toBe(401); + expect(await statusOf('POST', '/invitations/00000000-0000-0000-0000-000000000000/accept')).toBe(401); + }); +}); diff --git a/apps/server/src/auth/access.guard.ts b/apps/api/src/auth/access.guard.ts similarity index 100% rename from apps/server/src/auth/access.guard.ts rename to apps/api/src/auth/access.guard.ts diff --git a/apps/server/src/auth/auth.controller.ts b/apps/api/src/auth/auth.controller.ts similarity index 99% rename from apps/server/src/auth/auth.controller.ts rename to apps/api/src/auth/auth.controller.ts index fc33a88..0c58caf 100644 --- a/apps/server/src/auth/auth.controller.ts +++ b/apps/api/src/auth/auth.controller.ts @@ -273,6 +273,6 @@ export class AuthController { const presented = refreshCookie(cookies); const userId = presented ? await this.auth.sessionUser(presented) : undefined; if (!userId) throw new UnauthorizedException('Invalid session'); - return { redirectUrl: await this.oauth.issueDesktopCode(userId, body.code_challenge) }; + return { redirectUrl: await this.oauth.issueDesktopCode(userId, body.code_challenge, body.client) }; } } diff --git a/apps/server/src/auth/auth.http.int.spec.ts b/apps/api/src/auth/auth.http.int.spec.ts similarity index 100% rename from apps/server/src/auth/auth.http.int.spec.ts rename to apps/api/src/auth/auth.http.int.spec.ts diff --git a/apps/server/src/auth/auth.module.ts b/apps/api/src/auth/auth.module.ts similarity index 95% rename from apps/server/src/auth/auth.module.ts rename to apps/api/src/auth/auth.module.ts index 885530f..238e9fd 100644 --- a/apps/server/src/auth/auth.module.ts +++ b/apps/api/src/auth/auth.module.ts @@ -47,6 +47,6 @@ function buildProviders(config: AuthConfig): OAuthProviders { OAuthService, AccessGuard, ], - exports: [SessionService, SessionRevocations], + exports: [SessionService, SessionRevocations, AuthService, AccessGuard], }) export class AuthModule {} diff --git a/apps/server/src/auth/auth.service.ts b/apps/api/src/auth/auth.service.ts similarity index 98% rename from apps/server/src/auth/auth.service.ts rename to apps/api/src/auth/auth.service.ts index 9dd24a3..a6add06 100644 --- a/apps/server/src/auth/auth.service.ts +++ b/apps/api/src/auth/auth.service.ts @@ -1,6 +1,6 @@ import { ConflictException, Inject, Injectable, UnauthorizedException } from '@nestjs/common'; -import type { UserId } from '../domain'; +import type { UserId } from '@opencollab/domain'; import { AuthRepository, isUniqueViolation } from '../persistence/auth.repository'; import { UserRepository, type UserRecord } from '../persistence/user.repository'; import { PasswordService } from './password.service'; diff --git a/apps/server/src/auth/binding.spec.ts b/apps/api/src/auth/binding.spec.ts similarity index 100% rename from apps/server/src/auth/binding.spec.ts rename to apps/api/src/auth/binding.spec.ts diff --git a/apps/server/src/auth/binding.ts b/apps/api/src/auth/binding.ts similarity index 100% rename from apps/server/src/auth/binding.ts rename to apps/api/src/auth/binding.ts diff --git a/apps/server/src/auth/clock.ts b/apps/api/src/auth/clock.ts similarity index 100% rename from apps/server/src/auth/clock.ts rename to apps/api/src/auth/clock.ts diff --git a/apps/server/src/auth/config.module.ts b/apps/api/src/auth/config.module.ts similarity index 100% rename from apps/server/src/auth/config.module.ts rename to apps/api/src/auth/config.module.ts diff --git a/apps/server/src/auth/config.spec.ts b/apps/api/src/auth/config.spec.ts similarity index 100% rename from apps/server/src/auth/config.spec.ts rename to apps/api/src/auth/config.spec.ts diff --git a/apps/server/src/auth/config.ts b/apps/api/src/auth/config.ts similarity index 100% rename from apps/server/src/auth/config.ts rename to apps/api/src/auth/config.ts diff --git a/apps/server/src/auth/dto.ts b/apps/api/src/auth/dto.ts similarity index 88% rename from apps/server/src/auth/dto.ts rename to apps/api/src/auth/dto.ts index 9cb4732..4cedf41 100644 --- a/apps/server/src/auth/dto.ts +++ b/apps/api/src/auth/dto.ts @@ -27,12 +27,15 @@ export const refreshSchema = z.object({ refreshToken: opaque }).strict(); export const desktopTokenSchema = z.object({ code: opaque, codeVerifier: opaque }).strict(); export const desktopCodeSchema = z - .object({ code_challenge: z.string().refine(isValidCodeChallenge, 'invalid code_challenge') }) + .object({ + code_challenge: z.string().refine(isValidCodeChallenge, 'invalid code_challenge'), + client: z.enum(['desktop', 'desktop-dev']).default('desktop'), + }) .strict(); // Query strings are not strict: providers append their own parameters. export const startQuerySchema = z.object({ - client: z.enum(['web', 'desktop']).default('web'), + client: z.enum(['web', 'desktop', 'desktop-dev']).default('web'), code_challenge: z.string().refine(isValidCodeChallenge, 'invalid code_challenge').optional(), }); diff --git a/apps/server/src/auth/http-config.ts b/apps/api/src/auth/http-config.ts similarity index 100% rename from apps/server/src/auth/http-config.ts rename to apps/api/src/auth/http-config.ts diff --git a/apps/server/src/auth/keys.ts b/apps/api/src/auth/keys.ts similarity index 100% rename from apps/server/src/auth/keys.ts rename to apps/api/src/auth/keys.ts diff --git a/apps/server/src/auth/oauth-provider.ts b/apps/api/src/auth/oauth-provider.ts similarity index 100% rename from apps/server/src/auth/oauth-provider.ts rename to apps/api/src/auth/oauth-provider.ts diff --git a/apps/server/src/auth/oauth.service.ts b/apps/api/src/auth/oauth.service.ts similarity index 92% rename from apps/server/src/auth/oauth.service.ts rename to apps/api/src/auth/oauth.service.ts index 1ce93f8..9c19c47 100644 --- a/apps/server/src/auth/oauth.service.ts +++ b/apps/api/src/auth/oauth.service.ts @@ -10,7 +10,7 @@ import { NotFoundException, } from '@nestjs/common'; -import type { UserId } from '../domain'; +import type { UserId } from '@opencollab/domain'; import { AuthRepository, isUniqueViolation } from '../persistence/auth.repository'; import { UserRepository, type UserRecord } from '../persistence/user.repository'; import { AuthService, toUserView, type AuthResult } from './auth.service'; @@ -32,6 +32,7 @@ import { pickAvailableUsername, sanitizeUsername } from './username'; export const DESKTOP_CODE_TTL_MS = 60_000; export const DESKTOP_CALLBACK = 'opencollab://auth/callback'; +export const DESKTOP_DEV_CALLBACK = 'opencollab-dev://auth/callback'; /** A provider authorization URL plus the Set-Cookie that binds the flow to this browser. */ export interface FlowStart { @@ -141,15 +142,16 @@ export class OAuthService { return { url, setCookie: setCookie(flow, bindingValue, this.secure) }; } - start(name: string, client: 'web' | 'desktop', codeChallenge?: string): FlowStart { + start(name: string, client: 'web' | 'desktop' | 'desktop-dev', codeChallenge?: string): FlowStart { const provider = this.provider(name); - if (client === 'desktop' && !codeChallenge) { + const isDesktop = client === 'desktop' || client === 'desktop-dev'; + if (isDesktop && !codeChallenge) { throw new BadRequestException('code_challenge is required for the desktop client'); } return this.authorizationUrl(provider, { intent: 'login', client, - ...(client === 'desktop' ? { codeChallenge } : {}), + ...(isDesktop ? { codeChallenge } : {}), }); } @@ -201,8 +203,11 @@ export class OAuthService { if (state.intent === 'link') return this.link(provider, state, profile); const user = await this.resolveUser(provider, profile); - if (state.client === 'desktop') { - return { kind: 'desktop', redirectUrl: await this.issueDesktopCode(user.id, state.codeChallenge ?? '') }; + if (state.client === 'desktop' || state.client === 'desktop-dev') { + return { + kind: 'desktop', + redirectUrl: await this.issueDesktopCode(user.id, state.codeChallenge ?? '', state.client), + }; } return { kind: 'login', result: await this.authService.start(user, userAgent) }; } @@ -284,7 +289,11 @@ export class OAuthService { * the deep link that carries it. Shared by the OAuth desktop flow and by * `POST /auth/desktop/code` (an already authenticated web session). */ - async issueDesktopCode(userId: UserId, codeChallenge: string): Promise { + async issueDesktopCode( + userId: UserId, + codeChallenge: string, + client: 'desktop' | 'desktop-dev' = 'desktop', + ): Promise { const code = generateToken(); await this.auth.insertDesktopCode({ codeHash: hashToken(code), @@ -292,7 +301,8 @@ export class OAuthService { codeChallenge, expiresAt: new Date(this.clock.now().getTime() + DESKTOP_CODE_TTL_MS), }); - return `${DESKTOP_CALLBACK}?code=${encodeURIComponent(code)}`; + const callback = client === 'desktop-dev' ? DESKTOP_DEV_CALLBACK : DESKTOP_CALLBACK; + return `${callback}?code=${encodeURIComponent(code)}`; } /** Any attempt burns the code first, so a wrong verifier cannot be retried. */ diff --git a/apps/server/src/auth/password.service.ts b/apps/api/src/auth/password.service.ts similarity index 100% rename from apps/server/src/auth/password.service.ts rename to apps/api/src/auth/password.service.ts diff --git a/apps/server/src/auth/providers.spec.ts b/apps/api/src/auth/providers.spec.ts similarity index 100% rename from apps/server/src/auth/providers.spec.ts rename to apps/api/src/auth/providers.spec.ts diff --git a/apps/server/src/auth/providers.ts b/apps/api/src/auth/providers.ts similarity index 100% rename from apps/server/src/auth/providers.ts rename to apps/api/src/auth/providers.ts diff --git a/apps/server/src/auth/refresh-policy.spec.ts b/apps/api/src/auth/refresh-policy.spec.ts similarity index 100% rename from apps/server/src/auth/refresh-policy.spec.ts rename to apps/api/src/auth/refresh-policy.spec.ts diff --git a/apps/server/src/auth/refresh-policy.ts b/apps/api/src/auth/refresh-policy.ts similarity index 100% rename from apps/server/src/auth/refresh-policy.ts rename to apps/api/src/auth/refresh-policy.ts diff --git a/apps/server/src/auth/session-revocations.ts b/apps/api/src/auth/session-revocations.ts similarity index 100% rename from apps/server/src/auth/session-revocations.ts rename to apps/api/src/auth/session-revocations.ts diff --git a/apps/server/src/auth/session.service.spec.ts b/apps/api/src/auth/session.service.spec.ts similarity index 99% rename from apps/server/src/auth/session.service.spec.ts rename to apps/api/src/auth/session.service.spec.ts index 743cc0c..a5d40be 100644 --- a/apps/server/src/auth/session.service.spec.ts +++ b/apps/api/src/auth/session.service.spec.ts @@ -1,7 +1,7 @@ import jwt from 'jsonwebtoken'; import { describe, expect, it } from 'vitest'; -import { newUserId } from '../domain'; +import { newUserId } from '@opencollab/domain'; import type { AuthRepository, RefreshRow } from '../persistence/auth.repository'; import type { Clock } from './clock'; import type { AuthConfig } from './config'; diff --git a/apps/server/src/auth/session.service.ts b/apps/api/src/auth/session.service.ts similarity index 99% rename from apps/server/src/auth/session.service.ts rename to apps/api/src/auth/session.service.ts index e2facfb..aa1e67b 100644 --- a/apps/server/src/auth/session.service.ts +++ b/apps/api/src/auth/session.service.ts @@ -3,7 +3,7 @@ import { randomUUID } from 'node:crypto'; import { Inject, Injectable, UnauthorizedException } from '@nestjs/common'; import jwt from 'jsonwebtoken'; -import type { UserId } from '../domain'; +import type { UserId } from '@opencollab/domain'; import { AuthRepository, type NewRefreshToken } from '../persistence/auth.repository'; import { CLOCK, type Clock } from './clock'; import { AUTH_CONFIG, type AuthConfig } from './config'; diff --git a/apps/server/src/auth/state.spec.ts b/apps/api/src/auth/state.spec.ts similarity index 75% rename from apps/server/src/auth/state.spec.ts rename to apps/api/src/auth/state.spec.ts index 408434f..817885e 100644 --- a/apps/server/src/auth/state.spec.ts +++ b/apps/api/src/auth/state.spec.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from 'vitest'; +import { desktopCodeSchema, startQuerySchema } from './dto'; import { STATE_TTL_SECONDS, pkceVerifierFor, signState, verifyState, type OAuthState } from './state'; const secret = 'test-secret-test-secret-test-secret-1234'; @@ -53,3 +54,14 @@ describe('pkceVerifierFor', () => { expect(v).toMatch(/^[A-Za-z0-9_-]{43,128}$/); }); }); + +describe('desktop client schemas', () => { + const challenge = 'A'.repeat(43); + + it('accepts both desktop and desktop-dev in startQuerySchema and desktopCodeSchema', () => { + expect(startQuerySchema.parse({ client: 'desktop', code_challenge: challenge }).client).toBe('desktop'); + expect(startQuerySchema.parse({ client: 'desktop-dev', code_challenge: challenge }).client).toBe('desktop-dev'); + expect(desktopCodeSchema.parse({ code_challenge: challenge }).client).toBe('desktop'); + expect(desktopCodeSchema.parse({ code_challenge: challenge, client: 'desktop-dev' }).client).toBe('desktop-dev'); + }); +}); diff --git a/apps/server/src/auth/state.ts b/apps/api/src/auth/state.ts similarity index 98% rename from apps/server/src/auth/state.ts rename to apps/api/src/auth/state.ts index e311692..414a327 100644 --- a/apps/server/src/auth/state.ts +++ b/apps/api/src/auth/state.ts @@ -8,7 +8,7 @@ import type { ProviderName } from './oauth-provider'; export interface OAuthState { provider: ProviderName; intent: 'login' | 'link'; - client: 'web' | 'desktop'; + client: 'web' | 'desktop' | 'desktop-dev'; /** Random per flow; also derives the provider-side PKCE verifier. */ nonce: string; /** Random per flow; names the browser-binding cookie so parallel flows do not clash. */ diff --git a/apps/server/src/auth/test-app.ts b/apps/api/src/auth/test-app.ts similarity index 100% rename from apps/server/src/auth/test-app.ts rename to apps/api/src/auth/test-app.ts diff --git a/apps/server/src/auth/tokens.spec.ts b/apps/api/src/auth/tokens.spec.ts similarity index 100% rename from apps/server/src/auth/tokens.spec.ts rename to apps/api/src/auth/tokens.spec.ts diff --git a/apps/server/src/auth/tokens.ts b/apps/api/src/auth/tokens.ts similarity index 100% rename from apps/server/src/auth/tokens.ts rename to apps/api/src/auth/tokens.ts diff --git a/apps/server/src/auth/username.spec.ts b/apps/api/src/auth/username.spec.ts similarity index 100% rename from apps/server/src/auth/username.spec.ts rename to apps/api/src/auth/username.spec.ts diff --git a/apps/server/src/auth/username.ts b/apps/api/src/auth/username.ts similarity index 100% rename from apps/server/src/auth/username.ts rename to apps/api/src/auth/username.ts diff --git a/apps/server/src/auth/web-session.spec.ts b/apps/api/src/auth/web-session.spec.ts similarity index 100% rename from apps/server/src/auth/web-session.spec.ts rename to apps/api/src/auth/web-session.spec.ts diff --git a/apps/server/src/auth/web-session.ts b/apps/api/src/auth/web-session.ts similarity index 100% rename from apps/server/src/auth/web-session.ts rename to apps/api/src/auth/web-session.ts diff --git a/apps/server/src/collab.gateway.spec.ts b/apps/api/src/collab.gateway.spec.ts similarity index 99% rename from apps/server/src/collab.gateway.spec.ts rename to apps/api/src/collab.gateway.spec.ts index ca2bc38..642c9b6 100644 --- a/apps/server/src/collab.gateway.spec.ts +++ b/apps/api/src/collab.gateway.spec.ts @@ -9,7 +9,7 @@ import WebSocket from 'ws'; import { SessionRevocations } from './auth/session-revocations'; import { SessionService } from './auth/session.service'; import { CollabGateway } from './collab.gateway'; -import { Session, Workspace, newAgentProfile, newUserId, type SessionId, type UserId } from './domain'; +import { Session, Workspace, newAgentProfile, newUserId, type SessionId, type UserId } from '@opencollab/domain'; import { SESSION_STORE, SessionHub, type SessionStore } from './hub'; import { ConnectionDeadline, TOKEN_GRACE_MS } from './connection-deadline'; import { @@ -17,7 +17,7 @@ import { HEARTBEAT_INTERVAL_MS, MAX_BUFFERED_BYTES, } from './connection-policy'; -import { FORBIDDEN, NOT_JOINED, UNAUTHORIZED } from './protocol'; +import { FORBIDDEN, NOT_JOINED, UNAUTHORIZED } from '@opencollab/contracts'; const frame = (message: object): string => JSON.stringify({ version: 1, message }); diff --git a/apps/server/src/collab.gateway.ts b/apps/api/src/collab.gateway.ts similarity index 100% rename from apps/server/src/collab.gateway.ts rename to apps/api/src/collab.gateway.ts diff --git a/apps/api/src/collab/collab.module.ts b/apps/api/src/collab/collab.module.ts new file mode 100644 index 0000000..92d906e --- /dev/null +++ b/apps/api/src/collab/collab.module.ts @@ -0,0 +1,19 @@ +import { Module } from '@nestjs/common'; + +import { AuthModule } from '../auth/auth.module'; +import { PersistenceModule } from '../persistence/persistence.module'; +import { InvitationsController } from './invitations.controller'; +import { InvitationsService } from './invitations.service'; +import { SessionService } from './session.service'; +import { SessionsController } from './sessions.controller'; +import { TerminalsController } from './terminals.controller'; +import { WorkspacesController } from './workspaces.controller'; +import { WorkspaceService } from './workspace.service'; + +@Module({ + imports: [PersistenceModule, AuthModule], + controllers: [WorkspacesController, SessionsController, TerminalsController, InvitationsController], + providers: [WorkspaceService, SessionService, InvitationsService], + exports: [WorkspaceService, SessionService, InvitationsService], +}) +export class CollabModule {} diff --git a/apps/api/src/collab/domain-errors.ts b/apps/api/src/collab/domain-errors.ts new file mode 100644 index 0000000..5b44252 --- /dev/null +++ b/apps/api/src/collab/domain-errors.ts @@ -0,0 +1,26 @@ +import { DomainError } from '@opencollab/domain'; + +// S15: maps a caught domain error to the HTTP-equivalent result kind. The +// controller turns each kind into its Nest exception; anything that is not a +// DomainError is rethrown unchanged and becomes a 500. +export type DomainViolation = 'forbidden' | 'conflict' | 'not-found' | 'bad-request'; + +export function domainViolation(error: unknown): DomainViolation { + if (error instanceof DomainError) { + switch (error.code) { + case 'NotOwner': + case 'NotAParticipant': + return 'forbidden'; + case 'AlreadyHasAccess': + case 'InvitationTargetMismatch': + case 'CannotChangeOwnerAccess': + return 'conflict'; + case 'TerminalNotInSession': + case 'WorkspaceMismatch': + return 'not-found'; + case 'EmptyCommand': + return 'bad-request'; + } + } + throw error; +} diff --git a/apps/api/src/collab/dto.ts b/apps/api/src/collab/dto.ts new file mode 100644 index 0000000..680f69b --- /dev/null +++ b/apps/api/src/collab/dto.ts @@ -0,0 +1,100 @@ +import { z } from 'zod'; + +// The uuid message names the rule, never the submitted value (S14: ZodPipe +// only emits field paths and messages). +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + +// Explicit ids are uuids, normalized to lowercase so the same id string always +// matches the same row regardless of the casing the client chose. +function uuidId() { + return z.string().regex(UUID, { message: 'must be a uuid' }).transform((value) => value.toLowerCase()); +} + +// `.strict()` everywhere: unknown fields are rejected, not silently dropped. +export const createWorkspaceSchema = z + .object({ + name: z.string().trim().min(1).max(100), + // S7: an explicit uuid makes the create idempotent for its owner. + id: uuidId().optional(), + }) + .strict(); + +export type CreateWorkspaceBody = z.infer; + +// Session name follows the same rule as the workspace name (S4). +export const createSessionSchema = z + .object({ + name: z.string().trim().min(1).max(100), + id: uuidId().optional(), + }) + .strict(); + +export type CreateSessionBody = z.infer; + +// S7 body. `env` is deliberately absent: the strict schema rejects it, so a +// client can never smuggle secrets into a terminal profile. `command` cannot +// be blank (domain EmptyCommand) but keeps the caller's exact spacing; the +// blank check does not echo the submitted value (S14). +export const addTerminalSchema = z + .object({ + id: uuidId().optional(), + name: z.string(), + command: z.string().refine((value) => value.trim() !== '', { message: 'command must not be blank' }), + args: z.array(z.string()).optional(), + cwd: z.string().nullable().optional(), + // Snapshot metadata: which agent the pane launches (null = plain shell). + agent: z.string().nullable().optional(), + minimized: z.boolean().optional(), + }) + .strict(); + +export type AddTerminalBody = z.infer; + +// S7 bodies. Rename is a rename: `name` is required. The terminal patch is +// partial — absent keys keep the current value, null clears `cwd`/`agent`. +export const renameWorkspaceSchema = z + .object({ name: z.string().trim().min(1).max(100) }) + .strict(); + +export type RenameWorkspaceBody = z.infer; + +export const renameSessionSchema = z + .object({ name: z.string().trim().min(1).max(100) }) + .strict(); + +export type RenameSessionBody = z.infer; + +export const updateTerminalSchema = z + .object({ + name: z.string().optional(), + command: z + .string() + .refine((value) => value.trim() !== '', { message: 'command must not be blank' }) + .optional(), + args: z.array(z.string()).optional(), + cwd: z.string().nullable().optional(), + agent: z.string().nullable().optional(), + minimized: z.boolean().optional(), + }) + .strict(); + +export type UpdateTerminalBody = z.infer; + +export const reorderTerminalsSchema = z + .object({ ids: z.array(uuidId()) }) + .strict(); + +export type ReorderTerminalsBody = z.infer; + +// S9/S10 body. +export const inviteSchema = z + .object({ inviteeId: z.string().regex(UUID, { message: 'must be a uuid' }) }) + .strict(); + +export type InviteBody = z.infer; + +// Malformed invitation ids answer 404, never 500: Postgres uuid columns throw +// on non-uuid input, so the format is pre-checked before Prisma sees it. +export function isUuid(value: string): boolean { + return UUID.test(value); +} diff --git a/apps/api/src/collab/invitations.controller.int.spec.ts b/apps/api/src/collab/invitations.controller.int.spec.ts new file mode 100644 index 0000000..1afb654 --- /dev/null +++ b/apps/api/src/collab/invitations.controller.int.spec.ts @@ -0,0 +1,554 @@ +import { randomUUID } from 'node:crypto'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import type { InvitationId, UserId, WorkspaceId } from '@opencollab/domain'; +import { InvitationRepository } from '../persistence/invitation.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let workspaces: WorkspaceRepository; +let invitations: InvitationRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + workspaces = new WorkspaceRepository(t.prisma); + invitations = new InvitationRepository(t.prisma); +}); +afterAll(() => t.close()); +beforeEach(() => truncateAll(t.prisma)); + +interface Res { + status: number; + body: unknown; +} + +async function call(method: string, path: string, body?: unknown, token?: string): Promise { + const res = await fetch(`${t.baseUrl}${path}`, { + method, + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + let parsed: unknown = undefined; + try { + parsed = text ? JSON.parse(text) : undefined; + } catch { + parsed = text; + } + return { status: res.status, body: parsed }; +} + +const get = (path: string, token?: string) => call('GET', path, undefined, token); +const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); +const postEmpty = (path: string, token?: string) => call('POST', path, undefined, token); + +let counter = 0; +async function registerUser(prefix = 'user'): Promise<{ id: string; token: string; username: string }> { + counter += 1; + const username = `${prefix}${counter}`; + const res = await post('/auth/register', { + username, + password: 'correct horse battery', + displayName: prefix, + }); + expect(res.status).toBe(201); + const body = res.body as { accessToken: string; user: { id: string } }; + return { id: body.user.id, token: body.accessToken, username }; +} + +async function seedWorkspace(ownerToken: string, name = 'ws'): Promise<{ id: string }> { + const res = await post('/workspaces', { name }, ownerToken); + expect(res.status).toBe(201); + return res.body as { id: string }; +} + +async function seedSession(ownerToken: string, wsId: string, name = 'sess'): Promise<{ id: string }> { + const res = await post(`/workspaces/${wsId}/sessions`, { name }, ownerToken); + expect(res.status).toBe(201); + return res.body as { id: string }; +} + +// Seeds a member straight through the repository: no endpoint exists for it. +async function seedMember(workspaceId: WorkspaceId, ownerId: UserId, memberId: UserId): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + ws!.addMember(ownerId, memberId); + await workspaces.save(ws!); +} + +// Seeds an already-expired invitation straight through the repository: the API +// never creates expiring invitations, so expiry can only be set up this way. +async function seedExpiredWorkspaceInvitation( + workspaceId: WorkspaceId, + ownerId: UserId, + inviteeId: UserId, +): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + const invitation = ws!.inviteMember(ownerId, inviteeId); + await invitations.save(invitation, new Date(Date.now() - 60_000)); + return invitation.id; +} + +type InvitationBody = { + id: string; + target: + | { kind: 'workspace'; workspaceId: string; name: string } + | { kind: 'session'; sessionId: string; name: string }; + invitedBy: { userId: string; username: string; displayName: string }; +}; + +const UNKNOWN_ID = '00000000-0000-0000-0000-000000000000'; + +describe('POST /workspaces/:id/invitations (S9)', () => { + it('invites a user as member and returns the invitation view (201)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token, 'team'); + + const res = await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as InvitationBody; + expect(Object.keys(body).sort()).toEqual(['id', 'invitedBy', 'target']); + expect(body.target).toEqual({ kind: 'workspace', workspaceId: ws.id, name: 'team' }); + expect(body.invitedBy).toEqual({ + userId: owner.id, + username: owner.username, + displayName: 'owner', + }); + + // The invitation is stored as pending. + const stored = await invitations.find(body.id as InvitationId); + expect(stored?.status).toBe('pending'); + expect(stored?.invitation.invitee).toBe(invitee.id); + }); + + it('returns 404 for an unknown workspace, 403 for member and stranger, 401 without token', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const stranger = await registerUser('stranger'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + expect( + (await post(`/workspaces/${UNKNOWN_ID}/invitations`, { inviteeId: invitee.id }, owner.token)).status, + ).toBe(404); + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, member.token)).status, + ).toBe(403); + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, stranger.token)).status, + ).toBe(403); + expect((await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id })).status).toBe(401); + expect((await post(`/workspaces/${UNKNOWN_ID}/invitations`, { inviteeId: invitee.id })).status).toBe( + 401, + ); + }); + + it('returns 409 when the invitee is already the owner or a member', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const ws = await seedWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: owner.id }, owner.token)).status, + ).toBe(409); + expect( + (await post(`/workspaces/${ws.id}/invitations`, { inviteeId: member.id }, owner.token)).status, + ).toBe(409); + }); + + it('returns 404 for a ghost invitee (well-formed UUID of a nonexistent user) and stores nothing', async () => { + const owner = await registerUser('owner'); + const ws = await seedWorkspace(owner.token); + const ghost = randomUUID(); + + const res = await post(`/workspaces/${ws.id}/invitations`, { inviteeId: ghost }, owner.token); + expect(res.status).toBe(404); + + // Nothing was stored: the ghost has no pending invitation. + expect(await invitations.listPendingFor(ghost as UserId)).toEqual([]); + }); + + it('rejects invalid bodies with 400 without echoing submitted values (S14)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const path = `/workspaces/${ws.id}/invitations`; + + expect((await post(path, {}, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: 42 }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: null }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: 'not-a-uuid' }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: invitee.id, extra: true }, owner.token)).status).toBe(400); + + // Field path only: the submitted value must never appear in the response. + const leaked = 'definitely-not-a-user-zzz'; + const res = await post(path, { inviteeId: leaked }, owner.token); + expect(res.status).toBe(400); + expect(JSON.stringify(res.body)).not.toContain(leaked); + expect(JSON.stringify(res.body)).toContain('inviteeId'); + }); +}); + +describe('POST /sessions/:id/invitations (S10)', () => { + it('invites a user as guest and returns the session-target view (201)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token, 'team'); + const session = await seedSession(owner.token, ws.id, 'standup'); + + const res = await post(`/sessions/${session.id}/invitations`, { inviteeId: invitee.id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as InvitationBody; + expect(Object.keys(body).sort()).toEqual(['id', 'invitedBy', 'target']); + expect(body.target).toEqual({ kind: 'session', sessionId: session.id, name: 'standup' }); + expect(body.invitedBy.userId).toBe(owner.id); + }); + + it('returns 404 for an unknown session or a vanished workspace; 403 for member, stranger and guest; 401 without token', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const stranger = await registerUser('stranger'); + const guest = await registerUser('guest'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + // Guest role via the invitations flow itself. + const guestInvite = await post( + `/sessions/${session.id}/invitations`, + { inviteeId: guest.id }, + owner.token, + ); + expect(guestInvite.status).toBe(201); + expect( + (await postEmpty(`/invitations/${(guestInvite.body as InvitationBody).id}/accept`, guest.token)).status, + ).toBe(204); + + const path = `/sessions/${session.id}/invitations`; + expect((await post(path, { inviteeId: invitee.id }, member.token)).status).toBe(403); + expect((await post(path, { inviteeId: invitee.id }, stranger.token)).status).toBe(403); + expect((await post(path, { inviteeId: invitee.id }, guest.token)).status).toBe(403); + expect((await post(`/sessions/${UNKNOWN_ID}/invitations`, { inviteeId: invitee.id }, owner.token)).status).toBe( + 404, + ); + // A ghost invitee (unknown user id) is 404 on the session path too. + expect((await post(path, { inviteeId: randomUUID() }, owner.token)).status).toBe(404); + expect((await post(path, { inviteeId: invitee.id })).status).toBe(401); + + // A session whose workspace is gone is 404 (workspaces cascade to sessions). + await t.prisma.workspace.delete({ where: { id: ws.id } }); + expect((await post(path, { inviteeId: invitee.id }, owner.token)).status).toBe(404); + }); + + it('returns 409 when the invitee already has a role (owner, member, guest)', async () => { + const owner = await registerUser('owner'); + const member = await registerUser('member'); + const guest = await registerUser('guest'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const path = `/sessions/${session.id}/invitations`; + + expect((await post(path, { inviteeId: owner.id }, owner.token)).status).toBe(409); + expect((await post(path, { inviteeId: member.id }, owner.token)).status).toBe(409); + + const created = (await post(path, { inviteeId: guest.id }, owner.token)).body as InvitationBody; + expect((await postEmpty(`/invitations/${created.id}/accept`, guest.token)).status).toBe(204); + expect((await post(path, { inviteeId: guest.id }, owner.token)).status).toBe(409); + }); + + it('rejects invalid bodies with 400 without echoing submitted values (S14)', async () => { + const owner = await registerUser('owner'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + const path = `/sessions/${session.id}/invitations`; + + expect((await post(path, {}, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: 'not-a-uuid' }, owner.token)).status).toBe(400); + expect((await post(path, { inviteeId: randomUUID(), extra: 1 }, owner.token)).status).toBe(400); + + const leaked = 'definitely-not-a-user-zzz'; + const res = await post(path, { inviteeId: leaked }, owner.token); + expect(res.status).toBe(400); + expect(JSON.stringify(res.body)).not.toContain(leaked); + expect(JSON.stringify(res.body)).toContain('inviteeId'); + }); +}); + +describe('GET /invitations (S11)', () => { + it('lists the caller pending invitations with target and inviter (200)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token, 'team'); + const session = await seedSession(owner.token, ws.id, 'standup'); + + const wsInvite = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + const sessionInvite = ( + await post(`/sessions/${session.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + const res = await get('/invitations', invitee.token); + expect(res.status).toBe(200); + const list = res.body as InvitationBody[]; + expect(list).toHaveLength(2); + const byId = new Map(list.map((entry) => [entry.id, entry])); + expect(byId.get(wsInvite.id)?.target).toEqual({ + kind: 'workspace', + workspaceId: ws.id, + name: 'team', + }); + expect(byId.get(sessionInvite.id)?.target).toEqual({ + kind: 'session', + sessionId: session.id, + name: 'standup', + }); + for (const entry of list) { + expect(entry.invitedBy).toEqual({ + userId: owner.id, + username: owner.username, + displayName: 'owner', + }); + } + + // Another user sees none of them. + expect(((await get('/invitations', owner.token)).body as unknown[])).toEqual([]); + }); + + it('excludes declined, accepted and expired invitations from the list', async () => { + const owner = await registerUser('owner'); + const declined = await registerUser('declined'); + const accepted = await registerUser('accepted'); + const expired = await registerUser('expired'); + const ws = await seedWorkspace(owner.token); + + const declinedId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: declined.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${declinedId.id}/decline`, declined.token)).status).toBe(204); + + const acceptedId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: accepted.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${acceptedId.id}/accept`, accepted.token)).status).toBe(204); + + await seedExpiredWorkspaceInvitation(ws.id as WorkspaceId, owner.id as UserId, expired.id as UserId); + + expect(((await get('/invitations', declined.token)).body as unknown[])).toEqual([]); + expect(((await get('/invitations', accepted.token)).body as unknown[])).toEqual([]); + expect(((await get('/invitations', expired.token)).body as unknown[])).toEqual([]); + }); + + it('hides entries whose target aggregate no longer exists', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token); + expect(((await get('/invitations', invitee.token)).body as unknown[])).toHaveLength(1); + + // Workspaces cascade to their invitations, so the entry disappears with it. + await t.prisma.workspace.delete({ where: { id: ws.id } }); + expect(((await get('/invitations', invitee.token)).body as unknown[])).toEqual([]); + }); + + it('requires auth (401)', async () => { + expect((await get('/invitations')).status).toBe(401); + }); +}); + +describe('POST /invitations/:id/accept (S12)', () => { + it('workspace invitee accepts (204), becomes a member, invitation marked accepted', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + const res = await postEmpty(`/invitations/${created.id}/accept`, invitee.token); + expect(res.status).toBe(204); + expect(res.body).toBeUndefined(); + + // Membership applied: the invitee now sees the workspace detail as a member. + const detail = (await get(`/workspaces/${ws.id}`, invitee.token)).body as { + members: { userId: string }[]; + }; + expect(detail.members.map((m) => m.userId)).toContain(invitee.id); + + // Invitation marked accepted (S15: aggregate change and status stay together). + expect((await invitations.find(created.id as InvitationId))?.status).toBe('accepted'); + }); + + it('session invitee accepts (204) and can then view the session', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const stranger = await registerUser('stranger'); + const ws = await seedWorkspace(owner.token); + const session = await seedSession(owner.token, ws.id); + expect((await get(`/sessions/${session.id}`, invitee.token)).status).toBe(403); + + const created = ( + await post(`/sessions/${session.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(204); + expect((await get(`/sessions/${session.id}`, invitee.token)).status).toBe(200); + expect((await get(`/sessions/${session.id}`, stranger.token)).status).toBe(403); + }); + + it('returns 404 for unknown and malformed ids (never 500)', async () => { + const user = await registerUser('user'); + expect((await postEmpty(`/invitations/${UNKNOWN_ID}/accept`, user.token)).status).toBe(404); + expect((await postEmpty('/invitations/not-a-uuid/accept', user.token)).status).toBe(404); + }); + + it('returns 403 for non-invitees before any status signal (no leak)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const stranger = await registerUser('stranger'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + // Pending invitation, stranger probes: 403, not 404/409. + expect((await postEmpty(`/invitations/${created.id}/accept`, stranger.token)).status).toBe(403); + expect((await postEmpty(`/invitations/${created.id}/decline`, stranger.token)).status).toBe(403); + + // After the invitee accepts, the stranger still gets 403 (no status leak). + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${created.id}/accept`, stranger.token)).status).toBe(403); + expect((await postEmpty(`/invitations/${created.id}/accept`, owner.token)).status).toBe(403); + }); + + it('returns 409 for already-responded and expired invitations without changing them', async () => { + const owner = await registerUser('owner'); + const twice = await registerUser('twice'); + const declined = await registerUser('declined'); + const expired = await registerUser('expired'); + const ws = await seedWorkspace(owner.token); + + const twiceId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: twice.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${twiceId.id}/accept`, twice.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${twiceId.id}/accept`, twice.token)).status).toBe(409); + expect((await invitations.find(twiceId.id as InvitationId))?.status).toBe('accepted'); + + const declinedId = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: declined.id }, owner.token) + ).body as InvitationBody; + expect((await postEmpty(`/invitations/${declinedId.id}/decline`, declined.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${declinedId.id}/accept`, declined.token)).status).toBe(409); + expect((await invitations.find(declinedId.id as InvitationId))?.status).toBe('declined'); + + const expiredId = await seedExpiredWorkspaceInvitation( + ws.id as WorkspaceId, + owner.id as UserId, + expired.id as UserId, + ); + expect((await postEmpty(`/invitations/${expiredId}/accept`, expired.token)).status).toBe(409); + expect((await invitations.find(expiredId as InvitationId))?.status).toBe('pending'); + }); + + it('returns 409 and leaves the invitation pending when the invitee is already a member (failed accept never applies)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + // The invitee gains membership through another path before accepting. + await seedMember(ws.id as WorkspaceId, owner.id as UserId, invitee.id as UserId); + + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(409); + // A failed accept never marks the invitation accepted (S15). + expect((await invitations.find(created.id as InvitationId))?.status).toBe('pending'); + }); + + it('returns 404 when the target aggregate is gone', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + await t.prisma.workspace.delete({ where: { id: ws.id } }); + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(404); + }); + + it('requires auth (401)', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + expect((await postEmpty(`/invitations/${created.id}/accept`)).status).toBe(401); + expect((await postEmpty('/invitations/not-a-uuid/accept')).status).toBe(401); + }); +}); + +describe('POST /invitations/:id/decline (S13)', () => { + it('invitee declines (204): invitation marked declined and hidden from the list', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + expect(((await get('/invitations', invitee.token)).body as unknown[])).toHaveLength(1); + + const res = await postEmpty(`/invitations/${created.id}/decline`, invitee.token); + expect(res.status).toBe(204); + expect(res.body).toBeUndefined(); + expect((await invitations.find(created.id as InvitationId))?.status).toBe('declined'); + expect(((await get('/invitations', invitee.token)).body as unknown[])).toEqual([]); + + // Declining grants nothing: the invitee still cannot see the workspace. + expect((await get(`/workspaces/${ws.id}`, invitee.token)).status).toBe(403); + }); + + it('returns 409 on double decline and on accept-after-decline', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + expect((await postEmpty(`/invitations/${created.id}/decline`, invitee.token)).status).toBe(204); + expect((await postEmpty(`/invitations/${created.id}/decline`, invitee.token)).status).toBe(409); + expect((await postEmpty(`/invitations/${created.id}/accept`, invitee.token)).status).toBe(409); + expect((await invitations.find(created.id as InvitationId))?.status).toBe('declined'); + }); + + it('returns 403 for non-invitees, 404 for unknown/malformed ids, 401 without token', async () => { + const owner = await registerUser('owner'); + const invitee = await registerUser('invitee'); + const stranger = await registerUser('stranger'); + const ws = await seedWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id }, owner.token) + ).body as InvitationBody; + + expect((await postEmpty(`/invitations/${created.id}/decline`, stranger.token)).status).toBe(403); + expect((await postEmpty(`/invitations/${UNKNOWN_ID}/decline`, invitee.token)).status).toBe(404); + expect((await postEmpty('/invitations/not-a-uuid/decline', invitee.token)).status).toBe(404); + expect((await postEmpty(`/invitations/${created.id}/decline`)).status).toBe(401); + expect((await get('/invitations')).status).toBe(401); + expect((await post(`/workspaces/${ws.id}/invitations`, { inviteeId: invitee.id })).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/invitations.controller.ts b/apps/api/src/collab/invitations.controller.ts new file mode 100644 index 0000000..cfce725 --- /dev/null +++ b/apps/api/src/collab/invitations.controller.ts @@ -0,0 +1,90 @@ +import { + Body, + ConflictException, + Controller, + ForbiddenException, + Get, + HttpCode, + Inject, + NotFoundException, + Param, + Post, + UseGuards, +} from '@nestjs/common'; + +import type { SessionId, UserId, WorkspaceId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { inviteSchema, type InviteBody } from './dto'; +import { InvitationsService } from './invitations.service'; + +@Controller() +@UseGuards(AccessGuard) +export class InvitationsController { + constructor(@Inject(InvitationsService) private readonly service: InvitationsService) {} + + // S9: owner invites a workspace member; 201 with the invitation view. + @Post('workspaces/:id/invitations') + @HttpCode(201) + async inviteToWorkspace( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(inviteSchema)) body: InviteBody, + ) { + const result = await this.service.inviteToWorkspace( + user.id, + id as WorkspaceId, + body.inviteeId as UserId, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + return result.view; + } + + // S10: owner invites a session guest; 201 with the invitation view. + @Post('sessions/:id/invitations') + @HttpCode(201) + async inviteToSession( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(inviteSchema)) body: InviteBody, + ) { + const result = await this.service.inviteToSession( + user.id, + id as SessionId, + body.inviteeId as UserId, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + return result.view; + } + + // S11: the caller's pending, non-expired invitations. + @Get('invitations') + async list(@CurrentUser() user: UserRecord) { + return this.service.list(user.id); + } + + // S12: only the invitee may accept; 204 with no body. + @Post('invitations/:id/accept') + @HttpCode(204) + async accept(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.accept(user.id, id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + } + + // S13: only the invitee may decline; 204 with no body. + @Post('invitations/:id/decline') + @HttpCode(204) + async decline(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.decline(user.id, id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + } +} diff --git a/apps/api/src/collab/invitations.service.ts b/apps/api/src/collab/invitations.service.ts new file mode 100644 index 0000000..f54a61a --- /dev/null +++ b/apps/api/src/collab/invitations.service.ts @@ -0,0 +1,243 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import type { + Invitation, + InvitationId, + SessionId, + UserId, + WorkspaceId, +} from '@opencollab/domain'; +import { InvitationRepository, type StoredInvitation } from '../persistence/invitation.repository'; +import { SessionRepository } from '../persistence/session.repository'; +import { UserRepository } from '../persistence/user.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { domainViolation } from './domain-errors'; +import { isUuid } from './dto'; +import type { InvitationView } from './views'; + +export type InvitationCreateResult = + | { kind: 'created'; view: InvitationView } + | { kind: 'not-found' } + | { kind: 'forbidden' } + | { kind: 'conflict' }; + +export type InvitationRespondResult = + | { kind: 'ok' } + | { kind: 'not-found' } + | { kind: 'forbidden' } + | { kind: 'conflict' }; + +type ResponseLookup = + | { kind: 'ok'; stored: StoredInvitation } + | { kind: 'not-found' } + | { kind: 'forbidden' } + | { kind: 'conflict' }; + +@Injectable() +export class InvitationsService { + constructor( + @Inject(WorkspaceRepository) private readonly workspaces: WorkspaceRepository, + @Inject(SessionRepository) private readonly sessions: SessionRepository, + @Inject(UserRepository) private readonly users: UserRepository, + @Inject(InvitationRepository) private readonly invitations: InvitationRepository, + ) {} + + // S9: unknown workspace 404; any non-owner (member or stranger) 403 — the + // workspace existence is intentionally visible here, unlike the nested + // session routes. A ghost invitee (unknown user id) is stored as-is. + async inviteToWorkspace( + actor: UserId, + workspaceId: WorkspaceId, + inviteeId: UserId, + ): Promise { + const ws = await this.workspaces.find(workspaceId); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor)) return { kind: 'forbidden' }; + // Unknown users cannot be invited: the invitation row holds a required FK + // to User, so the check runs up front (after the owner check, so strangers + // still get 403 without learning whether the user id exists). + if (!(await this.users.findById(inviteeId))) return { kind: 'not-found' }; + let invitation: Invitation; + try { + invitation = ws.inviteMember(actor, inviteeId); + } catch (error) { + // Only AlreadyHasAccess is reachable (ownership was pre-checked). + return { kind: this.inviteViolation(error) }; + } + // Created invitations never expire. + await this.invitations.save(invitation, null); + const inviter = await this.users.findById(actor); + if (!inviter) throw new Error('authenticated user vanished'); // unreachable + return { + kind: 'created', + view: { + id: invitation.id, + target: { kind: 'workspace', workspaceId: ws.id, name: ws.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }, + }; + } + + // S10: unknown session (or a session whose workspace is gone) 404; any + // non-owner — member, stranger, or guest — 403. + async inviteToSession( + actor: UserId, + sessionId: SessionId, + inviteeId: UserId, + ): Promise { + const session = await this.sessions.find(sessionId); + if (!session) return { kind: 'not-found' }; + const ws = await this.workspaces.find(session.workspaceId); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor)) return { kind: 'forbidden' }; + // Unknown users cannot be invited: the invitation row holds a required FK + // to User, so the check runs up front (after the owner check, so strangers + // still get 403 without learning whether the user id exists). + if (!(await this.users.findById(inviteeId))) return { kind: 'not-found' }; + let invitation: Invitation; + try { + invitation = session.inviteGuest(ws, actor, inviteeId); + } catch (error) { + // Only AlreadyHasAccess is reachable (ownership was pre-checked). + return { kind: this.inviteViolation(error) }; + } + // Created invitations never expire. + await this.invitations.save(invitation, null); + const inviter = await this.users.findById(actor); + if (!inviter) throw new Error('authenticated user vanished'); // unreachable + return { + kind: 'created', + view: { + id: invitation.id, + target: { kind: 'session', sessionId: session.id, name: session.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }, + }; + } + + // S11: the caller's pending, non-expired invitations, oldest first. + async list(actor: UserId): Promise { + const pending = await this.invitations.listPendingFor(actor); + const inviterIds = [...new Set(pending.map((s) => s.invitation.invitedBy))]; + const inviters = new Map((await this.users.findByIds(inviterIds)).map((u) => [u.id, u] as const)); + const views: InvitationView[] = []; + for (const stored of pending) { + const inviter = inviters.get(stored.invitation.invitedBy); + if (!inviter) continue; // inviter deleted: nothing to attribute the entry to + const { target } = stored.invitation; + if (target.kind === 'workspace') { + // A target that no longer loads is skipped, never listed as an orphan: + // the entry would name something the caller can no longer accept. + const ws = await this.workspaces.find(target.workspaceId); + if (!ws) continue; + views.push({ + id: stored.invitation.id, + target: { kind: 'workspace', workspaceId: ws.id, name: ws.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }); + } else { + const session = await this.sessions.find(target.sessionId); + if (!session) continue; + views.push({ + id: stored.invitation.id, + target: { kind: 'session', sessionId: session.id, name: session.name }, + invitedBy: { userId: inviter.id, username: inviter.username, displayName: inviter.displayName }, + }); + } + } + return views; + } + + // S12: applies the domain accept, persists the aggregate, then marks the + // invitation accepted — in that order, so a failed accept never leaves a + // half-applied aggregate plus an accepted invitation (S15). + async accept(actor: UserId, id: string): Promise { + const loaded = await this.loadForResponse(id, actor); + if (loaded.kind !== 'ok') return loaded; + const { invitation } = loaded.stored; + if (invitation.target.kind === 'workspace') { + const ws = await this.workspaces.find(invitation.target.workspaceId); + if (!ws) return { kind: 'not-found' }; + try { + ws.acceptInvitation(invitation); + } catch (error) { + // The aggregate is untouched and the invitation stays pending. + return { kind: this.respondViolation(error) }; + } + // The aggregate save is already one batch transaction; only once it is + // fully applied may the invitation be marked accepted — never the + // reverse, so a crash between the two cannot accept without applying. + await this.workspaces.save(ws); + try { + await this.invitations.setStatus(invitation.id, 'accepted'); + } catch { + // Count 0 after our pending check means a raced response slipped in. + return { kind: 'conflict' }; + } + return { kind: 'ok' }; + } + const session = await this.sessions.find(invitation.target.sessionId); + if (!session) return { kind: 'not-found' }; + const ws = await this.workspaces.find(session.workspaceId); + if (!ws) return { kind: 'not-found' }; + try { + session.acceptInvitation(ws, invitation); + } catch (error) { + // The aggregate is untouched and the invitation stays pending. + return { kind: this.respondViolation(error) }; + } + await this.sessions.save(session); + try { + await this.invitations.setStatus(invitation.id, 'accepted'); + } catch { + // Count 0 after our pending check means a raced response slipped in. + return { kind: 'conflict' }; + } + return { kind: 'ok' }; + } + + // S13: declining only flips the invitation row; it never touches aggregates. + async decline(actor: UserId, id: string): Promise { + const loaded = await this.loadForResponse(id, actor); + if (loaded.kind !== 'ok') return loaded; + try { + await this.invitations.setStatus(loaded.stored.invitation.id, 'declined'); + } catch { + // Count 0 after our pending check means a raced response slipped in. + return { kind: 'conflict' }; + } + return { kind: 'ok' }; + } + + // Shared S12/S13 gate, strictly ordered: (1) unknown or malformed id 404 — + // malformed is pre-checked because Postgres uuid columns throw on it; + // (2) caller is not the invitee 403, before any status signal (no leak); + // (3) expired or no longer pending 409. + private async loadForResponse(id: string, actor: UserId): Promise { + if (!isUuid(id)) return { kind: 'not-found' }; + const stored = await this.invitations.find(id as InvitationId); + if (!stored) return { kind: 'not-found' }; + if (stored.invitation.invitee !== actor) return { kind: 'forbidden' }; + if (stored.status !== 'pending' || (stored.expiresAt !== null && stored.expiresAt <= new Date())) { + return { kind: 'conflict' }; + } + return { kind: 'ok', stored }; + } + + // Invites only ever raise AlreadyHasAccess past the ownership pre-check; + // anything else is an invariant break and must surface, not map. + private inviteViolation(error: unknown): 'forbidden' | 'conflict' { + const violation = domainViolation(error); + if (violation === 'forbidden' || violation === 'conflict') return violation; + throw error; + } + + // Accepts only ever raise AlreadyHasAccess (invitee already has the role), + // InvitationTargetMismatch, or NotOwner (inviter lost ownership); anything + // else is an invariant break and must surface, not map. + private respondViolation(error: unknown): 'forbidden' | 'conflict' { + const violation = domainViolation(error); + if (violation === 'forbidden' || violation === 'conflict') return violation; + throw error; + } +} diff --git a/apps/api/src/collab/session.service.ts b/apps/api/src/collab/session.service.ts new file mode 100644 index 0000000..35de38b --- /dev/null +++ b/apps/api/src/collab/session.service.ts @@ -0,0 +1,272 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { + newAgentProfile, + Session, + type SessionId, + type Terminal, + type TerminalId, + type UserId, + type Workspace, + type WorkspaceId, +} from '@opencollab/domain'; + +import { SessionRepository } from '../persistence/session.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { toSessionView, toTerminalView, type SessionView, type TerminalView } from './views'; +import type { AddTerminalBody, ReorderTerminalsBody, UpdateTerminalBody } from './dto'; + +// `not-found` covers both a missing workspace and a caller with no relation to +// it: sessions endpoints must not leak workspace existence (S4/S5). +export type SessionListResult = + | { kind: 'ok'; views: SessionView[] } + | { kind: 'not-found' }; + +// S7: the explicit-id create answers the current view when the caller already +// owns that id (idempotent), and 409 when someone else owns it. +export type SessionCreateResult = + | { kind: 'created'; view: SessionView } + | { kind: 'existing'; view: SessionView } + | { kind: 'conflict' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// S6: the session itself is either invisible (403 when it exists but the +// caller cannot view it) or missing (404). +export type SessionDetailResult = + | { kind: 'ok'; view: SessionView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// S7: rename/delete are owner actions; a non-owner (member, stranger or guest) +// answers 403 without learning whether the session exists. +export type SessionRenameResult = + | { kind: 'ok'; view: SessionView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type SessionRemoveResult = + | { kind: 'removed' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// S7/S8: terminal mutations are owner-only; a non-owner never learns whether +// a terminal id exists (owner check runs before terminal existence). +export type TerminalCreateResult = + | { kind: 'created'; view: TerminalView } + | { kind: 'existing'; view: TerminalView } + | { kind: 'conflict' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type TerminalUpdateResult = + | { kind: 'ok'; view: TerminalView } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type TerminalRemoveResult = + | { kind: 'removed' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// The order body is a request-shape rule (S7): exactly the session's +// terminals, no duplicates, no omissions — anything else is 400. +export type TerminalsOrderResult = + | { kind: 'ok'; views: TerminalView[] } + | { kind: 'bad-request' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// The loaded session + its workspace, with the owner check already applied. +type OwnedSession = + | { kind: 'ok'; session: Session; workspace: Workspace } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +@Injectable() +export class SessionService { + constructor( + @Inject(WorkspaceRepository) private readonly workspaces: WorkspaceRepository, + @Inject(SessionRepository) private readonly sessions: SessionRepository, + ) {} + + // Workspace classification for the nested routes: unknown or stranger is + // `not-found`, any member (owner or not) is `ok`. + private async access( + workspaceId: WorkspaceId, + actor: UserId, + ): Promise<{ kind: 'not-found' } | { kind: 'ok'; workspace: Workspace; owner: boolean }> { + const ws = await this.workspaces.find(workspaceId); + if (!ws || (!ws.isOwner(actor) && !ws.isMember(actor))) return { kind: 'not-found' }; + return { kind: 'ok', workspace: ws, owner: ws.isOwner(actor) }; + } + + async create( + actor: UserId, + workspaceId: WorkspaceId, + input: { name: string; id?: string }, + ): Promise { + const acc = await this.access(workspaceId, actor); + if (acc.kind === 'not-found') return acc; + if (!acc.owner) return { kind: 'forbidden' }; + if (input.id !== undefined) { + const existing = await this.sessions.find(input.id as SessionId); + if (existing) { + const existingWorkspace = await this.workspaces.find(existing.workspaceId); + // The session exists: same owner answers its current view (idempotent), + // another owner's id answers conflict. + if (existingWorkspace && existingWorkspace.isOwner(actor)) { + return { kind: 'existing', view: toSessionView(existing) }; + } + return { kind: 'conflict' }; + } + } + // `Session.create` re-checks ownership in the domain (ensureOwner). + const session = Session.create( + acc.workspace, + actor, + input.name, + ...(input.id === undefined ? [] : [input.id as SessionId]), + ); + await this.sessions.save(session); + return { kind: 'created', view: toSessionView(session) }; + } + + async list(actor: UserId, workspaceId: WorkspaceId): Promise { + const acc = await this.access(workspaceId, actor); + if (acc.kind === 'not-found') return acc; + const list = await this.sessions.listByWorkspace(workspaceId); + return { kind: 'ok', views: list.map(toSessionView) }; + } + + async detail(id: SessionId, actor: UserId): Promise { + const session = await this.sessions.find(id); + if (!session) return { kind: 'not-found' }; + const ws = await this.workspaces.find(session.workspaceId); + if (!ws || !session.canView(ws, actor)) return { kind: 'forbidden' }; + return { kind: 'ok', view: toSessionView(session) }; + } + + // Unknown session → 404; a caller without the workspace is `forbidden` (403), + // never leaking terminal existence. A vanished workspace is `not-found`: + // terminal mutations are meaningless without it (unreachable via cascade). + private async ownedSession(sessionId: SessionId, actor: UserId): Promise { + const session = await this.sessions.find(sessionId); + if (!session) return { kind: 'not-found' }; + const workspace = await this.workspaces.find(session.workspaceId); + if (!workspace) return { kind: 'not-found' }; + if (!workspace.isOwner(actor)) return { kind: 'forbidden' }; + return { kind: 'ok', session, workspace }; + } + + async addTerminal(actor: UserId, sessionId: SessionId, body: AddTerminalBody): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + if (body.id !== undefined) { + const existing = await this.sessions.terminalWithOwner(body.id as TerminalId); + if (existing) { + // Same owner answers the current terminal (idempotent; the id may even + // live in another session of the same caller); otherwise 409. + if (existing.ownerId !== actor) return { kind: 'conflict' }; + return { kind: 'existing', view: toTerminalView(existing.terminal) }; + } + } + // The domain factory copies args/env and enforces a non-blank command; + // env is always empty because the strict schema never accepts it (S7). + const profile = newAgentProfile(body.name, body.command, { + ...(body.args === undefined ? {} : { args: body.args }), + ...(body.cwd == null ? {} : { cwd: body.cwd }), + }); + // `addTerminal` re-checks ownership in the domain (ensureOwner). + const terminalId = acc.session.addTerminal(acc.workspace, actor, profile, { + ...(body.id === undefined ? {} : { id: body.id as TerminalId }), + ...(body.agent === undefined ? {} : { agent: body.agent }), + ...(body.minimized === undefined ? {} : { minimized: body.minimized }), + }); + await this.sessions.save(acc.session); + const terminal = acc.session.terminal(terminalId); + if (!terminal) throw new Error('terminal vanished after addTerminal'); // unreachable + return { kind: 'created', view: toTerminalView(terminal) }; + } + + async updateTerminal( + actor: UserId, + sessionId: SessionId, + terminalId: TerminalId, + patch: UpdateTerminalBody, + ): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // TerminalNotInSession → 404 (the owner check already ran above). + const terminal = acc.session.terminal(terminalId); + if (!terminal) return { kind: 'not-found' }; + // The domain factory rebuilds the profile, so a blank command stays + // impossible; the schema's blank check already rejected it anyway. + acc.session.updateTerminal(acc.workspace, actor, terminalId, patch); + await this.sessions.save(acc.session); + const updated = acc.session.terminal(terminalId); + if (!updated || !isTerminal(updated)) throw new Error('terminal vanished after updateTerminal'); // unreachable + return { kind: 'ok', view: toTerminalView(updated) }; + } + + // S7: the ids must be exactly the session's terminals — no duplicates, no + // omissions, no strangers — checked before the aggregate is touched. + async reorderTerminals( + actor: UserId, + sessionId: SessionId, + body: ReorderTerminalsBody, + ): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + const stored = acc.session.terminals; + const requested = body.ids as TerminalId[]; + const requestedSet = new Set(requested); + if ( + requested.length !== stored.length || + requestedSet.size !== requested.length || + !stored.every((t) => requestedSet.has(t.id)) + ) { + return { kind: 'bad-request' }; + } + // `reorderTerminals` re-checks ownership and membership in the domain. + acc.session.reorderTerminals(acc.workspace, actor, requested); + await this.sessions.save(acc.session); + return { kind: 'ok', views: acc.session.terminals.map(toTerminalView) }; + } + + async renameSession(actor: UserId, sessionId: SessionId, name: string): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // Unreachable NotOwner: the classification above is the same check. + acc.session.rename(acc.workspace, actor, name); + await this.sessions.save(acc.session); + return { kind: 'ok', view: toSessionView(acc.session) }; + } + + async removeSession(actor: UserId, sessionId: SessionId): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + await this.sessions.delete(sessionId); + return { kind: 'removed' }; + } + + async removeTerminal( + actor: UserId, + sessionId: SessionId, + terminalId: TerminalId, + ): Promise { + const acc = await this.ownedSession(sessionId, actor); + if (acc.kind !== 'ok') return acc; + // TerminalNotInSession → 404 (the owner check already ran above). + if (!acc.session.terminal(terminalId)) return { kind: 'not-found' }; + acc.session.removeTerminal(acc.workspace, actor, terminalId); + await this.sessions.save(acc.session); + return { kind: 'removed' }; + } +} + +// The domain mutators replace the terminal object entirely, so the re-read +// requires the metadata-bearing shape; this keeps the unreachable guard typed. +function isTerminal(value: Terminal | undefined): value is Terminal { + return value !== undefined; +} diff --git a/apps/api/src/collab/sessions.controller.int.spec.ts b/apps/api/src/collab/sessions.controller.int.spec.ts new file mode 100644 index 0000000..e5e83dd --- /dev/null +++ b/apps/api/src/collab/sessions.controller.int.spec.ts @@ -0,0 +1,379 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import type { InvitationId, SessionId, UserId, WorkspaceId } from '@opencollab/domain'; +import { SessionRepository } from '../persistence/session.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let sessions: SessionRepository; +let workspaces: WorkspaceRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + sessions = new SessionRepository(t.prisma); + workspaces = new WorkspaceRepository(t.prisma); +}); +afterAll(() => t.close()); +beforeEach(() => truncateAll(t.prisma)); + +interface Res { + status: number; + body: unknown; +} + +async function call(method: string, path: string, body?: unknown, token?: string): Promise { + const res = await fetch(`${t.baseUrl}${path}`, { + method, + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + let parsed: unknown = undefined; + try { + parsed = text ? JSON.parse(text) : undefined; + } catch { + parsed = text; + } + return { status: res.status, body: parsed }; +} + +const get = (path: string, token?: string) => call('GET', path, undefined, token); +const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); +const del = (path: string, token?: string) => call('DELETE', path, undefined, token); +const patch = (path: string, body?: unknown, token?: string) => call('PATCH', path, body ?? {}, token); + +let counter = 0; +async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { + counter += 1; + const username = `${prefix}${counter}`; + const res = await post('/auth/register', { + username, + password: 'correct horse battery', + displayName: prefix, + }); + expect(res.status).toBe(201); + const body = res.body as { accessToken: string; user: { id: string } }; + return { id: body.user.id, token: body.accessToken }; +} + +async function createWorkspace(ownerToken: string, name = 'ws'): Promise<{ id: string }> { + const res = await post('/workspaces', { name }, ownerToken); + expect(res.status).toBe(201); + return res.body as { id: string }; +} + +// Seeds a member straight through the repository: invitations belong to T4. +async function seedMember(workspaceId: WorkspaceId, ownerId: UserId, memberId: UserId): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + ws!.addMember(ownerId, memberId); + await workspaces.save(ws!); +} + +type SessionBody = { + id: string; + name: string; + terminals: { id: string; name: string; command: string; args: string[]; cwd: string | null }[]; +}; + +describe('POST /workspaces/:workspaceId/sessions', () => { + it('creates a session with the caller as owner (201, empty terminals)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'Standup' }, owner.token); + expect(res.status).toBe(201); + const body = res.body as SessionBody; + expect(body.name).toBe('Standup'); + expect(body.id).toBeTruthy(); + expect(body.terminals).toEqual([]); + }); + + it('returns 403 for a member who is not the owner', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'x' }, member.token); + expect(res.status).toBe(403); + }); + + it('returns 404 for a stranger (no access) and for an unknown workspace', async () => { + const owner = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + + expect((await post(`/workspaces/${ws.id}/sessions`, { name: 'x' }, stranger.token)).status).toBe(404); + expect( + (await post('/workspaces/00000000-0000-0000-0000-000000000000/sessions', { name: 'x' }, owner.token)) + .status, + ).toBe(404); + }); + + it('requires auth and a valid strict body (S14)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + + expect((await post(`/workspaces/${ws.id}/sessions`, { name: 'x' })).status).toBe(401); + expect((await post(`/workspaces/${ws.id}/sessions`, { name: '' }, owner.token)).status).toBe(400); + expect((await post(`/workspaces/${ws.id}/sessions`, { name: ' ' }, owner.token)).status).toBe(400); + expect( + (await post(`/workspaces/${ws.id}/sessions`, { name: 'x', extra: true }, owner.token)).status, + ).toBe(400); + }); +}); + +describe('GET /workspaces/:workspaceId/sessions', () => { + it('lists the sessions of the workspace for owner and member, with terminals in position order', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + + const created = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'first' }, owner.token) + ).body as SessionBody; + await post(`/workspaces/${ws.id}/sessions`, { name: 'second' }, owner.token); + + // Seed terminals straight through the repository (endpoints belong to T3): + // two terminals whose stored order must survive the list projection. + const wsAggregate = await workspaces.find(ws.id as WorkspaceId); + const aggregate = await sessions.find(created.id as SessionId); + expect(aggregate).toBeTruthy(); + aggregate!.addTerminal(wsAggregate!, owner.id as UserId, { + name: 'a', + command: 'echo', + args: ['a'], + env: [], + }); + aggregate!.addTerminal(wsAggregate!, owner.id as UserId, { + name: 'b', + command: 'echo', + args: ['b'], + env: [], + cwd: '/tmp', + }); + await sessions.save(aggregate!); + + const forOwner = (await get(`/workspaces/${ws.id}/sessions`, owner.token)).body as SessionBody[]; + expect(forOwner.map((s) => s.name)).toEqual(['first', 'second']); + const withTerminals = forOwner.find((s) => s.id === created.id)!; + expect(withTerminals.terminals.map((tm) => tm.name)).toEqual(['a', 'b']); + expect(withTerminals.terminals[0]).toMatchObject({ command: 'echo', args: ['a'], cwd: null }); + expect(withTerminals.terminals[1]).toMatchObject({ command: 'echo', args: ['b'], cwd: '/tmp' }); + + const forMember = (await get(`/workspaces/${ws.id}/sessions`, member.token)).body as SessionBody[]; + expect(forMember.map((s) => s.name)).toEqual(['first', 'second']); + }); + + it('returns 404 for a stranger and for an unknown workspace', async () => { + const owner = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await post(`/workspaces/${ws.id}/sessions`, { name: 'x' }, owner.token); + + expect((await get(`/workspaces/${ws.id}/sessions`, stranger.token)).status).toBe(404); + expect((await get('/workspaces/00000000-0000-0000-0000-000000000000/sessions', owner.token)).status).toBe( + 404, + ); + expect((await get(`/workspaces/${ws.id}/sessions`)).status).toBe(401); + }); +}); + +describe('GET /sessions/:id', () => { + it('returns the session detail with terminals for the owner', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const created = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'detail' }, owner.token) + ).body as SessionBody; + + const res = await get(`/sessions/${created.id}`, owner.token); + expect(res.status).toBe(200); + const body = res.body as SessionBody; + expect(body.id).toBe(created.id); + expect(body.name).toBe('detail'); + expect(body.terminals).toEqual([]); + }); + + it('allows a member and a guest to view, and rejects a stranger with 403', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const guest = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'shared' }, owner.token) + ).body as SessionBody; + + // Guest seeding mirrors T1's approach: the domain invitation flow is T4, + // so the guest role is applied directly on the aggregate. + const aggregate = await sessions.find(created.id as SessionId); + const wsAggregate = await workspaces.find(ws.id as WorkspaceId); + aggregate!.acceptInvitation(wsAggregate!, { + id: '00000000-0000-0000-0000-000000000001' as InvitationId, + target: { kind: 'session', sessionId: aggregate!.id }, + invitee: guest.id as UserId, + invitedBy: owner.id as UserId, + }); + await sessions.save(aggregate!); + + expect((await get(`/sessions/${created.id}`, member.token)).status).toBe(200); + expect((await get(`/sessions/${created.id}`, guest.token)).status).toBe(200); + expect((await get(`/sessions/${created.id}`, stranger.token)).status).toBe(403); + expect((await get(`/sessions/${created.id}`)).status).toBe(401); + }); + + it('returns 404 for an unknown session', async () => { + const owner = await registerUser(); + expect((await get('/sessions/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + }); +}); + +// S7: explicit session ids power the desktop's idempotent cloud round-trip. +describe('POST /workspaces/:workspaceId/sessions with explicit id', () => { + it('creates the session with the caller-provided id (201)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const id = '20000000-0000-4000-8000-000000000001'; + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'Con id', id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as { id: string; name: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Con id'); + }); + + it('returns 200 with the current view for a same-owner retry (idempotent)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const id = '20000000-0000-4000-8000-000000000002'; + await post(`/workspaces/${ws.id}/sessions`, { name: 'Original', id }, owner.token); + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'Original', id }, owner.token); + expect(res.status).toBe(200); + const body = res.body as { id: string; name: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Original'); + + const list = (await get(`/workspaces/${ws.id}/sessions`, owner.token)).body as { id: string }[]; + expect(list.filter((s) => s.id === id)).toHaveLength(1); + }); + + it('returns 409 for a session id owned by another workspace owner', async () => { + const owner = await registerUser(); + const other = await registerUser(); + const ws = await createWorkspace(owner.token); + const foreign = await createWorkspace(other.token, 'extranjero'); + const taken = ( + await post(`/workspaces/${foreign.id}/sessions`, { name: 'suyo' }, other.token) + ).body as { id: string }; + + const res = await post(`/workspaces/${ws.id}/sessions`, { name: 'mío', id: taken.id }, owner.token); + expect(res.status).toBe(409); + }); + + it('rejects a non-uuid id with 400', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + expect( + (await post(`/workspaces/${ws.id}/sessions`, { name: 'x', id: 'not-a-uuid' }, owner.token)).status, + ).toBe(400); + }); +}); + +// S7: session rename and delete complete the desktop's snapshot reconciliation. +describe('PATCH /sessions/:id', () => { + it('renames for the owner (200 with the current session view)', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'antes' }, owner.token) + ).body as SessionBody; + + const res = await patch(`/sessions/${session.id}`, { name: 'Renombrada' }, owner.token); + expect(res.status).toBe(200); + const body = res.body as SessionBody; + expect(body.id).toBe(session.id); + expect(body.name).toBe('Renombrada'); + expect(body.terminals).toEqual([]); + + const persisted = await sessions.find(session.id as SessionId); + expect(persisted?.name).toBe('Renombrada'); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'compartida' }, owner.token) + ).body as SessionBody; + const other = await registerUser(); + const otherWs = await createWorkspace(other.token, 'otro'); + + expect((await patch(`/sessions/${session.id}`, { name: 'x' }, member.token)).status).toBe(403); + expect((await patch(`/sessions/${session.id}`, { name: 'x' }, stranger.token)).status).toBe(403); + expect((await patch('/sessions/00000000-0000-0000-0000-000000000000', { name: 'x' }, owner.token)).status).toBe(404); + // A workspace id is not a session id: an unknown session answers 404. + expect((await patch(`/sessions/${otherWs.id}`, { name: 'x' }, owner.token)).status).toBe(404); + expect((await patch(`/sessions/${session.id}`, { name: 'x' })).status).toBe(401); + }); + + it('rejects a blank name with 400', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 's' }, owner.token) + ).body as SessionBody; + expect((await patch(`/sessions/${session.id}`, { name: '' }, owner.token)).status).toBe(400); + expect((await patch(`/sessions/${session.id}`, { name: ' ' }, owner.token)).status).toBe(400); + expect((await patch(`/sessions/${session.id}`, { extra: true }, owner.token)).status).toBe(400); + }); +}); + +describe('DELETE /sessions/:id', () => { + it('deletes for the owner (204) and removes its terminals', async () => { + const owner = await registerUser(); + const ws = await createWorkspace(owner.token); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'borrar' }, owner.token) + ).body as SessionBody; + await post(`/sessions/${session.id}/terminals`, { name: 't', command: 'sh' }, owner.token); + expect(await t.prisma.terminal.count()).toBe(1); + + const res = await del(`/sessions/${session.id}`, owner.token); + expect(res.status).toBe(204); + + expect(await t.prisma.terminal.count()).toBe(0); + expect((await get(`/sessions/${session.id}`, owner.token)).status).toBe(404); + // The workspace and the parent grouping survive the session delete. + expect(await t.prisma.workspace.count()).toBe(1); + expect((await get(`/workspaces/${ws.id}/sessions`, owner.token)).body).toEqual([]); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser("owner"); + const member = await registerUser(); + const stranger = await registerUser(); + const ws = await createWorkspace(owner.token); + await seedMember(ws.id as WorkspaceId, owner.id as UserId, member.id as UserId); + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name: 'protegida' }, owner.token) + ).body as SessionBody; + + expect((await del(`/sessions/${session.id}`, member.token)).status).toBe(403); + expect((await del(`/sessions/${session.id}`, stranger.token)).status).toBe(403); + expect((await del('/sessions/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + expect((await del(`/sessions/${session.id}`)).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/sessions.controller.ts b/apps/api/src/collab/sessions.controller.ts new file mode 100644 index 0000000..d7e601d --- /dev/null +++ b/apps/api/src/collab/sessions.controller.ts @@ -0,0 +1,100 @@ +import { + Body, + ConflictException, + Controller, + Delete, + ForbiddenException, + Get, + HttpCode, + HttpStatus, + Inject, + NotFoundException, + Param, + Patch, + Post, + Res, + UseGuards, +} from '@nestjs/common'; + +import type { SessionId, WorkspaceId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { + createSessionSchema, + renameSessionSchema, + type CreateSessionBody, + type RenameSessionBody, +} from './dto'; +import { SessionService } from './session.service'; + +// Status passthrough for the tri-state create (201/200/409): the existing +// @HttpCode annotation cannot express a dynamic code. +interface Reply { + status(code: number): unknown; +} + +@Controller() +@UseGuards(AccessGuard) +export class SessionsController { + constructor(@Inject(SessionService) private readonly service: SessionService) {} + + // S4/S7: only the workspace owner creates sessions (member 403; missing + // workspace or stranger 404). A fresh id answers 201, an id the caller + // already owns answers its current session as 200, a taken id answers 409. + @Post('workspaces/:workspaceId/sessions') + async create( + @CurrentUser() user: UserRecord, + @Param('workspaceId') workspaceId: string, + @Body(new ZodPipe(createSessionSchema)) body: CreateSessionBody, + @Res({ passthrough: true }) reply: Reply, + ): Promise { + const result = await this.service.create(user.id, workspaceId as WorkspaceId, body); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + reply.status(result.kind === 'created' ? 201 : 200); + return result.view; + } + + // S5: owner or member list; missing workspace or stranger 404. + @Get('workspaces/:workspaceId/sessions') + async list(@CurrentUser() user: UserRecord, @Param('workspaceId') workspaceId: string) { + const result = await this.service.list(user.id, workspaceId as WorkspaceId); + if (result.kind === 'not-found') throw new NotFoundException(); + return result.views; + } + + // S6: any viewer (owner, member, guest); 403 without view access, 404 unknown. + @Get('sessions/:id') + async detail(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.detail(id as SessionId, user.id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S7: rename answers the session view; non-owners answer 403 without + // learning whether the session exists; unknown sessions 404. + @Patch('sessions/:id') + async rename( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(renameSessionSchema)) body: RenameSessionBody, + ) { + const result = await this.service.renameSession(user.id, id as SessionId, body.name); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S7: delete returns 204 with no body and takes the session's terminals + // with it; non-owners answer 403, unknown sessions 404. + @Delete('sessions/:id') + @HttpCode(HttpStatus.NO_CONTENT) + async remove(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.removeSession(user.id, id as SessionId); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + } +} diff --git a/apps/api/src/collab/terminals.controller.int.spec.ts b/apps/api/src/collab/terminals.controller.int.spec.ts new file mode 100644 index 0000000..458f5d2 --- /dev/null +++ b/apps/api/src/collab/terminals.controller.int.spec.ts @@ -0,0 +1,579 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import type { SessionId, UserId, WorkspaceId } from '@opencollab/domain'; +import { SessionRepository } from '../persistence/session.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let sessions: SessionRepository; +let workspaces: WorkspaceRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + sessions = new SessionRepository(t.prisma); + workspaces = new WorkspaceRepository(t.prisma); +}); +afterAll(() => t.close()); +beforeEach(() => truncateAll(t.prisma)); + +interface Res { + status: number; + body: unknown; +} + +async function call(method: string, path: string, body?: unknown, token?: string): Promise { + const res = await fetch(`${t.baseUrl}${path}`, { + method, + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + let parsed: unknown = undefined; + try { + parsed = text ? JSON.parse(text) : undefined; + } catch { + parsed = text; + } + return { status: res.status, body: parsed }; +} + +const get = (path: string, token?: string) => call('GET', path, undefined, token); +const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); +const del = (path: string, token?: string) => call('DELETE', path, undefined, token); +const patch = (path: string, body?: unknown, token?: string) => call('PATCH', path, body ?? {}, token); +const put = (path: string, body?: unknown, token?: string) => call('PUT', path, body ?? {}, token); + +let counter = 0; +async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { + counter += 1; + const username = `${prefix}${counter}`; + const res = await post('/auth/register', { + username, + password: 'correct horse battery', + displayName: prefix, + }); + expect(res.status).toBe(201); + const body = res.body as { accessToken: string; user: { id: string } }; + return { id: body.user.id, token: body.accessToken }; +} + +async function seedMember(workspaceId: WorkspaceId, ownerId: UserId, memberId: UserId): Promise { + const ws = await workspaces.find(workspaceId); + expect(ws).toBeTruthy(); + ws!.addMember(ownerId, memberId); + await workspaces.save(ws!); +} + +// Creates workspace + session through the endpoints added in T1/T2. +async function seedSession(ownerToken: string, name = 'sess'): Promise<{ wsId: string; sessionId: string }> { + const ws = (await post('/workspaces', { name: 'ws' }, ownerToken)).body as { id: string }; + const session = ( + await post(`/workspaces/${ws.id}/sessions`, { name }, ownerToken) + ).body as { id: string }; + return { wsId: ws.id, sessionId: session.id }; +} + +type TerminalBody = { + id: string; + name: string; + command: string; + args: string[]; + cwd: string | null; + agent: string | null; + minimized: boolean; +}; + +// S7: the terminal view the desktop round-trips — exactly seven fields, never +// seq (DOM order bookkeeping) nor env (secrets stay client-side). +const TERMINAL_FIELDS = ['agent', 'args', 'command', 'cwd', 'id', 'minimized', 'name'] as const; + +describe('POST /sessions/:id/terminals', () => { + it('appends a terminal for the owner and exposes it in the session detail (201)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'shell', command: 'pwsh', args: ['-NoLogo'], cwd: 'C:/tmp' }, + owner.token, + ); + expect(res.status).toBe(201); + const body = res.body as TerminalBody; + expect(body.name).toBe('shell'); + expect(body.command).toBe('pwsh'); + expect(body.args).toEqual(['-NoLogo']); + expect(body.cwd).toBe('C:/tmp'); + expect('env' in body).toBe(false); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals).toHaveLength(1); + expect(detail.terminals[0]?.id).toBe(body.id); + }); + + it('defaults args to [] and cwd to null when omitted', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'bash' }, owner.token); + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ args: [], cwd: null }); + }); + + it('returns 403 for a member and a stranger, 404 for an unknown session', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + + expect( + (await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, member.token)).status, + ).toBe(403); + expect( + (await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, stranger.token)).status, + ).toBe(403); + expect( + (await post('/sessions/00000000-0000-0000-0000-000000000000/terminals', { name: 's', command: 'x' }, owner.token)) + .status, + ).toBe(404); + expect( + (await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' })).status, + ).toBe(401); + }); + + it('rejects invalid bodies with 400 and never accepts env (S7/S14)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const path = `/sessions/${sessionId}/terminals`; + + expect((await post(path, { name: 's' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: '' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: ' ' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', env: [['K', 'V']] }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', args: 'not-array' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', cwd: 42 }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', extra: true }, owner.token)).status).toBe(400); + }); + + it('never persists env even when the caller tries to send it (strict rejection)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const rejected = await post( + `/sessions/${sessionId}/terminals`, + { name: 's', command: 'x', env: [['SECRET', 'v']] }, + owner.token, + ); + expect(rejected.status).toBe(400); + + // The session stays empty and, on a valid create, the stored profile keeps env=[]. + const created = await post( + `/sessions/${sessionId}/terminals`, + { name: 's', command: 'x' }, + owner.token, + ); + expect(created.status).toBe(201); + const aggregate = await sessions.find(sessionId as SessionId); + expect(aggregate!.terminals[0]?.profile.env).toEqual([]); + }); +}); + +describe('DELETE /sessions/:id/terminals/:terminalId', () => { + it('removes the terminal for the owner (204) and it disappears from the detail', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, owner.token) + ).body as TerminalBody; + + const res = await del(`/sessions/${sessionId}/terminals/${created.id}`, owner.token); + expect(res.status).toBe(204); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals).toEqual([]); + }); + + it('returns 404 for an unknown terminal or session', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + expect( + (await del(`/sessions/${sessionId}/terminals/00000000-0000-0000-0000-000000000000`, owner.token)).status, + ).toBe(404); + expect( + (await del('/sessions/00000000-0000-0000-0000-000000000000/terminals/00000000-0000-0000-0000-000000000000', owner.token)) + .status, + ).toBe(404); + }); + + it('returns 403 for a member and a stranger before checking terminal existence', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 's', command: 'x' }, owner.token) + ).body as TerminalBody; + + expect((await del(`/sessions/${sessionId}/terminals/${created.id}`, member.token)).status).toBe(403); + // Non-owners must not learn whether a terminal id exists: a stranger probing + // an unknown id still gets 403, not 404. + expect( + (await del(`/sessions/${sessionId}/terminals/00000000-0000-0000-0000-000000000000`, stranger.token)).status, + ).toBe(403); + expect((await del(`/sessions/${sessionId}/terminals/${created.id}`)).status).toBe(401); + }); +}); + +describe('terminal metadata (S7)', () => { + it('accepts agent and minimized and reflects them in the detail', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'claude', command: 'claude', agent: 'claude', minimized: true }, + owner.token, + ); + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ agent: 'claude', minimized: true }); + }); + + it('defaults agent to null and minimized to false', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token); + expect(res.status).toBe(201); + expect(res.body).toMatchObject({ agent: null, minimized: false }); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals[0]).toMatchObject({ agent: null, minimized: false }); + }); + + it('accepts an explicit null agent', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', agent: null }, + owner.token, + ); + expect(res.status).toBe(201); + expect((res.body as TerminalBody).agent).toBeNull(); + }); + + it('rejects invalid metadata with 400', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const path = `/sessions/${sessionId}/terminals`; + + expect((await post(path, { name: 's', command: 'x', agent: 42 }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', minimized: 'yes' }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', seq: 3 }, owner.token)).status).toBe(400); + expect((await post(path, { name: 's', command: 'x', env: [] }, owner.token)).status).toBe(400); + }); +}); + +// S7: explicit terminal ids — idempotent for a same-owner id, conflict otherwise. +describe('POST /sessions/:id/terminals with explicit id', () => { + it('creates the terminal with the caller-provided id (201)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const id = '30000000-0000-4000-8000-000000000001'; + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', id }, + owner.token, + ); + expect(res.status).toBe(201); + expect((res.body as TerminalBody).id).toBe(id); + }); + + it('returns 200 with the current terminal for a same-owner retry (idempotent)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const id = '30000000-0000-4000-8000-000000000002'; + await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', id, agent: 'claude', minimized: true }, + owner.token, + ); + + const res = await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh', id }, owner.token); + expect(res.status).toBe(200); + // The current stored terminal comes back, not a second terminal. + expect(res.body).toMatchObject({ id, name: 'sh', agent: 'claude', minimized: true }); + expect(await t.prisma.terminal.count()).toBe(1); + }); + + it('returns 409 for a terminal id owned by another user', async () => { + const owner = await registerUser(); + const other = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const otherSession = await seedSession(other.token); + const taken = ( + await post( + `/sessions/${otherSession.sessionId}/terminals`, + { name: 'suyo', command: 'sh' }, + other.token, + ) + ).body as TerminalBody; + + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'mío', command: 'sh', id: taken.id }, + owner.token, + ); + expect(res.status).toBe(409); + }); + + it('rejects a non-uuid id with 400', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + expect( + (await post( + `/sessions/${sessionId}/terminals`, + { name: 's', command: 'x', id: 'nope' }, + owner.token, + )).status, + ).toBe(400); + }); +}); + +describe('PATCH /sessions/:id/terminals/:terminalId', () => { + it('patches one field for the owner and keeps the rest (200)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', args: ['-l'], cwd: '/tmp', agent: 'claude' }, + owner.token, + ) + ).body as TerminalBody; + + const res = await patch( + `/sessions/${sessionId}/terminals/${created.id}`, + { name: 'renamed' }, + owner.token, + ); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + id: created.id, + name: 'renamed', + command: 'sh', + args: ['-l'], + cwd: '/tmp', + agent: 'claude', + minimized: false, + }); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals[0]).toEqual(res.body); + }); + + it('clears agent/minimized/cwd with null and toggles minimized', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post( + `/sessions/${sessionId}/terminals`, + { name: 'claude', command: 'claude', agent: 'claude', minimized: false, cwd: '/tmp' }, + owner.token, + ) + ).body as TerminalBody; + + const res = await patch( + `/sessions/${sessionId}/terminals/${created.id}`, + { agent: null, minimized: true, cwd: null }, + owner.token, + ); + expect(res.status).toBe(200); + expect(res.body).toEqual({ + id: created.id, + name: 'claude', + command: 'claude', + args: [], + cwd: null, + agent: null, + minimized: true, + }); + }); + + it('never accepts seq or env anywhere in the body (S14)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/${created.id}`; + + expect((await patch(path, { seq: 3 }, owner.token)).status).toBe(400); + expect((await patch(path, { env: [['K', 'V']] }, owner.token)).status).toBe(400); + }); + + it('rejects invalid partial bodies with 400', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/${created.id}`; + + expect((await patch(path, { name: 42 }, owner.token)).status).toBe(400); + expect((await patch(path, { command: ' ' }, owner.token)).status).toBe(400); + expect((await patch(path, { args: 'x' }, owner.token)).status).toBe(400); + expect((await patch(path, { cwd: 7 }, owner.token)).status).toBe(400); + expect((await patch(path, { minimized: 1 }, owner.token)).status).toBe(400); + // An empty patch is a valid no-op. + expect((await patch(path, {}, owner.token)).status).toBe(200); + }); + + it('keeps the existing access matrix', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/${created.id}`; + + expect((await patch(path, { name: 'x' }, member.token)).status).toBe(403); + // A stranger probing a terminal id of a session they cannot see gets 403, not 404. + expect((await patch(path, { name: 'x' }, stranger.token)).status).toBe(403); + expect( + (await patch( + `/sessions/${sessionId}/terminals/00000000-0000-0000-0000-000000000000`, + { name: 'x' }, + owner.token, + )).status, + ).toBe(404); + expect( + (await patch( + '/sessions/00000000-0000-0000-0000-000000000000/terminals/00000000-0000-0000-0000-000000000000', + { name: 'x' }, + owner.token, + )).status, + ).toBe(404); + expect((await patch(path, { name: 'x' })).status).toBe(401); + }); +}); + +describe('PUT /sessions/:id/terminals/order', () => { + it('applies the new order and returns the terminal views in it (200)', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + for (const [index, id] of [ + '40000000-0000-4000-8000-000000000001', + '40000000-0000-4000-8000-000000000002', + '40000000-0000-4000-8000-000000000003', + ].entries()) { + await post(`/sessions/${sessionId}/terminals`, { name: `t${index}`, command: 'sh', id }, owner.token); + } + const created = ((await get(`/sessions/${sessionId}`, owner.token)).body as { terminals: TerminalBody[] }) + .terminals; + const want = [created[2]!.id, created[0]!.id, created[1]!.id]; + + const res = await put(`/sessions/${sessionId}/terminals/order`, { ids: want }, owner.token); + expect(res.status).toBe(200); + const views = res.body as TerminalBody[]; + expect(views.map((v) => v.id)).toEqual(want); + expect(views.map((v) => v.name)).toEqual(['t2', 't0', 't1']); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(detail.terminals.map((tm) => tm.id)).toEqual(want); + + // `position` is atomically rewritten to match the array order. + const rows = await t.prisma.terminal.findMany({ where: { sessionId }, orderBy: { position: 'asc' } }); + expect(rows.map((r) => r.id)).toEqual(want); + expect(rows.map((r) => r.position)).toEqual([0, 1, 2]); + }); + + it('returns 400 for duplicates, an omission or an unknown id', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const first = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'a', command: 'sh' }, owner.token) + ).body as TerminalBody; + const second = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'b', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/order`; + + expect((await put(path, { ids: [first.id, first.id] }, owner.token)).status).toBe(400); + expect((await put(path, { ids: [first.id] }, owner.token)).status).toBe(400); + expect( + (await put(path, { ids: ['40000000-0000-4000-8000-000000009999'] }, owner.token)).status, + ).toBe(400); + expect( + (await put( + path, + { ids: [first.id, second.id, '40000000-0000-4000-8000-000000009999'] }, + owner.token, + )).status, + ).toBe(400); + expect((await put(path, { ids: [] }, owner.token)).status).toBe(400); + expect((await put(path, { ids: [first.id], extra: true }, owner.token)).status).toBe(400); + expect((await put(path, { ids: 'a,b' }, owner.token)).status).toBe(400); + }); + + it('keeps the existing access matrix', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const { wsId, sessionId } = await seedSession(owner.token); + await seedMember(wsId as WorkspaceId, owner.id as UserId, member.id as UserId); + const created = ( + await post(`/sessions/${sessionId}/terminals`, { name: 'sh', command: 'sh' }, owner.token) + ).body as TerminalBody; + const path = `/sessions/${sessionId}/terminals/order`; + + expect((await put(path, { ids: [created.id] }, member.token)).status).toBe(403); + expect((await put(path, { ids: [created.id] }, stranger.token)).status).toBe(403); + expect( + (await put('/sessions/00000000-0000-0000-0000-000000000000/terminals/order', { ids: [] }, owner.token)) + .status, + ).toBe(404); + expect((await put(path, { ids: [created.id] })).status).toBe(401); + }); +}); + +describe('terminal view shape (additive, never seq/env)', () => { + it('exposes exactly the seven snapshot fields', async () => { + const owner = await registerUser(); + const { sessionId } = await seedSession(owner.token); + const res = await post( + `/sessions/${sessionId}/terminals`, + { name: 'sh', command: 'sh', agent: 'claude', minimized: true }, + owner.token, + ); + expect(Object.keys(res.body as object).sort()).toEqual([...TERMINAL_FIELDS]); + + const detail = (await get(`/sessions/${sessionId}`, owner.token)).body as { + terminals: TerminalBody[]; + }; + expect(Object.keys(detail.terminals[0] as object).sort()).toEqual([...TERMINAL_FIELDS]); + expect(JSON.stringify(detail)).not.toContain('"seq"'); + expect(JSON.stringify(detail)).not.toContain('"env"'); + }); +}); diff --git a/apps/api/src/collab/terminals.controller.ts b/apps/api/src/collab/terminals.controller.ts new file mode 100644 index 0000000..a069f07 --- /dev/null +++ b/apps/api/src/collab/terminals.controller.ts @@ -0,0 +1,118 @@ +import { + BadRequestException, + Body, + ConflictException, + Controller, + Delete, + ForbiddenException, + HttpCode, + Inject, + NotFoundException, + Param, + Patch, + Post, + Put, + Res, + UseGuards, +} from '@nestjs/common'; + +import type { SessionId, TerminalId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { + addTerminalSchema, + reorderTerminalsSchema, + updateTerminalSchema, + type AddTerminalBody, + type ReorderTerminalsBody, + type UpdateTerminalBody, +} from './dto'; +import { SessionService } from './session.service'; + +// Status passthrough for the tri-state create (201/200/409): the existing +// @HttpCode annotation cannot express a dynamic code. +interface Reply { + status(code: number): unknown; +} + +@Controller() +@UseGuards(AccessGuard) +export class TerminalsController { + constructor(@Inject(SessionService) private readonly service: SessionService) {} + + // S7: owner only; 403 for anyone else, 404 for an unknown session. A fresh + // id answers 201, an id the caller already owns answers its current + // terminal as 200 (idempotent), and a taken id answers 409. + @Post('sessions/:id/terminals') + async create( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(addTerminalSchema)) body: AddTerminalBody, + @Res({ passthrough: true }) reply: Reply, + ): Promise { + const result = await this.service.addTerminal(user.id, id as SessionId, body); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'conflict') throw new ConflictException(); + reply.status(result.kind === 'created' ? 201 : 200); + return result.view; + } + + // S7: partial update answers the new terminal view; non-owners answer 403 + // without learning whether the session or terminal exists; unknown sessions, + // sessions missing the terminal, or unknown terminals 404. + @Patch('sessions/:id/terminals/:terminalId') + async update( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Param('terminalId') terminalId: string, + @Body(new ZodPipe(updateTerminalSchema)) body: UpdateTerminalBody, + ) { + const result = await this.service.updateTerminal( + user.id, + id as SessionId, + terminalId as TerminalId, + body, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S7: the ids must be exactly the session's terminals; order requests that + // duplicate, omit or add ids answer 400 without touching stored state. + @Put('sessions/:id/terminals/order') + async reorder( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(reorderTerminalsSchema)) body: ReorderTerminalsBody, + ) { + const result = await this.service.reorderTerminals(user.id, id as SessionId, body); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + if (result.kind === 'bad-request') { + // The rule is the message; the submitted ids never echo back. + throw new BadRequestException('order must contain exactly the session terminals'); + } + return result.views; + } + + // S8: owner only; 204 on success, 404 for unknown session or terminal, + // 403 for anyone else (terminal existence stays hidden from non-owners). + @Delete('sessions/:id/terminals/:terminalId') + @HttpCode(204) + async remove( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Param('terminalId') terminalId: string, + ) { + const result = await this.service.removeTerminal( + user.id, + id as SessionId, + terminalId as TerminalId, + ); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + } +} diff --git a/apps/api/src/collab/test-app.ts b/apps/api/src/collab/test-app.ts new file mode 100644 index 0000000..3453db1 --- /dev/null +++ b/apps/api/src/collab/test-app.ts @@ -0,0 +1,60 @@ +import type { INestApplication } from '@nestjs/common'; +import { Test } from '@nestjs/testing'; + +import type { PrismaClient } from '../generated/prisma/client'; +import { AuthModule } from '../auth/auth.module'; +import { applyHttpConfig } from '../auth/http-config'; +import { AUTH_CONFIG, type AuthConfig } from '../auth/config'; +import { CLOCK } from '../auth/clock'; +import { OAUTH_PROVIDERS } from '../auth/oauth-provider'; +import { TestClock } from '../auth/test-app'; +import { PRISMA } from '../persistence/persistence.module'; +import { openTestClient } from '../persistence/test-db'; +import { CollabModule } from './collab.module'; + +export const TEST_SECRET = 'test-secret-test-secret-test-secret-test'; + +export interface CollabTestApp { + app: INestApplication; + prisma: PrismaClient; + clock: TestClock; + baseUrl: string; + close(): Promise; +} + +export async function startCollabTestApp(): Promise { + const prisma = openTestClient(); + const clock = new TestClock(); + const config: AuthConfig = { + jwtSecret: TEST_SECRET, + databaseUrl: 'unused', + publicBaseUrl: 'http://api.test', + webOrigin: 'http://web.test', + oauth: {}, + rateLimitEnabled: false, + trustProxy: false, + }; + const moduleRef = await Test.createTestingModule({ imports: [AuthModule, CollabModule] }) + .overrideProvider(PRISMA) + .useValue(prisma) + .overrideProvider(AUTH_CONFIG) + .useValue(config) + .overrideProvider(OAUTH_PROVIDERS) + .useValue({}) + .overrideProvider(CLOCK) + .useValue(clock) + .compile(); + const app = moduleRef.createNestApplication(); + applyHttpConfig(app, config); + await app.listen(0, '127.0.0.1'); + return { + app, + prisma, + clock, + baseUrl: await app.getUrl(), + close: async () => { + await app.close(); + await prisma.$disconnect(); + }, + }; +} diff --git a/apps/api/src/collab/views.ts b/apps/api/src/collab/views.ts new file mode 100644 index 0000000..4c79aed --- /dev/null +++ b/apps/api/src/collab/views.ts @@ -0,0 +1,93 @@ +import type { UserRecord } from '../persistence/user.repository'; +import type { Session, SessionId, Terminal, TerminalId, UserId, Workspace, WorkspaceId } from '@opencollab/domain'; + +export interface WorkspaceSummary { + id: WorkspaceId; + name: string; + owner: UserId; + memberCount: number; +} + +export interface MemberView { + userId: UserId; + username: string; + displayName: string; +} + +export interface WorkspaceDetail { + id: WorkspaceId; + name: string; + owner: UserId; + members: MemberView[]; +} + +export function toWorkspaceSummary(ws: Workspace): WorkspaceSummary { + return { id: ws.id, name: ws.name, owner: ws.owner, memberCount: ws.members.length }; +} + +export interface TerminalView { + id: TerminalId; + name: string; + command: string; + args: string[]; + cwd: string | null; + // Snapshot metadata (S7): which agent the pane launches, and its collapsed + // state. Always present over the wire; never `seq` or `env` (S7/A1). + agent: string | null; + minimized: boolean; +} + +export interface SessionView { + id: SessionId; + name: string; + terminals: TerminalView[]; +} + +// `cwd` is nullable: a terminal without an explicit working directory +// persists as null. `env` is never part of the projection (S7). +export function toTerminalView(terminal: Terminal): TerminalView { + return { + id: terminal.id, + name: terminal.profile.name, + command: terminal.profile.command, + args: terminal.profile.args, + cwd: terminal.profile.cwd ?? null, + agent: terminal.agent ?? null, + minimized: terminal.minimized ?? false, + }; +} + +// Terminals stay in the aggregate's position order (S5). +export function toSessionView(session: Session): SessionView { + return { + id: session.id, + name: session.name, + terminals: session.terminals.map(toTerminalView), + }; +} + +// `usersById` supplies the display fields for the member ids; ids missing from +// the map (deleted users) are dropped from the view. +export function toWorkspaceDetail(ws: Workspace, usersById: Map): WorkspaceDetail { + const members: MemberView[] = []; + for (const m of ws.members) { + const user = usersById.get(m.userId); + if (user) { + members.push({ userId: user.id, username: user.username, displayName: user.displayName }); + } + } + return { id: ws.id, name: ws.name, owner: ws.owner, members }; +} + +export type InvitationTargetView = + | { kind: 'workspace'; workspaceId: WorkspaceId; name: string } + | { kind: 'session'; sessionId: SessionId; name: string }; + +// S9-S11: what an invitation looks like over the wire. Lifecycle fields +// (status, expiresAt) are deliberately absent: they are server bookkeeping, +// and S12/S13 signal them through status codes instead. +export interface InvitationView { + id: string; + target: InvitationTargetView; + invitedBy: { userId: UserId; username: string; displayName: string }; +} diff --git a/apps/api/src/collab/workspace.service.ts b/apps/api/src/collab/workspace.service.ts new file mode 100644 index 0000000..576069c --- /dev/null +++ b/apps/api/src/collab/workspace.service.ts @@ -0,0 +1,96 @@ +import { Inject, Injectable } from '@nestjs/common'; + +import { Workspace, type UserId, type WorkspaceId } from '@opencollab/domain'; + +import { UserRepository } from '../persistence/user.repository'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { toWorkspaceDetail, toWorkspaceSummary, type WorkspaceDetail, type WorkspaceSummary } from './views'; + +export type WorkspaceLookup = + | { kind: 'ok'; workspace: Workspace } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +// S7: the explicit-id create answers the current view when the caller already +// owns that id (idempotent), and 409 when someone else owns it. +export type WorkspaceCreateResult = + | { kind: 'created'; view: WorkspaceDetail } + | { kind: 'existing'; view: WorkspaceDetail } + | { kind: 'conflict' }; + +// Rename/remove are owner actions: a member who can read still answers 403, +// with the same not-found/forbidden classification as GET detail. +export type WorkspaceRenameResult = + | { kind: 'ok'; view: WorkspaceDetail } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +export type WorkspaceRemoveResult = + | { kind: 'removed' } + | { kind: 'not-found' } + | { kind: 'forbidden' }; + +@Injectable() +export class WorkspaceService { + constructor( + @Inject(WorkspaceRepository) private readonly workspaces: WorkspaceRepository, + @Inject(UserRepository) private readonly users: UserRepository, + ) {} + + async create(actor: UserId, input: { name: string; id?: string }): Promise { + if (input.id !== undefined) { + const existing = await this.workspaces.find(input.id as WorkspaceId); + if (existing) { + if (!existing.isOwner(actor)) return { kind: 'conflict' }; + return { kind: 'existing', view: await this.detail(existing) }; + } + } + const ws = new Workspace(actor, input.name, ...(input.id === undefined ? [] : [input.id as WorkspaceId])); + await this.workspaces.save(ws); + return { kind: 'created', view: await this.detail(ws) }; + } + + async listFor(actor: UserId): Promise { + const list = await this.workspaces.listForUser(actor); + return list.map(toWorkspaceSummary); + } + + // Loads a workspace and classifies the caller's access so the controller can + // answer 404 vs 403 without leaking existence to strangers. + async lookup(id: WorkspaceId, actor: UserId): Promise { + const ws = await this.workspaces.find(id); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor) && !ws.isMember(actor)) return { kind: 'forbidden' }; + return { kind: 'ok', workspace: ws }; + } + + // Mutations are owner actions: members who can read still answer 403. + private async owned(id: WorkspaceId, actor: UserId): Promise { + const ws = await this.workspaces.find(id); + if (!ws) return { kind: 'not-found' }; + if (!ws.isOwner(actor)) return { kind: 'forbidden' }; + return { kind: 'ok', workspace: ws }; + } + + async rename(actor: UserId, id: WorkspaceId, name: string): Promise { + const owned = await this.owned(id, actor); + if (owned.kind !== 'ok') return owned; + // Unreachable NotOwner: the classification above is the same check. + owned.workspace.rename(actor, name); + await this.workspaces.save(owned.workspace); + return { kind: 'ok', view: await this.detail(owned.workspace) }; + } + + async remove(actor: UserId, id: WorkspaceId): Promise { + const owned = await this.owned(id, actor); + if (owned.kind !== 'ok') return owned; + await this.workspaces.delete(id); + return { kind: 'removed' }; + } + + async detail(ws: Workspace): Promise { + const ids = [ws.owner, ...ws.members.map((m) => m.userId)]; + const users = await this.users.findByIds(ids); + return toWorkspaceDetail(ws, new Map(users.map((u) => [u.id, u]))); + } +} diff --git a/apps/api/src/collab/workspaces.controller.int.spec.ts b/apps/api/src/collab/workspaces.controller.int.spec.ts new file mode 100644 index 0000000..6aa417b --- /dev/null +++ b/apps/api/src/collab/workspaces.controller.int.spec.ts @@ -0,0 +1,275 @@ +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +import { Workspace } from '@opencollab/domain'; +import type { UserId, WorkspaceId } from '@opencollab/domain'; +import { WorkspaceRepository } from '../persistence/workspace.repository'; +import { truncateAll } from '../persistence/test-db'; +import { startCollabTestApp, type CollabTestApp } from './test-app'; + +let t: CollabTestApp; +let workspaces: WorkspaceRepository; + +beforeAll(async () => { + t = await startCollabTestApp(); + workspaces = new WorkspaceRepository(t.prisma); +}); +afterAll(() => t.close()); +beforeEach(() => truncateAll(t.prisma)); + +interface Res { + status: number; + body: unknown; +} + +async function call(method: string, path: string, body?: unknown, token?: string): Promise { + const res = await fetch(`${t.baseUrl}${path}`, { + method, + headers: { + ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: body !== undefined ? JSON.stringify(body) : undefined, + }); + const text = await res.text(); + let parsed: unknown = undefined; + try { + parsed = text ? JSON.parse(text) : undefined; + } catch { + parsed = text; + } + return { status: res.status, body: parsed }; +} + +const get = (path: string, token?: string) => call('GET', path, undefined, token); +const post = (path: string, body?: unknown, token?: string) => call('POST', path, body ?? {}, token); +const del = (path: string, token?: string) => call('DELETE', path, undefined, token); +const patch = (path: string, body?: unknown, token?: string) => call('PATCH', path, body ?? {}, token); + +let counter = 0; +async function registerUser(prefix = 'user'): Promise<{ id: string; token: string }> { + counter += 1; + const username = `${prefix}${counter}`; + const res = await post('/auth/register', { + username, + password: 'correct horse battery', + displayName: prefix, + }); + expect(res.status).toBe(201); + const body = res.body as { accessToken: string; user: { id: string } }; + return { id: body.user.id, token: body.accessToken }; +} + +// Seeds a workspace with a member straight through the repository: the +// invitation endpoints belong to a later task, so this setup stays independent. +async function seedWorkspaceWithMember(ownerId: UserId, memberId: UserId, name: string): Promise { + const ws = new Workspace(ownerId, name); + ws.addMember(ownerId, memberId); + await workspaces.save(ws); + return ws.id; +} + +describe('POST /workspaces', () => { + it('creates a workspace with the caller as owner', async () => { + const { id, token } = await registerUser(); + const res = await post('/workspaces', { name: 'Proyecto X' }, token); + expect(res.status).toBe(201); + const body = res.body as { id: string; name: string; owner: string; members: unknown[] }; + expect(body.name).toBe('Proyecto X'); + expect(body.owner).toBe(id); + expect(body.members).toEqual([]); + }); + + it('rejects an unauthenticated request with 401', async () => { + const res = await post('/workspaces', { name: 'x' }); + expect(res.status).toBe(401); + }); + + it('rejects an empty or blank name with 400', async () => { + const { token } = await registerUser(); + expect((await post('/workspaces', { name: '' }, token)).status).toBe(400); + expect((await post('/workspaces', { name: ' ' }, token)).status).toBe(400); + }); + + it('rejects unknown fields with 400', async () => { + const { token } = await registerUser(); + const res = await post('/workspaces', { name: 'x', extra: true }, token); + expect(res.status).toBe(400); + }); +}); + +describe('GET /workspaces', () => { + it('lists only workspaces where the caller is owner or member', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + + const mine = (await post('/workspaces', { name: 'mine' }, owner.token)).body as { id: string }; + await post('/workspaces', { name: 'owned-by-member' }, member.token); + await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'shared'); + + const forOwner = (await get('/workspaces', owner.token)).body as { id: string; name: string }[]; + expect(forOwner.map((w) => w.name).sort()).toEqual(['mine', 'shared']); + + // Member owns 'owned-by-member' and belongs to 'shared' (seeded); they have + // no relation to 'mine', so it must not appear in their list. + const forMember = (await get('/workspaces', member.token)).body as { name: string }[]; + expect(forMember.map((w) => w.name).sort()).toEqual(['owned-by-member', 'shared']); + + const forStranger = (await get('/workspaces', stranger.token)).body as { name: string }[]; + expect(forStranger).toEqual([]); + expect(mine.id).toBeTruthy(); + }); +}); + +describe('GET /workspaces/:id', () => { + it('returns the detail with members for the owner', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'detail'); + + const res = await get(`/workspaces/${wsId}`, owner.token); + expect(res.status).toBe(200); + const body = res.body as { + id: string; + name: string; + owner: string; + members: { userId: string; username: string; displayName: string }[]; + }; + expect(body.id).toBe(wsId); + expect(body.name).toBe('detail'); + expect(body.owner).toBe(owner.id); + expect(body.members).toHaveLength(1); + expect(body.members[0]?.userId).toBe(member.id); + expect(body.members[0]?.username).toBeTruthy(); + expect(body.members[0]?.displayName).toBeTruthy(); + }); + + it('returns 404 for an unknown workspace and 403 for a stranger', async () => { + const owner = await registerUser(); + const stranger = await registerUser(); + const ws = (await post('/workspaces', { name: 'private' }, owner.token)).body as { id: string }; + + expect((await get('/workspaces/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + expect((await get(`/workspaces/${ws.id}`, stranger.token)).status).toBe(403); + }); +}); + +// S7: explicit ids let the desktop create idempotently (cloud round-trip). +describe('POST /workspaces with explicit id', () => { + it('creates the workspace with the caller-provided id (201)', async () => { + const owner = await registerUser(); + const id = '10000000-0000-4000-8000-000000000001'; + const res = await post('/workspaces', { name: 'Con id', id }, owner.token); + expect(res.status).toBe(201); + const body = res.body as { id: string; name: string; owner: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Con id'); + expect(body.owner).toBe(owner.id); + }); + + it('returns 200 with the current view for a same-owner retry (idempotent)', async () => { + const owner = await registerUser(); + const id = '10000000-0000-4000-8000-000000000002'; + await post('/workspaces', { name: 'Original', id }, owner.token); + + const res = await post('/workspaces', { name: 'Original', id }, owner.token); + expect(res.status).toBe(200); + const body = res.body as { id: string; name: string; owner: string }; + expect(body.id).toBe(id); + expect(body.name).toBe('Original'); + // The retry created nothing extra. + const list = (await get('/workspaces', owner.token)).body as { id: string }[]; + expect(list.filter((w) => w.id === id)).toHaveLength(1); + }); + + it('returns 409 for another owner\'s id', async () => { + const first = await registerUser(); + const second = await registerUser(); + const taken = (await post('/workspaces', { name: 'mine' }, first.token)).body as { id: string }; + + const res = await post('/workspaces', { name: 'other', id: taken.id }, second.token); + expect(res.status).toBe(409); + }); + + it('rejects a non-uuid id with 400', async () => { + const owner = await registerUser(); + const res = await post('/workspaces', { name: 'x', id: 'not-a-uuid' }, owner.token); + expect(res.status).toBe(400); + }); +}); + +// S7: rename is an owner action behind the same classification as GET detail. +describe('PATCH /workspaces/:id', () => { + it('renames for the owner (200 with the current detail view)', async () => { + const owner = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, (await registerUser()).id as UserId, 'antes'); + + const res = await patch(`/workspaces/${wsId}`, { name: 'Renombrado' }, owner.token); + expect(res.status).toBe(200); + const body = res.body as { id: string; name: string; owner: string; members: unknown[] }; + expect(body.id).toBe(wsId); + expect(body.name).toBe('Renombrado'); + expect(body.owner).toBe(owner.id); + expect(body.members).toHaveLength(1); + + const persisted = await workspaces.find(wsId); + expect(persisted?.name).toBe('Renombrado'); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'privado'); + const ws = (await post('/workspaces', { name: 'hidden' }, owner.token)).body as { id: string }; + + expect((await patch(`/workspaces/${wsId}`, { name: 'x' }, member.token)).status).toBe(403); + expect((await patch(`/workspaces/${wsId}`, { name: 'x' }, stranger.token)).status).toBe(403); + // A member only got read access; the name they can see cannot be changed by them. + const memberRead = await get(`/workspaces/${wsId}`, member.token); + expect(memberRead.status).toBe(200); + expect((await patch(`/workspaces/${ws.id}`, { name: 'y' }, stranger.token)).status).toBe(403); + expect((await patch('/workspaces/00000000-0000-0000-0000-000000000000', { name: 'y' }, owner.token)).status).toBe(404); + expect((await patch(`/workspaces/${wsId}`, { name: 'y' })).status).toBe(401); + }); + + it('rejects a blank name with 400', async () => { + const owner = await registerUser(); + const ws = (await post('/workspaces', { name: 'x' }, owner.token)).body as { id: string }; + expect((await patch(`/workspaces/${ws.id}`, { name: '' }, owner.token)).status).toBe(400); + expect((await patch(`/workspaces/${ws.id}`, { name: ' ' }, owner.token)).status).toBe(400); + expect((await patch(`/workspaces/${ws.id}`, { extra: true }, owner.token)).status).toBe(400); + }); +}); + +describe('DELETE /workspaces/:id', () => { + it('deletes for the owner (204) and cascades sessions and terminals', async () => { + const owner = await registerUser(); + const wsId = (await post('/workspaces', { name: 'borrar' }, owner.token)).body as { id: string }; + const session = ( + await post(`/workspaces/${wsId.id}/sessions`, { name: 's' }, owner.token) + ).body as { id: string }; + await post(`/sessions/${session.id}/terminals`, { name: 't', command: 'sh' }, owner.token); + expect(await t.prisma.terminal.count()).toBe(1); + + const res = await del(`/workspaces/${wsId.id}`, owner.token); + expect(res.status).toBe(204); + + expect(await t.prisma.workspace.count()).toBe(0); + expect(await t.prisma.session.count()).toBe(0); + expect(await t.prisma.terminal.count()).toBe(0); + expect((await get(`/workspaces/${wsId.id}`, owner.token)).status).toBe(404); + }); + + it('returns 403 for a member and a stranger, 404 for unknown, 401 unauthenticated', async () => { + const owner = await registerUser(); + const member = await registerUser(); + const stranger = await registerUser(); + const wsId = await seedWorkspaceWithMember(owner.id as UserId, member.id as UserId, 'protegido'); + + expect((await del(`/workspaces/${wsId}`, member.token)).status).toBe(403); + expect((await del(`/workspaces/${wsId}`, stranger.token)).status).toBe(403); + expect((await del('/workspaces/00000000-0000-0000-0000-000000000000', owner.token)).status).toBe(404); + expect((await del(`/workspaces/${wsId}`)).status).toBe(401); + }); +}); diff --git a/apps/api/src/collab/workspaces.controller.ts b/apps/api/src/collab/workspaces.controller.ts new file mode 100644 index 0000000..d03a83e --- /dev/null +++ b/apps/api/src/collab/workspaces.controller.ts @@ -0,0 +1,92 @@ +import { + Body, + ConflictException, + Controller, + Delete, + ForbiddenException, + Get, + HttpCode, + HttpStatus, + Inject, + NotFoundException, + Param, + Patch, + Post, + Res, + UseGuards, +} from '@nestjs/common'; + +import type { WorkspaceId } from '@opencollab/domain'; +import { AccessGuard, CurrentUser } from '../auth/access.guard'; +import { ZodPipe } from '../auth/dto'; +import type { UserRecord } from '../persistence/user.repository'; +import { + createWorkspaceSchema, + renameWorkspaceSchema, + type CreateWorkspaceBody, + type RenameWorkspaceBody, +} from './dto'; +import { WorkspaceService } from './workspace.service'; + +// Status passthrough for the tri-state create (201/200/409): the existing +// @HttpCode annotation cannot express a dynamic code. +interface Reply { + status(code: number): unknown; +} + +@Controller('workspaces') +@UseGuards(AccessGuard) +export class WorkspacesController { + constructor(@Inject(WorkspaceService) private readonly service: WorkspaceService) {} + + // S7: a fresh id answers 201, an id the caller already owns answers its + // current view as 200 (idempotent), and a taken id answers 409. + @Post() + async create( + @CurrentUser() user: UserRecord, + @Body(new ZodPipe(createWorkspaceSchema)) body: CreateWorkspaceBody, + @Res({ passthrough: true }) reply: Reply, + ): Promise { + const result = await this.service.create(user.id, body); + if (result.kind === 'conflict') throw new ConflictException(); + reply.status(result.kind === 'created' ? 201 : 200); + return result.view; + } + + @Get() + list(@CurrentUser() user: UserRecord) { + return this.service.listFor(user.id); + } + + @Get(':id') + async get(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.lookup(id as WorkspaceId, user.id); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return this.service.detail(result.workspace); + } + + // S7: rename answers the detail view; members and strangers answer 403, + // unknown workspaces 404 — same classification as GET detail. + @Patch(':id') + async rename( + @CurrentUser() user: UserRecord, + @Param('id') id: string, + @Body(new ZodPipe(renameWorkspaceSchema)) body: RenameWorkspaceBody, + ) { + const result = await this.service.rename(user.id, id as WorkspaceId, body.name); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + return result.view; + } + + // S7: delete returns 204 with no body; members and strangers answer 403, + // unknown workspaces 404. + @Delete(':id') + @HttpCode(HttpStatus.NO_CONTENT) + async remove(@CurrentUser() user: UserRecord, @Param('id') id: string) { + const result = await this.service.remove(user.id, id as WorkspaceId); + if (result.kind === 'not-found') throw new NotFoundException(); + if (result.kind === 'forbidden') throw new ForbiddenException(); + } +} diff --git a/apps/server/src/compose.spec.ts b/apps/api/src/compose.spec.ts similarity index 100% rename from apps/server/src/compose.spec.ts rename to apps/api/src/compose.spec.ts diff --git a/apps/server/src/connection-deadline.spec.ts b/apps/api/src/connection-deadline.spec.ts similarity index 100% rename from apps/server/src/connection-deadline.spec.ts rename to apps/api/src/connection-deadline.spec.ts diff --git a/apps/server/src/connection-deadline.ts b/apps/api/src/connection-deadline.ts similarity index 100% rename from apps/server/src/connection-deadline.ts rename to apps/api/src/connection-deadline.ts diff --git a/apps/server/src/connection-policy.ts b/apps/api/src/connection-policy.ts similarity index 100% rename from apps/server/src/connection-policy.ts rename to apps/api/src/connection-policy.ts diff --git a/apps/server/src/handshake.spec.ts b/apps/api/src/handshake.spec.ts similarity index 100% rename from apps/server/src/handshake.spec.ts rename to apps/api/src/handshake.spec.ts diff --git a/apps/server/src/handshake.ts b/apps/api/src/handshake.ts similarity index 100% rename from apps/server/src/handshake.ts rename to apps/api/src/handshake.ts diff --git a/apps/server/src/health.controller.ts b/apps/api/src/health.controller.ts similarity index 100% rename from apps/server/src/health.controller.ts rename to apps/api/src/health.controller.ts diff --git a/apps/server/src/hub.spec.ts b/apps/api/src/hub.spec.ts similarity index 99% rename from apps/server/src/hub.spec.ts rename to apps/api/src/hub.spec.ts index e7598a0..cb58891 100644 --- a/apps/server/src/hub.spec.ts +++ b/apps/api/src/hub.spec.ts @@ -9,7 +9,7 @@ import { type SessionId, type TerminalId, type UserId, -} from './domain'; +} from '@opencollab/domain'; import { SessionHub, UNAVAILABLE, type HubConnection, type SessionStore } from './hub'; import { FORBIDDEN, @@ -18,7 +18,7 @@ import { NOT_JOINED, UNAUTHORIZED, type Message, -} from './protocol'; +} from '@opencollab/contracts'; class FakeConn implements HubConnection { readonly sent: string[] = []; diff --git a/apps/server/src/hub.ts b/apps/api/src/hub.ts similarity index 99% rename from apps/server/src/hub.ts rename to apps/api/src/hub.ts index fe1beb6..09cfc9a 100644 --- a/apps/server/src/hub.ts +++ b/apps/api/src/hub.ts @@ -8,8 +8,8 @@ import { type TerminalId, type UserId, type Workspace, -} from './domain'; -import { FORBIDDEN, NOT_JOINED, PROTOCOL_VERSION, UNAUTHORIZED, parseFrame, type Message } from './protocol'; +} from '@opencollab/domain'; +import { FORBIDDEN, NOT_JOINED, PROTOCOL_VERSION, UNAUTHORIZED, parseFrame, type Message } from '@opencollab/contracts'; /** Nest injection token for the hub's `SessionStore` port. */ export const SESSION_STORE = Symbol('SESSION_STORE'); diff --git a/apps/server/src/main.ts b/apps/api/src/main.ts similarity index 100% rename from apps/server/src/main.ts rename to apps/api/src/main.ts diff --git a/apps/server/src/persistence/auth.repository.int.spec.ts b/apps/api/src/persistence/auth.repository.int.spec.ts similarity index 100% rename from apps/server/src/persistence/auth.repository.int.spec.ts rename to apps/api/src/persistence/auth.repository.int.spec.ts diff --git a/apps/server/src/persistence/auth.repository.ts b/apps/api/src/persistence/auth.repository.ts similarity index 99% rename from apps/server/src/persistence/auth.repository.ts rename to apps/api/src/persistence/auth.repository.ts index 06ade96..829a8a7 100644 --- a/apps/server/src/persistence/auth.repository.ts +++ b/apps/api/src/persistence/auth.repository.ts @@ -1,4 +1,4 @@ -import type { UserId } from '../domain'; +import type { UserId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import type { OAuthProvider } from '../generated/prisma/enums'; import { newUserData, toUserRecord, type NewUser, type UserRecord } from './user.repository'; diff --git a/apps/server/src/persistence/invitation.repository.int.spec.ts b/apps/api/src/persistence/invitation.repository.int.spec.ts similarity index 98% rename from apps/server/src/persistence/invitation.repository.int.spec.ts rename to apps/api/src/persistence/invitation.repository.int.spec.ts index 38dadac..c037856 100644 --- a/apps/server/src/persistence/invitation.repository.int.spec.ts +++ b/apps/api/src/persistence/invitation.repository.int.spec.ts @@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto'; import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { Session, Workspace, newInvitationId } from '../domain'; +import { Session, Workspace, newInvitationId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import { InvitationRepository } from './invitation.repository'; import { SessionRepository } from './session.repository'; diff --git a/apps/server/src/persistence/invitation.repository.ts b/apps/api/src/persistence/invitation.repository.ts similarity index 99% rename from apps/server/src/persistence/invitation.repository.ts rename to apps/api/src/persistence/invitation.repository.ts index 4bfbe79..988b371 100644 --- a/apps/server/src/persistence/invitation.repository.ts +++ b/apps/api/src/persistence/invitation.repository.ts @@ -5,7 +5,7 @@ import type { SessionId, UserId, WorkspaceId, -} from '../domain'; +} from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import type { InvitationKind, InvitationStatus as DbStatus } from '../generated/prisma/enums'; diff --git a/apps/server/src/persistence/mappers.ts b/apps/api/src/persistence/mappers.ts similarity index 88% rename from apps/server/src/persistence/mappers.ts rename to apps/api/src/persistence/mappers.ts index a7b2216..5530d25 100644 --- a/apps/server/src/persistence/mappers.ts +++ b/apps/api/src/persistence/mappers.ts @@ -1,4 +1,4 @@ -import type { AccessLevel } from '../domain'; +import type { AccessLevel } from '@opencollab/domain'; import type { AccessLevel as DbAccessLevel } from '../generated/prisma/enums'; const TO_DB: Record = { none: 'NONE', view: 'VIEW', write: 'WRITE' }; diff --git a/apps/server/src/persistence/persistence.module.ts b/apps/api/src/persistence/persistence.module.ts similarity index 86% rename from apps/server/src/persistence/persistence.module.ts rename to apps/api/src/persistence/persistence.module.ts index b9e2373..f4e0d90 100644 --- a/apps/server/src/persistence/persistence.module.ts +++ b/apps/api/src/persistence/persistence.module.ts @@ -3,6 +3,7 @@ import { Inject, Module, type OnApplicationShutdown } from '@nestjs/common'; import type { PrismaClient } from '../generated/prisma/client'; import { AuthRepository } from './auth.repository'; import { createPrismaClient } from './prisma'; +import { InvitationRepository } from './invitation.repository'; import { SessionRepository } from './session.repository'; import { UserRepository } from './user.repository'; import { WorkspaceRepository } from './workspace.repository'; @@ -22,9 +23,10 @@ export const PRISMA = Symbol('PRISMA'); { provide: UserRepository, useFactory: (p: PrismaClient) => new UserRepository(p), inject: [PRISMA] }, { provide: AuthRepository, useFactory: (p: PrismaClient) => new AuthRepository(p), inject: [PRISMA] }, { provide: SessionRepository, useFactory: (p: PrismaClient) => new SessionRepository(p), inject: [PRISMA] }, + { provide: InvitationRepository, useFactory: (p: PrismaClient) => new InvitationRepository(p), inject: [PRISMA] }, { provide: WorkspaceRepository, useFactory: (p: PrismaClient) => new WorkspaceRepository(p), inject: [PRISMA] }, ], - exports: [PRISMA, UserRepository, AuthRepository, SessionRepository, WorkspaceRepository], + exports: [PRISMA, UserRepository, AuthRepository, SessionRepository, InvitationRepository, WorkspaceRepository], }) export class PersistenceModule implements OnApplicationShutdown { constructor(@Inject(PRISMA) private readonly prisma: PrismaClient) {} diff --git a/apps/server/src/persistence/prisma.ts b/apps/api/src/persistence/prisma.ts similarity index 100% rename from apps/server/src/persistence/prisma.ts rename to apps/api/src/persistence/prisma.ts diff --git a/apps/server/src/persistence/session-store.int.spec.ts b/apps/api/src/persistence/session-store.int.spec.ts similarity index 97% rename from apps/server/src/persistence/session-store.int.spec.ts rename to apps/api/src/persistence/session-store.int.spec.ts index 0c05ac7..4fe1cad 100644 --- a/apps/server/src/persistence/session-store.int.spec.ts +++ b/apps/api/src/persistence/session-store.int.spec.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { Session, Workspace, newSessionId } from '../domain'; +import { Session, Workspace, newSessionId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import { RepositorySessionStore } from './session-store'; import { SessionRepository } from './session.repository'; diff --git a/apps/server/src/persistence/session-store.ts b/apps/api/src/persistence/session-store.ts similarity index 93% rename from apps/server/src/persistence/session-store.ts rename to apps/api/src/persistence/session-store.ts index dacdff5..ec278c0 100644 --- a/apps/server/src/persistence/session-store.ts +++ b/apps/api/src/persistence/session-store.ts @@ -1,4 +1,4 @@ -import type { Session, SessionId } from '../domain'; +import type { Session, SessionId } from '@opencollab/domain'; import type { SessionState, SessionStore } from '../hub'; import type { SessionRepository } from './session.repository'; import type { WorkspaceRepository } from './workspace.repository'; diff --git a/apps/server/src/persistence/session.repository.int.spec.ts b/apps/api/src/persistence/session.repository.int.spec.ts similarity index 74% rename from apps/server/src/persistence/session.repository.int.spec.ts rename to apps/api/src/persistence/session.repository.int.spec.ts index c7e28a4..2ddaffb 100644 --- a/apps/server/src/persistence/session.repository.int.spec.ts +++ b/apps/api/src/persistence/session.repository.int.spec.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { Session, Workspace, newAgentProfile, newSessionId } from '../domain'; +import { Session, Workspace, newAgentProfile, newSessionId, newTerminalId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import { SessionRepository } from './session.repository'; import { openTestClient, truncateAll } from './test-db'; @@ -130,4 +130,47 @@ describe('SessionRepository', () => { const listed = await sessions.listByWorkspace(f.workspace.id); expect(listed.map((s) => s.id).sort()).toEqual([f.session.id, second.id].sort()); }); + + // S7: agent and minimized round-trip through the cloud snapshot too. + it('round-trips terminal agent and minimized metadata', async () => { + const f = await fixture(); + const withMeta = f.session.addTerminal( + f.workspace, + f.owner, + newAgentProfile('claude', 'claude'), + { agent: 'claude', minimized: true }, + ); + const bare = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + await sessions.save(f.session); + + const rows = await prisma.terminal.findMany({ orderBy: { position: 'asc' } }); + expect(rows[0]).toMatchObject({ id: withMeta, agent: 'claude', minimized: true }); + expect(rows[1]).toMatchObject({ id: bare, agent: null, minimized: false }); + + const loaded = await sessions.find(f.session.id); + expect(loaded?.terminals.find((tm) => tm.id === withMeta)).toEqual({ + id: withMeta, + profile: { name: 'claude', command: 'claude', args: [], env: [] }, + agent: 'claude', + minimized: true, + }); + expect(loaded?.terminals.find((tm) => tm.id === bare)).toEqual({ + id: bare, + profile: { name: 'shell', command: 'sh', args: [], env: [] }, + agent: null, + minimized: false, + }); + }); + + it('resolves the owning workspace owner of a terminal id (idempotent-create check)', async () => { + const f = await fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('a', 'sh')); + await sessions.save(f.session); + const owned = await sessions.terminalWithOwner(id); + expect(owned).toEqual({ + ownerId: f.workspace.owner, + terminal: expect.objectContaining({ id }), + }); + expect(await sessions.terminalWithOwner(newTerminalId())).toBeUndefined(); + }); }); diff --git a/apps/server/src/persistence/session.repository.ts b/apps/api/src/persistence/session.repository.ts similarity index 61% rename from apps/server/src/persistence/session.repository.ts rename to apps/api/src/persistence/session.repository.ts index 34cb305..b8364a9 100644 --- a/apps/server/src/persistence/session.repository.ts +++ b/apps/api/src/persistence/session.repository.ts @@ -1,12 +1,13 @@ import { Session, + newTerminal, type SessionGuest, type SessionId, type Terminal, type TerminalId, type UserId, type WorkspaceId, -} from '../domain'; +} from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import type { AccessLevel as DbAccessLevel } from '../generated/prisma/enums'; import { accessFromDb, accessToDb } from './mappers'; @@ -21,7 +22,15 @@ interface SessionRow { id: string; workspaceId: string; name: string; - terminals: { id: string; name: string; command: string; args: string[]; cwd: string | null }[]; + terminals: { + id: string; + name: string; + command: string; + args: string[]; + cwd: string | null; + agent: string | null; + minimized: boolean; + }[]; overrides: { userId: string; access: DbAccessLevel }[]; guests: { userId: string; access: DbAccessLevel }[]; } @@ -50,6 +59,46 @@ export class SessionRepository { return rows.map(restore); } + // Removes the aggregate row; terminals, overrides, guests and invitations + // follow the schema's onDelete cascade. + async delete(id: SessionId): Promise { + // deleteMany over delete: an id raced away between the controller's + // existence check and here must not turn into a P2025 500. + await this.prisma.session.deleteMany({ where: { id } }); + } + + // Ownership projection for idempotent terminal creates (S7): the terminal + // and the owner of the workspace its session belongs to. Undefined when the + // id is free (globally unique primary key). + async terminalWithOwner(id: TerminalId): Promise<{ terminal: Terminal; ownerId: UserId } | undefined> { + const row = await this.prisma.terminal.findUnique({ + where: { id }, + select: { + id: true, + name: true, + command: true, + args: true, + cwd: true, + agent: true, + minimized: true, + session: { select: { workspace: { select: { ownerId: true } } } }, + }, + }); + if (!row) return undefined; + const terminal = newTerminal( + row.id as TerminalId, + { + name: row.name, + command: row.command, + args: row.args, + env: [], + ...(row.cwd === null ? {} : { cwd: row.cwd }), + }, + { agent: row.agent, minimized: row.minimized }, + ); + return { terminal, ownerId: row.session.workspace.ownerId as UserId }; + } + // Upserts the session and replaces its terminals (position = index), // overrides and guests, all in one transaction. async save(session: Session): Promise { @@ -69,6 +118,9 @@ export class SessionRepository { command: t.profile.command, args: t.profile.args, cwd: t.profile.cwd ?? null, + // Snapshot metadata (S7); a missing key means the domain default. + agent: t.agent ?? null, + minimized: t.minimized ?? false, env: [], })), }), @@ -93,16 +145,20 @@ export class SessionRepository { } function restore(row: SessionRow): Session { - const terminals: Terminal[] = row.terminals.map((t) => ({ - id: t.id as TerminalId, - profile: { - name: t.name, - command: t.command, - args: t.args, - env: [], - ...(t.cwd === null ? {} : { cwd: t.cwd }), - }, - })); + // Terminal.env is NOT persisted (secrets): rehydrated as [], always. + const terminals: Terminal[] = row.terminals.map((t) => + newTerminal( + t.id as TerminalId, + { + name: t.name, + command: t.command, + args: t.args, + env: [], + ...(t.cwd === null ? {} : { cwd: t.cwd }), + }, + { agent: t.agent, minimized: t.minimized }, + ), + ); const guests: SessionGuest[] = row.guests.map((g) => ({ userId: g.userId as UserId, access: accessFromDb(g.access), diff --git a/apps/server/src/persistence/test-db.ts b/apps/api/src/persistence/test-db.ts similarity index 100% rename from apps/server/src/persistence/test-db.ts rename to apps/api/src/persistence/test-db.ts diff --git a/apps/server/src/persistence/test-fixtures.ts b/apps/api/src/persistence/test-fixtures.ts similarity index 89% rename from apps/server/src/persistence/test-fixtures.ts rename to apps/api/src/persistence/test-fixtures.ts index 82c36b1..4ecd974 100644 --- a/apps/server/src/persistence/test-fixtures.ts +++ b/apps/api/src/persistence/test-fixtures.ts @@ -1,4 +1,4 @@ -import type { UserId } from '../domain'; +import type { UserId } from '@opencollab/domain'; import type { UserRepository } from './user.repository'; let counter = 0; diff --git a/apps/server/src/persistence/test-global-setup.ts b/apps/api/src/persistence/test-global-setup.ts similarity index 100% rename from apps/server/src/persistence/test-global-setup.ts rename to apps/api/src/persistence/test-global-setup.ts diff --git a/apps/server/src/persistence/user.repository.int.spec.ts b/apps/api/src/persistence/user.repository.int.spec.ts similarity index 98% rename from apps/server/src/persistence/user.repository.int.spec.ts rename to apps/api/src/persistence/user.repository.int.spec.ts index de0952a..34caf94 100644 --- a/apps/server/src/persistence/user.repository.int.spec.ts +++ b/apps/api/src/persistence/user.repository.int.spec.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { newUserId } from '../domain'; +import { newUserId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import { openTestClient, truncateAll } from './test-db'; import { UserRepository } from './user.repository'; diff --git a/apps/server/src/persistence/user.repository.ts b/apps/api/src/persistence/user.repository.ts similarity index 87% rename from apps/server/src/persistence/user.repository.ts rename to apps/api/src/persistence/user.repository.ts index 0ffa948..0f0a5f8 100644 --- a/apps/server/src/persistence/user.repository.ts +++ b/apps/api/src/persistence/user.repository.ts @@ -1,4 +1,4 @@ -import { newUserId, type UserId } from '../domain'; +import { newUserId, type UserId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; export interface UserRecord { @@ -54,6 +54,13 @@ export class UserRepository { return row ? toUserRecord(row) : undefined; } + // Batch lookup (member lists, invitation enrichment). Unknown ids are skipped. + async findByIds(ids: readonly UserId[]): Promise { + if (ids.length === 0) return []; + const rows = await this.prisma.user.findMany({ where: { id: { in: [...ids] } } }); + return rows.map(toUserRecord); + } + // An identifier containing `@` is an email, anything else a username. The // two namespaces never overlap, so a login is never ambiguous. async findByUsernameOrEmail(identifier: string): Promise { diff --git a/apps/server/src/persistence/workspace.repository.int.spec.ts b/apps/api/src/persistence/workspace.repository.int.spec.ts similarity index 76% rename from apps/server/src/persistence/workspace.repository.int.spec.ts rename to apps/api/src/persistence/workspace.repository.int.spec.ts index 1048f76..7b4ea3e 100644 --- a/apps/server/src/persistence/workspace.repository.int.spec.ts +++ b/apps/api/src/persistence/workspace.repository.int.spec.ts @@ -1,6 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; -import { Session, Workspace, newAgentProfile, newWorkspaceId } from '../domain'; +import { Session, Workspace, newAgentProfile, newWorkspaceId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; import { SessionRepository } from './session.repository'; import { openTestClient, truncateAll } from './test-db'; @@ -67,6 +67,33 @@ describe('WorkspaceRepository', () => { expect((await workspaces.find(ws.id))?.members).toHaveLength(1); }); + it('listForUser returns workspaces where the user is owner or member, and not others', async () => { + const owner = await seedUser(users); + const member = await seedUser(users); + const stranger = await seedUser(users); + const otherOwner = await seedUser(users); + + const mine = new Workspace(owner, 'mine'); + mine.addMember(owner, member); + await workspaces.save(mine); + + const shared = new Workspace(member, 'shared'); + await workspaces.save(shared); + + const foreign = new Workspace(otherOwner, 'foreign'); + await workspaces.save(foreign); + + // `mine` is owned by owner with member added; `shared` is owned by member only. + const forOwner = await workspaces.listForUser(owner); + expect(forOwner.map((w) => w.id)).toEqual([mine.id]); + + const forMember = await workspaces.listForUser(member); + expect(forMember.map((w) => w.id).sort()).toEqual([mine.id, shared.id].sort()); + + const forStranger = await workspaces.listForUser(stranger); + expect(forStranger).toEqual([]); + }); + it('deleting a workspace cascades to members, sessions and their children', async () => { const owner = await seedUser(users); const member = await seedUser(users); diff --git a/apps/server/src/persistence/workspace.repository.ts b/apps/api/src/persistence/workspace.repository.ts similarity index 57% rename from apps/server/src/persistence/workspace.repository.ts rename to apps/api/src/persistence/workspace.repository.ts index 47bccf9..e53e25b 100644 --- a/apps/server/src/persistence/workspace.repository.ts +++ b/apps/api/src/persistence/workspace.repository.ts @@ -1,4 +1,4 @@ -import { Workspace, type UserId, type WorkspaceId } from '../domain'; +import { Workspace, type UserId, type WorkspaceId } from '@opencollab/domain'; import type { PrismaClient } from '../generated/prisma/client'; // Aggregate-level port: the whole Workspace (with its members) in and out. @@ -19,6 +19,23 @@ export class WorkspaceRepository { }); } + // Every workspace where the user is owner or member, oldest first. + async listForUser(userId: UserId): Promise { + const rows = await this.prisma.workspace.findMany({ + where: { OR: [{ ownerId: userId }, { members: { some: { userId } } }] }, + include: { members: { orderBy: [{ joinedAt: 'asc' }, { userId: 'asc' }] } }, + orderBy: { createdAt: 'asc' }, + }); + return rows.map((row) => + Workspace.restore({ + id: row.id as WorkspaceId, + owner: row.ownerId as UserId, + name: row.name, + members: row.members.map((m) => m.userId as UserId), + }), + ); + } + // Upserts the workspace and makes the member rows match the aggregate. // Existing members keep their joinedAt. async save(workspace: Workspace): Promise { @@ -38,4 +55,12 @@ export class WorkspaceRepository { }), ]); } + + // Removes the aggregate row; members, sessions, terminals and invitations + // follow the schema's onDelete cascade. + async delete(id: WorkspaceId): Promise { + // deleteMany over delete: an id raced away between the controller's + // existence check and here must not turn into a P2025 500. + await this.prisma.workspace.deleteMany({ where: { id } }); + } } diff --git a/apps/server/src/protocol.spec.ts b/apps/api/src/protocol.spec.ts similarity index 99% rename from apps/server/src/protocol.spec.ts rename to apps/api/src/protocol.spec.ts index 679daef..5dae1dc 100644 --- a/apps/server/src/protocol.spec.ts +++ b/apps/api/src/protocol.spec.ts @@ -1,6 +1,6 @@ import { describe, expect, it } from 'vitest'; -import { INCOMPATIBLE_PROTOCOL_VERSION, INVALID_MESSAGE, UNAUTHORIZED, parseFrame } from './protocol'; +import { INCOMPATIBLE_PROTOCOL_VERSION, INVALID_MESSAGE, UNAUTHORIZED, parseFrame } from '@opencollab/contracts'; /** The raw error a frame would be answered with, or undefined when it is accepted. */ function replyForTextFrame(text: string): string | undefined { diff --git a/apps/server/tsconfig.build.json b/apps/api/tsconfig.build.json similarity index 100% rename from apps/server/tsconfig.build.json rename to apps/api/tsconfig.build.json diff --git a/apps/server/tsconfig.json b/apps/api/tsconfig.json similarity index 100% rename from apps/server/tsconfig.json rename to apps/api/tsconfig.json diff --git a/apps/server/vitest.config.mts b/apps/api/vitest.config.mts similarity index 100% rename from apps/server/vitest.config.mts rename to apps/api/vitest.config.mts diff --git a/apps/server/vitest.integration.config.mts b/apps/api/vitest.integration.config.mts similarity index 100% rename from apps/server/vitest.integration.config.mts rename to apps/api/vitest.integration.config.mts diff --git a/crates/application/Cargo.toml b/apps/desktop/core/application/Cargo.toml similarity index 100% rename from crates/application/Cargo.toml rename to apps/desktop/core/application/Cargo.toml diff --git a/crates/application/src/activity.rs b/apps/desktop/core/application/src/activity.rs similarity index 100% rename from crates/application/src/activity.rs rename to apps/desktop/core/application/src/activity.rs diff --git a/crates/application/src/agent_adapter.rs b/apps/desktop/core/application/src/agent_adapter.rs similarity index 100% rename from crates/application/src/agent_adapter.rs rename to apps/desktop/core/application/src/agent_adapter.rs diff --git a/crates/application/src/agent_detection.rs b/apps/desktop/core/application/src/agent_detection.rs similarity index 100% rename from crates/application/src/agent_detection.rs rename to apps/desktop/core/application/src/agent_detection.rs diff --git a/crates/application/src/agent_event.rs b/apps/desktop/core/application/src/agent_event.rs similarity index 100% rename from crates/application/src/agent_event.rs rename to apps/desktop/core/application/src/agent_event.rs diff --git a/crates/application/src/agent_state.rs b/apps/desktop/core/application/src/agent_state.rs similarity index 100% rename from crates/application/src/agent_state.rs rename to apps/desktop/core/application/src/agent_state.rs diff --git a/crates/application/src/collab_status.rs b/apps/desktop/core/application/src/collab_status.rs similarity index 71% rename from crates/application/src/collab_status.rs rename to apps/desktop/core/application/src/collab_status.rs index 9898a23..55bf188 100644 --- a/crates/application/src/collab_status.rs +++ b/apps/desktop/core/application/src/collab_status.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use domain::SessionId; use crate::error::AppError; -use crate::ports::{RelayProbe, WorkspaceRepository}; +use crate::ports::{RelayProbe, SessionRepository}; /// Resultado de sondear el relay. #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -39,11 +39,11 @@ impl CheckRelay { /// Cuántos participantes de la sesión tienen acceso (al menos Ver). Quien no /// puede ver la sesión no la está compartiendo con nadie, así que no cuenta. pub struct SessionCollaborators { - repo: Arc, + repo: Arc, } impl SessionCollaborators { - pub fn new(repo: Arc) -> Self { + pub fn new(repo: Arc) -> Self { Self { repo } } @@ -52,12 +52,8 @@ impl SessionCollaborators { .repo .find_session(session_id)? .ok_or(AppError::SessionNotFound(session_id))?; - let workspace = self - .repo - .find_workspace(session.workspace_id())? - .ok_or(AppError::WorkspaceNotFound(session.workspace_id()))?; Ok(session - .participants(&workspace) + .participants() .iter() .filter(|p| p.access.can_view()) .count()) @@ -70,7 +66,7 @@ mod tests { use std::sync::Mutex; use std::time::Duration; - use domain::{Session, UserId, Workspace, WorkspaceId}; + use domain::{AccessLevel, Session, UserId}; use super::*; use crate::ports::PortError; @@ -103,21 +99,10 @@ mod tests { #[derive(Default)] struct FakeRepo { - workspaces: Mutex>, sessions: Mutex>, } - impl WorkspaceRepository for FakeRepo { - fn find_workspace(&self, id: WorkspaceId) -> Result, PortError> { - Ok(self.workspaces.lock().unwrap().get(&id).cloned()) - } - fn save_workspace(&self, workspace: Workspace) -> Result<(), PortError> { - self.workspaces - .lock() - .unwrap() - .insert(workspace.id(), workspace); - Ok(()) - } + impl SessionRepository for FakeRepo { fn find_session(&self, id: SessionId) -> Result, PortError> { Ok(self.sessions.lock().unwrap().get(&id).cloned()) } @@ -128,32 +113,28 @@ mod tests { } struct World { - owner: UserId, - member: UserId, + viewer: UserId, session_id: SessionId, repo: Arc, } fn world() -> World { let owner = UserId::new(); - let member = UserId::new(); - let mut workspace = Workspace::new(owner, "proyecto"); - workspace.add_member(owner, member).unwrap(); - let session = Session::new(&workspace, owner, "sesión").unwrap(); + let viewer = UserId::new(); + let mut session = Session::new(owner, "sesión"); + session.set_access(viewer, AccessLevel::View).unwrap(); let session_id = session.id(); let repo = Arc::new(FakeRepo::default()); - repo.save_workspace(workspace).unwrap(); repo.save_session(session).unwrap(); World { - owner, - member, + viewer, session_id, repo, } } #[test] - fn counts_owner_and_members_with_default_view() { + fn counts_owner_and_viewers_granted_by_the_server() { let w = world(); let count = SessionCollaborators::new(w.repo.clone()).execute(w.session_id); assert_eq!(count, Ok(2)); @@ -162,17 +143,8 @@ mod tests { #[test] fn participant_without_view_is_not_counted() { let w = world(); - let workspace = w - .repo - .find_session(w.session_id) - .unwrap() - .map(|s| s.workspace_id()) - .and_then(|id| w.repo.find_workspace(id).unwrap()) - .unwrap(); let mut session = w.repo.find_session(w.session_id).unwrap().unwrap(); - session - .set_view(&workspace, w.owner, w.member, false) - .unwrap(); + session.set_access(w.viewer, AccessLevel::None).unwrap(); w.repo.save_session(session).unwrap(); let count = SessionCollaborators::new(w.repo.clone()).execute(w.session_id); assert_eq!(count, Ok(1)); diff --git a/crates/application/src/error.rs b/apps/desktop/core/application/src/error.rs similarity index 74% rename from crates/application/src/error.rs rename to apps/desktop/core/application/src/error.rs index fad2a11..8998207 100644 --- a/crates/application/src/error.rs +++ b/apps/desktop/core/application/src/error.rs @@ -1,4 +1,4 @@ -use domain::{DomainError, SessionId, TerminalId, UserId, WorkspaceId}; +use domain::{DomainError, SessionId, TerminalId, UserId}; use crate::ports::PortError; @@ -8,8 +8,6 @@ pub enum AppError { Domain(#[from] DomainError), #[error(transparent)] Port(#[from] PortError), - #[error("workspace {0} no encontrado")] - WorkspaceNotFound(WorkspaceId), #[error("sesión {0} no encontrada")] SessionNotFound(SessionId), #[error("{user} no tiene permiso de escritura en la terminal {terminal}")] diff --git a/crates/application/src/git.rs b/apps/desktop/core/application/src/git.rs similarity index 100% rename from crates/application/src/git.rs rename to apps/desktop/core/application/src/git.rs diff --git a/crates/application/src/lib.rs b/apps/desktop/core/application/src/lib.rs similarity index 72% rename from crates/application/src/lib.rs rename to apps/desktop/core/application/src/lib.rs index 01e6796..e2cb9b9 100644 --- a/crates/application/src/lib.rs +++ b/apps/desktop/core/application/src/lib.rs @@ -9,6 +9,7 @@ mod collab_status; mod error; pub mod git; pub mod ports; +pub mod storage; mod use_cases; pub use activity::{Activity, ActivityTracker}; @@ -22,7 +23,10 @@ pub use agent_state::AgentState; pub use collab_status::{CheckRelay, RelayStatus, SessionCollaborators}; pub use error::AppError; pub use git::Branch; +pub use storage::{ + StoredPane, StoredSession, StoredWorkspace, WorkspaceSnapshot, SNAPSHOT_VERSION, +}; pub use use_cases::{ - AccessChange, ChangeParticipantAccess, CloseTerminal, DetectTerminalAgents, InspectBranch, - LaunchTerminal, ListSubdirectories, ResizeTerminal, SendTerminalInput, + ApplyAccessLevel, CloseTerminal, DetectTerminalAgents, InspectBranch, LaunchTerminal, + ListSubdirectories, ResizeTerminal, SendTerminalInput, }; diff --git a/apps/desktop/core/application/src/ports.rs b/apps/desktop/core/application/src/ports.rs new file mode 100644 index 0000000..12ffad7 --- /dev/null +++ b/apps/desktop/core/application/src/ports.rs @@ -0,0 +1,208 @@ +//! Puertos que la infraestructura implementa. Sincrónicos a propósito: la +//! capa de aplicación no depende de un runtime async. + +use std::sync::Arc; +use std::time::Duration; + +use crate::agent_detection::ProcessInfo; +use crate::git::Branch; +use crate::storage::WorkspaceSnapshot; + +use domain::{AgentProfile, Session, SessionId, TerminalId}; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("{0}")] +pub struct PortError(pub String); + +impl PortError { + pub fn new(message: impl Into) -> Self { + Self(message.into()) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct TerminalSize { + pub cols: u16, + pub rows: u16, +} + +impl Default for TerminalSize { + fn default() -> Self { + Self { cols: 80, rows: 24 } + } +} + +/// Recibe la salida de los PTY. El adaptador de entrada (Tauri, relay) la +/// reenvía a quien corresponda. +pub trait TerminalOutputSink: Send + Sync { + fn output(&self, terminal: TerminalId, data: &[u8]); + fn exited(&self, terminal: TerminalId); +} + +pub trait PtyPort: Send + Sync { + fn spawn( + &self, + terminal: TerminalId, + profile: &AgentProfile, + size: TerminalSize, + sink: Arc, + ) -> Result<(), PortError>; + fn write(&self, terminal: TerminalId, data: &[u8]) -> Result<(), PortError>; + fn resize(&self, terminal: TerminalId, size: TerminalSize) -> Result<(), PortError>; + /// Termina el proceso. Si ya había terminado, no es un error. + fn kill(&self, terminal: TerminalId) -> Result<(), PortError>; + /// Pid del proceso raíz de la terminal, si sigue vivo. + fn process_id(&self, terminal: TerminalId) -> Option; +} + +/// Lectura de carpetas del disco local, para navegar desde el header de una terminal. +pub trait DirectoryBrowser: Send + Sync { + /// Nombres de las subcarpetas directas de `path` (sin orden garantizado). + fn subdirectories(&self, path: &std::path::Path) -> Result, PortError>; +} + +/// Lee el estado de git de una carpeta del disco local. +pub trait RepositoryInspector: Send + Sync { + /// Rama (o commit, si `HEAD` está desacoplado) de la carpeta, buscando hacia + /// arriba el repositorio que la contiene. `None` fuera de un repositorio. + fn current_branch(&self, path: &std::path::Path) -> Option; +} + +/// Foto de los procesos del sistema, para detectar qué corre en cada terminal. +pub trait ProcessInspector: Send + Sync { + fn snapshot(&self) -> Result, PortError>; +} + +/// Sondea al relay de colaboración. Bloquea hasta responder o agotar su timeout, +/// así que quien lo llame periódicamente debe hacerlo fuera del hilo de la UI. +pub trait RelayProbe: Send + Sync { + /// Tiempo de ida y vuelta si el relay respondió bien; error si no. + fn probe(&self) -> Result; +} + +/// Guarda la sesión local del host, incluido el nivel de acceso vigente que mandó el server. +pub trait SessionRepository: Send + Sync { + fn find_session(&self, id: SessionId) -> Result, PortError>; + fn save_session(&self, session: Session) -> Result<(), PortError>; +} + +/// Persiste el snapshot completo de la estructura del escritorio (workspaces, +/// sesiones y perfiles de arranque de las terminales). El modo local lo +/// implementa con un archivo en el directorio de datos y el modo nube con la +/// API REST; ambos quedan detrás del mismo puerto. `None` = no hay nada +/// guardado todavía (primera corrida o arranque limpio). +pub trait SnapshotStore: Send + Sync { + fn load_snapshot(&self) -> Result, PortError>; + fn save_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError>; +} + +/// Token de acceso para la API remota (modo nube). Se consulta por pedido +/// HTTP: si el access ya venció o está por vencer, el proveedor lo refresca +/// antes de devolverlo. +pub trait AccessTokenProvider: Send + Sync { + /// Token vigente, refrescándolo si la sesión lo pide (igual que hace la web). + fn access_token(&self) -> Result; + /// Token apenas refrescado a la fuerza: la API rechazó `rejected` con 401. + /// Si el token corriente ya cambió, otro pedido refrescó y se reutiliza. + fn refreshed_access_token(&self, rejected: &str) -> Result; +} + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + + use super::*; + + /// Fake del puerto: una lista de tokens donde el corriente es el primero. + /// `access_token` devuelve el corriente sin tocar la lista (un pedido no + /// debe refrescar); `refreshed_access_token` descarta el corriente y pasa + /// al siguiente, como haría un refresh real. + struct FakeTokens { + tokens: Mutex>, + } + + impl FakeTokens { + fn new(tokens: &[&str]) -> Self { + Self { + tokens: Mutex::new(tokens.iter().map(|t| t.to_string()).collect()), + } + } + } + + impl AccessTokenProvider for FakeTokens { + fn access_token(&self) -> Result { + let tokens = self.tokens.lock().expect("fake"); + tokens + .first() + .cloned() + .ok_or_else(|| PortError::new("sin token: no hay sesión iniciada")) + } + + fn refreshed_access_token(&self, rejected: &str) -> Result { + let mut tokens = self.tokens.lock().expect("fake"); + let Some(current) = tokens.first() else { + return Err(PortError::new("sin token: no hay sesión iniciada")); + }; + if current != rejected { + return Ok(current.clone()); + } + if tokens.len() > 1 { + tokens.remove(0); + } + Ok(tokens[0].clone()) + } + } + + #[test] + fn cada_pedido_consulta_el_token_vigente() { + let tokens = FakeTokens::new(&["tok-1", "tok-2"]); + // Dos pedidos seguidos reciben el mismo token y no lo consumen. + assert_eq!(tokens.access_token().unwrap(), "tok-1"); + assert_eq!(tokens.access_token().unwrap(), "tok-1"); + } + + #[test] + fn el_refresh_forzado_avanza_al_token_siguiente() { + let tokens = FakeTokens::new(&["tok-1", "tok-2"]); + assert_eq!(tokens.access_token().unwrap(), "tok-1"); + assert_eq!(tokens.refreshed_access_token("tok-1").unwrap(), "tok-2"); + // Y el nuevo pasa a ser el corriente. + assert_eq!(tokens.access_token().unwrap(), "tok-2"); + // Un último token se reutiliza: sin sesión a quién refrescar no existe. + assert_eq!(tokens.refreshed_access_token("tok-2").unwrap(), "tok-2"); + } + + #[test] + fn un_401_viejo_reutiliza_el_token_que_ya_refresco_otro_pedido() { + let tokens = FakeTokens::new(&["tok-2", "tok-3"]); + // El 401 llegó con tok-1, pero otro pedido ya dejó tok-2 vigente. + assert_eq!(tokens.refreshed_access_token("tok-1").unwrap(), "tok-2"); + assert_eq!(tokens.access_token().unwrap(), "tok-2"); + } + + #[test] + fn sin_token_todos_los_caminos_fallan_con_port_error() { + let tokens = FakeTokens::new(&[]); + assert_eq!( + tokens.access_token(), + Err(PortError::new("sin token: no hay sesión iniciada")) + ); + assert_eq!( + tokens.refreshed_access_token("tok-1"), + Err(PortError::new("sin token: no hay sesión iniciada")) + ); + } + + /// Helper que compila solo si el puerto es un trait-objeto `Send + Sync`: + /// el modo nube lo inyecta por `Arc) -> String { + provider.access_token().unwrap() + } + + #[test] + fn el_puerto_se_comparte_como_trait_objeto() { + let provider: Arc = Arc::new(FakeTokens::new(&["tok"])); + assert_eq!(port_is_shared_by_reference(provider), "tok"); + } +} diff --git a/apps/desktop/core/application/src/storage.rs b/apps/desktop/core/application/src/storage.rs new file mode 100644 index 0000000..0c6ffd4 --- /dev/null +++ b/apps/desktop/core/application/src/storage.rs @@ -0,0 +1,160 @@ +//! Snapshot de la estructura del escritorio: workspaces, sesiones y perfiles +//! de arranque de las terminales. Es lo único que se persiste en el modo local +//! (feature desktop-dual-storage, S5/A1): ni `env` ni scrollback ni estado de +//! procesos, solo lo necesario para reconstruir la grilla al arrancar. + +use serde::{Deserialize, Serialize}; + +/// Versión del formato. Un archivo con otra versión no se sabe leer y se pone +/// en cuarentena en vez de bochar la app; cuando haya migraciones reales se +/// agregan acá. +pub const SNAPSHOT_VERSION: u32 = 1; + +/// Una terminal del escritorio: su perfil de arranque y su lugar en la grilla. +/// Espeja al `Pane` de la UI (`packages/ui/src/model.ts`): el orden del DOM es +/// `seq` (estable, para no resetear xterm) y el orden visual es la posición en +/// el array de la sesión. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredPane { + pub id: String, + /// Orden de creación. Unicidad global, igual que en la UI. + pub seq: u64, + pub minimized: bool, + /// Carpeta inicial de la shell; `None` = la por defecto del núcleo. + pub initial_cwd: Option, + /// Agente que se lanza al abrir la terminal; `None` = solo la shell. + pub agent: Option, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredSession { + pub id: String, + pub name: String, + /// En orden visual (arrastrar paneles reordena este array). + pub panes: Vec, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StoredWorkspace { + pub id: String, + pub name: String, + pub sessions: Vec, +} + +/// Toda la estructura persistida del escritorio, de una vez. El backend la +/// guarda y la devuelve completa; no hay lectura por partes. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct WorkspaceSnapshot { + pub version: u32, + pub workspaces: Vec, +} + +impl WorkspaceSnapshot { + /// Snapshot de la versión vigente. + pub fn new(workspaces: Vec) -> Self { + Self { + version: SNAPSHOT_VERSION, + workspaces, + } + } + + /// Es de la versión que sabemos leer. + pub fn is_current_version(&self) -> bool { + self.version == SNAPSHOT_VERSION + } +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + + fn pane() -> StoredPane { + StoredPane { + id: "pane-1".into(), + seq: 7, + minimized: true, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + } + } + + #[test] + fn serializes_with_camel_case_keys_like_the_frontend_model() { + let snapshot = WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "OpenCollab".into(), + sessions: vec![StoredSession { + id: "session-1".into(), + name: "Sesión 1".into(), + panes: vec![pane()], + }], + }]); + assert_eq!( + serde_json::to_value(&snapshot).unwrap(), + json!({ + "version": 1, + "workspaces": [{ + "id": "ws-1", + "name": "OpenCollab", + "sessions": [{ + "id": "session-1", + "name": "Sesión 1", + "panes": [{ + "id": "pane-1", + "seq": 7, + "minimized": true, + "initialCwd": "C:\\repo", + "agent": "claude-code" + }] + }] + }] + }) + ); + } + + #[test] + fn round_trips_through_json() { + let snapshot = WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "trabajo".into(), + sessions: vec![ + StoredSession { + id: "session-1".into(), + name: "sin panes".into(), + panes: vec![], + }, + StoredSession { + id: "session-2".into(), + name: "con pane".into(), + panes: vec![StoredPane { + id: "pane-1".into(), + seq: 0, + minimized: false, + initial_cwd: None, + agent: None, + }], + }, + ], + }]); + let back: WorkspaceSnapshot = + serde_json::from_str(&serde_json::to_string(&snapshot).unwrap()).unwrap(); + assert_eq!(back, snapshot); + } + + #[test] + fn version_gate_knows_what_it_can_read() { + let current = WorkspaceSnapshot::new(vec![]); + assert!(current.is_current_version()); + let future = WorkspaceSnapshot { + version: SNAPSHOT_VERSION + 1, + workspaces: vec![], + }; + assert!(!future.is_current_version()); + } +} diff --git a/crates/application/src/use_cases.rs b/apps/desktop/core/application/src/use_cases.rs similarity index 75% rename from crates/application/src/use_cases.rs rename to apps/desktop/core/application/src/use_cases.rs index e138ff3..b07fd33 100644 --- a/crates/application/src/use_cases.rs +++ b/apps/desktop/core/application/src/use_cases.rs @@ -1,36 +1,28 @@ use std::sync::Arc; -use domain::{AccessLevel, AgentProfile, Session, SessionId, TerminalId, UserId, Workspace}; +use domain::{AccessLevel, AgentProfile, Session, SessionId, TerminalId, UserId}; use crate::agent_detection::{detect_agents_within, AgentTree}; use crate::error::AppError; use crate::git::Branch; use crate::ports::{ - CollabTransport, DirectoryBrowser, ProcessInspector, PtyPort, RepositoryInspector, - TerminalOutputSink, TerminalSize, WorkspaceRepository, + DirectoryBrowser, ProcessInspector, PtyPort, RepositoryInspector, SessionRepository, + TerminalOutputSink, TerminalSize, }; -fn load( - repo: &dyn WorkspaceRepository, - session_id: SessionId, -) -> Result<(Workspace, Session), AppError> { - let session = repo - .find_session(session_id)? - .ok_or(AppError::SessionNotFound(session_id))?; - let workspace = repo - .find_workspace(session.workspace_id())? - .ok_or(AppError::WorkspaceNotFound(session.workspace_id()))?; - Ok((workspace, session)) +fn load(repo: &dyn SessionRepository, session_id: SessionId) -> Result { + repo.find_session(session_id)? + .ok_or(AppError::SessionNotFound(session_id)) } /// Agrega una terminal a la sesión y lanza su PTY. pub struct LaunchTerminal { - repo: Arc, + repo: Arc, pty: Arc, } impl LaunchTerminal { - pub fn new(repo: Arc, pty: Arc) -> Self { + pub fn new(repo: Arc, pty: Arc) -> Self { Self { repo, pty } } @@ -42,8 +34,8 @@ impl LaunchTerminal { size: TerminalSize, sink: Arc, ) -> Result { - let (workspace, mut session) = load(self.repo.as_ref(), session_id)?; - let terminal = session.add_terminal(&workspace, actor, profile.clone())?; + let mut session = load(self.repo.as_ref(), session_id)?; + let terminal = session.add_terminal(actor, profile.clone())?; self.pty.spawn(terminal, &profile, size, sink)?; self.repo.save_session(session)?; Ok(terminal) @@ -53,12 +45,12 @@ impl LaunchTerminal { /// Escribe input en una terminal. Es el único camino de entrada al PTY, tanto /// local como remoto: valida contra el permiso vigente en cada llamada. pub struct SendTerminalInput { - repo: Arc, + repo: Arc, pty: Arc, } impl SendTerminalInput { - pub fn new(repo: Arc, pty: Arc) -> Self { + pub fn new(repo: Arc, pty: Arc) -> Self { Self { repo, pty } } @@ -76,12 +68,12 @@ impl SendTerminalInput { } pub struct ResizeTerminal { - repo: Arc, + repo: Arc, pty: Arc, } impl ResizeTerminal { - pub fn new(repo: Arc, pty: Arc) -> Self { + pub fn new(repo: Arc, pty: Arc) -> Self { Self { repo, pty } } @@ -100,12 +92,12 @@ impl ResizeTerminal { /// Quita una terminal de la sesión y termina su proceso. pub struct CloseTerminal { - repo: Arc, + repo: Arc, pty: Arc, } impl CloseTerminal { - pub fn new(repo: Arc, pty: Arc) -> Self { + pub fn new(repo: Arc, pty: Arc) -> Self { Self { repo, pty } } @@ -115,8 +107,8 @@ impl CloseTerminal { session_id: SessionId, terminal: TerminalId, ) -> Result<(), AppError> { - let (workspace, mut session) = load(self.repo.as_ref(), session_id)?; - session.remove_terminal(&workspace, actor, terminal)?; + let mut session = load(self.repo.as_ref(), session_id)?; + session.remove_terminal(actor, terminal)?; self.pty.kill(terminal)?; self.repo.save_session(session)?; Ok(()) @@ -165,7 +157,7 @@ impl InspectBranch { /// Qué agentes conocidos corren en cada terminal viva de la sesión: el principal /// de cada una y los que ese agente tiene anidados. pub struct DetectTerminalAgents { - repo: Arc, + repo: Arc, pty: Arc, inspector: Arc, /// Ejecutables en los que el recorrido se detiene (otras instancias de la app). @@ -174,7 +166,7 @@ pub struct DetectTerminalAgents { impl DetectTerminalAgents { pub fn new( - repo: Arc, + repo: Arc, pty: Arc, inspector: Arc, ) -> Self { @@ -221,14 +213,14 @@ impl DetectTerminalAgents { } fn ensure_can_write( - repo: &dyn WorkspaceRepository, + repo: &dyn SessionRepository, actor: UserId, session_id: SessionId, terminal: TerminalId, ) -> Result<(), AppError> { - let (workspace, session) = load(repo, session_id)?; + let session = load(repo, session_id)?; session.ensure_has_terminal(terminal)?; - if !session.can_write(&workspace, actor) { + if !session.can_write(actor) { return Err(AppError::WriteNotAllowed { user: actor, terminal, @@ -237,42 +229,28 @@ fn ensure_can_write( Ok(()) } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum AccessChange { - SetView(bool), - SetWrite(bool), -} - -/// El dueño cambia el acceso de un participante en vivo y se notifica a los demás. -pub struct ChangeParticipantAccess { - repo: Arc, - transport: Arc, +/// Aplica a la sesión el nivel de acceso que mandó el server (`Joined` / +/// `AccessChanged`) y lo persiste: el siguiente input se valida contra él. +/// El server decide quién puede qué; acá solo se guarda para la validación final. +pub struct ApplyAccessLevel { + repo: Arc, } -impl ChangeParticipantAccess { - pub fn new(repo: Arc, transport: Arc) -> Self { - Self { repo, transport } +impl ApplyAccessLevel { + pub fn new(repo: Arc) -> Self { + Self { repo } } pub fn execute( &self, - actor: UserId, session_id: SessionId, - target: UserId, - change: AccessChange, - ) -> Result { - let (workspace, mut session) = load(self.repo.as_ref(), session_id)?; - let level = match change { - AccessChange::SetView(enabled) => { - session.set_view(&workspace, actor, target, enabled)? - } - AccessChange::SetWrite(enabled) => { - session.set_write(&workspace, actor, target, enabled)? - } - }; + user: UserId, + level: AccessLevel, + ) -> Result<(), AppError> { + let mut session = load(self.repo.as_ref(), session_id)?; + session.set_access(user, level)?; self.repo.save_session(session)?; - self.transport.access_changed(session_id, target, level)?; - Ok(level) + Ok(()) } } @@ -281,7 +259,7 @@ mod tests { use std::collections::HashMap; use std::sync::Mutex; - use domain::{DomainError, WorkspaceId}; + use domain::DomainError; use super::*; use crate::agent_detection::KnownAgent; @@ -289,21 +267,10 @@ mod tests { #[derive(Default)] struct FakeRepo { - workspaces: Mutex>, sessions: Mutex>, } - impl WorkspaceRepository for FakeRepo { - fn find_workspace(&self, id: WorkspaceId) -> Result, PortError> { - Ok(self.workspaces.lock().unwrap().get(&id).cloned()) - } - fn save_workspace(&self, workspace: Workspace) -> Result<(), PortError> { - self.workspaces - .lock() - .unwrap() - .insert(workspace.id(), workspace); - Ok(()) - } + impl SessionRepository for FakeRepo { fn find_session(&self, id: SessionId) -> Result, PortError> { Ok(self.sessions.lock().unwrap().get(&id).cloned()) } @@ -361,23 +328,6 @@ mod tests { } } - #[derive(Default)] - struct FakeTransport { - events: Mutex>, - } - - impl CollabTransport for FakeTransport { - fn access_changed( - &self, - session: SessionId, - user: UserId, - access: AccessLevel, - ) -> Result<(), PortError> { - self.events.lock().unwrap().push((session, user, access)); - Ok(()) - } - } - struct NullSink; impl TerminalOutputSink for NullSink { fn output(&self, _terminal: TerminalId, _data: &[u8]) {} @@ -391,22 +341,17 @@ mod tests { terminal: TerminalId, repo: Arc, pty: Arc, - transport: Arc, } fn world() -> World { let owner = UserId::new(); let member = UserId::new(); - let mut workspace = Workspace::new(owner, "proyecto"); - workspace.add_member(owner, member).unwrap(); - let session = Session::new(&workspace, owner, "sesión").unwrap(); + let session = Session::new(owner, "sesión"); let session_id = session.id(); let repo = Arc::new(FakeRepo::default()); - repo.save_workspace(workspace).unwrap(); repo.save_session(session).unwrap(); let pty = Arc::new(FakePty::default()); - let transport = Arc::new(FakeTransport::default()); let terminal = LaunchTerminal::new(repo.clone(), pty.clone()) .execute( @@ -425,7 +370,6 @@ mod tests { terminal, repo, pty, - transport, } } @@ -614,7 +558,7 @@ mod tests { } #[test] - fn member_with_default_view_cannot_write() { + fn non_owner_without_server_grant_cannot_write() { let w = world(); let input = SendTerminalInput::new(w.repo.clone(), w.pty.clone()); let result = input.execute(w.member, w.session_id, w.terminal, b"ls\r"); @@ -623,69 +567,63 @@ mod tests { } #[test] - fn permission_change_applies_to_next_input() { + fn applying_view_then_write_from_server_allows_input() { let w = world(); - let change = ChangeParticipantAccess::new(w.repo.clone(), w.transport.clone()); + let apply = ApplyAccessLevel::new(w.repo.clone()); let input = SendTerminalInput::new(w.repo.clone(), w.pty.clone()); - change - .execute( - w.owner, - w.session_id, - w.member, - AccessChange::SetWrite(true), - ) - .unwrap(); - input - .execute(w.member, w.session_id, w.terminal, b"a") - .unwrap(); - - change - .execute( - w.owner, - w.session_id, - w.member, - AccessChange::SetWrite(false), - ) + apply + .execute(w.session_id, w.member, AccessLevel::View) .unwrap(); assert!(input - .execute(w.member, w.session_id, w.terminal, b"b") + .execute(w.member, w.session_id, w.terminal, b"a") .is_err()); + apply + .execute(w.session_id, w.member, AccessLevel::Write) + .unwrap(); + input + .execute(w.member, w.session_id, w.terminal, b"a") + .unwrap(); assert_eq!(w.pty.written.lock().unwrap().len(), 1); } #[test] - fn permission_change_is_broadcast() { + fn revoking_to_none_from_server_blocks_next_input() { let w = world(); - let change = ChangeParticipantAccess::new(w.repo.clone(), w.transport.clone()); - let level = change - .execute( - w.owner, - w.session_id, - w.member, - AccessChange::SetView(false), - ) + let apply = ApplyAccessLevel::new(w.repo.clone()); + let input = SendTerminalInput::new(w.repo.clone(), w.pty.clone()); + + apply + .execute(w.session_id, w.member, AccessLevel::Write) .unwrap(); - assert_eq!(level, AccessLevel::None); - assert_eq!( - *w.transport.events.lock().unwrap(), - vec![(w.session_id, w.member, AccessLevel::None)] - ); + input + .execute(w.member, w.session_id, w.terminal, b"a") + .unwrap(); + + apply + .execute(w.session_id, w.member, AccessLevel::None) + .unwrap(); + assert!(matches!( + input.execute(w.member, w.session_id, w.terminal, b"b"), + Err(AppError::WriteNotAllowed { .. }) + )); + assert_eq!(w.pty.written.lock().unwrap().len(), 1); } #[test] - fn non_owner_cannot_change_permissions_and_nothing_is_broadcast() { + fn applying_access_to_unknown_session_or_owner_is_rejected() { let w = world(); - let change = ChangeParticipantAccess::new(w.repo.clone(), w.transport.clone()); - let result = change.execute( - w.member, - w.session_id, - w.member, - AccessChange::SetWrite(true), + let apply = ApplyAccessLevel::new(w.repo.clone()); + let missing = SessionId::new(); + assert_eq!( + apply.execute(missing, w.member, AccessLevel::View), + Err(AppError::SessionNotFound(missing)) + ); + assert_eq!( + apply.execute(w.session_id, w.owner, AccessLevel::None), + Err(AppError::Domain(DomainError::CannotChangeOwnerAccess)) ); - assert_eq!(result, Err(AppError::Domain(DomainError::NotOwner))); - assert!(w.transport.events.lock().unwrap().is_empty()); } #[test] diff --git a/crates/domain/Cargo.toml b/apps/desktop/core/domain/Cargo.toml similarity index 100% rename from crates/domain/Cargo.toml rename to apps/desktop/core/domain/Cargo.toml diff --git a/apps/desktop/core/domain/src/error.rs b/apps/desktop/core/domain/src/error.rs new file mode 100644 index 0000000..8be94b8 --- /dev/null +++ b/apps/desktop/core/domain/src/error.rs @@ -0,0 +1,13 @@ +use crate::ids::TerminalId; + +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum DomainError { + #[error("solo el dueño de la sesión puede realizar esta acción")] + NotOwner, + #[error("los permisos del dueño no se pueden modificar")] + CannotChangeOwnerAccess, + #[error("la terminal {0} no pertenece a la sesión")] + TerminalNotInSession(TerminalId), + #[error("el comando del perfil de agente no puede estar vacío")] + EmptyCommand, +} diff --git a/crates/domain/src/ids.rs b/apps/desktop/core/domain/src/ids.rs similarity index 96% rename from crates/domain/src/ids.rs rename to apps/desktop/core/domain/src/ids.rs index 13db147..407a8e4 100644 --- a/crates/domain/src/ids.rs +++ b/apps/desktop/core/domain/src/ids.rs @@ -55,7 +55,5 @@ id_type!( /// Identidad de una persona usuaria de OpenCollab. UserId ); -id_type!(WorkspaceId); id_type!(SessionId); id_type!(TerminalId); -id_type!(InvitationId); diff --git a/apps/desktop/core/domain/src/lib.rs b/apps/desktop/core/domain/src/lib.rs new file mode 100644 index 0000000..ee97e0a --- /dev/null +++ b/apps/desktop/core/domain/src/lib.rs @@ -0,0 +1,16 @@ +//! Dominio del desktop de OpenCollab: Session → Terminal y el nivel de acceso +//! ordenado con el que se valida el input antes de escribir en el PTY. Las +//! reglas colaborativas (workspaces, miembros, invitaciones) viven en el server; +//! acá solo se aplica el nivel que él manda. Sin I/O. + +mod error; +mod ids; +mod permission; +mod session; +mod terminal; + +pub use error::DomainError; +pub use ids::{InvalidId, SessionId, TerminalId, UserId}; +pub use permission::AccessLevel; +pub use session::{Participant, Session}; +pub use terminal::{AgentProfile, Terminal}; diff --git a/crates/domain/src/permission.rs b/apps/desktop/core/domain/src/permission.rs similarity index 100% rename from crates/domain/src/permission.rs rename to apps/desktop/core/domain/src/permission.rs diff --git a/apps/desktop/core/domain/src/session.rs b/apps/desktop/core/domain/src/session.rs new file mode 100644 index 0000000..d599175 --- /dev/null +++ b/apps/desktop/core/domain/src/session.rs @@ -0,0 +1,220 @@ +use std::collections::HashMap; + +use crate::error::DomainError; +use crate::ids::{SessionId, TerminalId, UserId}; +use crate::permission::AccessLevel; +use crate::terminal::{AgentProfile, Terminal}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Participant { + pub user_id: UserId, + pub access: AccessLevel, +} + +/// Sesión local del host: grupo de terminales que se ven juntas en una grilla. +/// +/// El server es quien decide los permisos; acá solo se guarda el último nivel +/// que mandó para cada usuario ([`Session::set_access`]) y se valida contra él +/// antes de escribir en un PTY. Un usuario sin entrada no tiene acceso (falla +/// cerrado); el dueño siempre escribe. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Session { + id: SessionId, + name: String, + owner: UserId, + terminals: Vec, + access: HashMap, +} + +impl Session { + pub fn new(owner: UserId, name: impl Into) -> Self { + Self { + id: SessionId::new(), + name: name.into(), + owner, + terminals: Vec::new(), + access: HashMap::new(), + } + } + + pub fn id(&self) -> SessionId { + self.id + } + + pub fn name(&self) -> &str { + &self.name + } + + pub fn owner(&self) -> UserId { + self.owner + } + + pub fn terminals(&self) -> &[Terminal] { + &self.terminals + } + + pub fn terminal(&self, id: TerminalId) -> Option<&Terminal> { + self.terminals.iter().find(|t| t.id == id) + } + + /// Fuente única de verdad del acceso de `user` a esta sesión. + pub fn access_of(&self, user: UserId) -> AccessLevel { + if user == self.owner { + return AccessLevel::Write; + } + self.access.get(&user).copied().unwrap_or(AccessLevel::None) + } + + pub fn can_view(&self, user: UserId) -> bool { + self.access_of(user).can_view() + } + + pub fn can_write(&self, user: UserId) -> bool { + self.access_of(user).can_write() + } + + /// El dueño y los usuarios con al menos Ver, con su acceso vigente. + pub fn participants(&self) -> Vec { + let owner = std::iter::once(self.owner); + let granted = self.access.keys().copied(); + owner + .chain(granted) + .filter(|user| self.can_view(*user)) + .map(|user_id| Participant { + user_id, + access: self.access_of(user_id), + }) + .collect() + } + + /// Aplica el nivel que mandó el server para `user`. El del dueño no se puede cambiar. + pub fn set_access(&mut self, user: UserId, level: AccessLevel) -> Result<(), DomainError> { + if user == self.owner { + return Err(DomainError::CannotChangeOwnerAccess); + } + if level == AccessLevel::None { + self.access.remove(&user); + } else { + self.access.insert(user, level); + } + Ok(()) + } + + pub fn add_terminal( + &mut self, + actor: UserId, + profile: AgentProfile, + ) -> Result { + self.ensure_owner(actor)?; + let id = TerminalId::new(); + self.terminals.push(Terminal { id, profile }); + Ok(id) + } + + /// Quita una terminal de la sesión. Igual que agregarlas, es del dueño. + pub fn remove_terminal(&mut self, actor: UserId, id: TerminalId) -> Result<(), DomainError> { + self.ensure_owner(actor)?; + self.ensure_has_terminal(id)?; + self.terminals.retain(|t| t.id != id); + Ok(()) + } + + pub fn ensure_has_terminal(&self, id: TerminalId) -> Result<(), DomainError> { + self.terminal(id) + .map(|_| ()) + .ok_or(DomainError::TerminalNotInSession(id)) + } + + fn ensure_owner(&self, actor: UserId) -> Result<(), DomainError> { + if actor == self.owner { + Ok(()) + } else { + Err(DomainError::NotOwner) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session() -> (UserId, Session) { + let owner = UserId::new(); + (owner, Session::new(owner, "sesión")) + } + + #[test] + fn owner_always_writes() { + let (owner, mut s) = session(); + assert_eq!(s.access_of(owner), AccessLevel::Write); + assert!(s.can_write(owner)); + assert_eq!( + s.set_access(owner, AccessLevel::None), + Err(DomainError::CannotChangeOwnerAccess) + ); + assert!(s.can_write(owner)); + } + + #[test] + fn unknown_user_has_no_access() { + let (_, s) = session(); + let stranger = UserId::new(); + assert_eq!(s.access_of(stranger), AccessLevel::None); + assert!(!s.can_view(stranger) && !s.can_write(stranger)); + } + + #[test] + fn server_levels_drive_view_and_write() { + let (_, mut s) = session(); + let user = UserId::new(); + s.set_access(user, AccessLevel::View).unwrap(); + assert!(s.can_view(user) && !s.can_write(user)); + s.set_access(user, AccessLevel::Write).unwrap(); + assert!(s.can_view(user) && s.can_write(user)); + s.set_access(user, AccessLevel::None).unwrap(); + assert!(!s.can_view(user) && !s.can_write(user)); + } + + #[test] + fn participants_are_owner_plus_viewers() { + let (owner, mut s) = session(); + let viewer = UserId::new(); + let revoked = UserId::new(); + s.set_access(viewer, AccessLevel::View).unwrap(); + s.set_access(revoked, AccessLevel::Write).unwrap(); + s.set_access(revoked, AccessLevel::None).unwrap(); + let participants = s.participants(); + assert_eq!(participants.len(), 2); + assert!(participants.contains(&Participant { + user_id: owner, + access: AccessLevel::Write + })); + assert!(participants.contains(&Participant { + user_id: viewer, + access: AccessLevel::View + })); + } + + #[test] + fn only_owner_manages_terminals() { + let (owner, mut s) = session(); + let other = UserId::new(); + s.set_access(other, AccessLevel::Write).unwrap(); + let profile = AgentProfile::new("shell", "sh").unwrap(); + assert_eq!( + s.add_terminal(other, profile.clone()), + Err(DomainError::NotOwner) + ); + let terminal = s.add_terminal(owner, profile).unwrap(); + assert_eq!( + s.remove_terminal(other, terminal), + Err(DomainError::NotOwner) + ); + s.remove_terminal(owner, terminal).unwrap(); + assert!(s.terminal(terminal).is_none()); + assert_eq!( + s.remove_terminal(owner, terminal), + Err(DomainError::TerminalNotInSession(terminal)) + ); + } +} diff --git a/crates/domain/src/terminal.rs b/apps/desktop/core/domain/src/terminal.rs similarity index 100% rename from crates/domain/src/terminal.rs rename to apps/desktop/core/domain/src/terminal.rs diff --git a/crates/infrastructure/Cargo.toml b/apps/desktop/core/infrastructure/Cargo.toml similarity index 89% rename from crates/infrastructure/Cargo.toml rename to apps/desktop/core/infrastructure/Cargo.toml index 7e4fa9a..bc31b79 100644 --- a/crates/infrastructure/Cargo.toml +++ b/apps/desktop/core/infrastructure/Cargo.toml @@ -9,7 +9,9 @@ publish.workspace = true [dependencies] domain.workspace = true application.workspace = true +serde.workspace = true +serde_json.workspace = true +ureq.workspace = true portable-pty.workspace = true sysinfo.workspace = true -serde_json.workspace = true uuid.workspace = true diff --git a/crates/infrastructure/src/agent_launch.rs b/apps/desktop/core/infrastructure/src/agent_launch.rs similarity index 100% rename from crates/infrastructure/src/agent_launch.rs rename to apps/desktop/core/infrastructure/src/agent_launch.rs diff --git a/crates/infrastructure/src/claude_adapter.rs b/apps/desktop/core/infrastructure/src/claude_adapter.rs similarity index 100% rename from crates/infrastructure/src/claude_adapter.rs rename to apps/desktop/core/infrastructure/src/claude_adapter.rs diff --git a/crates/infrastructure/src/claude_hooks.rs b/apps/desktop/core/infrastructure/src/claude_hooks.rs similarity index 100% rename from crates/infrastructure/src/claude_hooks.rs rename to apps/desktop/core/infrastructure/src/claude_hooks.rs diff --git a/apps/desktop/core/infrastructure/src/cloud_store.rs b/apps/desktop/core/infrastructure/src/cloud_store.rs new file mode 100644 index 0000000..11a3caa --- /dev/null +++ b/apps/desktop/core/infrastructure/src/cloud_store.rs @@ -0,0 +1,1605 @@ +//! Backend de nube del snapshot: la API REST de OpenCollab detrás del mismo +//! puerto `SnapshotStore` que el modo local (feature desktop-dual-storage, S6/S7). +//! +//! El HTTP es bloqueante (`ureq` con rustls, sin runtime async, la misma regla +//! de la capa de aplicación). Cada pedido sale con el token vigente del +//! `AccessTokenProvider`; ante un 401 se fuerza un refresh una sola vez y se +//! reintenta el pedido antes de fallar. Los ids que no son UUID derivan un +//! UUID v5 determinista, así el mismo id local crea siempre el mismo recurso +//! en el server (creates idempotentes; la migración T6 reusa el mapeo). +//! +//! `save_snapshot` hace reconciliación: crea lo que falta, renombra/actualiza +//! lo que cambió y borra lo que sobró (primero terminales, después sesiones y +//! al final workspaces, respetando el cascade del server). Cualquier respuesta +//! que no sea 2xx corta el guardado con error: nunca se reporta éxito a +//! medias, y repetir el guardado es seguro porque los ids son idempotentes. + +use std::sync::Arc; +use std::time::Duration; + +use application::agent_detection::KnownAgent; +use application::ports::{AccessTokenProvider, PortError, SnapshotStore}; +use application::storage::{StoredPane, StoredSession, StoredWorkspace, WorkspaceSnapshot}; +use domain::AgentProfile; +use serde::Deserialize; +use uuid::Uuid; + +/// Tope por pedido HTTP: la API puede tardar, pero no debe dejar la llamada +/// bloqueada infinitamente (corre fuera del hilo de la UI). +const REQUEST_TIMEOUT: Duration = Duration::from_secs(30); + +/// Espacio de nombres congelado para derivar UUID v5 de ids locales. Es un +/// valor arbitrario: cambiarlo rompería la relación id local → recurso del +/// server ya guardada (los recursos dejarían de encontrarse entre corridas). +const LOCAL_ID_NAMESPACE: Uuid = Uuid::from_bytes([ + 0x63, 0x2f, 0x9c, 0x11, 0x7f, 0x5e, 0x4d, 0x1c, 0xa2, 0xb5, 0x3e, 0x87, 0x90, 0xd6, 0xf4, 0x55, +]); + +/// UUID del server para un id local: si el id ya es UUID viaja tal cual (en +/// su forma canónica); si no, deriva un UUID v5 del string. Mismo id local +/// produce siempre el mismo UUID, entre corridas y máquinas. +pub fn local_id_to_server_uuid(local_id: &str) -> String { + Uuid::parse_str(local_id) + .unwrap_or_else(|_| Uuid::new_v5(&LOCAL_ID_NAMESPACE, local_id.as_bytes())) + .to_string() +} + +/// Lo que la API devuelve de una terminal. Los campos que pueden no venir se +/// toleran ausentes con `#[serde(default)]`: la API es más nueva que el +/// desktop posible, no al revés. +#[derive(Debug, Clone, Deserialize)] +struct ApiTerminal { + id: String, + name: String, + command: String, + #[serde(default)] + args: Vec, + #[serde(default)] + cwd: Option, + #[serde(default)] + agent: Option, + #[serde(default)] + minimized: bool, +} + +#[derive(Debug, Deserialize)] +struct ApiSession { + id: String, + name: String, + #[serde(default)] + terminals: Vec, +} + +/// Resumen en `GET /workspaces` con las sesiones expandidas (es lo que una +/// reconciliación necesita comparar contra el estado del server). +#[derive(Debug, Deserialize)] +struct ApiWorkspace { + id: String, + name: String, + #[serde(default)] + sessions: Vec, +} + +/// Perfil de arranque derivado de un panel: lo que la API guarda como +/// `name`/`command`/`args` y que el snapshot local no persiste. +#[derive(Debug, Clone, PartialEq, Eq)] +struct TerminalIdentity { + name: String, + command: String, + args: Vec, +} + +/// Perfil determinista de un panel. Con un agente conocido, el perfil es el +/// comando base con el que se lanza (sin los argumentos que cada adaptador +/// agrega por corrida, que llevan destinos y secretos de la sesión: A1). +/// Sin agente —o con un id que la versión actual no conoce— es la shell por +/// defecto, igual que hace la UI al restaurar: un agente removido cae a +/// shell plana en vez de romper. +fn terminal_identity(pane: &StoredPane) -> TerminalIdentity { + match pane.agent.as_deref().and_then(KnownAgent::from_id) { + Some(agent) => TerminalIdentity { + name: agent.id().to_string(), + command: agent.launch_command().to_string(), + args: Vec::new(), + }, + None => { + let shell: AgentProfile = crate::default_shell_profile(None); + TerminalIdentity { + name: shell.name, + command: shell.command, + args: shell.args, + } + } + } +} + +/// Resultado de un intento HTTP. +enum Attempt { + /// Respuesta 2xx con el cuerpo ya leído. + Ok(String), + /// El server contestó un 4xx/5xx: `ureq::Error::StatusCode` trae el número. + Status(u16), + /// Cualquier otro problema (red, URI, cuerpo ilegible). + Failure(String), +} + +pub struct CloudSnapshotStore { + base_url: String, + agent: ureq::Agent, + tokens: Arc, +} + +impl CloudSnapshotStore { + pub fn new(base_url: impl Into, tokens: Arc) -> Self { + Self { + // Sin `/` final: los paths se pegan con `/workspaces` y una barra + // doble cambiaría la ruta. + base_url: base_url.into().trim_end_matches('/').to_string(), + agent: ureq::Agent::config_builder() + .timeout_global(Some(REQUEST_TIMEOUT)) + .build() + .into(), + tokens, + } + } + + fn url(&self, path: &str) -> String { + format!("{}{}", self.base_url, path) + } + + /// Un intento HTTP con un token dado. Los 4xx/5xx no se leen como cuerpo: + /// llegan como `Attempt::Status` con el número, para decidir si es un 401 + /// refrescable. + fn attempt(&self, method: &str, url: &str, token: &str, body: Option<&str>) -> Attempt { + let builder = ureq::http::Request::builder() + .method(method) + .uri(url) + .header("Authorization", format!("Bearer {token}")); + let outcome = match body { + Some(body) => { + let request = builder + .header("Content-Type", "application/json") + .body(body.to_string()); + match request { + Ok(request) => self.agent.run(request), + Err(e) => return Attempt::Failure(format!("pedido inválido: {e}")), + } + } + None => { + let request = builder.body(()); + match request { + Ok(request) => self.agent.run(request), + Err(e) => return Attempt::Failure(format!("pedido inválido: {e}")), + } + } + }; + match outcome { + Ok(mut response) => match response.body_mut().read_to_string() { + Ok(text) => Attempt::Ok(text), + Err(e) => Attempt::Failure(format!("respuesta ilegible: {e}")), + }, + Err(ureq::Error::StatusCode(status)) => Attempt::Status(status), + Err(e) => Attempt::Failure(format!("{e}")), + } + } + + /// Un pedido contra la API: obtiene un token por pedido y, ante 401, fuerza + /// un refresh (una sola vez) y reintenta el pedido idéntico con el token + /// nuevo. Todo otro error es `PortError`; el error nunca se reporta como + /// éxito a las capas de arriba. + fn call(&self, method: &str, path: &str, body: Option<&str>) -> Result { + let url = self.url(path); + let token = self.tokens.access_token()?; + match self.attempt(method, &url, &token, body) { + Attempt::Ok(text) => Ok(text), + Attempt::Status(401) => { + let token = self.tokens.refreshed_access_token(&token)?; + match self.attempt(method, &url, &token, body) { + Attempt::Ok(text) => Ok(text), + Attempt::Status(status) => Err(PortError::new(format!( + "la API rechazó el pedido ({status}) después de refrescar: {method} {path}" + ))), + Attempt::Failure(reason) => Err(PortError::new(format!( + "falló el pedido {method} {path} en el reintento: {reason}" + ))), + } + } + Attempt::Status(status) => Err(PortError::new(format!( + "la API rechazó el pedido ({status}): {method} {path}" + ))), + Attempt::Failure(reason) => Err(PortError::new(format!( + "falló el pedido {method} {path}: {reason}" + ))), + } + } + + /// Estado actual del server: workspaces con las sesiones de cada uno + /// expandidas. Cualquier respuesta inválida es error: nunca se reconcilia + /// contra datos bajo-informados (borrar por error una nube despoblada es + /// irreversible; una lectura fallida no es una estructura vacía). + fn fetch_current(&self) -> Result, PortError> { + let raw = self.call("GET", "/workspaces", None)?; + let mut workspaces: Vec = serde_json::from_str(&raw) + .map_err(|e| PortError::new(format!("respuesta de /workspaces inválida: {e}")))?; + for workspace in &mut workspaces { + let raw = self.call( + "GET", + &format!("/workspaces/{}/sessions", workspace.id), + None, + )?; + workspace.sessions = serde_json::from_str(&raw).map_err(|e| { + PortError::new(format!( + "respuesta de /workspaces/{}/sessions inválida: {e}", + workspace.id + )) + })?; + } + Ok(workspaces) + } + + /// Crea, actualiza y ordena las terminales de la sesión deseada contra + /// `current` (lo que hoy está en el server). + fn reconcile_terminals( + &self, + session_path: &str, + session: &StoredSession, + current: &[ApiTerminal], + ) -> Result<(), PortError> { + // Huerfanas primero: el PUT de orden pide "exactamente las terminales + // de la sesión", así que ninguna huérfana puede seguir viva ahí. + let desired_ids: Vec = session + .panes + .iter() + .map(|pane| local_id_to_server_uuid(&pane.id)) + .collect(); + let mut order_changed = false; + for terminal in current { + if !desired_ids.iter().any(|id| id == &terminal.id) { + self.call( + "DELETE", + &format!("{session_path}/terminals/{}", terminal.id), + None, + )?; + order_changed = true; + } + } + // Creaciones y updates de las deseadas, en el orden visual deseado + // (el server agrega al final: el PUT de orden termina de fijarlo). + for pane in &session.panes { + let terminal_id = local_id_to_server_uuid(&pane.id); + let identity = terminal_identity(pane); + let location = current.iter().find(|termino| termino.id == terminal_id); + match location { + None => { + self.create_terminal(session_path, &terminal_id, pane, &identity)?; + order_changed = true; + } + Some(server_terminal) => { + if let Some(body) = terminal_patch(server_terminal, pane, &identity) { + self.call( + "PATCH", + &format!("{session_path}/terminals/{terminal_id}"), + Some(&body), + )?; + } + } + } + } + // Orden visual: manda el array completo con los ids deseados solo si + // el orden actual difiere, o cambió la composición de la sesión (un + // create/delete reordena el array del server de todos modos). + let current_order: Vec<&str> = current.iter().map(|t| t.id.as_str()).collect(); + let desired_order: Vec<&str> = desired_ids.iter().map(String::as_str).collect(); + if order_changed || current_order != desired_order { + let ids = serde_json::json!({ "ids": desired_ids }).to_string(); + self.call( + "PUT", + &format!("{session_path}/terminals/order"), + Some(&ids), + )?; + } + Ok(()) + } + + /// POST de una terminal nueva: con id explícito (idempotente) y el perfil + /// derivado. Los campos nulos no viajan: el server ya los tiene por + /// default y un null explícito no agrega nada. + fn create_terminal( + &self, + session_path: &str, + terminal_id: &str, + pane: &StoredPane, + identity: &TerminalIdentity, + ) -> Result<(), PortError> { + let mut body = serde_json::Map::new(); + body.insert("id".into(), serde_json::json!(terminal_id)); + body.insert("name".into(), serde_json::json!(identity.name)); + body.insert("command".into(), serde_json::json!(identity.command)); + body.insert("args".into(), serde_json::json!(identity.args)); + if let Some(cwd) = &pane.initial_cwd { + body.insert("cwd".into(), serde_json::json!(cwd)); + } + if let Some(agent) = &pane.agent { + body.insert("agent".into(), serde_json::json!(agent)); + } + if pane.minimized { + body.insert("minimized".into(), serde_json::json!(true)); + } + let body = serde_json::Value::Object(body).to_string(); + self.call("POST", &format!("{session_path}/terminals"), Some(&body))?; + Ok(()) + } + + /// POST de una sesión nueva dentro de un workspace (id idempotente + nombre). + fn create_session(&self, wid: &str, sid: &str, name: &str) -> Result<(), PortError> { + self.call( + "POST", + &format!("/workspaces/{wid}/sessions"), + Some(&serde_json::json!({ "id": sid, "name": name }).to_string()), + )?; + Ok(()) + } + + /// Crea o actualiza un workspace y sus sesiones/terminales contra el estado + /// remoto actual (`current`), sin borrar sesiones ni otros workspaces. + fn upsert_workspace( + &self, + workspace: &StoredWorkspace, + current: &[ApiWorkspace], + ) -> Result<(), PortError> { + let wid = local_id_to_server_uuid(&workspace.id); + let born = current.iter().find(|w| w.id == wid).is_none(); + if born { + self.call( + "POST", + "/workspaces", + Some( + &serde_json::json!({ + "id": wid, + "name": workspace.name, + }) + .to_string(), + ), + )?; + } else { + let server_workspace = current + .iter() + .find(|w| w.id == wid) + .expect("existía en el fetch"); + if server_workspace.name != workspace.name { + self.call( + "PATCH", + &format!("/workspaces/{wid}"), + Some(&serde_json::json!({ "name": workspace.name }).to_string()), + )?; + } + } + for session in &workspace.sessions { + let sid = local_id_to_server_uuid(&session.id); + let server_session = if born { + None + } else { + let server_workspace = current + .iter() + .find(|w| w.id == wid) + .expect("existía en el fetch"); + server_workspace.sessions.iter().find(|s| s.id == sid) + }; + match server_session { + None => self.create_session(&wid, &sid, &session.name)?, + Some(server_session) => { + if server_session.name != session.name { + self.call( + "PATCH", + &format!("/sessions/{sid}"), + Some(&serde_json::json!({ "name": session.name }).to_string()), + )?; + } + } + } + let current_terminals: Vec = match server_session { + Some(server_session) => server_session.terminals.clone(), + None => Vec::new(), + }; + self.reconcile_terminals(&format!("/sessions/{sid}"), session, ¤t_terminals)?; + } + Ok(()) + } + + /// Migra los workspaces locales a la nube uno por uno (S4, A4), sin borrar + /// workspaces ni sesiones que la cuenta ya tuviera en el servidor. + pub fn migrate_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError> { + if snapshot.workspaces.is_empty() { + return Ok(()); + } + let current = self.fetch_current()?; + for workspace in &snapshot.workspaces { + self.upsert_workspace(workspace, ¤t)?; + } + Ok(()) + } +} + +/// Diferencia entre la terminal del server y el panel deseado: solo los +/// campos que cambian viajan en el PATCH (la API es partial). Un null +/// explícito es la forma de quitar el valor guardado. +fn terminal_patch( + server: &ApiTerminal, + pane: &StoredPane, + identity: &TerminalIdentity, +) -> Option { + let mut changed = serde_json::Map::new(); + if server.name != identity.name { + changed.insert("name".into(), serde_json::json!(identity.name)); + } + if server.command != identity.command { + changed.insert("command".into(), serde_json::json!(identity.command)); + } + if server.args != identity.args { + changed.insert("args".into(), serde_json::json!(identity.args)); + } + if server.cwd.as_deref() != pane.initial_cwd.as_deref() { + changed.insert("cwd".into(), serde_json::json!(pane.initial_cwd)); + } + if server.agent.as_deref() != pane.agent.as_deref() { + changed.insert("agent".into(), serde_json::json!(pane.agent)); + } + if server.minimized != pane.minimized { + changed.insert("minimized".into(), serde_json::json!(pane.minimized)); + } + (!changed.is_empty()).then(|| serde_json::Value::Object(changed).to_string()) +} + +impl SnapshotStore for CloudSnapshotStore { + fn load_snapshot(&self) -> Result, PortError> { + let current = self.fetch_current()?; + if current.is_empty() { + // Cuenta sin workspaces = primera corrida en la nube: arranque + // limpio (la UI arma su default y lo guarda después), tal como + // sucede en modo local sin archivo. + return Ok(None); + } + let mut seq = 0u64; + let mut workspaces = Vec::new(); + for workspace in current { + let mut sessions = Vec::new(); + for session in workspace.sessions { + let mut panes = Vec::new(); + for terminal in session.terminals { + panes.push(StoredPane { + id: terminal.id, + seq, + minimized: terminal.minimized, + initial_cwd: terminal.cwd, + agent: terminal.agent, + }); + seq += 1; + } + sessions.push(StoredSession { + id: session.id, + name: session.name, + panes, + }); + } + workspaces.push(StoredWorkspace { + id: workspace.id, + name: workspace.name, + sessions, + }); + } + Ok(Some(WorkspaceSnapshot::new(workspaces))) + } + + fn save_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError> { + let current = self.fetch_current()?; + let desired_ws: Vec = snapshot + .workspaces + .iter() + .map(|workspace| local_id_to_server_uuid(&workspace.id)) + .collect(); + + // Fase 1: crear/actualizar lo deseado, workspace por workspace. Si el + // workspace no está en la nube, se crea con sus sesiones desde cero. + for workspace in &snapshot.workspaces { + self.upsert_workspace(workspace, ¤t)?; + } + + // Fase 2: sesiones que sobraron en workspaces conservados. Las + // terminales huérfanas de una sesión conservada ya salieron en la + // fase 1 (la reconciliación borrarlas antes de fijar el orden, para + // que el PUT cuente la composición definitiva); la de una sesión + // enteramente huérfana viaja con el cascade del DELETE de la sesión. + for server_workspace in ¤t { + if !desired_ws.iter().any(|id| id == &server_workspace.id) { + continue; + } + let desired = snapshot + .workspaces + .iter() + .find(|w| local_id_to_server_uuid(&w.id) == server_workspace.id) + .expect("el workspace conservado está en el snapshot"); + for server_session in &server_workspace.sessions { + let wanted = desired + .sessions + .iter() + .any(|s| local_id_to_server_uuid(&s.id) == server_session.id); + if !wanted { + self.call("DELETE", &format!("/sessions/{}", server_session.id), None)?; + } + } + } + + // Fase 3: workspaces que el snapshot ya no menciona. Cada uno arrastra + // sus sesiones y terminales por cascade (204). + for server_workspace in ¤t { + if !desired_ws.iter().any(|id| id == &server_workspace.id) { + self.call( + "DELETE", + &format!("/workspaces/{}", server_workspace.id), + None, + )?; + } + } + Ok(()) + } +} + +/// POST de una sesión nueva dentro de un workspace (id idempotente + nombre). +#[cfg(test)] +mod tests { + use std::collections::VecDeque; + use std::io::{Read, Write}; + use std::net::{Shutdown, TcpListener, TcpStream}; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::Mutex; + use std::thread; + + use application::storage::SNAPSHOT_VERSION; + use serde_json::{json, Value}; + + use super::*; + + // -------------------------------------------------------------- mock -- + + /// Pedido HTTP registrado por el servidor de mentira, con lo que los + /// asserts necesitan mirar: método, ruta, token y cuerpo. + #[derive(Debug, Clone, PartialEq)] + struct Recorded { + method: String, + path: String, + auth: Option, + content_type: Option, + body: String, + } + + struct MockReply { + status: u16, + body: String, + } + + /// Respuesta `200` con JSON de cuerpo. + fn ok_reply(body: Value) -> MockReply { + MockReply { + status: 200, + body: body.to_string(), + } + } + + /// Respuesta de error con el cuerpo genérico de la API. + fn error_reply(status: u16) -> MockReply { + MockReply { + status, + body: r#"{"error":{"code":"X","message":"no"}}"#.to_string(), + } + } + + /// Servidor HTTP de mentira: `replies[i]` responde al pedido i (en orden + /// de llegada); lo que supera el guión recibe 500. Cada pedido vive en su + /// propia conexión (`connection: close`) y todos quedan registrados. + struct MockServer { + addr: String, + requests: Arc>>, + } + + impl MockServer { + fn start(replies: Vec) -> Self { + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap().to_string(); + let requests: Arc>> = Arc::new(Mutex::new(Vec::new())); + let requests_for_thread = Arc::clone(&requests); + let queue: Mutex> = Mutex::new(replies.into_iter().collect()); + thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + if let Some(recorded) = read_request(&mut stream) { + { + let mut all = requests_for_thread.lock().expect("mock"); + all.push(recorded); + } + let reply = queue + .lock() + .expect("mock") + .pop_front() + .unwrap_or_else(|| error_reply(500)); + write_reply(&mut stream, &reply); + } + let _ = stream.shutdown(Shutdown::Both); + } + }); + Self { addr, requests } + } + + fn url(&self) -> String { + format!("http://{}", self.addr) + } + + fn requests(&self) -> Vec { + self.requests.lock().expect("mock").clone() + } + + fn count(&self) -> usize { + self.requests.lock().expect("mock").len() + } + } + + /// Lee un pedido HTTP del stream: headers y body según Content-Length. + fn read_request(stream: &mut TcpStream) -> Option { + let mut buf = Vec::new(); + let mut chunk = [0u8; 1024]; + loop { + if let Some(recorded) = try_parse(&buf) { + return Some(recorded); + } + match stream.read(&mut chunk) { + Ok(0) => return try_parse(&buf), + Ok(n) => buf.extend_from_slice(&chunk[..n]), + Err(_) => return None, + } + } + } + + /// Parsea el pedido solo si ya está completo; `None` mientras falte leer. + fn try_parse(buf: &[u8]) -> Option { + let headers_end = buf.windows(4).position(|w| w == b"\r\n\r\n")? + 4; + let head = String::from_utf8_lossy(&buf[..headers_end]); + let head = &head[..head.len() - 4]; + let mut lines = head.lines(); + let request_line = lines.next()?; + let mut parts = request_line.split_whitespace(); + let method = parts.next()?.to_string(); + let path = parts.next()?.to_string(); + let mut auth = None; + let mut content_type = None; + let mut content_length = 0usize; + for line in lines { + let (key, value) = line.split_once(':')?; + let key = key.trim().to_ascii_lowercase(); + let value = value.trim(); + match key.as_str() { + "authorization" => auth = Some(value.to_string()), + "content-type" => content_type = Some(value.to_string()), + "content-length" => content_length = value.parse::().ok()?, + _ => {} + } + } + let needed = headers_end + content_length; + if buf.len() < needed { + return None; + } + let body = String::from_utf8_lossy(&buf[headers_end..needed]).to_string(); + Some(Recorded { + method, + path, + auth, + content_type, + body, + }) + } + + fn write_reply(stream: &mut TcpStream, reply: &MockReply) { + if reply.status == 204 { + let _ = stream.write_all(b"HTTP/1.1 204 No Content\r\nconnection: close\r\n\r\n"); + return; + } + let reason = match reply.status { + 200 => "OK", + 201 => "Created", + 400 => "Bad Request", + 401 => "Unauthorized", + 403 => "Forbidden", + 404 => "Not Found", + 409 => "Conflict", + 500 => "Internal Server Error", + _ => "Status", + }; + let head = format!( + "HTTP/1.1 {status} {reason}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n", + reply.body.len(), + status = reply.status, + ); + let _ = stream.write_all(head.as_bytes()); + let _ = stream.write_all(reply.body.as_bytes()); + } + + // ------------------------------------------------------------- fakes -- + + /// Proveedor con dos tokens: el corriente ("tok-1") y el que entrega el + /// refresh forzado ("tok-2"). Anota los refreshes para los asserts; el + /// `Clone` comparte el contador vía `Arc`. + #[derive(Clone)] + struct FakeTokens { + refreshes: Arc, + } + + impl FakeTokens { + fn new() -> Self { + Self { + refreshes: Arc::new(AtomicUsize::new(0)), + } + } + + fn refresh_count(&self) -> usize { + self.refreshes.load(Ordering::SeqCst) + } + } + + impl AccessTokenProvider for FakeTokens { + fn access_token(&self) -> Result { + Ok("tok-1".to_string()) + } + + fn refreshed_access_token(&self, _rejected: &str) -> Result { + self.refreshes.fetch_add(1, Ordering::SeqCst); + Ok("tok-2".to_string()) + } + } + + fn tokens() -> Arc { + Arc::new(FakeTokens::new()) + } + + fn store(server: &MockServer) -> CloudSnapshotStore { + CloudSnapshotStore::new(server.url(), tokens()) + } + + // ---------------------------------------------------------- fixtures -- + + /// Snapshot deseado de prueba: ws-1 "OpenCollab", sesión s-1 "Sesión 1", + /// dos paneles (agente claude-code con cwd; shell minimizada). + fn desired() -> WorkspaceSnapshot { + WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "OpenCollab".into(), + sessions: vec![StoredSession { + id: "session-1".into(), + name: "Sesión 1".into(), + panes: vec![ + StoredPane { + id: "pane-1".into(), + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + }, + StoredPane { + id: "pane-2".into(), + seq: 1, + minimized: true, + initial_cwd: None, + agent: None, + }, + ], + }], + }]) + } + + /// Entrada de `GET /workspaces` (el view del server lleva campos de más: + /// el mapeo solo toma lo que usa). + fn workspace_entry(id: &str, name: &str) -> Value { + json!({ "id": id, "name": name, "owner": "u1", "memberCount": 1 }) + } + + /// View de terminal del server construido con el mismo perfil derivado, + /// para que los asserts de negocio vean solo lo que cambia de verdad. + fn server_terminal(pane: &StoredPane) -> Value { + let identity = terminal_identity(pane); + json!({ + "id": local_id_to_server_uuid(&pane.id), + "name": identity.name, + "command": identity.command, + "args": identity.args, + "cwd": pane.initial_cwd, + "agent": pane.agent, + "minimized": pane.minimized, + }) + } + + fn server_session(id: &str, name: &str, terminals: Vec) -> Value { + json!({ "id": id, "name": name, "terminals": terminals }) + } + + /// Terminal "ajena": un perfil que no corresponde con nada deseado. + fn stray_terminal(id: &str, name: &str) -> Value { + json!({ + "id": id, + "name": name, + "command": "cmd", + "args": [], + "cwd": null, + "agent": null, + "minimized": false, + }) + } + + // -------------------------------------------------------------- tests -- + + #[test] + fn la_derivacion_es_estable_y_los_uuid_viajan_tal_cual() { + // Mismo id local → mismo UUID siempre, entre llamadas e instancias. + let first = local_id_to_server_uuid("ws-1"); + assert_eq!(first, local_id_to_server_uuid("ws-1")); + // Es un UUID y no es el id local crudo. + assert!(Uuid::parse_str(&first).is_ok()); + assert_ne!(first, "ws-1"); + // Dos ids locales distintos no colisionan. + assert_ne!(first, local_id_to_server_uuid("session-1")); + // Un id que ya es UUID viaja igual (forma canónica en minúsculas). + assert_eq!( + local_id_to_server_uuid("E4E0F07E-8B3E-4DC2-A1F0-5B2C9D01AA33"), + "e4e0f07e-8b3e-4dc2-a1f0-5b2c9d01aa33" + ); + assert_eq!( + local_id_to_server_uuid("e4e0f07e-8b3e-4dc2-a1f0-5b2c9d01aa33"), + "e4e0f07e-8b3e-4dc2-a1f0-5b2c9d01aa33" + ); + } + + #[test] + fn load_mapea_views_de_la_api_al_snapshot() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "Cloud")])), + ok_reply(json!([{ + "id": sid, + "name": "Trabajo", + "terminals": [ + { + "id": tid1, + "name": "Claude Code", + "command": "claude", + "args": ["--resume"], + "cwd": "C:\\repo", + "agent": "claude-code", + "minimized": false, + }, + { + "id": tid2, + "name": "PowerShell", + "command": "powershell.exe", + "args": [], + "cwd": null, + "agent": null, + "minimized": true, + }, + ], + }])), + ]); + let cloud = store(&server); + + let loaded = cloud.load_snapshot().unwrap().expect("hay snapshot"); + + assert_eq!(loaded.version, SNAPSHOT_VERSION); + assert_eq!(loaded.workspaces.len(), 1); + let workspace = &loaded.workspaces[0]; + assert_eq!(workspace.id, wid); + assert_eq!(workspace.name, "Cloud"); + assert_eq!(workspace.sessions.len(), 1); + let session = &workspace.sessions[0]; + assert_eq!(session.name, "Trabajo"); + // Orden visual = orden del array del view; seq = posición en él. + assert_eq!(session.panes.len(), 2); + assert_eq!( + session.panes[0], + StoredPane { + id: tid1, + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + } + ); + assert_eq!( + session.panes[1], + StoredPane { + id: tid2, + seq: 1, + minimized: true, + initial_cwd: None, + agent: None, + } + ); + // Dos pedidos: la lista y las sesiones del workspace leído. + let all = server.requests(); + assert_eq!(all.len(), 2); + assert_eq!(all[0].method, "GET"); + assert_eq!(all[0].path, "/workspaces"); + assert_eq!(all[0].auth.as_deref(), Some("Bearer tok-1")); + assert_eq!( + all[1].path, + format!("/workspaces/{wid}/sessions"), + "el GET de sesiones usa el id del workspace" + ); + } + + #[test] + fn load_de_una_cuenta_vacia_es_arranque_limpio() { + let server = MockServer::start(vec![ok_reply(json!([]))]); + let cloud = store(&server); + assert_eq!(cloud.load_snapshot().unwrap(), None); + assert_eq!(server.count(), 1, "con la lista vacía no se pide más"); + } + + #[test] + fn load_no_reutiliza_seq_entre_sesiones() { + let (wid, s1, s2) = ( + local_id_to_server_uuid("ws-1"), + local_id_to_server_uuid("s-1"), + local_id_to_server_uuid("s-2"), + ); + let (t1, t2) = ( + local_id_to_server_uuid("p-1"), + local_id_to_server_uuid("p-2"), + ); + let pane = |id: &str| { + json!({ + "id": id, + "name": "PowerShell", + "command": "powershell.exe", + "args": [], + "cwd": null, + "agent": null, + "minimized": false, + }) + }; + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "Cloud")])), + ok_reply(json!([ + server_session(&s1, "S1", vec![pane(&t1)]), + server_session(&s2, "S2", vec![pane(&t2)]), + ])), + ]); + + let loaded = store(&server).load_snapshot().unwrap().unwrap(); + let seqs: Vec = loaded.workspaces[0] + .sessions + .iter() + .flat_map(|session| session.panes.iter().map(|pane| pane.seq)) + .collect(); + assert_eq!(seqs, vec![0, 1], "Pane.seq es único global"); + } + + #[test] + fn save_crea_lo_que_falta_con_datos_explicitos() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + // Nube vacía: la reconciliación crea todo. Los creates contestan 200 + // (recurso ya existía: el caso idempotente del contrato) sin drama. + let server = MockServer::start(vec![ + ok_reply(json!([])), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!( + shapes, + vec![ + ("GET".into(), "/workspaces".into()), + ("POST".into(), "/workspaces".into()), + ("POST".into(), format!("/workspaces/{wid}/sessions")), + ("POST".into(), format!("/sessions/{sid}/terminals")), + ("POST".into(), format!("/sessions/{sid}/terminals")), + ("PUT".into(), format!("/sessions/{sid}/terminals/order")), + ] + ); + assert_eq!(all[0].auth.as_deref(), Some("Bearer tok-1")); + + let ws_body: Value = serde_json::from_str(&all[1].body).unwrap(); + assert_eq!(all[1].content_type.as_deref(), Some("application/json")); + assert_eq!(ws_body["id"], Value::String(wid)); + assert_eq!(ws_body["name"], "OpenCollab"); + + let session_body: Value = serde_json::from_str(&all[2].body).unwrap(); + assert_eq!(session_body["id"], Value::String(sid.clone())); + assert_eq!(session_body["name"], "Sesión 1"); + + // Panel con agente conocido: el perfil es el comando base del agente + // (sin los argumentos que cada adaptador agrega por corrida: A1). + let agent_body: Value = serde_json::from_str(&all[3].body).unwrap(); + assert_eq!(agent_body["id"], Value::String(tid1.clone())); + assert_eq!(agent_body["name"], "claude-code"); + assert_eq!(agent_body["command"], "claude"); + assert_eq!(agent_body["args"], json!([])); + assert_eq!(agent_body["agent"], "claude-code"); + assert_eq!(agent_body["cwd"], "C:\\repo"); + // `minimized` falso no viaja: el server ya lo tiene por default. + assert!(agent_body.get("minimized").is_none()); + + // Shell plana: el perfil derivado es la shell por defecto del sistema. + let shell = crate::default_shell_profile(None); + let shell_body: Value = serde_json::from_str(&all[4].body).unwrap(); + assert_eq!(shell_body["id"], Value::String(tid2.clone())); + assert_eq!(shell_body["name"], Value::String(shell.name.clone())); + assert_eq!(shell_body["command"], Value::String(shell.command.clone())); + assert_eq!(shell_body["args"], json!(shell.args)); + assert_eq!(shell_body["minimized"], true); + // Los nulos no viajan: el server ya los tiene por default. + assert!(shell_body.get("cwd").is_none(), "cwd nulo no viaja"); + assert!(shell_body.get("agent").is_none(), "agent nulo no viaja"); + + let order: Value = serde_json::from_str(&all[5].body).unwrap(); + assert_eq!(order, json!({ "ids": [tid1, tid2] })); + } + + #[test] + fn save_renombra_y_actualiza_solo_lo_cambiado() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + // Server: mismos recursos con nombres viejos y el cwd de pane-1 vacío. + // El resto del perfil de pane-1 ya coincide: no se PATCHea. + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "viejo")])), + ok_reply(json!([{ + "id": sid, + "name": "vieja sesión", + "terminals": [{ + "id": tid1, + "name": "claude-code", + "command": "claude", + "args": [], + "cwd": null, + "agent": "claude-code", + "minimized": false, + }], + }])), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ok_reply(json!({})), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + // Esperado: lectura (workspaces + sesiones), PATCH ws, PATCH sesión, + // PATCH pane-1 (cwd), create pane-2, PUT de orden. + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!( + shapes, + vec![ + ("GET".into(), "/workspaces".into()), + ("GET".into(), format!("/workspaces/{wid}/sessions")), + ("PATCH".into(), format!("/workspaces/{wid}")), + ("PATCH".into(), format!("/sessions/{sid}")), + ("PATCH".into(), format!("/sessions/{sid}/terminals/{tid1}")), + ("POST".into(), format!("/sessions/{sid}/terminals")), + ("PUT".into(), format!("/sessions/{sid}/terminals/order")), + ] + ); + + let ws_patch: Value = serde_json::from_str(&all[2].body).unwrap(); + assert_eq!(ws_patch, json!({"name": "OpenCollab"})); + let session_patch: Value = serde_json::from_str(&all[3].body).unwrap(); + assert_eq!(session_patch, json!({"name": "Sesión 1"})); + + // pane-1 existe y solo cambia su cwd; pane-2 (nuevo) se crea después. + let patched: Value = serde_json::from_str(&all[4].body).unwrap(); + assert_eq!(patched, json!({"cwd": "C:\\repo"})); + let created: Value = serde_json::from_str(&all[5].body).unwrap(); + assert_eq!(created["id"], Value::String(tid2.clone())); + assert_eq!(created["minimized"], true); + + let order: Value = serde_json::from_str(&all[6].body).unwrap(); + assert_eq!(order, json!({"ids": [tid1, tid2]})); + } + + #[test] + fn save_borra_huerfanos_terminales_sesiones_y_workspaces() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + let wid_b = local_id_to_server_uuid("ws-extra"); + let wid_c = "33333333-3333-4333-8333-333333333333"; + let sid_huerfana = "44444444-4444-4444-8444-444444444444"; + let terminal_huerfana = "55555555-5555-4555-8555-555555555555"; + let panes = desired().workspaces[0].sessions[0].panes.clone(); + + let server = MockServer::start(vec![ + ok_reply(json!([ + workspace_entry(&wid, "OpenCollab"), + workspace_entry(&wid_b, "extra"), + workspace_entry(wid_c, "otro"), + ])), + ok_reply(json!([ + server_session( + &sid, + "Sesión 1", + vec![ + server_terminal(&panes[0]), + stray_terminal(terminal_huerfana, "sobra"), + ] + ), + server_session( + sid_huerfana, + "huérfana", + vec![stray_terminal( + "66666666-6666-4666-8666-666666666666", + "de la sesión huérfana", + )], + ), + ])), + ok_reply(json!([server_session( + "77777777-7777-4777-8777-777777777777", + "de otro workspace", + vec![], + )])), + ok_reply(json!([])), + ok_reply(json!({})), // create pane-2 (pane-1 ya coincide) + ok_reply(json!({})), // PUT de orden (cambió la composición) + ok_reply(json!({})), // DELETE terminal huérfana + ok_reply(json!({})), // DELETE sesión huérfana + ok_reply(json!({})), // DELETE ws_b + ok_reply(json!({})), // DELETE ws_c + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!(shapes.len(), 10, "{shapes:?}"); + // Fase 1, sesión conservada: DELETE de la terminal huérfana (primero + // ojo: el PUT de orden pide exactamente las que deben quedar), + // create de pane-2 y PUT con el orden final. + assert_eq!( + shapes[4], + ( + "DELETE".into(), + format!("/sessions/{sid}/terminals/{terminal_huerfana}") + ) + ); + assert_eq!( + shapes[5], + ("POST".into(), format!("/sessions/{sid}/terminals")) + ); + assert_eq!( + shapes[6], + ("PUT".into(), format!("/sessions/{sid}/terminals/order")) + ); + let order: Value = serde_json::from_str(&all[6].body).unwrap(); + assert_eq!(order, json!({"ids": [tid1, tid2]})); + // Fase 2: la sesión entera huérfana; su terminal no se borra por + // pedido propio, el cascade de la sesión lo hace. + assert_eq!( + shapes[7], + ("DELETE".into(), format!("/sessions/{sid_huerfana}")) + ); + // Fase 3: los workspaces sobrantes, al final del todo. + assert_eq!(shapes[8], ("DELETE".into(), format!("/workspaces/{wid_b}"))); + assert_eq!(shapes[9], ("DELETE".into(), format!("/workspaces/{wid_c}"))); + // El orden global(respetado en cascada): terminales → sesiones → workspaces. + let explicit_terminal_deletes = shapes + .iter() + .filter(|(m, p)| m == "DELETE" && p.contains("/terminals/")) + .count(); + assert_eq!(explicit_terminal_deletes, 1); + let (x, y, z) = delete_order(&shapes); + assert_eq!(x, 4, "primera DELETE de terminal"); + assert_eq!(y, 7, "primera DELETE de sesión"); + assert_eq!(z, 8, "primera DELETE de workspace"); + // El GET de sesiones tocó todos los workspaces del server. + assert_eq!( + shapes[2], + ("GET".into(), format!("/workspaces/{wid_b}/sessions")) + ); + assert_eq!( + shapes[3], + ("GET".into(), format!("/workspaces/{wid_c}/sessions")) + ); + } + + /// Posiciones de la primera DELETE por cada nivel del cascade. + fn delete_order(shapes: &[(String, String)]) -> (usize, usize, usize) { + let terminal = shapes + .iter() + .position(|(m, p)| m == "DELETE" && p.contains("/terminals/")) + .unwrap(); + let session = shapes + .iter() + .position(|(m, p)| { + m == "DELETE" && p.starts_with("/sessions/") && !p.contains("/terminals/") + }) + .unwrap(); + let workspace = shapes + .iter() + .position(|(m, p)| m == "DELETE" && p.starts_with("/workspaces/")) + .unwrap(); + (terminal, session, workspace) + } + + #[test] + fn save_orden_distinto_manda_put_y_reconstruye_el_orden() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + let panes = desired().workspaces[0].sessions[0].panes.clone(); + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "OpenCollab")])), + ok_reply(json!([server_session( + &sid, + "Sesión 1", + vec![server_terminal(&panes[1]), server_terminal(&panes[0]),] + )])), + ok_reply(json!({})), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + + // Solo el PUT: sin creates ni patches, los contenidos ya coinciden. + let all = server.requests(); + let shapes: Vec<(String, String)> = all + .iter() + .map(|r| (r.method.clone(), r.path.clone())) + .collect(); + assert_eq!( + shapes, + vec![ + ("GET".into(), "/workspaces".into()), + ("GET".into(), format!("/workspaces/{wid}/sessions")), + ("PUT".into(), format!("/sessions/{sid}/terminals/order")), + ] + ); + let order: Value = serde_json::from_str(&all[2].body).unwrap(); + assert_eq!(order, json!({"ids": [tid1, tid2]})); + } + + #[test] + fn save_con_orden_igual_no_manda_put() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let panes = desired().workspaces[0].sessions[0].panes.clone(); + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "OpenCollab")])), + ok_reply(json!([server_session( + &sid, + "Sesión 1", + vec![server_terminal(&panes[0]), server_terminal(&panes[1]),] + )])), + ]); + let cloud = store(&server); + cloud.save_snapshot(&desired()).unwrap(); + assert_eq!(server.count(), 2, "sin cambios: solo las lecturas"); + } + + #[test] + fn un_401_fuerza_un_refresh_y_reintenta_una_vez() { + let tokens = FakeTokens::new(); + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let server = MockServer::start(vec![ + error_reply(401), + ok_reply(json!([workspace_entry(&wid, "Cloud")])), + ok_reply(json!([server_session( + &sid, + "sesión", + vec![json!({ + "id": tid1, + "name": "x", + "command": "cmd", + "args": [], + "cwd": null, + "agent": null, + "minimized": false, + })] + )])), + ]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(tokens.clone())); + + let loaded = cloud.load_snapshot().unwrap().expect("cargó tras el retry"); + assert_eq!(loaded.workspaces[0].name, "Cloud"); + assert_eq!(tokens.refresh_count(), 1, "un único refresh"); + + let all = server.requests(); + assert_eq!(all.len(), 3); + assert_eq!(all[0].path, "/workspaces"); + assert_eq!(all[1].path, "/workspaces"); + assert_eq!(all[0].auth.as_deref(), Some("Bearer tok-1")); + assert_eq!( + all[1].auth.as_deref(), + Some("Bearer tok-2"), + "el reintento lleva el token refrescado" + ); + } + + #[test] + fn un_segundo_401_tras_el_reintento_es_error() { + let tokens = FakeTokens::new(); + let server = MockServer::start(vec![error_reply(401), error_reply(401)]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(tokens.clone())); + + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains("401"), "{}", err.0); + assert_eq!(tokens.refresh_count(), 1, "un solo refresh, sin loops"); + assert_eq!(server.count(), 2, "intento + reintento, nada más"); + } + + #[test] + fn los_403_404_500_son_errores_sin_reintento_ni_refresh() { + for status in [403u16, 404, 500] { + let tokens = FakeTokens::new(); + let server = MockServer::start(vec![error_reply(status)]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(tokens.clone())); + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains(&status.to_string()), "{status}: {}", err.0); + assert_eq!(tokens.refresh_count(), 0, "no hay refresh por un 401 ajeno"); + assert_eq!(server.count(), 1); + } + } + + #[test] + fn json_malformado_es_error_sin_panico() { + let server = MockServer::start(vec![MockReply { + status: 200, + body: "esto no es json".to_string(), + }]); + let cloud = store(&server); + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains("workspaces"), "{}", err.0); + assert!(err.0.contains("inválida"), "{}", err.0); + + // Y con una lista de workspaces a la que le falta un campo fijo. + let server2 = MockServer::start(vec![ok_reply(json!([{"name": "sin id"}]))]); + let cloud2 = store(&server2); + assert!(cloud2.load_snapshot().is_err()); + } + + #[test] + fn un_fallo_de_lectura_no_reporta_exit_ni_borra() { + let wid = local_id_to_server_uuid("ws-1"); + // La segunda lectura (sesiones del workspace) explota: no arrancó + // ninguna escritura y no hay deletes que hagan daño. + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "otra")])), + error_reply(500), + ]); + let cloud = store(&server); + let err = cloud.save_snapshot(&desired()).unwrap_err(); + assert!(err.0.contains("500"), "{}", err.0); + let all = server.requests(); + assert!( + all.iter().all(|r| r.method == "GET"), + "ninguna escritura se mandó" + ); + } + + #[test] + fn un_fallo_a_la_mitad_del_save_corta_en_seco() { + let sid = local_id_to_server_uuid("session-1"); + let tid1 = local_id_to_server_uuid("pane-1"); + let tid2 = local_id_to_server_uuid("pane-2"); + // El create del primer terminal explota a mitad de la fase 1: el + // guardado es Err y ninguna fase posterior queda colgando. + let server = MockServer::start(vec![ + ok_reply(json!([])), + ok_reply(json!({})), + ok_reply(json!({})), + error_reply(500), + ]); + let cloud = store(&server); + let err = cloud.save_snapshot(&desired()).unwrap_err(); + assert!(err.0.contains("500"), "{}", err.0); + let all = server.requests(); + assert_eq!(all.len(), 4, "ni un pedido más después del fallo"); + assert_eq!(all[3].method, "POST"); + assert_eq!(all[3].path, format!("/sessions/{sid}/terminals")); + assert!( + !all.iter() + .any(|r| r.method == "DELETE" || r.path.contains("/order")), + "sin deletes ni PUT colgado" + ); + let _ = (tid1, tid2); + } + + #[test] + fn guardar_un_snapshot_vacio_borra_todos_los_workspaces() { + let wid = local_id_to_server_uuid("ws-1"); + let sid = local_id_to_server_uuid("session-1"); + let panes = desired().workspaces[0].sessions[0].panes.clone(); + // Snapshot vacío: el DELETE del workspace arrasa el resto por cascade, + // así que no hay deletes de sesiones ni de terminales. + let server = MockServer::start(vec![ + ok_reply(json!([workspace_entry(&wid, "una")])), + ok_reply(json!([server_session( + &sid, + "una", + vec![server_terminal(&panes[0]), server_terminal(&panes[1]),] + )])), + ok_reply(json!({})), // DELETE del workspace huérfano + ]); + let cloud = store(&server); + cloud + .save_snapshot(&WorkspaceSnapshot::new(vec![])) + .unwrap(); + + let all = server.requests(); + let deletes: Vec<&Recorded> = all.iter().filter(|r| r.method == "DELETE").collect(); + assert_eq!(deletes.len(), 1); + assert_eq!(deletes[0].path, format!("/workspaces/{wid}")); + } + + #[test] + fn sin_token_no_se_consulta_la_api() { + struct SinSesion; + impl AccessTokenProvider for SinSesion { + fn access_token(&self) -> Result { + Err(PortError::new( + "no hay sesión iniciada: el modo nube necesita login", + )) + } + + fn refreshed_access_token(&self, _rejected: &str) -> Result { + Err(PortError::new( + "no hay sesión iniciada: el modo nube necesita login", + )) + } + } + let server = MockServer::start(vec![]); + let cloud = CloudSnapshotStore::new(server.url(), Arc::new(SinSesion)); + let err = cloud.load_snapshot().unwrap_err(); + assert!(err.0.contains("no hay sesión"), "{}", err.0); + assert_eq!(server.count(), 0, "la API ni se enteró"); + assert!(cloud.save_snapshot(&desired()).is_err()); + assert_eq!(server.count(), 0); + } + + #[test] + fn base_url_con_barra_final_no_duplica_las_barras() { + let server = MockServer::start(vec![ok_reply(json!([]))]); + let cloud = CloudSnapshotStore::new(format!("{}/", server.url()), tokens()); + cloud.load_snapshot().unwrap(); + assert_eq!(server.requests()[0].path, "/workspaces"); + } + + #[test] + fn un_fallo_de_conexion_es_error_de_puerto() { + // Puerto reservado y soltado: nadie escucha ahí. + let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let url = format!("http://{}", listener.local_addr().unwrap()); + drop(listener); + let cloud = CloudSnapshotStore::new(url, tokens()); + let err = cloud.load_snapshot().unwrap_err(); + assert!( + err.0.contains("falló el pedido GET /workspaces"), + "{}", + err.0 + ); + } + + #[test] + fn migrar_sube_workspaces_locales_uno_por_uno_sin_borrar_los_que_ya_tenia_la_nube() { + let existing_wid = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; + let existing_sid = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; + let local_w1 = local_id_to_server_uuid("w-local-1"); + let local_s1 = local_id_to_server_uuid("s-local-1"); + let local_p1 = local_id_to_server_uuid("p-local-1"); + let local_w2 = local_id_to_server_uuid("w-local-2"); + let local_s2 = local_id_to_server_uuid("s-local-2"); + + let server = MockServer::start(vec![ + // fetch_current: la cuenta ya tiene un workspace previo en la nube. + ok_reply(json!([workspace_entry(existing_wid, "Ya en la nube")])), + ok_reply(json!([server_session(existing_sid, "Remota", vec![])])), + // Workspace local 1: POST workspace + POST session + POST terminal + PUT order. + ok_reply(json!({ "id": local_w1, "name": "Local 1" })), + ok_reply(json!({ "id": local_s1, "name": "Sesión 1", "terminals": [] })), + ok_reply(json!({ "id": local_p1 })), + ok_reply(json!({ "ids": [local_p1] })), + // Workspace local 2: POST workspace + POST session (sin terminales = sin PUT order). + ok_reply(json!({ "id": local_w2, "name": "Local 2" })), + ok_reply(json!({ "id": local_s2, "name": "Sesión 2", "terminals": [] })), + ]); + + let snapshot = WorkspaceSnapshot::new(vec![ + StoredWorkspace { + id: "w-local-1".into(), + name: "Local 1".into(), + sessions: vec![StoredSession { + id: "s-local-1".into(), + name: "Sesión 1".into(), + panes: vec![StoredPane { + id: "p-local-1".into(), + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("codex".into()), + }], + }], + }, + StoredWorkspace { + id: "w-local-2".into(), + name: "Local 2".into(), + sessions: vec![StoredSession { + id: "s-local-2".into(), + name: "Sesión 2".into(), + panes: vec![], + }], + }, + ]); + + let cloud = store(&server); + cloud.migrate_snapshot(&snapshot).unwrap(); + + let requests = server.requests(); + assert!( + requests.iter().all(|r| r.method != "DELETE"), + "la migración nunca debe borrar workspaces o sesiones existentes en la nube: {requests:?}" + ); + let paths: Vec<(&str, &str)> = requests + .iter() + .map(|r| (r.method.as_str(), r.path.as_str())) + .collect(); + let s1_terminals = format!("/workspaces/{local_w1}/sessions"); + let t1_path = format!("/sessions/{local_s1}/terminals"); + let t1_order = format!("/sessions/{local_s1}/terminals/order"); + let s2_sessions = format!("/workspaces/{local_w2}/sessions"); + let existing_sessions = format!("/workspaces/{existing_wid}/sessions"); + assert_eq!( + paths, + vec![ + ("GET", "/workspaces"), + ("GET", existing_sessions.as_str()), + ("POST", "/workspaces"), + ("POST", s1_terminals.as_str()), + ("POST", t1_path.as_str()), + ("PUT", t1_order.as_str()), + ("POST", "/workspaces"), + ("POST", s2_sessions.as_str()), + ] + ); + } + + #[test] + fn migrar_snapshot_vacio_no_consulta_la_api() { + let server = MockServer::start(vec![]); + let cloud = store(&server); + cloud + .migrate_snapshot(&WorkspaceSnapshot::new(vec![])) + .unwrap(); + assert_eq!(server.count(), 0); + } +} diff --git a/crates/infrastructure/src/directory_browser.rs b/apps/desktop/core/infrastructure/src/directory_browser.rs similarity index 100% rename from crates/infrastructure/src/directory_browser.rs rename to apps/desktop/core/infrastructure/src/directory_browser.rs diff --git a/crates/infrastructure/src/hook_receiver.rs b/apps/desktop/core/infrastructure/src/hook_receiver.rs similarity index 100% rename from crates/infrastructure/src/hook_receiver.rs rename to apps/desktop/core/infrastructure/src/hook_receiver.rs diff --git a/crates/infrastructure/src/lib.rs b/apps/desktop/core/infrastructure/src/lib.rs similarity index 79% rename from crates/infrastructure/src/lib.rs rename to apps/desktop/core/infrastructure/src/lib.rs index ded0677..ad77534 100644 --- a/crates/infrastructure/src/lib.rs +++ b/apps/desktop/core/infrastructure/src/lib.rs @@ -3,8 +3,10 @@ mod agent_launch; mod claude_adapter; mod claude_hooks; +mod cloud_store; mod directory_browser; mod hook_receiver; +mod local_store; mod memory_repository; mod opencode_adapter; mod opencode_events; @@ -17,9 +19,11 @@ mod sse; pub use agent_launch::{agent_shell_profile, command_exists}; pub use claude_adapter::ClaudeCodeAdapter; +pub use cloud_store::{local_id_to_server_uuid, CloudSnapshotStore}; pub use directory_browser::FsDirectoryBrowser; pub use hook_receiver::HookReceiver; -pub use memory_repository::InMemoryWorkspaceRepository; +pub use local_store::FsSnapshotStore; +pub use memory_repository::InMemorySessionRepository; pub use opencode_adapter::OpenCodeAdapter; pub use process_inspector::SysinfoProcessInspector; pub use pty::PortablePtyAdapter; diff --git a/apps/desktop/core/infrastructure/src/local_store.rs b/apps/desktop/core/infrastructure/src/local_store.rs new file mode 100644 index 0000000..e268df9 --- /dev/null +++ b/apps/desktop/core/infrastructure/src/local_store.rs @@ -0,0 +1,254 @@ +//! Backend local del snapshot: un JSON en el directorio de datos de la app. +//! +//! Escritura atómica (temporal + renombre) para que un cierre a medias nunca +//! deje el snapshot corrupto, y cuarentena de archivos ilegibles: un archivo +//! que no se puede leer se renombra a `.corrupt` y la app arranca limpia en +//! vez de no abrir (S5: persistir es una mejora, nunca un obstáculo). + +use std::fs; +use std::path::PathBuf; + +use application::ports::{PortError, SnapshotStore}; +use application::storage::WorkspaceSnapshot; + +const FILE_NAME: &str = "workspaces.json"; +const CORRUPT_EXT: &str = "corrupt"; + +/// Snapshot en `dir/workspaces.json`. `dir` es el directorio de datos de la +/// app (appdata en producción, un temporal en los tests). +pub struct FsSnapshotStore { + path: PathBuf, +} + +impl FsSnapshotStore { + pub fn new(dir: impl Into) -> Self { + Self { + path: dir.into().join(FILE_NAME), + } + } + + pub fn path(&self) -> &std::path::Path { + &self.path + } + + /// Pone el archivo ilegible a un lado con extensión `.corrupt` para no + /// pisarlo con el próximo guardado. Best-effort: si falla, el arranque + /// limpio sigue igual (el próximo guardado lo reemplaza). + fn quarantine(&self) { + let to = self.path.with_extension(CORRUPT_EXT); + let _ = fs::rename(&self.path, &to); + } +} + +impl SnapshotStore for FsSnapshotStore { + fn load_snapshot(&self) -> Result, PortError> { + let data = match fs::read_to_string(&self.path) { + Ok(data) => data, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(e) => return Err(PortError::new(format!("no se pudo leer el snapshot: {e}"))), + }; + match serde_json::from_str::(&data) { + Ok(snapshot) if snapshot.is_current_version() => Ok(Some(snapshot)), + // Ilegible o de una versión que no sabemos leer: cuarentena y + // arranque limpio. Nunca frenar la app por un archivo roto. + _ => { + self.quarantine(); + Ok(None) + } + } + } + + fn save_snapshot(&self, snapshot: &WorkspaceSnapshot) -> Result<(), PortError> { + let json = serde_json::to_string(snapshot) + .map_err(|e| PortError::new(format!("no se pudo serializar el snapshot: {e}")))?; + // Escritura atómica: primero al temporal, después renombre. Un cierre + // a medias deja intacto el snapshot anterior. + if let Some(parent) = self.path.parent() { + fs::create_dir_all(parent).map_err(|e| { + PortError::new(format!("no se pudo crear el directorio de datos: {e}")) + })?; + } + let tmp = self.path.with_extension("json.tmp"); + fs::write(&tmp, json) + .map_err(|e| PortError::new(format!("no se pudo escribir el snapshot: {e}")))?; + fs::rename(&tmp, &self.path) + .map_err(|e| PortError::new(format!("no se pudo reemplazar el snapshot: {e}"))) + } +} + +#[cfg(test)] +mod tests { + use std::path::Path; + use std::sync::atomic::{AtomicU64, Ordering}; + + use application::storage::{StoredPane, StoredSession, StoredWorkspace, SNAPSHOT_VERSION}; + + use super::*; + + /// Directorio temporal por test; se borra al salir del scope. + struct TempDir(PathBuf); + + impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::SeqCst); + let path = std::env::temp_dir().join(format!( + "opencollab-local-store-{tag}-{}-{n}", + std::process::id() + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + + fn sub(&self, name: &str) -> PathBuf { + let p = self.0.join(name); + fs::create_dir_all(&p).unwrap(); + p + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn snapshot() -> WorkspaceSnapshot { + WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-1".into(), + name: "OpenCollab".into(), + sessions: vec![StoredSession { + id: "session-1".into(), + name: "Sesión 1".into(), + panes: vec![ + StoredPane { + id: "pane-1".into(), + seq: 0, + minimized: false, + initial_cwd: Some("C:\\repo".into()), + agent: Some("claude-code".into()), + }, + StoredPane { + id: "pane-2".into(), + seq: 1, + minimized: true, + initial_cwd: None, + agent: None, + }, + ], + }], + }]) + } + + #[test] + fn round_trips_the_whole_structure() { + let dir = TempDir::new("round-trip"); + let store = FsSnapshotStore::new(dir.0.clone()); + store.save_snapshot(&snapshot()).unwrap(); + let loaded = store.load_snapshot().unwrap(); + assert_eq!(loaded, Some(snapshot())); + } + + #[test] + fn no_file_yet_means_no_snapshot() { + let dir = TempDir::new("missing"); + let store = FsSnapshotStore::new(dir.0.clone()); + assert_eq!(store.load_snapshot().unwrap(), None); + } + + #[test] + fn save_creates_missing_parent_directories() { + let dir = TempDir::new("create-dirs"); + let nested = dir.sub("a").join("b"); // todavía no existe + let store = FsSnapshotStore::new(nested); + store.save_snapshot(&snapshot()).unwrap(); + assert!(store.path().is_file()); + } + + #[test] + fn saving_replaces_the_previous_snapshot() { + let dir = TempDir::new("replace"); + let store = FsSnapshotStore::new(dir.0.clone()); + store.save_snapshot(&snapshot()).unwrap(); + let next = WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "ws-2".into(), + name: "otro".into(), + sessions: vec![], + }]); + store.save_snapshot(&next).unwrap(); + assert_eq!(store.load_snapshot().unwrap(), Some(next)); + } + + #[test] + fn garbage_file_is_quarantined_and_boot_is_fresh() { + let dir = TempDir::new("garbage"); + let store = FsSnapshotStore::new(dir.0.clone()); + fs::write(store.path(), "no es json").unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + // El original queda a un lado, recuperable a mano. + let corrupt = store.path().with_extension(CORRUPT_EXT); + assert_eq!(fs::read_to_string(&corrupt).unwrap(), "no es json"); + // Y el segundo arranque ya ni lo ve: el archivo original ya no está. + assert_eq!(store.load_snapshot().unwrap(), None); + } + + #[test] + fn future_version_is_quarantined_and_boot_is_fresh() { + let dir = TempDir::new("future"); + let store = FsSnapshotStore::new(dir.0.clone()); + let future = serde_json::to_string(&WorkspaceSnapshot { + version: SNAPSHOT_VERSION + 1, + workspaces: vec![], + }) + .unwrap(); + fs::write(store.path(), future).unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + assert!(store.path().with_extension(CORRUPT_EXT).is_file()); + } + + #[test] + fn empty_file_is_quarantined_and_boot_is_fresh() { + let dir = TempDir::new("empty"); + let store = FsSnapshotStore::new(dir.0.clone()); + fs::write(store.path(), "").unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + assert!(store.path().with_extension(CORRUPT_EXT).is_file()); + } + + #[test] + fn save_over_quarantined_leftovers_still_works() { + let dir = TempDir::new("after-corrupt"); + let store = FsSnapshotStore::new(dir.0.clone()); + fs::write(store.path(), "roto").unwrap(); + assert_eq!(store.load_snapshot().unwrap(), None); + // Arrancó limpio: el próximo guardado escribe el archivo de vuelta. + store.save_snapshot(&snapshot()).unwrap(); + assert_eq!(store.load_snapshot().unwrap(), Some(snapshot())); + // La cuarentena del arranque anterior no molesta al nuevo archivo. + assert!(store.path().with_extension(CORRUPT_EXT).is_file()); + } + + #[test] + fn pane_order_survives_the_round_trip() { + let dir = TempDir::new("order"); + let store = FsSnapshotStore::new(dir.0.clone()); + let mut snap = snapshot(); + let StoredWorkspace { sessions, .. } = &mut snap.workspaces[0]; + sessions[0].panes.reverse(); // orden visual distinto al de creación + store.save_snapshot(&snap).unwrap(); + let loaded = store.load_snapshot().unwrap().unwrap(); + let panes = &loaded.workspaces[0].sessions[0].panes; + assert_eq!(panes[0].id, "pane-2"); + assert_eq!(panes[1].id, "pane-1"); + // El seq (orden del DOM) viaja intacto aunque el array esté reordenado. + assert_eq!(panes[0].seq, 1); + assert_eq!(panes[1].seq, 0); + } + + #[test] + fn path_is_inside_the_configured_directory() { + let dir = TempDir::new("path"); + let store = FsSnapshotStore::new(dir.0.clone()); + assert_eq!(store.path(), Path::new(&dir.0).join(FILE_NAME)); + } +} diff --git a/apps/desktop/core/infrastructure/src/memory_repository.rs b/apps/desktop/core/infrastructure/src/memory_repository.rs new file mode 100644 index 0000000..09feea9 --- /dev/null +++ b/apps/desktop/core/infrastructure/src/memory_repository.rs @@ -0,0 +1,52 @@ +use std::collections::HashMap; +use std::sync::Mutex; + +use application::ports::{PortError, SessionRepository}; +use domain::{Session, SessionId}; + +/// Repositorio en memoria. Sirve para el desktop mientras no haya persistencia. +#[derive(Default)] +pub struct InMemorySessionRepository { + sessions: Mutex>, +} + +impl InMemorySessionRepository { + pub fn new() -> Self { + Self::default() + } +} + +fn poisoned(_: T) -> PortError { + PortError::new("repositorio en memoria envenenado") +} + +impl SessionRepository for InMemorySessionRepository { + fn find_session(&self, id: SessionId) -> Result, PortError> { + Ok(self.sessions.lock().map_err(poisoned)?.get(&id).cloned()) + } + + fn save_session(&self, session: Session) -> Result<(), PortError> { + self.sessions + .lock() + .map_err(poisoned)? + .insert(session.id(), session); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use domain::UserId; + + use super::*; + + #[test] + fn saves_and_finds() { + let repo = InMemorySessionRepository::new(); + let session = Session::new(UserId::new(), "s"); + let id = session.id(); + repo.save_session(session).unwrap(); + assert!(repo.find_session(id).unwrap().is_some()); + assert!(repo.find_session(SessionId::new()).unwrap().is_none()); + } +} diff --git a/crates/infrastructure/src/opencode_adapter.rs b/apps/desktop/core/infrastructure/src/opencode_adapter.rs similarity index 100% rename from crates/infrastructure/src/opencode_adapter.rs rename to apps/desktop/core/infrastructure/src/opencode_adapter.rs diff --git a/crates/infrastructure/src/opencode_events.rs b/apps/desktop/core/infrastructure/src/opencode_events.rs similarity index 100% rename from crates/infrastructure/src/opencode_events.rs rename to apps/desktop/core/infrastructure/src/opencode_events.rs diff --git a/crates/infrastructure/src/process_inspector.rs b/apps/desktop/core/infrastructure/src/process_inspector.rs similarity index 100% rename from crates/infrastructure/src/process_inspector.rs rename to apps/desktop/core/infrastructure/src/process_inspector.rs diff --git a/crates/infrastructure/src/pty.rs b/apps/desktop/core/infrastructure/src/pty.rs similarity index 100% rename from crates/infrastructure/src/pty.rs rename to apps/desktop/core/infrastructure/src/pty.rs diff --git a/crates/infrastructure/src/relay_probe.rs b/apps/desktop/core/infrastructure/src/relay_probe.rs similarity index 100% rename from crates/infrastructure/src/relay_probe.rs rename to apps/desktop/core/infrastructure/src/relay_probe.rs diff --git a/crates/infrastructure/src/repository_inspector.rs b/apps/desktop/core/infrastructure/src/repository_inspector.rs similarity index 100% rename from crates/infrastructure/src/repository_inspector.rs rename to apps/desktop/core/infrastructure/src/repository_inspector.rs diff --git a/crates/infrastructure/src/shell.rs b/apps/desktop/core/infrastructure/src/shell.rs similarity index 100% rename from crates/infrastructure/src/shell.rs rename to apps/desktop/core/infrastructure/src/shell.rs diff --git a/crates/infrastructure/src/sse.rs b/apps/desktop/core/infrastructure/src/sse.rs similarity index 100% rename from crates/infrastructure/src/sse.rs rename to apps/desktop/core/infrastructure/src/sse.rs diff --git a/crates/infrastructure/tests/agent_detection_e2e.rs b/apps/desktop/core/infrastructure/tests/agent_detection_e2e.rs similarity index 100% rename from crates/infrastructure/tests/agent_detection_e2e.rs rename to apps/desktop/core/infrastructure/tests/agent_detection_e2e.rs diff --git a/crates/infrastructure/tests/claude_adapter_e2e.rs b/apps/desktop/core/infrastructure/tests/claude_adapter_e2e.rs similarity index 100% rename from crates/infrastructure/tests/claude_adapter_e2e.rs rename to apps/desktop/core/infrastructure/tests/claude_adapter_e2e.rs diff --git a/crates/infrastructure/tests/opencode_adapter_e2e.rs b/apps/desktop/core/infrastructure/tests/opencode_adapter_e2e.rs similarity index 100% rename from crates/infrastructure/tests/opencode_adapter_e2e.rs rename to apps/desktop/core/infrastructure/tests/opencode_adapter_e2e.rs diff --git a/crates/infrastructure/tests/shell_integration_e2e.rs b/apps/desktop/core/infrastructure/tests/shell_integration_e2e.rs similarity index 100% rename from crates/infrastructure/tests/shell_integration_e2e.rs rename to apps/desktop/core/infrastructure/tests/shell_integration_e2e.rs diff --git a/crates/protocol/Cargo.toml b/apps/desktop/core/protocol/Cargo.toml similarity index 100% rename from crates/protocol/Cargo.toml rename to apps/desktop/core/protocol/Cargo.toml diff --git a/crates/protocol/src/lib.rs b/apps/desktop/core/protocol/src/lib.rs similarity index 100% rename from crates/protocol/src/lib.rs rename to apps/desktop/core/protocol/src/lib.rs diff --git a/apps/desktop/e2e/run.mjs b/apps/desktop/e2e/run.mjs index d294eab..01cd8d1 100644 --- a/apps/desktop/e2e/run.mjs +++ b/apps/desktop/e2e/run.mjs @@ -19,6 +19,12 @@ import statusBarLive from "./scenarios/status-bar-live.mjs"; import newTerminalHere from "./scenarios/new-terminal-here.mjs"; import launchAgent from "./scenarios/launch-agent.mjs"; import authSignin from "./scenarios/auth-signin.mjs"; +import snapshotLoadError from "./scenarios/snapshot-load-error.mjs"; +import onboarding from "./scenarios/onboarding.mjs"; +import settingsStorage from "./scenarios/settings-storage.mjs"; +import cloudBootSession from "./scenarios/cloud-boot-session.mjs"; +import localCollabInactive from "./scenarios/local-collab-inactive.mjs"; +import localToCloudMigration from "./scenarios/local-to-cloud-migration.mjs"; const scenarios = { "drag & swap de terminales": dragSwap, @@ -29,6 +35,12 @@ const scenarios = { "exit en la shell cierra el panel": exitClosesPane, "status bar con estado real": statusBarLive, "login vía la web": authSignin, + "fallo de carga no pisa el snapshot": snapshotLoadError, + "primera corrida elige almacenamiento": onboarding, + "ajustes de almacenamiento": settingsStorage, + "reinicio cloud sin sesión": cloudBootSession, + "colaboración visible pero inactiva en modo local": localCollabInactive, + "migración local a cloud al cambiar de modo": localToCloudMigration, }; function chromePath() { diff --git a/apps/desktop/e2e/scenarios/cloud-boot-session.mjs b/apps/desktop/e2e/scenarios/cloud-boot-session.mjs new file mode 100644 index 0000000..58efba9 --- /dev/null +++ b/apps/desktop/e2e/scenarios/cloud-boot-session.mjs @@ -0,0 +1,58 @@ +// Reinicio en modo cloud: la config persiste pero los tokens viven solo en +// memoria, así que sin login no se monta la grilla ni se guarda nada. Al +// iniciar sesión se carga el snapshot de la cuenta; logout vuelve al gate y el +// siguiente login lo recupera. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +const cloudSnapshot = { + version: 1, + workspaces: [ + { + id: "w-cloud", + name: "Nube", + sessions: [ + { + id: "s-cloud", + name: "Sesión nube", + panes: [{ id: "p-cloud", seq: 0, minimized: false, initialCwd: null, agent: null }], + }, + ], + }, + ], +}; + +export default async function cloudBootSession(page, checks) { + const base = page.url().split("?")[0]; + await page.goto(`${base}?mockCloud=1`, { waitUntil: "networkidle0" }); + await wait(300); + + checks["cloud sin sesión no monta la grilla"] = (await page.$(".app")) === null; + checks["cloud sin sesión pide login"] = await page.evaluate(() => + document.body.textContent.includes("Sign in to load your workspace structure"), + ); + checks["cloud sin sesión no guarda el default"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) === null; + + await page.evaluate((snapshot) => window.__mock.setSnapshot(snapshot), cloudSnapshot); + await page.evaluate(() => window.__mock.signIn()); + await wait(600); + + checks["el login carga la nube"] = await page.evaluate(() => + document.body.textContent.includes("Nube"), + ); + checks["la grilla usa el snapshot de la cuenta"] = await page.evaluate( + () => window.__mock.savedSnapshot?.workspaces?.[0]?.id === "w-cloud", + ); + + await page.evaluate(() => window.__mock.signOut()); + await wait(300); + checks["logout vuelve al gate"] = + (await page.$(".app")) === null && + (await page.evaluate(() => document.body.textContent.includes("Sign in"))); + + await page.evaluate(() => window.__mock.signIn()); + await wait(600); + checks["re-login recupera la nube"] = await page.evaluate(() => + document.body.textContent.includes("Nube"), + ); +} diff --git a/apps/desktop/e2e/scenarios/local-collab-inactive.mjs b/apps/desktop/e2e/scenarios/local-collab-inactive.mjs new file mode 100644 index 0000000..48176e8 --- /dev/null +++ b/apps/desktop/e2e/scenarios/local-collab-inactive.mjs @@ -0,0 +1,90 @@ +// Modo local (S3): la colaboración sigue visible en TopBar, Sidebar y +// StatusBar pero permanece inactiva hasta cambiar a almacenamiento Cloud. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function localCollabInactive(page, checks) { + await wait(300); + + const initial = await page.evaluate(() => { + const invite = [...document.querySelectorAll(".topbar-actions button")].find((b) => + b.textContent.includes("Invite"), + ); + const wsMeta = document.querySelector(".sidebar .ws-meta"); + const userCard = document.querySelector(".sidebar .user"); + const statusItems = [...document.querySelectorAll(".statusbar-item")]; + return { + inviteVisible: !!invite && invite.offsetParent !== null, + inviteDisabled: invite instanceof HTMLButtonElement && invite.disabled, + inviteInactive: invite?.getAttribute("data-collab-inactive") === "true", + inviteTitle: invite?.getAttribute("title") ?? "", + wsMetaVisible: !!wsMeta && wsMeta.offsetParent !== null, + wsMetaInactive: wsMeta?.getAttribute("data-collab-inactive") === "true", + userVisible: !!userCard && userCard.offsetParent !== null, + userInactive: userCard?.getAttribute("data-collab-inactive") === "true", + userText: userCard?.textContent ?? "", + statusCount: statusItems.length, + statusInactive: statusItems.every((el) => el.getAttribute("data-collab-inactive") === "true"), + statusTexts: statusItems.map((el) => el.textContent.trim()), + }; + }); + + checks["Invite sigue visible pero deshabilitado en modo local"] = + initial.inviteVisible && initial.inviteDisabled && initial.inviteInactive; + checks["Invite explica que el modo local no invita"] = initial.inviteTitle.includes("Modo local"); + checks["el contador de miembros del workspace sigue visible e inactivo"] = + initial.wsMetaVisible && initial.wsMetaInactive; + checks["la tarjeta de cuenta indica colaboración inactiva en modo local"] = + initial.userVisible && + initial.userInactive && + initial.userText.includes("Colaboración inactiva en modo local"); + checks["la status bar mantiene visibles los indicadores en estado inactivo"] = + initial.statusCount === 2 && + initial.statusInactive && + initial.statusTexts[0] === "Local · relay no conectado" && + initial.statusTexts[1] === "1 collaborator"; + + // Incluso con sesión iniciada, el modo local no aparece como Online. + await page.evaluate(() => window.__mock.signIn()); + await wait(200); + const signedInLocal = await page.evaluate(() => ({ + userText: document.querySelector(".sidebar .user")?.textContent ?? "", + userInactive: + document.querySelector(".sidebar .user")?.getAttribute("data-collab-inactive") === "true", + })); + checks["con cuenta iniciada en modo local muestra colaboración inactiva (no Online)"] = + signedInLocal.userInactive && + signedInLocal.userText.includes("Local · colaboración inactiva") && + !signedInLocal.userText.includes("Online"); + + // Cambiar a Cloud en Settings activa los indicadores de colaboración. + await page.click('button[aria-label="Settings"]'); + await wait(200); + await page.evaluate(() => { + const [, cloud] = document.querySelectorAll(".settings-mode input"); + cloud.click(); + }); + await wait(100); + await page.click(".modal-actions .btn--primary"); + await wait(400); + + const inCloud = await page.evaluate(() => { + const invite = [...document.querySelectorAll(".topbar-actions button")].find((b) => + b.textContent.includes("Invite"), + ); + const userCard = document.querySelector(".sidebar .user"); + const wsMeta = document.querySelector(".sidebar .ws-meta"); + return { + inviteInactive: invite?.getAttribute("data-collab-inactive"), + inviteTitle: invite?.getAttribute("title") ?? "", + userInactive: userCard?.getAttribute("data-collab-inactive"), + userText: userCard?.textContent ?? "", + wsMetaInactive: wsMeta?.getAttribute("data-collab-inactive"), + }; + }); + checks["al pasar a Cloud la colaboración deja de figurar inactiva"] = + inCloud.inviteInactive === null && + inCloud.userInactive === null && + inCloud.wsMetaInactive === null && + inCloud.userText.includes("Online") && + inCloud.inviteTitle.includes("Requiere el relay"); +} diff --git a/apps/desktop/e2e/scenarios/local-to-cloud-migration.mjs b/apps/desktop/e2e/scenarios/local-to-cloud-migration.mjs new file mode 100644 index 0000000..b59d934 --- /dev/null +++ b/apps/desktop/e2e/scenarios/local-to-cloud-migration.mjs @@ -0,0 +1,76 @@ +// Cambio de modo local → cloud (S4, A4): migra los workspaces, sesiones y +// terminales locales a la cuenta cloud sin borrar los que la cuenta ya tenía, +// y conserva intacto el archivo local. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +const preExistingCloud = { + version: 1, + workspaces: [ + { + id: "w-cloud-existing", + name: "Equipo Cloud", + sessions: [ + { + id: "s-cloud-existing", + name: "Sesión compartida", + panes: [{ id: "p-cloud-1", seq: 0, minimized: false, initialCwd: null, agent: null }], + }, + ], + }, + ], +}; + +export default async function localToCloudMigration(page, checks) { + await wait(300); + + // Creamos un segundo workspace en modo local para verificar que viaja toda + // la estructura local al cambiar a Cloud. + await page.click(".ws-current"); + await wait(150); + await page.click(".ws-menu-new"); + await wait(300); + + const localBeforeSwitch = await page.evaluate(() => window.__mock.localSnapshot); + checks["en modo local se persisten los workspaces creados"] = + Array.isArray(localBeforeSwitch?.workspaces) && localBeforeSwitch.workspaces.length === 2; + + // La cuenta cloud ya tiene un workspace previo ("Equipo Cloud"). + await page.evaluate((cloud) => { + window.__mock.setCloudSnapshot(cloud); + window.__mock.signIn(); + }, preExistingCloud); + await wait(200); + + await page.click('button[aria-label="Settings"]'); + await wait(200); + await page.evaluate(() => { + const [, cloud] = document.querySelectorAll(".settings-mode input"); + cloud.click(); + }); + await wait(100); + + checks["Settings avisa que los datos locales se migran y el archivo local se conserva"] = + await page.evaluate(() => { + const hint = document.querySelector(".settings-hint")?.textContent ?? ""; + return hint.includes("migrated to your cloud account") && hint.includes("Local files are kept"); + }); + + await page.click(".modal-actions .btn--primary"); + await wait(500); + + const afterMigration = await page.evaluate(() => ({ + mode: window.__mock.storageConfig.mode, + localWorkspaces: window.__mock.localSnapshot?.workspaces?.map((w) => w.name) ?? [], + cloudWorkspaces: window.__mock.cloudSnapshot?.workspaces?.map((w) => w.name) ?? [], + })); + + checks["el cambio pasa a modo cloud"] = afterMigration.mode === "cloud"; + checks["la nube conserva su workspace previo y suma los migrados desde local"] = + afterMigration.cloudWorkspaces.includes("Equipo Cloud") && + afterMigration.cloudWorkspaces.includes("OpenCollab") && + afterMigration.cloudWorkspaces.includes("Workspace 2"); + checks["el archivo local se conserva intacto tras la migración (A4)"] = + afterMigration.localWorkspaces.length === 2 && + afterMigration.localWorkspaces.includes("OpenCollab") && + afterMigration.localWorkspaces.includes("Workspace 2"); +} diff --git a/apps/desktop/e2e/scenarios/onboarding.mjs b/apps/desktop/e2e/scenarios/onboarding.mjs new file mode 100644 index 0000000..9426963 --- /dev/null +++ b/apps/desktop/e2e/scenarios/onboarding.mjs @@ -0,0 +1,29 @@ +// Primera corrida: sin configuración completa la app muestra el onboarding y +// no monta la grilla. Elegir local persiste el modo y crea el snapshot default. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function onboarding(page, checks) { + const base = page.url().split("?")[0]; + await page.goto(`${base}?mockFirstRun=1`, { waitUntil: "networkidle0" }); + await wait(300); + + checks["la primera corrida muestra el onboarding"] = (await page.$(".onboarding")) !== null; + checks["el onboarding reemplaza la grilla"] = (await page.$(".app")) === null; + + const clicked = await page.evaluate(() => { + const button = [...document.querySelectorAll(".onboarding-mode")].find((b) => + b.textContent.includes("Local"), + ); + if (button) button.click(); + return !!button; + }); + checks["ofrece elegir almacenamiento local"] = clicked; + await wait(500); + + checks["elegir local entra a la app"] = (await page.$(".app")) !== null; + checks["persiste el modo local"] = await page.evaluate( + () => window.__mock.storageConfig.onboardingComplete && window.__mock.storageConfig.mode === "local", + ); + checks["crea el snapshot default"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) !== null; +} diff --git a/apps/desktop/e2e/scenarios/settings-storage.mjs b/apps/desktop/e2e/scenarios/settings-storage.mjs new file mode 100644 index 0000000..66d753c --- /dev/null +++ b/apps/desktop/e2e/scenarios/settings-storage.mjs @@ -0,0 +1,38 @@ +// Settings: el engranaje del TopBar abre el modal y guardar persiste la base +// URL vía `storage_config_set`. Con sesión anónima, cloud queda bloqueado. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function settingsStorage(page, checks) { + await wait(300); + await page.click('button[aria-label="Settings"]'); + await wait(200); + checks["el engranaje abre Settings"] = (await page.$(".modal")) !== null; + checks["Settings muestra las dos opciones"] = + (await page.$$(".settings-mode")).length === 2; + + await page.evaluate(() => { + const input = document.querySelector(".settings-field input"); + const setter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set; + setter.call(input, "http://localhost:9999"); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await page.click(".modal-actions .btn--primary"); + await wait(400); + + checks["guardar persiste la base URL"] = await page.evaluate( + () => window.__mock.storageConfig.apiBaseUrl === "http://localhost:9999", + ); + checks["guardar cierra el modal"] = (await page.$(".modal")) === null; + + await page.click('button[aria-label="Settings"]'); + await wait(200); + await page.evaluate(() => { + const [, cloud] = document.querySelectorAll(".settings-mode input"); + cloud.click(); + }); + await wait(100); + checks["cloud sin sesión no se puede guardar"] = await page.evaluate(() => { + const save = document.querySelector(".modal-actions .btn--primary"); + return save instanceof HTMLButtonElement && save.disabled; + }); +} diff --git a/apps/desktop/e2e/scenarios/snapshot-load-error.mjs b/apps/desktop/e2e/scenarios/snapshot-load-error.mjs new file mode 100644 index 0000000..39b3d57 --- /dev/null +++ b/apps/desktop/e2e/scenarios/snapshot-load-error.mjs @@ -0,0 +1,28 @@ +// Regresión de R4-load-error-destroys-snapshot: si el núcleo falla al cargar +// el snapshot, la app sigue con la estructura default pero NO debe habilitar +// el guardado; de lo contrario la primera mutación pisa el archivo válido. +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +export default async function snapshotLoadError(page, checks) { + const base = page.url().split("?")[0]; + await page.goto(`${base}?mockSnapshotLoadError=1`, { waitUntil: "networkidle0" }); + await wait(300); + + checks["el fallo de carga deja la estructura default"] = + (await page.$$(".pane:not([hidden])")).length === 1; + + // Primera mutación estructural después del fallo: abrir otra terminal. + await page.click(".topbar .btn--primary"); + await wait(300); + + checks["una mutación posterior al fallo no persiste el default"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) === null; + + // Sin el fallo inyectado, la persistencia vuelve a funcionar en la carga siguiente. + await page.goto(base, { waitUntil: "networkidle0" }); + await wait(300); + await page.click(".topbar .btn--primary"); + await wait(300); + checks["sin el fallo, la mutación vuelve a persistir"] = + (await page.evaluate(() => window.__mock.savedSnapshot)) !== null; +} diff --git a/apps/desktop/e2e/tauri-mock.js b/apps/desktop/e2e/tauri-mock.js index 25d5920..bc71b74 100644 --- a/apps/desktop/e2e/tauri-mock.js +++ b/apps/desktop/e2e/tauri-mock.js @@ -11,6 +11,11 @@ // agentState(id, patch) emite terminal-agent-state con el estado completo (patch sobre el vacío) // branches carpeta -> { name, detached } devuelto por git_branch (sin entrada = no es un repo) // prompt(id, path) como la shell integration: OSC 7 + prompt (cambia la carpeta de la terminal) +// savedSnapshot último payload de snapshot_save (versión 1 estampada por el mock) +// storageConfig modo/base URL vigentes (storage_config_get/set) +// signIn()/signOut() simula el deep link de login / logout (emite auth-changed) +// setSnapshot(snap) precarga el snapshot que devuelve snapshot_load +// snapshotLoads cantidad de snapshot_load ejecutados export function installTauriMock() { const listeners = {}; // evento -> [id de callback] let callbacks = 0; @@ -19,6 +24,19 @@ export function installTauriMock() { const opened = []; const closed = []; const branches = {}; + let localSaved = null; // snapshot local (workspaces.json) + let cloudSaved = null; // snapshot cloud (API REST) + const params = new URLSearchParams(location.search); + // ?mockFirstRun=1 simula la primera corrida; ?mockCloud=1 arranca en cloud + // con la configuración completa pero sin sesión en memoria (reinicio real). + let signedIn = false; + let snapshotLoads = 0; + let storageConfig = { + version: 1, + mode: params.get("mockCloud") === "1" ? "cloud" : "local", + apiBaseUrl: "http://127.0.0.1:8787", + onboardingComplete: params.get("mockFirstRun") !== "1", + }; const encoder = new TextEncoder(); const emit = (event, payload) => @@ -51,7 +69,48 @@ export function installTauriMock() { }, }); - window.__mock = { emit, agentState, prompt, writes, opened, closed, branches }; + const user = { id: "u1", username: "tester", email: null, displayName: "Tester" }; + const signIn = () => { + signedIn = true; + emit("auth-changed", { user }); + }; + const signOut = () => { + signedIn = false; + emit("auth-changed", { user: null }); + }; + window.__mock = { + emit, + agentState, + prompt, + writes, + opened, + closed, + branches, + signIn, + signOut, + setSnapshot(snapshot) { + if (storageConfig.mode === "cloud") cloudSaved = snapshot; + else localSaved = snapshot; + }, + setCloudSnapshot(snapshot) { + cloudSaved = snapshot; + }, + get savedSnapshot() { + return storageConfig.mode === "cloud" ? cloudSaved : localSaved; + }, + get localSnapshot() { + return localSaved; + }, + get cloudSnapshot() { + return cloudSaved; + }, + get storageConfig() { + return storageConfig; + }, + get snapshotLoads() { + return snapshotLoads; + }, + }; window.__TAURI_EVENT_PLUGIN_INTERNALS__ = { unregisterListener() {} }; window.__TAURI_INTERNALS__ = { metadata: { @@ -90,6 +149,63 @@ export function installTauriMock() { closed.push(args.terminalId); setTimeout(() => emit("terminal-exit", { terminalId: args.terminalId }), 20); return null; + case "snapshot_load": + // Fallo de carga inyectado por el escenario de regresión (?mockSnapshotLoadError=1). + if (new URLSearchParams(location.search).get("mockSnapshotLoadError") === "1") + throw new Error("snapshot_load failed (e2e)"); + snapshotLoads += 1; + // Cloud sin tokens en memoria: el núcleo real responde sin sesión. + if (storageConfig.mode === "cloud" && !signedIn) + throw new Error("no hay sesión iniciada"); + // Sin snapshot guardado: primera corrida / arranque limpio. + { + const active = storageConfig.mode === "cloud" ? cloudSaved : localSaved; + return active ? JSON.parse(JSON.stringify(active)) : null; + } + case "snapshot_save": + // Guardado en memoria: los escenarios lo inspeccionan en __mock.savedSnapshot. + if (storageConfig.mode === "cloud") { + cloudSaved = { version: 1, workspaces: args.workspaces }; + } else { + localSaved = { version: 1, workspaces: args.workspaces }; + } + return null; + case "storage_config_get": + return { ...storageConfig }; + case "storage_config_set": { + // Migrar local → cloud (S4, A4): sube los workspaces locales uno por + // uno sin borrar los que ya tenía la nube y conserva `localSaved`. + if ( + storageConfig.onboardingComplete && + storageConfig.mode === "local" && + args.mode === "cloud" + ) { + if (new URLSearchParams(location.search).get("mockMigrateError") === "1") { + throw new Error("falló la migración local a cloud (e2e)"); + } + if (localSaved?.workspaces?.length) { + const existing = cloudSaved?.workspaces + ? JSON.parse(JSON.stringify(cloudSaved.workspaces)) + : []; + for (const ws of JSON.parse(JSON.stringify(localSaved.workspaces))) { + const idx = existing.findIndex((item) => item.id === ws.id); + if (idx >= 0) existing[idx] = ws; + else existing.push(ws); + } + cloudSaved = { version: 1, workspaces: existing }; + } + } + storageConfig = { + version: 1, + mode: args.mode, + apiBaseUrl: args.apiBaseUrl, + onboardingComplete: true, + }; + if (args.mode === "local") { + emit("collab-status", { connected: false, syncMs: null, collaborators: 1 }); + } + return { ...storageConfig }; + } case "collab_status": // Como el núcleo sin relay: desconectado, sin latencia, solo el usuario local. return { connected: false, syncMs: null, collaborators: 1 }; @@ -97,11 +213,13 @@ export function installTauriMock() { // Como el núcleo: guarda el verifier y abre la web (acá solo devuelve la URL). return `http://localhost:1421/login?client=desktop&code_challenge=${args.challenge}`; case "auth_finish": - return { id: "u1", username: "tester", email: null, displayName: "Tester" }; + signedIn = true; + return user; case "auth_status": // Sin sesión: anónimo (los E2E emiten `auth-changed` para simular el login). - return null; + return signedIn ? user : null; case "auth_logout": + signOut(); return null; case "git_branch": return branches[args.path] ?? null; diff --git a/apps/desktop/package.json b/apps/desktop/package.json index 3b088c1..29fd40f 100644 --- a/apps/desktop/package.json +++ b/apps/desktop/package.json @@ -1,11 +1,12 @@ { - "name": "opencollab-desktop", + "name": "@opencollab/desktop", "private": true, - "version": "0.3.0", + "version": "0.4.0", "type": "module", - "packageManager": "pnpm@11.1.1", "scripts": { - "dev": "vite", + "dev": "tauri dev -c src-tauri/tauri.dev.conf.json", + "dev:vite": "vite", + "dev:desktop": "tauri dev -c src-tauri/tauri.dev.conf.json", "build": "tsc --noEmit && vite build", "preview": "vite preview", "test": "vitest run", @@ -18,6 +19,7 @@ "@tauri-apps/plugin-deep-link": "^2.6.1", "@xterm/addon-fit": "^0.11.0", "@xterm/xterm": "^6.0.0", + "@opencollab/ui": "workspace:*", "react": "^19.3.0", "react-dom": "^19.3.0", "react-icons": "^5.7.0" diff --git a/apps/desktop/pnpm-lock.yaml b/apps/desktop/pnpm-lock.yaml deleted file mode 100644 index 3d7e68b..0000000 --- a/apps/desktop/pnpm-lock.yaml +++ /dev/null @@ -1,1305 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: - dependencies: - '@fontsource-variable/google-sans': - specifier: ^5.3.1 - version: 5.3.1 - '@tauri-apps/api': - specifier: ^2.12.1 - version: 2.12.1 - '@tauri-apps/plugin-deep-link': - specifier: ^2.6.1 - version: 2.6.1 - '@xterm/addon-fit': - specifier: ^0.11.0 - version: 0.11.0 - '@xterm/xterm': - specifier: ^6.0.0 - version: 6.0.0 - react: - specifier: ^19.3.0 - version: 19.3.0 - react-dom: - specifier: ^19.3.0 - version: 19.3.0(react@19.3.0) - react-icons: - specifier: ^5.7.0 - version: 5.7.0(react@19.3.0) - devDependencies: - '@tauri-apps/cli': - specifier: ^2.12.1 - version: 2.12.1 - '@types/react': - specifier: ^19.3.0 - version: 19.3.0 - '@types/react-dom': - specifier: ^19.3.0 - version: 19.3.0(@types/react@19.3.0) - '@vitejs/plugin-react': - specifier: ^6.1.1 - version: 6.1.1(vite@8.3.2) - puppeteer-core: - specifier: ^25.12.0 - version: 25.12.0 - typescript: - specifier: ^7.0.2 - version: 7.0.2 - vite: - specifier: ^8.3.2 - version: 8.3.2 - vitest: - specifier: ^5.0.3 - version: 5.0.3(vite@8.3.2) - -packages: - - '@fontsource-variable/google-sans@5.3.1': - resolution: {integrity: sha512-FLB6ZktdAtYWj49W6TtmqThHb33XL5g8l6T+oKNcvmNUXou4PPdIkstt1Z/UyD6K+g/CYjiHF+j+eRMNZxYKZg==} - - '@jridgewell/resolve-uri@3.1.2': - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - - '@jridgewell/sourcemap-codec@1.6.0': - resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} - - '@jridgewell/trace-mapping@0.3.31': - resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - - '@oxc-project/types@0.152.0': - resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==} - - '@puppeteer/browsers@3.2.3': - resolution: {integrity: sha512-2Bt3m6dDAJqmZehn0wiXSYyQmuhyiHHZ7FjvrVaS1W2RoFGV6eCK71UvKYkNJjkwC1Q9nobjhvTMhLQztFVINA==} - engines: {node: '>=22.12.0'} - hasBin: true - peerDependencies: - proxy-agent: '>=8.0.1' - yauzl: ^2.10.0 || ^3.4.0 - peerDependenciesMeta: - proxy-agent: - optional: true - yauzl: - optional: true - - '@rolldown/binding-android-arm-eabi@1.2.12': - resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [android] - - '@rolldown/binding-android-arm64@1.2.12': - resolution: {integrity: sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@rolldown/binding-darwin-arm64@1.2.12': - resolution: {integrity: sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@rolldown/binding-darwin-x64@1.2.12': - resolution: {integrity: sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@rolldown/binding-freebsd-x64@1.2.12': - resolution: {integrity: sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@rolldown/binding-linux-arm-gnueabihf@1.2.12': - resolution: {integrity: sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@rolldown/binding-linux-arm64-gnu@1.2.12': - resolution: {integrity: sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-arm64-musl@1.2.12': - resolution: {integrity: sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@rolldown/binding-linux-ppc64-gnu@1.2.12': - resolution: {integrity: sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-s390x-gnu@1.2.12': - resolution: {integrity: sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-gnu@1.2.12': - resolution: {integrity: sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-musl@1.2.12': - resolution: {integrity: sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@rolldown/binding-openharmony-arm64@1.2.12': - resolution: {integrity: sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - - '@rolldown/binding-win32-arm64-msvc@1.2.12': - resolution: {integrity: sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - - '@rolldown/binding-win32-x64-msvc@1.2.12': - resolution: {integrity: sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - - '@rolldown/pluginutils@1.0.1': - resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - - '@tauri-apps/api@2.12.1': - resolution: {integrity: sha512-DeyFHa3wynpyoqTDikDEDGTJIq4LQ5USfolQGRmGIWT6JMADyxZBTDa5cAdT3tDg73rUXufPaCwN7aXBos4OnQ==} - - '@tauri-apps/cli-darwin-arm64@2.12.1': - resolution: {integrity: sha512-8bMnbpJ2jKO/ufrOPL65EMHC3ptw7fzeraoQkwibyfGLqIl+UCWsC0152kmNbW6r9NvVQduXqAZF5mH1QgTWhw==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [darwin] - - '@tauri-apps/cli-darwin-x64@2.12.1': - resolution: {integrity: sha512-G+2qte8GNqNlEZ9ftd21rbu/APVkl3r/nzNDI7LVxEoqJWVNe9GbEgQUMH1r4PHT20Z2UxR3KjCkltIb0e/Wjg==} - engines: {node: '>= 10'} - cpu: [x64] - os: [darwin] - - '@tauri-apps/cli-linux-arm-gnueabihf@2.12.1': - resolution: {integrity: sha512-5b3n4DaTW+A1Zntnh4Yn44VyLrlPEpB8kMOBRfWkzNnzolBk+AYhKIfKjCLmoC8Mob3ETodxAEOMkE2YPKEWzQ==} - engines: {node: '>= 10'} - cpu: [arm] - os: [linux] - - '@tauri-apps/cli-linux-arm64-gnu@2.12.1': - resolution: {integrity: sha512-APArHhDu+8pXSCkCQmvaz1nD3d8WTmlCoSS/oG475TJ6AATBvyQOAmf5qELgsQ4s2+8MOsop0Zd699RKELF1Cw==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@tauri-apps/cli-linux-arm64-musl@2.12.1': - resolution: {integrity: sha512-JaCxcLoV0oGtllVkLr4UAHWG/wTfkEunnUqnsEsGYOp0VRxnUwHg63wFBD0jU2ul5eFfSLIDS4RF2gfzsSo5Jg==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@tauri-apps/cli-linux-riscv64-gnu@2.12.1': - resolution: {integrity: sha512-K5+VXM7+SGVDwZleA2+lMgvbTVuA5e1tkiVEawu1Yxj26ZyEfO8h8xTC1rBdRX2xgJDSwCk6vPUBCS6i+Z5slQ==} - engines: {node: '>= 10'} - cpu: [riscv64] - os: [linux] - libc: [glibc] - - '@tauri-apps/cli-linux-x64-gnu@2.12.1': - resolution: {integrity: sha512-Z1QGPr49HJZMktu+Spu6Q1b/f9ANadXvqZZZt2645ua1x1ev6prOgp85eiGv2jRzohFEMLo6aJyaLjLUX5KIvA==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@tauri-apps/cli-linux-x64-musl@2.12.1': - resolution: {integrity: sha512-nHuEhRPOMSJ/8RRhtMRxB9B9lVr7xxpe4DapBz8x1GIau3vdzjHHJ1hAfmw+PyayPLZ6XoaVIHPgI17rX6ii8w==} - engines: {node: '>= 10'} - cpu: [x64] - os: [linux] - libc: [musl] - - '@tauri-apps/cli-win32-arm64-msvc@2.12.1': - resolution: {integrity: sha512-I0oPk2uGh86R8dAs2X5OxSP+/GqSc8jh1Px3l8EqrocSNivsRHDTh2k3PVOqdv163dlV6PIVvmhZAbH/lPfZrA==} - engines: {node: '>= 10'} - cpu: [arm64] - os: [win32] - - '@tauri-apps/cli-win32-ia32-msvc@2.12.1': - resolution: {integrity: sha512-baNZRBfepAJ5qNFRMwzgBk94xQmkcmTZrNDjZjnzrq2vAaTC3NAhallb/zo3hyoCGQlMS13sdovktrg46NZz6Q==} - engines: {node: '>= 10'} - cpu: [ia32] - os: [win32] - - '@tauri-apps/cli-win32-x64-msvc@2.12.1': - resolution: {integrity: sha512-dIFaKslrzcbesb+bBh+E1R9km241pHyj32w6D9FPtvQeYpRUFbiCLEa/2S+S0UnIytfxepp4P+X8IerGqnXeYg==} - engines: {node: '>= 10'} - cpu: [x64] - os: [win32] - - '@tauri-apps/cli@2.12.1': - resolution: {integrity: sha512-kEDEiGzG+yAc5FeLxtXpES/VN+F2C8H0r4gDVtfRLKxT9np9101d9REG/Kgo2lr0hKi0IpDsODiHnU3+naOmLg==} - engines: {node: '>= 10'} - hasBin: true - - '@tauri-apps/plugin-deep-link@2.6.1': - resolution: {integrity: sha512-yomIOIoiiDwXW3Bgy/V5c4frWo9sfWM9WZQew2s7vr7hXtDdbLDCLzvytIMCjMxbnln9O0oJsTI3XdDd2T9XlA==} - - '@types/chai@5.2.3': - resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} - - '@types/deep-eql@4.0.2': - resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} - - '@types/estree@1.0.9': - resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} - - '@types/react-dom@19.3.0': - resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} - peerDependencies: - '@types/react': ^19.3.0 - - '@types/react@19.3.0': - resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} - - '@typescript/typescript-aix-ppc64@7.0.2': - resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} - engines: {node: '>=16.20.0'} - cpu: [ppc64] - os: [aix] - - '@typescript/typescript-darwin-arm64@7.0.2': - resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [darwin] - - '@typescript/typescript-darwin-x64@7.0.2': - resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [darwin] - - '@typescript/typescript-freebsd-arm64@7.0.2': - resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [freebsd] - - '@typescript/typescript-freebsd-x64@7.0.2': - resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [freebsd] - - '@typescript/typescript-linux-arm64@7.0.2': - resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [linux] - - '@typescript/typescript-linux-arm@7.0.2': - resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} - engines: {node: '>=16.20.0'} - cpu: [arm] - os: [linux] - - '@typescript/typescript-linux-loong64@7.0.2': - resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} - engines: {node: '>=16.20.0'} - cpu: [loong64] - os: [linux] - - '@typescript/typescript-linux-mips64el@7.0.2': - resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} - engines: {node: '>=16.20.0'} - cpu: [mips64el] - os: [linux] - - '@typescript/typescript-linux-ppc64@7.0.2': - resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} - engines: {node: '>=16.20.0'} - cpu: [ppc64] - os: [linux] - - '@typescript/typescript-linux-riscv64@7.0.2': - resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} - engines: {node: '>=16.20.0'} - cpu: [riscv64] - os: [linux] - - '@typescript/typescript-linux-s390x@7.0.2': - resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} - engines: {node: '>=16.20.0'} - cpu: [s390x] - os: [linux] - - '@typescript/typescript-linux-x64@7.0.2': - resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [linux] - - '@typescript/typescript-netbsd-arm64@7.0.2': - resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [netbsd] - - '@typescript/typescript-netbsd-x64@7.0.2': - resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [netbsd] - - '@typescript/typescript-openbsd-arm64@7.0.2': - resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [openbsd] - - '@typescript/typescript-openbsd-x64@7.0.2': - resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [openbsd] - - '@typescript/typescript-sunos-x64@7.0.2': - resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [sunos] - - '@typescript/typescript-win32-arm64@7.0.2': - resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [win32] - - '@typescript/typescript-win32-x64@7.0.2': - resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [win32] - - '@vitejs/plugin-react@6.1.1': - resolution: {integrity: sha512-yxLaQV9gkhS8ezJqCM6+ndU7mDY6gqAg75NQ+0IjwEI8IYOmQCgkRwHKVSfWXW076DsqMo0Dk+0FK1U+M5RgFw==} - engines: {node: ^20.19.0 || >=22.12.0} - peerDependencies: - '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 - babel-plugin-react-compiler: ^1.0.0 - oxc-transform-react: ^0.145.0 - vite: ^8.0.0 - peerDependenciesMeta: - '@rolldown/plugin-babel': - optional: true - babel-plugin-react-compiler: - optional: true - oxc-transform-react: - optional: true - - '@vitest/mocker@5.0.3': - resolution: {integrity: sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==} - peerDependencies: - msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 - peerDependenciesMeta: - msw: - optional: true - vite: - optional: true - - '@vitest/spy@5.0.3': - resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==} - - '@xterm/addon-fit@0.11.0': - resolution: {integrity: sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==} - - '@xterm/xterm@6.0.0': - resolution: {integrity: sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==} - - ansi-regex@6.4.0: - resolution: {integrity: sha512-KzTVk2tCWAHtYrvvvaP8bJKJq2pVinhLcGEQdtLIYPbmNGNyYe8QwNaTUYQp2J7/vIsUKt5QCqAfUkYyG9DkOw==} - engines: {node: '>=12'} - - ansi-styles@6.2.3: - resolution: {integrity: sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==} - engines: {node: '>=12'} - - assertion-error@2.0.1: - resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} - engines: {node: '>=12'} - - chai@6.3.0: - resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} - engines: {node: '>=18'} - - chromium-bidi@17.0.2: - resolution: {integrity: sha512-5v9GQFhTktFvotn/OFNJBmKLKRAb6n9r0bVCwf7sHgWc3/JryK0bj1nn93L3pHFrfgcsu6Be6EWsDi+1XHTGDg==} - engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0'} - peerDependencies: - devtools-protocol: '*' - - cliui@9.0.1: - resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==} - engines: {node: '>=20'} - - csstype@3.2.3: - resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} - - detect-libc@2.1.2: - resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} - engines: {node: '>=8'} - - devtools-protocol@0.0.1687809: - resolution: {integrity: sha512-t7kSb+UKYdyxcmqy98U2P86ne6rCve3DIJ4+lp54i/hhClgFuG35JrLj23rO14Jw3sWDsp7i+22QhNU0+/qk8g==} - - emoji-regex@10.6.0: - resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} - - es-module-lexer@2.3.2: - resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} - - escalade@3.2.0: - resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==} - engines: {node: '>=6'} - - estree-walker@3.0.3: - resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} - - expect-type@1.4.0: - resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} - engines: {node: '>=12.0.0'} - - fdir@6.5.0: - resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} - engines: {node: '>=12.0.0'} - peerDependencies: - picomatch: ^3 || ^4 - peerDependenciesMeta: - picomatch: - optional: true - - fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - - get-caller-file@2.0.5: - resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} - engines: {node: 6.* || 8.* || >= 10.*} - - get-east-asian-width@1.7.0: - resolution: {integrity: sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==} - engines: {node: '>=18'} - - lightningcss-android-arm64@1.33.0: - resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [android] - - lightningcss-darwin-arm64@1.33.0: - resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [darwin] - - lightningcss-darwin-x64@1.33.0: - resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [darwin] - - lightningcss-freebsd-x64@1.33.0: - resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [freebsd] - - lightningcss-linux-arm-gnueabihf@1.33.0: - resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm] - os: [linux] - - lightningcss-linux-arm64-gnu@1.33.0: - resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - lightningcss-linux-arm64-musl@1.33.0: - resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [musl] - - lightningcss-linux-x64-gnu@1.33.0: - resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [glibc] - - lightningcss-linux-x64-musl@1.33.0: - resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [musl] - - lightningcss-win32-arm64-msvc@1.33.0: - resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [win32] - - lightningcss-win32-x64-msvc@1.33.0: - resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [win32] - - lightningcss@1.33.0: - resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} - engines: {node: '>= 12.0.0'} - - magic-string@1.4.2: - resolution: {integrity: sha512-vG+rjFRj1PqdIBozIxAGMjPlOhaVe+GXpbttY/iSK7rGcJRMlwNJO7dcUwmUqkymsFLJiNGI06t4D7Fr7yRC9g==} - - mitt@3.0.1: - resolution: {integrity: sha512-vKivATfr97l2/QBCYAkXYDbrIWPM2IIKEl7YPhjCvKlG3kE2gm+uBo6nEXK3M5/Ffh/FLpKExzOQ3JJoJGFKBw==} - - modern-tar@0.8.5: - resolution: {integrity: sha512-snEhs+6G5Tjd4I7tLCDOaoln2RgE0bD19RzEKgvgK2hZ5VKy3MpLhLTZ2fWpXSTg4K2cyPwp+VHATFJhxfnOeA==} - engines: {node: '>=18.0.0'} - - nanoid@3.3.19: - resolution: {integrity: sha512-Y2tUNy4ouw6tq5oDSKeQYGOyhkUBhNOcGV/02KC+6kd9eDGqdZd++mjMiIDilrBYvjEnCYvVtsuHCuP+okSfug==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - - obug@2.2.1: - resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} - engines: {node: '>=12.20.0'} - - picocolors@1.1.1: - resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - - picomatch@4.0.7: - resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} - engines: {node: '>=12'} - - postcss@8.5.28: - resolution: {integrity: sha512-RRuzqDtt5Y9h3quz5hWhK+TPnsmVs6WwSU6LkJMeY4HstUEDuYTG8UJSdawMRzmzAtV+KEoG8N3Qg2qLy5vM/A==} - engines: {node: ^10 || ^12 || >=14} - - puppeteer-core@25.12.0: - resolution: {integrity: sha512-z6LQUt5SH7jwGtGA+nMtJuEjZIsqPiwQ+EFHCYuVDQrJpvifNmmGuyDvTzAKPyFzihxgHc5f3aMzu2kn8Ps37A==} - engines: {node: '>=22.12.0'} - - react-dom@19.3.0: - resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==} - peerDependencies: - react: ^19.3.0 - - react-icons@5.7.0: - resolution: {integrity: sha512-LBLy340Rzqy6+/yVhZKT3B/QpP1BZaesGqasf09HPOBzRarcDIFH0WwXlXQfE7q7ipxK4MSiC5DIBWURCny6fw==} - peerDependencies: - react: '*' - - react@19.3.0: - resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==} - engines: {node: '>=0.10.0'} - - rolldown@1.2.12: - resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - - scheduler@0.28.0: - resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} - - source-map-js@1.2.2: - resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} - engines: {node: '>=0.10.0'} - - std-env@4.3.0: - resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} - - string-width@7.2.0: - resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} - engines: {node: '>=18'} - - string-width@8.3.0: - resolution: {integrity: sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==} - engines: {node: '>=20'} - - strip-ansi@7.2.0: - resolution: {integrity: sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==} - engines: {node: '>=12'} - - tinybench@6.2.0: - resolution: {integrity: sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==} - engines: {node: '>=20.0.0'} - - tinyexec@1.3.1: - resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} - engines: {node: '>=18'} - - tinyglobby@0.2.17: - resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} - engines: {node: '>=12.0.0'} - - typed-query-selector@2.12.3: - resolution: {integrity: sha512-/dtuMZyutHLlrxWhhC1uib00ELUr2dZ8C9B8YzZYsJmeE3V56OxRblrSM2UaF142pcMtak7ehZ6+poWGeehNIg==} - - typescript@7.0.2: - resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} - engines: {node: '>=16.20.0'} - hasBin: true - - vite@8.3.2: - resolution: {integrity: sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.7.1 - esbuild: ^0.27.0 || ^0.28.0 - jiti: '>=1.21.0' - less: ^4.0.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - '@vitejs/devtools': - optional: true - esbuild: - optional: true - jiti: - optional: true - less: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - - vitest@5.0.3: - resolution: {integrity: sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==} - engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} - hasBin: true - peerDependencies: - '@edge-runtime/vm': '*' - '@opentelemetry/api': ^1.9.0 - '@types/node': ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 5.0.3 - '@vitest/browser-preview': 5.0.3 - '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 - '@vitest/coverage-istanbul': 5.0.3 - '@vitest/coverage-v8': 5.0.3 - '@vitest/ui': 5.0.3 - happy-dom: '*' - jsdom: '*' - vite: ^6.4.0 || ^7.0.0 || ^8.0.0 - peerDependenciesMeta: - '@edge-runtime/vm': - optional: true - '@opentelemetry/api': - optional: true - '@types/node': - optional: true - '@vitest/browser-playwright': - optional: true - '@vitest/browser-preview': - optional: true - '@vitest/browser-webdriverio': - optional: true - '@vitest/coverage-istanbul': - optional: true - '@vitest/coverage-v8': - optional: true - '@vitest/ui': - optional: true - happy-dom: - optional: true - jsdom: - optional: true - - webdriver-bidi-protocol@0.4.3: - resolution: {integrity: sha512-uuN0goWfxP22B7J/uAgBpOYNPttC+XVseYE+rSY5+rQ+YBeVz/VORw8WbmLVcqW78zNg5A4qnjNXYUWR3il2ig==} - - why-is-node-running@3.2.1: - resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} - engines: {node: '>=20.11'} - hasBin: true - - wrap-ansi@9.0.2: - resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==} - engines: {node: '>=18'} - - ws@8.22.0: - resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - - y18n@5.0.8: - resolution: {integrity: sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==} - engines: {node: '>=10'} - - yargs-parser@22.0.0: - resolution: {integrity: sha512-rwu/ClNdSMpkSrUb+d6BRsSkLUq1fmfsY6TOpYzTwvwkg1/NRG85KBy3kq++A8LKQwX6lsu+aWad+2khvuXrqw==} - engines: {node: ^20.19.0 || ^22.12.0 || >=23} - - yargs@18.2.0: - resolution: {integrity: sha512-9OpKOLeaoNFecEp7P6iYbzze/5CqWoH7N3SMs/6y1XF4nMvFMspEGZzJ6uFi9MmQwXhyzqYoSEKO3tvA3Z/o2w==} - engines: {node: ^20.19.0 || ^22.12.0 || >=23} - - zod@3.25.76: - resolution: {integrity: sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ==} - -snapshots: - - '@fontsource-variable/google-sans@5.3.1': {} - - '@jridgewell/resolve-uri@3.1.2': {} - - '@jridgewell/sourcemap-codec@1.6.0': {} - - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.6.0 - - '@oxc-project/types@0.152.0': {} - - '@puppeteer/browsers@3.2.3': - dependencies: - modern-tar: 0.8.5 - yargs: 18.2.0 - - '@rolldown/binding-android-arm-eabi@1.2.12': - optional: true - - '@rolldown/binding-android-arm64@1.2.12': - optional: true - - '@rolldown/binding-darwin-arm64@1.2.12': - optional: true - - '@rolldown/binding-darwin-x64@1.2.12': - optional: true - - '@rolldown/binding-freebsd-x64@1.2.12': - optional: true - - '@rolldown/binding-linux-arm-gnueabihf@1.2.12': - optional: true - - '@rolldown/binding-linux-arm64-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-arm64-musl@1.2.12': - optional: true - - '@rolldown/binding-linux-ppc64-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-s390x-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-x64-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-x64-musl@1.2.12': - optional: true - - '@rolldown/binding-openharmony-arm64@1.2.12': - optional: true - - '@rolldown/binding-win32-arm64-msvc@1.2.12': - optional: true - - '@rolldown/binding-win32-x64-msvc@1.2.12': - optional: true - - '@rolldown/pluginutils@1.0.1': {} - - '@tauri-apps/api@2.12.1': {} - - '@tauri-apps/cli-darwin-arm64@2.12.1': - optional: true - - '@tauri-apps/cli-darwin-x64@2.12.1': - optional: true - - '@tauri-apps/cli-linux-arm-gnueabihf@2.12.1': - optional: true - - '@tauri-apps/cli-linux-arm64-gnu@2.12.1': - optional: true - - '@tauri-apps/cli-linux-arm64-musl@2.12.1': - optional: true - - '@tauri-apps/cli-linux-riscv64-gnu@2.12.1': - optional: true - - '@tauri-apps/cli-linux-x64-gnu@2.12.1': - optional: true - - '@tauri-apps/cli-linux-x64-musl@2.12.1': - optional: true - - '@tauri-apps/cli-win32-arm64-msvc@2.12.1': - optional: true - - '@tauri-apps/cli-win32-ia32-msvc@2.12.1': - optional: true - - '@tauri-apps/cli-win32-x64-msvc@2.12.1': - optional: true - - '@tauri-apps/cli@2.12.1': - optionalDependencies: - '@tauri-apps/cli-darwin-arm64': 2.12.1 - '@tauri-apps/cli-darwin-x64': 2.12.1 - '@tauri-apps/cli-linux-arm-gnueabihf': 2.12.1 - '@tauri-apps/cli-linux-arm64-gnu': 2.12.1 - '@tauri-apps/cli-linux-arm64-musl': 2.12.1 - '@tauri-apps/cli-linux-riscv64-gnu': 2.12.1 - '@tauri-apps/cli-linux-x64-gnu': 2.12.1 - '@tauri-apps/cli-linux-x64-musl': 2.12.1 - '@tauri-apps/cli-win32-arm64-msvc': 2.12.1 - '@tauri-apps/cli-win32-ia32-msvc': 2.12.1 - '@tauri-apps/cli-win32-x64-msvc': 2.12.1 - - '@tauri-apps/plugin-deep-link@2.6.1': - dependencies: - '@tauri-apps/api': 2.12.1 - - '@types/chai@5.2.3': - dependencies: - '@types/deep-eql': 4.0.2 - assertion-error: 2.0.1 - - '@types/deep-eql@4.0.2': {} - - '@types/estree@1.0.9': {} - - '@types/react-dom@19.3.0(@types/react@19.3.0)': - dependencies: - '@types/react': 19.3.0 - - '@types/react@19.3.0': - dependencies: - csstype: 3.2.3 - - '@typescript/typescript-aix-ppc64@7.0.2': - optional: true - - '@typescript/typescript-darwin-arm64@7.0.2': - optional: true - - '@typescript/typescript-darwin-x64@7.0.2': - optional: true - - '@typescript/typescript-freebsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-freebsd-x64@7.0.2': - optional: true - - '@typescript/typescript-linux-arm64@7.0.2': - optional: true - - '@typescript/typescript-linux-arm@7.0.2': - optional: true - - '@typescript/typescript-linux-loong64@7.0.2': - optional: true - - '@typescript/typescript-linux-mips64el@7.0.2': - optional: true - - '@typescript/typescript-linux-ppc64@7.0.2': - optional: true - - '@typescript/typescript-linux-riscv64@7.0.2': - optional: true - - '@typescript/typescript-linux-s390x@7.0.2': - optional: true - - '@typescript/typescript-linux-x64@7.0.2': - optional: true - - '@typescript/typescript-netbsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-netbsd-x64@7.0.2': - optional: true - - '@typescript/typescript-openbsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-openbsd-x64@7.0.2': - optional: true - - '@typescript/typescript-sunos-x64@7.0.2': - optional: true - - '@typescript/typescript-win32-arm64@7.0.2': - optional: true - - '@typescript/typescript-win32-x64@7.0.2': - optional: true - - '@vitejs/plugin-react@6.1.1(vite@8.3.2)': - dependencies: - '@rolldown/pluginutils': 1.0.1 - vite: 8.3.2 - - '@vitest/mocker@5.0.3(vite@8.3.2)': - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - '@vitest/spy': 5.0.3 - estree-walker: 3.0.3 - magic-string: 1.4.2 - optionalDependencies: - vite: 8.3.2 - - '@vitest/spy@5.0.3': {} - - '@xterm/addon-fit@0.11.0': {} - - '@xterm/xterm@6.0.0': {} - - ansi-regex@6.4.0: {} - - ansi-styles@6.2.3: {} - - assertion-error@2.0.1: {} - - chai@6.3.0: {} - - chromium-bidi@17.0.2(devtools-protocol@0.0.1687809): - dependencies: - devtools-protocol: 0.0.1687809 - mitt: 3.0.1 - zod: 3.25.76 - - cliui@9.0.1: - dependencies: - string-width: 7.2.0 - strip-ansi: 7.2.0 - wrap-ansi: 9.0.2 - - csstype@3.2.3: {} - - detect-libc@2.1.2: {} - - devtools-protocol@0.0.1687809: {} - - emoji-regex@10.6.0: {} - - es-module-lexer@2.3.2: {} - - escalade@3.2.0: {} - - estree-walker@3.0.3: - dependencies: - '@types/estree': 1.0.9 - - expect-type@1.4.0: {} - - fdir@6.5.0(picomatch@4.0.7): - optionalDependencies: - picomatch: 4.0.7 - - fsevents@2.3.3: - optional: true - - get-caller-file@2.0.5: {} - - get-east-asian-width@1.7.0: {} - - lightningcss-android-arm64@1.33.0: - optional: true - - lightningcss-darwin-arm64@1.33.0: - optional: true - - lightningcss-darwin-x64@1.33.0: - optional: true - - lightningcss-freebsd-x64@1.33.0: - optional: true - - lightningcss-linux-arm-gnueabihf@1.33.0: - optional: true - - lightningcss-linux-arm64-gnu@1.33.0: - optional: true - - lightningcss-linux-arm64-musl@1.33.0: - optional: true - - lightningcss-linux-x64-gnu@1.33.0: - optional: true - - lightningcss-linux-x64-musl@1.33.0: - optional: true - - lightningcss-win32-arm64-msvc@1.33.0: - optional: true - - lightningcss-win32-x64-msvc@1.33.0: - optional: true - - lightningcss@1.33.0: - dependencies: - detect-libc: 2.1.2 - optionalDependencies: - lightningcss-android-arm64: 1.33.0 - lightningcss-darwin-arm64: 1.33.0 - lightningcss-darwin-x64: 1.33.0 - lightningcss-freebsd-x64: 1.33.0 - lightningcss-linux-arm-gnueabihf: 1.33.0 - lightningcss-linux-arm64-gnu: 1.33.0 - lightningcss-linux-arm64-musl: 1.33.0 - lightningcss-linux-x64-gnu: 1.33.0 - lightningcss-linux-x64-musl: 1.33.0 - lightningcss-win32-arm64-msvc: 1.33.0 - lightningcss-win32-x64-msvc: 1.33.0 - - magic-string@1.4.2: - dependencies: - '@jridgewell/sourcemap-codec': 1.6.0 - - mitt@3.0.1: {} - - modern-tar@0.8.5: {} - - nanoid@3.3.19: {} - - obug@2.2.1: {} - - picocolors@1.1.1: {} - - picomatch@4.0.7: {} - - postcss@8.5.28: - dependencies: - nanoid: 3.3.19 - picocolors: 1.1.1 - source-map-js: 1.2.2 - - puppeteer-core@25.12.0: - dependencies: - '@puppeteer/browsers': 3.2.3 - chromium-bidi: 17.0.2(devtools-protocol@0.0.1687809) - devtools-protocol: 0.0.1687809 - typed-query-selector: 2.12.3 - webdriver-bidi-protocol: 0.4.3 - ws: 8.22.0 - transitivePeerDependencies: - - bufferutil - - proxy-agent - - utf-8-validate - - yauzl - - react-dom@19.3.0(react@19.3.0): - dependencies: - react: 19.3.0 - scheduler: 0.28.0 - - react-icons@5.7.0(react@19.3.0): - dependencies: - react: 19.3.0 - - react@19.3.0: {} - - rolldown@1.2.12: - dependencies: - '@oxc-project/types': 0.152.0 - '@rolldown/pluginutils': 1.0.1 - optionalDependencies: - '@rolldown/binding-android-arm-eabi': 1.2.12 - '@rolldown/binding-android-arm64': 1.2.12 - '@rolldown/binding-darwin-arm64': 1.2.12 - '@rolldown/binding-darwin-x64': 1.2.12 - '@rolldown/binding-freebsd-x64': 1.2.12 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.12 - '@rolldown/binding-linux-arm64-gnu': 1.2.12 - '@rolldown/binding-linux-arm64-musl': 1.2.12 - '@rolldown/binding-linux-ppc64-gnu': 1.2.12 - '@rolldown/binding-linux-s390x-gnu': 1.2.12 - '@rolldown/binding-linux-x64-gnu': 1.2.12 - '@rolldown/binding-linux-x64-musl': 1.2.12 - '@rolldown/binding-openharmony-arm64': 1.2.12 - '@rolldown/binding-win32-arm64-msvc': 1.2.12 - '@rolldown/binding-win32-x64-msvc': 1.2.12 - - scheduler@0.28.0: {} - - source-map-js@1.2.2: {} - - std-env@4.3.0: {} - - string-width@7.2.0: - dependencies: - emoji-regex: 10.6.0 - get-east-asian-width: 1.7.0 - strip-ansi: 7.2.0 - - string-width@8.3.0: - dependencies: - get-east-asian-width: 1.7.0 - strip-ansi: 7.2.0 - - strip-ansi@7.2.0: - dependencies: - ansi-regex: 6.4.0 - - tinybench@6.2.0: {} - - tinyexec@1.3.1: {} - - tinyglobby@0.2.17: - dependencies: - fdir: 6.5.0(picomatch@4.0.7) - picomatch: 4.0.7 - - typed-query-selector@2.12.3: {} - - typescript@7.0.2: - optionalDependencies: - '@typescript/typescript-aix-ppc64': 7.0.2 - '@typescript/typescript-darwin-arm64': 7.0.2 - '@typescript/typescript-darwin-x64': 7.0.2 - '@typescript/typescript-freebsd-arm64': 7.0.2 - '@typescript/typescript-freebsd-x64': 7.0.2 - '@typescript/typescript-linux-arm': 7.0.2 - '@typescript/typescript-linux-arm64': 7.0.2 - '@typescript/typescript-linux-loong64': 7.0.2 - '@typescript/typescript-linux-mips64el': 7.0.2 - '@typescript/typescript-linux-ppc64': 7.0.2 - '@typescript/typescript-linux-riscv64': 7.0.2 - '@typescript/typescript-linux-s390x': 7.0.2 - '@typescript/typescript-linux-x64': 7.0.2 - '@typescript/typescript-netbsd-arm64': 7.0.2 - '@typescript/typescript-netbsd-x64': 7.0.2 - '@typescript/typescript-openbsd-arm64': 7.0.2 - '@typescript/typescript-openbsd-x64': 7.0.2 - '@typescript/typescript-sunos-x64': 7.0.2 - '@typescript/typescript-win32-arm64': 7.0.2 - '@typescript/typescript-win32-x64': 7.0.2 - - vite@8.3.2: - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.7 - postcss: 8.5.28 - rolldown: 1.2.12 - tinyglobby: 0.2.17 - optionalDependencies: - fsevents: 2.3.3 - - vitest@5.0.3(vite@8.3.2): - dependencies: - '@types/chai': 5.2.3 - '@vitest/mocker': 5.0.3(vite@8.3.2) - chai: 6.3.0 - es-module-lexer: 2.3.2 - expect-type: 1.4.0 - magic-string: 1.4.2 - obug: 2.2.1 - picomatch: 4.0.7 - std-env: 4.3.0 - tinybench: 6.2.0 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 - vite: 8.3.2 - why-is-node-running: 3.2.1 - transitivePeerDependencies: - - msw - - webdriver-bidi-protocol@0.4.3: {} - - why-is-node-running@3.2.1: {} - - wrap-ansi@9.0.2: - dependencies: - ansi-styles: 6.2.3 - string-width: 7.2.0 - strip-ansi: 7.2.0 - - ws@8.22.0: {} - - y18n@5.0.8: {} - - yargs-parser@22.0.0: {} - - yargs@18.2.0: - dependencies: - cliui: 9.0.1 - escalade: 3.2.0 - get-caller-file: 2.0.5 - string-width: 8.3.0 - y18n: 5.0.8 - yargs-parser: 22.0.0 - - zod@3.25.76: {} diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.toml index 85364dd..f572f9d 100644 --- a/apps/desktop/src-tauri/Cargo.toml +++ b/apps/desktop/src-tauri/Cargo.toml @@ -17,5 +17,6 @@ protocol.workspace = true tauri.workspace = true tauri-plugin-deep-link = "2" tauri-plugin-single-instance = { version = "2", features = ["deep-link"] } +keyring.workspace = true serde.workspace = true serde_json.workspace = true diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rs index c89b437..b0262b6 100644 --- a/apps/desktop/src-tauri/src/auth.rs +++ b/apps/desktop/src-tauri/src/auth.rs @@ -7,15 +7,19 @@ //! app. El frontend extrae el `code` y llama `auth_finish`, que lo canjea en //! `POST /auth/desktop/token`. //! -//! Los tokens viven **solo en la memoria del núcleo**; el frontend recibe el +//! El `access_token` de corta vida vive **solo en la memoria del núcleo** y el +//! `refresh_token` junto al usuario se persisten en el llavero seguro del +//! sistema operativo (`keyring`: Windows Credential Manager / macOS Keychain / +//! Linux Secret Service) siguiendo RFC 8252. El frontend recibe únicamente el //! usuario y el evento `auth-changed`. El HTTP va con `std::net`, sin runtime //! async (como `HttpRelayProbe`): el relay escucha en HTTP local sin TLS. use std::io::{Read, Write}; use std::net::{TcpStream, ToSocketAddrs}; -use std::sync::Mutex; +use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; +use application::ports::{AccessTokenProvider, PortError}; use serde::{Deserialize, Serialize}; use tauri::{AppHandle, Emitter, State}; @@ -74,42 +78,334 @@ struct Session { user: UserView, } +/// Datos de la sesión que se persisten en el llavero del sistema operativo +/// (RFC 8252: el `access_token` de corta vida nunca sale de la memoria RAM). +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PersistedSession { + pub refresh_token: String, + pub user: UserView, +} + +/// Puerto de almacenamiento seguro para la sesión de larga vida (`refresh_token` + usuario). +pub trait SessionVault: Send + Sync { + fn load(&self) -> Option; + fn save(&self, session: &PersistedSession); + fn clear(&self); +} + +struct NoopVault; + +impl SessionVault for NoopVault { + fn load(&self) -> Option { + None + } + fn save(&self, _session: &PersistedSession) {} + fn clear(&self) {} +} + +const KEYRING_USER: &str = "session"; + +/// Implementación de `SessionVault` sobre el almacén nativo de credenciales del SO. +struct KeyringVault { + service: &'static str, +} + +impl KeyringVault { + fn new(service: &'static str) -> Self { + Self { service } + } + + fn entry(&self) -> Result { + keyring::Entry::new(self.service, KEYRING_USER) + } +} + +impl SessionVault for KeyringVault { + fn load(&self) -> Option { + let raw = self.entry().ok()?.get_password().ok()?; + let persisted: PersistedSession = serde_json::from_str(&raw).ok()?; + if persisted.refresh_token.is_empty() || persisted.user.id.is_empty() { + return None; + } + Some(persisted) + } + + fn save(&self, session: &PersistedSession) { + let Ok(raw) = serde_json::to_string(session) else { + return; + }; + if let Ok(entry) = self.entry() { + let _ = entry.set_password(&raw); + } + } + + fn clear(&self) { + if let Ok(entry) = self.entry() { + let _ = entry.delete_credential(); + } + } +} + struct Inner { verifier: Option, session: Option, } -/// Sesión del desktop: dirección del relay, origen de la web y estado mutable -/// (verifier pendiente + tokens). Todo queda en memoria del proceso. +/// Resultado de consultar/renovar la sesión. `Fresh` no toca la red; `Refreshed` +/// ya actualizó el par de tokens; `Rejected` cerró la sesión (el relay rechazó +/// el refresh); `Malformed` conserva la sesión (respuesta ilegible o fallo transitorio). +enum RefreshOutcome { + Fresh { + user: UserView, + access_token: String, + }, + Refreshed { + user: UserView, + access_token: String, + }, + NoSession, + Rejected, + Malformed, +} + +/// Sesión del desktop: dirección del relay, origen de la web, llavero y estado +/// mutable (`access_token` y verifier PKCE solo en memoria; `refresh_token` en el llavero). pub struct AuthStore { api_addr: String, web_origin: String, + client: &'static str, + vault: Arc, inner: Mutex, + /// Serializa los refresh: si dos pedidos reciben 401 a la vez, el segundo + /// espera y reutiliza el token que renovó el primero. + refresh_lock: Mutex<()>, } impl AuthStore { pub fn new(api_addr: String) -> Self { - let web_origin = std::env::var("OPENCOLLAB_WEB_ORIGIN") - .ok() - .filter(|origin| is_http_origin(origin)) - .unwrap_or_else(|| DEFAULT_WEB_ORIGIN.to_string()); + let web_origin = resolve_web_origin(|k| std::env::var(k)); Self { api_addr, web_origin, + client: "desktop", + vault: Arc::new(NoopVault), inner: Mutex::new(Inner { verifier: None, session: None, }), + refresh_lock: Mutex::new(()), + } + } + + /// Selecciona el identificador de cliente enviado a `/login` (`desktop-dev` + /// cuando la app corre bajo el perfil `com.opencollab.desktop.dev`, para que la + /// web devuelva el esquema aislado `opencollab-dev://`). + pub fn with_dev_client(mut self, is_dev: bool) -> Self { + self.client = if is_dev { "desktop-dev" } else { "desktop" }; + self + } + + /// Nombre del servicio en el llavero del SO (`opencollab` en producción y + /// `opencollab-dev` en desarrollo, igual que el esquema del deep link), + /// aislado para que sus rotaciones de `refresh_token` no se pisen mutuamente. + pub fn keyring_service(&self) -> &'static str { + if self.client == "desktop-dev" { + "opencollab-dev" + } else { + "opencollab" + } + } + + /// Conecta el llavero nativo del sistema operativo e hidrata la sesión si existe. + pub fn with_os_keyring(self) -> Self { + let service = self.keyring_service(); + self.with_vault(Arc::new(KeyringVault::new(service))) + } + + /// Conecta un `SessionVault` (llavero real o doble de pruebas) e hidrata la + /// sesión guardada con `access_token` vacío y vencimiento inmediato para que + /// el primer pedido o `auth_status` rote el `refresh_token` contra el relay. + pub fn with_vault(mut self, vault: Arc) -> Self { + if let Some(persisted) = vault.load() { + if !persisted.refresh_token.is_empty() { + self.inner.lock().expect("auth").session = Some(Session { + access_token: String::new(), + refresh_token: persisted.refresh_token, + expires_at: Instant::now(), + user: persisted.user, + }); + } } + self.vault = vault; + self + } + + /// Elimina la sesión de la memoria y del llavero, devolviendo el `refresh_token` + /// vigente para avisar al relay en `/auth/logout`. + pub fn clear_session(&self) -> Option { + let refresh_token = self + .inner + .lock() + .expect("auth") + .session + .take() + .map(|session| session.refresh_token); + self.vault.clear(); + refresh_token + } + + /// Hay una sesión en memoria (puede estar vencida: el refresh lo decide + /// el pedido). El modo nube exige al menos esto para configurarse. + pub fn has_session(&self) -> bool { + self.inner.lock().expect("auth").session.is_some() } /// URL de la web donde el usuario hace el login para esta máquina. pub fn login_url(&self, challenge: &str) -> String { format!( - "{}/login?client=desktop&code_challenge={challenge}", - self.web_origin + "{}/login?client={}&code_challenge={challenge}", + self.web_origin, self.client ) } + + /// Token para un pedido a la API: si el access venció o está por vencer, + /// renueva el par antes de devolverlo. Sin sesión (o refresh rechazado) es + /// un error: el modo nube nunca manda un pedido sin credencial. + pub fn access_token_for_request(&self) -> Result { + match self.refresh_now(false, None) { + RefreshOutcome::Fresh { access_token, .. } + | RefreshOutcome::Refreshed { access_token, .. } => Ok(access_token), + RefreshOutcome::NoSession | RefreshOutcome::Rejected => { + Err("no hay sesión iniciada".to_string()) + } + RefreshOutcome::Malformed => Err("respuesta del relay inválida".to_string()), + } + } + + /// Igual que `access_token_for_request`, pero fuerza el refresh si el + /// token rechazado sigue siendo el vigente. Si otro pedido ya renovó + /// (`rejected` quedó viejo), devuelve el token nuevo sin otra red. + pub fn refreshed_access_token_for_request(&self, rejected: &str) -> Result { + match self.refresh_now(true, Some(rejected)) { + RefreshOutcome::Fresh { access_token, .. } + | RefreshOutcome::Refreshed { access_token, .. } => Ok(access_token), + RefreshOutcome::NoSession | RefreshOutcome::Rejected => { + Err("no hay sesión iniciada".to_string()) + } + RefreshOutcome::Malformed => Err("respuesta del relay inválida".to_string()), + } + } + + /// Estado de la sesión y, si corresponde, refresh contra el relay. Es la + /// única implementación del refresh: la comparten `auth_status` y el + /// proveedor de tokens del modo nube. + fn refresh_now(&self, force: bool, rejected: Option<&str>) -> RefreshOutcome { + let _refresh = self.refresh_lock.lock().expect("refresh lock"); + let refresh_token = { + let inner = self.inner.lock().expect("auth"); + let Some(session) = inner.session.as_ref() else { + return RefreshOutcome::NoSession; + }; + if let Some(rejected) = rejected { + if !session.access_token.is_empty() && session.access_token != rejected { + return RefreshOutcome::Fresh { + user: session.user.clone(), + access_token: session.access_token.clone(), + }; + } + } + if !force + && !session.access_token.is_empty() + && session.expires_at.saturating_duration_since(Instant::now()) > REFRESH_MARGIN + { + return RefreshOutcome::Fresh { + user: session.user.clone(), + access_token: session.access_token.clone(), + }; + } + session.refresh_token.clone() + }; + let body = format!("{{\"refreshToken\":\"{}\"}}", json_escape(&refresh_token)); + match post_json(self, "/auth/refresh", &body) { + Ok((200, raw)) => match serde_json::from_slice::(&raw) { + Ok(pair) => { + let (outcome, persisted) = { + let mut inner = self.inner.lock().expect("auth"); + let Some(session) = inner.session.as_mut() else { + return RefreshOutcome::NoSession; + }; + session.access_token = pair.access_token; + session.refresh_token = pair.refresh_token; + session.expires_at = Instant::now() + Duration::from_secs(pair.expires_in); + let persisted = PersistedSession { + refresh_token: session.refresh_token.clone(), + user: session.user.clone(), + }; + ( + RefreshOutcome::Refreshed { + user: session.user.clone(), + access_token: session.access_token.clone(), + }, + persisted, + ) + }; + self.vault.save(&persisted); + outcome + } + Err(_) => RefreshOutcome::Malformed, + }, + Ok((400 | 401 | 403, _)) => { + let should_clear = { + let mut inner = self.inner.lock().expect("auth"); + if inner + .session + .as_ref() + .is_some_and(|s| s.refresh_token == refresh_token) + { + inner.session = None; + true + } else { + false + } + }; + if should_clear { + self.vault.clear(); + } + RefreshOutcome::Rejected + } + // Fallos de red (`Err`) o errores transitorios del servidor (`5xx`, `429`): + // se preserva la sesión en memoria y en el llavero para no desloguear al + // usuario cuando el relay local todavía está arrancando o hay microcortes. + _ => RefreshOutcome::Malformed, + } + } +} + +impl AccessTokenProvider for AuthStore { + fn access_token(&self) -> Result { + self.access_token_for_request().map_err(PortError::new) + } + + fn refreshed_access_token(&self, rejected: &str) -> Result { + self.refreshed_access_token_for_request(rejected) + .map_err(PortError::new) + } +} + +/// Resuelve el origen de la web para el login: +/// 1. `OPENCOLLAB_WEB_ORIGIN` (override específico para el desktop). +/// 2. `WEB_ORIGIN` (variable general del monorepo / .env). +/// 3. `DEFAULT_WEB_ORIGIN` ("http://localhost:1421"). +pub fn resolve_web_origin(var_getter: F) -> String +where + F: Fn(&str) -> Result, +{ + var_getter("OPENCOLLAB_WEB_ORIGIN") + .or_else(|_| var_getter("WEB_ORIGIN")) + .ok() + .filter(|origin| is_http_origin(origin)) + .unwrap_or_else(|| DEFAULT_WEB_ORIGIN.to_string()) } /// Solo un origen `http(s)` sin ruta, para no redirigir al navegador a otro lado. @@ -147,10 +443,13 @@ fn is_valid_code(value: &str) -> bool { .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') } -/// `code` del deep link `opencollab://auth/callback?code=…`; `None` si la URL no -/// es un callback de login (nunca confiar en un deep link con otra forma). +/// `code` del deep link `opencollab://auth/callback?code=…` (o +/// `opencollab-dev://auth/callback?code=…` en dev); `None` si la URL no es un +/// callback de login (nunca confiar en un deep link con otra forma). pub fn parse_callback_code(url: &str) -> Option { - let rest = url.strip_prefix("opencollab://")?; + let rest = url + .strip_prefix("opencollab://") + .or_else(|| url.strip_prefix("opencollab-dev://"))?; let (path, query) = rest.split_once('?')?; if path != "auth/callback" { return None; @@ -269,6 +568,10 @@ fn emit_changed(app: &AppHandle, user: Option) { } fn adopt_session(store: &AuthStore, result: AuthResultBody) -> UserView { + let persisted = PersistedSession { + refresh_token: result.refresh_token.clone(), + user: result.user.clone(), + }; let session = Session { access_token: result.access_token, refresh_token: result.refresh_token, @@ -276,6 +579,7 @@ fn adopt_session(store: &AuthStore, result: AuthResultBody) -> UserView { user: result.user.clone(), }; store.inner.lock().expect("auth").session = Some(session); + store.vault.save(&persisted); result.user } @@ -337,63 +641,32 @@ pub fn auth_finish( /// lo renueva una vez (igual que la web); si el refresh falla, cierra la sesión. #[tauri::command(async)] pub fn auth_status(app: AppHandle, state: State<'_, AppState>) -> Result, String> { - if let Some(user) = fresh_user(&state.auth) { - return Ok(Some(user)); - } - let Some(refresh_token) = refresh_due(&state.auth) else { - return Ok(state + match state.auth.refresh_now(false, None) { + RefreshOutcome::Fresh { user, .. } => Ok(Some(user)), + RefreshOutcome::Refreshed { user, .. } => { + emit_changed(&app, Some(user.clone())); + Ok(Some(user)) + } + RefreshOutcome::NoSession => Ok(None), + RefreshOutcome::Rejected => { + emit_changed(&app, None); + Ok(None) + } + RefreshOutcome::Malformed => Ok(state .auth .inner .lock() .expect("auth") .session .as_ref() - .map(|s| s.user.clone())); - }; - let body = format!("{{\"refreshToken\":\"{}\"}}", json_escape(&refresh_token)); - match post_json(&state.auth, "/auth/refresh", &body) { - Ok((200, raw)) => match serde_json::from_slice::(&raw) { - Ok(pair) => { - let mut inner = state.auth.inner.lock().expect("auth"); - if let Some(session) = inner.session.as_mut() { - session.access_token = pair.access_token; - session.refresh_token = pair.refresh_token; - session.expires_at = Instant::now() + Duration::from_secs(pair.expires_in); - let user = session.user.clone(); - drop(inner); - emit_changed(&app, Some(user.clone())); - return Ok(Some(user)); - } - Ok(None) - } - Err(_) => Ok(state - .auth - .inner - .lock() - .expect("auth") - .session - .as_ref() - .map(|s| s.user.clone())), - }, - _ => { - state.auth.inner.lock().expect("auth").session = None; - emit_changed(&app, None); - Ok(None) - } + .map(|s| s.user.clone())), } } -/// Cierra la sesión (avisa al relay sin bloquear) y emite `auth-changed` sin usuario. +/// Cierra la sesión (avisa al relay sin bloquear), limpia el llavero y emite `auth-changed` sin usuario. #[tauri::command(async)] pub fn auth_logout(app: AppHandle, state: State<'_, AppState>) -> Result<(), String> { - let refresh_token = state - .auth - .inner - .lock() - .expect("auth") - .session - .take() - .map(|session| session.refresh_token); + let refresh_token = state.auth.clear_session(); if let Some(refresh_token) = refresh_token { let body = format!("{{\"refreshToken\":\"{}\"}}", json_escape(&refresh_token)); let _ = post_json(&state.auth, "/auth/logout", &body); @@ -402,29 +675,6 @@ pub fn auth_logout(app: AppHandle, state: State<'_, AppState>) -> Result<(), Str Ok(()) } -fn fresh_user(store: &AuthStore) -> Option { - let inner = store.inner.lock().expect("auth"); - inner.session.as_ref().and_then(|session| { - if session.expires_at.saturating_duration_since(Instant::now()) > REFRESH_MARGIN { - Some(session.user.clone()) - } else { - None - } - }) -} - -/// Refresh token si la sesión existe y el access está vencido o por vencer. -fn refresh_due(store: &AuthStore) -> Option { - let inner = store.inner.lock().expect("auth"); - inner.session.as_ref().and_then(|session| { - if session.expires_at.saturating_duration_since(Instant::now()) <= REFRESH_MARGIN { - Some(session.refresh_token.clone()) - } else { - None - } - }) -} - #[cfg(test)] mod tests { use super::*; @@ -443,10 +693,13 @@ mod tests { let store = AuthStore { api_addr: "127.0.0.1:8787".to_string(), web_origin: "https://app.example.com".to_string(), + client: "desktop", + vault: Arc::new(NoopVault), inner: Mutex::new(Inner { verifier: None, session: None, }), + refresh_lock: Mutex::new(()), }; assert_eq!( store.login_url(&"a".repeat(43)), @@ -455,6 +708,14 @@ mod tests { "a".repeat(43) ) ); + let dev_store = store.with_dev_client(true); + assert_eq!( + dev_store.login_url(&"a".repeat(43)), + format!( + "https://app.example.com/login?client=desktop-dev&code_challenge={}", + "a".repeat(43) + ) + ); } #[test] @@ -473,6 +734,10 @@ mod tests { parse_callback_code("opencollab://auth/callback?code=abc123"), Some("abc123".to_string()) ); + assert_eq!( + parse_callback_code("opencollab-dev://auth/callback?code=dev123"), + Some("dev123".to_string()) + ); // Parámetros extra no molestan; el primero que vale es el code. assert_eq!( parse_callback_code("opencollab://auth/callback?foo=1&code=xyz"), @@ -517,4 +782,350 @@ mod tests { assert!(!is_valid_verifier(&"a".repeat(129))); assert!(!is_valid_verifier("corto")); } + + #[test] + fn resolve_web_origin_prefers_opencollab_origin_then_web_origin_then_default() { + // 1. OPENCOLLAB_WEB_ORIGIN tiene prioridad si ambas están + let origin = resolve_web_origin(|key| match key { + "OPENCOLLAB_WEB_ORIGIN" => Ok("http://localhost:9999".to_string()), + "WEB_ORIGIN" => Ok("http://localhost:8080".to_string()), + _ => Err(std::env::VarError::NotPresent), + }); + assert_eq!(origin, "http://localhost:9999"); + + // 2. WEB_ORIGIN se usa si OPENCOLLAB_WEB_ORIGIN no está + let origin = resolve_web_origin(|key| match key { + "WEB_ORIGIN" => Ok("http://localhost:8080".to_string()), + _ => Err(std::env::VarError::NotPresent), + }); + assert_eq!(origin, "http://localhost:8080"); + + // 3. DEFAULT_WEB_ORIGIN si ninguna está + let origin = resolve_web_origin(|_| Err(std::env::VarError::NotPresent)); + assert_eq!(origin, "http://localhost:1421"); + + // 4. Si el origen es inválido (ej. con path), cae al default + let origin = resolve_web_origin(|key| match key { + "WEB_ORIGIN" => Ok("http://localhost:8080/invalid/path".to_string()), + _ => Err(std::env::VarError::NotPresent), + }); + assert_eq!(origin, "http://localhost:1421"); + } + + fn store_with_session(access_token: &str, refresh_token: &str) -> AuthStore { + AuthStore { + api_addr: "127.0.0.1:1".to_string(), + web_origin: DEFAULT_WEB_ORIGIN.to_string(), + client: "desktop", + vault: Arc::new(NoopVault), + inner: Mutex::new(Inner { + verifier: None, + session: Some(Session { + access_token: access_token.to_string(), + refresh_token: refresh_token.to_string(), + expires_at: Instant::now() + Duration::from_secs(600), + user: UserView { + id: "u1".to_string(), + username: "ana".to_string(), + email: None, + display_name: "Ana".to_string(), + }, + }), + }), + refresh_lock: Mutex::new(()), + } + } + + #[test] + fn fresh_session_token_comes_from_memory_without_the_relay() { + // El relay apunta a un puerto cerrado a propósito: un token vigente no + // debe intentar red, ni por el método propio ni por el puerto. + let store = store_with_session("access-1", "refresh-1"); + assert_eq!(store.access_token_for_request().unwrap(), "access-1"); + assert_eq!( + AccessTokenProvider::access_token(&store).unwrap(), + "access-1" + ); + } + + #[test] + fn no_session_cannot_produce_a_token() { + let store = AuthStore { + api_addr: "127.0.0.1:1".to_string(), + web_origin: DEFAULT_WEB_ORIGIN.to_string(), + client: "desktop", + vault: Arc::new(NoopVault), + inner: Mutex::new(Inner { + verifier: None, + session: None, + }), + refresh_lock: Mutex::new(()), + }; + assert_eq!( + store.access_token_for_request(), + Err("no hay sesión iniciada".to_string()) + ); + assert!(AccessTokenProvider::access_token(&store).is_err()); + assert!(store.refreshed_access_token_for_request("stale").is_err()); + assert!(!store.has_session()); + } + + #[test] + fn a_stale_rejected_token_reuses_the_concurrent_refresh_without_network() { + // El relay apunta a un puerto cerrado: si el short-circuit no ocurre, + // este test falla por timeout de red en vez de devolver el token nuevo. + let store = store_with_session("access-2", "refresh-2"); + // El 401 llegó con "access-1", pero otro pedido ya renovó a "access-2". + assert_eq!( + store + .refreshed_access_token_for_request("access-1") + .unwrap(), + "access-2" + ); + assert!(store.has_session()); + } + + #[test] + fn dos_401_concurrentes_comparten_un_solo_refresh() { + use std::io::{Read, Write}; + use std::net::TcpListener; + use std::sync::atomic::{AtomicUsize, Ordering}; + use std::sync::{Arc, Barrier}; + + let listener = TcpListener::bind("127.0.0.1:0").expect("listener"); + let addr = listener.local_addr().expect("addr").to_string(); + let hits = Arc::new(AtomicUsize::new(0)); + let hits_server = Arc::clone(&hits); + std::thread::spawn(move || { + for stream in listener.incoming() { + let Ok(mut stream) = stream else { continue }; + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + hits_server.fetch_add(1, Ordering::SeqCst); + let body = + r#"{"accessToken":"access-2","refreshToken":"refresh-2","expiresIn":600}"#; + let response = format!( + "HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}", + body.len(), + body + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + + let store = Arc::new(AuthStore { + api_addr: addr, + web_origin: DEFAULT_WEB_ORIGIN.to_string(), + client: "desktop", + vault: Arc::new(NoopVault), + inner: Mutex::new(Inner { + verifier: None, + session: Some(Session { + access_token: "access-1".to_string(), + refresh_token: "refresh-1".to_string(), + expires_at: Instant::now() + Duration::from_secs(600), + user: UserView { + id: "u1".to_string(), + username: "ana".to_string(), + email: None, + display_name: "Ana".to_string(), + }, + }), + }), + refresh_lock: Mutex::new(()), + }); + + let barrier = Arc::new(Barrier::new(2)); + let handles: Vec<_> = (0..2) + .map(|_| { + let store = Arc::clone(&store); + let barrier = Arc::clone(&barrier); + std::thread::spawn(move || { + barrier.wait(); + store.refreshed_access_token_for_request("access-1") + }) + }) + .collect(); + for handle in handles { + assert_eq!(handle.join().expect("hilo"), Ok("access-2".to_string())); + } + assert_eq!( + hits.load(Ordering::SeqCst), + 1, + "un solo refresh para dos 401" + ); + } + + #[derive(Default)] + struct MemoryVault { + stored: Mutex>, + } + + impl MemoryVault { + fn with(session: PersistedSession) -> Arc { + Arc::new(Self { + stored: Mutex::new(Some(session)), + }) + } + } + + impl SessionVault for MemoryVault { + fn load(&self) -> Option { + self.stored.lock().expect("vault").clone() + } + fn save(&self, session: &PersistedSession) { + *self.stored.lock().expect("vault") = Some(session.clone()); + } + fn clear(&self) { + *self.stored.lock().expect("vault") = None; + } + } + + fn sample_user() -> UserView { + UserView { + id: "u1".to_string(), + username: "ana".to_string(), + email: Some("ana@example.com".to_string()), + display_name: "Ana".to_string(), + } + } + + fn serve_once(status_line: &'static str, response_body: &'static str) -> String { + use std::io::{Read, Write}; + use std::net::TcpListener; + + let listener = TcpListener::bind("127.0.0.1:0").expect("listener"); + let addr = listener.local_addr().expect("addr").to_string(); + std::thread::spawn(move || { + if let Ok((mut stream, _)) = listener.accept() { + let mut buf = [0u8; 4096]; + let _ = stream.read(&mut buf); + let response = format!( + "HTTP/1.1 {status_line}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{response_body}", + response_body.len() + ); + let _ = stream.write_all(response.as_bytes()); + } + }); + addr + } + + #[test] + fn servicio_del_llavero_aisla_produccion_y_desarrollo() { + let prod = AuthStore::new("127.0.0.1:8787".to_string()); + assert_eq!(prod.keyring_service(), "opencollab"); + let dev = AuthStore::new("127.0.0.1:8787".to_string()).with_dev_client(true); + assert_eq!(dev.keyring_service(), "opencollab-dev"); + } + + #[test] + fn adopt_session_guarda_refresh_y_usuario_en_el_llavero_y_logout_lo_limpia() { + let vault = Arc::new(MemoryVault::default()); + let store = AuthStore::new("127.0.0.1:1".to_string()).with_vault(vault.clone()); + let user = sample_user(); + + let returned = adopt_session( + &store, + AuthResultBody { + access_token: "access-secreto".to_string(), + refresh_token: "refresh-1".to_string(), + expires_in: 900, + user: user.clone(), + }, + ); + assert_eq!(returned, user); + assert_eq!( + vault.load(), + Some(PersistedSession { + refresh_token: "refresh-1".to_string(), + user, + }) + ); + + let cleared = store.clear_session(); + assert_eq!(cleared.as_deref(), Some("refresh-1")); + assert!(!store.has_session()); + assert_eq!(vault.load(), None); + } + + #[test] + fn restaura_la_sesion_del_llavero_y_renueva_el_access_en_el_primer_pedido() { + let addr = serve_once( + "200 OK", + r#"{"accessToken":"access-nuevo","refreshToken":"refresh-rotado","expiresIn":600}"#, + ); + let vault = MemoryVault::with(PersistedSession { + refresh_token: "refresh-guardado".to_string(), + user: sample_user(), + }); + let store = AuthStore::new(addr).with_vault(vault.clone()); + assert!( + store.has_session(), + "debe hidratar la sesión del llavero al iniciar" + ); + + let token = store + .access_token_for_request() + .expect("refresh al iniciar"); + assert_eq!(token, "access-nuevo"); + assert_eq!( + vault.load().map(|s| s.refresh_token), + Some("refresh-rotado".to_string()), + "el refresh rotado debe persistirse en el llavero" + ); + } + + #[test] + fn fallo_de_red_o_5xx_preserva_la_sesion_en_memoria_y_en_el_llavero() { + let vault = MemoryVault::with(PersistedSession { + refresh_token: "refresh-vivo".to_string(), + user: sample_user(), + }); + // 1. Relay caído (puerto cerrado) + let store_down = AuthStore::new("127.0.0.1:1".to_string()).with_vault(vault.clone()); + assert!(store_down.access_token_for_request().is_err()); + assert!( + store_down.has_session(), + "un fallo de conexión no debe cerrar la sesión local" + ); + assert_eq!( + vault.load().map(|s| s.refresh_token), + Some("refresh-vivo".to_string()), + "un fallo de conexión no debe borrar el llavero" + ); + + // 2. Relay responde 503 Service Unavailable + let addr_503 = serve_once("503 Service Unavailable", r#"{"message":"starting"}"#); + let store_503 = AuthStore::new(addr_503).with_vault(vault.clone()); + assert!(store_503.access_token_for_request().is_err()); + assert!( + store_503.has_session(), + "un 5xx del relay no debe cerrar la sesión local" + ); + assert_eq!( + vault.load().map(|s| s.refresh_token), + Some("refresh-vivo".to_string()), + "un 5xx del relay no debe borrar el llavero" + ); + } + + #[test] + fn rechazo_401_del_relay_borra_la_sesion_de_memoria_y_del_llavero() { + let addr_401 = serve_once("401 Unauthorized", r#"{"message":"Invalid refresh token"}"#); + let vault = MemoryVault::with(PersistedSession { + refresh_token: "refresh-revocado".to_string(), + user: sample_user(), + }); + let store = AuthStore::new(addr_401).with_vault(vault.clone()); + assert_eq!( + store.access_token_for_request(), + Err("no hay sesión iniciada".to_string()) + ); + assert!(!store.has_session()); + assert_eq!( + vault.load(), + None, + "un 401 explícito del relay debe limpiar el llavero" + ); + } } diff --git a/apps/desktop/src-tauri/src/collab_status.rs b/apps/desktop/src-tauri/src/collab_status.rs index e3e8659..2d1f09a 100644 --- a/apps/desktop/src-tauri/src/collab_status.rs +++ b/apps/desktop/src-tauri/src/collab_status.rs @@ -9,6 +9,7 @@ use serde::Serialize; use tauri::{AppHandle, Emitter, Manager}; use crate::state::AppState; +use crate::storage_config::StorageMode; pub const COLLAB_STATUS_EVENT: &str = "collab-status"; const INTERVAL: Duration = Duration::from_secs(3); @@ -47,15 +48,28 @@ impl CollabStatusPayload { /// colaboradores. No falla: si el conteo da error, el estado del relay se /// sigue reportando con el último conteo conocido (`last_collaborators`). pub fn snapshot(state: &AppState, last_collaborators: Option) -> CollabStatusPayload { - let collaborators = state.session_collaborators.execute(state.session_id); + snapshot_for_mode( + state.storage_config().mode, + || state.check_relay.execute(), + || state.session_collaborators.execute(state.session_id), + last_collaborators, + ) +} + +fn snapshot_for_mode( + mode: StorageMode, + probe_relay: impl FnOnce() -> RelayStatus, + count_collaborators: impl FnOnce() -> Result, + last_collaborators: Option, +) -> CollabStatusPayload { + if mode == StorageMode::Local { + return CollabStatusPayload::new(RelayStatus::Disconnected, 1); + } + let collaborators = count_collaborators(); if let Err(e) = &collaborators { eprintln!("estado de colaboración: {e}"); } - compose( - state.check_relay.execute(), - collaborators, - last_collaborators, - ) + compose(probe_relay(), collaborators, last_collaborators) } /// Arma el estado sin dejar que un error del conteo tape el del relay: usa el @@ -184,4 +198,39 @@ mod tests { let json = serde_json::to_value(disconnected(1)).unwrap(); assert_eq!(json["syncMs"], serde_json::Value::Null); } + + #[test] + fn local_mode_keeps_collaboration_inactive_without_probing_the_relay() { + let mut probed = false; + let mut counted = false; + let payload = snapshot_for_mode( + StorageMode::Local, + || { + probed = true; + RelayStatus::Connected { latency_ms: 11 } + }, + || { + counted = true; + Ok(4) + }, + Some(3), + ); + assert_eq!(payload, disconnected(1)); + assert!(!probed, "el modo local no debe sondear el relay"); + assert!( + !counted, + "el modo local no debe consultar colaboradores remotos" + ); + } + + #[test] + fn cloud_mode_probes_the_relay_and_counts_collaborators() { + let payload = snapshot_for_mode( + StorageMode::Cloud, + || RelayStatus::Connected { latency_ms: 18 }, + || Ok(3), + Some(1), + ); + assert_eq!(payload, connected(18, 3)); + } } diff --git a/apps/desktop/src-tauri/src/commands.rs b/apps/desktop/src-tauri/src/commands.rs index 3a01385..819c229 100644 --- a/apps/desktop/src-tauri/src/commands.rs +++ b/apps/desktop/src-tauri/src/commands.rs @@ -4,6 +4,7 @@ use std::sync::Arc; use std::time::Instant; use application::ports::{TerminalOutputSink, TerminalSize}; +use application::storage::{StoredWorkspace, WorkspaceSnapshot}; use domain::TerminalId; use serde::Serialize; use tauri::{AppHandle, Emitter, State}; @@ -15,6 +16,7 @@ use application::{exit_event, ActivityTracker, AgentAdapters, AgentStates, Known use crate::agent_events::TauriAgentEvents; use crate::collab_status::{self, CollabStatusPayload}; use crate::state::AppState; +use crate::storage_config::{StorageConfig, StorageMode}; pub const TERMINAL_OUTPUT_EVENT: &str = "terminal-output"; pub const TERMINAL_EXIT_EVENT: &str = "terminal-exit"; @@ -247,3 +249,64 @@ pub fn resize_terminal( ) .map_err(|e| e.to_string()) } + +// Snapshot de la estructura del escritorio (S5 del feature desktop-dual-storage). +// Disco: `async` para no frenar la UI; las escrituras las encola el frontend +// (una cola de promesas), así que acá no hace falta serializarlas más. + +/// El snapshot guardado; `None` si no hay nada (primera corrida, arranque +/// limpio o cuarentena del archivo corrupto anterior). +#[tauri::command(async)] +pub fn snapshot_load(state: State<'_, AppState>) -> Result, String> { + state + .snapshot_store() + .load_snapshot() + .map_err(|e| e.to_string()) +} + +/// Guarda la estructura completa. La versión del formato la maneja el núcleo +/// (`WorkspaceSnapshot::new` estampa `SNAPSHOT_VERSION`). Un snapshot vacío se +/// rechaza: un estado sin hidratar no debe borrar la nube. +#[tauri::command(async)] +pub fn snapshot_save( + state: State<'_, AppState>, + workspaces: Vec, +) -> Result<(), String> { + if workspaces.is_empty() { + return Err("se rechazó guardar un snapshot vacío".to_string()); + } + let snapshot = WorkspaceSnapshot::new(workspaces); + state + .snapshot_store() + .save_snapshot(&snapshot) + .map_err(|e| e.to_string()) +} + +/// Configuración vigente de almacenamiento (modo, base URL, onboarding). +#[tauri::command] +pub fn storage_config_get(state: State<'_, AppState>) -> StorageConfig { + state.storage_config() +} + +/// Cambia el modo de almacenamiento y persiste la configuración. Cloud exige +/// una sesión iniciada; el store se reemplaza antes de devolver el resultado. +#[tauri::command(async)] +pub fn storage_config_set( + app: AppHandle, + state: State<'_, AppState>, + mode: StorageMode, + api_base_url: String, +) -> Result { + let current = state.storage_config(); + let updated = state.set_storage_config(StorageConfig { + version: current.version, + mode, + api_base_url, + onboarding_complete: current.onboarding_complete, + })?; + let _ = app.emit( + collab_status::COLLAB_STATUS_EVENT, + collab_status::snapshot(&state, None), + ); + Ok(updated) +} diff --git a/apps/desktop/src-tauri/src/env.rs b/apps/desktop/src-tauri/src/env.rs new file mode 100644 index 0000000..782f616 --- /dev/null +++ b/apps/desktop/src-tauri/src/env.rs @@ -0,0 +1,110 @@ +use std::path::{Path, PathBuf}; + +/// Parsea una línea de formato `.env`. Devuelve `(clave, valor)` o `None` si es +/// comentario, está vacía o es inválida. +pub fn parse_env_line(line: &str) -> Option<(&str, &str)> { + let line = line.trim(); + if line.is_empty() || line.starts_with('#') { + return None; + } + let (key, val) = line.split_once('=')?; + let key = key.trim(); + if key.is_empty() { + return None; + } + let val = val.trim(); + let val = if (val.starts_with('"') && val.ends_with('"')) + || (val.starts_with('\'') && val.ends_with('\'')) + { + if val.len() >= 2 { + &val[1..val.len() - 1] + } else { + val + } + } else { + val + }; + Some((key, val)) +} + +/// Busca el archivo `.env` en `dir` y sus directorios padre. +fn find_env_file_from(start: &Path) -> Option { + let mut current = Some(start); + while let Some(dir) = current { + let candidate = dir.join(".env"); + if candidate.is_file() { + return Some(candidate); + } + current = dir.parent(); + } + None +} + +/// Carga las variables de un archivo `.env` en el entorno del proceso si no +/// están ya definidas en el sistema. +pub fn load_dot_env() { + let mut candidates = Vec::new(); + if let Ok(cwd) = std::env::current_dir() { + candidates.push(cwd); + } + if let Ok(exe) = std::env::current_exe() { + if let Some(parent) = exe.parent() { + candidates.push(parent.to_path_buf()); + } + } + + for start in candidates { + if let Some(path) = find_env_file_from(&start) { + if let Ok(content) = std::fs::read_to_string(path) { + for line in content.lines() { + if let Some((key, val)) = parse_env_line(line) { + if std::env::var_os(key).is_none() { + std::env::set_var(key, val); + } + } + } + } + return; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_plain_key_value() { + assert_eq!(parse_env_line("FOO=bar"), Some(("FOO", "bar"))); + assert_eq!(parse_env_line(" PORT = 8080 "), Some(("PORT", "8080"))); + } + + #[test] + fn ignores_comments_and_empty_lines() { + assert_eq!(parse_env_line(""), None); + assert_eq!(parse_env_line(" "), None); + assert_eq!(parse_env_line("# Comentario"), None); + assert_eq!(parse_env_line(" # Comentario identado"), None); + } + + #[test] + fn strips_enclosing_quotes() { + assert_eq!(parse_env_line("FOO=\"bar baz\""), Some(("FOO", "bar baz"))); + assert_eq!(parse_env_line("FOO='bar baz'"), Some(("FOO", "bar baz"))); + assert_eq!(parse_env_line("FOO=\"\""), Some(("FOO", ""))); + } + + #[test] + fn preserves_inner_equals_signs() { + assert_eq!( + parse_env_line("URL=https://example.com/login?foo=1&bar=2"), + Some(("URL", "https://example.com/login?foo=1&bar=2")) + ); + } + + #[test] + fn rejects_missing_key() { + assert_eq!(parse_env_line("=valor"), None); + assert_eq!(parse_env_line(" =valor"), None); + } +} diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rs index a9a31fa..aceeb54 100644 --- a/apps/desktop/src-tauri/src/main.rs +++ b/apps/desktop/src-tauri/src/main.rs @@ -6,11 +6,14 @@ mod agent_watcher; mod auth; mod collab_status; mod commands; +mod env; mod state; +mod storage_config; use tauri::Manager; fn main() { + env::load_dot_env(); let mut builder = tauri::Builder::default(); // Único: el deep link que llega como argumento de un segundo proceso se // reenvía a esta instancia (el plugin `deep-link` lo entrega igual). @@ -30,7 +33,21 @@ fn main() { let _ = window.set_icon(icon.clone()); } } - app.manage(state::AppState::bootstrap()?); + // appdata del bundle (app_data_dir une el identificador del + // tauri.conf.json a la carpeta de datos del usuario). + let data_dir = app + .path() + .app_data_dir() + .map_err(|e| format!("no se pudo resolver el directorio de datos: {e}"))?; + let is_dev_app = app.config().identifier.ends_with(".dev"); + #[cfg(any(windows, target_os = "linux"))] + if is_dev_app { + use tauri_plugin_deep_link::DeepLinkExt; + if let Err(e) = app.deep_link().register("opencollab-dev") { + eprintln!("no se pudo registrar el esquema opencollab-dev://: {e}"); + } + } + app.manage(state::AppState::bootstrap(data_dir, is_dev_app)?); agent_watcher::spawn(app.handle().clone()); collab_status::spawn(app.handle().clone()); Ok(()) @@ -41,6 +58,10 @@ fn main() { commands::write_terminal, commands::resize_terminal, commands::close_terminal, + commands::snapshot_load, + commands::snapshot_save, + commands::storage_config_get, + commands::storage_config_set, commands::list_subdirectories, commands::git_branch, commands::collab_status, diff --git a/apps/desktop/src-tauri/src/state.rs b/apps/desktop/src-tauri/src/state.rs index f01523b..2977f1a 100644 --- a/apps/desktop/src-tauri/src/state.rs +++ b/apps/desktop/src-tauri/src/state.rs @@ -1,24 +1,31 @@ -use std::sync::Arc; +use std::path::{Path, PathBuf}; +use std::sync::{Arc, RwLock}; use std::time::Duration; -use application::ports::{ProcessInspector, PtyPort, RelayProbe, WorkspaceRepository}; +use application::ports::{ + AccessTokenProvider, PortError, ProcessInspector, PtyPort, RelayProbe, SessionRepository, + SnapshotStore, +}; +use application::storage::WorkspaceSnapshot; use application::{ ActivityTracker, AgentAdapter, AgentAdapters, AgentStates, AppError, CheckRelay, CloseTerminal, DetectTerminalAgents, InspectBranch, LaunchTerminal, ListSubdirectories, ResizeTerminal, SendTerminalInput, SessionCollaborators, }; -use domain::{Session, SessionId, UserId, Workspace}; +use domain::{Session, SessionId, UserId}; use infrastructure::{ - ClaudeCodeAdapter, FsDirectoryBrowser, FsRepositoryInspector, HookReceiver, HttpRelayProbe, - InMemoryWorkspaceRepository, OpenCodeAdapter, PortablePtyAdapter, SysinfoProcessInspector, + ClaudeCodeAdapter, CloudSnapshotStore, FsDirectoryBrowser, FsRepositoryInspector, + FsSnapshotStore, HookReceiver, HttpRelayProbe, InMemorySessionRepository, OpenCodeAdapter, + PortablePtyAdapter, SysinfoProcessInspector, }; use crate::auth::AuthStore; +use crate::storage_config::{StorageConfig, StorageMode}; /// Silencio de un PTY a partir del cual se considera inactivo. const ACTIVITY_IDLE_AFTER: Duration = Duration::from_secs(3); -/// Dependencias cableadas de la app. Mientras no haya cuentas ni persistencia, -/// arranca con un usuario local dueño de un workspace y una sesión. +/// Dependencias cableadas de la app. El usuario local sigue siendo el dueño de +/// la sesión de arranque; la persistencia la elige `storage_config`. pub struct AppState { pub local_user: UserId, pub session_id: SessionId, @@ -38,8 +45,14 @@ pub struct AppState { pub adapters: Arc, pub check_relay: CheckRelay, pub session_collaborators: SessionCollaborators, - /// Sesión del desktop (tokens solo en memoria) + verifier PKCE pendiente. - pub auth: AuthStore, + /// Sesión del desktop (`access_token` y verifier PKCE en memoria; `refresh_token` en el llavero del SO). + pub auth: Arc, + /// Persistencia de la estructura del escritorio (snapshot de workspaces, + /// sesiones y perfiles de arranque). Se reemplaza al cambiar de modo. + pub snapshot_store: RwLock>, + /// Modo y base URL vigentes; se persisten en appdata. + pub storage_config: RwLock, + data_dir: PathBuf, } /// Adaptadores ricos disponibles. Si uno no puede arrancar (p. ej. no abre su @@ -55,8 +68,13 @@ fn agent_adapters() -> Vec> { } impl AppState { - pub fn bootstrap() -> Result { - let repo: Arc = Arc::new(InMemoryWorkspaceRepository::new()); + /// `data_dir` es el directorio de datos de la app (appdata resuelto por + /// Tauri en el setup); el port lo implanta en un archivo, no lo crea. + /// Cuando `is_dev_app` es `true`, el login usa `client=desktop-dev` para + /// regresar por el esquema aislado `opencollab-dev://`. + pub fn bootstrap(data_dir: std::path::PathBuf, is_dev_app: bool) -> Result { + crate::env::load_dot_env(); + let repo: Arc = Arc::new(InMemorySessionRepository::new()); let pty: Arc = Arc::new(PortablePtyAdapter::new()); let inspector: Arc = Arc::new(SysinfoProcessInspector::new()); @@ -66,12 +84,19 @@ impl AppState { let relay_probe: Arc = Arc::new(HttpRelayProbe::new(relay_addr.clone())); let local_user = UserId::new(); - let workspace = Workspace::new(local_user, "Local"); - let session = Session::new(&workspace, local_user, "Sesión local")?; + let session = Session::new(local_user, "Sesión local"); let session_id = session.id(); - repo.save_workspace(workspace)?; repo.save_session(session)?; + let auth = Arc::new( + AuthStore::new(relay_addr.clone()) + .with_dev_client(is_dev_app) + .with_os_keyring(), + ); + let default_api_base_url = format!("http://{relay_addr}"); + let config = StorageConfig::load(&data_dir, &default_api_base_url); + let snapshot_store = build_snapshot_store(&config, &data_dir, auth.clone()); + Ok(Self { local_user, session_id, @@ -88,9 +113,64 @@ impl AppState { adapters: Arc::new(AgentAdapters::new(agent_adapters())), check_relay: CheckRelay::new(relay_probe), session_collaborators: SessionCollaborators::new(repo), - auth: AuthStore::new(relay_addr), + auth, + snapshot_store: RwLock::new(snapshot_store), + storage_config: RwLock::new(config), + data_dir, }) } + + /// Store vigente; se clona el `Arc` para no sostener el lock durante I/O. + pub fn snapshot_store(&self) -> Arc { + self.snapshot_store.read().expect("snapshot store").clone() + } + + pub fn storage_config(&self) -> StorageConfig { + self.storage_config.read().expect("storage config").clone() + } + + /// Persiste el modo/base URL, valida que cloud tenga sesión y cambia el + /// store antes de devolver la configuración ya completa. Al pasar de local + /// a cloud migra el snapshot local a la cuenta (S4, A4) dejando el archivo + /// local intacto. + pub fn set_storage_config(&self, mut config: StorageConfig) -> Result { + config.validate()?; + if config.mode == StorageMode::Cloud && !self.auth.has_session() { + return Err("iniciá sesión antes de usar el modo nube".to_string()); + } + let current = self.storage_config(); + let store: Arc = match config.mode { + StorageMode::Local => Arc::new(FsSnapshotStore::new(self.data_dir.clone())), + StorageMode::Cloud => { + let tokens: Arc = self.auth.clone(); + let cloud = Arc::new(CloudSnapshotStore::new(config.api_base_url.clone(), tokens)); + let local = FsSnapshotStore::new(self.data_dir.clone()); + migrate_local_snapshot_if_needed(¤t, config.mode, &local, |snapshot| { + cloud.migrate_snapshot(snapshot) + })?; + cloud + } + }; + config.onboarding_complete = true; + config.save(&self.data_dir)?; + *self.snapshot_store.write().expect("snapshot store") = store; + *self.storage_config.write().expect("storage config") = config.clone(); + Ok(config) + } +} + +fn build_snapshot_store( + config: &StorageConfig, + data_dir: &Path, + auth: Arc, +) -> Arc { + match config.mode { + StorageMode::Local => Arc::new(FsSnapshotStore::new(data_dir.to_path_buf())), + StorageMode::Cloud => { + let tokens: Arc = auth; + Arc::new(CloudSnapshotStore::new(config.api_base_url.clone(), tokens)) + } + } } /// Nombre del ejecutable de esta app: la detección de agentes no baja por otra @@ -101,3 +181,152 @@ fn own_executable_name() -> Option { .file_name() .map(|name| name.to_string_lossy().into_owned()) } + +fn migrate_local_snapshot_if_needed( + previous: &StorageConfig, + target_mode: StorageMode, + local_store: &dyn SnapshotStore, + migrate: impl FnOnce(&WorkspaceSnapshot) -> Result<(), PortError>, +) -> Result<(), String> { + if !previous.onboarding_complete + || previous.mode != StorageMode::Local + || target_mode != StorageMode::Cloud + { + return Ok(()); + } + if let Some(snapshot) = local_store.load_snapshot().map_err(|e| e.to_string())? { + if !snapshot.workspaces.is_empty() { + migrate(&snapshot).map_err(|e| e.to_string())?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use application::storage::{StoredPane, StoredSession, StoredWorkspace}; + use std::sync::atomic::{AtomicU64, Ordering}; + + fn temp_dir(tag: &str) -> PathBuf { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::SeqCst); + let dir = std::env::temp_dir().join(format!( + "opencollab-state-migrate-{tag}-{}-{n}", + std::process::id() + )); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn sample_snapshot() -> WorkspaceSnapshot { + WorkspaceSnapshot::new(vec![StoredWorkspace { + id: "w1".into(), + name: "Local".into(), + sessions: vec![StoredSession { + id: "s1".into(), + name: "Sesión".into(), + panes: vec![StoredPane { + id: "p1".into(), + seq: 0, + minimized: false, + initial_cwd: None, + agent: None, + }], + }], + }]) + } + + #[test] + fn switching_from_completed_local_to_cloud_migrates_and_keeps_local_file() { + let dir = temp_dir("local-to-cloud"); + let local = FsSnapshotStore::new(&dir); + let expected = sample_snapshot(); + local.save_snapshot(&expected).unwrap(); + + let previous = StorageConfig { + version: 1, + mode: StorageMode::Local, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: true, + }; + let mut migrated: Option = None; + migrate_local_snapshot_if_needed(&previous, StorageMode::Cloud, &local, |snap| { + migrated = Some(snap.clone()); + Ok(()) + }) + .unwrap(); + + assert_eq!(migrated.as_ref(), Some(&expected)); + assert_eq!( + local.load_snapshot().unwrap().as_ref(), + Some(&expected), + "el archivo local debe conservarse intacto tras migrar (A4)" + ); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn migration_error_fails_closed_and_keeps_local_file() { + let dir = temp_dir("migrate-error"); + let local = FsSnapshotStore::new(&dir); + let expected = sample_snapshot(); + local.save_snapshot(&expected).unwrap(); + + let previous = StorageConfig { + version: 1, + mode: StorageMode::Local, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: true, + }; + let err = migrate_local_snapshot_if_needed(&previous, StorageMode::Cloud, &local, |_| { + Err(PortError::new("fallo de red al migrar")) + }) + .unwrap_err(); + + assert!(err.contains("fallo de red al migrar"), "{err}"); + assert_eq!(local.load_snapshot().unwrap().as_ref(), Some(&expected)); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn first_run_or_non_local_source_does_not_migrate() { + let dir = temp_dir("skip-migrate"); + let local = FsSnapshotStore::new(&dir); + local.save_snapshot(&sample_snapshot()).unwrap(); + + let first_run = StorageConfig { + version: 1, + mode: StorageMode::Local, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: false, + }; + let mut called = false; + migrate_local_snapshot_if_needed(&first_run, StorageMode::Cloud, &local, |_| { + called = true; + Ok(()) + }) + .unwrap(); + assert!( + !called, + "el primer arranque no debe migrar como cambio de modo" + ); + + let already_cloud = StorageConfig { + version: 1, + mode: StorageMode::Cloud, + api_base_url: "http://127.0.0.1:8787".into(), + onboarding_complete: true, + }; + migrate_local_snapshot_if_needed(&already_cloud, StorageMode::Cloud, &local, |_| { + called = true; + Ok(()) + }) + .unwrap(); + assert!( + !called, + "cloud -> cloud no debe volver a migrar el archivo local" + ); + let _ = std::fs::remove_dir_all(&dir); + } +} diff --git a/apps/desktop/src-tauri/src/storage_config.rs b/apps/desktop/src-tauri/src/storage_config.rs new file mode 100644 index 0000000..3abe827 --- /dev/null +++ b/apps/desktop/src-tauri/src/storage_config.rs @@ -0,0 +1,230 @@ +//! Configuración de almacenamiento del desktop: modo local/cloud y base URL +//! de la API. Vive en appdata junto al snapshot local y sobrevive reinicios. + +use std::fs; +use std::path::{Path, PathBuf}; + +use serde::{Deserialize, Serialize}; + +const CONFIG_FILE: &str = "storage.json"; +const CONFIG_VERSION: u32 = 1; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum StorageMode { + Local, + Cloud, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StorageConfig { + pub version: u32, + pub mode: StorageMode, + pub api_base_url: String, + #[serde(default)] + pub onboarding_complete: bool, +} + +impl StorageConfig { + /// Default seguro: local, onboarding pendiente y la API del relay. + pub fn local(default_api_base_url: &str) -> Self { + Self { + version: CONFIG_VERSION, + mode: StorageMode::Local, + api_base_url: default_api_base_url.to_string(), + onboarding_complete: false, + } + } + + pub fn path(data_dir: &Path) -> PathBuf { + data_dir.join(CONFIG_FILE) + } + + /// Lee la configuración. Archivo ausente, ilegible, de otra versión o con + /// una URL inválida cae al default local: nunca impide arrancar. + pub fn load(data_dir: &Path, default_api_base_url: &str) -> Self { + let fallback = Self::local(default_api_base_url); + let Ok(raw) = fs::read_to_string(Self::path(data_dir)) else { + return fallback; + }; + let Ok(mut config) = serde_json::from_str::(&raw) else { + return fallback; + }; + if config.version != CONFIG_VERSION { + return fallback; + } + let Ok(url) = normalize_api_base_url(&config.api_base_url) else { + // Una config inválida no debe dejar cloud + onboarding completo: + // el fallback es el default seguro completo, no solo la URL. + return fallback; + }; + config.api_base_url = url; + config + } + + /// Valida y normaliza los campos editables. El modo cloud requiere una + /// base URL http(s) absoluta; el valor se guarda sin barra final. + pub fn validate(&mut self) -> Result<(), String> { + self.api_base_url = normalize_api_base_url(&self.api_base_url)?; + self.version = CONFIG_VERSION; + Ok(()) + } + + /// Persiste la configuración de forma atómica (tmp + rename). El + /// `onboarding_complete` lo decide quien llama y ya viene validado. + pub fn save(&self, data_dir: &Path) -> Result<(), String> { + fs::create_dir_all(data_dir) + .map_err(|e| format!("no se pudo crear el directorio de datos: {e}"))?; + let json = serde_json::to_string_pretty(self) + .map_err(|e| format!("no se pudo serializar la configuración: {e}"))?; + let path = Self::path(data_dir); + let tmp = path.with_extension("json.tmp"); + fs::write(&tmp, json).map_err(|e| format!("no se pudo escribir la configuración: {e}"))?; + fs::rename(&tmp, &path).map_err(|e| format!("no se pudo reemplazar la configuración: {e}")) + } +} + +fn normalize_api_base_url(value: &str) -> Result { + let trimmed = value.trim().trim_end_matches('/'); + let rest = trimmed + .strip_prefix("http://") + .or_else(|| trimmed.strip_prefix("https://")) + .ok_or_else(|| "la URL de la API debe empezar con http:// o https://".to_string())?; + if rest.is_empty() || rest.chars().any(char::is_whitespace) { + return Err("la URL de la API no es válida".to_string()); + } + // Autoridad con host: rechaza `http://:8787` y `http:///path`. + let authority = rest.split('/').next().unwrap_or_default(); + if authority.is_empty() || authority.starts_with(':') { + return Err("la URL de la API no es válida".to_string()); + } + if trimmed.contains(['?', '#']) { + return Err("la URL de la API no puede tener query ni fragmento".to_string()); + } + Ok(trimmed.to_string()) +} + +#[cfg(test)] +mod tests { + use std::path::PathBuf; + use std::sync::atomic::{AtomicU64, Ordering}; + + use super::*; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(tag: &str) -> Self { + static N: AtomicU64 = AtomicU64::new(0); + let n = N.fetch_add(1, Ordering::SeqCst); + let path = std::env::temp_dir().join(format!( + "opencollab-storage-config-{tag}-{}-{n}", + std::process::id() + )); + fs::create_dir_all(&path).unwrap(); + Self(path) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = fs::remove_dir_all(&self.0); + } + } + + fn default_url() -> &'static str { + "http://127.0.0.1:8787" + } + + #[test] + fn missing_file_is_local_and_pending_onboarding() { + let dir = TempDir::new("missing"); + let config = StorageConfig::load(&dir.0, default_url()); + assert_eq!(config.mode, StorageMode::Local); + assert_eq!(config.api_base_url, default_url()); + assert!(!config.onboarding_complete); + } + + #[test] + fn round_trips_the_storage_config() { + let dir = TempDir::new("roundtrip"); + let mut config = StorageConfig { + version: CONFIG_VERSION, + mode: StorageMode::Cloud, + api_base_url: "https://api.example.com/".into(), + onboarding_complete: true, + }; + config.validate().unwrap(); + config.save(&dir.0).unwrap(); + assert_eq!(StorageConfig::load(&dir.0, default_url()), config); + } + + #[test] + fn malformed_or_future_config_falls_back_to_local() { + let dir = TempDir::new("malformed"); + fs::write(StorageConfig::path(&dir.0), "not json").unwrap(); + let malformed = StorageConfig::load(&dir.0, default_url()); + assert_eq!(malformed.mode, StorageMode::Local); + assert!(!malformed.onboarding_complete); + + fs::write( + StorageConfig::path(&dir.0), + r#"{"version":99,"mode":"cloud","apiBaseUrl":"https://api.example.com","onboardingComplete":true}"#, + ) + .unwrap(); + let future = StorageConfig::load(&dir.0, default_url()); + assert_eq!(future.mode, StorageMode::Local); + assert_eq!(future.api_base_url, default_url()); + } + + #[test] + fn invalid_api_base_url_falls_back_to_local_and_pending_onboarding() { + let dir = TempDir::new("invalid"); + fs::write( + StorageConfig::path(&dir.0), + r#"{"version":1,"mode":"cloud","apiBaseUrl":"not-a-url","onboardingComplete":true}"#, + ) + .unwrap(); + let config = StorageConfig::load(&dir.0, default_url()); + assert_eq!(config, StorageConfig::local(default_url())); + } + + #[test] + fn missing_version_is_treated_as_malformed() { + let dir = TempDir::new("version"); + fs::write( + StorageConfig::path(&dir.0), + r#"{"mode":"cloud","apiBaseUrl":"https://api.example.com","onboardingComplete":true}"#, + ) + .unwrap(); + assert_eq!( + StorageConfig::load(&dir.0, default_url()), + StorageConfig::local(default_url()) + ); + } + + #[test] + fn validates_and_normalizes_the_api_base_url() { + let mut config = StorageConfig { + version: 1, + mode: StorageMode::Cloud, + api_base_url: " https://api.example.com/ ".into(), + onboarding_complete: false, + }; + config.validate().unwrap(); + assert_eq!(config.api_base_url, "https://api.example.com"); + assert_eq!(config.version, CONFIG_VERSION); + + config.api_base_url = "ftp://api.example.com".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http://".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http://:8787".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http:///path".into(); + assert!(config.validate().is_err()); + config.api_base_url = "http://api.example.com?token=1".into(); + assert!(config.validate().is_err()); + } +} diff --git a/apps/desktop/src-tauri/tauri.conf.json b/apps/desktop/src-tauri/tauri.conf.json index 11ce577..d6b1c7f 100644 --- a/apps/desktop/src-tauri/tauri.conf.json +++ b/apps/desktop/src-tauri/tauri.conf.json @@ -1,10 +1,10 @@ { "$schema": "https://schema.tauri.app/config/2", "productName": "OpenCollab", - "version": "0.3.0", - "identifier": "dev.opencollab.app", + "version": "0.4.0", + "identifier": "com.opencollab.desktop", "build": { - "beforeDevCommand": "pnpm dev", + "beforeDevCommand": "pnpm dev:vite", "devUrl": "http://localhost:1420", "beforeBuildCommand": "pnpm build", "frontendDist": "../dist" diff --git a/apps/desktop/src-tauri/tauri.dev.conf.json b/apps/desktop/src-tauri/tauri.dev.conf.json new file mode 100644 index 0000000..16ea50e --- /dev/null +++ b/apps/desktop/src-tauri/tauri.dev.conf.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://schema.tauri.app/config/2", + "productName": "OpenCollab Dev", + "identifier": "com.opencollab.desktop.dev", + "app": { + "windows": [ + { + "title": "OpenCollab (Dev)" + } + ] + }, + "plugins": { + "deep-link": { + "desktop": { + "schemes": ["opencollab-dev"] + } + } + } +} diff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsx index fa47f9a..646eea2 100644 --- a/apps/desktop/src/App.tsx +++ b/apps/desktop/src/App.tsx @@ -1,29 +1,38 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react"; -import { opencollabLogoTransparent } from "./assets/brand"; -import { Button } from "./components/Button"; -import { Sidebar } from "./components/Sidebar"; -import { Plus } from "./icons"; -import type { AgentId } from "./agents"; -import { StatusBar } from "./components/StatusBar"; -import { TerminalPane } from "./components/TerminalPane"; -import { TopBar } from "./components/TopBar"; import { + Button, + Plus, + Sidebar, + StatusBar, + TopBar, insertPaneAfter, + isMod, newPane, newSession, newWorkspace, + opencollabLogoTransparent, swapPanes, + type AgentId, type Layout, type PaneMeta, type PaneStatus, type Session, type Workspace, -} from "./model"; -import { isMod } from "./shortcuts"; -import { useAuth } from "./useAuth"; -import { useCollabStatus } from "./useCollabStatus"; -import { usePaneDrag } from "./usePaneDrag"; +} from "@opencollab/ui"; +import { CloudGate } from "./components/CloudGate"; +import { TerminalPane } from "./components/TerminalPane"; +import { Onboarding } from "./components/Onboarding"; +import { SettingsDialog } from "./components/SettingsDialog"; +import { useAuth, useCollabStatus, usePaneDrag } from "./hooks"; +import { loadSnapshot, saveSnapshot, flushSnapshotSaves } from "./services/snapshot"; +import { + DEFAULT_STORAGE_CONFIG, + loadStorageConfig, + saveStorageConfig, + type StorageConfig, + type StorageMode, +} from "./services/storage"; function initialWorkspaces(): Workspace[] { const ws = newWorkspace("OpenCollab"); @@ -48,6 +57,173 @@ export function App() { const [statuses, setStatuses] = useState>({}); const [meta, setMeta] = useState>({}); const searchRef = useRef(null); + const [storage, setStorage] = useState(null); + const [storageBusy, setStorageBusy] = useState(false); + const [storageError, setStorageError] = useState(null); + const [settingsOpen, setSettingsOpen] = useState(false); + const activeWorkspaceIdRef = useRef(activeWorkspaceId); + useEffect(() => { + activeWorkspaceIdRef.current = activeWorkspaceId; + }, [activeWorkspaceId]); + + // La estructura arranca con el default y a los valores reemplaza el snapshot + // guardado del núcleo (S5 del feature desktop-dual-storage): mientras carga, + // todo lo que asume `workspaces[0]` sigue funcionando. + const hydratedRef = useRef(false); + // Descarta una carga que quedó en vuelo cuando ya empezó otra (cambio de + // modo durante el arranque): su resultado pertenece a otro store. + const hydrationGeneration = useRef(0); + // La grilla cloud no se muestra hasta que el snapshot cloud terminó de + // cargar: un default visible con persistencia apagada perdería mutaciones. + const [hydrationReady, setHydrationReady] = useState(false); + const [hydrationError, setHydrationError] = useState(null); + const hydratingRef = useRef(false); + // `applyStorage` hidrata el store nuevo directamente; este flag evita que el + // efecto de boot lance una segunda carga para el mismo cambio. + const skipHydrationEffect = useRef(false); + + /// Reemplaza la estructura y, si el workspace activo no existe en el store + /// nuevo, reapunta la selección al primero (cambio local ↔ cloud). + const adoptWorkspaces = useCallback((next: Workspace[]) => { + setWorkspaces(next); + if (next.length === 0) return; + if (next.some((w) => w.id === activeWorkspaceIdRef.current)) return; + const first = next[0]; + const firstSession = first.sessions[0]; + setActiveWorkspaceId(first.id); + setActiveSessionByWs({ [first.id]: firstSession.id }); + setFocusedPaneId(firstSession.panes[0]?.id ?? null); + setMaximizedPaneId(null); + }, []); + + /// Carga el snapshot del store que el núcleo ya tiene seleccionado. En un + /// cambio de modo, `resetWhenMissing` evita reenviar la estructura local al + /// store vacío: T6 es quien migra, no un efecto implícito de T4. + const hydrate = useCallback( + async (resetWhenMissing = false) => { + const generation = ++hydrationGeneration.current; + hydratingRef.current = true; + hydratedRef.current = false; + setHydrationReady(false); + setHydrationError(null); + try { + const loaded = await loadSnapshot(); + if (generation !== hydrationGeneration.current) return false; + if (loaded && loaded.length > 0) adoptWorkspaces(loaded); + else if (resetWhenMissing) adoptWorkspaces(initialWorkspaces()); + else setWorkspaces((current: Workspace[]) => [...current]); + hydratedRef.current = true; + setHydrationReady(true); + return true; + } catch (error) { + if (generation !== hydrationGeneration.current) return false; + // Error inesperado del núcleo al cargar: la persistencia queda apagada + // para no pisar un snapshot que todavía puede ser válido. La cuarentena + // de un archivo corrupto la resuelve el núcleo y llega como `null`, no + // como rechazo, así que este camino nunca habilita el guardado. + console.error("no se pudo cargar el snapshot de workspaces:", error); + setHydrationError(error instanceof Error ? error.message : String(error)); + return false; + } finally { + if (generation === hydrationGeneration.current) hydratingRef.current = false; + } + }, + [adoptWorkspaces], + ); + + // Primero la configuración: el snapshot se carga recién cuando el núcleo ya + // apunta al store elegido. Sin configuración (navegador/E2E viejo) entra en + // local completo para no bloquear la app. + useEffect(() => { + let cancelled = false; + void loadStorageConfig() + .then((config) => { + if (!cancelled) setStorage(config); + }) + .catch((error) => { + console.error("no se pudo cargar la configuración de almacenamiento:", error); + if (!cancelled) setStorage({ ...DEFAULT_STORAGE_CONFIG, onboardingComplete: true }); + }); + return () => { + cancelled = true; + }; + }, []); + + // El snapshot cloud solo se carga con sesión. Al perder la sesión se apaga + // la persistencia y se vuelve al gate de login; al recuperarla se recarga el + // store cloud. Para local, una única carga alcanza. + useEffect(() => { + if (!storage?.onboardingComplete) return; + if (storage.mode === "cloud" && auth.state.status !== "authenticated") { + // Cancela una carga en vuelo: su resultado pertenece a una sesión que ya + // no existe y no debe volver a habilitar el guardado. + hydrationGeneration.current += 1; + hydratingRef.current = false; + hydratedRef.current = false; + skipHydrationEffect.current = false; + setHydrationReady(false); + return; + } + if (skipHydrationEffect.current) { + skipHydrationEffect.current = false; + return; + } + if (hydrationReady || hydratingRef.current || hydrationError) return; + void hydrate(); + }, [storage, auth.state.status, hydrate, hydrationReady, hydrationError]); + + /// Guarda el modo/base URL y recarga el store nuevo. `true` si el núcleo + /// aceptó el cambio (cloud exige sesión y URL válida). + const applyStorage = useCallback( + async (mode: StorageMode, apiBaseUrl: string) => { + setStorageBusy(true); + setStorageError(null); + const wasHydrated = hydratedRef.current; + const wasReady = hydrationReady; + // Nada nuevo se guarda mientras se cambia de store; lo ya encolado + // termina en el store viejo antes de que el núcleo lo reemplace. + hydratedRef.current = false; + setHydrationReady(false); + setHydrationError(null); + try { + await flushSnapshotSaves(); + const next = await saveStorageConfig(mode, apiBaseUrl); + // El efecto de boot no debe lanzar una segunda carga: la de acá abajo + // es la que corresponde a este cambio de store. + skipHydrationEffect.current = true; + setStorage(next); + if (!(await hydrate(true))) { + setStorageError("No se pudo cargar el almacenamiento seleccionado."); + return; + } + setSettingsOpen(false); + } catch (error) { + hydratedRef.current = wasHydrated; + setHydrationReady(wasReady); + setStorageError(error instanceof Error ? error.message : String(error)); + } finally { + setStorageBusy(false); + } + }, + [hydrate, hydrationReady], + ); + + const retryHydration = useCallback(() => { + setHydrationError(null); + void hydrate(); + }, [hydrate]); + + const useLocalStorage = useCallback(() => { + if (!storage) return; + void applyStorage("local", storage.apiBaseUrl); + }, [applyStorage, storage]); + + // Persistencia en cada mutación de la estructura; la cola del servicio + // (`saveSnapshot`) garantiza que dos guardados nunca se cruzan. + useEffect(() => { + if (!hydratedRef.current) return; + void saveSnapshot(workspaces); + }, [workspaces]); const activeWorkspace = workspaces.find((w) => w.id === activeWorkspaceId) ?? workspaces[0]; const activeSession = @@ -209,6 +385,71 @@ export function App() { return { terminals: panes.length, live }; }, [activeSession.panes, statuses]); + if (!storage) { + return
Loading…
; + } + + if (!storage.onboardingComplete) { + return ( + void applyStorage(mode, storage.apiBaseUrl)} + onSignIn={() => void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + /> + ); + } + + // Cloud sin sesión no monta la grilla: sin tokens, cada mutación se + // descartaría en silencio. El login rearma el store y recién ahí se hidrata. + if (storage.mode === "cloud") { + if (auth.state.status === "unknown") { + return
Loading…
; + } + if (auth.state.status !== "authenticated") { + return ( + void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + onSignOut={() => void auth.logout()} + onRetry={retryHydration} + onUseLocal={useLocalStorage} + /> + ); + } + if (!hydrationReady) { + if (!hydrationError) { + return
Loading your cloud workspace…
; + } + return ( + void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + onSignOut={() => void auth.logout()} + onRetry={retryHydration} + onUseLocal={useLocalStorage} + /> + ); + } + } + return (
{ setLayout(l); setMaximizedPaneId(null); }} onNewTerminal={() => addTerminal()} + onOpenSettings={() => { + setStorageError(null); + setSettingsOpen(true); + }} />
- +
+ + {settingsOpen && ( + setSettingsOpen(false)} + onSave={(mode, apiBaseUrl) => void applyStorage(mode, apiBaseUrl)} + onSignIn={() => void auth.beginLogin()} + onCancelLogin={auth.cancelLogin} + /> + )} ); } diff --git a/apps/desktop/src/agents.ts b/apps/desktop/src/agents.ts deleted file mode 100644 index 6584772..0000000 --- a/apps/desktop/src/agents.ts +++ /dev/null @@ -1,27 +0,0 @@ -// Presentación de los agentes que detecta el núcleo (ver -// crates/application/src/agent_detection.rs: los ids tienen que coincidir). - -export type AgentId = "claude-code" | "opencode" | "codex" | "antigravity-cli" | "grok"; - -type AgentInfo = { name: string; badge: string; logoFile: string }; - -const catalog: Record = { - "claude-code": { name: "Claude Code", badge: "CC", logoFile: "claudecode-logo.svg" }, - opencode: { name: "OpenCode", badge: "OC", logoFile: "opencode-logo.svg" }, - codex: { name: "Codex", badge: "CX", logoFile: "codex-logo.svg" }, - "antigravity-cli": { name: "Antigravity CLI", badge: "AG", logoFile: "antigravitycli-logo.svg" }, - grok: { name: "Grok", badge: "GK", logoFile: "grok-xai-logo.svg" }, -}; - -// Glob en vez de imports directos: si un SVG todavía no está en la carpeta, -// el build no falla y el panel muestra el badge de texto. -const logos = import.meta.glob("./assets/agents/*.svg", { - eager: true, - query: "?url", - import: "default", -}); - -export function agentInfo(id: AgentId) { - const info = catalog[id]; - return { ...info, logo: logos[`./assets/agents/${info.logoFile}`] ?? null }; -} diff --git a/apps/desktop/src/collabStatus.test.ts b/apps/desktop/src/collabStatus.test.ts deleted file mode 100644 index 4a374b2..0000000 --- a/apps/desktop/src/collabStatus.test.ts +++ /dev/null @@ -1,32 +0,0 @@ -import { describe, expect, it } from "vitest"; - -import { DEFAULT_COLLAB_STATUS, parseCollabStatus } from "./collabStatus"; - -describe("DEFAULT_COLLAB_STATUS", () => { - it("es honesto: desconectado, sin latencia y solo el usuario local", () => { - expect(DEFAULT_COLLAB_STATUS).toEqual({ connected: false, syncMs: null, collaborators: 1 }); - }); -}); - -describe("parseCollabStatus", () => { - it("acepta un estado conectado", () => { - expect(parseCollabStatus({ connected: true, syncMs: 12, collaborators: 2 })).toEqual({ - connected: true, - syncMs: 12, - collaborators: 2, - }); - }); - - it("sin conexión no hay latencia, aunque el payload traiga una", () => { - expect(parseCollabStatus({ connected: false, syncMs: 12, collaborators: 1 }).syncMs).toBeNull(); - }); - - it("conectado sin latencia válida la deja en null", () => { - expect(parseCollabStatus({ connected: true, syncMs: null, collaborators: 1 }).syncMs).toBeNull(); - }); - - it("un payload malformado cae a los valores honestos", () => { - expect(parseCollabStatus(null)).toEqual(DEFAULT_COLLAB_STATUS); - expect(parseCollabStatus({ connected: "sí", collaborators: -3 })).toEqual(DEFAULT_COLLAB_STATUS); - }); -}); diff --git a/apps/desktop/src/components/CloudGate.tsx b/apps/desktop/src/components/CloudGate.tsx new file mode 100644 index 0000000..88a8ce4 --- /dev/null +++ b/apps/desktop/src/components/CloudGate.tsx @@ -0,0 +1,72 @@ +import { Button, opencollabLogoTransparent, type AuthState } from "@opencollab/ui"; + +import { StorageAuth } from "./StorageAuth"; + +type Props = { + auth: AuthState; + authBusy: boolean; + authError: string | null; + loginUrl: string | null; + busy: boolean; + error: string | null; + onSignIn: () => void; + onCancelLogin: () => void; + onSignOut: () => void; + onRetry: () => void; + onUseLocal: () => void; +}; + +/// Gate del modo cloud: sin sesión no se monta la grilla, y si el snapshot +/// cloud no carga se ofrece reintentar o volver a local. Evita arrancar en +/// cloud con la persistencia apagada y perder mutaciones en silencio. +export function CloudGate(props: Props) { + const signedIn = props.auth.status === "authenticated"; + return ( +
+
+ OpenCollab +

OpenCollab Cloud

+

+ {signedIn + ? "We couldn't load your cloud workspace." + : "Sign in to load your workspace structure from the cloud."} +

+ + + + {props.error && ( +

+ {props.error} +

+ )} + +
+ {props.error && ( + + )} + {signedIn && ( + + )} + +
+ +

+ Cloud storage needs an account. Local storage stays on this computer. +

+
+
+ ); +} diff --git a/apps/desktop/src/components/CwdSwitcher.tsx b/apps/desktop/src/components/CwdSwitcher.tsx index 7fd5f25..5c61f60 100644 --- a/apps/desktop/src/components/CwdSwitcher.tsx +++ b/apps/desktop/src/components/CwdSwitcher.tsx @@ -1,10 +1,9 @@ -import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; -import { VscChevronRight, VscFolder, VscFolderOpened } from "react-icons/vsc"; +import { useEffect, useRef, useState } from "react"; +import { VscChevronRight, VscCopy, VscFolder, VscFolderOpened } from "react-icons/vsc"; -import { joinPath, parentDirectories } from "../cwd"; -import { Check, ChevronsUpDown, Search } from "../icons"; -import { listSubdirectories } from "../terminalApi"; +import { Check, ChevronsUpDown, PopoverMenu, Search, joinPath, parentDirectories } from "@opencollab/ui"; +import { listSubdirectories } from "../services/terminalApi"; +import { copyTextToClipboard } from "../services/terminalClipboard"; type Props = { cwd: string; @@ -15,27 +14,37 @@ type Props = { /// Con más subcarpetas que esto se muestra un filtro. const FILTER_FROM = 8; +const COPIED_FEEDBACK_MS = 1500; type Subdirs = { state: "loading" } | { state: "error"; message: string } | { state: "ok"; names: string[] }; /// Ruta del header de una terminal: menú para ir hacia atrás (`..`, directorios -/// padre) o hacia adelante (subcarpetas). +/// padre) o hacia adelante (subcarpetas), y acción para copiar la ruta actual. export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) { const [open, setOpen] = useState(false); - const [position, setPosition] = useState<{ left: number; top: number } | null>(null); + const [copied, setCopied] = useState(false); const [subdirs, setSubdirs] = useState({ state: "loading" }); const [filter, setFilter] = useState(""); const buttonRef = useRef(null); - const menuRef = useRef(null); + const copyTimerRef = useRef(null); const parents = parentDirectories(cwd); - // El panel recorta su contenido (overflow: hidden): el menú va en un portal - // con posición fija, debajo del botón. - useLayoutEffect(() => { - if (!open || !buttonRef.current) return; - const r = buttonRef.current.getBoundingClientRect(); - setPosition({ left: r.left, top: r.bottom + 4 }); - }, [open]); + useEffect(() => { + return () => { + if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current); + }; + }, []); + + const copyPath = async () => { + const ok = await copyTextToClipboard(cwd); + if (!ok) return; + setCopied(true); + if (copyTimerRef.current !== null) window.clearTimeout(copyTimerRef.current); + copyTimerRef.current = window.setTimeout(() => { + setCopied(false); + copyTimerRef.current = null; + }, COPIED_FEEDBACK_MS); + }; // Las subcarpetas se piden al abrir: el disco pudo cambiar desde la última vez. useEffect(() => { @@ -51,24 +60,6 @@ export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) { }; }, [open, cwd]); - useEffect(() => { - if (!open) return; - const onDown = (e: PointerEvent) => { - const t = e.target as Node; - if (!menuRef.current?.contains(t) && !buttonRef.current?.contains(t)) setOpen(false); - }; - const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false); - const close = () => setOpen(false); - document.addEventListener("pointerdown", onDown); - document.addEventListener("keydown", onKey); - window.addEventListener("resize", close); - return () => { - document.removeEventListener("pointerdown", onDown); - document.removeEventListener("keydown", onKey); - window.removeEventListener("resize", close); - }; - }, [open]); - // Si la shell deja de estar disponible (arranca un agente), cerrar el menú. useEffect(() => { if (disabledReason) setOpen(false); @@ -99,90 +90,103 @@ export function CwdSwitcher({ cwd, disabledReason, onNavigate }: Props) { {cwd} + - {open && - position && - createPortal( -
-
- - {cwd} - - - -
+ setOpen(false)} anchorRef={buttonRef} align="left"> +
+ + {cwd} + + + +
+ - {/* Hacia adelante: subcarpetas del directorio actual. */} -
-
Subdirectories
- {subdirs.state === "ok" && subdirs.names.length > FILTER_FROM && ( - - )} -
- {subdirs.state === "loading" &&
Cargando…
} - {subdirs.state === "error" && ( -
- No se pudo leer la carpeta -
- )} - {subdirs.state === "ok" && visible.length === 0 && ( -
- {subdirs.names.length === 0 ? "Sin subcarpetas" : "Sin coincidencias"} -
- )} - {visible.map((name) => ( - - ))} + {/* Hacia adelante: subcarpetas del directorio actual. */} +
+
Subdirectories
+ {subdirs.state === "ok" && subdirs.names.length > FILTER_FROM && ( + + )} +
+ {subdirs.state === "loading" &&
Cargando…
} + {subdirs.state === "error" && ( +
+ No se pudo leer la carpeta
+ )} + {subdirs.state === "ok" && visible.length === 0 && ( +
+ {subdirs.names.length === 0 ? "Sin subcarpetas" : "Sin coincidencias"} +
+ )} + {visible.map((name) => ( + + ))} +
- {/* Hacia atrás: `..` y todos los directorios padre. */} - {parents.length > 0 && ( - <> -
-
Parent directories
- - {parents.map((path) => ( - - ))} - - )} -
, - document.body, + {/* Hacia atrás: `..` y todos los directorios padre. */} + {parents.length > 0 && ( + <> +
+
Parent directories
+ + {parents.map((path) => ( + + ))} + )} + ); } diff --git a/apps/desktop/src/components/NewTerminalMenu.tsx b/apps/desktop/src/components/NewTerminalMenu.tsx index 28a1754..50fb94c 100644 --- a/apps/desktop/src/components/NewTerminalMenu.tsx +++ b/apps/desktop/src/components/NewTerminalMenu.tsx @@ -1,12 +1,16 @@ -import { useEffect, useLayoutEffect, useRef, useState } from "react"; -import { createPortal } from "react-dom"; +import { useEffect, useRef, useState } from "react"; import { VscFolderOpened, VscHome } from "react-icons/vsc"; -import { agentInfo, type AgentId } from "../agents"; -import { Plus } from "../icons"; -import { modKey, shiftKey } from "../shortcuts"; -import { availableAgents } from "../terminalApi"; -import { TerminalIcon } from "./TerminalIcon"; +import { + Plus, + PopoverMenu, + TerminalIcon, + agentInfo, + modKey, + shiftKey, + type AgentId, +} from "@opencollab/ui"; +import { availableAgents } from "../services/terminalApi"; type Props = { /// Carpeta actual de la terminal (`null` si todavía no se conoce). @@ -20,18 +24,8 @@ type Props = { /// por defecto, o directamente un agente instalado (corre dentro de la shell). export function NewTerminalMenu({ cwd, onOpen }: Props) { const [open, setOpen] = useState(false); - const [position, setPosition] = useState<{ right: number; top: number } | null>(null); const [agents, setAgents] = useState([]); const buttonRef = useRef(null); - const menuRef = useRef(null); - - // Mismo motivo que en CwdSwitcher: el panel recorta (overflow: hidden), así que - // el menú va en un portal con posición fija, alineado al borde derecho del botón. - useLayoutEffect(() => { - if (!open || !buttonRef.current) return; - const r = buttonRef.current.getBoundingClientRect(); - setPosition({ right: window.innerWidth - r.right, top: r.bottom + 4 }); - }, [open]); // Se consulta al abrir por primera vez (el núcleo lo cachea en `availableAgents`). useEffect(() => { @@ -43,24 +37,6 @@ export function NewTerminalMenu({ cwd, onOpen }: Props) { }; }, [open]); - useEffect(() => { - if (!open) return; - const onDown = (e: PointerEvent) => { - const t = e.target as Node; - if (!menuRef.current?.contains(t) && !buttonRef.current?.contains(t)) setOpen(false); - }; - const onKey = (e: KeyboardEvent) => e.key === "Escape" && setOpen(false); - const close = () => setOpen(false); - document.addEventListener("pointerdown", onDown); - document.addEventListener("keydown", onKey); - window.addEventListener("resize", close); - return () => { - document.removeEventListener("pointerdown", onDown); - document.removeEventListener("keydown", onKey); - window.removeEventListener("resize", close); - }; - }, [open]); - const choose = (dir: string | null, agent?: AgentId) => { setOpen(false); onOpen(dir, agent); @@ -80,53 +56,58 @@ export function NewTerminalMenu({ cwd, onOpen }: Props) { - {open && - position && - createPortal( -
-
New terminal
- - - {agents.length > 0 && ( - <> -
Launch agent{cwd ? " here" : ""}
- {agents.map((id) => ( - - ))} - - )} -
, - document.body, + setOpen(false)} + anchorRef={buttonRef} + align="right" + className="new-terminal-menu" + > +
New terminal
+ + + {agents.length > 0 && ( + <> +
Launch agent{cwd ? " here" : ""}
+ {agents.map((id) => ( + + ))} + )} +
); } diff --git a/apps/desktop/src/components/Onboarding.tsx b/apps/desktop/src/components/Onboarding.tsx new file mode 100644 index 0000000..32ae222 --- /dev/null +++ b/apps/desktop/src/components/Onboarding.tsx @@ -0,0 +1,69 @@ +import { opencollabLogoTransparent, type AuthState } from "@opencollab/ui"; +import type { StorageMode } from "../services/storage"; +import { StorageAuth } from "./StorageAuth"; + +type Props = { + auth: AuthState; + authBusy: boolean; + authError: string | null; + loginUrl: string | null; + busy: boolean; + error: string | null; + onChoose: (mode: StorageMode) => void; + onSignIn: () => void; + onCancelLogin: () => void; +}; + +/// Primera corrida: el usuario elige dónde vive la estructura del escritorio. +/// Cloud exige sesión; ambas opciones persisten la elección antes de entrar. +export function Onboarding(props: Props) { + const signedIn = props.auth.status === "authenticated"; + return ( +
+
+ OpenCollab +

Welcome to OpenCollab

+

Choose where your workspace structure lives.

+ +
+ + +
+ + {!signedIn && ( + + )} + + {props.error && ( +

+ {props.error} +

+ )} +

You can change this later in Settings.

+
+
+ ); +} diff --git a/apps/desktop/src/components/SettingsDialog.tsx b/apps/desktop/src/components/SettingsDialog.tsx new file mode 100644 index 0000000..4777cdb --- /dev/null +++ b/apps/desktop/src/components/SettingsDialog.tsx @@ -0,0 +1,145 @@ +import { useEffect, useState } from "react"; +import { Button, Close, IconButton, type AuthState } from "@opencollab/ui"; + +import type { StorageConfig, StorageMode } from "../services/storage"; +import { StorageAuth } from "./StorageAuth"; + +type Props = { + storage: StorageConfig; + auth: AuthState; + authBusy: boolean; + authError: string | null; + loginUrl: string | null; + busy: boolean; + error: string | null; + onClose: () => void; + onSave: (mode: StorageMode, apiBaseUrl: string) => void; + onSignIn: () => void; + onCancelLogin: () => void; +}; + +/// Ajustes de almacenamiento: modo y base URL de la API. El guardado lo hace +/// el núcleo (valida URL y exige sesión para cloud); acá solo se edita. +export function SettingsDialog(props: Props) { + const [mode, setMode] = useState(props.storage.mode); + const [apiBaseUrl, setApiBaseUrl] = useState(props.storage.apiBaseUrl); + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") props.onClose(); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [props.onClose]); + + const signedIn = props.auth.status === "authenticated"; + const invalidUrl = mode === "cloud" && !/^https?:\/\/\S+$/.test(apiBaseUrl.trim()); + const cloudNeedsLogin = mode === "cloud" && !signedIn; + const saveDisabled = props.busy || invalidUrl || cloudNeedsLogin; + + return ( +
props.onClose()} + > +
e.stopPropagation()} + > +
+

Settings

+ } title="Close settings" onClick={props.onClose} /> +
+ +
+

Storage

+ + +
+ + + + {cloudNeedsLogin && ( +
+

Sign in before switching to cloud storage.

+ +
+ )} + + {props.storage.mode === "local" && mode === "cloud" && ( +

+ Your local workspaces, sessions, and terminals will be migrated to your cloud account. + Local files are kept on this computer. +

+ )} + + {invalidUrl && ( +

+ Enter an absolute http:// or https:// URL. +

+ )} + {props.error && ( +

+ {props.error} +

+ )} + +
+ + +
+
+
+ ); +} diff --git a/apps/desktop/src/components/StorageAuth.tsx b/apps/desktop/src/components/StorageAuth.tsx new file mode 100644 index 0000000..4455a55 --- /dev/null +++ b/apps/desktop/src/components/StorageAuth.tsx @@ -0,0 +1,47 @@ +import { Button, type AuthState } from "@opencollab/ui"; + +type Props = { + auth: AuthState; + busy: boolean; + error: string | null; + loginUrl: string | null; + onSignIn: () => void; + onCancelLogin: () => void; +}; + +/// Bloque de login reutilizado por el onboarding y Settings: el modo nube +/// necesita una sesión, y el login siempre ocurre en el navegador. +export function StorageAuth(props: Props) { + if (props.auth.status === "authenticated") { + return ( +

+ Signed in as {props.auth.user.displayName || props.auth.user.username} +

+ ); + } + if (props.auth.status === "unknown") { + return

Checking session…

; + } + return ( +
+
+ {props.busy ? ( + + ) : ( + + )} + {props.busy ? "Finish sign-in in your browser" : "Sign in to use cloud storage"} +
+ {props.error && ( +

+ {props.error} +

+ )} + {props.busy && props.loginUrl && ( + + Open login page + + )} +
+ ); +} diff --git a/apps/desktop/src/components/TerminalPane.tsx b/apps/desktop/src/components/TerminalPane.tsx index 00a3d14..2bc21ee 100644 --- a/apps/desktop/src/components/TerminalPane.tsx +++ b/apps/desktop/src/components/TerminalPane.tsx @@ -3,26 +3,47 @@ import { Terminal } from "@xterm/xterm"; import { FitAddon } from "@xterm/addon-fit"; import "@xterm/xterm/css/xterm.css"; -import { applyActivity, applyFocus, initialActivity, isWatching, type ActivityState } from "../activity"; -import { agentInfo, type AgentId } from "../agents"; -import type { AgentState } from "../agentState"; -import { useGitBranch } from "../useGitBranch"; -import { useWindowFocus } from "../useWindowFocus"; -import { cdCommand, parseOsc7 } from "../cwd"; -import { Close, Maximize, Minus } from "../icons"; -import { localUser, statusLabel, type PaneMeta, type PaneStatus } from "../model"; -import { IconButton } from "./Button"; +import { + Close, + IconButton, + Maximize, + Minus, + Panel, + PopoverMenu, + TerminalIcon, + agentInfo, + applyActivity, + applyFocus, + cdCommand, + clampMenuPosition, + initialActivity, + isWatching, + localUser, + modKey, + parseOsc7, + statusLabel, + type ActivityState, + type AgentId, + type AgentState, + type PaneMeta, + type PaneStatus, +} from "@opencollab/ui"; +import { useGitBranch } from "../hooks/useGitBranch"; +import { useWindowFocus } from "../hooks/useWindowFocus"; import { CwdSwitcher } from "./CwdSwitcher"; import { NewTerminalMenu } from "./NewTerminalMenu"; -import { Panel } from "./Panel"; -import { TerminalIcon } from "./TerminalIcon"; import { attachTerminal, closeTerminal, openShell, resizeTerminal, writeTerminal, -} from "../terminalApi"; +} from "../services/terminalApi"; +import { + copyTerminalSelection, + createTerminalKeyEventHandler, + pasteFromClipboard, +} from "../services/terminalClipboard"; type Props = { paneId: string; @@ -89,6 +110,11 @@ export function TerminalPane(props: Props) { const branch = useGitBranch(cwd, activityState.activity === "idle"); const [status, setStatus] = useState("starting"); const [error, setError] = useState(null); + const [contextMenu, setContextMenu] = useState<{ + left: number; + top: number; + hasSelection: boolean; + } | null>(null); useEffect(() => onStatus(paneId, status), [paneId, status, onStatus]); useEffect( @@ -131,6 +157,24 @@ export function TerminalPane(props: Props) { const fit = new FitAddon(); term.loadAddon(fit); term.open(container); + term.attachCustomKeyEventHandler(createTerminalKeyEventHandler(term)); + + const onContextMenu = (e: MouseEvent) => { + e.preventDefault(); + props.onFocus(); + const { left, top } = clampMenuPosition( + e.clientX, + e.clientY, + window.innerWidth, + window.innerHeight, + ); + setContextMenu({ + left, + top, + hasSelection: term.hasSelection(), + }); + }; + container.addEventListener("contextmenu", onContextMenu); // fit() con el contenedor oculto (0x0) deja la terminal en 1 columna. const fitIfVisible = () => { @@ -200,6 +244,7 @@ export function TerminalPane(props: Props) { return () => { disposed = true; + container.removeEventListener("contextmenu", onContextMenu); osc7.dispose(); observer.disconnect(); input.dispose(); @@ -290,16 +335,87 @@ export function TerminalPane(props: Props) { ); return ( - props.registerEl(paneId, el)} - className={classes} - hidden={props.hidden} - style={{ order: props.order }} - // pointerdown y no mousedown: el arrastre cancela los eventos de mouse del header. - onPointerDown={props.onFocus} - header={header} - bodyRef={containerRef} - bodyClassName="pane-body" - /> + <> + props.registerEl(paneId, el)} + className={classes} + hidden={props.hidden} + style={{ order: props.order }} + // pointerdown y no mousedown: el arrastre cancela los eventos de mouse del header. + onPointerDown={props.onFocus} + header={header} + bodyRef={containerRef} + bodyClassName="pane-body" + /> + setContextMenu(null)} + position={contextMenu ? { left: contextMenu.left, top: contextMenu.top } : null} + className="term-context-menu" + > + + +
+ + + + ); } diff --git a/apps/desktop/src/hooks/index.ts b/apps/desktop/src/hooks/index.ts new file mode 100644 index 0000000..9421592 --- /dev/null +++ b/apps/desktop/src/hooks/index.ts @@ -0,0 +1,5 @@ +export * from "./useAuth"; +export * from "./useCollabStatus"; +export * from "./useGitBranch"; +export * from "./usePaneDrag"; +export * from "./useWindowFocus"; diff --git a/apps/desktop/src/useAuth.ts b/apps/desktop/src/hooks/useAuth.ts similarity index 99% rename from apps/desktop/src/useAuth.ts rename to apps/desktop/src/hooks/useAuth.ts index 125cdec..5405d92 100644 --- a/apps/desktop/src/useAuth.ts +++ b/apps/desktop/src/hooks/useAuth.ts @@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from "react"; import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; -import { createPkcePair, isAuthCallback, type AuthState, type AuthUser } from "./auth"; +import { createPkcePair, isAuthCallback, type AuthState, type AuthUser } from "../services/auth"; type ChangedPayload = { user: AuthUser | null }; diff --git a/apps/desktop/src/useCollabStatus.ts b/apps/desktop/src/hooks/useCollabStatus.ts similarity index 85% rename from apps/desktop/src/useCollabStatus.ts rename to apps/desktop/src/hooks/useCollabStatus.ts index 91d7260..3fce937 100644 --- a/apps/desktop/src/useCollabStatus.ts +++ b/apps/desktop/src/hooks/useCollabStatus.ts @@ -1,7 +1,7 @@ import { useEffect, useState } from "react"; -import { DEFAULT_COLLAB_STATUS, type CollabStatus } from "./collabStatus"; -import { getCollabStatus, onCollabStatus } from "./terminalApi"; +import { DEFAULT_COLLAB_STATUS, type CollabStatus } from "@opencollab/ui"; +import { getCollabStatus, onCollabStatus } from "../services/terminalApi"; /// Estado real de la status bar: pide el valor actual una vez y después escucha /// los cambios que emite el núcleo. Mientras tanto (o si falla) muestra el diff --git a/apps/desktop/src/useGitBranch.ts b/apps/desktop/src/hooks/useGitBranch.ts similarity index 86% rename from apps/desktop/src/useGitBranch.ts rename to apps/desktop/src/hooks/useGitBranch.ts index fc0df63..5e769bf 100644 --- a/apps/desktop/src/useGitBranch.ts +++ b/apps/desktop/src/hooks/useGitBranch.ts @@ -1,7 +1,7 @@ import { useEffect, useState } from "react"; -import { sameBranch, watchBranch } from "./branchWatch"; -import { gitBranch, type GitBranch } from "./terminalApi"; +import { sameBranch, watchBranch } from "../services/branchWatch"; +import { gitBranch, type GitBranch } from "../services/terminalApi"; /// Rama de git de `cwd` (`null` fuera de un repositorio o si no se conoce la /// carpeta). Se vuelve a consultar al cambiar `cwd`, cada vez que cambia diff --git a/apps/desktop/src/usePaneDrag.ts b/apps/desktop/src/hooks/usePaneDrag.ts similarity index 100% rename from apps/desktop/src/usePaneDrag.ts rename to apps/desktop/src/hooks/usePaneDrag.ts diff --git a/apps/desktop/src/useWindowFocus.ts b/apps/desktop/src/hooks/useWindowFocus.ts similarity index 100% rename from apps/desktop/src/useWindowFocus.ts rename to apps/desktop/src/hooks/useWindowFocus.ts diff --git a/apps/desktop/src/auth.test.ts b/apps/desktop/src/services/auth.test.ts similarity index 91% rename from apps/desktop/src/auth.test.ts rename to apps/desktop/src/services/auth.test.ts index a454467..566bd49 100644 --- a/apps/desktop/src/auth.test.ts +++ b/apps/desktop/src/services/auth.test.ts @@ -3,8 +3,9 @@ import { describe, expect, it } from "vitest"; import { createPkcePair, initialsOf, isAuthCallback, type AuthUser } from "./auth"; describe("isAuthCallback", () => { - it("acepta el callback del desktop", () => { + it("acepta el callback del desktop (producción y dev)", () => { expect(isAuthCallback("opencollab://auth/callback?code=abc123")).toBe(true); + expect(isAuthCallback("opencollab-dev://auth/callback?code=abc123")).toBe(true); }); it("rechaza deep links ajenos", () => { diff --git a/apps/desktop/src/auth.ts b/apps/desktop/src/services/auth.ts similarity index 64% rename from apps/desktop/src/auth.ts rename to apps/desktop/src/services/auth.ts index 008ef9e..ad8486e 100644 --- a/apps/desktop/src/auth.ts +++ b/apps/desktop/src/services/auth.ts @@ -3,24 +3,15 @@ // memoria de este módulo (y en el núcleo tras `auth_begin_login`), los tokens // solo en el núcleo. El núcleo revalida todo antes de canjear. -export interface AuthUser { - id: string; - username: string; - email: string | null; - displayName: string; -} - -export type AuthState = - | { status: "unknown" } - | { status: "anonymous" } - | { status: "authenticated"; user: AuthUser }; +export type { AuthState, AuthUser } from "@opencollab/ui"; +export { initialsOf } from "@opencollab/ui"; /** `true` si la URL es un callback de login del desktop (filtro rápido; el núcleo revalida). */ export function isAuthCallback(url: string): boolean { try { const parsed = new URL(url); return ( - parsed.protocol === "opencollab:" && + (parsed.protocol === "opencollab:" || parsed.protocol === "opencollab-dev:") && parsed.host === "auth" && parsed.pathname === "/callback" && parsed.searchParams.get("code") !== null @@ -43,11 +34,3 @@ export async function createPkcePair(): Promise<{ verifier: string; challenge: s return { verifier, challenge: base64url(new Uint8Array(digest)) }; } -/** Iniciales para el avatar (hasta 2 letras, del nombre visible o del usuario). */ -export function initialsOf(user: AuthUser): string { - const source = user.displayName.trim() || user.username; - const parts = source.split(/\s+/); - const first = parts[0]?.charAt(0) ?? "?"; - const second = parts.length > 1 ? (parts[parts.length - 1]?.charAt(0) ?? "") : ""; - return (first + second).toUpperCase(); -} diff --git a/apps/desktop/src/branchWatch.test.ts b/apps/desktop/src/services/branchWatch.test.ts similarity index 100% rename from apps/desktop/src/branchWatch.test.ts rename to apps/desktop/src/services/branchWatch.test.ts diff --git a/apps/desktop/src/branchWatch.ts b/apps/desktop/src/services/branchWatch.ts similarity index 100% rename from apps/desktop/src/branchWatch.ts rename to apps/desktop/src/services/branchWatch.ts diff --git a/apps/desktop/src/services/index.ts b/apps/desktop/src/services/index.ts new file mode 100644 index 0000000..08c5215 --- /dev/null +++ b/apps/desktop/src/services/index.ts @@ -0,0 +1,3 @@ +export * from "./auth"; +export * from "./branchWatch"; +export * from "./terminalApi"; diff --git a/apps/desktop/src/services/snapshot.test.ts b/apps/desktop/src/services/snapshot.test.ts new file mode 100644 index 0000000..e441f2b --- /dev/null +++ b/apps/desktop/src/services/snapshot.test.ts @@ -0,0 +1,229 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; + +import { invoke } from "@tauri-apps/api/core"; +import { newPane, newSession, newWorkspace } from "@opencollab/ui"; + +import { + flushSnapshotSaves, + fromSavedSnapshot, + saveSnapshot, + toSavedWorkspaces, + type SavedSnapshot, +} from "./snapshot"; + +vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn() })); +const mockedInvoke = vi.mocked(invoke); + +// Espejo del payload camelCase que serializa el núcleo Rust +// (`WorkspaceSnapshot::new` → serde). Candados del formato: solo perfil de +// arranque de las terminales, nunca `env` ni scrollback (A1 del feature). +const saved: SavedSnapshot = { + workspaces: [ + { + id: "ws-1", + name: "trabajo", + sessions: [ + { + id: "session-1", + name: "con pane", + panes: [ + { + id: "pane-1", + seq: 500, + minimized: true, + initialCwd: "C:\\repo", + agent: "claude-code", + }, + ], + }, + { id: "session-2", name: "sin panes", panes: [] }, + ], + }, + ], +}; + +function uiWorkspaceWithSavedPanes() { + const ws = newWorkspace("local"); + ws.members = 3; + ws.sessions.push(newSession("extra")); + ws.sessions[0].panes.push(newPane("C:\\repo", "opencode")); + return ws; +} + +describe("toSavedWorkspaces", () => { + it("deja solo los campos persistentes, con las claves camelCase del núcleo", () => { + const ws = uiWorkspaceWithSavedPanes(); + const [savedWs] = toSavedWorkspaces([ws]); + + // `members` y todo estado volátil de la UI no viajan al snapshot. + expect(savedWs).toEqual({ + id: ws.id, + name: "local", + sessions: [ + { + id: ws.sessions[0].id, + name: "Sesión 1", + panes: [ + { + id: ws.sessions[0].panes[0].id, + seq: ws.sessions[0].panes[0].seq, + minimized: false, + initialCwd: "C:\\repo", + agent: "opencode", + }, + ], + }, + { id: ws.sessions[1].id, name: "extra", panes: [] }, + ], + }); + }); +}); + +describe("fromSavedSnapshot", () => { + beforeEach(() => { + mockedInvoke.mockReset(); + }); + + it("reconstruye workspaces de la UI; `members` vuelve al default local", () => { + const [ws] = fromSavedSnapshot(saved)!; + expect(ws).toEqual({ + id: "ws-1", + name: "trabajo", + members: 1, + sessions: [ + { + id: "session-1", + name: "con pane", + panes: [ + { + id: "pane-1", + seq: 500, + minimized: true, + initialCwd: "C:\\repo", + agent: "claude-code", + }, + ], + }, + { id: "session-2", name: "sin panes", panes: [] }, + ], + }); + }); + + it("rebasa el contador de seq: nuevos paneles no colisionan con los restaurados", () => { + fromSavedSnapshot(saved); + expect(newPane().seq).toBeGreaterThan(500); + }); + + it("un agente que ya no está en el catálogo cae a `null` (shell plana)", () => { + const peninsula = { + ...saved, + workspaces: [ + { + ...saved.workspaces[0], + sessions: [ + { + ...saved.workspaces[0].sessions[0], + panes: [{ ...saved.workspaces[0].sessions[0].panes[0], agent: "agente-fantasma" }], + }, + ], + }, + ], + } satisfies SavedSnapshot; + const [ws] = fromSavedSnapshot(peninsula)!; + expect(ws.sessions[0].panes[0].agent).toBeNull(); + }); + + it("caída a `null` ante un payload inválido", () => { + expect(fromSavedSnapshot(null)).toBeNull(); + expect(fromSavedSnapshot({} as SavedSnapshot)).toBeNull(); + expect(fromSavedSnapshot({ workspaces: [] })).toBeNull(); + expect(fromSavedSnapshot({ workspaces: [null as never] })).toBeNull(); + expect( + fromSavedSnapshot({ + workspaces: [{ id: "ws-1", name: "x", sessions: [{ id: "s-1", name: "y", panes: [{}] as never }] }], + }), + ).toBeNull(); + }); +}); + +describe("loadSnapshot/saveSnapshot", () => { + beforeEach(() => { + mockedInvoke.mockReset(); + }); + + it("sin datos guardados devuelve `null` (primera corrida / arranque limpio)", async () => { + mockedInvoke.mockResolvedValueOnce(null); + expect(await (await import("./snapshot")).loadSnapshot()).toBeNull(); + }); + + it("el guardado siguiente espera al anterior: nunca se cruzan los writes", async () => { + let release: (() => void) | undefined; + let firstDone = false; + try { + const marks: ("after" | "before")[] = []; + mockedInvoke + // Primera escritura que depende de un `release` manual y segunda rápida: + // si el guardado no se encadenara, a la segunda no le importaría la primera. + .mockImplementationOnce( + () => + new Promise((res) => { + release = () => { + firstDone = true; + res(null); + }; + }), + ) + .mockImplementationOnce(() => { + marks.push(firstDone ? "after" : "before"); + return Promise.resolve(null); + }); + const first = saveSnapshot([uiWorkspaceWithSavedPanes()]); + const second = saveSnapshot([]); + // Un turno corto de timers: bastante para que la cola despache al primero + // y encadene al segundo detrás de su resolución. + await new Promise((r) => setTimeout(r, 10)); + expect(mockedInvoke).toHaveBeenCalledTimes(1); + release!(); + await Promise.all([first, second]); + expect(firstDone).toBe(true); + expect(marks).toEqual(["after"]); + expect(mockedInvoke).toHaveBeenCalledTimes(2); + expect(mockedInvoke.mock.calls[0][0]).toBe("snapshot_save"); + expect(mockedInvoke.mock.calls[0][1]).toEqual({ + workspaces: expect.any(Array), + }); + } finally { + release?.(); + await Promise.resolve(); + } + }); + + it("un guardado que falla no bloquea los siguientes", async () => { + mockedInvoke.mockRejectedValueOnce(new Error("disk full")); + const first = saveSnapshot([uiWorkspaceWithSavedPanes()]); + const second = saveSnapshot([uiWorkspaceWithSavedPanes()]); + await expect(first).resolves.toBeUndefined(); + await expect(second).resolves.toBeUndefined(); + expect(mockedInvoke).toHaveBeenCalledTimes(2); + }); + + it("flush espera el guardado en vuelo antes de cambiar de store", async () => { + let release: (() => void) | undefined; + mockedInvoke.mockImplementationOnce( + () => + new Promise((res) => { + release = () => res(null); + }), + ); + const pending = saveSnapshot([uiWorkspaceWithSavedPanes()]); + let flushed = false; + const flush = flushSnapshotSaves().then(() => { + flushed = true; + }); + await new Promise((r) => setTimeout(r, 10)); + expect(flushed).toBe(false); + release!(); + await Promise.all([pending, flush]); + expect(flushed).toBe(true); + }); +}); diff --git a/apps/desktop/src/services/snapshot.ts b/apps/desktop/src/services/snapshot.ts new file mode 100644 index 0000000..6128eb7 --- /dev/null +++ b/apps/desktop/src/services/snapshot.ts @@ -0,0 +1,136 @@ +import { invoke } from "@tauri-apps/api/core"; +import { adoptPaneSeq, isAgentId, type Pane, type Session, type Workspace } from "@opencollab/ui"; + +// Espeja StoredPane/StoredSession/StoredWorkspace del núcleo Rust +// (apps/desktop/core/application/src/storage.ts): solo el perfil de arranque +// de las terminales, nunca `env` ni scrollback (regla A1 del feature +// desktop-dual-storage). El `SNAPSHOT_VERSION` lo maneja el núcleo: acá viaja +// solo el array de workspaces. +export type SavedPane = { + id: string; + seq: number; + minimized: boolean; + initialCwd: string | null; + agent: string | null; +}; + +export type SavedSession = { id: string; name: string; panes: SavedPane[] }; + +export type SavedWorkspace = { id: string; name: string; sessions: SavedSession[] }; + +export type SavedSnapshot = { workspaces: SavedWorkspace[] }; + +const savedPaneOf = (pane: Pane): SavedPane => ({ + id: pane.id, + seq: pane.seq, + minimized: pane.minimized, + initialCwd: pane.initialCwd, + agent: pane.agent, +}); + +const savedSessionOf = (session: Session): SavedSession => ({ + id: session.id, + name: session.name, + panes: session.panes.map(savedPaneOf), +}); + +export function toSavedWorkspaces(workspaces: Workspace[]): SavedWorkspace[] { + return workspaces.map((ws) => ({ + id: ws.id, + name: ws.name, + // `members` (y cualquier otro estado volátil de la UI) queda fuera del snapshot. + sessions: ws.sessions.map(savedSessionOf), + })); +} + +function isRecord(value: unknown): value is Record { + return typeof value === "object" && value !== null; +} + +function paneOf(raw: unknown): Pane | null { + if (!isRecord(raw)) return null; + const { id, seq, minimized, initialCwd, agent } = raw; + if (typeof id !== "string" || typeof seq !== "number" || typeof minimized !== "boolean") + return null; + if (initialCwd !== null && typeof initialCwd !== "string") return null; + if (agent !== null && typeof agent !== "string") return null; + // Un agente que ya no existe en el catálogo (snapshot viejo) pasa a + // `null`: la terminal apertura plana en vez de romper la UI. + return { id, seq, minimized, initialCwd, agent: isAgentId(agent) ? agent : null }; +} + +function sessionOf(raw: unknown): Session | null { + if (!isRecord(raw)) return null; + const { id, name, panes } = raw; + if (typeof id !== "string" || typeof name !== "string" || !Array.isArray(panes)) return null; + const restored: Pane[] = []; + for (const item of panes) { + const pane = paneOf(item); + if (!pane) return null; + // Los seq restaurados reservan su lugar: los `newPane` de esta corrida + // generan seq mayores y no chocan (el orden visual del grid queda estable). + adoptPaneSeq(pane.seq); + restored.push(pane); + } + return { id, name, panes: restored }; +} + +function workspaceOf(raw: unknown): Workspace | null { + if (!isRecord(raw)) return null; + const { id, name, sessions } = raw; + if (typeof id !== "string" || typeof name !== "string" || !Array.isArray(sessions)) return null; + const restored: Session[] = []; + for (const item of sessions) { + const session = sessionOf(item); + if (!session) return null; + restored.push(session); + } + return { id, name, members: 1, sessions: restored }; +} + +/// Reconstruye los workspaces de la UI desde el payload del núcleo. +/// Todo payload inválido cae a `null` y quien llama arranca con el default: +/// el archivo lo valida antes Rust (quarentena de lo ilegible/versión futura), +/// así que acá solo queda blindarse ante un shape inesperado. +export function fromSavedSnapshot(saved: unknown): Workspace[] | null { + if (!isRecord(saved) || !Array.isArray(saved.workspaces) || saved.workspaces.length === 0) + return null; + const restored: Workspace[] = []; + for (const item of saved.workspaces) { + const ws = workspaceOf(item); + if (!ws) return null; + restored.push(ws); + } + return restored; +} + +/// Snapshot guardado del arranque anterior; `null` si no hay nada (primera +/// corrida, arranque limpio o cuarentena del último archivo corrupto). +export async function loadSnapshot(): Promise { + const saved = await invoke("snapshot_load"); + return fromSavedSnapshot(saved); +} + +// Los guardados se encadenan: el snapshot chico escribe en milisegundos, pero +// dos writes concurrentes sobre el mismo archivo no deben cruzarse jamás. +let saveQueue: Promise = Promise.resolve(); + +/// Espera los guardados ya encolados antes de cambiar de store: un write +/// pendiente del modo viejo nunca debe aterrizar en el store nuevo. +export function flushSnapshotSaves(): Promise { + return saveQueue.then(() => undefined); +} + +/// Guarda el estado persistente de los workspaces. Nunca rechaza: un error del +/// disco no debe tumbar la app (el próximo guardado lo reintenta igual). +export async function saveSnapshot(workspaces: Workspace[]): Promise { + const saved = toSavedWorkspaces(workspaces); + const next = saveQueue + .then(() => invoke("snapshot_save", { workspaces: saved })) + .then( + () => undefined, + (error) => console.error("no se pudo guardar el snapshot:", error), + ); + saveQueue = next; + return next; +} diff --git a/apps/desktop/src/services/storage.ts b/apps/desktop/src/services/storage.ts new file mode 100644 index 0000000..509b186 --- /dev/null +++ b/apps/desktop/src/services/storage.ts @@ -0,0 +1,29 @@ +import { invoke } from "@tauri-apps/api/core"; + +export type StorageMode = "local" | "cloud"; + +export type StorageConfig = { + version: number; + mode: StorageMode; + apiBaseUrl: string; + onboardingComplete: boolean; +}; + +/// Fallback para navegador/E2E sin núcleo: mismo default que Rust. +export const DEFAULT_STORAGE_CONFIG: StorageConfig = { + version: 1, + mode: "local", + apiBaseUrl: "http://127.0.0.1:8787", + onboardingComplete: false, +}; + +export function loadStorageConfig(): Promise { + return invoke("storage_config_get"); +} + +export function saveStorageConfig( + mode: StorageMode, + apiBaseUrl: string, +): Promise { + return invoke("storage_config_set", { mode, apiBaseUrl }); +} diff --git a/apps/desktop/src/terminalApi.ts b/apps/desktop/src/services/terminalApi.ts similarity index 97% rename from apps/desktop/src/terminalApi.ts rename to apps/desktop/src/services/terminalApi.ts index fcf4028..96ae178 100644 --- a/apps/desktop/src/terminalApi.ts +++ b/apps/desktop/src/services/terminalApi.ts @@ -3,9 +3,7 @@ import { invoke } from "@tauri-apps/api/core"; import { listen } from "@tauri-apps/api/event"; -import type { AgentId } from "./agents"; -import type { AgentState } from "./agentState"; -import { parseCollabStatus, type CollabStatus } from "./collabStatus"; +import { parseCollabStatus, type AgentId, type AgentState, type CollabStatus } from "@opencollab/ui"; type OutputPayload = { terminalId: string; data: number[] }; type ExitPayload = { terminalId: string }; diff --git a/apps/desktop/src/services/terminalClipboard.test.ts b/apps/desktop/src/services/terminalClipboard.test.ts new file mode 100644 index 0000000..724b1ab --- /dev/null +++ b/apps/desktop/src/services/terminalClipboard.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it, vi } from "vitest"; + +import { + copyTextToClipboard, + createTerminalKeyEventHandler, + pasteFromClipboard, + type ClipboardAdapter, + type TerminalLike, +} from "./terminalClipboard"; + +function makeTerm(selection = ""): TerminalLike & { + pasted: string[]; + clearedSelection: number; + selectedAll: number; + clearedBuffer: number; +} { + let currentSelection = selection; + const term = { + pasted: [] as string[], + clearedSelection: 0, + selectedAll: 0, + clearedBuffer: 0, + hasSelection: () => currentSelection.length > 0, + getSelection: () => currentSelection, + clearSelection: () => { + currentSelection = ""; + term.clearedSelection += 1; + }, + paste: (data: string) => { + term.pasted.push(data); + }, + selectAll: () => { + term.selectedAll += 1; + }, + clear: () => { + term.clearedBuffer += 1; + }, + }; + return term; +} + +function makeKeyEvent( + overrides: Partial & { key: string }, +): KeyboardEvent & { defaultPrevented: boolean } { + const event = { + type: "keydown", + ctrlKey: false, + metaKey: false, + shiftKey: false, + altKey: false, + defaultPrevented: false, + preventDefault() { + this.defaultPrevented = true; + }, + ...overrides, + }; + return event as unknown as KeyboardEvent & { defaultPrevented: boolean }; +} + +describe("terminalClipboard", () => { + it("Ctrl+C with active selection copies text, clears selection, and blocks SIGINT", async () => { + const term = makeTerm("hello world"); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue(""), + }; + const handler = createTerminalKeyEventHandler(term, clipboard); + const event = makeKeyEvent({ key: "c", ctrlKey: true }); + + const allowXterm = handler(event); + + expect(allowXterm).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledWith("hello world"); + expect(term.clearedSelection).toBe(1); + }); + + it("Ctrl+C without selection passes through to xterm so SIGINT reaches the PTY", () => { + const term = makeTerm(""); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue(""), + }; + const handler = createTerminalKeyEventHandler(term, clipboard); + const event = makeKeyEvent({ key: "c", ctrlKey: true }); + + const allowXterm = handler(event); + + expect(allowXterm).toBe(true); + expect(clipboard.writeText).not.toHaveBeenCalled(); + }); + + it("Ctrl+Shift+C always blocks PTY input and copies when selection exists", () => { + const termWithSel = makeTerm("selected output"); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue(""), + }; + const handlerWithSel = createTerminalKeyEventHandler(termWithSel, clipboard); + + expect(handlerWithSel(makeKeyEvent({ key: "C", ctrlKey: true, shiftKey: true }))).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledWith("selected output"); + expect(termWithSel.clearedSelection).toBe(1); + + const termEmpty = makeTerm(""); + const handlerEmpty = createTerminalKeyEventHandler(termEmpty, clipboard); + expect(handlerEmpty(makeKeyEvent({ key: "C", ctrlKey: true, shiftKey: true }))).toBe(false); + expect(clipboard.writeText).toHaveBeenCalledTimes(1); + }); + + it("Ctrl+V and Ctrl+Shift+V prevent default browser paste, read clipboard, and paste into terminal", async () => { + const term = makeTerm(""); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue("npm test"), + }; + const handler = createTerminalKeyEventHandler(term, clipboard); + const ctrlV = makeKeyEvent({ key: "v", ctrlKey: true }); + + const allowXterm = handler(ctrlV); + + expect(allowXterm).toBe(false); + expect(ctrlV.defaultPrevented).toBe(true); + await vi.waitFor(() => { + expect(term.pasted).toEqual(["npm test"]); + }); + + const ctrlShiftV = makeKeyEvent({ key: "V", ctrlKey: true, shiftKey: true }); + expect(handler(ctrlShiftV)).toBe(false); + expect(ctrlShiftV.defaultPrevented).toBe(true); + await vi.waitFor(() => { + expect(term.pasted).toEqual(["npm test", "npm test"]); + }); + }); + + it("copyTextToClipboard and pasteFromClipboard handle clipboard operations safely", async () => { + const term = makeTerm(""); + const clipboard: ClipboardAdapter = { + writeText: vi.fn().mockResolvedValue(undefined), + readText: vi.fn().mockResolvedValue("copied path"), + }; + + expect(await copyTextToClipboard("C:\\Users\\facun", clipboard)).toBe(true); + expect(clipboard.writeText).toHaveBeenCalledWith("C:\\Users\\facun"); + + await pasteFromClipboard(term, clipboard); + expect(term.pasted).toEqual(["copied path"]); + }); +}); diff --git a/apps/desktop/src/services/terminalClipboard.ts b/apps/desktop/src/services/terminalClipboard.ts new file mode 100644 index 0000000..daa4942 --- /dev/null +++ b/apps/desktop/src/services/terminalClipboard.ts @@ -0,0 +1,107 @@ +export interface ClipboardAdapter { + writeText(text: string): Promise; + readText(): Promise; +} + +export interface TerminalLike { + hasSelection(): boolean; + getSelection(): string; + clearSelection(): void; + paste(data: string): void; + selectAll(): void; + clear(): void; +} + +const defaultClipboard: ClipboardAdapter = { + writeText: async (text: string) => { + if (typeof navigator !== "undefined" && navigator.clipboard?.writeText) { + await navigator.clipboard.writeText(text); + } + }, + readText: async () => { + if (typeof navigator !== "undefined" && navigator.clipboard?.readText) { + return navigator.clipboard.readText(); + } + return ""; + }, +}; + +export async function copyTextToClipboard( + text: string, + clipboard: ClipboardAdapter = defaultClipboard, +): Promise { + if (!text) return false; + try { + await clipboard.writeText(text); + return true; + } catch { + return false; + } +} + +export function copyTerminalSelection( + term: TerminalLike, + clipboard: ClipboardAdapter = defaultClipboard, +): boolean { + if (!term.hasSelection()) return false; + const selection = term.getSelection(); + if (!selection) return false; + void copyTextToClipboard(selection, clipboard); + term.clearSelection(); + return true; +} + +export async function pasteFromClipboard( + term: TerminalLike, + clipboard: ClipboardAdapter = defaultClipboard, +): Promise { + try { + const text = await clipboard.readText(); + if (text) term.paste(text); + } catch { + // El permiso de portapapeles puede fallar o estar vacío; se ignora sin romper la sesión. + } +} + +/// Manejador para `term.attachCustomKeyEventHandler`: +/// - `Ctrl+C` / `Cmd+C` con selección activa copia al portapapeles y evita mandar `SIGINT` (`\x03`). +/// - `Ctrl+C` / `Cmd+C` sin selección deja pasar el evento para interrumpir el proceso en el PTY. +/// - `Ctrl+Shift+C` siempre actúa como atajo explícito de copia y nunca envía `SIGINT`. +/// - `Ctrl+V` / `Ctrl+Shift+V` pega desde el portapapeles usando `term.paste` sin enviar `\x16`. +export function createTerminalKeyEventHandler( + term: TerminalLike, + clipboard: ClipboardAdapter = defaultClipboard, +): (e: KeyboardEvent) => boolean { + return (e: KeyboardEvent): boolean => { + const mod = e.ctrlKey || e.metaKey; + if (!mod || e.altKey) return true; + + const key = e.key.toLowerCase(); + + if (key === "c") { + if (e.shiftKey) { + if (e.type === "keydown") { + copyTerminalSelection(term, clipboard); + } + return false; + } + if (term.hasSelection()) { + if (e.type === "keydown") { + copyTerminalSelection(term, clipboard); + } + return false; + } + return true; + } + + if (key === "v") { + e.preventDefault(); + if (e.type === "keydown") { + void pasteFromClipboard(term, clipboard); + } + return false; + } + + return true; + }; +} diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.css index b162505..17d7125 100644 --- a/apps/desktop/src/styles.css +++ b/apps/desktop/src/styles.css @@ -228,6 +228,12 @@ kbd { color: var(--text-muted); } +.ws-meta[data-collab-inactive="true"], +.user--collab-inactive .user-status, +.statusbar-item--inactive { + color: var(--text-faint); +} + .ws-menu { position: absolute; z-index: 10; @@ -420,11 +426,19 @@ kbd { debajo calcularía el codo sobre el alto de toda la lista y apuntaría al medio en vez de a su terminal. */ --thread-row: 26px; + --thread-sub-row: 22px; + --thread-gap: 6px; list-style: none; margin: 0 0 6px; padding: 0; } +.thread:not(.thread--sub) { + display: flex; + flex-direction: column; + gap: var(--thread-gap); +} + .thread li { position: relative; padding-left: calc(var(--thread-x) + 16px); @@ -445,31 +459,49 @@ kbd { } /* Continuación vertical hacia la siguiente rama. */ -.thread li:not(:last-child)::after { +.thread > li:not(:last-child)::after { content: ""; position: absolute; left: var(--thread-x); /* Arranca donde empieza la curva del codo (su radio es 8px), no donde termina: si no, la línea recta queda cortada a la altura de cada rama. */ top: calc(min(50%, var(--thread-row)) - 8px); - bottom: -1px; + bottom: calc(-1 * var(--thread-gap) - 1px); + border-left: var(--thread-line); +} + +/* Si la última terminal tiene una rama de git o sub-hilo, la línea vertical + debe continuar hasta el codo de la rama hija sin sobrepasar la fila. */ +.thread > li:last-child:has(.thread--sub)::after { + content: ""; + position: absolute; + left: var(--thread-x); + top: calc(min(50%, var(--thread-row)) - 8px); + bottom: calc(var(--thread-sub-row) / 2); border-left: var(--thread-line); } -/* El primer tramo no tiene nada arriba con qué superponerse. */ -.thread li:first-child::before { +/* El primer tramo de la sesión no tiene nada arriba con qué superponerse. */ +.thread:not(.thread--sub) > li:first-child::before { top: 0; height: min(50%, var(--thread-row)); border-top-left-radius: 2px; } /* Nivel interno del hilo: la rama de git que cuelga de la terminal de arriba. - Hereda el codo de `.thread`, con menos sangría, una fila más baja y un cuerpo - chico para que se lea como hijo y no como otra terminal. */ + Alinea su codo horizontalmente con el tallo de la terminal padre (cancela + el padding heredado del li contenedor) y mantiene el cuerpo y fila más chicos + para leerse como detalle hijo sin desbordar el ancho del panel. */ .thread--sub { - --thread-x: 8px; - --thread-row: 22px; + --thread-x: 12px; + --thread-row: var(--thread-sub-row, 22px); + --thread-gap: 0px; margin: 0; + margin-left: calc(-1 * (var(--thread-x) + 16px)); +} + +.thread--sub li { + padding-left: calc(var(--thread-x) + 16px); } .thread--sub .thread-item { @@ -478,6 +510,14 @@ kbd { color: var(--text-faint); } +.thread-branch { + width: 100%; +} + +.thread-branch svg { + flex: none; +} + .thread-item { display: flex; align-items: center; @@ -491,6 +531,10 @@ kbd { text-align: left; } +.thread-item--has-uptime { + padding-right: 44px; +} + .thread-item:hover { background: var(--surface-2); color: var(--text); @@ -804,6 +848,7 @@ kbd { .terminal-icon--logo { display: inline-block; background-color: var(--text); + -webkit-mask: var(--logo) center / contain no-repeat; mask: var(--logo) center / contain no-repeat; } @@ -1051,3 +1096,407 @@ button.cwd-item:hover { .new-terminal-label { flex: none; } + +/* ---------- ThreadMeta (línea secundaria y badge absoluto de uptime) ---------- */ + +.thread-meta { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 2px 6px; + padding: 0 8px 4px; + font-size: 11px; + line-height: 1.4; + color: var(--text-faint); +} + +.thread-meta-part { + display: inline-flex; + align-items: center; + gap: 4px; + white-space: nowrap; +} + +/* Estado del agente junto al título: "Claude Code · Working". El nombre se recorta antes que el estado. */ +.thread-heading { + display: flex; + flex: 1; + align-items: center; + min-width: 0; +} + +.thread-heading .thread-label { + flex: 0 1 auto; +} + +.thread-state { + display: inline-flex; + align-items: center; + gap: 4px; + flex: 0 100 auto; + min-width: 0; + color: var(--text-faint); +} + +.thread-state-sep { + white-space: pre; +} + +.thread-state-label { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.thread-state svg { + flex: none; +} + +.thread-state--working { + color: var(--text-muted); +} + +.thread-state--working svg { + color: var(--accent-soft); + animation: thread-meta-pulse 1.4s ease-in-out infinite; +} + +/* Pide que se mire la terminal o que se apruebe algo: resalta con el acento. */ +.thread-state--attention, +.thread-state--approval { + color: var(--accent-soft); + font-weight: 600; +} + +.thread-state--error { + color: var(--red); + font-weight: 600; +} + +/* Herramienta en curso (`Bash: echo hi`) o detalle del error: una línea, recortada. */ +.thread-meta-tool { + min-width: 0; + max-width: 100%; + overflow: hidden; + text-overflow: ellipsis; + font-family: var(--mono); +} + +@keyframes thread-meta-pulse { + 50% { + opacity: 0.35; + } +} + +@media (prefers-reduced-motion: reduce) { + .thread-state--working svg { + animation: none; + } +} + +/* Cuando solo muestra el tiempo (sin herramienta activa), no ocupa espacio en el flujo. */ +.thread-meta--uptime-only { + padding: 0; + margin: 0; + height: 0; + line-height: 0; +} + +/* Tiempo transcurrido: en la esquina superior derecha de cada terminal del sidebar, + con posición absoluta y con el color del contenedor (var(--surface-2)). */ +.thread-meta-uptime { + position: absolute; + top: 5px; + right: 6px; + display: inline-flex; + align-items: center; + justify-content: center; + height: 16px; + padding: 0 5px; + border-radius: 4px; + background: var(--surface-2); + border: 1px solid var(--border); + font-family: var(--mono); + font-size: 10px; + font-weight: 500; + line-height: 1; + color: var(--text-muted); + pointer-events: none; + z-index: 2; + white-space: nowrap; +} + +/* El badge absoluto no lleva separador con viñeta. */ +.thread-meta-part + .thread-meta-uptime::before { + content: none; + margin: 0; +} + +/* Al enfocar o pasar el cursor sobre la terminal, destacar el badge sutilmente. */ +.thread-item:hover ~ .thread-meta .thread-meta-uptime, +.thread-item--focused ~ .thread-meta .thread-meta-uptime { + border-color: var(--border-strong); + color: var(--text); +} + +/* Separador entre partes de la línea secundaria: "Bash: echo hi · ...". */ +.thread-meta-part + .thread-meta-part:not(.thread-meta-uptime)::before { + content: "·"; + margin-right: 6px; + color: var(--text-faint); +} + + +/* ---------- Onboarding y ajustes de almacenamiento ---------- */ + +.boot { + display: grid; + place-items: center; + height: 100%; + color: var(--text-muted); +} + +.onboarding { + display: grid; + place-items: center; + min-height: 100%; + padding: 32px; + background: + radial-gradient(circle at 50% 20%, rgba(124, 92, 255, 0.16), transparent 55%), + var(--bg); +} + +.onboarding-card { + width: min(560px, 100%); + padding: 28px; + border: 1px solid var(--border); + border-radius: 12px; + background: var(--surface); + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.35); +} + +.onboarding-logo { + width: 64px; + height: 64px; + margin-bottom: 12px; + filter: drop-shadow(0 0 18px rgba(124, 92, 255, 0.35)); +} + +.onboarding-card h1 { + margin: 0 0 6px; + font-size: 24px; +} + +.onboarding-lead, +.onboarding-footnote { + margin: 0; + color: var(--text-muted); +} + +.onboarding-modes { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + margin: 20px 0; +} + +.onboarding-mode { + display: flex; + flex-direction: column; + gap: 6px; + padding: 14px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface-2); + text-align: left; +} + +.onboarding-mode:hover:not(:disabled) { + border-color: var(--accent); + background: var(--surface-3); +} + +.onboarding-mode span { + color: var(--text-muted); + font-size: 12px; + line-height: 1.4; +} + +.onboarding-footnote { + margin-top: 16px; + font-size: 11px; +} + +.onboarding-actions { + display: flex; + flex-wrap: wrap; + gap: 8px; + margin-top: 16px; +} + +.storage-auth { + display: flex; + flex-direction: column; + gap: 8px; + padding: 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + background: var(--surface-2); + color: var(--text-muted); + font-size: 12px; +} + +.storage-auth--ok { + color: var(--green); +} + +.storage-auth-row { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.modal-backdrop { + position: fixed; + inset: 0; + z-index: 50; + display: grid; + place-items: center; + padding: 24px; + background: rgba(0, 0, 0, 0.62); +} + +.modal { + display: flex; + flex-direction: column; + gap: 18px; + width: min(520px, 100%); + max-height: calc(100vh - 48px); + overflow-y: auto; + padding: 20px; + border: 1px solid var(--border-strong); + border-radius: 12px; + background: var(--surface); + box-shadow: 0 24px 60px rgba(0, 0, 0, 0.45); +} + +.modal-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.modal-head h2 { + margin: 0; + font-size: 18px; +} + +.modal-section h3 { + margin: 0 0 8px; + color: var(--text-muted); + font-size: 11px; + font-weight: 600; + letter-spacing: 0.06em; + text-transform: uppercase; +} + +.settings-mode { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: var(--radius); + cursor: pointer; +} + +.settings-mode + .settings-mode { + margin-top: 8px; +} + +.settings-mode:has(input:checked) { + border-color: var(--accent); + background: rgba(124, 92, 255, 0.08); +} + +.settings-mode input { + margin-top: 3px; + accent-color: var(--accent); +} + +.settings-mode span { + display: flex; + flex-direction: column; + gap: 3px; +} + +.settings-mode small, +.settings-field small { + color: var(--text-muted); + font-size: 11px; +} + +.settings-field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.settings-field > span { + font-weight: 500; +} + +.settings-field input { + height: 32px; + padding: 0 10px; + border: 1px solid var(--border-strong); + border-radius: var(--radius); + background: var(--surface-2); + color: var(--text); + font: inherit; +} + +.settings-field input:focus { + outline: none; + border-color: var(--accent); +} + +.settings-auth { + display: flex; + flex-direction: column; + gap: 8px; +} + +.settings-warning, +.settings-error { + margin: 0; + font-size: 12px; +} + +.settings-hint { + margin: 0; + color: var(--text-muted); + font-size: 12px; + line-height: 1.4; +} + +.settings-warning { + color: var(--amber); +} + +.settings-error { + color: var(--red); +} + +.modal-actions { + display: flex; + justify-content: flex-end; + gap: 8px; +} + +@media (max-width: 520px) { + .onboarding-modes { + grid-template-columns: 1fr; + } +} diff --git a/apps/server/Dockerfile b/apps/server/Dockerfile deleted file mode 100644 index ec51782..0000000 --- a/apps/server/Dockerfile +++ /dev/null @@ -1,32 +0,0 @@ -# syntax=docker/dockerfile:1 -# Relay server image. Build context: apps/server. - -FROM node:24-slim AS build -WORKDIR /app -RUN corepack enable -COPY package.json pnpm-lock.yaml pnpm-workspace.yaml ./ -COPY prisma ./prisma -COPY prisma.config.ts tsconfig.json tsconfig.build.json ./ -# postinstall runs `prisma generate`: it needs the schema, config and tsconfig (the latter decides the import extensions it emits). -RUN pnpm install --frozen-lockfile -COPY src ./src -RUN pnpm build - -FROM node:24-slim -ENV NODE_ENV=production \ - RELAY_ADDR=0.0.0.0:8787 -# Prisma detects the libssl version through openssl, which slim images lack. -RUN apt-get update && apt-get install -y --no-install-recommends openssl \ - && rm -rf /var/lib/apt/lists/* -WORKDIR /app -# The Prisma CLI (a devDependency) stays in node_modules: it applies the -# migrations on startup, so the whole tree is copied instead of pruned. -COPY --from=build --chown=node:node /app/node_modules ./node_modules -COPY --from=build --chown=node:node /app/dist ./dist -COPY --from=build --chown=node:node /app/prisma ./prisma -COPY --from=build --chown=node:node /app/prisma.config.ts /app/package.json ./ -USER node -EXPOSE 8787 -HEALTHCHECK --interval=10s --timeout=3s --start-period=20s --retries=5 \ - CMD ["node", "-e", "fetch('http://127.0.0.1:8787/health').then(r=>r.text()).then(t=>process.exit(t==='ok'?0:1)).catch(()=>process.exit(1))"] -CMD ["sh", "-c", "node_modules/.bin/prisma migrate deploy && exec node dist/main.js"] diff --git a/apps/server/pnpm-workspace.yaml b/apps/server/pnpm-workspace.yaml deleted file mode 100644 index 20f1888..0000000 --- a/apps/server/pnpm-workspace.yaml +++ /dev/null @@ -1,5 +0,0 @@ -allowBuilds: - '@prisma/engines': true - argon2: false - esbuild: true - prisma: true diff --git a/apps/server/src/domain/terminal.ts b/apps/server/src/domain/terminal.ts deleted file mode 100644 index 5ae69d4..0000000 --- a/apps/server/src/domain/terminal.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { DomainError } from './error'; -import type { TerminalId } from './ids'; - -// How to launch an agent (or a shell). Agnostic: any CLI is a profile. -export interface AgentProfile { - readonly name: string; - readonly command: string; - readonly args: string[]; - readonly env: [string, string][]; - readonly cwd?: string; -} - -export function newAgentProfile( - name: string, - command: string, - opts: { args?: string[]; env?: [string, string][]; cwd?: string } = {}, -): AgentProfile { - if (command.trim() === '') throw new DomainError({ code: 'EmptyCommand' }); - // Copies, so the caller keeps no handle on the profile's internals. - const args = [...(opts.args ?? [])]; - const env = (opts.env ?? []).map(([k, v]): [string, string] => [k, v]); - const profile = { name, command, args, env }; - return opts.cwd === undefined ? profile : { ...profile, cwd: opts.cwd }; -} - -// A PTY inside a session running an `AgentProfile`. -export interface Terminal { - readonly id: TerminalId; - readonly profile: AgentProfile; -} diff --git a/apps/server/src/persistence/index.ts b/apps/server/src/persistence/index.ts deleted file mode 100644 index 1cab84f..0000000 --- a/apps/server/src/persistence/index.ts +++ /dev/null @@ -1,6 +0,0 @@ -export * from './invitation.repository'; -export * from './prisma'; -export * from './session-store'; -export * from './session.repository'; -export * from './user.repository'; -export * from './workspace.repository'; diff --git a/apps/server/src/protocol.ts b/apps/server/src/protocol.ts deleted file mode 100644 index ed3d07b..0000000 --- a/apps/server/src/protocol.ts +++ /dev/null @@ -1,129 +0,0 @@ -// Wire contract: TS mirror of `crates/protocol` (Envelope/Message). -// The Rust domain stays authoritative for the RULES; this file owns the Nest -// side of the BYTES until `packages/contracts` becomes the single source. -// IDs travel as UUID strings. PROTOCOL_VERSION must match the desktop. - -export const PROTOCOL_VERSION = 1; - -/** snake_case on the wire, mirroring `AccessLevelDto`. */ -export type AccessLevelDto = 'none' | 'view' | 'write'; - -export type Message = - | { - type: 'terminal_output'; - session_id: string; - terminal_id: string; - /** Vec serializes as a JSON number array. */ - data: number[]; - } - | { - type: 'terminal_input'; - session_id: string; - terminal_id: string; - user_id: string; - data: number[]; - } - | { - type: 'access_changed'; - session_id: string; - user_id: string; - access: AccessLevelDto; - } - /** Client -> server: subscribe this connection to a session. */ - | { type: 'join_session'; session_id: string } - /** Server -> client: join accepted, with the access in force right now. */ - | { type: 'joined'; session_id: string; access: AccessLevelDto } - /** Client -> server: a fresh access token to keep the socket alive (never the refresh token). */ - | { type: 'reauth'; token: string } - /** Server -> client: renewal accepted; `expires_at` is unix seconds. */ - | { type: 'reauthenticated'; expires_at: number }; - -export interface Envelope { - version: number; - message: Message; -} - -export const INCOMPATIBLE_PROTOCOL_VERSION = '{"error":"incompatible_protocol_version"}'; -export const INVALID_MESSAGE = '{"error":"invalid_message"}'; -/** Also answers unknown sessions, so existence is not revealed. */ -export const FORBIDDEN = '{"error":"forbidden"}'; -export const NOT_JOINED = '{"error":"not_joined"}'; -/** A `reauth` token that is invalid or belongs to another user. */ -export const UNAUTHORIZED = '{"error":"unauthorized"}'; - -type Fields = Record; - -const isObject = (value: unknown): value is Fields => - typeof value === 'object' && value !== null && !Array.isArray(value); - -const isString = (value: unknown): value is string => typeof value === 'string'; - -const isUint = (value: unknown, max: number): boolean => - typeof value === 'number' && Number.isInteger(value) && value >= 0 && value <= max; - -const isBytes = (value: unknown): boolean => - Array.isArray(value) && value.every((byte) => isUint(byte, 255)); - -const ACCESS_LEVELS: readonly unknown[] = ['none', 'view', 'write']; - -/** Same shape check serde runs for `Message`; unknown fields are ignored. */ -function isMessage(value: unknown): value is Message { - if (!isObject(value)) return false; - // The only messages that are not about a session. - if (value.type === 'reauth') return isString(value.token); - if (value.type === 'reauthenticated') return isUint(value.expires_at, Number.MAX_SAFE_INTEGER); - if (!isString(value.session_id)) return false; - switch (value.type) { - case 'terminal_output': - return isString(value.terminal_id) && isBytes(value.data); - case 'terminal_input': - return isString(value.terminal_id) && isString(value.user_id) && isBytes(value.data); - case 'access_changed': - return isString(value.user_id) && ACCESS_LEVELS.includes(value.access); - case 'join_session': - return true; - case 'joined': - return ACCESS_LEVELS.includes(value.access); - default: - return false; - } -} - -/** Equivalent of `serde_json::from_str::` succeeding (`version: u16`). */ -function isEnvelope(value: unknown): value is Envelope { - return isObject(value) && isUint(value.version, 0xffff) && isMessage(value.message); -} - -/** - * `JSON.parse` turns `1.0` and `1e0` into the integer 1, but serde rejects - * them for integer fields. Every number in the wire is an integer, so a - * number whose source text is not an integer literal becomes NaN and fails - * the integer checks (the reviver context needs Node 21+; CI runs Node 24). - */ -function parseWire(text: string): unknown { - return JSON.parse(text, (_key, value: unknown, context?: { source?: string }) => - typeof value === 'number' && context?.source !== undefined && !/^-?\d+$/.test(context.source) - ? Number.NaN - : value, - ); -} - -export type ParsedFrame = { ok: true; envelope: Envelope } | { ok: false; error: string }; - -/** - * Same acceptance rules as the Rust relay: a frame that does not deserialize - * into a complete `Envelope` is a message error and an envelope of another - * version is a version error. Routing the accepted message is the hub's job, - * which forwards the ORIGINAL text rather than a re-serialization. - */ -export function parseFrame(text: string): ParsedFrame { - let parsed: unknown; - try { - parsed = parseWire(text); - } catch { - return { ok: false, error: INVALID_MESSAGE }; - } - if (!isEnvelope(parsed)) return { ok: false, error: INVALID_MESSAGE }; - if (parsed.version !== PROTOCOL_VERSION) return { ok: false, error: INCOMPATIBLE_PROTOCOL_VERSION }; - return { ok: true, envelope: parsed }; -} diff --git a/apps/web/Dockerfile b/apps/web/Dockerfile index 1795a15..18de84f 100644 --- a/apps/web/Dockerfile +++ b/apps/web/Dockerfile @@ -1,18 +1,20 @@ # syntax=docker/dockerfile:1 -# Web image: Vite build served by nginx. Build context: apps/web. +# Web image: Vite build served by nginx. Build context: the repo root +# docker build -f apps/web/Dockerfile . FROM node:24-slim AS build WORKDIR /app RUN corepack enable -COPY package.json pnpm-lock.yaml ./ -RUN pnpm install --frozen-lockfile -COPY index.html tsconfig.json vite.config.ts ./ -COPY src ./src -RUN pnpm build +COPY package.json pnpm-lock.yaml pnpm-workspace.yaml turbo.json ./ +COPY apps/web/package.json ./apps/web/ +RUN pnpm install --frozen-lockfile --filter @opencollab/web... +COPY apps/web/index.html apps/web/tsconfig.json apps/web/vite.config.ts ./apps/web/ +COPY apps/web/src ./apps/web/src +RUN pnpm --filter @opencollab/web build FROM nginxinc/nginx-unprivileged:stable-alpine -COPY nginx.conf /etc/nginx/conf.d/default.conf -COPY --from=build /app/dist /usr/share/nginx/html +COPY apps/web/nginx.conf /etc/nginx/conf.d/default.conf +COPY --from=build /app/apps/web/dist /usr/share/nginx/html EXPOSE 8080 HEALTHCHECK --interval=10s --timeout=3s --start-period=5s --retries=5 \ CMD ["wget", "-qO-", "http://127.0.0.1:8080/"] diff --git a/apps/web/nginx.conf b/apps/web/nginx.conf index 646e3f1..5a4f900 100644 --- a/apps/web/nginx.conf +++ b/apps/web/nginx.conf @@ -27,11 +27,11 @@ server { proxy_set_header Connection $connection_upgrade; location /auth/ { - proxy_pass http://server:8787; + proxy_pass http://api:8787; } location /ws { - proxy_pass http://server:8787; + proxy_pass http://api:8787; proxy_read_timeout 1h; proxy_send_timeout 1h; } diff --git a/apps/web/package.json b/apps/web/package.json index ba0ef76..30272fe 100644 --- a/apps/web/package.json +++ b/apps/web/package.json @@ -1,9 +1,8 @@ { - "name": "web", + "name": "@opencollab/web", "private": true, "version": "0.1.0", "type": "module", - "packageManager": "pnpm@11.1.1", "scripts": { "dev": "vite", "build": "tsc --noEmit && vite build", diff --git a/apps/web/pnpm-lock.yaml b/apps/web/pnpm-lock.yaml deleted file mode 100644 index d603372..0000000 --- a/apps/web/pnpm-lock.yaml +++ /dev/null @@ -1,1474 +0,0 @@ -lockfileVersion: '9.0' - -settings: - autoInstallPeers: true - excludeLinksFromLockfile: false - -importers: - - .: - dependencies: - '@fontsource-variable/google-sans': - specifier: ^5.3.1 - version: 5.3.1 - react: - specifier: ^19.3.0 - version: 19.3.0 - react-dom: - specifier: ^19.3.0 - version: 19.3.0(react@19.3.0) - devDependencies: - '@testing-library/dom': - specifier: ^10.4.0 - version: 10.4.2 - '@testing-library/react': - specifier: ^16.3.0 - version: 16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0) - '@testing-library/user-event': - specifier: ^14.6.1 - version: 14.6.7(@testing-library/dom@10.4.2) - '@types/node': - specifier: ^24.19.1 - version: 24.19.1 - '@types/react': - specifier: ^19.3.0 - version: 19.3.0 - '@types/react-dom': - specifier: ^19.3.0 - version: 19.3.0(@types/react@19.3.0) - '@vitejs/plugin-react': - specifier: ^6.1.1 - version: 6.1.2(vite@8.3.2(@types/node@24.19.1)) - jsdom: - specifier: ^27.0.0 - version: 27.4.0 - typescript: - specifier: ^7.0.2 - version: 7.0.2 - vite: - specifier: ^8.3.2 - version: 8.3.2(@types/node@24.19.1) - vitest: - specifier: ^5.0.3 - version: 5.0.3(@types/node@24.19.1)(jsdom@27.4.0)(vite@8.3.2(@types/node@24.19.1)) - -packages: - - '@acemir/cssom@0.9.31': - resolution: {integrity: sha512-ZnR3GSaH+/vJ0YlHau21FjfLYjMpYVIzTD8M8vIEQvIGxeOXyXdzCI140rrCY862p/C/BbzWsjc1dgnM9mkoTA==} - - '@asamuzakjp/css-color@4.1.2': - resolution: {integrity: sha512-NfBUvBaYgKIuq6E/RBLY1m0IohzNHAYyaJGuTK79Z23uNwmz2jl1mPsC5ZxCCxylinKhT1Amn5oNTlx1wN8cQg==} - - '@asamuzakjp/dom-selector@6.8.1': - resolution: {integrity: sha512-MvRz1nCqW0fsy8Qz4dnLIvhOlMzqDVBabZx6lH+YywFDdjXhMY37SmpV1XFX3JzG5GWHn63j6HX6QPr3lZXHvQ==} - - '@asamuzakjp/nwsapi@2.3.9': - resolution: {integrity: sha512-n8GuYSrI9bF7FFZ/SjhwevlHc8xaVlb/7HmHelnc/PZXBD2ZR49NnN9sMMuDdEGPeeRQ5d0hqlSlEpgCX3Wl0Q==} - - '@babel/code-frame@7.29.7': - resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==} - engines: {node: '>=6.9.0'} - - '@babel/helper-validator-identifier@7.29.7': - resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==} - engines: {node: '>=6.9.0'} - - '@babel/runtime@7.29.7': - resolution: {integrity: sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw==} - engines: {node: '>=6.9.0'} - - '@csstools/color-helpers@6.1.2': - resolution: {integrity: sha512-grhRy3OKmniaAEKXMjua5z/EODX0MSqBGjunw8+j/3HQjOnahs2AGhvEOIYVUWcU6ScApbhLhVrQTX8XqrMrow==} - engines: {node: '>=20.19.0'} - - '@csstools/css-calc@3.4.3': - resolution: {integrity: sha512-iex20d8CHVkyvg6B7UKV7uHnI2Bqo9g+EFfT9E0y+GvTvhZ/DwONJ+9aKb1dlqm0ZiGsL5RXjp0fCoJYnkeDjA==} - engines: {node: '>=20.19.0'} - peerDependencies: - '@csstools/css-parser-algorithms': ^4.0.2 - '@csstools/css-tokenizer': ^4.0.2 - - '@csstools/css-color-parser@4.2.6': - resolution: {integrity: sha512-iiPQ3iRWwnJkeEn6RIu6SJPr7hYrLz6XZ9s/QZl+2/LI5KQVjpl2fdmDSZKuD4xP6GMmMPgHFFXg6k1Wkz0Trg==} - engines: {node: '>=20.19.0'} - peerDependencies: - '@csstools/css-parser-algorithms': ^4.0.2 - '@csstools/css-tokenizer': ^4.0.2 - - '@csstools/css-parser-algorithms@4.0.2': - resolution: {integrity: sha512-40cSKyMvK+tq4qz6Awrlye2WGuOKt3FwPgtGg6KTfbHOWNw+Rk1rzbAtZnZ6IBhsY491HLRnDXwoyBAijmmILA==} - engines: {node: '>=20.19.0'} - peerDependencies: - '@csstools/css-tokenizer': ^4.0.2 - - '@csstools/css-syntax-patches-for-csstree@1.1.15': - resolution: {integrity: sha512-J0u7HkVl2nzSlhsiTOp4AmwcUQ3D+mGEEKfBy/7To5/y7F2OHwyLrXfrhR0SMgr4p5Lo+eaMVSeai24zUcBIxA==} - peerDependencies: - css-tree: ^3.2.1 - peerDependenciesMeta: - css-tree: - optional: true - - '@csstools/css-tokenizer@4.0.2': - resolution: {integrity: sha512-OoKoR0f76dCY666JlcbhmVTs2drYj1GUXZTYTcbUgJjh9Nv41aFfZ21bPQTERm5+L5cBDo466NltB2lplS5GBw==} - engines: {node: '>=20.19.0'} - - '@exodus/bytes@1.16.0': - resolution: {integrity: sha512-IcpW84uEn3N7ETtNZMlxKhfl6Pec8rUNGOTBtWbK1FKhJxIFAptZyVrvVRVBimAJxJCgc3PxepxkdWWG4DVzfA==} - engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} - peerDependencies: - '@noble/hashes': ^1.8.0 || ^2.0.0 - peerDependenciesMeta: - '@noble/hashes': - optional: true - - '@fontsource-variable/google-sans@5.3.1': - resolution: {integrity: sha512-FLB6ZktdAtYWj49W6TtmqThHb33XL5g8l6T+oKNcvmNUXou4PPdIkstt1Z/UyD6K+g/CYjiHF+j+eRMNZxYKZg==} - - '@jridgewell/resolve-uri@3.1.2': - resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==} - engines: {node: '>=6.0.0'} - - '@jridgewell/sourcemap-codec@1.6.0': - resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==} - - '@jridgewell/trace-mapping@0.3.31': - resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} - - '@oxc-project/types@0.152.0': - resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==} - - '@rolldown/binding-android-arm-eabi@1.2.12': - resolution: {integrity: sha512-dB/a1214qKfHMXCpgqR4OZT+jS4kTyEXbQGJPqzobt5EwH5rX080pxE37alt3RzvR1bf1Yz/yGqRfrYAxuPw0A==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [android] - - '@rolldown/binding-android-arm64@1.2.12': - resolution: {integrity: sha512-7KHFgQ5VJxIHcLlrwrc3Xbds7oTNQT7Pgi9gQCJKrd2VGab/UksIOYp6VD8MzCstGxOKMgNamPwUCfxPdP1OHg==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [android] - - '@rolldown/binding-darwin-arm64@1.2.12': - resolution: {integrity: sha512-3YIhqHD96nA5SaYNRBR16HnGv4oavZvXfD/ayHM+oYZ0WD/8lBAtf6zQua4kEyAvpqrluKXl0lnOBoiNby7x9w==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [darwin] - - '@rolldown/binding-darwin-x64@1.2.12': - resolution: {integrity: sha512-UuuJ35MFw4gmFOrE9pEqIV+K3syIKveph+Qc1/ljHZVdoDW4pz/JHR/eMVom+TZGl/5OOvGJOWaOCVt3ZfqhxA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [darwin] - - '@rolldown/binding-freebsd-x64@1.2.12': - resolution: {integrity: sha512-uMvssit0a4W+/7D8CbHUvG719mH3R2jwXAlh/XcPvuHTE0g++LymF88DCGNX0HM2rBOn0xrzgXktIB6fLSJBTQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [freebsd] - - '@rolldown/binding-linux-arm-gnueabihf@1.2.12': - resolution: {integrity: sha512-XcFu0R0xWnwzSf4IQgFH1rJIckPN1pLy2R+4r9IDB7Yfu/ys9cVqfa4pBrMHj7a3gl8mIR4nRNPg0e5IvEVs6g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm] - os: [linux] - - '@rolldown/binding-linux-arm64-gnu@1.2.12': - resolution: {integrity: sha512-260UrKgn8tz39ak+SMDOirKzr7V04M9dWPw5llW00SwBivCZoWcRBKV1d8cXnRkUmSZA3BdiUmBHWk7734Ulpw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-arm64-musl@1.2.12': - resolution: {integrity: sha512-5YK1I9SqDkbPgc1IA8BgDl34suqUS2q0KWnBrirm0E51YjOs6eo6dV6jbQfNE/argHRSvd0QUGgtpIoYx+WWpw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [linux] - libc: [musl] - - '@rolldown/binding-linux-ppc64-gnu@1.2.12': - resolution: {integrity: sha512-Rkcrmp7eFRg74yL5fXEU91JEWbdEPLevWwGtXpmhbjlD1StScbWTmO94Bhly+Mo+ketKYkdmM1vNUKeWSlx8cQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [ppc64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-s390x-gnu@1.2.12': - resolution: {integrity: sha512-qvK4DuAsQc2BSjlx+Xr+IzOIvvxbGZqxFwdWfG6F518Erj0GGISyQbJ6pIappnOxlNPzNHvo/L0BwB30GZ+zVw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [s390x] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-gnu@1.2.12': - resolution: {integrity: sha512-Q9uLBO53Xd4QIq1WOycVQyPP1O4HhraEV2qqb3uTrnVw6QZih9duY4vNXOivL1xoUS1/z+W8eF4NMfl2a8Sdjw==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [glibc] - - '@rolldown/binding-linux-x64-musl@1.2.12': - resolution: {integrity: sha512-3IBxWFMjbOZskDPKv8Lf9BCnahlKuHthWkYnyIxOH/QcJrFcS4EmcenthApkwr/5+nEqZlLzeYbxeMaX7A5u4g==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [linux] - libc: [musl] - - '@rolldown/binding-openharmony-arm64@1.2.12': - resolution: {integrity: sha512-xtX61xg4LKPkPWilZU1ynKClz5Gj4bf74LML4r3eVLWumKnGjoEr1OSHQhMdbBDoYTi+yjrujvpZe2pUnqCrrA==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [openharmony] - - '@rolldown/binding-win32-arm64-msvc@1.2.12': - resolution: {integrity: sha512-At7fPB6PCaIjzgIhEZFxuT+BBFqiQibJDT4d3PhiR3f4E7bbMZF4aKblbFfEM3sETRDd1YiQx/+U/g/B/ou5Ew==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [arm64] - os: [win32] - - '@rolldown/binding-win32-x64-msvc@1.2.12': - resolution: {integrity: sha512-WIw2haVKwjuYdXkHaoC0mF8Le71TuCBxjrdKqLbJGctbBABj+ClfmNvtbOnzpq3RokNo5+V1qhtSzJyXorsklQ==} - engines: {node: ^20.19.0 || >=22.12.0} - cpu: [x64] - os: [win32] - - '@rolldown/pluginutils@1.0.1': - resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} - - '@testing-library/dom@10.4.2': - resolution: {integrity: sha512-yzr2S9HyAIdhz2/6qHgbs665Q7PKVcDF05vsOlHPxG1mo36gKVesdYVeDLnXgfjJ03CrKRk08knc6+E/9m8v2Q==} - engines: {node: '>=18'} - - '@testing-library/react@16.3.3': - resolution: {integrity: sha512-Uo193NgQbPMz6lrrhtRQQFcMC6Re/ELLFbbuVL30WDlZxlpZf9/lMHTAVxPRLw1q1iu9OJmR1c2BLiENRstdBg==} - engines: {node: '>=18'} - peerDependencies: - '@testing-library/dom': ^10.0.0 - '@types/react': ^18.0.0 || ^19.0.0 - '@types/react-dom': ^18.0.0 || ^19.0.0 - react: ^18.0.0 || ^19.0.0 - react-dom: ^18.0.0 || ^19.0.0 - peerDependenciesMeta: - '@types/react': - optional: true - '@types/react-dom': - optional: true - - '@testing-library/user-event@14.6.7': - resolution: {integrity: sha512-MPCpX8bxe8zS+JmmTwLp8jd0dy1rAm60Te/SL8JrQM3qvQJcBOs1d7IefJMyZzqM3EWBrDn/LWDt1BCGu4ASfg==} - engines: {node: '>=12', npm: '>=6'} - peerDependencies: - '@testing-library/dom': '>=7.21.4' - - '@types/aria-query@5.0.4': - resolution: {integrity: sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==} - - '@types/chai@5.2.3': - resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} - - '@types/deep-eql@4.0.2': - resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} - - '@types/estree@1.0.9': - resolution: {integrity: sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==} - - '@types/node@24.19.1': - resolution: {integrity: sha512-aS3/DG0oM05K0RIXXP+hKjinGG5IgSSVGzswZxW3O0sS3pH4/fycXundUC9XsszgKCk4gHXylTEK6hyFxVxnoQ==} - - '@types/react-dom@19.3.0': - resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} - peerDependencies: - '@types/react': ^19.3.0 - - '@types/react@19.3.0': - resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} - - '@typescript/typescript-aix-ppc64@7.0.2': - resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} - engines: {node: '>=16.20.0'} - cpu: [ppc64] - os: [aix] - - '@typescript/typescript-darwin-arm64@7.0.2': - resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [darwin] - - '@typescript/typescript-darwin-x64@7.0.2': - resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [darwin] - - '@typescript/typescript-freebsd-arm64@7.0.2': - resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [freebsd] - - '@typescript/typescript-freebsd-x64@7.0.2': - resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [freebsd] - - '@typescript/typescript-linux-arm64@7.0.2': - resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [linux] - - '@typescript/typescript-linux-arm@7.0.2': - resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} - engines: {node: '>=16.20.0'} - cpu: [arm] - os: [linux] - - '@typescript/typescript-linux-loong64@7.0.2': - resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} - engines: {node: '>=16.20.0'} - cpu: [loong64] - os: [linux] - - '@typescript/typescript-linux-mips64el@7.0.2': - resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} - engines: {node: '>=16.20.0'} - cpu: [mips64el] - os: [linux] - - '@typescript/typescript-linux-ppc64@7.0.2': - resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} - engines: {node: '>=16.20.0'} - cpu: [ppc64] - os: [linux] - - '@typescript/typescript-linux-riscv64@7.0.2': - resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} - engines: {node: '>=16.20.0'} - cpu: [riscv64] - os: [linux] - - '@typescript/typescript-linux-s390x@7.0.2': - resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} - engines: {node: '>=16.20.0'} - cpu: [s390x] - os: [linux] - - '@typescript/typescript-linux-x64@7.0.2': - resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [linux] - - '@typescript/typescript-netbsd-arm64@7.0.2': - resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [netbsd] - - '@typescript/typescript-netbsd-x64@7.0.2': - resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [netbsd] - - '@typescript/typescript-openbsd-arm64@7.0.2': - resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [openbsd] - - '@typescript/typescript-openbsd-x64@7.0.2': - resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [openbsd] - - '@typescript/typescript-sunos-x64@7.0.2': - resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [sunos] - - '@typescript/typescript-win32-arm64@7.0.2': - resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} - engines: {node: '>=16.20.0'} - cpu: [arm64] - os: [win32] - - '@typescript/typescript-win32-x64@7.0.2': - resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} - engines: {node: '>=16.20.0'} - cpu: [x64] - os: [win32] - - '@vitejs/plugin-react@6.1.2': - resolution: {integrity: sha512-fhJNGUdscQa4HkI0xFxwonWyhnVReCPDbXI7FH7jmzpnVCrFQI7PRrhWecO263610vOrs9tr2Y4xcf8uAdFxbw==} - engines: {node: ^20.19.0 || >=22.12.0} - peerDependencies: - '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 - babel-plugin-react-compiler: ^1.0.0 - oxc-transform-react: ^0.152.0 - vite: ^8.0.0 - peerDependenciesMeta: - '@rolldown/plugin-babel': - optional: true - babel-plugin-react-compiler: - optional: true - oxc-transform-react: - optional: true - - '@vitest/mocker@5.0.3': - resolution: {integrity: sha512-T8sWAIbkSyAjkwTcaEc3Iu0o9A27X1/kdXrizhZkGuSKScRQtRzclfAMpOTcGdXCsqxeWlpGy3XjqaW8CpLORg==} - peerDependencies: - msw: ^2.4.9 - vite: ^6.0.0 || ^7.0.0 || ^8.0.0 - peerDependenciesMeta: - msw: - optional: true - vite: - optional: true - - '@vitest/spy@5.0.3': - resolution: {integrity: sha512-XhFysQTB8AZ+P4gMi+Lpo99vg2AZi0qKpaB9yXQl37+CaMEAPO3iH/wGVnSyL5MPERiLezpqTVtrR6UZH5GCXg==} - - agent-base@7.1.4: - resolution: {integrity: sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==} - engines: {node: '>= 14'} - - ansi-regex@5.0.1: - resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} - engines: {node: '>=8'} - - ansi-styles@5.2.0: - resolution: {integrity: sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==} - engines: {node: '>=10'} - - aria-query@5.3.0: - resolution: {integrity: sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==} - - assertion-error@2.0.1: - resolution: {integrity: sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==} - engines: {node: '>=12'} - - bidi-js@1.1.0: - resolution: {integrity: sha512-fX1Onk0tdVPC7obPWB5EbJ1z7NVhLq4m2xZLq2YXBkxzMXIGRpNMU88n0EPgWseKl12J7zXs7qrDxPK4sRs2fg==} - - chai@6.3.0: - resolution: {integrity: sha512-XWAtwJ6OHO+tj0EKCs0Y2UamnyOxseZWltU4x2U2wh8g4AigdjwvtUjvLP2tqkA/avxHEtzxNaqGq/YGNwckKg==} - engines: {node: '>=18'} - - css-tree@3.2.1: - resolution: {integrity: sha512-X7sjQzceUhu1u7Y/ylrRZFU2FS6LRiFVp6rKLPg23y3x3c3DOKAwuXGDp+PAGjh6CSnCjYeAul8pcT8bAl+lSA==} - engines: {node: ^10 || ^12.20.0 || ^14.13.0 || >=15.0.0} - - cssstyle@5.3.7: - resolution: {integrity: sha512-7D2EPVltRrsTkhpQmksIu+LxeWAIEk6wRDMJ1qljlv+CKHJM+cJLlfhWIzNA44eAsHXSNe3+vO6DW1yCYx8SuQ==} - engines: {node: '>=20'} - - csstype@3.2.3: - resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} - - data-urls@6.0.1: - resolution: {integrity: sha512-euIQENZg6x8mj3fO6o9+fOW8MimUI4PpD/fZBhJfeioZVy9TUpM4UY7KjQNVZFlqwJ0UdzRDzkycB997HEq1BQ==} - engines: {node: '>=20'} - - debug@4.4.3: - resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==} - engines: {node: '>=6.0'} - peerDependencies: - supports-color: '*' - peerDependenciesMeta: - supports-color: - optional: true - - decimal.js@10.6.0: - resolution: {integrity: sha512-YpgQiITW3JXGntzdUmyUR1V812Hn8T1YVXhCu+wO3OpS4eU9l4YdD3qjyiKdV6mvV29zapkMeD390UVEf2lkUg==} - - dequal@2.0.3: - resolution: {integrity: sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==} - engines: {node: '>=6'} - - detect-libc@2.1.2: - resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} - engines: {node: '>=8'} - - dom-accessibility-api@0.5.16: - resolution: {integrity: sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==} - - entities@8.1.0: - resolution: {integrity: sha512-kxL7msIffSuh9aaFAMD7rxAIuTRMAHMeBtgHW2yUdWw732ZNh4MehkF2gdjvtdmikkaIP9bFDDJOPlsvm7avrA==} - engines: {node: '>=20.19.0'} - - es-module-lexer@2.3.2: - resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} - - estree-walker@3.0.3: - resolution: {integrity: sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==} - - expect-type@1.4.0: - resolution: {integrity: sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==} - engines: {node: '>=12.0.0'} - - fdir@6.5.0: - resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} - engines: {node: '>=12.0.0'} - peerDependencies: - picomatch: ^3 || ^4 - peerDependenciesMeta: - picomatch: - optional: true - - fsevents@2.3.3: - resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} - engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} - os: [darwin] - - html-encoding-sniffer@6.0.0: - resolution: {integrity: sha512-CV9TW3Y3f8/wT0BRFc1/KAVQ3TUHiXmaAb6VW9vtiMFf7SLoMd1PdAc4W3KFOFETBJUb90KatHqlsZMWV+R9Gg==} - engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} - - http-proxy-agent@7.0.2: - resolution: {integrity: sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==} - engines: {node: '>= 14'} - - https-proxy-agent@7.0.6: - resolution: {integrity: sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==} - engines: {node: '>= 14'} - - is-potential-custom-element-name@1.0.1: - resolution: {integrity: sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==} - - js-tokens@4.0.0: - resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} - - jsdom@27.4.0: - resolution: {integrity: sha512-mjzqwWRD9Y1J1KUi7W97Gja1bwOOM5Ug0EZ6UDK3xS7j7mndrkwozHtSblfomlzyB4NepioNt+B2sOSzczVgtQ==} - engines: {node: ^20.19.0 || ^22.12.0 || >=24.0.0} - peerDependencies: - canvas: ^3.0.0 - peerDependenciesMeta: - canvas: - optional: true - - lightningcss-android-arm64@1.33.0: - resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [android] - - lightningcss-darwin-arm64@1.33.0: - resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [darwin] - - lightningcss-darwin-x64@1.33.0: - resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [darwin] - - lightningcss-freebsd-x64@1.33.0: - resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [freebsd] - - lightningcss-linux-arm-gnueabihf@1.33.0: - resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm] - os: [linux] - - lightningcss-linux-arm64-gnu@1.33.0: - resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [glibc] - - lightningcss-linux-arm64-musl@1.33.0: - resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [linux] - libc: [musl] - - lightningcss-linux-x64-gnu@1.33.0: - resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [glibc] - - lightningcss-linux-x64-musl@1.33.0: - resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [linux] - libc: [musl] - - lightningcss-win32-arm64-msvc@1.33.0: - resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} - engines: {node: '>= 12.0.0'} - cpu: [arm64] - os: [win32] - - lightningcss-win32-x64-msvc@1.33.0: - resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} - engines: {node: '>= 12.0.0'} - cpu: [x64] - os: [win32] - - lightningcss@1.33.0: - resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} - engines: {node: '>= 12.0.0'} - - lru-cache@11.5.3: - resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==} - engines: {node: 20 || >=22} - - lz-string@1.5.0: - resolution: {integrity: sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==} - hasBin: true - - magic-string@1.4.3: - resolution: {integrity: sha512-z12OxmaPGE0F4xlpGdjuAUckipLpQlTAuAmyGhNoD7ODpYUzvDfvtxUbjM/jwznyP178oju/KDdyi220wNJ0RQ==} - - mdn-data@2.27.1: - resolution: {integrity: sha512-9Yubnt3e8A0OKwxYSXyhLymGW4sCufcLG6VdiDdUGVkPhpqLxlvP5vl1983gQjJl3tqbrM731mjaZaP68AgosQ==} - - ms@2.1.3: - resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} - - nanoid@3.3.20: - resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} - engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} - hasBin: true - - obug@2.2.1: - resolution: {integrity: sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q==} - engines: {node: '>=12.20.0'} - - parse5@8.0.1: - resolution: {integrity: sha512-z1e/HMG90obSGeidlli3hj7cbocou0/wa5HacvI3ASx34PecNjNQeaHNo5WIZpWofN9kgkqV1q5YvXe3F0FoPw==} - - picocolors@1.1.1: - resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} - - picomatch@4.0.7: - resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} - engines: {node: '>=12'} - - postcss@8.5.29: - resolution: {integrity: sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==} - engines: {node: ^10 || ^12 || >=14} - - pretty-format@27.5.1: - resolution: {integrity: sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==} - engines: {node: ^10.13.0 || ^12.13.0 || ^14.15.0 || >=15.0.0} - - punycode@2.3.1: - resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} - engines: {node: '>=6'} - - react-dom@19.3.0: - resolution: {integrity: sha512-JDk8dgif51OjFoDE70+OT9ICyYr+69HlmihNwp1+Nsfbna3t5sIiCa9ZJktDmQ4/1b/rn26hIAR2uYXDMr5r0Q==} - peerDependencies: - react: ^19.3.0 - - react-is@17.0.2: - resolution: {integrity: sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==} - - react@19.3.0: - resolution: {integrity: sha512-E8LUcbtBWt20bbl2YoHfx4ZDBdxVTfOKtCZn9cDSJ4l6/nuoApcpIBcj47t2wZoVX8g2ZHuMHbiShgCR1T5Sog==} - engines: {node: '>=0.10.0'} - - require-from-string@2.0.2: - resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} - engines: {node: '>=0.10.0'} - - rolldown@1.2.12: - resolution: {integrity: sha512-8wafseiaG80xmXSfqidUNqZcylTlhmPZZt+za2m+js2sFZ8dTNlhIOV2WcbIPx2hgwPBJpEUGFAMZ9bgBBLTSQ==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - - saxes@6.0.0: - resolution: {integrity: sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==} - engines: {node: '>=v12.22.7'} - - scheduler@0.28.0: - resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} - - source-map-js@1.2.2: - resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} - engines: {node: '>=0.10.0'} - - std-env@4.3.0: - resolution: {integrity: sha512-OtU/EgQ1kIm5KwqQpBC6ZEMXrZRui11w8zgfTWp8cdO9B8OaPsbA8bTHO2P+HNo1VlUTGMVBwPhydu6poeXiag==} - - symbol-tree@3.2.4: - resolution: {integrity: sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==} - - tinybench@6.2.0: - resolution: {integrity: sha512-78U2TlB2CnVenajOFzf3BKSm0J6oz5L0NV7g32LCPccvYc0lbWvys4d3uUUCS2B1N8PAf2+aekR8i1KbC3HO7Q==} - engines: {node: '>=20.0.0'} - - tinyexec@1.3.1: - resolution: {integrity: sha512-GCvB3aoys96IuDFBMcTB46JOR6mdMtAToqwiW8JlWhsoh1mhHi/xn9ss/Dg7N555GiJyEt2qzoG/NHCwM6h1EA==} - engines: {node: '>=18'} - - tinyglobby@0.2.17: - resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} - engines: {node: '>=12.0.0'} - - tldts-core@7.4.16: - resolution: {integrity: sha512-MDolfaSJtlSK5Y0A1xl3277ekubZwobpBjugknDizI9O5Rm60a1m8k4ICK+MRsCDzPygT81mp3BBf5RKDlFRfA==} - - tldts@7.4.16: - resolution: {integrity: sha512-QwBER5KMR86IIjpIiO7H/Z3IMJPsZ1A6RKPAqzTTgOyUQUSt9FdnKcqhTaJmkY6HVrgouZHZR0ncK5QxvmnQeg==} - hasBin: true - - tough-cookie@6.0.2: - resolution: {integrity: sha512-exgYmnmL/sJpR3upZfXG5PoatXQii55xAiXGXzY+sROLZ/Y+SLcp9PgJNI9Vz37HpQ74WvDcLT8eqm+kV3FzrA==} - engines: {node: '>=16'} - - tr46@6.0.0: - resolution: {integrity: sha512-bLVMLPtstlZ4iMQHpFHTR7GAGj2jxi8Dg0s2h2MafAE4uSWF98FC/3MomU51iQAMf8/qDUbKWf5GxuvvVcXEhw==} - engines: {node: '>=20'} - - typescript@7.0.2: - resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} - engines: {node: '>=16.20.0'} - hasBin: true - - undici-types@7.24.6: - resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} - - vite@8.3.2: - resolution: {integrity: sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w==} - engines: {node: ^20.19.0 || >=22.12.0} - hasBin: true - peerDependencies: - '@types/node': ^20.19.0 || >=22.12.0 - '@vitejs/devtools': ^0.7.1 - esbuild: ^0.27.0 || ^0.28.0 - jiti: '>=1.21.0' - less: ^4.0.0 - sass: ^1.70.0 - sass-embedded: ^1.70.0 - stylus: '>=0.54.8' - sugarss: ^5.0.0 - terser: ^5.16.0 - tsx: ^4.8.1 - yaml: ^2.4.2 - peerDependenciesMeta: - '@types/node': - optional: true - '@vitejs/devtools': - optional: true - esbuild: - optional: true - jiti: - optional: true - less: - optional: true - sass: - optional: true - sass-embedded: - optional: true - stylus: - optional: true - sugarss: - optional: true - terser: - optional: true - tsx: - optional: true - yaml: - optional: true - - vitest@5.0.3: - resolution: {integrity: sha512-xMw97S3rjdtj5dkVat7jCsqWBpvchs3RlpQctUqwJD0KkERk40vz2fJ77lDwW/Vzh/pk18eItYAzkodhSes3jQ==} - engines: {node: ^22.12.0 || ^24.0.0 || >=26.0.0} - hasBin: true - peerDependencies: - '@edge-runtime/vm': '*' - '@opentelemetry/api': ^1.9.0 - '@types/node': ^22.0.0 || >=24.0.0 - '@vitest/browser-playwright': 5.0.3 - '@vitest/browser-preview': 5.0.3 - '@vitest/browser-webdriverio': ^5.0.0-beta.5 || >=5.0.0 - '@vitest/coverage-istanbul': 5.0.3 - '@vitest/coverage-v8': 5.0.3 - '@vitest/ui': 5.0.3 - happy-dom: '*' - jsdom: '*' - vite: ^6.4.0 || ^7.0.0 || ^8.0.0 - peerDependenciesMeta: - '@edge-runtime/vm': - optional: true - '@opentelemetry/api': - optional: true - '@types/node': - optional: true - '@vitest/browser-playwright': - optional: true - '@vitest/browser-preview': - optional: true - '@vitest/browser-webdriverio': - optional: true - '@vitest/coverage-istanbul': - optional: true - '@vitest/coverage-v8': - optional: true - '@vitest/ui': - optional: true - happy-dom: - optional: true - jsdom: - optional: true - - w3c-xmlserializer@5.0.0: - resolution: {integrity: sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==} - engines: {node: '>=18'} - - webidl-conversions@8.0.1: - resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==} - engines: {node: '>=20'} - - whatwg-mimetype@4.0.0: - resolution: {integrity: sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==} - engines: {node: '>=18'} - - whatwg-mimetype@5.0.0: - resolution: {integrity: sha512-sXcNcHOC51uPGF0P/D4NVtrkjSU2fNsm9iog4ZvZJsL3rjoDAzXZhkm2MWt1y+PUdggKAYVoMAIYcs78wJ51Cw==} - engines: {node: '>=20'} - - whatwg-url@15.1.0: - resolution: {integrity: sha512-2ytDk0kiEj/yu90JOAp44PVPUkO9+jVhyf+SybKlRHSDlvOOZhdPIrr7xTH64l4WixO2cP+wQIcgujkGBPPz6g==} - engines: {node: '>=20'} - - why-is-node-running@3.2.1: - resolution: {integrity: sha512-Tb2FUhB4vUsGQlfSquQLYkApkuPAFQXGFzxWKHHumVz2dK+X1RUm/HnID4+TfIGYJ1kTcwOaCk/buYCEJr6YjQ==} - engines: {node: '>=20.11'} - hasBin: true - - ws@8.22.0: - resolution: {integrity: sha512-Ydggc987+RO0AnWtZ/7Wq9FtNvcrL1b/RO0ud9mWjUPgDrsAAwQSF51sm2hm1XofbU/4jkpGEsLFsZZxU+1DOg==} - engines: {node: '>=10.0.0'} - peerDependencies: - bufferutil: ^4.0.1 - utf-8-validate: '>=5.0.2' - peerDependenciesMeta: - bufferutil: - optional: true - utf-8-validate: - optional: true - - xml-name-validator@5.0.0: - resolution: {integrity: sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==} - engines: {node: '>=18'} - - xmlchars@2.2.0: - resolution: {integrity: sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==} - -snapshots: - - '@acemir/cssom@0.9.31': {} - - '@asamuzakjp/css-color@4.1.2': - dependencies: - '@csstools/css-calc': 3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) - '@csstools/css-color-parser': 4.2.6(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) - '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) - '@csstools/css-tokenizer': 4.0.2 - lru-cache: 11.5.3 - - '@asamuzakjp/dom-selector@6.8.1': - dependencies: - '@asamuzakjp/nwsapi': 2.3.9 - bidi-js: 1.1.0 - css-tree: 3.2.1 - is-potential-custom-element-name: 1.0.1 - lru-cache: 11.5.3 - - '@asamuzakjp/nwsapi@2.3.9': {} - - '@babel/code-frame@7.29.7': - dependencies: - '@babel/helper-validator-identifier': 7.29.7 - js-tokens: 4.0.0 - picocolors: 1.1.1 - - '@babel/helper-validator-identifier@7.29.7': {} - - '@babel/runtime@7.29.7': {} - - '@csstools/color-helpers@6.1.2': {} - - '@csstools/css-calc@3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': - dependencies: - '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) - '@csstools/css-tokenizer': 4.0.2 - - '@csstools/css-color-parser@4.2.6(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2)': - dependencies: - '@csstools/color-helpers': 6.1.2 - '@csstools/css-calc': 3.4.3(@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2))(@csstools/css-tokenizer@4.0.2) - '@csstools/css-parser-algorithms': 4.0.2(@csstools/css-tokenizer@4.0.2) - '@csstools/css-tokenizer': 4.0.2 - - '@csstools/css-parser-algorithms@4.0.2(@csstools/css-tokenizer@4.0.2)': - dependencies: - '@csstools/css-tokenizer': 4.0.2 - - '@csstools/css-syntax-patches-for-csstree@1.1.15(css-tree@3.2.1)': - optionalDependencies: - css-tree: 3.2.1 - - '@csstools/css-tokenizer@4.0.2': {} - - '@exodus/bytes@1.16.0': {} - - '@fontsource-variable/google-sans@5.3.1': {} - - '@jridgewell/resolve-uri@3.1.2': {} - - '@jridgewell/sourcemap-codec@1.6.0': {} - - '@jridgewell/trace-mapping@0.3.31': - dependencies: - '@jridgewell/resolve-uri': 3.1.2 - '@jridgewell/sourcemap-codec': 1.6.0 - - '@oxc-project/types@0.152.0': {} - - '@rolldown/binding-android-arm-eabi@1.2.12': - optional: true - - '@rolldown/binding-android-arm64@1.2.12': - optional: true - - '@rolldown/binding-darwin-arm64@1.2.12': - optional: true - - '@rolldown/binding-darwin-x64@1.2.12': - optional: true - - '@rolldown/binding-freebsd-x64@1.2.12': - optional: true - - '@rolldown/binding-linux-arm-gnueabihf@1.2.12': - optional: true - - '@rolldown/binding-linux-arm64-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-arm64-musl@1.2.12': - optional: true - - '@rolldown/binding-linux-ppc64-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-s390x-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-x64-gnu@1.2.12': - optional: true - - '@rolldown/binding-linux-x64-musl@1.2.12': - optional: true - - '@rolldown/binding-openharmony-arm64@1.2.12': - optional: true - - '@rolldown/binding-win32-arm64-msvc@1.2.12': - optional: true - - '@rolldown/binding-win32-x64-msvc@1.2.12': - optional: true - - '@rolldown/pluginutils@1.0.1': {} - - '@testing-library/dom@10.4.2': - dependencies: - '@babel/code-frame': 7.29.7 - '@babel/runtime': 7.29.7 - '@types/aria-query': 5.0.4 - aria-query: 5.3.0 - dom-accessibility-api: 0.5.16 - lz-string: 1.5.0 - picocolors: 1.1.1 - pretty-format: 27.5.1 - - '@testing-library/react@16.3.3(@testing-library/dom@10.4.2)(@types/react-dom@19.3.0(@types/react@19.3.0))(@types/react@19.3.0)(react-dom@19.3.0(react@19.3.0))(react@19.3.0)': - dependencies: - '@babel/runtime': 7.29.7 - '@testing-library/dom': 10.4.2 - react: 19.3.0 - react-dom: 19.3.0(react@19.3.0) - optionalDependencies: - '@types/react': 19.3.0 - '@types/react-dom': 19.3.0(@types/react@19.3.0) - - '@testing-library/user-event@14.6.7(@testing-library/dom@10.4.2)': - dependencies: - '@testing-library/dom': 10.4.2 - - '@types/aria-query@5.0.4': {} - - '@types/chai@5.2.3': - dependencies: - '@types/deep-eql': 4.0.2 - assertion-error: 2.0.1 - - '@types/deep-eql@4.0.2': {} - - '@types/estree@1.0.9': {} - - '@types/node@24.19.1': - dependencies: - undici-types: 7.24.6 - - '@types/react-dom@19.3.0(@types/react@19.3.0)': - dependencies: - '@types/react': 19.3.0 - - '@types/react@19.3.0': - dependencies: - csstype: 3.2.3 - - '@typescript/typescript-aix-ppc64@7.0.2': - optional: true - - '@typescript/typescript-darwin-arm64@7.0.2': - optional: true - - '@typescript/typescript-darwin-x64@7.0.2': - optional: true - - '@typescript/typescript-freebsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-freebsd-x64@7.0.2': - optional: true - - '@typescript/typescript-linux-arm64@7.0.2': - optional: true - - '@typescript/typescript-linux-arm@7.0.2': - optional: true - - '@typescript/typescript-linux-loong64@7.0.2': - optional: true - - '@typescript/typescript-linux-mips64el@7.0.2': - optional: true - - '@typescript/typescript-linux-ppc64@7.0.2': - optional: true - - '@typescript/typescript-linux-riscv64@7.0.2': - optional: true - - '@typescript/typescript-linux-s390x@7.0.2': - optional: true - - '@typescript/typescript-linux-x64@7.0.2': - optional: true - - '@typescript/typescript-netbsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-netbsd-x64@7.0.2': - optional: true - - '@typescript/typescript-openbsd-arm64@7.0.2': - optional: true - - '@typescript/typescript-openbsd-x64@7.0.2': - optional: true - - '@typescript/typescript-sunos-x64@7.0.2': - optional: true - - '@typescript/typescript-win32-arm64@7.0.2': - optional: true - - '@typescript/typescript-win32-x64@7.0.2': - optional: true - - '@vitejs/plugin-react@6.1.2(vite@8.3.2(@types/node@24.19.1))': - dependencies: - '@rolldown/pluginutils': 1.0.1 - vite: 8.3.2(@types/node@24.19.1) - - '@vitest/mocker@5.0.3(vite@8.3.2(@types/node@24.19.1))': - dependencies: - '@jridgewell/trace-mapping': 0.3.31 - '@vitest/spy': 5.0.3 - estree-walker: 3.0.3 - magic-string: 1.4.3 - optionalDependencies: - vite: 8.3.2(@types/node@24.19.1) - - '@vitest/spy@5.0.3': {} - - agent-base@7.1.4: {} - - ansi-regex@5.0.1: {} - - ansi-styles@5.2.0: {} - - aria-query@5.3.0: - dependencies: - dequal: 2.0.3 - - assertion-error@2.0.1: {} - - bidi-js@1.1.0: - dependencies: - require-from-string: 2.0.2 - - chai@6.3.0: {} - - css-tree@3.2.1: - dependencies: - mdn-data: 2.27.1 - source-map-js: 1.2.2 - - cssstyle@5.3.7: - dependencies: - '@asamuzakjp/css-color': 4.1.2 - '@csstools/css-syntax-patches-for-csstree': 1.1.15(css-tree@3.2.1) - css-tree: 3.2.1 - lru-cache: 11.5.3 - - csstype@3.2.3: {} - - data-urls@6.0.1: - dependencies: - whatwg-mimetype: 5.0.0 - whatwg-url: 15.1.0 - - debug@4.4.3: - dependencies: - ms: 2.1.3 - - decimal.js@10.6.0: {} - - dequal@2.0.3: {} - - detect-libc@2.1.2: {} - - dom-accessibility-api@0.5.16: {} - - entities@8.1.0: {} - - es-module-lexer@2.3.2: {} - - estree-walker@3.0.3: - dependencies: - '@types/estree': 1.0.9 - - expect-type@1.4.0: {} - - fdir@6.5.0(picomatch@4.0.7): - optionalDependencies: - picomatch: 4.0.7 - - fsevents@2.3.3: - optional: true - - html-encoding-sniffer@6.0.0: - dependencies: - '@exodus/bytes': 1.16.0 - transitivePeerDependencies: - - '@noble/hashes' - - http-proxy-agent@7.0.2: - dependencies: - agent-base: 7.1.4 - debug: 4.4.3 - transitivePeerDependencies: - - supports-color - - https-proxy-agent@7.0.6: - dependencies: - agent-base: 7.1.4 - debug: 4.4.3 - transitivePeerDependencies: - - supports-color - - is-potential-custom-element-name@1.0.1: {} - - js-tokens@4.0.0: {} - - jsdom@27.4.0: - dependencies: - '@acemir/cssom': 0.9.31 - '@asamuzakjp/dom-selector': 6.8.1 - '@exodus/bytes': 1.16.0 - cssstyle: 5.3.7 - data-urls: 6.0.1 - decimal.js: 10.6.0 - html-encoding-sniffer: 6.0.0 - http-proxy-agent: 7.0.2 - https-proxy-agent: 7.0.6 - is-potential-custom-element-name: 1.0.1 - parse5: 8.0.1 - saxes: 6.0.0 - symbol-tree: 3.2.4 - tough-cookie: 6.0.2 - w3c-xmlserializer: 5.0.0 - webidl-conversions: 8.0.1 - whatwg-mimetype: 4.0.0 - whatwg-url: 15.1.0 - ws: 8.22.0 - xml-name-validator: 5.0.0 - transitivePeerDependencies: - - '@noble/hashes' - - bufferutil - - supports-color - - utf-8-validate - - lightningcss-android-arm64@1.33.0: - optional: true - - lightningcss-darwin-arm64@1.33.0: - optional: true - - lightningcss-darwin-x64@1.33.0: - optional: true - - lightningcss-freebsd-x64@1.33.0: - optional: true - - lightningcss-linux-arm-gnueabihf@1.33.0: - optional: true - - lightningcss-linux-arm64-gnu@1.33.0: - optional: true - - lightningcss-linux-arm64-musl@1.33.0: - optional: true - - lightningcss-linux-x64-gnu@1.33.0: - optional: true - - lightningcss-linux-x64-musl@1.33.0: - optional: true - - lightningcss-win32-arm64-msvc@1.33.0: - optional: true - - lightningcss-win32-x64-msvc@1.33.0: - optional: true - - lightningcss@1.33.0: - dependencies: - detect-libc: 2.1.2 - optionalDependencies: - lightningcss-android-arm64: 1.33.0 - lightningcss-darwin-arm64: 1.33.0 - lightningcss-darwin-x64: 1.33.0 - lightningcss-freebsd-x64: 1.33.0 - lightningcss-linux-arm-gnueabihf: 1.33.0 - lightningcss-linux-arm64-gnu: 1.33.0 - lightningcss-linux-arm64-musl: 1.33.0 - lightningcss-linux-x64-gnu: 1.33.0 - lightningcss-linux-x64-musl: 1.33.0 - lightningcss-win32-arm64-msvc: 1.33.0 - lightningcss-win32-x64-msvc: 1.33.0 - - lru-cache@11.5.3: {} - - lz-string@1.5.0: {} - - magic-string@1.4.3: - dependencies: - '@jridgewell/sourcemap-codec': 1.6.0 - - mdn-data@2.27.1: {} - - ms@2.1.3: {} - - nanoid@3.3.20: {} - - obug@2.2.1: {} - - parse5@8.0.1: - dependencies: - entities: 8.1.0 - - picocolors@1.1.1: {} - - picomatch@4.0.7: {} - - postcss@8.5.29: - dependencies: - nanoid: 3.3.20 - picocolors: 1.1.1 - source-map-js: 1.2.2 - - pretty-format@27.5.1: - dependencies: - ansi-regex: 5.0.1 - ansi-styles: 5.2.0 - react-is: 17.0.2 - - punycode@2.3.1: {} - - react-dom@19.3.0(react@19.3.0): - dependencies: - react: 19.3.0 - scheduler: 0.28.0 - - react-is@17.0.2: {} - - react@19.3.0: {} - - require-from-string@2.0.2: {} - - rolldown@1.2.12: - dependencies: - '@oxc-project/types': 0.152.0 - '@rolldown/pluginutils': 1.0.1 - optionalDependencies: - '@rolldown/binding-android-arm-eabi': 1.2.12 - '@rolldown/binding-android-arm64': 1.2.12 - '@rolldown/binding-darwin-arm64': 1.2.12 - '@rolldown/binding-darwin-x64': 1.2.12 - '@rolldown/binding-freebsd-x64': 1.2.12 - '@rolldown/binding-linux-arm-gnueabihf': 1.2.12 - '@rolldown/binding-linux-arm64-gnu': 1.2.12 - '@rolldown/binding-linux-arm64-musl': 1.2.12 - '@rolldown/binding-linux-ppc64-gnu': 1.2.12 - '@rolldown/binding-linux-s390x-gnu': 1.2.12 - '@rolldown/binding-linux-x64-gnu': 1.2.12 - '@rolldown/binding-linux-x64-musl': 1.2.12 - '@rolldown/binding-openharmony-arm64': 1.2.12 - '@rolldown/binding-win32-arm64-msvc': 1.2.12 - '@rolldown/binding-win32-x64-msvc': 1.2.12 - - saxes@6.0.0: - dependencies: - xmlchars: 2.2.0 - - scheduler@0.28.0: {} - - source-map-js@1.2.2: {} - - std-env@4.3.0: {} - - symbol-tree@3.2.4: {} - - tinybench@6.2.0: {} - - tinyexec@1.3.1: {} - - tinyglobby@0.2.17: - dependencies: - fdir: 6.5.0(picomatch@4.0.7) - picomatch: 4.0.7 - - tldts-core@7.4.16: {} - - tldts@7.4.16: - dependencies: - tldts-core: 7.4.16 - - tough-cookie@6.0.2: - dependencies: - tldts: 7.4.16 - - tr46@6.0.0: - dependencies: - punycode: 2.3.1 - - typescript@7.0.2: - optionalDependencies: - '@typescript/typescript-aix-ppc64': 7.0.2 - '@typescript/typescript-darwin-arm64': 7.0.2 - '@typescript/typescript-darwin-x64': 7.0.2 - '@typescript/typescript-freebsd-arm64': 7.0.2 - '@typescript/typescript-freebsd-x64': 7.0.2 - '@typescript/typescript-linux-arm': 7.0.2 - '@typescript/typescript-linux-arm64': 7.0.2 - '@typescript/typescript-linux-loong64': 7.0.2 - '@typescript/typescript-linux-mips64el': 7.0.2 - '@typescript/typescript-linux-ppc64': 7.0.2 - '@typescript/typescript-linux-riscv64': 7.0.2 - '@typescript/typescript-linux-s390x': 7.0.2 - '@typescript/typescript-linux-x64': 7.0.2 - '@typescript/typescript-netbsd-arm64': 7.0.2 - '@typescript/typescript-netbsd-x64': 7.0.2 - '@typescript/typescript-openbsd-arm64': 7.0.2 - '@typescript/typescript-openbsd-x64': 7.0.2 - '@typescript/typescript-sunos-x64': 7.0.2 - '@typescript/typescript-win32-arm64': 7.0.2 - '@typescript/typescript-win32-x64': 7.0.2 - - undici-types@7.24.6: {} - - vite@8.3.2(@types/node@24.19.1): - dependencies: - lightningcss: 1.33.0 - picomatch: 4.0.7 - postcss: 8.5.29 - rolldown: 1.2.12 - tinyglobby: 0.2.17 - optionalDependencies: - '@types/node': 24.19.1 - fsevents: 2.3.3 - - vitest@5.0.3(@types/node@24.19.1)(jsdom@27.4.0)(vite@8.3.2(@types/node@24.19.1)): - dependencies: - '@types/chai': 5.2.3 - '@vitest/mocker': 5.0.3(vite@8.3.2(@types/node@24.19.1)) - chai: 6.3.0 - es-module-lexer: 2.3.2 - expect-type: 1.4.0 - magic-string: 1.4.3 - obug: 2.2.1 - picomatch: 4.0.7 - std-env: 4.3.0 - tinybench: 6.2.0 - tinyexec: 1.3.1 - tinyglobby: 0.2.17 - vite: 8.3.2(@types/node@24.19.1) - why-is-node-running: 3.2.1 - optionalDependencies: - '@types/node': 24.19.1 - jsdom: 27.4.0 - transitivePeerDependencies: - - msw - - w3c-xmlserializer@5.0.0: - dependencies: - xml-name-validator: 5.0.0 - - webidl-conversions@8.0.1: {} - - whatwg-mimetype@4.0.0: {} - - whatwg-mimetype@5.0.0: {} - - whatwg-url@15.1.0: - dependencies: - tr46: 6.0.0 - webidl-conversions: 8.0.1 - - why-is-node-running@3.2.1: {} - - ws@8.22.0: {} - - xml-name-validator@5.0.0: {} - - xmlchars@2.2.0: {} diff --git a/apps/web/src/App.test.tsx b/apps/web/src/App.test.tsx index 608867d..4decde4 100644 --- a/apps/web/src/App.test.tsx +++ b/apps/web/src/App.test.tsx @@ -2,8 +2,8 @@ import { cleanup, render, screen, waitFor } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { App } from "./App"; -import { createAuthClient } from "./authClient"; -import { captureInitialHandoff } from "./handoff"; +import { createAuthClient } from "./services/authClient"; +import { captureInitialHandoff } from "./services/handoff"; const user = { id: "u1", username: "ada", email: "ada@example.com", displayName: "Ada L", emailVerifiedAt: null }; const tokens = { accessToken: "access-1", expiresIn: 900, tokenType: "Bearer" }; diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 370e936..5407d34 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -1,7 +1,5 @@ import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from "react"; -import type { AuthClient } from "./authClient"; import { messageOf } from "./components"; -import { readPendingHandoff, runPendingHandoff } from "./handoff"; import { AccountPage, ContinuePage, @@ -11,7 +9,9 @@ import { RegisterPage, WorkingPage, } from "./pages"; -import { navigate, useLocation } from "./router"; +import type { AuthClient } from "./services/authClient"; +import { readPendingHandoff, runPendingHandoff } from "./services/handoff"; +import { navigate, useLocation } from "./utils/router"; type Handoff = { kind: "idle" } | { kind: "running" } | { kind: "done" } | { kind: "error"; message: string }; diff --git a/apps/web/src/components.tsx b/apps/web/src/components.tsx deleted file mode 100644 index f3ae63c..0000000 --- a/apps/web/src/components.tsx +++ /dev/null @@ -1,70 +0,0 @@ -import type { InputHTMLAttributes, MouseEvent, ReactNode } from "react"; -import { navigate } from "./router"; - -export function Shell({ title, children }: { title: string; children: ReactNode }) { - return ( -
-
-

OpenCollab

-

{title}

- {children} -
-
- ); -} - -/** In-app link: client-side navigation on a plain click, a normal link otherwise. */ -export function Link({ to, children }: { to: string; children: ReactNode }) { - const onClick = (event: MouseEvent) => { - if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return; - event.preventDefault(); - navigate(to); - }; - return ( - - {children} - - ); -} - -export function Field({ - label, - error, - hint, - id, - ...input -}: { label: string; error?: string; hint?: string; id: string } & InputHTMLAttributes) { - const describedBy = [error ? `${id}-error` : "", hint ? `${id}-hint` : ""].filter(Boolean).join(" ") || undefined; - return ( -
- - - {hint && ( -

- {hint} -

- )} - {error && ( -

- {error} -

- )} -
- ); -} - -export function OAuthButtons() { - return ( - - ); -} - -export const messageOf = (error: unknown): string => - error instanceof Error ? error.message : "Something went wrong. Please try again."; diff --git a/apps/web/src/components/Field.tsx b/apps/web/src/components/Field.tsx new file mode 100644 index 0000000..435c693 --- /dev/null +++ b/apps/web/src/components/Field.tsx @@ -0,0 +1,27 @@ +import type { InputHTMLAttributes } from "react"; + +export function Field({ + label, + error, + hint, + id, + ...input +}: { label: string; error?: string; hint?: string; id: string } & InputHTMLAttributes) { + const describedBy = [error ? `${id}-error` : "", hint ? `${id}-hint` : ""].filter(Boolean).join(" ") || undefined; + return ( +
+ + + {hint && ( +

+ {hint} +

+ )} + {error && ( +

+ {error} +

+ )} +
+ ); +} diff --git a/apps/web/src/components/Link.tsx b/apps/web/src/components/Link.tsx new file mode 100644 index 0000000..fb7094c --- /dev/null +++ b/apps/web/src/components/Link.tsx @@ -0,0 +1,16 @@ +import type { MouseEvent, ReactNode } from "react"; +import { navigate } from "../utils/router"; + +/** In-app link: client-side navigation on a plain click, a normal link otherwise. */ +export function Link({ to, children }: { to: string; children: ReactNode }) { + const onClick = (event: MouseEvent) => { + if (event.defaultPrevented || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey) return; + event.preventDefault(); + navigate(to); + }; + return ( + + {children} + + ); +} diff --git a/apps/web/src/components/OAuthButtons.tsx b/apps/web/src/components/OAuthButtons.tsx new file mode 100644 index 0000000..d1f2fbc --- /dev/null +++ b/apps/web/src/components/OAuthButtons.tsx @@ -0,0 +1,12 @@ +export function OAuthButtons() { + return ( + + ); +} diff --git a/apps/web/src/components/Shell.tsx b/apps/web/src/components/Shell.tsx new file mode 100644 index 0000000..0ac8cc5 --- /dev/null +++ b/apps/web/src/components/Shell.tsx @@ -0,0 +1,13 @@ +import type { ReactNode } from "react"; + +export function Shell({ title, children }: { title: string; children: ReactNode }) { + return ( +
+
+

OpenCollab

+

{title}

+ {children} +
+
+ ); +} diff --git a/apps/web/src/components/index.ts b/apps/web/src/components/index.ts new file mode 100644 index 0000000..5aaee54 --- /dev/null +++ b/apps/web/src/components/index.ts @@ -0,0 +1,7 @@ +export * from "./Field"; +export * from "./Link"; +export * from "./OAuthButtons"; +export * from "./Shell"; + +export const messageOf = (error: unknown): string => + error instanceof Error ? error.message : "Something went wrong. Please try again."; diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index ffa4c06..d9af1d5 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,8 +1,8 @@ import "@fontsource-variable/google-sans"; import { createRoot } from "react-dom/client"; import { App } from "./App"; -import { createAuthClient } from "./authClient"; -import { captureInitialHandoff } from "./handoff"; +import { createAuthClient } from "./services/authClient"; +import { captureInitialHandoff } from "./services/handoff"; import "./styles.css"; // Run once, before the first render (outside React, so StrictMode cannot repeat it). diff --git a/apps/web/src/pages.tsx b/apps/web/src/pages.tsx deleted file mode 100644 index a747e0c..0000000 --- a/apps/web/src/pages.tsx +++ /dev/null @@ -1,300 +0,0 @@ -import { useEffect, useState, type FormEvent } from "react"; -import type { AuthClient, Provider, UserView } from "./authClient"; -import { Field, Link, OAuthButtons, Shell, messageOf } from "./components"; -import { navigate } from "./router"; -import { oauthErrorMessage, validateLogin, validateRegister } from "./validation"; - -interface FormProps { - client: AuthClient; - search: string; - onAuthenticated: () => void; -} - -export function LoginPage({ client, search, onAuthenticated }: FormProps) { - const [identifier, setIdentifier] = useState(""); - const [password, setPassword] = useState(""); - const [errors, setErrors] = useState>({}); - const [failure, setFailure] = useState(() => oauthErrorMessage(new URLSearchParams(search).get("error"))); - const [busy, setBusy] = useState(false); - - const submit = async (event: FormEvent) => { - event.preventDefault(); - const found = validateLogin({ identifier, password }); - setErrors(found); - setFailure(null); - if (Object.keys(found).length > 0) return; - setBusy(true); - try { - await client.login(identifier.trim(), password); - onAuthenticated(); - } catch (error) { - setFailure(messageOf(error)); - setBusy(false); - } - }; - - return ( - - {failure && ( -

- {failure} -

- )} -
- setIdentifier(e.target.value)} - /> - setPassword(e.target.value)} - /> - - -

or

- -

- New here? Create an account -

-
- ); -} - -export function RegisterPage({ client, onAuthenticated }: Omit) { - const [values, setValues] = useState({ username: "", password: "", email: "", displayName: "" }); - const [errors, setErrors] = useState>({}); - const [failure, setFailure] = useState(null); - const [busy, setBusy] = useState(false); - const bind = (key: keyof typeof values) => ({ - value: values[key], - error: errors[key], - onChange: (e: { target: { value: string } }) => setValues((v) => ({ ...v, [key]: e.target.value })), - }); - - const submit = async (event: FormEvent) => { - event.preventDefault(); - const found = validateRegister(values); - setErrors(found); - setFailure(null); - if (Object.keys(found).length > 0) return; - setBusy(true); - try { - await client.register({ ...values, username: values.username.trim() }); - onAuthenticated(); - } catch (error) { - setFailure(messageOf(error)); - setBusy(false); - } - }; - - return ( - - {failure && ( -

- {failure} -

- )} -
- - - - - - -

or

- -

- Already have an account? Sign in -

-
- ); -} - -export function WorkingPage({ text }: { text: string }) { - return ( - -

{text}

-
- ); -} - -export function DonePage() { - return ( - -

You are signed in. Switch back to the OpenCollab desktop app to continue. You can close this tab.

-
- ); -} - -export function HandoffErrorPage({ message, onRetry }: { message: string; onRetry: () => void }) { - return ( - -

- {message} -

- -
- ); -} - -export function ContinuePage({ - client, - onContinue, - onSwitch, -}: { - client: AuthClient; - onContinue: () => void; - /** Signs out of the web session; rejects when the server could not confirm it. */ - onSwitch: () => Promise; -}) { - const [user, setUser] = useState(null); - const [failure, setFailure] = useState(null); - const [attempt, setAttempt] = useState(0); - useEffect(() => { - let current = true; - client.me().then( - (value) => current && setUser(value), - (error) => current && setFailure(messageOf(error)), - ); - return () => { - current = false; - }; - }, [client, attempt]); - - const retry = () => { - setFailure(null); - setAttempt((n) => n + 1); - }; - const switchAccount = () => { - setFailure(null); - onSwitch().catch(() => setFailure(SIGN_OUT_FAILED)); - }; - - return ( - -

You are already signed in on the web. Link this session to the desktop app?

- {failure && ( -

- {failure} -

- )} - - {failure && !user && ( - - )} - -
- ); -} - -const SIGN_OUT_FAILED = "Could not sign out, try again."; - -const PROVIDERS: Record = { github: "GitHub", google: "Google" }; -const isProvider = (value: string | null): value is Provider => value !== null && Object.hasOwn(PROVIDERS, value); - -export function AccountPage({ - client, - search, - assign, -}: { - client: AuthClient; - search: string; - assign: (url: string) => void; -}) { - const params = new URLSearchParams(search); - const linked = params.get("linked"); - const initialError = oauthErrorMessage(params.get("error")); - const [user, setUser] = useState(null); - const [failure, setFailure] = useState(initialError); - const [busy, setBusy] = useState(false); - - useEffect(() => { - client.me().then(setUser, (error) => setFailure(messageOf(error))); - }, [client]); - - const link = async (provider: Provider) => { - setBusy(true); - setFailure(null); - try { - assign(await client.linkStart(provider)); - } catch (error) { - setFailure(messageOf(error)); - setBusy(false); - } - }; - - const signOut = async () => { - setFailure(null); - try { - await client.logout(); - } catch { - setFailure(SIGN_OUT_FAILED); - return; - } - navigate("/login", true); - }; - - return ( - - {isProvider(linked) && ( -

- {PROVIDERS[linked]} account linked. -

- )} - {failure && ( -

- {failure} -

- )} - {user && ( -
-
Username
-
{user.username}
-
Email
-
{user.email ?? "Not set"}
-
Display name
-
{user.displayName ?? "Not set"}
-
- )} -

Link a provider

-
- {(Object.keys(PROVIDERS) as Provider[]).map((provider) => ( - - ))} -
- -
- ); -} diff --git a/apps/web/src/pages/AccountPage.tsx b/apps/web/src/pages/AccountPage.tsx new file mode 100644 index 0000000..4cfa67f --- /dev/null +++ b/apps/web/src/pages/AccountPage.tsx @@ -0,0 +1,89 @@ +import { useEffect, useState } from "react"; +import type { AuthClient, Provider, UserView } from "../services/authClient"; +import { Shell, messageOf } from "../components"; +import { navigate } from "../utils/router"; +import { oauthErrorMessage } from "../utils/validation"; + +const SIGN_OUT_FAILED = "Could not sign out, try again."; + +const PROVIDERS: Record = { github: "GitHub", google: "Google" }; +const isProvider = (value: string | null): value is Provider => value !== null && Object.hasOwn(PROVIDERS, value); + +export function AccountPage({ + client, + search, + assign, +}: { + client: AuthClient; + search: string; + assign: (url: string) => void; +}) { + const params = new URLSearchParams(search); + const linked = params.get("linked"); + const initialError = oauthErrorMessage(params.get("error")); + const [user, setUser] = useState(null); + const [failure, setFailure] = useState(initialError); + const [busy, setBusy] = useState(false); + + useEffect(() => { + client.me().then(setUser, (error) => setFailure(messageOf(error))); + }, [client]); + + const link = async (provider: Provider) => { + setBusy(true); + setFailure(null); + try { + assign(await client.linkStart(provider)); + } catch (error) { + setFailure(messageOf(error)); + setBusy(false); + } + }; + + const signOut = async () => { + setFailure(null); + try { + await client.logout(); + } catch { + setFailure(SIGN_OUT_FAILED); + return; + } + navigate("/login", true); + }; + + return ( + + {isProvider(linked) && ( +

+ {PROVIDERS[linked]} account linked. +

+ )} + {failure && ( +

+ {failure} +

+ )} + {user && ( +
+
Username
+
{user.username}
+
Email
+
{user.email ?? "Not set"}
+
Display name
+
{user.displayName ?? "Not set"}
+
+ )} +

Link a provider

+
+ {(Object.keys(PROVIDERS) as Provider[]).map((provider) => ( + + ))} +
+ +
+ ); +} diff --git a/apps/web/src/pages/AuthCompletePage.tsx b/apps/web/src/pages/AuthCompletePage.tsx new file mode 100644 index 0000000..4016634 --- /dev/null +++ b/apps/web/src/pages/AuthCompletePage.tsx @@ -0,0 +1,90 @@ +import { useEffect, useState } from "react"; +import type { AuthClient, UserView } from "../services/authClient"; +import { Shell, messageOf } from "../components"; + +export function WorkingPage({ text }: { text: string }) { + return ( + +

{text}

+
+ ); +} + +export function DonePage() { + return ( + +

You are signed in. Switch back to the OpenCollab desktop app to continue. You can close this tab.

+
+ ); +} + +export function HandoffErrorPage({ message, onRetry }: { message: string; onRetry: () => void }) { + return ( + +

+ {message} +

+ +
+ ); +} + +const SIGN_OUT_FAILED = "Could not sign out, try again."; + +export function ContinuePage({ + client, + onContinue, + onSwitch, +}: { + client: AuthClient; + onContinue: () => void; + /** Signs out of the web session; rejects when the server could not confirm it. */ + onSwitch: () => Promise; +}) { + const [user, setUser] = useState(null); + const [failure, setFailure] = useState(null); + const [attempt, setAttempt] = useState(0); + useEffect(() => { + let current = true; + client.me().then( + (value) => current && setUser(value), + (error) => current && setFailure(messageOf(error)), + ); + return () => { + current = false; + }; + }, [client, attempt]); + + const retry = () => { + setFailure(null); + setAttempt((n) => n + 1); + }; + const switchAccount = () => { + setFailure(null); + onSwitch().catch(() => setFailure(SIGN_OUT_FAILED)); + }; + + return ( + +

You are already signed in on the web. Link this session to the desktop app?

+ {failure && ( +

+ {failure} +

+ )} + + {failure && !user && ( + + )} + +
+ ); +} diff --git a/apps/web/src/pages/LoginPage.tsx b/apps/web/src/pages/LoginPage.tsx new file mode 100644 index 0000000..eacf22b --- /dev/null +++ b/apps/web/src/pages/LoginPage.tsx @@ -0,0 +1,71 @@ +import { useState, type FormEvent } from "react"; +import type { AuthClient } from "../services/authClient"; +import { Field, Link, OAuthButtons, Shell, messageOf } from "../components"; +import { oauthErrorMessage, validateLogin } from "../utils/validation"; + +export interface FormProps { + client: AuthClient; + search: string; + onAuthenticated: () => void; +} + +export function LoginPage({ client, search, onAuthenticated }: FormProps) { + const [identifier, setIdentifier] = useState(""); + const [password, setPassword] = useState(""); + const [errors, setErrors] = useState>({}); + const [failure, setFailure] = useState(() => oauthErrorMessage(new URLSearchParams(search).get("error"))); + const [busy, setBusy] = useState(false); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const found = validateLogin({ identifier, password }); + setErrors(found); + setFailure(null); + if (Object.keys(found).length > 0) return; + setBusy(true); + try { + await client.login(identifier.trim(), password); + onAuthenticated(); + } catch (error) { + setFailure(messageOf(error)); + setBusy(false); + } + }; + + return ( + + {failure && ( +

+ {failure} +

+ )} +
+ setIdentifier(e.target.value)} + /> + setPassword(e.target.value)} + /> + + +

or

+ +

+ New here? Create an account +

+
+ ); +} diff --git a/apps/web/src/pages/RegisterPage.tsx b/apps/web/src/pages/RegisterPage.tsx new file mode 100644 index 0000000..afeb861 --- /dev/null +++ b/apps/web/src/pages/RegisterPage.tsx @@ -0,0 +1,63 @@ +import { useState, type FormEvent } from "react"; +import { Field, Link, OAuthButtons, Shell, messageOf } from "../components"; +import { validateRegister } from "../utils/validation"; +import type { FormProps } from "./LoginPage"; + +export function RegisterPage({ client, onAuthenticated }: Omit) { + const [values, setValues] = useState({ username: "", password: "", email: "", displayName: "" }); + const [errors, setErrors] = useState>({}); + const [failure, setFailure] = useState(null); + const [busy, setBusy] = useState(false); + const bind = (key: keyof typeof values) => ({ + value: values[key], + error: errors[key], + onChange: (e: { target: { value: string } }) => setValues((v) => ({ ...v, [key]: e.target.value })), + }); + + const submit = async (event: FormEvent) => { + event.preventDefault(); + const found = validateRegister(values); + setErrors(found); + setFailure(null); + if (Object.keys(found).length > 0) return; + setBusy(true); + try { + await client.register({ ...values, username: values.username.trim() }); + onAuthenticated(); + } catch (error) { + setFailure(messageOf(error)); + setBusy(false); + } + }; + + return ( + + {failure && ( +

+ {failure} +

+ )} +
+ + + + + + +

or

+ +

+ Already have an account? Sign in +

+
+ ); +} diff --git a/apps/web/src/pages/index.ts b/apps/web/src/pages/index.ts new file mode 100644 index 0000000..220980c --- /dev/null +++ b/apps/web/src/pages/index.ts @@ -0,0 +1,4 @@ +export * from "./AccountPage"; +export * from "./AuthCompletePage"; +export * from "./LoginPage"; +export * from "./RegisterPage"; diff --git a/apps/web/src/authClient.test.ts b/apps/web/src/services/authClient.test.ts similarity index 100% rename from apps/web/src/authClient.test.ts rename to apps/web/src/services/authClient.test.ts diff --git a/apps/web/src/authClient.ts b/apps/web/src/services/authClient.ts similarity index 96% rename from apps/web/src/authClient.ts rename to apps/web/src/services/authClient.ts index 5e3a311..ecec4d8 100644 --- a/apps/web/src/authClient.ts +++ b/apps/web/src/services/authClient.ts @@ -231,8 +231,10 @@ export function createAuthClient(overrides: Partial = {}) { if (state.status === "authenticated") set({ ...state, user }); return user; }, - async desktopCode(codeChallenge: string): Promise { - const response = await webPost("desktop-code", { code_challenge: codeChallenge }); + async desktopCode(codeChallenge: string, client?: "desktop" | "desktop-dev"): Promise { + const body = + client && client !== "desktop" ? { code_challenge: codeChallenge, client } : { code_challenge: codeChallenge }; + const response = await webPost("desktop-code", body); if (!response.ok) throw await errorOf(response); return ((await response.json()) as { redirectUrl: string }).redirectUrl; }, diff --git a/apps/web/src/handoff.test.ts b/apps/web/src/services/handoff.test.ts similarity index 87% rename from apps/web/src/handoff.test.ts rename to apps/web/src/services/handoff.test.ts index 61e6705..ca61e1c 100644 --- a/apps/web/src/handoff.test.ts +++ b/apps/web/src/services/handoff.test.ts @@ -81,6 +81,17 @@ describe("runPendingHandoff", () => { expect(readPendingHandoff()).toBeNull(); }); + it("supports client=desktop-dev and redirects to opencollab-dev://", async () => { + expect(captureHandoff(`?client=desktop-dev&code_challenge=${challenge}`)).toBe(true); + expect(readPendingHandoff()).toBe(challenge); + const desktopCode = vi.fn(async () => "opencollab-dev://auth/callback?code=xyz"); + const assign = vi.fn(); + expect(await runPendingHandoff({ desktopCode }, assign)).toBe(true); + expect(desktopCode).toHaveBeenCalledWith(challenge, "desktop-dev"); + expect(assign).toHaveBeenCalledWith("opencollab-dev://auth/callback?code=xyz"); + expect(readPendingHandoff()).toBeNull(); + }); + it("refuses to navigate to anything but the opencollab deep link", async () => { captureHandoff(`?client=desktop&code_challenge=${challenge}`); const assign = vi.fn(); diff --git a/apps/web/src/handoff.ts b/apps/web/src/services/handoff.ts similarity index 65% rename from apps/web/src/handoff.ts rename to apps/web/src/services/handoff.ts index b684a3d..c56f760 100644 --- a/apps/web/src/handoff.ts +++ b/apps/web/src/services/handoff.ts @@ -3,7 +3,10 @@ // survives the OAuth round trip; tokens never touch storage. const KEY = "opencollab.handoff.challenge"; -const DEEP_LINK_PREFIX = "opencollab://"; +const CLIENT_KEY = "opencollab.handoff.client"; +const DEEP_LINK_PREFIXES = ["opencollab://", "opencollab-dev://"]; + +export type DesktopHandoffClient = "desktop" | "desktop-dev"; // S256 challenge: base64url of a 32-byte digest is always 43 chars. export const isValidCodeChallenge = (value: string): boolean => /^[A-Za-z0-9_-]{43}$/.test(value); @@ -17,9 +20,18 @@ export function readPendingHandoff(): string | null { } } +export function readPendingHandoffClient(): DesktopHandoffClient { + try { + return sessionStorage.getItem(CLIENT_KEY) === "desktop-dev" ? "desktop-dev" : "desktop"; + } catch { + return "desktop"; + } +} + export function clearPendingHandoff(): void { try { sessionStorage.removeItem(KEY); + sessionStorage.removeItem(CLIENT_KEY); } catch { // Storage unavailable: nothing was persisted. } @@ -36,9 +48,14 @@ export function captureHandoff(search: string): boolean { const client = params.get("client"); const challenge = params.get("code_challenge"); if (client === null && challenge === null) return false; - if (client === "desktop" && challenge !== null && isValidCodeChallenge(challenge)) { + if ((client === "desktop" || client === "desktop-dev") && challenge !== null && isValidCodeChallenge(challenge)) { try { sessionStorage.setItem(KEY, challenge); + if (client === "desktop-dev") { + sessionStorage.setItem(CLIENT_KEY, "desktop-dev"); + } else { + sessionStorage.removeItem(CLIENT_KEY); + } } catch { // Without storage the handoff only survives password login (no OAuth trip). } @@ -50,13 +67,17 @@ export function captureHandoff(search: string): boolean { /** Exchanges the pending challenge for a deep link and navigates to it. Returns whether a handoff ran. */ export async function runPendingHandoff( - api: { desktopCode(challenge: string): Promise }, + api: { desktopCode(challenge: string, client?: DesktopHandoffClient): Promise }, assign: (url: string) => void, ): Promise { const challenge = readPendingHandoff(); if (!challenge) return false; - const redirectUrl = await api.desktopCode(challenge); - if (!redirectUrl.startsWith(DEEP_LINK_PREFIX)) throw new Error("Unexpected redirect target"); + const client = readPendingHandoffClient(); + const redirectUrl = + client === "desktop-dev" ? await api.desktopCode(challenge, "desktop-dev") : await api.desktopCode(challenge); + if (!DEEP_LINK_PREFIXES.some((prefix) => redirectUrl.startsWith(prefix))) { + throw new Error("Unexpected redirect target"); + } clearPendingHandoff(); assign(redirectUrl); return true; diff --git a/apps/web/src/router.ts b/apps/web/src/utils/router.ts similarity index 100% rename from apps/web/src/router.ts rename to apps/web/src/utils/router.ts diff --git a/apps/web/src/validation.test.ts b/apps/web/src/utils/validation.test.ts similarity index 100% rename from apps/web/src/validation.test.ts rename to apps/web/src/utils/validation.test.ts diff --git a/apps/web/src/validation.ts b/apps/web/src/utils/validation.ts similarity index 98% rename from apps/web/src/validation.ts rename to apps/web/src/utils/validation.ts index 61dadf5..05ef35a 100644 --- a/apps/web/src/validation.ts +++ b/apps/web/src/utils/validation.ts @@ -1,4 +1,4 @@ -// Client-side checks that mirror the server's zod schemas (apps/server/src/auth/dto.ts). +// Client-side checks that mirror the server's zod schemas (apps/api/src/auth/dto.ts). // The server stays the authority; this only saves a round trip and explains the rule. export interface RegisterValues { diff --git a/apps/web/vite.config.ts b/apps/web/vite.config.ts index 3f39f38..23ad890 100644 --- a/apps/web/vite.config.ts +++ b/apps/web/vite.config.ts @@ -1,10 +1,11 @@ import { defineConfig } from "vitest/config"; +import { loadEnv } from "vite"; import react from "@vitejs/plugin-react"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; -// Same-origin with the API: /auth is proxied to the server, so the httpOnly -// refresh cookie (Path=/auth) works and no CORS is needed. -const api = process.env.OPENCOLLAB_API ?? "http://127.0.0.1:8787"; -const proxy = { "/auth": { target: api, changeOrigin: false } }; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +const rootDir = path.resolve(__dirname, "../../"); // Production must serve the same header from the reverse proxy (see AGENTS.md). // Not applied to the dev server: React Fast Refresh needs an inline script there. @@ -21,21 +22,33 @@ export const CSP = [ "frame-ancestors 'none'", ].join("; "); -export default defineConfig({ - plugins: [react()], - clearScreen: false, - // No inlined data: URIs, so the CSP can keep font-src 'self'. - build: { assetsInlineLimit: 0 }, - server: { port: 1421, strictPort: true, proxy }, - preview: { - port: 1421, - strictPort: true, - proxy, - headers: { "Content-Security-Policy": CSP }, - }, - test: { - environment: "jsdom", - include: ["src/**/*.test.{ts,tsx}"], - restoreMocks: true, - }, +export default defineConfig(({ mode }) => { + // Same-origin with the API: /auth is proxied to the server, so the httpOnly + // refresh cookie (Path=/auth) works and no CORS is needed. + const env = loadEnv(mode, rootDir, ""); + const api = + process.env.OPENCOLLAB_API ?? + env.OPENCOLLAB_API ?? + (env.RELAY_ADDR ? `http://${env.RELAY_ADDR}` : undefined) ?? + "http://127.0.0.1:8787"; + const proxy = { "/auth": { target: api, changeOrigin: false } }; + + return { + plugins: [react()], + clearScreen: false, + // No inlined data: URIs, so the CSP can keep font-src 'self'. + build: { assetsInlineLimit: 0 }, + server: { port: 1421, strictPort: true, proxy }, + preview: { + port: 1421, + strictPort: true, + proxy, + headers: { "Content-Security-Policy": CSP }, + }, + test: { + environment: "jsdom", + include: ["src/**/*.test.{ts,tsx}"], + restoreMocks: true, + }, + }; }); diff --git a/crates/application/src/ports.rs b/crates/application/src/ports.rs deleted file mode 100644 index d547ff4..0000000 --- a/crates/application/src/ports.rs +++ /dev/null @@ -1,99 +0,0 @@ -//! Puertos que la infraestructura implementa. Sincrónicos a propósito: la -//! capa de aplicación no depende de un runtime async. - -use std::sync::Arc; -use std::time::Duration; - -use crate::agent_detection::ProcessInfo; -use crate::git::Branch; - -use domain::{ - AccessLevel, AgentProfile, Session, SessionId, TerminalId, UserId, Workspace, WorkspaceId, -}; - -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -#[error("{0}")] -pub struct PortError(pub String); - -impl PortError { - pub fn new(message: impl Into) -> Self { - Self(message.into()) - } -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct TerminalSize { - pub cols: u16, - pub rows: u16, -} - -impl Default for TerminalSize { - fn default() -> Self { - Self { cols: 80, rows: 24 } - } -} - -/// Recibe la salida de los PTY. El adaptador de entrada (Tauri, relay) la -/// reenvía a quien corresponda. -pub trait TerminalOutputSink: Send + Sync { - fn output(&self, terminal: TerminalId, data: &[u8]); - fn exited(&self, terminal: TerminalId); -} - -pub trait PtyPort: Send + Sync { - fn spawn( - &self, - terminal: TerminalId, - profile: &AgentProfile, - size: TerminalSize, - sink: Arc, - ) -> Result<(), PortError>; - fn write(&self, terminal: TerminalId, data: &[u8]) -> Result<(), PortError>; - fn resize(&self, terminal: TerminalId, size: TerminalSize) -> Result<(), PortError>; - /// Termina el proceso. Si ya había terminado, no es un error. - fn kill(&self, terminal: TerminalId) -> Result<(), PortError>; - /// Pid del proceso raíz de la terminal, si sigue vivo. - fn process_id(&self, terminal: TerminalId) -> Option; -} - -/// Lectura de carpetas del disco local, para navegar desde el header de una terminal. -pub trait DirectoryBrowser: Send + Sync { - /// Nombres de las subcarpetas directas de `path` (sin orden garantizado). - fn subdirectories(&self, path: &std::path::Path) -> Result, PortError>; -} - -/// Lee el estado de git de una carpeta del disco local. -pub trait RepositoryInspector: Send + Sync { - /// Rama (o commit, si `HEAD` está desacoplado) de la carpeta, buscando hacia - /// arriba el repositorio que la contiene. `None` fuera de un repositorio. - fn current_branch(&self, path: &std::path::Path) -> Option; -} - -/// Foto de los procesos del sistema, para detectar qué corre en cada terminal. -pub trait ProcessInspector: Send + Sync { - fn snapshot(&self) -> Result, PortError>; -} - -/// Sondea al relay de colaboración. Bloquea hasta responder o agotar su timeout, -/// así que quien lo llame periódicamente debe hacerlo fuera del hilo de la UI. -pub trait RelayProbe: Send + Sync { - /// Tiempo de ida y vuelta si el relay respondió bien; error si no. - fn probe(&self) -> Result; -} - -pub trait WorkspaceRepository: Send + Sync { - fn find_workspace(&self, id: WorkspaceId) -> Result, PortError>; - fn save_workspace(&self, workspace: Workspace) -> Result<(), PortError>; - fn find_session(&self, id: SessionId) -> Result, PortError>; - fn save_session(&self, session: Session) -> Result<(), PortError>; -} - -/// Salida hacia los demás participantes (vía relay). -pub trait CollabTransport: Send + Sync { - fn access_changed( - &self, - session: SessionId, - user: UserId, - access: AccessLevel, - ) -> Result<(), PortError>; -} diff --git a/crates/domain/src/error.rs b/crates/domain/src/error.rs deleted file mode 100644 index 97571e7..0000000 --- a/crates/domain/src/error.rs +++ /dev/null @@ -1,24 +0,0 @@ -use crate::ids::{SessionId, TerminalId, UserId, WorkspaceId}; - -#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] -pub enum DomainError { - #[error("solo el dueño del workspace puede realizar esta acción")] - NotOwner, - #[error("los permisos del dueño no se pueden modificar")] - CannotChangeOwnerAccess, - #[error("{0} no participa de la sesión")] - NotAParticipant(UserId), - #[error("{0} ya tiene acceso")] - AlreadyHasAccess(UserId), - #[error("la sesión {session} no pertenece al workspace {workspace}")] - WorkspaceMismatch { - session: SessionId, - workspace: WorkspaceId, - }, - #[error("la invitación no corresponde a este destino")] - InvitationTargetMismatch, - #[error("la terminal {0} no pertenece a la sesión")] - TerminalNotInSession(TerminalId), - #[error("el comando del perfil de agente no puede estar vacío")] - EmptyCommand, -} diff --git a/crates/domain/src/invitation.rs b/crates/domain/src/invitation.rs deleted file mode 100644 index 291429c..0000000 --- a/crates/domain/src/invitation.rs +++ /dev/null @@ -1,19 +0,0 @@ -use crate::ids::{InvitationId, SessionId, UserId, WorkspaceId}; - -/// A qué da acceso una invitación. Las dos formas de colaborar son distintas: -/// miembro fijo del workspace o invitado temporal de una sola sesión. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum InvitationTarget { - Workspace(WorkspaceId), - Session(SessionId), -} - -/// Se crea con `Workspace::invite_member` o `Session::invite_guest`, que -/// validan que quien invita sea el dueño. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Invitation { - pub id: InvitationId, - pub target: InvitationTarget, - pub invitee: UserId, - pub invited_by: UserId, -} diff --git a/crates/domain/src/lib.rs b/crates/domain/src/lib.rs deleted file mode 100644 index a8c7395..0000000 --- a/crates/domain/src/lib.rs +++ /dev/null @@ -1,18 +0,0 @@ -//! Dominio de OpenCollab: Workspace → Session → Terminal, y las reglas de -//! acceso (Ver es el mínimo y viene activo por defecto). Sin I/O. - -mod error; -mod ids; -mod invitation; -mod permission; -mod session; -mod terminal; -mod workspace; - -pub use error::DomainError; -pub use ids::{InvalidId, InvitationId, SessionId, TerminalId, UserId, WorkspaceId}; -pub use invitation::{Invitation, InvitationTarget}; -pub use permission::AccessLevel; -pub use session::{Participant, ParticipantRole, Session, SessionGuest}; -pub use terminal::{AgentProfile, Terminal}; -pub use workspace::{Workspace, WorkspaceMember}; diff --git a/crates/domain/src/session.rs b/crates/domain/src/session.rs deleted file mode 100644 index 57408bc..0000000 --- a/crates/domain/src/session.rs +++ /dev/null @@ -1,536 +0,0 @@ -use std::collections::HashMap; - -use crate::error::DomainError; -use crate::ids::{InvitationId, SessionId, TerminalId, UserId, WorkspaceId}; -use crate::invitation::{Invitation, InvitationTarget}; -use crate::permission::AccessLevel; -use crate::terminal::{AgentProfile, Terminal}; -use crate::workspace::Workspace; - -/// Invitado temporal: accede solo a esta sesión, nunca al resto del workspace. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct SessionGuest { - pub user_id: UserId, - pub access: AccessLevel, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum ParticipantRole { - Owner, - Member, - Guest, -} - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub struct Participant { - pub user_id: UserId, - pub role: ParticipantRole, - pub access: AccessLevel, -} - -/// Grupo de varias terminales que se ven juntas en una grilla. Es la unidad -/// que se comparte en vivo. -/// -/// El acceso efectivo de un miembro del workspace es su override en esta -/// sesión o, si no tiene, [`AccessLevel::DEFAULT`] (Ver). Así un miembro -/// agregado después de crear la sesión también arranca con Ver, sin tener -/// que recorrer las sesiones existentes. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Session { - id: SessionId, - workspace_id: WorkspaceId, - name: String, - terminals: Vec, - member_overrides: HashMap, - guests: Vec, -} - -impl Session { - pub fn new( - workspace: &Workspace, - actor: UserId, - name: impl Into, - ) -> Result { - workspace.ensure_owner(actor)?; - Ok(Self { - id: SessionId::new(), - workspace_id: workspace.id(), - name: name.into(), - terminals: Vec::new(), - member_overrides: HashMap::new(), - guests: Vec::new(), - }) - } - - pub fn id(&self) -> SessionId { - self.id - } - - pub fn workspace_id(&self) -> WorkspaceId { - self.workspace_id - } - - pub fn name(&self) -> &str { - &self.name - } - - pub fn terminals(&self) -> &[Terminal] { - &self.terminals - } - - pub fn terminal(&self, id: TerminalId) -> Option<&Terminal> { - self.terminals.iter().find(|t| t.id == id) - } - - pub fn guests(&self) -> &[SessionGuest] { - &self.guests - } - - fn ensure_belongs_to(&self, workspace: &Workspace) -> Result<(), DomainError> { - if workspace.id() == self.workspace_id { - Ok(()) - } else { - Err(DomainError::WorkspaceMismatch { - session: self.id, - workspace: workspace.id(), - }) - } - } - - fn guest(&self, user: UserId) -> Option<&SessionGuest> { - self.guests.iter().find(|g| g.user_id == user) - } - - fn role_of(&self, workspace: &Workspace, user: UserId) -> Option { - if workspace.is_owner(user) { - Some(ParticipantRole::Owner) - } else if workspace.is_member(user) { - Some(ParticipantRole::Member) - } else if self.guest(user).is_some() { - Some(ParticipantRole::Guest) - } else { - None - } - } - - /// Fuente única de verdad del acceso de `user` a esta sesión. - /// Si `workspace` no es el de la sesión, el resultado es `None` (sin acceso). - pub fn access_of(&self, workspace: &Workspace, user: UserId) -> AccessLevel { - if self.ensure_belongs_to(workspace).is_err() { - return AccessLevel::None; - } - match self.role_of(workspace, user) { - Some(ParticipantRole::Owner) => AccessLevel::Write, - Some(ParticipantRole::Member) => self - .member_overrides - .get(&user) - .copied() - .unwrap_or(AccessLevel::DEFAULT), - Some(ParticipantRole::Guest) => self - .guest(user) - .map(|g| g.access) - .unwrap_or(AccessLevel::None), - None => AccessLevel::None, - } - } - - pub fn can_view(&self, workspace: &Workspace, user: UserId) -> bool { - self.access_of(workspace, user).can_view() - } - - pub fn can_write(&self, workspace: &Workspace, user: UserId) -> bool { - self.access_of(workspace, user).can_write() - } - - /// Todos los que podrían participar (dueño, miembros e invitados) con su acceso vigente. - pub fn participants(&self, workspace: &Workspace) -> Vec { - if self.ensure_belongs_to(workspace).is_err() { - return Vec::new(); - } - let owner = std::iter::once(workspace.owner()); - let members = workspace.members().iter().map(|m| m.user_id); - let guests = self.guests.iter().map(|g| g.user_id); - owner - .chain(members) - .chain(guests) - .filter_map(|user_id| { - self.role_of(workspace, user_id).map(|role| Participant { - user_id, - role, - access: self.access_of(workspace, user_id), - }) - }) - .collect() - } - - /// Cambia el acceso de un participante. Solo el dueño puede hacerlo, en - /// cualquier momento mientras la sesión está activa. Devuelve el nivel resultante. - pub fn set_access( - &mut self, - workspace: &Workspace, - actor: UserId, - target: UserId, - level: AccessLevel, - ) -> Result { - self.ensure_belongs_to(workspace)?; - workspace.ensure_owner(actor)?; - match self.role_of(workspace, target) { - Some(ParticipantRole::Owner) => Err(DomainError::CannotChangeOwnerAccess), - Some(ParticipantRole::Member) => { - self.member_overrides.insert(target, level); - Ok(level) - } - Some(ParticipantRole::Guest) => { - let guest = self - .guests - .iter_mut() - .find(|g| g.user_id == target) - .ok_or(DomainError::NotAParticipant(target))?; - guest.access = level; - Ok(level) - } - None => Err(DomainError::NotAParticipant(target)), - } - } - - /// Activa/desactiva Ver. Desactivarlo revoca Escribir y el acceso. - pub fn set_view( - &mut self, - workspace: &Workspace, - actor: UserId, - target: UserId, - enabled: bool, - ) -> Result { - let level = self.access_of(workspace, target).with_view(enabled); - self.set_access(workspace, actor, target, level) - } - - /// Activa/desactiva Escribir. Activarlo activa también Ver. - pub fn set_write( - &mut self, - workspace: &Workspace, - actor: UserId, - target: UserId, - enabled: bool, - ) -> Result { - let level = self.access_of(workspace, target).with_write(enabled); - self.set_access(workspace, actor, target, level) - } - - pub fn invite_guest( - &self, - workspace: &Workspace, - actor: UserId, - invitee: UserId, - ) -> Result { - self.ensure_belongs_to(workspace)?; - workspace.ensure_owner(actor)?; - if self.role_of(workspace, invitee).is_some() { - return Err(DomainError::AlreadyHasAccess(invitee)); - } - Ok(Invitation { - id: InvitationId::new(), - target: InvitationTarget::Session(self.id), - invitee, - invited_by: actor, - }) - } - - /// El invitado entra con Ver, el mínimo para que la sesión esté compartida. - pub fn accept_invitation( - &mut self, - workspace: &Workspace, - invitation: &Invitation, - ) -> Result<(), DomainError> { - self.ensure_belongs_to(workspace)?; - if invitation.target != InvitationTarget::Session(self.id) { - return Err(DomainError::InvitationTargetMismatch); - } - workspace.ensure_owner(invitation.invited_by)?; - if self.role_of(workspace, invitation.invitee).is_some() { - return Err(DomainError::AlreadyHasAccess(invitation.invitee)); - } - self.guests.push(SessionGuest { - user_id: invitation.invitee, - access: AccessLevel::DEFAULT, - }); - Ok(()) - } - - pub fn add_terminal( - &mut self, - workspace: &Workspace, - actor: UserId, - profile: AgentProfile, - ) -> Result { - self.ensure_belongs_to(workspace)?; - workspace.ensure_owner(actor)?; - let id = TerminalId::new(); - self.terminals.push(Terminal { id, profile }); - Ok(id) - } - - /// Quita una terminal de la sesión. Igual que agregarlas, es del dueño. - pub fn remove_terminal( - &mut self, - workspace: &Workspace, - actor: UserId, - id: TerminalId, - ) -> Result<(), DomainError> { - self.ensure_belongs_to(workspace)?; - workspace.ensure_owner(actor)?; - self.ensure_has_terminal(id)?; - self.terminals.retain(|t| t.id != id); - Ok(()) - } - - pub fn ensure_has_terminal(&self, id: TerminalId) -> Result<(), DomainError> { - self.terminal(id) - .map(|_| ()) - .ok_or(DomainError::TerminalNotInSession(id)) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - struct Fixture { - owner: UserId, - member: UserId, - workspace: Workspace, - session: Session, - } - - fn fixture() -> Fixture { - let owner = UserId::new(); - let member = UserId::new(); - let mut workspace = Workspace::new(owner, "proyecto"); - workspace.add_member(owner, member).unwrap(); - let session = Session::new(&workspace, owner, "sesión").unwrap(); - Fixture { - owner, - member, - workspace, - session, - } - } - - fn with_guest(f: &mut Fixture) -> UserId { - let guest = UserId::new(); - let inv = f - .session - .invite_guest(&f.workspace, f.owner, guest) - .unwrap(); - f.session.accept_invitation(&f.workspace, &inv).unwrap(); - guest - } - - #[test] - fn only_owner_removes_terminals() { - let mut f = fixture(); - let profile = AgentProfile::new("shell", "sh").unwrap(); - let terminal = f - .session - .add_terminal(&f.workspace, f.owner, profile) - .unwrap(); - assert_eq!( - f.session.remove_terminal(&f.workspace, f.member, terminal), - Err(DomainError::NotOwner) - ); - f.session - .remove_terminal(&f.workspace, f.owner, terminal) - .unwrap(); - assert!(f.session.terminal(terminal).is_none()); - assert_eq!( - f.session.remove_terminal(&f.workspace, f.owner, terminal), - Err(DomainError::TerminalNotInSession(terminal)) - ); - } - - #[test] - fn member_starts_with_view_by_default() { - let f = fixture(); - assert_eq!( - f.session.access_of(&f.workspace, f.member), - AccessLevel::View - ); - assert!(f.session.can_view(&f.workspace, f.member)); - assert!(!f.session.can_write(&f.workspace, f.member)); - } - - #[test] - fn member_added_after_session_creation_also_gets_view() { - let mut f = fixture(); - let late = UserId::new(); - f.workspace.add_member(f.owner, late).unwrap(); - assert_eq!(f.session.access_of(&f.workspace, late), AccessLevel::View); - } - - #[test] - fn guest_starts_with_view() { - let mut f = fixture(); - let guest = with_guest(&mut f); - assert_eq!(f.session.access_of(&f.workspace, guest), AccessLevel::View); - } - - #[test] - fn enabling_write_enables_view() { - let mut f = fixture(); - f.session - .set_view(&f.workspace, f.owner, f.member, false) - .unwrap(); - let level = f - .session - .set_write(&f.workspace, f.owner, f.member, true) - .unwrap(); - assert_eq!(level, AccessLevel::Write); - assert!(f.session.can_view(&f.workspace, f.member)); - assert!(f.session.can_write(&f.workspace, f.member)); - } - - #[test] - fn no_participant_can_write_without_view() { - let mut f = fixture(); - let guest = with_guest(&mut f); - for user in [f.owner, f.member, guest] { - for (view, write) in [(true, true), (false, true), (true, false), (false, false)] { - if user != f.owner { - let _ = f.session.set_write(&f.workspace, f.owner, user, write); - let _ = f.session.set_view(&f.workspace, f.owner, user, view); - } - if f.session.can_write(&f.workspace, user) { - assert!(f.session.can_view(&f.workspace, user)); - } - } - } - } - - #[test] - fn removing_view_revokes_write_and_access() { - let mut f = fixture(); - f.session - .set_write(&f.workspace, f.owner, f.member, true) - .unwrap(); - f.session - .set_view(&f.workspace, f.owner, f.member, false) - .unwrap(); - assert_eq!( - f.session.access_of(&f.workspace, f.member), - AccessLevel::None - ); - assert!(!f.session.can_view(&f.workspace, f.member)); - assert!(!f.session.can_write(&f.workspace, f.member)); - } - - #[test] - fn removing_view_for_guest_revokes_access() { - let mut f = fixture(); - let guest = with_guest(&mut f); - f.session - .set_view(&f.workspace, f.owner, guest, false) - .unwrap(); - assert!(!f.session.can_view(&f.workspace, guest)); - } - - #[test] - fn view_override_is_per_session() { - let mut f = fixture(); - let other = Session::new(&f.workspace, f.owner, "otra").unwrap(); - f.session - .set_view(&f.workspace, f.owner, f.member, false) - .unwrap(); - assert!(!f.session.can_view(&f.workspace, f.member)); - assert!(other.can_view(&f.workspace, f.member)); - } - - #[test] - fn guest_cannot_see_other_sessions_of_the_workspace() { - let mut f = fixture(); - let guest = with_guest(&mut f); - let other = Session::new(&f.workspace, f.owner, "otra").unwrap(); - assert!(f.session.can_view(&f.workspace, guest)); - assert!(!other.can_view(&f.workspace, guest)); - assert!(!f.workspace.is_member(guest)); - } - - #[test] - fn only_owner_can_change_permissions() { - let mut f = fixture(); - let guest = with_guest(&mut f); - assert_eq!( - f.session.set_write(&f.workspace, f.member, guest, true), - Err(DomainError::NotOwner) - ); - assert_eq!( - f.session.set_view(&f.workspace, guest, f.member, false), - Err(DomainError::NotOwner) - ); - assert_eq!(f.session.access_of(&f.workspace, guest), AccessLevel::View); - assert_eq!( - f.session.access_of(&f.workspace, f.member), - AccessLevel::View - ); - } - - #[test] - fn owner_always_has_full_access() { - let mut f = fixture(); - assert_eq!( - f.session.access_of(&f.workspace, f.owner), - AccessLevel::Write - ); - assert_eq!( - f.session.set_view(&f.workspace, f.owner, f.owner, false), - Err(DomainError::CannotChangeOwnerAccess) - ); - assert_eq!( - f.session.access_of(&f.workspace, f.owner), - AccessLevel::Write - ); - } - - #[test] - fn strangers_have_no_access() { - let f = fixture(); - assert_eq!( - f.session.access_of(&f.workspace, UserId::new()), - AccessLevel::None - ); - } - - #[test] - fn removed_member_loses_access() { - let mut f = fixture(); - f.workspace.remove_member(f.owner, f.member).unwrap(); - assert!(!f.session.can_view(&f.workspace, f.member)); - } - - #[test] - fn cannot_invite_existing_member_as_guest() { - let f = fixture(); - assert_eq!( - f.session.invite_guest(&f.workspace, f.owner, f.member), - Err(DomainError::AlreadyHasAccess(f.member)) - ); - } - - #[test] - fn wrong_workspace_grants_no_access() { - let f = fixture(); - let foreign = Workspace::new(f.member, "ajeno"); - assert_eq!(f.session.access_of(&foreign, f.member), AccessLevel::None); - } - - #[test] - fn participants_lists_effective_access() { - let mut f = fixture(); - let guest = with_guest(&mut f); - let participants = f.session.participants(&f.workspace); - assert_eq!(participants.len(), 3); - let find = |u| participants.iter().find(|p| p.user_id == u).unwrap(); - assert_eq!(find(f.owner).role, ParticipantRole::Owner); - assert_eq!(find(f.member).access, AccessLevel::View); - assert_eq!(find(guest).role, ParticipantRole::Guest); - } -} diff --git a/crates/domain/src/workspace.rs b/crates/domain/src/workspace.rs deleted file mode 100644 index 656091f..0000000 --- a/crates/domain/src/workspace.rs +++ /dev/null @@ -1,140 +0,0 @@ -use crate::error::DomainError; -use crate::ids::{InvitationId, UserId, WorkspaceId}; -use crate::invitation::{Invitation, InvitationTarget}; - -/// Miembro fijo del workspace: equipo estable, permanente hasta que el dueño lo quite. -/// Accede a todas las sesiones del workspace con Ver por defecto. -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct WorkspaceMember { - pub user_id: UserId, -} - -#[derive(Debug, Clone, PartialEq, Eq)] -pub struct Workspace { - id: WorkspaceId, - name: String, - owner: UserId, - members: Vec, -} - -impl Workspace { - pub fn new(owner: UserId, name: impl Into) -> Self { - Self { - id: WorkspaceId::new(), - name: name.into(), - owner, - members: Vec::new(), - } - } - - pub fn id(&self) -> WorkspaceId { - self.id - } - - pub fn name(&self) -> &str { - &self.name - } - - pub fn owner(&self) -> UserId { - self.owner - } - - pub fn members(&self) -> &[WorkspaceMember] { - &self.members - } - - pub fn is_owner(&self, user: UserId) -> bool { - self.owner == user - } - - pub fn is_member(&self, user: UserId) -> bool { - self.members.iter().any(|m| m.user_id == user) - } - - pub fn ensure_owner(&self, actor: UserId) -> Result<(), DomainError> { - if self.is_owner(actor) { - Ok(()) - } else { - Err(DomainError::NotOwner) - } - } - - pub fn invite_member(&self, actor: UserId, invitee: UserId) -> Result { - self.ensure_owner(actor)?; - if self.is_owner(invitee) || self.is_member(invitee) { - return Err(DomainError::AlreadyHasAccess(invitee)); - } - Ok(Invitation { - id: InvitationId::new(), - target: InvitationTarget::Workspace(self.id), - invitee, - invited_by: actor, - }) - } - - pub fn accept_invitation(&mut self, invitation: &Invitation) -> Result<(), DomainError> { - if invitation.target != InvitationTarget::Workspace(self.id) { - return Err(DomainError::InvitationTargetMismatch); - } - self.add_member(invitation.invited_by, invitation.invitee) - } - - pub fn add_member(&mut self, actor: UserId, user: UserId) -> Result<(), DomainError> { - self.ensure_owner(actor)?; - if self.is_owner(user) || self.is_member(user) { - return Err(DomainError::AlreadyHasAccess(user)); - } - self.members.push(WorkspaceMember { user_id: user }); - Ok(()) - } - - pub fn remove_member(&mut self, actor: UserId, user: UserId) -> Result<(), DomainError> { - self.ensure_owner(actor)?; - let before = self.members.len(); - self.members.retain(|m| m.user_id != user); - if self.members.len() == before { - return Err(DomainError::NotAParticipant(user)); - } - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn only_owner_adds_members() { - let owner = UserId::new(); - let other = UserId::new(); - let mut ws = Workspace::new(owner, "proyecto"); - assert_eq!( - ws.add_member(other, UserId::new()), - Err(DomainError::NotOwner) - ); - assert!(ws.add_member(owner, other).is_ok()); - assert!(ws.is_member(other)); - } - - #[test] - fn accepting_workspace_invitation_adds_member() { - let owner = UserId::new(); - let invitee = UserId::new(); - let mut ws = Workspace::new(owner, "proyecto"); - let inv = ws.invite_member(owner, invitee).unwrap(); - ws.accept_invitation(&inv).unwrap(); - assert!(ws.is_member(invitee)); - } - - #[test] - fn non_owner_cannot_invite() { - let owner = UserId::new(); - let member = UserId::new(); - let mut ws = Workspace::new(owner, "proyecto"); - ws.add_member(owner, member).unwrap(); - assert_eq!( - ws.invite_member(member, UserId::new()), - Err(DomainError::NotOwner) - ); - } -} diff --git a/crates/infrastructure/src/memory_repository.rs b/crates/infrastructure/src/memory_repository.rs deleted file mode 100644 index 29d074e..0000000 --- a/crates/infrastructure/src/memory_repository.rs +++ /dev/null @@ -1,69 +0,0 @@ -use std::collections::HashMap; -use std::sync::Mutex; - -use application::ports::{PortError, WorkspaceRepository}; -use domain::{Session, SessionId, Workspace, WorkspaceId}; - -/// Repositorio en memoria. Sirve para el desktop mientras no haya persistencia. -#[derive(Default)] -pub struct InMemoryWorkspaceRepository { - workspaces: Mutex>, - sessions: Mutex>, -} - -impl InMemoryWorkspaceRepository { - pub fn new() -> Self { - Self::default() - } -} - -fn poisoned(_: T) -> PortError { - PortError::new("repositorio en memoria envenenado") -} - -impl WorkspaceRepository for InMemoryWorkspaceRepository { - fn find_workspace(&self, id: WorkspaceId) -> Result, PortError> { - Ok(self.workspaces.lock().map_err(poisoned)?.get(&id).cloned()) - } - - fn save_workspace(&self, workspace: Workspace) -> Result<(), PortError> { - self.workspaces - .lock() - .map_err(poisoned)? - .insert(workspace.id(), workspace); - Ok(()) - } - - fn find_session(&self, id: SessionId) -> Result, PortError> { - Ok(self.sessions.lock().map_err(poisoned)?.get(&id).cloned()) - } - - fn save_session(&self, session: Session) -> Result<(), PortError> { - self.sessions - .lock() - .map_err(poisoned)? - .insert(session.id(), session); - Ok(()) - } -} - -#[cfg(test)] -mod tests { - use domain::UserId; - - use super::*; - - #[test] - fn saves_and_finds() { - let repo = InMemoryWorkspaceRepository::new(); - let owner = UserId::new(); - let ws = Workspace::new(owner, "p"); - let session = Session::new(&ws, owner, "s").unwrap(); - let (ws_id, s_id) = (ws.id(), session.id()); - repo.save_workspace(ws).unwrap(); - repo.save_session(session).unwrap(); - assert!(repo.find_workspace(ws_id).unwrap().is_some()); - assert!(repo.find_session(s_id).unwrap().is_some()); - assert!(repo.find_session(SessionId::new()).unwrap().is_none()); - } -} diff --git a/docker-compose.yml b/docker-compose.yml index ed3336e..88612c4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,9 +1,10 @@ -# `docker compose up -d --build` levanta Postgres + server + web (requiere JWT_SECRET en .env; -# sin él, el contenedor del server sale al arrancar: verlo con `docker compose logs server`). -# `docker compose up -d postgres` levanta solo la base para los tests de integración del server. +# `docker compose up -d --build` levanta Postgres + api + web (requiere JWT_SECRET en .env; +# sin él, el contenedor de la API sale al arrancar: verlo con `docker compose logs api`). +# `docker compose up -d postgres` levanta solo la base para los tests de integración. # Todo se publica únicamente en 127.0.0.1. services: postgres: + container_name: opencollab-postgres image: postgres:17 environment: POSTGRES_USER: opencollab @@ -19,24 +20,27 @@ services: timeout: 3s retries: 10 - server: - build: ./apps/server + api: + container_name: opencollab-api + build: + context: . + dockerfile: apps/api/Dockerfile depends_on: postgres: condition: service_healthy environment: DATABASE_URL: postgresql://opencollab:opencollab@postgres:5432/opencollab - # Sin valor por defecto: el server se niega a arrancar con menos de 32 caracteres. + # Sin valor por defecto: la API se niega a arrancar con menos de 32 caracteres. # No se usa `${JWT_SECRET:?}` porque Compose interpola todos los servicios y # rompería `docker compose up -d postgres` para los tests. JWT_SECRET: ${JWT_SECRET:-} RELAY_ADDR: 0.0.0.0:8787 - # nginx es el único salto delante del server. + # nginx es el único salto delante de la API. TRUST_PROXY: "1" # Los callbacks de OAuth pasan por el origen de la web (nginx proxea /auth). WEB_ORIGIN: ${WEB_ORIGIN:-http://localhost:8080} PUBLIC_BASE_URL: ${PUBLIC_BASE_URL:-http://localhost:8080} - # OAuth obligatorio (GitHub y Google): igual que JWT_SECRET, el server no arranca sin ellos. + # OAuth obligatorio (GitHub y Google): igual que JWT_SECRET, la API no arranca sin ellos. GITHUB_CLIENT_ID: ${GITHUB_CLIENT_ID:-} GITHUB_CLIENT_SECRET: ${GITHUB_CLIENT_SECRET:-} GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-} @@ -47,9 +51,12 @@ services: restart: on-failure:5 web: - build: ./apps/web + container_name: opencollab-web + build: + context: . + dockerfile: apps/web/Dockerfile depends_on: - server: + api: condition: service_healthy ports: - "127.0.0.1:8080:8080" diff --git a/odd/tasks/api-rest-crud.md b/odd/tasks/api-rest-crud.md new file mode 100644 index 0000000..ac72ce8 --- /dev/null +++ b/odd/tasks/api-rest-crud.md @@ -0,0 +1,52 @@ +# API REST CRUD — workspaces, sessions, terminals, invitations + +Objective: expose the existing domain + persistence (Workspace/Session/Terminal/Invitation) as authenticated REST endpoints so the desktop (Feature 2: dual storage mode) has a cloud CRUD surface to call. +Branch: feature/api-rest-crud | Delivery: PR chain to develop (strategy `feature-branch-chain`, decided L8; slices: PR1=T1, PR2=T2+T3, PR3=T4+T5) | Test runner: `pnpm --filter @opencollab/server test` (unit) + `pnpm --filter @opencollab/server test:integration` (needs Postgres via `DATABASE_URL`) + +## Specs + +- S1: `POST /workspaces` — any authenticated user creates a workspace; the caller becomes owner. Body: `{ "name": string }` (trimmed, 1..100 chars). Returns the created workspace view (201). +- S2: `GET /workspaces` — lists every workspace where the caller is owner or member, each with its member count. Returns an array (200). +- S3: `GET /workspaces/:id` — workspace detail (name, owner, members with username/displayName). Owner or member only; 404 if not found, 403 if the caller has no access. +- S4: `POST /workspaces/:workspaceId/sessions` — creates a session in the workspace. Owner only (matches domain `Session.create` which requires `workspace.ensureOwner(actor)`). Body: `{ "name": string }` (trimmed, 1..100). Returns the session view (201). 403 for non-owner members, 404 if the workspace does not exist or the caller has no access. +- S5: `GET /workspaces/:workspaceId/sessions` — lists the sessions of the workspace (owner or member), each with its terminals in position order. Returns an array (200). +- S6: `GET /sessions/:id` — session detail with terminals (id, name, command, args, cwd). Viewable by anyone who can view the session (owner, member, or guest — matches `session.canView(workspace, user)`). 404 if not found, 403 if no view access. +- S7: `POST /sessions/:id/terminals` — appends a terminal to the session. Owner only (domain `addTerminal` is owner-only). Body: `{ "name": string, "command": string, "args"?: string[], "cwd"?: string | null }`. Returns the terminal view (201). Env is never accepted nor persisted (domain rule: env may hold secrets). +- S8: `DELETE /sessions/:id/terminals/:terminalId` — removes the terminal. Owner only. 204 on success; 404 if session or terminal not found; 403 if not owner. +- S9: `POST /workspaces/:id/invitations` — invites a user to the workspace as member. Owner only (domain `inviteMember`). Body: `{ "inviteeId": string }` (a UserId). Creates the invitation as pending. Returns the invitation view (201). 403 for non-owners; 409 if the invitee is already owner or member (`AlreadyHasAccess`). +- S10: `POST /sessions/:id/invitations` — invites a user to the session as guest. Owner only (domain `inviteGuest`). Body: `{ "inviteeId": string }`. Returns the invitation view (201). 403 for non-owners; 409 if the invitee already has a role (`AlreadyHasAccess`). +- S11: `GET /invitations` — lists the caller's pending, non-expired invitations (uses `InvitationRepository.listPendingFor`). Each entry carries the target (workspace or session) and who invited. Returns an array (200). +- S12: `POST /invitations/:id/accept` — accepts an invitation. Only the invitee may accept (403 otherwise). Applies the domain accept (`Workspace.acceptInvitation` or `Session.acceptInvitation`), persists the workspace/session, and marks the invitation accepted. 204 on success; 404 if not found; 409 if already responded/revoked/expired. +- S13: `POST /invitations/:id/decline` — declines an invitation. Only the invitee (403 otherwise). Marks it declined. 204; 404 if not found; 409 if already responded/revoked/expired. +- S14: All endpoints require `Authorization: Bearer ` (reuse `AccessGuard` + `CurrentUser`); missing/invalid token → 401. Bodies are validated with zod + `ZodPipe` (strict: unknown fields rejected); invalid body → 400 with field paths only, never echoing submitted values. +- S15: Domain errors map to HTTP: `NotOwner` → 403, `AlreadyHasAccess` → 409, `NotAParticipant` → 403, `TerminalNotInSession` → 404, invitation already responded → 409. Persistence changes are transactional: a failed accept never leaves a half-applied workspace/session plus an accepted invitation. + +Assumptions (marked as such, not user requirements): +- A1: "terminales" as an API resource means the persisted terminal profile (name/command/args/cwd), not live PTY streaming — live I/O already goes through the WebSocket gateway (`collab.gateway.ts`). +- A2: Renaming workspaces/sessions, removing members, and changing session access via REST are out of scope for this feature (access changes already exist as the `access_changed` WS frame). +- A3: `WorkspaceRepository` gains a `listForUser` method (it currently only has find/save); `InvitationRepository` is added to `PersistenceModule` exports (currently missing). + +## Tasks + +- T1 (S1-S3, S14): WorkspacesController — list/create/get + `WorkspaceRepository.listForUser` + module wiring; int tests RED→GREEN. route: inline — DONE (13 int tests, unit 166, int 107, typecheck ok). Review: tier high (463 lines), outcome granted/acknowledged (lineage review-78dd02cdbbd5c9c3, 0 blockers; advisory R3-001/R3-002 → L6) +- T2 (S4-S6, S14-S15): SessionsController — create/list/get sessions + terminals in views; int tests RED→GREEN. route: inline — DONE (9 int tests, unit 166, int 116, typecheck 0, commit b51d335). Review assess: medium, under_budget (pending in slice) +- T3 (S7-S8, S14-S15): TerminalsController — add/remove terminal; int tests RED→GREEN. route: inline — DONE (8 int tests, unit 166, int 124, typecheck 0, commit 3d2ae33). Review assess: medium, under_budget (pending in slice) +- T4 (S9-S13, S15): InvitationsController + accept/decline orchestration service; int tests RED→GREEN. route: delegated (writer, context backstop) — DONE (24 int tests, unit 166, int 148, typecheck 0, commit b70b272; ghost-invitee → 404 per L10). Review assess: medium, under_budget (pending in slice). Independent verify: not required — assess tier medium (no named high-risk item; writer self-verification + parent spot-check stand) +- T5 (S1-S15): AppModule wiring, full unit + integration suite green, typecheck + build. route: inline — DONE (RED 4/5 → GREEN 5/5 wiring spec; unit 166, int 153, typecheck 0, build 0; commit 44068f1). Review assess: medium (executable_change app.module.ts), under_budget over 2e3e113..HEAD — stays pending in slice, no review due + +## Log + +- L1 (2026-10-14, user verbatim): "En la API ya se encuentran los endpoints para la creación de workspaces - sesiones - terminales e invitaciones. Lo ideal es que el usuario tenga 2 opciones al usar la aplicación, almacenar todo local (podria ser en appdata) o guardar todo en "cloud" que seria que se interactue con la API." +- L2 (2026-10-14, verification): Checked the premise against develop HEAD 6a45795: the API has NO REST endpoints for workspaces/sessions/terminals/invitations — only `/auth/*`, `/health`, the WS gateway, and internal repositories. User confirmed the scope split. +- L3 (2026-10-14, user decision): Dual-mode product decisions (for Feature 2, recorded here for continuity): mode selection = "Onboarding + Settings"; collaboration in local mode = "Visibles pero inactivas"; switching local→cloud = "Migrar local → cloud". +- L4 (2026-10-14, user decision): Scope = "Dos features secuenciales": this feature builds the API REST CRUD first; Feature 2 (desktop dual storage mode) follows in a separate feature branch. +- L5 (2026-10-14, T1 done): WorkspacesController (POST/GET /workspaces, GET /workspaces/:id) implemented with `WorkspaceRepository.listForUser`, `UserRepository.findByIds`, zod `ZodPipe` validation, `AccessGuard`. New `CollabModule` imports PersistenceModule + AuthModule; AuthModule now exports `AuthService` and `AccessGuard` (previously only SessionService/SessionRevocations). Added `collab/test-app.ts` (bootstraps AuthModule+CollabModule against the `_test` database). Verified: unit 166/166, integration 107/107, typecheck clean. +- L6 (2026-10-15, T1 review): RDD review of commit 2e3e113 (lineage review-78dd02cdbbd5c9c3, tier high, 463 changed lines, 3 lenses risk/readability/reliability) reached approved; authority burned, no corrections, 0 blocking findings. Advisory (non-blocking, candidates for T5 test hardening — not authorized scope by themselves): R3-001 `GET /workspaces/:id` casts the raw route param to WorkspaceId without a malformed-id failure-path assertion (400 vs 404 vs 500 unproved); R3-002 create-body upper boundary/shape handling and summary memberCount lack observable assertions (overlong name, non-string name, trimmed persistence, memberCount). +- L7 (2026-10-15, T2 done): SessionsController with full-route @Controller() (POST/GET `workspaces/:workspaceId/sessions`, GET `sessions/:id`) + `SessionService` access classification: missing workspace AND stranger both → 404 on nested routes (no existence leak, S4/S5); member non-owner → 403 on create; detail uses `session.canView(workspace, user)` (guests included) → 403 without view access, 404 unknown. New `SessionView`/`TerminalView` projections in views.ts (cwd nullable, position order from repository include); `createSessionSchema` strict (S14). Guest/member/terminal seeding in tests bypasses the T4/T3 endpoints via repositories (documented in-spec). Evidence: RED 7/9 failed → focused GREEN 9/9; unit 166/166, integration 116/116, typecheck exit 0; gitleaks clean; commit b51d335 (411 authored lines in slice → running count now >400, chain strategy question owed before next commit per delivery budget). Environment note: integration runs need Docker Desktop up + `docker compose up -d postgres` and `DATABASE_URL=postgresql://opencollab:opencollab@localhost:5432/opencollab` (CI default creds; root .env has no DATABASE_URL). +- L8 (2026-10-15, user decision): Delivery strategy asked once per ask-on-risk (running count >400 authored lines). User chose `feature-branch-chain`: PR chain from feature/api-rest-crud to develop, slices PR1=T1 (2e3e113), PR2=T2+T3 (b51d335..T3), PR3=T4+T5. Push/PR creation remain human decisions. +- L9 (2026-10-15, T3 done): TerminalsController (POST/DELETE `sessions/:id/terminals`) + `SessionService.addTerminal/removeTerminal` with `ownedSession` helper: unknown session → 404, non-owner (member/stranger/guest) → 403 BEFORE terminal-existence check (stranger probing unknown terminal id gets 403, not 404 — no existence leak), unknown terminal → 404. Profile built via domain `newAgentProfile` (copies args, blank command blocked); zod `addTerminalSchema` strict rejects `env` (never accepted/persisted) and rejects blank command with a non-echoing refine; `cwd: null` normalized to absent. `toTerminalView` extracted in views.ts (env never projected). Evidence: RED 7/8 failed → focused GREEN 8/8; unit 166/166, integration 124/124, typecheck exit 0. +- L10 (2026-10-15, T4 done + user decision): Invitations endpoints implemented by delegated writer (5 routes, 24 int tests): POST `workspaces/:id/invitations`, POST `sessions/:id/invitations`, GET `invitations`, POST `invitations/:id/accept`, POST `invitations/:id/decline`; `InvitationRepository` registered+exported in PersistenceModule (A3); `domain-errors.ts` S15 mapping; accept order = aggregate save → `setStatus('accepted')` LAST so a failed accept provably leaves the row pending (test: seeded-member accept → 409 + row still PENDING). USER DECISION (supersedes the parent's draft decision 5 "ghost → 201"): the schema enforces FK `Invitation.inviteeId/invitedById → User` (schema.prisma FKs, empirically P2003/23503 on ghost insert → 500), so ghost invitees (well-formed UUID, nonexistent user) are rejected with 404 via a `UserRepository.findById` precheck placed AFTER the owner check (no user-enumeration leak to unauthorized callers), and no invitation row is stored (asserted). Malformed (non-UUID) invitation `:id` params → 404 before Prisma (Postgres uuid columns throw → would be 500; closes R3-001-class for invitations). Invitation expiry at create: `expiresAt = null` (never expires). Evidence: RED 22/24 failed → GREEN 24/24; unit 166/166; integration 148/148; typecheck 0; parent spot-check re-ran focused suite (24/24, exit 0); gitleaks clean; commit b70b272 (954 lines). +- L11 (2026-10-15, T5 done): AppModule now imports CollabModule (production module graph exposes the collab REST surface; main.ts unchanged). New `src/app.routes.int.spec.ts` boots the REAL AppModule (overrides PRISMA/AUTH_CONFIG/OAUTH_PROVIDERS/CLOCK, WsAdapter like main.ts, `listen(0)`) and pins S14 wiring per controller: unauthenticated hits on `/workspaces`, nested sessions, terminals and invitations routes → 401, and `/health` stays 200. Evidence: RED 4/5 (404 — routes absent from AppModule) → focused GREEN 5/5; unit 166/166; integration 153/153; typecheck exit 0; build exit 0. Independent verify on T4 corrected: assess tier medium → no separate verifier per the verification gate (writer self-verification + parent spot-check stand). Commit 44068f1. +- L12 (2026-10-15, feature closure): All tasks T1–T5 DONE. Final assess of the accumulated range 2e3e113..44068f1 (16 paths, 1828 changed lines): risk medium (reason `executable_change` apps/api/src/app.module.ts), review_due false, reason under_budget — T2..T5 remain pending-in-slice, no native review required; untracked `.gga` excluded via explicit inventory declaration (not part of this change). Advisories R3-001/R3-002 (L6) remain open follow-ups, not authorized scope. Delivery per L8: PR chain feature/api-rest-crud → develop (PR1=T1 2e3e113, PR2=T2+T3 b51d335..3d2ae33, PR3=T4+T5 b70b272..44068f1); push/PR creation remain human decisions. Next feature (separate branch, per L3/L4): desktop dual storage mode (local appdata vs cloud API). +- L13 (2026-10-15, delivery, user: "Dale crealo"): PR chain created (feature-branch-chain, per L8): #13 workspaces (T1, 463 lines, base develop) ← #14 sessions+terminals (T2+T3, 789, base -01-workspaces) ← #15 invitations+wiring (T4+T5, 1048, base -02-sessions-terminals); #16 tracker PR DRAFT (feature/api-rest-crud → develop, 2272 lines, merges the whole feature last). Slice branches at 2e3e113 and 3d2ae33 pushed alongside feature/api-rest-crud; diffs verified clean per slice (no polluted diffs). Review order #13→#14→#15; nothing lands on develop until the tracker merges. `size:exception` disclosed in each PR body (#13 single reviewed unit; #14/#15 user-decided slices per L8). Note: git pushes hung on GCM credential prompts; fixed with `gh auth setup-git` (gh as credential helper for github.com). CI runs on all pushed branches. +- L14 (2026-10-15, feature landed, user: "podrias ir haciendolo vos?"): CI green on all 4 PRs (Rust fmt/clippy/unit+E2E, Server unit+integration+build, Frontend, Web). Tracker #16 marked ready and merged (--merge, merge commit 0dd8d1c) → the whole feature is on develop. #13 auto-marked MERGED; #14/#15 closed with landing comments (their commits reached develop via the tracker). Local slice branches deleted; remote branches kept (repo convention). FEATURE DELIVERED AND CLOSED. Follow-up feature kicked off next: desktop dual storage mode (see `odd/tasks/desktop-dual-storage.md`). diff --git a/odd/tasks/desktop-dual-storage.md b/odd/tasks/desktop-dual-storage.md new file mode 100644 index 0000000..c1acd8e --- /dev/null +++ b/odd/tasks/desktop-dual-storage.md @@ -0,0 +1,59 @@ +# Desktop dual storage mode — local (appdata) vs cloud (API) + +Objective: give the desktop two storage options for workspaces/sessions/terminals — persist everything locally (appdata) or store everything in the cloud through the REST API built in feature `api-rest-crud` — with mode selection on Onboarding + Settings, collaboration visible-but-inactive in local mode, and a local→cloud migration path on switch. +Branch: feature/desktop-dual-storage (from develop c647c6f) | Delivery: PRs to develop (strategy `feature-branch-chain`, user-chosen 2026-10-19 — slices accumulate on this branch; chained PRs open at slice close, api-rest-crud style) | Test runner: `cargo test --workspace` + `cargo clippy --workspace --all-targets -- -D warnings` + `pnpm -r test` + `pnpm -r typecheck` + +## Specs + +- S1 (user, verbatim from the original request): "Lo ideal es que el usuario tenga 2 opciones al usar la aplicación, almacenar todo local (podria ser en appdata) o guardar todo en "cloud" que seria que se interactue con la API." — Two storage modes for the same desktop data. +- S2 (user decision, verbatim): Mode selection = "Onboarding + Settings" — the user picks the mode on first run (onboarding) and can change it later from Settings. +- S3 (user decision, verbatim): Collaboration in local mode = "Visibles pero inactivas" — collaboration UI stays visible but inactive when there is no cloud behind it. +- S4 (user decision, verbatim): Switching local→cloud = "Migrar local → cloud" — changing the mode from local to cloud migrates existing local data to the API. +- S5: In local mode the desktop's workspaces, sessions and terminal profiles survive restarts: they are written to appdata and restored on launch (today they are plain React state, `App.tsx` `useState`, lost on close). +- S6: In cloud mode the same workspace/session/terminal structure is stored through the authenticated REST API from feature `api-rest-crud` (develop 0dd8d1c): workspaces, sessions and terminals endpoints; the desktop's existing PKCE auth session provides the token. +- S7 (user decision 2026-10-19, verbatim): "Extender la API (Recommended)" — cloud mode must round-trip the full desktop snapshot faithfully; extend the REST API (rename/delete workspaces and sessions, terminal update/reorder/metadata, stable IDs) instead of accepting a lossy subset or adding a whole-snapshot endpoint. + +Assumptions (marked as such, not user requirements — challenge or confirm anytime): +- A1: Persisted per-terminal data = launch profile only: name/command/args/cwd/agent id, plus pane order (`Pane.seq` semantics: DOM order stable, visual order = array order) and minimized flag. Never `env` (secrets rule shared with the API), never PTY scrollback or process state. +- A2: The storage port lives in the desktop Rust core — `packages/ui/src/model.ts` already says "Workspaces y sesiones viven acá hasta que el núcleo exponga comandos para ellos" — with a local file backend (JSON under the OS appdata dir) and a cloud backend (HTTP client to the API) behind one port, exposed to the frontend through Tauri commands. +- A3: Window-level UI state (layout choice grid/columns/single, focused pane, maximized pane) is NOT persisted in this feature — only workspace/session/terminal structure. Can be a follow-up. +- A4: Migration (S4) = on mode switch to cloud, local workspaces/sessions/terminals are pushed to the API one workspace at a time; local files are kept (not deleted) after a successful migration. +- A5: Cloud mode requires a signed-in user (existing PKCE flow); switching to cloud without a session prompts login first. +- A6: The REST API base URL is configurable in Settings (dev default `http://localhost:3000`-style local API); the exact default comes from the existing desktop relay/API configuration during T3. + +## Tasks + +- T1 (S5, A1-A2): Rust core storage port (`WorkspaceSnapshot` load/save) + local appdata JSON backend + unit tests (round-trip, malformed file recovery). route: inline — DONE (RED 8/8 failing → GREEN 87/87; clippy -D warnings 0 workspace-wide; typecheck 0 post-incident recovery). Review assess: medium, under budget (no review due alone) +- T2 (S5): Tauri commands exposing the port (load on launch, save on change) + frontend bootstraps workspaces from the backend instead of `initialWorkspaces()` + persistence on every mutation. route: inline — DONE (RED 4/4 failing stub → GREEN 8/8 snapshot service; desktop suite 20/20; e2e 8 escenarios OK; `cargo test --workspace` 0 failed; clippy -D warnings 0; fmt clean; desktop `tsc --noEmit` OK). Review assess: high (`process_boundary` main.rs), review_due → native review found 1 CRITICAL (R4-load-error-destroys-snapshot) → corrected, see L10 +- T3a (S6, S7, A5): API extensions for full snapshot fidelity — PATCH/DELETE `/workspaces/:id`, PATCH/DELETE `/sessions/:id`, `PATCH /sessions/:id/terminals/:terminalId`, `PUT /sessions/:id/terminals/order`, explicit optional `id` on creates (UUID, idempotent per owner), terminal `agent`/`minimized` columns (Prisma migration) and views; domain factories accept optional id; int/unit tests per endpoint + regressions. route: delegated — parallel writer (Writer trigger: T3a/T3b independent units with disjoint edit surfaces, each several files / >100 lines). Status: DONE (commit `1b4494c`; API typecheck 0, unit 166/166, integration 190/190, domain 58/58; fixed DELETE 204 and a stale repository test; verifier T3: no blockers, L16) +- T3b (S6, S7, A2, A5): Rust cloud backend — `AccessTokenProvider` application port + `AuthStore` impl with refresh-on-demand, blocking HTTP client with TLS consuming the frozen T3 contract, `CloudSnapshotStore` behind the existing `SnapshotStore` port (load mapping, save reconciliation create/update/delete/reorder, deterministic UUID v5 mapping for local IDs), mock-server tests + error mapping. route: delegated — parallel writer (Writer trigger, same as T3a). Status: DONE (commits `313306f` + `aeb53e7`; `cargo test --workspace` 238 passed, clippy -D warnings 0, fmt clean, desktop 24/24; fixed ureq 3 API and stale tests; seq global fix + regression, L16) +- T4 (S2, A6): Onboarding on first run + Settings mode switch (mode persisted); wire `AppState.snapshot_store` to the selected backend; base URL configurable in Settings with default from the existing relay/API config; refuse empty/unhydrated cloud saves and add single-flight token refresh before exposing the provider. route: inline — DONE (commits `0c025af` + `ab7b45b`; verifier T4 found B1 cloud boot without session and B2 invalid-URL partial fallback, both fixed in `ab7b45b` with `CloudGate`, full config fallback, auth single-flight concurrency tests, and `cloud-boot-session.mjs` E2E, L18) +- T5 (S3): Local-mode collaboration visible-but-inactive. route: inline — DONE (commit `e4b4045`; RED 1/12 Rust + 1/7 UI → GREEN 12/12 `collab_status` + 65/65 UI + 21/21 desktop + 13/13 E2E incl. `local-collab-inactive.mjs`; clippy -D warnings 0; fmt clean; typecheck 0, L19-L20) +- T6 (S4, A4): Local→cloud migration on switch. route: inline — DONE (commit `6e79869`; RED 2/2 `infrastructure` + 2/2 `desktop::state` → GREEN 2/2 `migrar_` + 3/3 `state::tests` + 14/14 E2E incl. `local-to-cloud-migration.mjs`; clippy -D warnings 0; fmt clean; independent verifier `ae925551`: PASS on S4/A4, 0 blockers, L21-L22) +- T7 (S1-S6): Full verification: cargo test/clippy/fmt, pnpm test/typecheck/build, help/docs updated. route: inline — DONE (commit `67140cf`; `cargo fmt --all --check` 0, `cargo clippy --workspace --all-targets -- -D warnings` 0, `cargo test --workspace` 254 passed / 0 failed / 6 ignored, `pnpm -r typecheck` 5/5, `pnpm -r test` 406/406 across 37 files, `pnpm -r build` 6/6, desktop E2E 14/14 scenarios / 107 assertions; `AGENTS.md` + `README.md` updated, L23) + +## Log + +- L1 (2026-10-15, user kickoff, verbatim): "podrias ir haciendolo vos?" — continue the delegated flow autonomously: merge the api-rest-crud PR chain (done, see L2) and start this next feature (per the scope decision recorded in `odd/tasks/api-rest-crud.md` L3/L4). Original product request (verbatim, carried over): "Lo ideal es que el usuario tenga 2 opciones al usar la aplicación, almacenar todo local (podria ser en appdata) o guardar todo en "cloud" que seria que se interactue con la API." +- L2 (2026-10-15, delivery closed): api-rest-crud landed on develop via tracker PR #16 (merge commit 0dd8d1c, CI green on all slices). #13 auto-merged; #14/#15 closed with landing comments. develop docs commit c647c6f. This branch forks from develop c647c6f. +- L3 (2026-10-15, exploration findings): (a) Desktop workspaces/sessions/panes are pure React state (`apps/desktop/src/App.tsx`, `packages/ui/src/model.ts`) initialized from a hardcoded "OpenCollab" workspace — zero persistence today. (b) `model.ts` documents the planned move: core should expose commands for workspaces/sessions. (c) Rust core already has the domain parity model (`apps/desktop/core/domain`: Session/Terminal/AgentProfile with owner+access) — the same model the API persists. (d) Desktop auth (PKCE, tokens in Rust memory via `AuthStore`) already exists in `apps/desktop/src-tauri/src/auth.rs`. (e) The REST surface to consume: POST/GET /workspaces, GET /workspaces/:id, POST/GET /workspaces/:id/sessions, GET /sessions/:id, POST/DELETE /sessions/:id/terminals (env never persisted server-side). +- L4 (2026-10-15, carried-over product decisions, verbatim): Mode selection = "Onboarding + Settings"; collaboration in local mode = "Visibles pero inactivas"; switching local→cloud = "Migrar local → cloud". +- L5 (2026-10-15, T1 done): `application::storage` (WorkspaceSnapshot + Stored{Workspace,Session,Pane}, `SNAPSHOT_VERSION=1`, camelCase serde mirroring the frontend `Pane` model; `is_current_version` gate) + `SnapshotStore` port in `ports.rs` (sync by house rule: "la capa de aplicación no depende de un runtime async") + `infrastructure::FsSnapshotStore` (`workspaces.json` under the configured dir): atomic write (tmp + rename; `fs::rename` replaces on Windows), quarantine of unreadable/future-version files to `.corrupt` with fresh boot (`Ok(None)`), best-effort quarantine so a broken file never blocks the app. House patterns followed: PortError, `Fs*` adapter naming, in-module Spanish-commented tests, `serve_once`-style fixtures. Evidence: RED with stubbed store (8 behavioral tests failing) → GREEN 87/87 (`cargo test -p application -p infrastructure --lib`); `cargo clippy --workspace --all-targets -- -D warnings` exit 0; `cargo fmt --all` clean. +- L6 (2026-10-15, ENVIRONMENT INCIDENT during T1): something external wiped `packages/*` tracked files, ALL `node_modules`, `dist/` builds and left empty dirs (`.git`, root `target/`, `apps/`, `odd/` untouched; docker-compose exonerated — postgres uses a named volume, no bind mounts). Most likely OneDrive (repo lives inside OneDrive; pnpm's symlinked node_modules is a known OneDrive hazard) or Storage Sense. Recovery: `git restore packages/` (68 files), `pnpm install`, `pnpm --filter @opencollab/server^... build`; canary `pnpm -r typecheck` exit 0. OPEN RISK: this WILL recur while the repo stays inside OneDrive — relocation of the repo outside OneDrive (or excluding the folder) is a user decision, surfaced. +- L7 (2026-10-19, T2 done): bootstrapping + persistence wired end to end. Rust: `AppState.snapshot_store: Arc` (new field); `bootstrap(data_dir: PathBuf)` — the appdata dir is resolved in `main.rs` setup via `app.path().app_data_dir()` (Tauri v2: joins the bundle identifier to the OS data dir) and passed in; commands `snapshot_load` / `snapshot_save` in `commands.rs` (`#[tauri::command(async)]`, file IO off the UI thread; save takes `Vec` and the core stamps `SNAPSHOT_VERSION` via `WorkspaceSnapshot::new`). Frontend: `apps/desktop/src/services/snapshot.ts` — wire types mirroring the Rust `Stored*` structs (camelCase, `members` excluded), `toSavedWorkspaces`/`fromSavedSnapshot` (shape-validated, anything invalid → `null` fallback), `loadSnapshot`/`saveSnapshot` (save writes chained through a promise queue: two concurrent saves can never cross; failures logged, never thrown). `App.tsx`: starts with `initialWorkspaces()`, hydrates from `snapshot_load` on mount (default stays until load resolves so every `workspaces[0]` assumption holds; even a null result re-emits state once to persist the first-run baseline) and persists on every `workspaces` change gated by `hydratedRef` (a pending save must never overwrite the file with the default). Seq counter: restoring old panes would collide with `newPane()` seqs (`packages/ui/src/model.ts` counter has no setter) → new exported `adoptPaneSeq(seq)` raises the counter past the restored max. Agent ids: `packages/ui/src/agents.ts` exports `isAgentId`; a snapshot naming a removed agent restores a plain shell (`agent: null`) instead of breaking the UI. Mock: `tauri-mock.js` handles `snapshot_load` (null = clean boot) and `snapshot_save` (records, exposes `__mock.savedSnapshot`). Evidence: RED stub 4 behavioral failures → GREEN 8/8 service tests; desktop suite 20/20; e2e "Todos los E2E pasaron"; `cargo test --workspace` 13 suites 0 failed; clippy `-D warnings` 0 (one unused-import fix: `dyn` trait methods don't need the trait imported); `cargo fmt --all` clean; desktop `tsc --noEmit` OK. Authored lines T2: ~177 (git diff 7 files + 2 new service files). Running count: ~648. +- L8 (2026-10-19, delivery budget crossed): running count passed ~400 at T1 (471) and again after T2. Strategy question for the PR chain is owed before the next commit (user to choose `stacked-to-main` or `feature-branch-chain` over PRs to develop). +- L9 (2026-10-19, delivery strategy decided): user chose `feature-branch-chain` (same pattern as api-rest-crud) — feature branch keeps accumulating slices; chained PRs to develop are opened at slice close (planned: PR1 = T1+T2, PR2 = T3, PR3 = T4+T5, PR4 = T6, PR5 = T7/docs, each ≤~400 authored lines). +- L10 (2026-10-19, native review T1+T2 → correction): assess `high` (15 paths / 918 lines, reason `process_boundary` main.rs); lineage `review-be1a9a18389844a7`, target `sha256:a6b14bc5…`; one deterministic CRITICAL finding `R4-load-error-destroys-snapshot` (resilience): `App.tsx:65-70` enabled persistence after a failed `snapshot_load`, so the next mutation overwrote a still-valid snapshot with the default structure. Fix: on load rejection keep `hydratedRef` false (no quarantine/no backup needed — corrupt files arrive as `null` from the core, only unexpected errors reject); regression: e2e scenario `snapshot-load-error` (mock fails `snapshot_load` via `?mockSnapshotLoadError=1`; asserts no save after mutation and save resumes without the injected fault). Evidence: desktop vitest 20/20; `tsc --noEmit` + vite build OK; e2e 9/9 scenarios (3 new checks) OK. +- L11 (2026-10-19, native review closure BLOCKED by provider defect): successor lineage `review-9e1ebbdc684ede40` (generation 2 after `scope_changed`; target `sha256:6b1fbc38…`; correction commit `e593bac`, 50/200 correction lines). The four lenses re-ran on the corrected candidate and all were admitted (`admission_decision: completed` for risk, resilience, readability, reliability). The next bound `review.status --next-transition` returned `gentle-ai.review-integration.failure/v2`: operation `review.status`, phase `pre_native`, code `operation_timeout`, message "The negotiated review operation exceeded its aggregate time budget.", `mutation_outcome: not_started`, `authority_applicability: not_evaluated`, `retry_safe: false`, `replayability: manual_action_required`, `next_action: stop`, cause `context deadline exceeded`. One attempt only; no retry (`retry_safe: false`). State preserved: lineage stays in `reviewing` with its four admitted results; no abandon/reset/recover, no RDD toggle, no substitute command. With user consent the occurrence was reported on the open equivalent tracker: https://github.com/Gentleman-Programming/gentle-ai/issues/5422#issuecomment-6272771664 — no verifiable published fix was identified (#5094 closed by maintainer disposition without root cause; #5422 open follow-up; #5595 recurrence). No captured decline invocation exists for this lineage, so the consumer continuation fails closed. PR1 (T1+T2) remains pending review closure; implementation evidence is intact. NEXT: user decision on how to proceed (continue T3 under ordinary policy with the lineage preserved, wait for maintainer guidance, or clone-scope RDD disable). +- L12 (2026-10-19, T3 read-only exploration): the current REST API (feature api-rest-crud) exposes only POST/GET workspaces, GET workspace by id, POST/GET sessions, GET session, and POST/DELETE terminals. It has no rename/delete for workspaces or sessions, no terminal update, and no fields for pane `agent` or `minimized` (only `name`/`command`/`args`/`cwd`; strict DTOs reject `env`). `seq` is derivable from terminal array order. Desktop IDs are non-UUID strings while API IDs are UUIDs, with no mapping defined. Auth: `AuthStore` has no token getter; refresh runs only inside `auth_status` on mount while the access JWT TTL is 15 minutes. No HTTP client dependency exists; the existing clients are hand-rolled blocking `std::net` without TLS. Conclusion: cloud mode cannot faithfully round-trip the snapshot under the current API. OPEN DECISION (user): (1) extend the API for full fidelity (recommended), (2) add a whole-snapshot JSON endpoint, or (3) accept a lossy subset. T3 stays route TBD until this is decided. +- L13 (2026-10-19, T3 decision): user chose verbatim "Extender la API (Recommended)" — full-fidelity cloud round-trip via extended REST endpoints; no whole-snapshot endpoint, no lossy subset. Consequence: T3 splits into T3a (API) and T3b (Rust cloud backend), launched as parallel writers with disjoint surfaces. +- L14 (2026-10-19, T3 frozen contract v1): T3a extends the API behind the existing AccessGuard (write requires Write access; inaccessible = 404, no existence leak): `PATCH /workspaces/:id` `{name}`; `DELETE /workspaces/:id` (204, cascades members/sessions/terminals); `PATCH /sessions/:id` `{name}`; `DELETE /sessions/:id` (204, cascades terminals); `POST` creates accept optional explicit UUID `id` (idempotent for the same owner: existing same-owner resource → 200 with current view, another owner's id → 409); `POST /sessions/:id/terminals` body adds `agent?`/`minimized?`; new `PATCH /sessions/:id/terminals/:terminalId` (partial `name`/`command`/`args`/`cwd`/`agent`/`minimized`, `agent` may be null) and `PUT /sessions/:id/terminals/order` `{ids: string[]}` (exactly the session's terminals, atomic reorder); all terminal views gain `agent`/`minimized`; no `seq`/`env` fields ever (A1). Prisma: add `agent String?` and `minimized Boolean @default(false)` to Terminal + new migration (int tests apply real migrations via `prisma migrate deploy`); `position` already exists. Domain: factories accept optional ids; `Terminal` gains optional metadata; defaults keep every existing call site and test behavior unchanged. ID strategy (frozen): Rust derives a deterministic UUID v5 from each non-UUID local id (fixed namespace constant; an id that already parses as UUID is used as-is), so creates are idempotent across restarts and T6 migration reuses the mapping; server-generated ids remain for web clients. T3b: new sync `AccessTokenProvider` port in application with `AuthStore` impl that checks expiry and refreshes on demand (extracted from `auth_status`); `CloudSnapshotStore` in infrastructure using a blocking HTTP client with TLS (`ureq` 3 + rustls preferred; no async runtime) and a configurable base URL (existing relay address); `load_snapshot` = GET workspaces + GET sessions per workspace; `save_snapshot` = reconcile create/update/delete/reorder, fail closed on any non-2xx (PortError, never partial silent state), reorder only when array order differs. Mode selection/wiring stays in T4 — T3b delivers the adapter and tests; local remains the constructive default. Open follow-up (T5/S3): the snapshot carries no access level; cloud load includes all workspaces the API returns and unpermitted mutations fail closed at the API (403) — read-only UI semantics belong to T5. Route: T3a/T3b delegated parallel writers; verification: writer self-check + independent verifier (high-risk items: auth/permissions, new dependency) + seam check. +- L15 (2026-10-20, T3a/T3b implementation + verification): both writers were cancelled after writing their units, so the parent completed and verified the work inline. T3a commit `1b4494c` (API+domain, 20 files); T3b commit `313306f` (Rust cloud client+auth, 7 files). Fixes applied: `@HttpCode(204)` on workspace/session DELETE (Nest defaulted to 200), `sessions.save` before `terminalWithOwner` in the repository test, ureq 3 request builder (`http::Request` + `agent.run`), `Clone` on `ApiTerminal`, `Result<(), PortError>` returns, mock Arc clone, stale GET-sessions and DELETE-order expectations; auth adapter added (`RefreshOutcome`, `refresh_now`, `AccessTokenProvider`) and old helpers removed. Evidence: API `typecheck` 0; API unit 166/166; API integration 190/190 with real migrations (Postgres compose, `DATABASE_URL` set for the test DB); domain 58/58; desktop 20/20; `pnpm -r typecheck` 0; `pnpm -r test` 403/403; Rust `cargo test --workspace` 237 passed + 6 ignored e2e; `cargo clippy --workspace --all-targets -- -D warnings` 0; `cargo fmt --all --check` clean; seam checked against L14 (paths/bodies/status, no seq/env). Open follow-up: native review pending the provider defect (L11); independent verifier result and seq correction in L16. Next: T4. +- L16 (2026-10-20, T3 independent verification + seq correction): read-only verifier on candidate `d880187` (base `e593bac`) reproduced no change-caused blockers in any user-reachable path; all Rust/TS/API probes green (238 Rust + 6 ignored, 403 TS, 190 integration). Eight advisories: (a) save reconciliation is destructive and an empty/unhydrated snapshot wipes the cloud — T4 must refuse those saves; (b) `seq` restarted per session on cloud load — fixed in `aeb53e7` by a single global counter + regression `load_no_reutiliza_seq_entre_sesiones`; (c) latent double-refresh race in `AuthStore` — T4 single-flight; (d) rare v5 cross-account collision from timestamp/counter ids; (e) derived profile clobber for cross-client edits; (f) pre-existing terminal table delete+recreate on save; (g) 403-vs-404 existence oracle ambiguity inherited from baseline; (h) `cargo audit` unavailable offline, so the new ureq/rustls tree has no advisory scan. A6 remains unmet at the T3 layer: only a constructor base URL exists, no Settings field/relay-derived default — moved to T4. Review assess: `high` (28 paths / 3403 lines, `hot_path` auth.rs), `review_due: high_risk`; preflight stops at `intended_untracked_selection_required` for `.gga`; no native review started, PR1/T3 closure still blocked by L11. PR2 exceeds the ~400-line slice target; evaluate split at delivery. Next: T4. +- L17 (2026-10-20, T4 frozen contract): config file `storage.json` under appdata, `{version:1, mode:"local"|"cloud", apiBaseUrl, onboardingComplete}`; missing/malformed file falls back to local + `http://` (default 8787) + onboarding incomplete. Core: `AppState.auth: Arc`, `storage_config: RwLock`, `snapshot_store: RwLock>`; commands `storage_config_get` and `storage_config_set {mode, apiBaseUrl}` validate the URL, require a session for cloud (`AuthStore::has_session`), persist, swap the store, and return the complete config; `snapshot_save` rejects an empty workspace list. Refresh single-flight: `AuthStore` serializes refreshes and compares the rejected access token, so a concurrent 401 reuses the winner's token; the `AccessTokenProvider` refresh method receives the rejected token. UI: first-run onboarding screen (Local vs Cloud; Cloud needs sign-in, inline auth prompt) and a Settings modal opened from the TopBar `Sliders` button (mode + API base URL + sign-in when needed); boot waits for the config before loading a snapshot; switching reloads the target store. T6 owns local→cloud migration — T4 only switches and leaves the local file intact. Tests: storage config unit tests, auth rejected-token short-circuit, E2E first-run onboarding; no Writer trigger (sequential core→UI), route inline. +- L18 (2026-10-22, T4 implementation + independent verification + fix closed): initial implementation in `0c025af` (`storage_config.rs`, `state.rs`, `commands.rs`, `auth.rs` single-flight refresh, `Onboarding.tsx`, `SettingsDialog.tsx`, `StorageAuth.tsx`, `TopBar.tsx`, E2E `onboarding.mjs` + `settings-storage.mjs`). Independent read-only verifier (`#570`) reported two blockers: (B1) a persisted cloud config with no in-memory session mounted the grid without a login gate and never re-hydrated on `auth-changed`, dropping mutations; (B2) an invalid `apiBaseUrl` in `storage.json` reset only the URL while preserving `mode: Cloud` and `onboardingComplete: true`. Both fixed in `ab7b45b`: added `CloudGate.tsx` (sign-in or switch to Local) and re-hydration when auth transitions to authenticated, full safe fallback in `storage_config.rs` on invalid URL, multithreaded single-flight refresh tests in `auth.rs`, and E2E scenario `cloud-boot-session.mjs`. Next: T5 (S3: local-mode collaboration visible-but-inactive). +- L19 (2026-10-22, T5 contract): S3 requires collaboration UI to remain visible but inactive in local mode. Core: `collab_status::snapshot` short-circuits in `StorageMode::Local` to `CollabStatusPayload { connected: false, sync_ms: None, collaborators: 1 }` without probing the relay; `storage_config_set` emits `collab-status` on mode switch. UI (`@opencollab/ui` `TopBar`, `Sidebar`, `StatusBar` + `App.tsx`): pass `storageMode?: "local" | "cloud"`; in local mode `Invite` stays visible and disabled with local-mode tooltip + `data-collab-inactive="true"`, `Sidebar` `.ws-meta` and `.user` stay visible with `data-collab-inactive="true"` (signed-in status shows `Local · colaboración inactiva` instead of `Online`; anonymous status shows local-mode collaboration inactive hint while preserving sign-in for Cloud switch), and `StatusBar` items stay visible with `data-collab-inactive="true"` when disconnected in local mode. Route: inline (sequential core→UI, no Writer trigger). +- L20 (2026-10-22, T5 done): implemented in `e4b4045` (13 files, +279/-20). Observed RED in `collab_status::tests::local_mode_keeps_collaboration_inactive_without_probing_the_relay` and `describeCollabMode` → GREEN 12/12 `collab_status` Rust tests, 65/65 `@opencollab/ui` tests, 21/21 `@opencollab/desktop` tests, 13/13 E2E scenarios (`local-collab-inactive.mjs` 7/7 checks + JS error check), `cargo clippy --workspace --all-targets -- -D warnings` 0, `cargo fmt --all --check` 0, `pnpm -r typecheck` 0. Risk: none (optional `storageMode` prop in `@opencollab/ui` defaults to `"cloud"`). Next: T6 (S4, A4: local→cloud migration on switch). +- L21 (2026-10-22, T6 contract): S4 + A4 require migrating existing local data to the API when switching from Local to Cloud while keeping local files intact. Core: `CloudSnapshotStore::migrate_snapshot(&WorkspaceSnapshot)` pushes each workspace in `snapshot.workspaces` one workspace at a time (reusing Phase 1 upsert + deterministic UUID v5 mapping from `local_id_to_server_uuid`) without deleting unrelated cloud workspaces already in the account (no Phase 3 workspace deletion during migration); `AppState::set_storage_config` triggers migration on `Local -> Cloud` transition when `current.onboarding_complete && current.mode == StorageMode::Local` and `FsSnapshotStore::load_snapshot()` returns a non-empty snapshot, failing closed before saving `storage.json` or swapping `snapshot_store` if migration fails, and leaving `workspaces.json` untouched on disk. UI: `SettingsDialog.tsx` local→cloud hint updated to state that local data is migrated to the cloud account and local files are kept. Route: inline (sequential core→UI, no Writer trigger); Verification trigger fires after implementation (Risk item 1: local→cloud data migration). +- L22 (2026-10-22, T6 implementation + independent verification closed): implemented in `6e79869` (7 files, +446/-78). Observed RED in `infrastructure` (`migrar_`) and `desktop::state::tests` → GREEN 2/2 `cargo test -p infrastructure migrar_`, 3/3 `cargo test -p desktop state::tests`, 14/14 E2E scenarios (`local-to-cloud-migration.mjs` 5/5 checks + 0 JS errors), `cargo clippy --workspace --all-targets -- -D warnings` 0, `cargo fmt --all --check` 0. Independent read-only verifier (`ae925551`) verified S4 and A4 on `6e79869`: PASS (0 blockers, 0 advisories). Risk: item 1 (data migration: local workspaces/sessions/terminals snapshot pushed to Cloud REST API on Local -> Cloud mode switch). Next: T7 (S1-S6: full verification + docs). +- L23 (2026-10-22, T7 full verification + docs closed): updated `AGENTS.md` and `README.md` in `67140cf` to document Local (`appdata` `workspaces.json`) vs Cloud (`CloudSnapshotStore` REST API) storage modes, first-run Onboarding and Settings (`storage.json`), local-mode visible-but-inactive collaboration (`data-collab-inactive="true"`), and additive local→cloud migration. Full suite runner (`5862a3df`) observed all checks green: `cargo fmt --all --check` exit 0; `cargo clippy --workspace --all-targets -- -D warnings` exit 0; `cargo test --workspace` 254 passed, 0 failed, 6 ignored (`application` 89, `desktop` 37, `domain` 12, `infrastructure` 108, `protocol` 8); `pnpm -r typecheck` 5/5 projects exit 0; `pnpm -r test` 37 files / 406 tests passed (`domain` 58, `ui` 65, `contracts` 6, `web` 90, `desktop` 21, `api` 166); `pnpm -r build` 6/6 packages built exit 0; `pnpm --filter @opencollab/desktop test:e2e` 14/14 scenarios (107 assertions) passed exit 0. All tasks T1–T7 DONE; ready for user decision on PR chain delivery to `develop`. diff --git a/odd/tasks/modularize-frontend.md b/odd/tasks/modularize-frontend.md new file mode 100644 index 0000000..3c824fc --- /dev/null +++ b/odd/tasks/modularize-frontend.md @@ -0,0 +1,56 @@ +# Modularize frontend directory structure (apps/web and apps/desktop) +Objective: Decompose monolithic files and modularize directory structures in apps/web and apps/desktop per issue #11 +Branch: feature/modularize-frontend | Delivery: PR a develop | Test runner: vitest + cargo test + +## Specs +- S1: "Decompose `apps/web/src/components.tsx` into individual components under `apps/web/src/components/`." + Target structure: + apps/web/src/components/ + ├── Field.tsx + ├── Link.tsx + ├── OAuthButtons.tsx + ├── Shell.tsx + └── index.ts +- S2: "Decompose `apps/web/src/pages.tsx` into individual page views under `apps/web/src/pages/`." + Target structure: + apps/web/src/pages/ + ├── AccountPage.tsx + ├── AuthCompletePage.tsx + ├── LoginPage.tsx + ├── RegisterPage.tsx + └── index.ts +- S3: "Move web clients (`authClient`, `handoff`) to `apps/web/src/services/` and routing/validation to `apps/web/src/utils/`." + Target structure: + apps/web/src/services/ (authClient.ts, authClient.test.ts, handoff.ts, handoff.test.ts) + apps/web/src/utils/ (router.ts, validation.ts, validation.test.ts) +- S4: "Move desktop hooks to `apps/desktop/src/hooks/` and API/infrastructure modules to `apps/desktop/src/services/`." + Target structure: + apps/desktop/src/hooks/ (useAuth.ts, useCollabStatus.ts, useGitBranch.ts, usePaneDrag.ts, useWindowFocus.ts, index.ts) + apps/desktop/src/services/ (auth.ts, auth.test.ts, branchWatch.ts, branchWatch.test.ts, terminalApi.ts, index.ts) +- S5: "Update all import paths across apps and test files accordingly." +- S6: "Ensure all packages and apps pass typechecking (`pnpm -r typecheck`), unit tests (`pnpm -r test`), and build (`pnpm -r build`)." +- S7: "Maintain strict boundaries: zero changes to `@opencollab/contracts` or `@opencollab/domain`." + +## Tasks +- [x] T1 (S1) — Decompose `apps/web/src/components.tsx` into individual components under `apps/web/src/components/`. [route: direct inline, commit: 7f64c06] +- [x] T2 (S2) — Decompose `apps/web/src/pages.tsx` into individual page views under `apps/web/src/pages/`. [route: direct inline, commit: 7f64c06] +- [x] T3 (S3, S5) — Move web clients to `apps/web/src/services/` and utils to `apps/web/src/utils/`, updating all web imports and tests. [route: direct inline, commit: 7f64c06] +- [x] T4 (S4, S5) — Move desktop hooks to `apps/desktop/src/hooks/` and services to `apps/desktop/src/services/`, updating all desktop imports and tests. [route: direct inline, commit: 7f64c06] +- [x] T5 (S6, S7) — Comprehensive verification (`pnpm -r typecheck`, `pnpm -r test`, `pnpm -r build`, `cargo test --workspace`) and boundary enforcement. [route: direct inline, commit: 7f64c06] + +## Log +- L1: 2026-10-14 Verificación inicial: monorepo-apps corroborado y mergeado en develop (PR #10, commit 3c53e1f). Inicio de refactorización según Issue #11. +- L2: 2026-10-14 Modularización completada en apps/web y apps/desktop: + - apps/web/src/components/: Field.tsx, Link.tsx, OAuthButtons.tsx, Shell.tsx, index.ts. + - apps/web/src/pages/: AccountPage.tsx, AuthCompletePage.tsx, LoginPage.tsx, RegisterPage.tsx, index.ts. + - apps/web/src/services/: authClient.ts, authClient.test.ts, handoff.ts, handoff.test.ts. + - apps/web/src/utils/: router.ts, validation.ts, validation.test.ts. + - apps/desktop/src/hooks/: useAuth.ts, useCollabStatus.ts, useGitBranch.ts, usePaneDrag.ts, useWindowFocus.ts, index.ts. + - apps/desktop/src/services/: auth.ts, auth.test.ts, branchWatch.ts, branchWatch.test.ts, terminalApi.ts, index.ts. + - Verificación integral: + - pnpm -r typecheck: OK (0 errores). + - pnpm -r test: OK (Vitest: 383/383 tests pasando). + - pnpm --filter @opencollab/desktop test:e2e: OK (todos los escenarios E2E pasando). + - pnpm -r build: OK (todos los paquetes y aplicaciones compilan). + - cargo test --workspace: OK (85/85 tests de Rust pasando). + - Límites de paquetes: 0 cambios en @opencollab/contracts y @opencollab/domain. diff --git a/odd/tasks/monorepo-packages.md b/odd/tasks/monorepo-packages.md new file mode 100644 index 0000000..d52ec82 --- /dev/null +++ b/odd/tasks/monorepo-packages.md @@ -0,0 +1,75 @@ +# monorepo-packages — `apps/` → `packages/`, one pnpm workspace, `desktop-v*` tags + +## Objective + +Treat the repo as a real monorepo: rename `apps/` to `packages/`, manage the +three JS packages (desktop, server, web) as one pnpm workspace with a single +lockfile, and tag desktop releases as `desktop-vX.Y.Z` like the other packages. + +## Problem + +- `apps/desktop`, `apps/server` and `apps/web` are three independent pnpm + projects (one lockfile and `node_modules` each, no root `package.json`), so + the repo is a monorepo only by convention. +- After `per-package-versioning`, server and web use prefixed tags + (`server-v*`, `web-v*`) but the desktop still uses bare `v*`. + +## User decisions (2026-10-08) + +- Folder name: `packages/` (replaces `apps/`). `crates/` stays as is. +- Desktop tags: `desktop-vX.Y.Z`. Already published tags (`v0.1.0`…`v0.3.0`) + are not rewritten. +- Merge `feature/per-package-versioning` and `feature/sidebar-thread-duration` + into `develop` first (done: `f2bba8f`, `32a5332`). + +## Scope + +Branch `feature/monorepo-packages` (from `develop`). Historical ODD documents +keep their old `apps/` paths (they are history); live docs (`AGENTS.md`, +`README.md`, this file, `nest-server.md` pending items) are updated. + +## Constraints + +- Strict TDD (session config): existing suites are the safety net for the + rename; the tag change gets an observed RED with `check-version.ps1`. +- Git Flow: no commits on `develop`/`main`; no push without the user. +- Docker images must still build and run with the single root lockfile. + +## Checklist + +- [x] **M1** — `git mv apps packages` and update every live path reference + (Cargo workspace members, CI, release workflow, scripts, docker-compose, + Dockerfiles, `.gitignore`, `AGENTS.md`, `README.md`, code/comments). +- [x] **M2** — Root pnpm workspace: root `package.json` (private, shared + `packageManager`, convenience scripts), `pnpm-workspace.yaml` with + `packages/*` (absorbing the server's workspace settings), one root + `pnpm-lock.yaml` (per-package lockfiles removed), CI and Dockerfiles adapted. +- [x] **M3** — Desktop tags `desktop-vX.Y.Z`: `check-version.ps1`, + `release.yml` trigger and pre-release detection, `AGENTS.md`. + +## Acceptance criteria + +- No live reference to `apps/` remains (outside historical ODD docs). +- `pnpm install` at the root installs all three packages; desktop, server and + web tests and builds pass from the root workspace. +- `cargo test --workspace`, clippy and fmt pass. +- `docker compose up -d --build` brings the three services up healthy. +- `check-version.ps1 -Package desktop -Tag desktop-v0.3.0` passes and + `-Tag v0.3.0` fails; `release.yml` triggers only on `desktop-v*.*.*`. + +## Applicable checks + +`pnpm -r test`, `pnpm -r build`, desktop `pnpm test:e2e`, +`cargo fmt --all --check`, `cargo clippy --workspace --all-targets -- -D warnings`, +`cargo test --workspace`, `check-version.ps1` for the three packages, +`docker compose up -d --build` + `/health`. + +## Progress + +- Route: delegated direct (writer trigger: 2+ non-trivial files per task). +- M1 03f07a3, M2 e7f5d09, M3 6dee186. Docker unavailable locally: images built only via simulated pnpm filter install + deploy. +- Verified (writer, parent spot check of the bare `v0.3.0` tag failing): root `pnpm install --frozen-lockfile`; desktop 73 tests + build + E2E; server 212 tests + typecheck + build; web 90 tests + build; cargo fmt/clippy/test; check-version RED→GREEN. Pending: `docker compose up` + `/health`, server `test:integration`. +- Review (RDD on, risk high): consent granted, START refused with `lens_context_budget_exceeded` (the tool counts the rename as 45k changed lines, no review authority created). Authored lines: M1 ~170 (+ renames), M2 ~195 (+ lockfile), M3 36. +- Review of the reduced scope (M2+M3+docs, base 03f07a3, user-authorized): 4 lenses, approved with no findings; acknowledged (lineage review-a5bdff32acc0baad, authority burned). M1 (mechanical rename) left unreviewed by user decision; covered by the full test suites. +- Docker verified on `feature/domain-slim` HEAD (2026-10-08): `docker compose up -d --build` built both images from the repo root with the single lockfile; postgres, server and web healthy; `/health` = ok (200); `/login` 200 with the CSP; `/auth` reaches the server through nginx (401 without cookie); migrations: none pending. Server `test:integration` 99/99, desktop E2E all passed. +- Done. Merged into `develop` together with `feature/domain-slim`. diff --git a/odd/tasks/monorepo-restructure.md b/odd/tasks/monorepo-restructure.md new file mode 100644 index 0000000..3d7ef8e --- /dev/null +++ b/odd/tasks/monorepo-restructure.md @@ -0,0 +1,39 @@ +# Monorepo restructure — apps/* + packages/* (domain manda) +Objective: Migrar a apps/web, apps/desktop, apps/api + packages/domain, contracts, ui, api-client, config, utils +Branch: feature/monorepo-apps | Delivery: PR a develop | Test runner: vitest + cargo test + +## Specs +- S1: `packages/domain` (@opencollab/domain) es la única autoridad de reglas colaborativas (Workspace, Session, Invitation, permission, ids, errores) en TypeScript puro sin dependencias de Nest, Prisma ni React. `server/src/domain/index.ts` re-exporta `@opencollab/domain`. Todos los tests unitarios del dominio (*.spec.ts) corren y pasan en `packages/domain`. +- S2: `packages/contracts` (@opencollab/contracts) es la única fuente del wire contract (Envelope, Message, AccessLevelDto, parseFrame, PROTOCOL_VERSION = 1). Paridad de bytes con Rust (snake_case, Vec como number[], versión u16). Zod schemas para validación. +- S3: Mudanza de rutas de aplicaciones y Rust: `packages/desktop` -> `apps/desktop`, `packages/server` -> `apps/api`, `packages/web` -> `apps/web`, y `crates/*` -> `apps/desktop/core/*`. Actualización de miembros en `Cargo.toml`, `pnpm-workspace.yaml` (apps/* y packages/*) y configuración de `turbo.json` con `dependsOn: ["^build"]`. +- S4: `packages/ui` (@opencollab/ui) contiene componentes presentacionales compartidos (Panel, Sidebar, StatusBar, TopBar, ThreadMeta, icons, helpers puros) sin lógica de negocio ni `@tauri-apps/api`. +- S5: Builds con tsup en cada package (CJS + ESM + d.ts). `apps/api` permanece en CJS (`dist/main.js`). Desktop y web consumen paquetes compilados. +- S6: Prisma vive dentro de `apps/api` (`prisma/schema.prisma`, `prisma.config.ts`, migraciones y cliente generado). +- S7: Compatibilidad en CI (`ci.yml`, `release.yml`), Dockerfiles (`apps/api`, `apps/web`), `.dockerignore`, `tauri.conf.json` y scripts de versionado (`check-version.ps1`, `package-release.ps1`). +- S8: Verificación integral de la suite completa: `pnpm -r build`, `pnpm -r typecheck`, `pnpm -r test`, `cargo test --workspace`, `cargo clippy`, `cargo fmt --check`, E2E desktop y tests de integración. + +## Tasks +- [x] T1 (S1) — `packages/domain`: consolidar `packages/domain` (@opencollab/domain) con TS puro; server re-exporta; tests de dominio pasan. [route: direct inline, commit: 83d9cde] +- [x] T2 (S2) — `packages/contracts`: wire contract Zod único y paridad de bytes con Rust verificado; server y apps consumen contracts. [route: direct inline, commit: da245c4] +- [x] T3 (S3) — Mudanza estructural a `apps/*` y `apps/desktop/core/*`: Cargo.toml, pnpm-workspace.yaml, turbo.json. [route: direct inline, commit: 7a5da79] +- [x] T4 (S4) — `packages/ui`: extracción de componentes presentacionales compartidos. [route: direct inline, commit: 51d27d1] +- [x] T5 (S5) — Builds con tsup en packages y empaquetado CJS/ESM. [route: direct inline, commit: 87467f1] +- [x] T6 (S6) — Prisma ubicado en `apps/api`: cliente generado y scripts aislados. [route: direct inline, commit: 7a5da79] +- [x] T7 (S7) — CI/CD, Dockerfiles y scripts de release actualizados. [route: direct inline, commit: fdaaedb] +- [x] T8 (S8) — Verificación integral (builds, unit tests, integración, E2E, Docker). [route: direct inline] +- [x] T9 (S7) — Optimizar CI/CD y Docker: runner Ubuntu para web, eliminación de db:generate redundante, desvinculación de @opencollab/ui en web y compilación transitiva (^...). [route: direct inline, commit: 2cf2576] + +## Log +- L1: 2026-10-13 "sigamos con monorepo-apps" — Retoma de la reestructuración a apps/* y packages/* con domain como autoridad. +- L2: 2026-10-13 Verificación integral completada (T8): + - pnpm -r build: OK (todos los paquetes y apps compilan). + - pnpm -r typecheck: OK (0 errores en TS). + - pnpm -r test: OK (444/444 tests en Vitest). + - cargo test --workspace: OK (97/97 tests en Rust). + - cargo clippy: OK (-D warnings sin alertas). + - cargo fmt --check: OK. + - shell_integration_e2e: OK (2/2 tests de PTY y shell real). + - desktop test:e2e: OK (todos los escenarios E2E pasando). + - Scripts de versionado (check-version.ps1): OK para desktop (0.3.0), server (0.1.0), web (0.1.0). +- L3: 2026-10-13 Limpieza de código muerto en apps/api (domain/index.ts, persistence/index.ts, protocol.ts) y conexión de apps/desktop a @opencollab/ui eliminando 24 archivos duplicados locales (-1,745 líneas netas). Tests unitarios (383/383) y E2E de desktop al 100% (commit 6ea1164). +- L4: 2026-10-13 Optimización de CI/CD y Docker: runner web a ubuntu-latest, prisma db:generate redundante eliminado, desvinculación de @opencollab/ui en web y compilación transitiva (^...) en ci.yml y release.yml. Toda la suite de tests en verde (383/383 Vitest). diff --git a/odd/tasks/nest-server.md b/odd/tasks/nest-server.md index 02769c4..fb5b6a5 100644 --- a/odd/tasks/nest-server.md +++ b/odd/tasks/nest-server.md @@ -162,9 +162,38 @@ sí aporta en el core del desktop (PTYs, procesos del SO). rechaza si el server no confirma, timeout de 10 s en cada request (libera el Web Lock), `ContinuePage` con error y reintento, captura del handoff fuera de React (`main.tsx`). -- [ ] **T7** — Achicar `crates/domain` a lo que necesita el desktop (PTY, +- [x] **T7** — Achicar `crates/domain` a lo que necesita el desktop (PTY, terminal, validación final con el `AccessLevel` que manda el server) y actualizar `AGENTS.md` (deja de regir "el dominio Rust manda"). + - Rama `feature/domain-slim` (apilada sobre `feature/monorepo-packages`). + Ruta: delegada (mapeo con un Explore; escritor único, 2+ archivos no + triviales). TDD estricto (configuración de la sesión), runner + `cargo test --workspace`. + - Diseño: se borran `Workspace`, `WorkspaceMember`, `Invitation`, + `InvitationTarget`, `InvitationId`, `SessionGuest`, `ParticipantRole`, + `WorkspaceId` y la resolución de permisos por membresía. `Session` queda + como sesión local del host: id, nombre, dueño, terminales y un mapa de + `AccessLevel` por usuario que **llena el server** (`Joined` / + `AccessChanged`). Sin entrada = `None` (falla cerrado: el server decide); + el dueño siempre escribe. `AccessLevel` sigue siendo el tipo ordenado + (Escribir sin Ver irrepresentable). `ChangeParticipantAccess` (que + difundía cambios por `CollabTransport`) se reemplaza por un caso de uso + que aplica el nivel recibido del server; `WorkspaceRepository` pasa a + ser un repositorio de sesiones. `SessionCollaborators` cuenta dueño + + usuarios con Ver. + - Evidencia: commit `d15cc16`. RED observado: `owner_always_writes`, + `server_levels_drive_view_and_write`, `participants_are_owner_plus_viewers` + (domain) y `applying_view_then_write_from_server_allows_input`, + `revoking_to_none_from_server_blocks_next_input`, + `applying_access_to_unknown_session_or_owner_is_rejected` (application) + fallaban contra un stub; GREEN tras implementar. `cargo fmt --check`, + clippy `-D warnings` y `cargo test --workspace` (194 tests) en verde; + build y Vitest del desktop en verde. `CollabTransport` se retira (vuelve + con el cliente WS). + - Revisión (RDD, riesgo medio, consentida): una lente (confiabilidad), + aprobada sin hallazgos y reconocida (lineage `review-382acf7be262846b`). + Spot check del padre: `cargo test -p domain -p application` en verde. + Sin correr: E2E de la interfaz (no cambió ningún comando ni evento). - [x] **T8** — Docker (pedido del usuario antes del push): `docker compose` levanta Postgres + server + web; el desktop NO va en contenedor (se descarga el instalador de la release y corre nativo contra el server del diff --git a/odd/tasks/per-package-versioning.md b/odd/tasks/per-package-versioning.md new file mode 100644 index 0000000..dcfc70e --- /dev/null +++ b/odd/tasks/per-package-versioning.md @@ -0,0 +1,78 @@ +# per-package-versioning — versión independiente por paquete + +## Objetivo + +Versionar por separado `desktop`, `server` y `web`. Solo el desktop publica +releases de GitHub. + +## Problema + +Hoy hay una única versión (la del desktop, en 3 fuentes) y `AGENTS.md` +habla de "la versión de la app". Con el server Nest y la web en el +monorepo, cada paquete evoluciona a su ritmo y necesita su propia versión. + +## Decisiones del usuario (2026-10-07) + +- Desktop: tags `vX.Y.Z` sin prefijo (se entiende que es la app de + escritorio; continúa desde `v0.2.0`). Única que genera release de GitHub. +- Server: `apps/server/package.json`, tags `server-vX.Y.Z`. +- Web: `apps/web/package.json`, tags `web-vX.Y.Z` (la app nace en T6b de + `nest-server`; el chequeo se activa cuando exista). +- Artefactos del desktop: `opencollab--.` (p. ej. + `opencollab-windows-0.3.0.exe`), con su `.sha256` y `SHA256SUMS.txt`. +- `PROTOCOL_VERSION` sigue independiente de las tres. + +## Alcance autorizado + +Rama `feature/per-package-versioning` (desde `develop`). Tocar: +`scripts/check-version.ps1`, `scripts/package-release.ps1`, +`.github/workflows/release.yml`, `.github/workflows/ci.yml` (paso de +versión), `AGENTS.md` (Versionado, CI/CD, Git Flow) y este documento. + +## Checklist + +- [x] **V1** — `check-version.ps1 -Package desktop|server|web [-Tag]`: + desktop valida las 3 fuentes y tag `vX.Y.Z`; server/web validan su + `package.json` y tag `-vX.Y.Z`; web falla claro si el paquete no + existe. Default `desktop` (compatibilidad). +- [x] **V2** — `package-release.ps1` y `release.yml`: nombres + `opencollab-windows-.{exe,msi}`; release solo con tags `v*.*.*` + del desktop. +- [x] **V3** — CI: chequeo de versión de desktop y server. +- [x] **V4** — `AGENTS.md`: Versionado por paquete, ramas + `release/X.Y.Z` (desktop), `release/server-X.Y.Z`, `release/web-X.Y.Z` (y + `hotfix/` igual), convención de nombres de artefactos. + +## Checks aplicables + +Sin runner de tests para los scripts PowerShell (TDD no aplica a estos +archivos): verificación funcional ejecutando `check-version.ps1` en todos +los casos (ok, tag correcto/incorrecto, paquete inexistente) y +`package-release.ps1` contra instaladores falsos en una carpeta temporal. + +## Ruta + +Delegado directo: un writer (5 archivos no triviales). + +## Progreso + +- 2026-10-07: creado. Rama `feature/per-package-versioning` desde `develop`. +- 2026-10-07: V1–V4 implementados (sin commit). Evidencia: `check-version.ps1` sin args = ok (0.2.0); `-Package desktop -Tag v0.2.0` ok, `-Tag v9.9.9` falla; `-Package web` falla claro (paquete inexistente). `apps/server/package.json` NO existe en esta rama (`apps/server/` está sin trackear y sin package.json), así que `-Package server` falla acá; verificado en un árbol temporal con un package.json falso: ok, `-Tag server-v0.1.0` ok, `-Tag v0.1.0` falla. `package-release.ps1 -Version 0.0.0-test` con instaladores falsos produjo `opencollab-windows-0.0.0-test.{exe,msi}` + `.sha256` + `SHA256SUMS.txt` + `release-notes.md`; `sha256sum -c` OK. Bug propio corregido en el camino (`$Relative:` se parseaba como variable con ámbito). `actionlint` y PyYAML no disponibles: workflows sin parsear. Pendiente: el paso de CI de server fallará hasta que `apps/server/package.json` esté versionado en el repo (lo introduce `nest-server`). + +- 2026-10-07: el parent ajustó V3: el paso de CI verifica desktop siempre y + server/web solo si existe su `package.json` (se activan solos al + mergear `nest-server` y T6b). Simulado localmente: desktop ok, server y + web salteados en `develop`. Commit work-unit en esta rama. +- 2026-10-07: Review de `5752498` (4 lentes, riesgo alto por shell en CI, + consent granted): aprobada y acknowledged. Corregido inline: el guard + `$LASTEXITCODE` cortaba el loop con éxito antes de la web (variable sin + setear → `exit $null`); se quitó (el script corta con error terminante) y + se loguea cuando un paquete se saltea; `AGENTS.md` alineado. Simulado en + un árbol temporal: desktop y server verificados, web salteada con log, + server con versión inválida → exit 1. +- 2026-10-07: Review de `3d8f5cd` (4 lentes, consent granted): aprobada y + acknowledged. Aviso R3-001 (el paso depende del error terminante del + script) verificado y aceptado: el script fija `$ErrorActionPreference = + 'Stop'`, el shell `pwsh` de Actions también, y la simulación con versión + inválida dio exit 1. Feature lista para PR a `develop` (cuando el + usuario decida el push). diff --git a/package.json b/package.json new file mode 100644 index 0000000..f49c54b --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "opencollab", + "version": "0.0.0", + "private": true, + "description": "Monorepo de OpenCollab: desktop (Tauri), server (NestJS) y web (Vite). El core Rust vive en crates/ y se maneja con Cargo.", + "packageManager": "pnpm@11.1.1", + "scripts": { + "dev": "pnpm --filter \"./packages/*\" build && pnpm --parallel --stream --filter \"./apps/*\" dev", + "desktop:dev": "pnpm --filter @opencollab/desktop dev", + "api:dev": "pnpm --filter @opencollab/server dev", + "web:dev": "pnpm --filter @opencollab/web dev", + "test": "pnpm -r test", + "build": "pnpm -r build", + "typecheck": "pnpm -r --if-present typecheck", + "check:rust": "cargo fmt --all --check && cargo clippy --workspace --all-targets -- -D warnings && cargo test --workspace", + "pre-push": "pnpm typecheck && pnpm test && pnpm check:rust", + "prepare": "husky" + }, + "devDependencies": { + "husky": "^9.1.7", + "tsup": "^8.5.1" + } +} \ No newline at end of file diff --git a/packages/config/package.json b/packages/config/package.json new file mode 100644 index 0000000..11ff057 --- /dev/null +++ b/packages/config/package.json @@ -0,0 +1,7 @@ +{ + "name": "@opencollab/config", + "version": "0.1.0", + "private": true, + "description": "Configuración TypeScript compartida de OpenCollab (tsconfig base, sin build).", + "files": ["tsconfig.base.json"] +} diff --git a/packages/config/tsconfig.base.json b/packages/config/tsconfig.base.json new file mode 100644 index 0000000..3546ff7 --- /dev/null +++ b/packages/config/tsconfig.base.json @@ -0,0 +1,11 @@ +{ + // Shared base: exactly what apps/desktop, apps/api and + // apps/web tsconfig.json already agree on (verified 2026-10-13). + // App-specific options (module, jsx, decorators, outDir, types, ...) + // stay in each package's own tsconfig; wiring `extends` comes later. + "compilerOptions": { + "target": "ES2022", + "strict": true, + "skipLibCheck": true + } +} diff --git a/packages/contracts/package.json b/packages/contracts/package.json new file mode 100644 index 0000000..de2ae2d --- /dev/null +++ b/packages/contracts/package.json @@ -0,0 +1,33 @@ +{ + "name": "@opencollab/contracts", + "version": "0.1.0", + "description": "Wire contract de OpenCollab (única fuente del protocolo Envelope/Message): schemas zod + tipos inferidos + PROTOCOL_VERSION + errores.", + "main": "dist/index.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "tsup src/index.ts --format cjs,esm --dts --clean", + "test": "vitest run", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "dependencies": { + "zod": "^4.6.5" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "tsup": "^8.5.1", + "typescript": "~5.9.0", + "vitest": "^5.0.0" + } +} diff --git a/packages/contracts/src/contracts.spec.ts b/packages/contracts/src/contracts.spec.ts new file mode 100644 index 0000000..38c4dde --- /dev/null +++ b/packages/contracts/src/contracts.spec.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from 'vitest'; + +import { INCOMPATIBLE_PROTOCOL_VERSION, INVALID_MESSAGE, PROTOCOL_VERSION, parseFrame } from './index'; + +/** The raw error a frame would be answered with, or undefined when it is accepted. */ +function replyForTextFrame(text: string): string | undefined { + const parsed = parseFrame(text); + return parsed.ok ? undefined : parsed.error; +} + +// Wire parity with `crates/protocol` and the former `server/src/protocol.ts`: +// same fixtures, same expectations (snake_case, Vec as number[], +// version u16, rejection of 1.0/1e0 like serde). +describe('contracts wire', () => { + it('exposes PROTOCOL_VERSION 1', () => { + expect(PROTOCOL_VERSION).toBe(1); + }); + + it('accepts a valid frame and hands back the parsed message', () => { + const message = { type: 'access_changed', session_id: 's', user_id: 'u', access: 'view' }; + expect(parseFrame(JSON.stringify({ version: 1, message }))).toEqual({ + ok: true, + envelope: { version: 1, message }, + }); + }); + + it('rejects other versions (mirror of the Rust envelope test)', () => { + const text = + '{"version":999,"message":{"type":"terminal_output","session_id":"s","terminal_id":"t","data":[104,105]}}'; + expect(replyForTextFrame(text)).toBe(INCOMPATIBLE_PROTOCOL_VERSION); + }); + + it('rejects valid JSON that is not an envelope as an invalid message', () => { + expect(replyForTextFrame('{"version":1}')).toBe(INVALID_MESSAGE); + expect(replyForTextFrame('{"version":1,"message":{"type":"unknown"}}')).toBe(INVALID_MESSAGE); + expect(replyForTextFrame('esto no es json {')).toBe(INVALID_MESSAGE); + }); + + it('rejects non-integer numbers the way serde rejects them', () => { + const message = '{"type":"access_changed","session_id":"s","user_id":"u","access":"none"}'; + expect(replyForTextFrame(`{"version":1.0,"message":${message}}`)).toBe(INVALID_MESSAGE); + expect(replyForTextFrame(`{"version":1e0,"message":${message}}`)).toBe(INVALID_MESSAGE); + const output = (data: string) => + `{"version":1,"message":{"type":"terminal_output","session_id":"s","terminal_id":"t","data":${data}}}`; + expect(replyForTextFrame(output('[1.5]'))).toBe(INVALID_MESSAGE); + expect(replyForTextFrame(output('[104,256]'))).toBe(INVALID_MESSAGE); + }); + + it('accepts the known access levels and rejects the rest', () => { + const frame = (access: string) => + `{"version":1,"message":{"type":"joined","session_id":"s","access":${access}}}`; + expect(replyForTextFrame(frame('"write"'))).toBeUndefined(); + expect(replyForTextFrame(frame('"root"'))).toBe(INVALID_MESSAGE); + }); +}); diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts new file mode 100644 index 0000000..00eda8c --- /dev/null +++ b/packages/contracts/src/index.ts @@ -0,0 +1,135 @@ +// Wire contract: single source of the desktop <-> relay bytes (Envelope/Message). +// Zod schemas mirror `crates/protocol` field-for-field: snake_case on the +// wire, `Vec` as a JSON number array, `version: u16`. The Rust domain +// stays authoritative for the RULES; this package owns the BYTES. +// IDs travel as UUID strings. PROTOCOL_VERSION must match the desktop. + +import { z } from 'zod'; + +export const PROTOCOL_VERSION = 1; + +/** snake_case on the wire, mirroring `AccessLevelDto`. */ +export const accessLevelSchema = z.enum(['none', 'view', 'write']); +export type AccessLevelDto = z.infer; + +/** A `Vec` serialized as a JSON number array. */ +const bytesSchema = z.array(z.number().int().min(0).max(255)); + +/** Equivalent of serde's `version: u16`. */ +const versionSchema = z.number().int().min(0).max(0xffff); + +const terminalOutputSchema = z.object({ + type: z.literal('terminal_output'), + session_id: z.string(), + terminal_id: z.string(), + data: bytesSchema, +}); + +const terminalInputSchema = z.object({ + type: z.literal('terminal_input'), + session_id: z.string(), + terminal_id: z.string(), + user_id: z.string(), + data: bytesSchema, +}); + +const accessChangedSchema = z.object({ + type: z.literal('access_changed'), + session_id: z.string(), + user_id: z.string(), + access: accessLevelSchema, +}); + +/** Client -> server: subscribe this connection to a session. */ +const joinSessionSchema = z.object({ + type: z.literal('join_session'), + session_id: z.string(), +}); + +/** Server -> client: join accepted, with the access in force right now. */ +const joinedSchema = z.object({ + type: z.literal('joined'), + session_id: z.string(), + access: accessLevelSchema, +}); + +/** Client -> server: a fresh access token to keep the socket alive (never the refresh token). */ +const reauthSchema = z.object({ + type: z.literal('reauth'), + token: z.string(), +}); + +/** Server -> client: renewal accepted; `expires_at` is unix seconds. */ +const reauthenticatedSchema = z.object({ + type: z.literal('reauthenticated'), + expires_at: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER), +}); + +/** + * Same shape check serde runs for `Message`. Objects strip unknown fields, + * so extra keys are ignored exactly like serde does. + */ +export const messageSchema = z.discriminatedUnion('type', [ + terminalOutputSchema, + terminalInputSchema, + accessChangedSchema, + joinSessionSchema, + joinedSchema, + reauthSchema, + reauthenticatedSchema, +]); +export type Message = z.infer; + +/** Equivalent of `serde_json::from_str::` succeeding (`version: u16`). */ +export const envelopeSchema = z.object({ + version: versionSchema, + message: messageSchema, +}); +export interface Envelope { + version: number; + message: Message; +} + +export const INCOMPATIBLE_PROTOCOL_VERSION = '{"error":"incompatible_protocol_version"}'; +export const INVALID_MESSAGE = '{"error":"invalid_message"}'; +/** Also answers unknown sessions, so existence is not revealed. */ +export const FORBIDDEN = '{"error":"forbidden"}'; +export const NOT_JOINED = '{"error":"not_joined"}'; +/** A `reauth` token that is invalid or belongs to another user. */ +export const UNAUTHORIZED = '{"error":"unauthorized"}'; + +/** + * `JSON.parse` turns `1.0` and `1e0` into the integer 1, but serde rejects + * them for integer fields. Every number in the wire is an integer, so a + * number whose source text is not an integer literal becomes NaN and fails + * the integer checks (the reviver context needs Node 21+; CI runs Node 24). + */ +function parseWire(text: string): unknown { + return JSON.parse(text, (_key, value: unknown, context?: { source?: string }) => + typeof value === 'number' && context?.source !== undefined && !/^-?\d+$/.test(context.source) + ? Number.NaN + : value, + ); +} + +export type ParsedFrame = { ok: true; envelope: Envelope } | { ok: false; error: string }; + +/** + * Same acceptance rules as the Rust relay: a frame that does not deserialize + * into a complete `Envelope` is a message error and an envelope of another + * version is a version error. Routing the accepted message is the hub's job, + * which forwards the ORIGINAL text rather than a re-serialization. + */ +export function parseFrame(text: string): ParsedFrame { + let parsed: unknown; + try { + parsed = parseWire(text); + } catch { + return { ok: false, error: INVALID_MESSAGE }; + } + const envelope = envelopeSchema.safeParse(parsed); + if (!envelope.success) return { ok: false, error: INVALID_MESSAGE }; + if (envelope.data.version !== PROTOCOL_VERSION) + return { ok: false, error: INCOMPATIBLE_PROTOCOL_VERSION }; + return { ok: true, envelope: envelope.data }; +} diff --git a/packages/contracts/tsconfig.build.json b/packages/contracts/tsconfig.build.json new file mode 100644 index 0000000..e401417 --- /dev/null +++ b/packages/contracts/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "dist", "src/**/*.spec.ts"] +} diff --git a/packages/contracts/tsconfig.json b/packages/contracts/tsconfig.json new file mode 100644 index 0000000..48a0945 --- /dev/null +++ b/packages/contracts/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "sourceMap": true, + "types": ["node"] + }, + "include": ["src/**/*"] +} diff --git a/packages/domain/package.json b/packages/domain/package.json new file mode 100644 index 0000000..0b5f762 --- /dev/null +++ b/packages/domain/package.json @@ -0,0 +1,30 @@ +{ + "name": "@opencollab/domain", + "version": "0.1.0", + "description": "Dominio colaborativo puro de OpenCollab (única autoridad de reglas, sin Nest/Prisma/React).", + "main": "dist/index.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "tsup src/index.ts --format cjs,esm --dts --clean", + "test": "vitest run", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "tsup": "^8.5.1", + "typescript": "~5.9.0", + "vitest": "^5.0.0" + } +} diff --git a/apps/server/src/domain/error.ts b/packages/domain/src/error.ts similarity index 100% rename from apps/server/src/domain/error.ts rename to packages/domain/src/error.ts diff --git a/apps/server/src/domain/ids.spec.ts b/packages/domain/src/ids.spec.ts similarity index 100% rename from apps/server/src/domain/ids.spec.ts rename to packages/domain/src/ids.spec.ts diff --git a/apps/server/src/domain/ids.ts b/packages/domain/src/ids.ts similarity index 100% rename from apps/server/src/domain/ids.ts rename to packages/domain/src/ids.ts diff --git a/apps/server/src/domain/index.ts b/packages/domain/src/index.ts similarity index 100% rename from apps/server/src/domain/index.ts rename to packages/domain/src/index.ts diff --git a/apps/server/src/domain/invitation.ts b/packages/domain/src/invitation.ts similarity index 100% rename from apps/server/src/domain/invitation.ts rename to packages/domain/src/invitation.ts diff --git a/apps/server/src/domain/permission.spec.ts b/packages/domain/src/permission.spec.ts similarity index 100% rename from apps/server/src/domain/permission.spec.ts rename to packages/domain/src/permission.spec.ts diff --git a/apps/server/src/domain/permission.ts b/packages/domain/src/permission.ts similarity index 100% rename from apps/server/src/domain/permission.ts rename to packages/domain/src/permission.ts diff --git a/apps/server/src/domain/session.spec.ts b/packages/domain/src/session.spec.ts similarity index 68% rename from apps/server/src/domain/session.spec.ts rename to packages/domain/src/session.spec.ts index dcfcc70..ab27987 100644 --- a/apps/server/src/domain/session.spec.ts +++ b/packages/domain/src/session.spec.ts @@ -300,4 +300,136 @@ describe('Session', () => { guests.push({ userId: newUserId(), access: 'view' }); expect(session.guests).toEqual([{ userId: guests[0].userId, access: 'view' }]); }); + + it('create honors an explicit id', () => { + const f = fixture(); + const id = newSessionId(); + const session = Session.create(f.workspace, f.owner, 'con id', id); + expect(session.id).toBe(id); + }); + + it('addTerminal honors an explicit id and metadata', () => { + const f = fixture(); + const id = newTerminalId(); + f.session.addTerminal(f.workspace, f.owner, newAgentProfile('claude', 'claude'), { + id, + agent: 'claude', + minimized: true, + }); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'claude', command: 'claude', args: [], env: [] }, + agent: 'claude', + minimized: true, + }); + }); + + it('addTerminal without options keeps the legacy shape with default metadata', () => { + const f = fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'shell', command: 'sh', args: [], env: [] }, + agent: null, + minimized: false, + }); + }); + + it('updateTerminal applies a partial patch and keeps untouched fields', () => { + const f = fixture(); + const id = f.session.addTerminal( + f.workspace, + f.owner, + newAgentProfile('shell', 'sh', { args: ['-l'], cwd: '/tmp' }), + ); + f.session.updateTerminal(f.workspace, f.owner, id, { name: 'renamed', minimized: true }); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'renamed', command: 'sh', args: ['-l'], env: [], cwd: '/tmp' }, + agent: null, + minimized: true, + }); + }); + + it('updateTerminal replaces args, cwd and agent', () => { + const f = fixture(); + const id = f.session.addTerminal( + f.workspace, + f.owner, + newAgentProfile('claude', 'claude', { cwd: '/old' }), + { agent: 'claude', minimized: true }, + ); + f.session.updateTerminal(f.workspace, f.owner, id, { + args: ['--new'], + cwd: null, + agent: null, + minimized: false, + }); + expect(f.session.terminal(id)).toEqual({ + id, + profile: { name: 'claude', command: 'claude', args: ['--new'], env: [] }, + agent: null, + minimized: false, + }); + }); + + it('updateTerminal rejects a blank command like creation does', () => { + const f = fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + expectDomainError(() => f.session.updateTerminal(f.workspace, f.owner, id, { command: ' ' }), { + code: 'EmptyCommand', + }); + }); + + it('updateTerminal keeps owner-only rules and rejects unknown terminals', () => { + const f = fixture(); + const id = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('shell', 'sh')); + expectDomainError( + () => f.session.updateTerminal(f.workspace, f.member, id, { name: 'x' }), + { code: 'NotOwner' }, + ); + const unknown = newTerminalId(); + expectDomainError( + () => f.session.updateTerminal(f.workspace, f.owner, unknown, { name: 'x' }), + { code: 'TerminalNotInSession', terminal: unknown }, + ); + // A forbidden patch never leaks: the terminal stays untouched. + expect(f.session.terminal(id)?.profile.name).toBe('shell'); + }); + + it('reorderTerminals reorders the terminals by the given ids', () => { + const f = fixture(); + const a = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('a', 'sh')); + const b = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('b', 'sh')); + const c = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('c', 'sh')); + f.session.reorderTerminals(f.workspace, f.owner, [c, a, b]); + expect(f.session.terminals.map((t) => t.id)).toEqual([c, a, b]); + // Reordering twice with the same list is stable (idempotent). + f.session.reorderTerminals(f.workspace, f.owner, [b, c, a]); + expect(f.session.terminals.map((t) => t.id)).toEqual([b, c, a]); + }); + + it('reorderTerminals keeps owner-only rules and rejects unknown terminals', () => { + const f = fixture(); + const a = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('a', 'sh')); + const b = f.session.addTerminal(f.workspace, f.owner, newAgentProfile('b', 'sh')); + expectDomainError( + () => f.session.reorderTerminals(f.workspace, f.member, [b, a]), + { code: 'NotOwner' }, + ); + const unknown = newTerminalId(); + expectDomainError( + () => f.session.reorderTerminals(f.workspace, f.owner, [a, unknown]), + { code: 'TerminalNotInSession', terminal: unknown }, + ); + // A rejected reorder never mutates the stored order. + expect(f.session.terminals.map((t) => t.id)).toEqual([a, b]); + }); + + it('rename changes the session name in place, owner-only', () => { + const f = fixture(); + expectDomainError(() => f.session.rename(f.workspace, f.member, 'no'), { code: 'NotOwner' }); + f.session.rename(f.workspace, f.owner, 'renombrada'); + expect(f.session.name).toBe('renombrada'); + }); }); diff --git a/apps/server/src/domain/session.ts b/packages/domain/src/session.ts similarity index 71% rename from apps/server/src/domain/session.ts rename to packages/domain/src/session.ts index f4bcd61..a71f8df 100644 --- a/apps/server/src/domain/session.ts +++ b/packages/domain/src/session.ts @@ -17,7 +17,14 @@ import { withWrite, type AccessLevel, } from './permission'; -import type { AgentProfile, Terminal } from './terminal'; +import { + newAgentProfile, + newTerminal, + type AgentProfile, + type Terminal, + type TerminalCreateOptions, + type TerminalPatch, +} from './terminal'; import type { Workspace } from './workspace'; // Temporary guest: access to this session only, never the rest of the workspace. @@ -45,12 +52,14 @@ export class Session { private constructor( readonly id: SessionId, readonly workspaceId: WorkspaceId, - readonly name: string, + private _name: string, ) {} - static create(workspace: Workspace, actor: UserId, name: string): Session { + static create(workspace: Workspace, actor: UserId, name: string, id?: SessionId): Session { workspace.ensureOwner(actor); - return new Session(newSessionId(), workspace.id, name); + // An explicit id (S7) lets a client retry its create without duplicating + // the aggregate; the caller still runs the ownership/idempotency checks. + return new Session(id ?? newSessionId(), workspace.id, name); } // Rebuilds an aggregate from persisted state: no creation-time checks. @@ -75,6 +84,10 @@ export class Session { return [...this.memberOverrides]; } + get name(): string { + return this._name; + } + get terminals(): readonly Terminal[] { return this._terminals; } @@ -206,12 +219,55 @@ export class Session { this._guests.push({ userId: invitation.invitee, access: DEFAULT_ACCESS }); } - addTerminal(workspace: Workspace, actor: UserId, profile: AgentProfile): TerminalId { + addTerminal( + workspace: Workspace, + actor: UserId, + profile: AgentProfile, + opts: TerminalCreateOptions = {}, + ): TerminalId { + this.ensureBelongsTo(workspace); + workspace.ensureOwner(actor); + const terminal = newTerminal(opts.id ?? newTerminalId(), profile, opts); + this._terminals.push(terminal); + return terminal.id; + } + + // Owner-only partial update (S7): absent patch keys keep the current value, + // explicit nulls clear `cwd`/`agent`. The profile is rebuilt through the + // factory so a blank command stays impossible. + updateTerminal(workspace: Workspace, actor: UserId, id: TerminalId, patch: TerminalPatch): void { + this.ensureBelongsTo(workspace); + workspace.ensureOwner(actor); + const terminal = this.terminal(id); + if (!terminal) throw new DomainError({ code: 'TerminalNotInSession', terminal: id }); + const p = terminal.profile; + const cwd = patch.cwd === undefined ? (p.cwd ?? null) : patch.cwd; + this._terminals[this._terminals.indexOf(terminal)] = newTerminal( + id, + newAgentProfile(patch.name ?? p.name, patch.command ?? p.command, { + args: patch.args ?? p.args, + ...(cwd === null ? {} : { cwd }), + }), + { + agent: patch.agent === undefined ? (terminal.agent ?? null) : patch.agent, + minimized: patch.minimized === undefined ? (terminal.minimized ?? false) : patch.minimized, + }, + ); + } + + // Owner-only reorder (S7): `ids` is the exact new order. The caller must pass + // the session's terminals exactly (the REST layer turns a mismatch into 400); + // the domain still refuses to reorder around unknown or duplicated ids. + reorderTerminals(workspace: Workspace, actor: UserId, ids: readonly TerminalId[]): void { this.ensureBelongsTo(workspace); workspace.ensureOwner(actor); - const id = newTerminalId(); - this._terminals.push({ id, profile }); - return id; + for (const id of ids) this.ensureHasTerminal(id); + if (new Set(ids).size !== ids.length || ids.length !== this._terminals.length) { + throw new Error('reorderTerminals requires exactly the session terminals, without duplicates'); + } + const byId = new Map(this._terminals.map((t) => [t.id, t] as const)); + this._terminals.length = 0; + for (const id of ids) this._terminals.push(byId.get(id)!); } // Like adding them, removing terminals is owner-only. @@ -223,6 +279,13 @@ export class Session { this._terminals.splice(index, 1); } + // Owner-only rename (S7); persistence re-saves the aggregate afterwards. + rename(workspace: Workspace, actor: UserId, name: string): void { + this.ensureBelongsTo(workspace); + workspace.ensureOwner(actor); + this._name = name; + } + ensureHasTerminal(id: TerminalId): void { if (!this.terminal(id)) throw new DomainError({ code: 'TerminalNotInSession', terminal: id }); } diff --git a/apps/server/src/domain/terminal.spec.ts b/packages/domain/src/terminal.spec.ts similarity index 100% rename from apps/server/src/domain/terminal.spec.ts rename to packages/domain/src/terminal.spec.ts diff --git a/packages/domain/src/terminal.ts b/packages/domain/src/terminal.ts new file mode 100644 index 0000000..87cad99 --- /dev/null +++ b/packages/domain/src/terminal.ts @@ -0,0 +1,65 @@ +import { DomainError } from './error'; +import type { TerminalId } from './ids'; + +// How to launch an agent (or a shell). Agnostic: any CLI is a profile. +export interface AgentProfile { + readonly name: string; + readonly command: string; + readonly args: string[]; + readonly env: [string, string][]; + readonly cwd?: string; +} + +export function newAgentProfile( + name: string, + command: string, + opts: { args?: string[]; env?: [string, string][]; cwd?: string } = {}, +): AgentProfile { + if (command.trim() === '') throw new DomainError({ code: 'EmptyCommand' }); + // Copies, so the caller keeps no handle on the profile's internals. + const args = [...(opts.args ?? [])]; + const env = (opts.env ?? []).map(([k, v]): [string, string] => [k, v]); + const profile = { name, command, args, env }; + return opts.cwd === undefined ? profile : { ...profile, cwd: opts.cwd }; +} + +// A PTY inside a session running an `AgentProfile`. +export interface Terminal { + readonly id: TerminalId; + readonly profile: AgentProfile; + // Snapshot metadata (S7): which agent the pane launches (null = plain shell) + // and its collapsed state. Optional so legacy shapes still typecheck; the + // factories below always produce the canonical defaults. + readonly agent?: string | null; + readonly minimized?: boolean; +} + +// Creation input for a terminal: the explicit id powers the desktop's +// idempotent create (S7); the metadata mirrors the saved pane state. +export interface TerminalCreateOptions { + readonly id?: TerminalId; + readonly agent?: string | null; + readonly minimized?: boolean; +} + +// Partial terminal update (S7). Absent keys keep the current value; explicit +// nulls clear `cwd` and `agent`. +export interface TerminalPatch { + readonly name?: string; + readonly command?: string; + readonly args?: string[]; + readonly cwd?: string | null; + readonly agent?: string | null; + readonly minimized?: boolean; +} + +// Canonical terminal constructor: metadata is always present in memory, so +// views and persistence never branch on missing keys. +export function newTerminal(id: TerminalId, profile: AgentProfile, opts: TerminalCreateOptions = {}): Terminal { + return { + id, + profile, + agent: opts.agent ?? null, + minimized: opts.minimized ?? false, + }; +} diff --git a/apps/server/src/domain/test-helpers.ts b/packages/domain/src/test-helpers.ts similarity index 100% rename from apps/server/src/domain/test-helpers.ts rename to packages/domain/src/test-helpers.ts diff --git a/apps/server/src/domain/workspace.spec.ts b/packages/domain/src/workspace.spec.ts similarity index 85% rename from apps/server/src/domain/workspace.spec.ts rename to packages/domain/src/workspace.spec.ts index 388964f..d728159 100644 --- a/apps/server/src/domain/workspace.spec.ts +++ b/packages/domain/src/workspace.spec.ts @@ -81,4 +81,19 @@ describe('Workspace', () => { ws.addMember(owner, invitee); expect(ws.isMember(invitee)).toBe(true); }); + + it('accepts an explicit id and keeps generating one by default', () => { + const owner = newUserId(); + const id = newWorkspaceId(); + expect(new Workspace(owner, 'con id', id).id).toBe(id); + expect(new Workspace(owner, 'generado').id).toBeTruthy(); + }); + + it('rename changes the workspace name in place, owner-only', () => { + const owner = newUserId(); + const ws = new Workspace(owner, 'antes'); + expectDomainError(() => ws.rename(newUserId(), 'no'), { code: 'NotOwner' }); + ws.rename(owner, 'después'); + expect(ws.name).toBe('después'); + }); }); diff --git a/apps/server/src/domain/workspace.ts b/packages/domain/src/workspace.ts similarity index 90% rename from apps/server/src/domain/workspace.ts rename to packages/domain/src/workspace.ts index 25abe1b..b151b95 100644 --- a/apps/server/src/domain/workspace.ts +++ b/packages/domain/src/workspace.ts @@ -12,7 +12,7 @@ export class Workspace { constructor( readonly owner: UserId, - readonly name: string, + private _name: string, readonly id: WorkspaceId = newWorkspaceId(), ) {} @@ -28,6 +28,16 @@ export class Workspace { return ws; } + get name(): string { + return this._name; + } + + // Owner-only rename (S7); persistence re-saves the aggregate afterwards. + rename(actor: UserId, name: string): void { + this.ensureOwner(actor); + this._name = name; + } + get members(): readonly WorkspaceMember[] { return this._members; } diff --git a/packages/domain/tsconfig.build.json b/packages/domain/tsconfig.build.json new file mode 100644 index 0000000..76c8404 --- /dev/null +++ b/packages/domain/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["node_modules", "dist", "src/**/*.spec.ts", "src/**/test-*.ts"] +} diff --git a/packages/domain/tsconfig.json b/packages/domain/tsconfig.json new file mode 100644 index 0000000..48a0945 --- /dev/null +++ b/packages/domain/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "commonjs", + "strict": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "sourceMap": true, + "types": ["node"] + }, + "include": ["src/**/*"] +} diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 0000000..bc700ed --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,42 @@ +{ + "name": "@opencollab/ui", + "version": "0.1.0", + "description": "Componentes visuales compartidos de OpenCollab (sin negocio, sin dependencias de Tauri ni xterm).", + "main": "dist/index.js", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "files": [ + "dist" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./package.json": "./package.json" + }, + "scripts": { + "build": "tsup && tsc -p tsconfig.build.json", + "test": "vitest run", + "typecheck": "tsc --noEmit -p tsconfig.json" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "dependencies": { + "react-icons": "^5.7.0" + }, + "devDependencies": { + "@types/node": "^24.0.0", + "@types/react": "^19.3.0", + "@types/react-dom": "^19.3.0", + "react": "^19.3.0", + "react-dom": "^19.3.0", + "tsup": "^8.5.1", + "typescript": "~5.9.0", + "vite": "^8.3.2", + "vitest": "^5.0.0" + } +} diff --git a/apps/desktop/src/activity.test.ts b/packages/ui/src/activity.test.ts similarity index 100% rename from apps/desktop/src/activity.test.ts rename to packages/ui/src/activity.test.ts diff --git a/apps/desktop/src/activity.ts b/packages/ui/src/activity.ts similarity index 100% rename from apps/desktop/src/activity.ts rename to packages/ui/src/activity.ts diff --git a/apps/desktop/src/agentState.test.ts b/packages/ui/src/agentState.test.ts similarity index 100% rename from apps/desktop/src/agentState.test.ts rename to packages/ui/src/agentState.test.ts diff --git a/apps/desktop/src/agentState.ts b/packages/ui/src/agentState.ts similarity index 100% rename from apps/desktop/src/agentState.ts rename to packages/ui/src/agentState.ts diff --git a/apps/desktop/src/agents.test.ts b/packages/ui/src/agents.test.ts similarity index 100% rename from apps/desktop/src/agents.test.ts rename to packages/ui/src/agents.test.ts diff --git a/packages/ui/src/agents.ts b/packages/ui/src/agents.ts new file mode 100644 index 0000000..70b15ed --- /dev/null +++ b/packages/ui/src/agents.ts @@ -0,0 +1,31 @@ +import antigravityLogo from "./assets/agents/antigravitycli-logo.svg"; +import claudeLogo from "./assets/agents/claudecode-logo.svg"; +import codexLogo from "./assets/agents/codex-logo.svg"; +import grokLogo from "./assets/agents/grok-xai-logo.svg"; +import opencodeLogo from "./assets/agents/opencode-logo.svg"; + +// Presentación de los agentes que detecta el núcleo (ver +// apps/desktop/core/application/src/agent_detection.rs: los ids tienen que coincidir). + +export type AgentId = "claude-code" | "opencode" | "codex" | "antigravity-cli" | "grok"; + +type AgentInfo = { name: string; badge: string; logoFile: string; logo: string | null }; + +const catalog: Record = { + "claude-code": { name: "Claude Code", badge: "CC", logoFile: "claudecode-logo.svg", logo: claudeLogo }, + opencode: { name: "OpenCode", badge: "OC", logoFile: "opencode-logo.svg", logo: opencodeLogo }, + codex: { name: "Codex", badge: "CX", logoFile: "codex-logo.svg", logo: codexLogo }, + "antigravity-cli": { name: "Antigravity CLI", badge: "AG", logoFile: "antigravitycli-logo.svg", logo: antigravityLogo }, + grok: { name: "Grok", badge: "GK", logoFile: "grok-xai-logo.svg", logo: grokLogo }, +}; + +export function agentInfo(id: AgentId) { + return catalog[id]; +} + +/// ¿`value` es un id de agente vigente? Para validar datos guardados: el +/// scheduler de un snapshot viejo podría nombrar un agente que la versión de +/// hoy ya no conoce; ese caso cae a `null` (shell plana) en vez de romper. +export function isAgentId(value: unknown): value is AgentId { + return typeof value === "string" && value in catalog; +} diff --git a/apps/desktop/src/assets/agents/.gitkeep b/packages/ui/src/assets/agents/.gitkeep similarity index 100% rename from apps/desktop/src/assets/agents/.gitkeep rename to packages/ui/src/assets/agents/.gitkeep diff --git a/apps/desktop/src/assets/agents/antigravitycli-logo.svg b/packages/ui/src/assets/agents/antigravitycli-logo.svg similarity index 100% rename from apps/desktop/src/assets/agents/antigravitycli-logo.svg rename to packages/ui/src/assets/agents/antigravitycli-logo.svg diff --git a/apps/desktop/src/assets/agents/claudecode-logo.svg b/packages/ui/src/assets/agents/claudecode-logo.svg similarity index 100% rename from apps/desktop/src/assets/agents/claudecode-logo.svg rename to packages/ui/src/assets/agents/claudecode-logo.svg diff --git a/apps/desktop/src/assets/agents/codex-logo.svg b/packages/ui/src/assets/agents/codex-logo.svg similarity index 100% rename from apps/desktop/src/assets/agents/codex-logo.svg rename to packages/ui/src/assets/agents/codex-logo.svg diff --git a/apps/desktop/src/assets/agents/grok-xai-logo.svg b/packages/ui/src/assets/agents/grok-xai-logo.svg similarity index 100% rename from apps/desktop/src/assets/agents/grok-xai-logo.svg rename to packages/ui/src/assets/agents/grok-xai-logo.svg diff --git a/apps/desktop/src/assets/agents/opencode-logo.svg b/packages/ui/src/assets/agents/opencode-logo.svg similarity index 100% rename from apps/desktop/src/assets/agents/opencode-logo.svg rename to packages/ui/src/assets/agents/opencode-logo.svg diff --git a/packages/ui/src/authTypes.ts b/packages/ui/src/authTypes.ts new file mode 100644 index 0000000..8f2f50e --- /dev/null +++ b/packages/ui/src/authTypes.ts @@ -0,0 +1,20 @@ +export interface AuthUser { + id: string; + username: string; + email: string | null; + displayName: string; +} + +export type AuthState = + | { status: "unknown" } + | { status: "anonymous" } + | { status: "authenticated"; user: AuthUser }; + +/** Iniciales para el avatar (hasta 2 letras, del nombre visible o del usuario). */ +export function initialsOf(user: AuthUser): string { + const source = user.displayName.trim() || user.username; + const parts = source.split(/\s+/); + const first = parts[0]?.charAt(0) ?? "?"; + const second = parts.length > 1 ? (parts[parts.length - 1]?.charAt(0) ?? "") : ""; + return (first + second).toUpperCase(); +} diff --git a/packages/ui/src/boundary.spec.ts b/packages/ui/src/boundary.spec.ts new file mode 100644 index 0000000..1a481d8 --- /dev/null +++ b/packages/ui/src/boundary.spec.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "vitest"; +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { join } from "node:path"; + +function getAllSourceFiles(dir: string): string[] { + const files: string[] = []; + for (const entry of readdirSync(dir)) { + const fullPath = join(dir, entry); + if (statSync(fullPath).isDirectory()) { + files.push(...getAllSourceFiles(fullPath)); + } else if (/\.(ts|tsx)$/.test(entry) && !entry.endsWith("boundary.spec.ts")) { + files.push(fullPath); + } + } + return files; +} + +describe("@opencollab/ui boundary constraints", () => { + const srcFiles = getAllSourceFiles(__dirname); + + it("never imports @tauri-apps/api inside @opencollab/ui", () => { + for (const file of srcFiles) { + const content = readFileSync(file, "utf8"); + expect(content, `File ${file} must not import @tauri-apps/api`).not.toContain("@tauri-apps/api"); + } + }); + + it("never imports @xterm inside @opencollab/ui", () => { + for (const file of srcFiles) { + const content = readFileSync(file, "utf8"); + expect(content, `File ${file} must not import @xterm`).not.toContain("@xterm"); + } + }); +}); diff --git a/apps/desktop/src/assets/brand/index.ts b/packages/ui/src/brand/index.ts similarity index 100% rename from apps/desktop/src/assets/brand/index.ts rename to packages/ui/src/brand/index.ts diff --git a/packages/ui/src/brand/opencollab-logo-rounded.png b/packages/ui/src/brand/opencollab-logo-rounded.png new file mode 100644 index 0000000..4712b9a Binary files /dev/null and b/packages/ui/src/brand/opencollab-logo-rounded.png differ diff --git a/packages/ui/src/brand/opencollab-logo-transparent.png b/packages/ui/src/brand/opencollab-logo-transparent.png new file mode 100644 index 0000000..f218ec0 Binary files /dev/null and b/packages/ui/src/brand/opencollab-logo-transparent.png differ diff --git a/packages/ui/src/collabStatus.test.ts b/packages/ui/src/collabStatus.test.ts new file mode 100644 index 0000000..e18e2dd --- /dev/null +++ b/packages/ui/src/collabStatus.test.ts @@ -0,0 +1,54 @@ +import { describe, expect, it } from "vitest"; + +import { DEFAULT_COLLAB_STATUS, describeCollabMode, parseCollabStatus } from "./collabStatus"; + +describe("DEFAULT_COLLAB_STATUS", () => { + it("es honesto: desconectado, sin latencia y solo el usuario local", () => { + expect(DEFAULT_COLLAB_STATUS).toEqual({ connected: false, syncMs: null, collaborators: 1 }); + }); +}); + +describe("parseCollabStatus", () => { + it("acepta un estado conectado", () => { + expect(parseCollabStatus({ connected: true, syncMs: 12, collaborators: 2 })).toEqual({ + connected: true, + syncMs: 12, + collaborators: 2, + }); + }); + + it("sin conexión no hay latencia, aunque el payload traiga una", () => { + expect(parseCollabStatus({ connected: false, syncMs: 12, collaborators: 1 }).syncMs).toBeNull(); + }); + + it("conectado sin latencia válida la deja en null", () => { + expect(parseCollabStatus({ connected: true, syncMs: null, collaborators: 1 }).syncMs).toBeNull(); + }); + + it("un payload malformado cae a los valores honestos", () => { + expect(parseCollabStatus(null)).toEqual(DEFAULT_COLLAB_STATUS); + expect(parseCollabStatus({ connected: "sí", collaborators: -3 })).toEqual(DEFAULT_COLLAB_STATUS); + }); +}); + +describe("describeCollabMode", () => { + it("en modo local marca la colaboración como inactiva con textos explícitos", () => { + const local = describeCollabMode("local"); + expect(local.inactive).toBe(true); + expect(local.inviteTitle).toContain("Modo local"); + expect(local.workspaceMetaTitle).toBe("Colaboración inactiva en modo local"); + expect(local.onlineLabel).toBe("Local · colaboración inactiva"); + expect(local.anonymousHint).toBe("Colaboración inactiva en modo local"); + expect(local.statusBarTitle).toBe("Colaboración inactiva en modo local"); + }); + + it("en modo cloud mantiene la colaboración activa", () => { + const cloud = describeCollabMode("cloud"); + expect(cloud.inactive).toBe(false); + expect(cloud.inviteTitle).toBe("Requiere el relay: todavía no está conectado"); + expect(cloud.workspaceMetaTitle).toBeUndefined(); + expect(cloud.onlineLabel).toBe("Online"); + expect(cloud.anonymousHint).toBe("Sign in to collaborate"); + expect(cloud.statusBarTitle).toBeUndefined(); + }); +}); diff --git a/apps/desktop/src/collabStatus.ts b/packages/ui/src/collabStatus.ts similarity index 56% rename from apps/desktop/src/collabStatus.ts rename to packages/ui/src/collabStatus.ts index fd48449..04d70bd 100644 --- a/apps/desktop/src/collabStatus.ts +++ b/packages/ui/src/collabStatus.ts @@ -9,6 +9,38 @@ export type CollabStatus = { collaborators: number; }; +export type StorageMode = "local" | "cloud"; + +export type CollabModeCopy = { + inactive: boolean; + inviteTitle: string; + workspaceMetaTitle: string | undefined; + onlineLabel: string; + anonymousHint: string; + statusBarTitle: string | undefined; +}; + +export function describeCollabMode(mode: StorageMode = "cloud"): CollabModeCopy { + if (mode === "local") { + return { + inactive: true, + inviteTitle: "Modo local: cambiá a Cloud en Settings para invitar colaboradores", + workspaceMetaTitle: "Colaboración inactiva en modo local", + onlineLabel: "Local · colaboración inactiva", + anonymousHint: "Colaboración inactiva en modo local", + statusBarTitle: "Colaboración inactiva en modo local", + }; + } + return { + inactive: false, + inviteTitle: "Requiere el relay: todavía no está conectado", + workspaceMetaTitle: undefined, + onlineLabel: "Online", + anonymousHint: "Sign in to collaborate", + statusBarTitle: undefined, + }; +} + export const DEFAULT_COLLAB_STATUS: CollabStatus = { connected: false, syncMs: null, collaborators: 1 }; /// Convierte el payload del núcleo (`collab_status` / evento `collab-status`) en un diff --git a/apps/desktop/src/components/Button.tsx b/packages/ui/src/components/Button.tsx similarity index 100% rename from apps/desktop/src/components/Button.tsx rename to packages/ui/src/components/Button.tsx diff --git a/apps/desktop/src/components/Panel.tsx b/packages/ui/src/components/Panel.tsx similarity index 100% rename from apps/desktop/src/components/Panel.tsx rename to packages/ui/src/components/Panel.tsx diff --git a/packages/ui/src/components/PopoverMenu.tsx b/packages/ui/src/components/PopoverMenu.tsx new file mode 100644 index 0000000..d23f809 --- /dev/null +++ b/packages/ui/src/components/PopoverMenu.tsx @@ -0,0 +1,116 @@ +import { + useEffect, + useLayoutEffect, + useRef, + useState, + type ReactNode, + type RefObject, +} from "react"; +import { createPortal } from "react-dom"; + +export type MenuAlign = "left" | "right"; +export type MenuPosition = { left?: number; right?: number; top: number }; + +export function anchorMenuPosition( + rect: Pick, + align: MenuAlign = "left", + viewportWidth = typeof window !== "undefined" ? window.innerWidth : 0, + gap = 4, +): MenuPosition { + if (align === "right") { + return { + right: viewportWidth - rect.right, + top: rect.bottom + gap, + }; + } + return { + left: rect.left, + top: rect.bottom + gap, + }; +} + +export function clampMenuPosition( + clientX: number, + clientY: number, + viewportWidth: number, + viewportHeight: number, + menuWidth = 210, + menuHeight = 160, + margin = 8, +): { left: number; top: number } { + return { + left: Math.min(clientX, Math.max(margin, viewportWidth - menuWidth - margin)), + top: Math.min(clientY, Math.max(margin, viewportHeight - menuHeight - margin)), + }; +} + +type Props = { + open: boolean; + onClose: () => void; + /// Botón que abre el menú: el menú se ubica debajo suyo y los clics sobre él no disparan `onClose` acá. + anchorRef?: RefObject; + /// Alineación respecto de `anchorRef` (`left` en CwdSwitcher, `right` en NewTerminalMenu). + align?: MenuAlign; + /// Coordenadas fijas cuando el menú se abre en el cursor (p. ej. clic derecho en la terminal). + position?: MenuPosition | null; + className?: string; + children: ReactNode; +}; + +/// Menú flotante renderizado en un portal sobre `document.body` para no quedar +/// recortado por contenedores con `overflow: hidden`. Se cierra solo con clic +/// afuera (`pointerdown`), `Escape` o al redimensionar la ventana. +export function PopoverMenu({ + open, + onClose, + anchorRef, + align = "left", + position, + className, + children, +}: Props) { + const menuRef = useRef(null); + const onCloseRef = useRef(onClose); + onCloseRef.current = onClose; + const [anchorPos, setAnchorPos] = useState(null); + + useLayoutEffect(() => { + if (!open || position || !anchorRef?.current) return; + const rect = anchorRef.current.getBoundingClientRect(); + setAnchorPos(anchorMenuPosition(rect, align, window.innerWidth)); + }, [open, position, anchorRef, align]); + + useEffect(() => { + if (!open) return; + const onDown = (e: PointerEvent) => { + const target = e.target as Node; + if (menuRef.current?.contains(target)) return; + if (anchorRef?.current?.contains(target)) return; + onCloseRef.current(); + }; + const onKey = (e: KeyboardEvent) => { + if (e.key === "Escape") onCloseRef.current(); + }; + const onResize = () => onCloseRef.current(); + document.addEventListener("pointerdown", onDown); + document.addEventListener("keydown", onKey); + window.addEventListener("resize", onResize); + return () => { + document.removeEventListener("pointerdown", onDown); + document.removeEventListener("keydown", onKey); + window.removeEventListener("resize", onResize); + }; + }, [open, anchorRef]); + + const resolvedPosition = position ?? anchorPos; + if (!open || !resolvedPosition) return null; + + const classes = ["cwd-menu", className].filter(Boolean).join(" "); + + return createPortal( +
+ {children} +
, + document.body, + ); +} diff --git a/apps/desktop/src/components/Sidebar.tsx b/packages/ui/src/components/Sidebar.tsx similarity index 88% rename from apps/desktop/src/components/Sidebar.tsx rename to packages/ui/src/components/Sidebar.tsx index 5916305..fcd8614 100644 --- a/apps/desktop/src/components/Sidebar.tsx +++ b/packages/ui/src/components/Sidebar.tsx @@ -3,9 +3,10 @@ import { useEffect, useRef, useState } from "react"; import { VscTerminal } from "react-icons/vsc"; import { agentInfo } from "../agents"; -import { opencollabLogoRounded } from "../assets/brand"; -import { initialsOf, type AuthState } from "../auth"; -import { Check, ChevronDown, ChevronsUpDown, Plus, Search, SignOut } from "../icons"; +import { opencollabLogoRounded } from "../brand"; +import { initialsOf, type AuthState } from "../authTypes"; +import { describeCollabMode, type CollabModeCopy, type StorageMode } from "../collabStatus"; +import { Check, ChevronDown, Plus, Search, SignOut } from "../icons"; import { sessionSummary, type PaneMeta, @@ -32,6 +33,7 @@ type Props = { onSelectSession: (id: string) => void; onSelectTerminal: (sessionId: string, paneId: string) => void; onCreateSession: () => void; + storageMode?: StorageMode; auth: AuthState; authBusy: boolean; authError: string | null; @@ -43,6 +45,7 @@ type Props = { export function Sidebar(props: Props) { const { workspaces, activeWorkspace, activeSessionId, statuses, meta } = props; + const collab = describeCollabMode(props.storageMode); const [switcherOpen, setSwitcherOpen] = useState(false); const [query, setQuery] = useState(""); const switcherRef = useRef(null); @@ -74,7 +77,11 @@ export function Sidebar(props: Props) { {activeWorkspace.name} - + Workspace · {activeWorkspace.members} member{activeWorkspace.members === 1 ? "" : "s"} @@ -187,11 +194,14 @@ export function Sidebar(props: Props) { const { tone, label: stateLabel } = describeAgent(agentState, attention); const branch = m?.branch ?? null; const select = () => props.onSelectTerminal(s.id, pane.id); + const hasUptime = agent !== null && m?.startedAt != null; return (
  • + } title="Settings" onClick={props.onOpenSettings} />
    {layouts.map(({ id, label, icon: LayoutIcon }) => (