mirror of
https://github.com/stablyai/orca.git
synced 2026-11-17 03:15:01 +00:00
Merge remote-tracking branch 'private/cloud/integration' into cloud/copy-sweep
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -9,6 +9,28 @@ set -euo pipefail
|
||||
DIR=/etc/orca/members
|
||||
caller="${SUDO_USER:-}"
|
||||
case "$caller" in '' | root | *[!a-z0-9_-]*) echo 'orca-git-identity: run through orca-git-as' >&2; exit 4 ;; esac
|
||||
# Hands the caller a one-shot copy of a member's git config (owned by them, removed by orca-git-as).
|
||||
emit() {
|
||||
local file
|
||||
file="$DIR/$(printf '%s' "$1" | tr ':' '_').gitconfig"
|
||||
[ -s "$file" ] || exit 3
|
||||
out="$(sudo -u "$caller" mktemp)"
|
||||
cat "$file" >"$out"
|
||||
echo "$out"
|
||||
exit 0
|
||||
}
|
||||
# GH-SOLO: a workspace only one person can use (the control plane's rule, member-git.ts pickActing) acts as that
|
||||
# person whoever typed: a TUI typed into directly has no attested sender. The control plane writes `solo` only
|
||||
# while that holds, and removes it before any other member's device is paired (grants.ts).
|
||||
if [ -s "$DIR/solo" ]; then
|
||||
solo="$(cat "$DIR/solo")"
|
||||
case "$solo" in '' | *[!A-Za-z0-9_.:-]*) exit 3 ;; esac
|
||||
if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$solo" ]; then
|
||||
echo "orca-git-as: only $solo uses this workspace, not $ORCA_GIT_AS; refusing to push as someone else." >&2
|
||||
exit 4
|
||||
fi
|
||||
emit "$solo"
|
||||
fi
|
||||
# orcad's own data dir and HOME (the agent's user may not use its passwd home, e.g. HOME=/vercel).
|
||||
orcad_pid="$(pgrep -u "$caller" -f orcad-server.js | head -n 1 || true)"
|
||||
[ -n "$orcad_pid" ] || exit 3
|
||||
@@ -42,9 +64,4 @@ if [ -n "${ORCA_GIT_AS:-}" ] && [ "$ORCA_GIT_AS" != "$member" ]; then
|
||||
echo "orca-git-as: this agent's latest message came from $member, not $ORCA_GIT_AS; refusing to push as someone else." >&2
|
||||
exit 4
|
||||
fi
|
||||
file="$DIR/$(printf '%s' "$member" | tr ':' '_').gitconfig"
|
||||
[ -s "$file" ] || exit 3
|
||||
# The caller reads the identity through this one-shot copy (owned by them, removed by orca-git-as).
|
||||
out="$(sudo -u "$caller" mktemp)"
|
||||
cat "$file" >"$out"
|
||||
echo "$out"
|
||||
emit "$member"
|
||||
|
||||
@@ -51,6 +51,15 @@ done < <(jq -c '.[]' <<<"$coauthors")
|
||||
DEVICES_JQ='add | [.[] | select(.userId | test("^[A-Za-z0-9_.:-]+$")) | .userId as $u | (.deviceIds // [])[] | select(test("^[A-Za-z0-9_-]{1,128}$")) | {key: ., value: $u}] | group_by(.key) | map(select((map(.value) | unique | length) == 1) | .[0]) | from_entries'
|
||||
jq -c -s "$DEVICES_JQ" <(printf '%s' "$json") <(printf '%s' "$coauthors") >"$tmp/devices.json"
|
||||
devices="$(jq 'length' "$tmp/devices.json")"
|
||||
# GH-SOLO: ORCA_SOLO_MEMBER = the only person who can use this workspace (absent when shared). orca-git-identity
|
||||
# then acts as them without an attested sender, matching the control plane.
|
||||
solo="${ORCA_SOLO_MEMBER:-}"
|
||||
solo_file=''
|
||||
case "$solo" in '' | *[!A-Za-z0-9_.:-]*) solo='' ;; esac
|
||||
if [ -n "$solo" ]; then
|
||||
solo_file="$tmp/$(printf '%s' "$solo" | tr ':' '_').gitconfig"
|
||||
if [ -s "$solo_file" ]; then printf '%s\n' "$solo" >"$tmp/solo"; else solo=''; solo_file=''; fi
|
||||
fi
|
||||
chmod 0700 "$tmp" && chmod 0600 "$tmp"/*
|
||||
rm -rf "$DIR.old"
|
||||
[ -d "$DIR" ] && mv "$DIR" "$DIR.old"
|
||||
@@ -71,6 +80,21 @@ fi
|
||||
user_home="$(getent passwd "$USER_NAME" | cut -d: -f6)"
|
||||
[ -n "$orcad_pid" ] && user_home="$(tr '\0' '\n' <"/proc/$orcad_pid/environ" | sed -n 's/^HOME=//p' | head -n 1)"
|
||||
[ -n "$user_home" ] && rm -rf "$user_home/.orca-sandbox/members"
|
||||
# GH-SOLO: in a one-person workspace a plain `git commit` (no turn at all) is theirs too: the default author is
|
||||
# the member's GitHub noreply identity. Marked, so a workspace that becomes shared goes back to Orca's.
|
||||
if [ -n "$user_home" ]; then
|
||||
as_user() { sudo -u "$USER_NAME" env HOME="$user_home" git config --global "$@"; }
|
||||
solo_email="$( [ -n "$solo" ] && git config -f "$DIR/$(printf '%s' "$solo" | tr ':' '_').gitconfig" user.email 2>/dev/null || true)"
|
||||
if [ -n "$solo_email" ]; then
|
||||
as_user user.name "$(git config -f "$DIR/$(printf '%s' "$solo" | tr ':' '_').gitconfig" user.name)"
|
||||
as_user user.email "$solo_email"
|
||||
as_user orca.soloauthor true
|
||||
elif [ "$(as_user --get orca.soloauthor 2>/dev/null || true)" = true ]; then
|
||||
as_user user.name 'Orca'
|
||||
as_user user.email 'noreply@orca.dev'
|
||||
as_user --unset orca.soloauthor || true
|
||||
fi
|
||||
fi
|
||||
# Commits outside a teammate's turn still need an author (images older than orca-sandbox-start's default).
|
||||
if [ -n "$user_home" ]; then
|
||||
sudo -u "$USER_NAME" env HOME="$user_home" git config --global user.email >/dev/null 2>&1 \
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "wrangler dev -c wrangler.jsonc -c wrangler.build-runner.jsonc --port 8791 --ip 127.0.0.1",
|
||||
"dev": "wrangler dev -c wrangler.jsonc -c wrangler.build-runner.jsonc --var SANDBOX_ENV:local --port 8791 --ip 127.0.0.1",
|
||||
"db:migrate:local": "wrangler d1 migrations apply SANDBOX_DB --local",
|
||||
"golden-image": "tsx image/build-golden-image.ts",
|
||||
"typecheck": "node scripts/typecheck.mjs",
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env node
|
||||
// Launch smoke for a deployed sandbox-control Worker: its public /v1/health must say ok, model keys swapped at
|
||||
// egress (keySwap "on"), and the environment it was deployed as (default "prod"). A prod Worker missing
|
||||
// SANDBOX_ENV=prod reports something else and fails here, before anything else runs against it.
|
||||
// node scripts/launch-smoke.mjs <base url> [expected environment, default prod]
|
||||
const [base, expected = 'prod'] = process.argv.slice(2)
|
||||
if (!base) {
|
||||
console.error('usage: launch-smoke.mjs <base url> [expected environment]')
|
||||
process.exit(2)
|
||||
}
|
||||
const response = await fetch(new URL('/v1/health', base), { signal: AbortSignal.timeout(15_000) })
|
||||
const body = await response.json().catch(() => null)
|
||||
const problems = []
|
||||
if (response.status !== 200 || body?.ok !== true) problems.push(`health ${response.status} ${JSON.stringify(body)}`)
|
||||
if (body?.keySwap !== 'on') problems.push(`keySwap is ${JSON.stringify(body?.keySwap)}, expected "on"`)
|
||||
if (body?.environment !== expected) problems.push(`environment is ${JSON.stringify(body?.environment)}, expected ${JSON.stringify(expected)}`)
|
||||
if (problems.length > 0) {
|
||||
console.error(`launch smoke FAILED for ${base}:\n- ${problems.join('\n- ')}`)
|
||||
process.exit(1)
|
||||
}
|
||||
console.log(`launch smoke OK: ${base} is ${expected}, keySwap on`)
|
||||
@@ -15,7 +15,8 @@ import { memberNamesFor } from './member-names'
|
||||
import { effectiveSecrets } from './secrets'
|
||||
import { getSandbox, type SandboxRow } from './store'
|
||||
import { agentCredentialState, isUsable } from './agent-credentials'
|
||||
import { accountProvider, isSharedWorkspace } from './account-providers'
|
||||
import { accountProvider } from './account-providers'
|
||||
import { sharedWorkspaceMode } from './shared-workspace'
|
||||
|
||||
export type AgentSource = 'sign-in' | 'key'
|
||||
type OfferAnswer = 'unanswered' | 'accepted' | 'declined'
|
||||
@@ -157,7 +158,7 @@ export async function agentSourcesView(
|
||||
owner = { userId: row.user_id, displayName: names.get(row.user_id) ?? null, isCaller: row.user_id === caller.userId }
|
||||
}
|
||||
// D13: personal accounts never apply in a workspace shared with teammates.
|
||||
const sharedWorkspace = row ? isSharedWorkspace(row) : false
|
||||
const sharedWorkspace = row ? await sharedWorkspaceMode(db, row) : false
|
||||
return { defaults, inWorkspace, workspace, effective: resolved, coveredByKey: covered, signInOffer, owner, sharedWorkspace }
|
||||
}
|
||||
|
||||
@@ -236,6 +237,7 @@ export async function agentModesFor(
|
||||
const inWorkspace = inWorkspaceAgents(rows)
|
||||
const covered = coveredByKey(new Set(Object.keys(env)))
|
||||
const modes = {} as Record<CredentialAgent, AgentMode>
|
||||
const shared = await sharedWorkspaceMode(db, row)
|
||||
for (const agent of CREDENTIAL_AGENTS) {
|
||||
if (!workspace[agent] && inWorkspace[agent]) {
|
||||
// Nothing of Orca's for this agent: no placeholder, no key, no egress route, so the login the person
|
||||
@@ -255,7 +257,7 @@ export async function agentModesFor(
|
||||
} else if (!enabled) {
|
||||
// Kill switch (or no provider yet): the agent signs in inside the sandbox; keys stay out (Rule 3).
|
||||
modes[agent] = 'omit'
|
||||
} else if (usable && options.accountsUsable && !isSharedWorkspace(row)) {
|
||||
} else if (usable && options.accountsUsable && !shared) {
|
||||
modes[agent] = 'account'
|
||||
} else {
|
||||
// Expired/revoked, placeholders off, or a shared workspace (D13): the winning key, if any.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Desktop callers present a short-lived ES256 JWT minted by Orca Cloud auth (aud=orca-sandbox,
|
||||
// purpose=sandbox), verified against the auth JWKS — the billing Worker's pattern.
|
||||
import { devOnly } from './dev-only'
|
||||
import {
|
||||
createLocalJWKSet,
|
||||
jwtVerify,
|
||||
@@ -114,7 +115,7 @@ let stagingKeys: { source: string; keys: JWTVerifyGetKey } | null = null
|
||||
/** Staging auth's keys and issuer; never honored in prod. Same accounts as billing dev (it trusts staging too). */
|
||||
function stagingKeysFor(env: Env): { keys: JWTVerifyGetKey; issuer: string[] | undefined } | null {
|
||||
const source = env.SANDBOX_STAGING_JWKS_URL ?? (env.SANDBOX_STAGING_JWKS ? `inline:${env.SANDBOX_STAGING_JWKS}` : null)
|
||||
if (env.SANDBOX_ENV === 'prod' || !source || !env.SANDBOX_STAGING_AUTH_ISSUER) {
|
||||
if (!devOnly(env) || !source || !env.SANDBOX_STAGING_AUTH_ISSUER) {
|
||||
return null
|
||||
}
|
||||
if (stagingKeys?.source !== source) {
|
||||
@@ -177,7 +178,7 @@ export async function authenticateDesktop(
|
||||
const caller =
|
||||
(await verify(token, keysFor(env), env, issuerList(env.SANDBOX_AUTH_ISSUER), now)) ??
|
||||
(staging ? await verify(token, staging.keys, env, staging.issuer, now) : null)
|
||||
if (caller || !env.SANDBOX_DEV_JWKS || env.SANDBOX_ENV === 'prod') {
|
||||
if (caller || !env.SANDBOX_DEV_JWKS || !devOnly(env)) {
|
||||
if (!caller || (await tokenPredatesRemoval(env.SANDBOX_DB, caller))) {
|
||||
return null
|
||||
}
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
// Dev-only routes and behaviors (operator/seed/dev-sign-in/debug): an allowlist of environment names, so an
|
||||
// unset SANDBOX_ENV, staging, prod or a typo all leave them off. Never `!== 'prod'`.
|
||||
import type { Env } from './env'
|
||||
|
||||
export function devOnly(env: Pick<Env, 'SANDBOX_ENV'>): boolean {
|
||||
return env.SANDBOX_ENV === 'dev' || env.SANDBOX_ENV === 'local' || env.SANDBOX_ENV === 'test'
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
// Billing Worker client (cloud/apps/billing on nwparker/billing-worker): start checks and usage.
|
||||
// Fails closed: without a configured billing URL no sandbox starts, except the local-dev stub.
|
||||
import { devOnly } from './dev-only'
|
||||
import { z } from 'zod'
|
||||
import type { Env } from './env'
|
||||
|
||||
@@ -95,7 +96,7 @@ export const STOP_RUNNING_REASONS: ReadonlySet<string> = new Set([
|
||||
/** Dev operator test accounts (`dev:*`, see auth.ts) never reach billing outside prod. */
|
||||
export function withDevAccountBypass(env: Env, client: EntitlementClient): EntitlementClient {
|
||||
// SANDBOX_DEV_BILLING_PASSTHROUGH=true sends dev accounts to billing too (live smoke of the internal routes).
|
||||
if (env.SANDBOX_ENV === 'prod' || env.SANDBOX_DEV_BILLING_PASSTHROUGH === 'true') {
|
||||
if (!devOnly(env) || env.SANDBOX_DEV_BILLING_PASSTHROUGH === 'true') {
|
||||
return client
|
||||
}
|
||||
const enforced = devBillingEnforcePrefix(env)
|
||||
@@ -135,8 +136,8 @@ export function createEntitlementClient(
|
||||
doFetch: typeof fetch = env.BILLING ? (input, init) => env.BILLING!.fetch(input, init) : fetch
|
||||
): EntitlementClient {
|
||||
if (env.ENTITLEMENTS_MODE === 'stub') {
|
||||
if (env.SANDBOX_ENV === 'prod') {
|
||||
throw new BillingUnavailableError('stub entitlements refused in prod')
|
||||
if (!devOnly(env)) {
|
||||
throw new BillingUnavailableError('stub entitlements refused outside dev')
|
||||
}
|
||||
return {
|
||||
checkStart: async () => ({ allow: true, reason: null, suspendRunning: false }),
|
||||
|
||||
@@ -41,6 +41,8 @@ export type Env = {
|
||||
/** GH-AS-MEMBER: how long a shared workspace's latest sender keeps acting after their last send (default 60; `0`: no cap). */
|
||||
MEMBER_GIT_SHARED_MAX_MINUTES?: string
|
||||
/** GH-AS-MEMBER: `on` lets gh in workspaces act as the attested sender (off by default). */
|
||||
/** TEAM-SHARING hold (team-sharing.ts): `on` lets workspaces be shared with the team; anything else holds it. */
|
||||
TEAM_SHARING?: string
|
||||
GH_AS_MEMBER?: string
|
||||
/**
|
||||
* Who sees a member's daily activity heatmap on their profile. `opt_in` (default): only members
|
||||
|
||||
@@ -7,11 +7,12 @@
|
||||
// DELETE /v1/team/workspaces/:id/grants/:grantId grantee, workspace owner or org admin
|
||||
// Revocation removes the device from orcad's registry (orca-sandbox-revoke); while the sandbox is
|
||||
// not running it is queued and applied at the next boot before orcad starts.
|
||||
import { teamSharingEnabled } from './team-sharing'
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { isDeviceSessionLive } from './device-sessions'
|
||||
import { markRevoked, runVmRevoke, type GrantRow } from './grant-revokes'
|
||||
import { LifecycleError, settleMemberGit, resumeSandbox, syncMemberGit, type LifecycleDeps, type Ready } from './lifecycle'
|
||||
import { DROP_SOLO_SCRIPT, LifecycleError, settleMemberGit, resumeSandbox, syncMemberGit, type LifecycleDeps, type Ready } from './lifecycle'
|
||||
import { ensureEntryPoints } from './golden-images'
|
||||
import type { CommandResult } from './sandbox-provider'
|
||||
import { ORCAD_PORT } from './sandbox-vm-commands'
|
||||
@@ -133,6 +134,14 @@ export async function issueGrant(
|
||||
.run()
|
||||
let output: z.infer<typeof GrantOutputSchema>
|
||||
try {
|
||||
// GH-SOLO: anyone but a still-untransferred owner makes it (possibly) shared: drop the VM's one-person mark
|
||||
// first, and refuse the grant if that fails (lifecycle.ts DROP_SOLO_SCRIPT).
|
||||
if (caller.userId !== row.user_id || row.ownership_transferred_at != null) {
|
||||
const dropped = await deps.provider.runCommand(live.sessionId, { command: 'bash', args: ['-c', DROP_SOLO_SCRIPT], sudo: true, timeoutMs: 15_000 })
|
||||
if (dropped.exitCode !== 0) {
|
||||
throw new Error(`drop_solo_exit_${dropped.exitCode}`)
|
||||
}
|
||||
}
|
||||
const result = await withEntryPoints(deps, live.sessionId, GRANT_COMMAND, () =>
|
||||
deps.provider.runCommand(live.sessionId, {
|
||||
command: GRANT_COMMAND,
|
||||
@@ -260,6 +269,40 @@ export async function revokeForAccessChange(
|
||||
return revokeGrants(deps, row, results, { by, reason: mode === 'non_owner' ? 'workspace_private' : 'owner_changed' })
|
||||
}
|
||||
|
||||
/**
|
||||
* TEAM-SHARING hold (team-sharing.ts): while sharing is held, a workspace stored as `team` acts private, so
|
||||
* every device grant but its owner's goes, the way making it private revokes them (reason team_sharing_held).
|
||||
* Transferred workspaces keep their own rules. Bounded per run; the next run takes the rest.
|
||||
*/
|
||||
export async function sweepHeldTeamGrants(deps: LifecycleDeps): Promise<{ workspaces: number; revoked: number; queued: number }> {
|
||||
const out = { workspaces: 0, revoked: 0, queued: 0 }
|
||||
if (teamSharingEnabled()) {
|
||||
return out
|
||||
}
|
||||
const { results } = await deps.db
|
||||
.prepare(
|
||||
`SELECT g.* FROM workspace_grants g JOIN sandboxes s ON s.id = g.sandbox_id
|
||||
WHERE g.status IN ('issuing', 'active') AND g.user_id <> s.user_id AND s.visibility = 'team' AND s.ownership_transferred_at IS NULL AND s.status <> 'destroyed'
|
||||
ORDER BY g.sandbox_id LIMIT 500`
|
||||
)
|
||||
.all<GrantRow>()
|
||||
const bySandbox = new Map<string, GrantRow[]>()
|
||||
for (const grant of results) {
|
||||
bySandbox.set(grant.sandbox_id, [...(bySandbox.get(grant.sandbox_id) ?? []), grant])
|
||||
}
|
||||
for (const [sandboxId, grants] of bySandbox) {
|
||||
const row = await getSandbox(deps.db, sandboxId)
|
||||
if (!row) {
|
||||
continue
|
||||
}
|
||||
const result = await revokeGrants(deps, row, grants, { by: 'system', reason: 'team_sharing_held' }).catch(() => ({ revoked: 0, queued: 0 }))
|
||||
out.workspaces++
|
||||
out.revoked += result.revoked
|
||||
out.queued += result.queued
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/** A member left the org (auth push) or a phone session ended (W8): revoke everywhere. */
|
||||
async function revokeWhere(deps: LifecycleDeps, where: string, binds: (string | number)[], audit: { by: string; reason: string }) {
|
||||
const { results } = await deps.db
|
||||
|
||||
@@ -39,6 +39,8 @@
|
||||
// Operator (OPERATOR_TOKEN): /v1/internal/* (see operator.ts)
|
||||
// Public share links (src/share-gateway.ts): /s/<token>/*, plus the root-path cookie fallback
|
||||
// Vercel network-policy forwardURL target (Vercel sandbox OIDC): /v1/egress/proxy
|
||||
import { devOnly } from './dev-only'
|
||||
import { configureTeamSharing, teamSharingEnabled } from './team-sharing'
|
||||
import { purgeTeamSecrets, teamDeleteRoute, teamWorkspaceCount } from './team-delete'
|
||||
import { ReadSnapshotRouteError, getReadSnapshot, handleReaderKeysRoute, pruneReadSnapshotToOwner, revokeDeviceSessionReaderKeys } from './read-snapshots'
|
||||
import { refreshEnvironment, refreshStaleEnvironments, type GoldenRefreshOptions } from './environment-golden-refresh'
|
||||
@@ -137,7 +139,8 @@ import { pushCredentialToSandbox, refreshAfterSecretChange, refreshSandboxEnv }
|
||||
import { credentialPushTargets, markCredentialChanged, pushCredentialChange, pushPendingCredentialChanges, type CredentialChange, type PushDeps } from './credential-outbox'
|
||||
import { markExpiredAccountCredentials, refreshGitHubUserTokens } from './credential-refresh'
|
||||
import type { CredentialAgent } from './agent-credential-names'
|
||||
import { ACCOUNT_PROVIDERS, accountProvider, claudeAccount, isSharedWorkspace } from './account-providers'
|
||||
import { ACCOUNT_PROVIDERS, accountProvider, claudeAccount } from './account-providers'
|
||||
import { sharedWorkspaceMode } from './shared-workspace'
|
||||
import { handleAccountRequestSucceeded, handleAccountUnauthorized, runScheduledAccountChecks, verifyAccountCredential } from './agent-credential-checks'
|
||||
import { codexBrokerTick, handleCodexBrokerRoute, type BrokerDeps } from './codex-broker'
|
||||
import { codexAccount, parseStoredCodex, refreshCodexLeases, storeCodexLogin } from './codex-credentials'
|
||||
@@ -207,7 +210,8 @@ import {
|
||||
recordOwnerDeviceForCreate,
|
||||
revokeForAccessChange,
|
||||
revokeGrantsForDeviceSession,
|
||||
revokeOne
|
||||
revokeOne,
|
||||
sweepHeldTeamGrants
|
||||
} from './grants'
|
||||
import { getOrgPrompts, putOrgPrompts } from './org-prompts'
|
||||
import {
|
||||
@@ -475,7 +479,7 @@ function egressRoutes(env: Env, deps: Deps): (row: SandboxRow, host: string) =>
|
||||
scheduleEnvRefresh(env, deps, row)
|
||||
return signedOut('account_owner_changed')
|
||||
}
|
||||
if (isSharedWorkspace(row)) {
|
||||
if (await sharedWorkspaceMode(env.SANDBOX_DB, row)) {
|
||||
scheduleEnvRefresh(env, deps, row)
|
||||
return signedOut('account_not_shared')
|
||||
}
|
||||
@@ -888,7 +892,7 @@ function githubManifestStart(url: URL): Response {
|
||||
|
||||
/** GitHub App manifest flow redirect: the operator's exchange script reads the one-time code from logs. */
|
||||
function githubManifestCallback(env: Env, url: URL): Response {
|
||||
if (env.SANDBOX_ENV === 'prod') {
|
||||
if (!devOnly(env)) {
|
||||
return fail('not_found', 404)
|
||||
}
|
||||
const code = url.searchParams.get('code') ?? ''
|
||||
@@ -923,7 +927,7 @@ async function configureAppWebhook(env: Env, deps: Deps, body: unknown): Promise
|
||||
|
||||
function devCredentials(env: Env): CredentialBroker {
|
||||
const value = env.EGRESS_DEV_STATIC_AUTHORIZATION
|
||||
if (!value || env.SANDBOX_ENV === 'prod') {
|
||||
if (!value || !devOnly(env)) {
|
||||
return NO_CREDENTIALS
|
||||
}
|
||||
return { authorizationFor: async (_row, host) => (host === 'api.github.com' ? value : null) }
|
||||
@@ -1061,7 +1065,7 @@ export async function lifecycleDeps(env: Env, deps: Deps): Promise<LifecycleDeps
|
||||
...regions,
|
||||
egressProxyUrl: env.EGRESS_PROXY_URL,
|
||||
sessionDeadlineMs:
|
||||
env.SESSION_DEADLINE_MS && env.SANDBOX_ENV !== 'prod' ? Number(env.SESSION_DEADLINE_MS) : undefined
|
||||
env.SESSION_DEADLINE_MS && devOnly(env) ? Number(env.SESSION_DEADLINE_MS) : undefined
|
||||
}
|
||||
}
|
||||
// ENV-BUILD-CHURN: every environment boot records the use; a stale one refreshes lazily.
|
||||
@@ -1101,7 +1105,7 @@ async function goldenRegions(
|
||||
}
|
||||
// Preview versions in dev may pin an image under test (shared D1's active image is the live one);
|
||||
// the pin replaces the default region's image, so it must be a snapshot taken in that region.
|
||||
const override = env.SANDBOX_ENV !== 'prod' ? env.GOLDEN_SNAPSHOT_OVERRIDE : undefined
|
||||
const override = devOnly(env) ? env.GOLDEN_SNAPSHOT_OVERRIDE : undefined
|
||||
if (override) {
|
||||
goldens[defaultRegion] = override
|
||||
}
|
||||
@@ -1355,6 +1359,7 @@ async function shareGateway(request: Request, url: URL, env: Env, deps: Deps): P
|
||||
}
|
||||
|
||||
export async function handleRequest(request: Request, env: Env, deps: Deps = {}): Promise<Response> {
|
||||
configureTeamSharing(env)
|
||||
try {
|
||||
return await routeRequest(request, env, deps)
|
||||
} catch (error) {
|
||||
@@ -1443,7 +1448,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
if (url.pathname === '/v1/github/manifest-callback') {
|
||||
return githubManifestCallback(env, url)
|
||||
}
|
||||
if (url.pathname === '/v1/github/manifest-start' && env.SANDBOX_ENV !== 'prod') {
|
||||
if (url.pathname === '/v1/github/manifest-start' && devOnly(env)) {
|
||||
return githubManifestStart(url)
|
||||
}
|
||||
if (url.pathname === '/v1/github/setup' || url.pathname === '/v1/github/callback') {
|
||||
@@ -1515,7 +1520,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
if (url.pathname === '/v1/internal/github/app-webhook' && request.method === 'POST') {
|
||||
return await configureAppWebhook(env, deps, await readJson(request))
|
||||
}
|
||||
if (url.pathname === '/v1/internal/dev/member-github' && request.method === 'POST' && env.SANDBOX_ENV !== 'prod') {
|
||||
if (url.pathname === '/v1/internal/dev/member-github' && request.method === 'POST' && devOnly(env)) {
|
||||
// Dev rehearsal only: stand in a member's GitHub user token with a fresh app installation
|
||||
// token for one repo, so git-as-sender can be exercised without a second GitHub human.
|
||||
const body = DevMemberGitHubSchema.safeParse(await readJson(request))
|
||||
@@ -1538,7 +1543,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
)
|
||||
return json({ stored: true, expiresAt: minted.expiresAt })
|
||||
}
|
||||
if (url.pathname === '/v1/internal/dev/codex-login' && request.method === 'POST' && env.SANDBOX_ENV !== 'prod') {
|
||||
if (url.pathname === '/v1/internal/dev/codex-login' && request.method === 'POST' && devOnly(env)) {
|
||||
// Dev rehearsal only (EGRESS-REFRESH): store a Codex login for a throwaway identity, so the central
|
||||
// refresher can be exercised with a near-expiry or bogus token without a real ChatGPT sign-in.
|
||||
const body = DevCodexLoginSchema.safeParse(await readJson(request))
|
||||
@@ -1583,8 +1588,9 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
console.error(JSON.stringify({ event: 'config_error', variable: 'EGRESS_PROXY_URL', environment: env.SANDBOX_ENV }))
|
||||
return json({ error: 'egress_proxy_missing', keySwap: 'off' }, 503)
|
||||
}
|
||||
// keySwap: whether model keys can be swapped at egress (the launch smoke asserts "on").
|
||||
return json({ ok: true, keySwap: env.EGRESS_PROXY_URL ? 'on' : 'off' }, 200)
|
||||
// keySwap: whether model keys can be swapped at egress; environment: the SANDBOX_ENV name (not a secret).
|
||||
// The launch smoke (scripts/launch-smoke.mjs) asserts keySwap "on" and environment "prod".
|
||||
return json({ ok: true, keySwap: env.EGRESS_PROXY_URL ? 'on' : 'off', environment: env.SANDBOX_ENV ?? null }, 200)
|
||||
}
|
||||
if (url.pathname === '/v1/config' && request.method === 'GET') {
|
||||
// Public product constants (no auth): every client reads these instead of hardcoding them.
|
||||
@@ -1599,7 +1605,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
{ headers: { 'cache-control': 'public, max-age=300' } }
|
||||
)
|
||||
}
|
||||
if (url.pathname === '/v1/github/dev-connect' && env.SANDBOX_ENV !== 'prod') {
|
||||
if (url.pathname === '/v1/github/dev-connect' && devOnly(env)) {
|
||||
// Dev-only, link-shareable start of the user flow: mints a fresh 10-min state per click for a dev:<sub>
|
||||
// account (desktop builds call POST /v1/github/connect instead).
|
||||
const connect = githubConnect(env, deps)
|
||||
@@ -1644,7 +1650,7 @@ async function routeRequest(request: Request, env: Env, deps: Deps): Promise<Res
|
||||
})
|
||||
})
|
||||
}
|
||||
if (url.pathname === '/v1/github/dev-user-connect' && env.SANDBOX_ENV !== 'prod') {
|
||||
if (url.pathname === '/v1/github/dev-user-connect' && devOnly(env)) {
|
||||
// Dev-only, link-shareable start of a member's own GitHub identity (git as the sender) for
|
||||
// dev:org:<org> member <sub>; desktop builds call POST /v1/github/user/connect instead.
|
||||
const connect = githubConnect(env, deps)
|
||||
@@ -2435,7 +2441,8 @@ async function workspaceRoute(request: Request, url: URL, env: Env, deps: Deps,
|
||||
const route = `${request.method} ${action ?? ''}${grantId ? ' :grant' : ''}`
|
||||
const view = async (r = row) => (await workspaceViews(db, caller, [r], clock(), githubActingOptions(env)))[0]
|
||||
if (route === 'GET ') {
|
||||
return json({ workspace: await view() })
|
||||
// TEAM-SHARING hold: the capability rides on the single-workspace answer too (panels and link opens read it).
|
||||
return json({ workspace: await view(), teamSharing: teamSharingEnabled() })
|
||||
}
|
||||
if (route === 'GET read-snapshot') {
|
||||
try {
|
||||
@@ -2799,11 +2806,15 @@ function errorResponse(error: unknown): Response {
|
||||
return fail('internal_error', 500)
|
||||
}
|
||||
|
||||
/** TEAM-SHARING hold: whether this isolate has run the held-grants sweep yet (a value, never a promise). */
|
||||
let heldSweepRan = false
|
||||
|
||||
export default {
|
||||
fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
|
||||
return handleRequest(request, env, { waitUntil: (work) => ctx.waitUntil(work.catch(() => undefined)) })
|
||||
},
|
||||
async scheduled(controller: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
|
||||
configureTeamSharing(env)
|
||||
// Every minute: routines (schedule slots, run polling). Every fifth minute: everything else.
|
||||
ctx.waitUntil(
|
||||
lifecycleDeps(env, {}).then(async (life) => {
|
||||
@@ -2834,6 +2845,17 @@ export default {
|
||||
)
|
||||
const fifthMinute = new Date(controller.scheduledTime).getUTCMinutes() % 5 === 0
|
||||
ctx.waitUntil(credentialTick(env, fifthMinute))
|
||||
// TEAM-SHARING hold: every fifth minute, and on an isolate's first run (so right after a deploy).
|
||||
if (!teamSharingEnabled() && (fifthMinute || !heldSweepRan)) {
|
||||
heldSweepRan = true
|
||||
ctx.waitUntil(
|
||||
lifecycleDeps(env, {}).then(async (life) => {
|
||||
const swept = life ? await sweepHeldTeamGrants(life).catch(() => null) : null
|
||||
// Counts only.
|
||||
console.log(JSON.stringify({ event: 'team_sharing_held_sweep', ...(swept ?? { failed: true }) }))
|
||||
})
|
||||
)
|
||||
}
|
||||
if (env.AGENT_ACCOUNTS_CODEX === 'on') {
|
||||
ctx.waitUntil(codexTick(env, fifthMinute))
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// Sandbox lifecycle: one persistent provider sandbox per Orca workspace, with an Orca-owned lease,
|
||||
// a forced stop before the provider's 24h cap, usage metering and write-ahead rows.
|
||||
import { teamSharingEnabled } from './team-sharing'
|
||||
import { accountProvider } from './account-providers'
|
||||
import { readUsableAgentCredential } from './agent-credentials'
|
||||
import { CODEX_FIREWALL_ALL_PATHS, CODEX_FIREWALL_PATHS } from './codex-paths'
|
||||
@@ -7,7 +8,7 @@ import { codexPlaceholder } from './codex-credentials'
|
||||
/** Where Codex refreshes its ChatGPT login. */
|
||||
export const CODEX_AUTH_HOST = 'auth.openai.com'
|
||||
import { parseStoredCodex } from './codex-credentials'
|
||||
import { isSharedWorkspace } from './shared-workspace'
|
||||
import { sharedWorkspaceMode } from './shared-workspace'
|
||||
import { deleteAgentSourcesForSandbox } from './agent-sources'
|
||||
import { signOutAgentsBeforeDelete } from './agent-signout'
|
||||
import type { EntitlementClient, MachineSize } from './entitlements'
|
||||
@@ -25,7 +26,7 @@ import { applyQueuedRevokes } from './grant-revokes'
|
||||
import { ENTRY_POINTS_PROBE, ensureEntryPoints, entryPointsBehind, installEntryPoints, parseEntryPointsProbe } from './golden-images'
|
||||
import { RUNTIME_REFRESH_SCRIPT, type RuntimeBundle } from './runtime-bundles'
|
||||
import { memberPlaceholder, type MemberGitIdentity } from './github-user-tokens'
|
||||
import { connectedMembers, memberCoauthors, memberGitConfigs } from './member-git'
|
||||
import { connectedMembers, memberCoauthors, memberGitConfigs, soloMember } from './member-git'
|
||||
import type { RetentionConfig } from './retention'
|
||||
import { ProviderError, type ProviderSandboxState, type SandboxProviderApi } from './sandbox-provider'
|
||||
import { egressAccountRoutes, egressSecretHosts, placeholderValues, secretPlaceholder, type SecretEgressHost } from './secret-egress'
|
||||
@@ -428,11 +429,12 @@ export async function firewallInputsFor(deps: LifecycleDeps, row: SandboxRow): P
|
||||
}
|
||||
const keyring = deps.secrets.keyring
|
||||
const accounts: FirewallAccount[] = []
|
||||
const shared = await sharedWorkspaceMode(deps.db, row)
|
||||
for (const route of egressAccountRoutes(row)) {
|
||||
if (!classes.has(route.agent)) {
|
||||
continue
|
||||
}
|
||||
const applies = route.owner === row.user_id && !isSharedWorkspace(row) && Boolean(deps.secrets.accountProviders?.[route.agent])
|
||||
const applies = route.owner === row.user_id && !shared && Boolean(deps.secrets.accountProviders?.[route.agent])
|
||||
const stored = applies ? await readUsableAgentCredential(deps.db, keyring, row.user_id, route.agent, deps.now()).catch(() => null) : null
|
||||
if (route.agent === 'codex') {
|
||||
const tokens = stored ? parseStoredCodex(stored) : null
|
||||
@@ -1245,23 +1247,41 @@ export async function syncMemberGit(deps: LifecycleDeps, row: SandboxRow, sessio
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* GH-SOLO: before another person's device is paired, the VM stops treating the workspace as one person's
|
||||
* (orca-git-identity would otherwise act as the owner for that device's agents too). The members sync after
|
||||
* the grant writes it back if it still holds.
|
||||
*/
|
||||
export const DROP_SOLO_SCRIPT = 'rm -f /etc/orca/members/solo'
|
||||
|
||||
/** Throws when the VM did not take the identities; on success the VM's setup reads ready. */
|
||||
async function installMemberGit(deps: LifecycleDeps, row: SandboxRow, sessionId: string): Promise<number> {
|
||||
await ensureEntryPoints(deps, sessionId)
|
||||
await refreshGitCredentials(deps, row, sessionId)
|
||||
const configs = await memberGitConfigs({ db: deps.db, identity: deps.memberIdentity! }, row)
|
||||
const coauthors = await memberCoauthors(deps.db, row, new Set(configs.map((config) => config.userId)))
|
||||
// GH-SOLO: the only person who can use the workspace acts as themselves in the VM with no attested sender
|
||||
// (a TUI typed into directly has none), as the egress proxy already allows (memberMayAct).
|
||||
const solo = await soloMember(deps.db, row)
|
||||
const encode = (value: unknown) => btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(value))))
|
||||
const result = await deps.provider.runCommand(sessionId, {
|
||||
command: MEMBERS_COMMAND,
|
||||
// GIT-COAUTHOR: a separate variable, which an image's older members script simply ignores.
|
||||
env: { ORCA_MEMBERS_B64: encode(configs), ORCA_COAUTHORS_B64: encode(coauthors) },
|
||||
env: { ORCA_MEMBERS_B64: encode(configs), ORCA_COAUTHORS_B64: encode(coauthors), ...(solo ? { ORCA_SOLO_MEMBER: solo } : {}) },
|
||||
sudo: true,
|
||||
timeoutMs: 30_000
|
||||
})
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`members_exit_${result.exitCode}`)
|
||||
}
|
||||
// GH-SOLO: a grant may have started between the read above and the VM write (it drops the mark first, and
|
||||
// this write could have put it back). Re-check now; if it no longer holds, drop it, failing closed.
|
||||
if (solo && (await soloMember(deps.db, row)) !== solo) {
|
||||
const dropped = await deps.provider.runCommand(sessionId, { command: 'bash', args: ['-c', DROP_SOLO_SCRIPT], sudo: true, timeoutMs: 15_000 })
|
||||
if (dropped.exitCode !== 0) {
|
||||
throw new Error(`drop_solo_exit_${dropped.exitCode}`)
|
||||
}
|
||||
}
|
||||
if (row.git_setup_failed_at) {
|
||||
await deps.db.prepare('UPDATE sandboxes SET git_setup_failed_at = NULL WHERE id = ?').bind(row.id).run()
|
||||
}
|
||||
@@ -1438,8 +1458,9 @@ export async function createSandbox(
|
||||
source_snapshot_id: bootSnapshotId,
|
||||
repo_branch: request.repo?.ref ?? null,
|
||||
name: request.title ?? null,
|
||||
// A personal account has no team: its workspaces are always private.
|
||||
visibility: request.visibility === 'team' && caller.accountId.includes('org:') ? 'team' : 'private',
|
||||
// A personal account has no team: its workspaces are always private. So is every one while team sharing
|
||||
// is held (team-sharing.ts).
|
||||
visibility: request.visibility === 'team' && caller.accountId.includes('org:') && teamSharingEnabled() ? 'team' : 'private',
|
||||
section: request.section ?? null,
|
||||
ownership_transferred_at: request.ownershipTransferredAt ?? null
|
||||
},
|
||||
|
||||
@@ -82,6 +82,30 @@ export async function actingMember(db: D1Database, row: SandboxRow, now: number,
|
||||
return pickActing(row, grantees, latest, now, sharedMaxMs)
|
||||
}
|
||||
|
||||
/**
|
||||
* GH-SOLO: the one person who can use this workspace, or null. From the people set itself (active grantees, plus
|
||||
* the untransferred owner, who may have no grant row: the create's own pairing code), never from "no expiry".
|
||||
* Someone else's grant still being issued or revoked (their device may be pairing, or not yet unpaired) means not
|
||||
* solo.
|
||||
*/
|
||||
export async function soloMember(db: D1Database, row: SandboxRow): Promise<string | null> {
|
||||
const { results } = await db
|
||||
.prepare(`SELECT DISTINCT user_id, status FROM workspace_grants WHERE sandbox_id = ? AND status IN ('issuing', 'active', 'revoking')`)
|
||||
.bind(row.id)
|
||||
.all<{ user_id: string; status: string }>()
|
||||
const pick = pickActing(
|
||||
row,
|
||||
results.filter((r) => r.status === 'active').map((r) => r.user_id),
|
||||
null,
|
||||
0,
|
||||
null
|
||||
)
|
||||
if (!('userId' in pick)) {
|
||||
return null
|
||||
}
|
||||
return results.some((r) => r.user_id !== pick.userId) ? null : pick.userId
|
||||
}
|
||||
|
||||
export type ActingMember = { userId: string; until: number | null } | { none: 'no_send' | 'stale' }
|
||||
|
||||
/** The rule itself, on already-read rows (the workspace list reads them for every row in one go). */
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// the control plane at runtime chooses the recipient keys and drives the VM, so it is trusted not to
|
||||
// add its own key (same as relaying grant keys). Access mirrors canOpen at read time, and pruning
|
||||
// (removal, private, revoke) deletes wrapped keys at once, without the VM.
|
||||
import { effectiveVisibility } from './team-sharing'
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import { ensureEntryPoints } from './golden-images'
|
||||
@@ -202,7 +203,7 @@ export async function readerKeysFor(db: D1Database, row: SandboxRow, now: number
|
||||
if (row.archived_at !== null) {
|
||||
return []
|
||||
}
|
||||
const team = row.visibility === 'team'
|
||||
const team = effectiveVisibility(row) === 'team'
|
||||
const { results } = await db
|
||||
.prepare(
|
||||
`SELECT k.id, k.public_key FROM reader_keys k
|
||||
@@ -340,7 +341,7 @@ export async function captureReadSnapshot(deps: LifecycleDeps, row: SandboxRow,
|
||||
await deps.db.batch(statements)
|
||||
// The workspace may have been made private while sealing: re-apply the current rule.
|
||||
const current = await deps.db.prepare('SELECT * FROM sandboxes WHERE id = ?').bind(row.id).first<SandboxRow>()
|
||||
if (current && current.visibility !== 'team') {
|
||||
if (current && effectiveVisibility(current) !== 'team') {
|
||||
await pruneReadSnapshotToOwner(deps.db, current)
|
||||
}
|
||||
return done({
|
||||
@@ -387,7 +388,7 @@ export async function readSnapshotTimes(db: D1Database, ids: readonly string[]):
|
||||
|
||||
export async function getReadSnapshot(db: D1Database, caller: SandboxCaller, row: SandboxRow, keyId: string | null, now: number) {
|
||||
// Belt and braces over canOpen: a private workspace's snapshot opens only for its owner.
|
||||
if (!canOpen(caller, row) || (row.visibility !== 'team' && !isOwner(caller, row))) {
|
||||
if (!canOpen(caller, row) || (effectiveVisibility(row) !== 'team' && !isOwner(caller, row))) {
|
||||
throw new WorkspaceError('not_found')
|
||||
}
|
||||
if (!keyId || !KEY_ID.test(keyId)) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { createKeyring, type Keyring, type SealFormat, type SecretBinding } from
|
||||
import { createKekUnwrapper, SecretsKmsError } from './secrets-kms'
|
||||
import { AUTH_IAT_BACKDATE_MS } from './member-changes'
|
||||
import { BASE_URL_NAMES, baseUrlHost } from './provider-env'
|
||||
import { isSharedWorkspace } from './shared-workspace'
|
||||
import { isSharedWorkspace, sharedWorkspaceMode } from './shared-workspace'
|
||||
import type { SandboxRow } from './store'
|
||||
import { secretLog } from './secret-log'
|
||||
import {
|
||||
@@ -196,12 +196,15 @@ function repoOwner(accountId: string, repo: string): string {
|
||||
* never its owner's personal ones, the same rule as personal accounts (D13). Fails closed: only a row
|
||||
* known to be private counts as unshared.
|
||||
*/
|
||||
export function ownersForSandbox(row: Pick<SandboxRow, 'account_id' | 'user_id' | 'repo_url' | 'visibility' | 'ownership_transferred_at'>) {
|
||||
export function ownersForSandbox(
|
||||
row: Pick<SandboxRow, 'account_id' | 'user_id' | 'repo_url' | 'visibility' | 'ownership_transferred_at'>,
|
||||
shared: boolean = isSharedWorkspace(row)
|
||||
) {
|
||||
const repo = normalizeRepo(row.repo_url)
|
||||
return {
|
||||
org: ORG_ACCOUNT.test(row.account_id) ? row.account_id : null,
|
||||
// The one definition of "shared" (visibility, or ever transferred to another owner).
|
||||
personal: isSharedWorkspace(row) ? null : personalOwner(row.user_id, row.account_id.startsWith('dev:')),
|
||||
personal: shared ? null : personalOwner(row.user_id, row.account_id.startsWith('dev:')),
|
||||
repo: repo ? repoOwner(row.account_id, repo) : null
|
||||
}
|
||||
}
|
||||
@@ -362,7 +365,7 @@ export async function resolveSandboxSecrets(
|
||||
keyring: Keyring,
|
||||
row: Pick<SandboxRow, 'id' | 'account_id' | 'user_id' | 'repo_url' | 'visibility' | 'ownership_transferred_at'>
|
||||
): Promise<ResolvedSecrets> {
|
||||
const owners = ownersForSandbox(row)
|
||||
const owners = ownersForSandbox(row, await sharedWorkspaceMode(db, row))
|
||||
const pairs: [SecretScope, string][] = []
|
||||
if (owners.personal) {
|
||||
pairs.push(['personal', owners.personal])
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// DELETE /v1/sandboxes/:id/shares/:shareId -> {share}
|
||||
// POST /v1/shares/:token/visit -> {url} (team-only: a one-time sign-in URL for this viewer)
|
||||
// The public side is src/share-gateway.ts.
|
||||
import { devOnly } from './dev-only'
|
||||
import { auditSession } from './api/audit'
|
||||
import { z } from 'zod'
|
||||
import type { SandboxCaller } from './auth'
|
||||
@@ -77,7 +78,7 @@ export function shareSecrets(env: Env): string[] | null {
|
||||
* from SHARE_HOST_SUFFIX (a separate registrable domain).
|
||||
*/
|
||||
export function sharePathMode(env: Env): boolean {
|
||||
return env.SHARE_PATH_MODE === 'on' || (env.SHARE_PATH_MODE !== 'off' && env.SANDBOX_ENV !== 'prod')
|
||||
return env.SHARE_PATH_MODE === 'on' || (env.SHARE_PATH_MODE !== 'off' && devOnly(env))
|
||||
}
|
||||
|
||||
export function shareState(link: ShareLinkRow, now: number): ShareState {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// What counts as a shared workspace when deciding whose credentials a session may carry. One
|
||||
// definition, used by secrets, agent accounts, the egress proxy and the member git rules.
|
||||
import type { SandboxRow } from './store'
|
||||
import { teamSharingEnabled } from './team-sharing'
|
||||
|
||||
/**
|
||||
* D13: a workspace shared with teammates never uses a personal account. Fails closed: only a row
|
||||
@@ -12,3 +13,43 @@ import type { SandboxRow } from './store'
|
||||
export function isSharedWorkspace(row: Pick<SandboxRow, 'visibility' | 'ownership_transferred_at'>): boolean {
|
||||
return row.visibility !== 'private' || row.ownership_transferred_at != null
|
||||
}
|
||||
|
||||
/**
|
||||
* The rule above, precisely, for callers that can read the database (all of them today). TEAM-SHARING hold: a
|
||||
* workspace stored as `team` acts private while sharing is held, but keeps shared mode until no one but its
|
||||
* owner holds a device grant on it (the hold's sweep revokes them, grants.ts sweepHeldTeamGrants), and none was
|
||||
* revoked during the current session (what a teammate started there may still run): personal credentials never
|
||||
* reach a VM a teammate may still be paired to or running in. Fails closed on a failed read.
|
||||
*/
|
||||
export async function sharedWorkspaceMode(
|
||||
db: D1Database,
|
||||
row: Pick<SandboxRow, 'id' | 'user_id' | 'visibility' | 'ownership_transferred_at'>
|
||||
): Promise<boolean> {
|
||||
if (row.ownership_transferred_at != null) {
|
||||
return true
|
||||
}
|
||||
if (row.visibility !== 'private' && (teamSharingEnabled() || row.visibility !== 'team')) {
|
||||
return true
|
||||
}
|
||||
// Private, or `team` while held: shared only while a teammate's grant is live or was revoked this session
|
||||
// (Make private and the hold's sweep alike).
|
||||
// Review M1: a revoke closes a teammate's connections, not what they left running in this session's
|
||||
// terminals. A grant revoked during the current session keeps it shared until the next boot.
|
||||
// The session start is read here, not from the caller's row (which may be a partial or older copy). A revoke
|
||||
// queued while the workspace slept (no session) counts for nothing: the next boot applies it before orcad
|
||||
// accepts a sign-in, and that boot's processes are all new, so its session can be private. Its revoked_at
|
||||
// is when it was queued (revokeGrants; markRevoked keeps it), so it never reads as "revoked this session".
|
||||
// Unknown (null) falls back to the apply time there.
|
||||
const others = await db
|
||||
.prepare(
|
||||
`SELECT COUNT(*) AS n FROM workspace_grants g JOIN sandboxes s ON s.id = g.sandbox_id WHERE g.sandbox_id = ? AND g.user_id <> ?
|
||||
AND (g.status IN ('issuing', 'active')
|
||||
OR (g.status = 'revoking' AND s.session_started_at IS NOT NULL)
|
||||
OR (s.session_started_at IS NOT NULL AND g.revoked_at IS NOT NULL AND g.revoked_at >= s.session_started_at))`
|
||||
)
|
||||
.bind(row.id, row.user_id)
|
||||
.first<{ n: number }>()
|
||||
.catch(() => null)
|
||||
return !others || others.n > 0
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// TEAM-SHARING hold: team workspace sharing ships in a later release. TEAM_SHARING=on turns it on; anything else
|
||||
// (the default) holds it. While held, a workspace stored as `team` acts private everywhere access is decided
|
||||
// (owner only, plus org admins' metadata as before): the column and its data stay, so turning it on restores
|
||||
// each workspace's own setting. Set from the Worker's env at the start of every request and scheduled run (the
|
||||
// same value for the whole isolate: no per-request state).
|
||||
import type { SandboxRow } from './store'
|
||||
|
||||
let enabled = false
|
||||
|
||||
export function configureTeamSharing(env: { TEAM_SHARING?: string }): void {
|
||||
enabled = env.TEAM_SHARING === 'on'
|
||||
}
|
||||
|
||||
export function teamSharingEnabled(): boolean {
|
||||
return enabled
|
||||
}
|
||||
|
||||
/** The visibility access rules use: the stored one with sharing on, else always private. */
|
||||
export function effectiveVisibility(row: Pick<SandboxRow, 'visibility'>): 'private' | 'team' {
|
||||
return enabled && row.visibility === 'team' ? 'team' : 'private'
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
// visible to the whole team). A private workspace's only viewer is its owner, so a teammate's old
|
||||
// follow of a workspace that turned private is never shown and never counts. Archived workspaces
|
||||
// may still be followed: they stay browsable.
|
||||
import { effectiveVisibility } from './team-sharing'
|
||||
import type { SandboxCaller } from './auth'
|
||||
import type { SandboxRow } from './store'
|
||||
|
||||
@@ -42,7 +43,7 @@ export function visibleFollowers(
|
||||
if (!seen) {
|
||||
return []
|
||||
}
|
||||
return row.visibility === 'team' ? [...followers] : followers.filter((id) => id === row.user_id)
|
||||
return effectiveVisibility(row) === 'team' ? [...followers] : followers.filter((id) => id === row.user_id)
|
||||
}
|
||||
|
||||
/** The caller must be able to see the row (the route checks canSee first). */
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
// Access rule: a workspace is visible to its owner, and to every member of the owning org when
|
||||
// visibility is `team`. Org owners/admins additionally see private rows' metadata (scope=all) so a
|
||||
// departed member's workspaces can be reassigned or archived — metadata only, never access.
|
||||
import { effectiveVisibility, teamSharingEnabled } from './team-sharing'
|
||||
import { githubActingViews, type GithubActingOptions, type GithubActingView } from './git-actor'
|
||||
import type { TeamMembershipCheck } from './team-membership'
|
||||
import { z } from 'zod'
|
||||
@@ -63,7 +64,7 @@ export function canSee(caller: SandboxCaller, row: SandboxRow): boolean {
|
||||
if (row.account_id !== caller.accountId || row.status === 'destroyed') {
|
||||
return false
|
||||
}
|
||||
return row.user_id === caller.userId || (row.visibility === 'team' && caller.orgId !== undefined)
|
||||
return row.user_id === caller.userId || (effectiveVisibility(row) === 'team' && caller.orgId !== undefined)
|
||||
}
|
||||
|
||||
/** Can the caller pair a device with it (grant) or keep it awake (lease)? */
|
||||
@@ -231,7 +232,8 @@ export async function workspaceViews(
|
||||
// The link to copy: org slug + number when both exist, else the sandbox id form.
|
||||
link: workspaceLink(row, slug),
|
||||
repo: repoView(row),
|
||||
visibility: row.visibility,
|
||||
// TEAM-SHARING hold: what access actually follows (stored `team` reads private while held).
|
||||
visibility: effectiveVisibility(row),
|
||||
section: row.section,
|
||||
archivedAt: row.archived_at,
|
||||
createdBy: row.created_by ?? row.user_id,
|
||||
@@ -315,6 +317,8 @@ export async function listWorkspaces(db: D1Database, caller: SandboxCaller, url:
|
||||
])
|
||||
return {
|
||||
workspaces: views.map((view, i) => ({ ...view, routineName: routineNames.get(rows[i]!.id) ?? null })),
|
||||
// TEAM-SHARING hold: whether workspaces can be shared with the team on this control plane (older ones omit it).
|
||||
teamSharing: teamSharingEnabled(),
|
||||
// Home: offer the Routine runs switch only when the team has routines, and say what it hides
|
||||
// (its count and hours still belong in the team's totals).
|
||||
routineRuns: {
|
||||
@@ -393,6 +397,10 @@ export async function patchWorkspace(
|
||||
if (patch.archived === true) {
|
||||
throw new WorkspaceError('invalid_request', 'archive_via_lifecycle')
|
||||
}
|
||||
if (patch.visibility === 'team' && !teamSharingEnabled()) {
|
||||
// TEAM-SHARING hold (team-sharing.ts): sharing with the team isn't available yet.
|
||||
throw new WorkspaceError('invalid_request', 'team_sharing_unavailable')
|
||||
}
|
||||
if (patch.visibility === 'team' && !row.account_id.includes('org:')) {
|
||||
// A personal account has no team to share with.
|
||||
throw new WorkspaceError('invalid_request', 'personal_account')
|
||||
|
||||
@@ -42,12 +42,12 @@ describe('SANDBOX_DEV_BILLING_ENFORCE_PREFIX', () => {
|
||||
expect(devBillingEnforcePrefix({ SANDBOX_ENV: 'dev', SANDBOX_DEV_BILLING_ENFORCE_PREFIX: 'dev:billing-test-' })).toBe('dev:billing-test-')
|
||||
})
|
||||
|
||||
it('outside dev, dev accounts keep the plain bypass even with the prefix set (prod sends everything to billing anyway)', async () => {
|
||||
it('outside dev/local/test (staging, prod) there is no dev-account bypass at all: everything goes to billing', async () => {
|
||||
const { client, seen } = billing()
|
||||
const staging = withDevAccountBypass({ SANDBOX_ENV: 'staging', SANDBOX_DEV_BILLING_ENFORCE_PREFIX: 'dev:billing-test-' } as Env, client)
|
||||
expect(await staging.checkStart(start('dev:billing-test-alice'))).toMatchObject({ allow: true })
|
||||
await staging.checkStart(start('dev:billing-test-alice'))
|
||||
const prod = withDevAccountBypass({ SANDBOX_ENV: 'prod', SANDBOX_DEV_BILLING_ENFORCE_PREFIX: 'dev:billing-test-' } as Env, client)
|
||||
expect(await prod.checkStart(start('user:bob'))).toMatchObject({ allow: false })
|
||||
expect(seen).toEqual(['user:bob'])
|
||||
expect(seen).toEqual(['dev:billing-test-alice', 'user:bob'])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// The dev GitHub seed route stores any installation token as a member's GitHub user token: it must not exist
|
||||
// outside dev/local/test, whatever else is configured.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { devOnly } from '../src/dev-only'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
const OP = 'o'.repeat(40)
|
||||
|
||||
describe('dev member-github seed route gate', () => {
|
||||
it('is an allowlist: only dev, local and test', () => {
|
||||
for (const env of ['dev', 'local', 'test']) {
|
||||
expect(devOnly({ SANDBOX_ENV: env })).toBe(true)
|
||||
}
|
||||
for (const env of ['prod', 'staging', '', 'Dev', 'production', 'dev ', undefined as unknown as string]) {
|
||||
expect(devOnly({ SANDBOX_ENV: env })).toBe(false)
|
||||
}
|
||||
})
|
||||
|
||||
it('answers 404 in staging and prod even with the operator token, and stores nothing', async () => {
|
||||
for (const SANDBOX_ENV of ['staging', 'prod']) {
|
||||
const h = await createHarness({ SANDBOX_ENV, OPERATOR_TOKEN: OP, SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') })
|
||||
const seeded = await h.call('POST', '/v1/internal/dev/member-github', {
|
||||
bearer: OP,
|
||||
body: { accountId: 'org:acme', userId: 'alice', repoUrl: 'https://github.com/acme/app', login: 'alice-gh', githubUserId: 11, name: 'A' }
|
||||
})
|
||||
expect(seeded.status).toBe(404)
|
||||
expect(h.raw.prepare('SELECT COUNT(*) AS n FROM github_user_tokens').get()).toEqual({ n: 0 })
|
||||
}
|
||||
})
|
||||
|
||||
it('the other dev-only routes are gone in staging too (seed, dev connect, codex login, manifest)', async () => {
|
||||
const h = await createHarness({ SANDBOX_ENV: 'staging', OPERATOR_TOKEN: OP })
|
||||
for (const [method, path] of [
|
||||
['POST', '/v1/internal/dev/codex-login'],
|
||||
['GET', '/v1/github/dev-connect'],
|
||||
['GET', '/v1/github/dev-user-connect'],
|
||||
['GET', '/v1/github/manifest-start']
|
||||
] as const) {
|
||||
expect((await h.call(method, path, { bearer: OP, body: method === 'POST' ? {} : undefined })).status, path).toBe(404)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -142,9 +142,9 @@ describe('EGRESS-SWAP-FAIL-CLOSED', () => {
|
||||
const missing = await setup({ SANDBOX_ENV: 'staging' })
|
||||
expect(await missing.h.call('GET', '/v1/health')).toEqual({ status: 503, body: { error: 'egress_proxy_missing', keySwap: 'off' } })
|
||||
const present = await setup({ SANDBOX_ENV: 'staging', EGRESS_PROXY_URL: 'https://sandbox.test/v1/egress/proxy' })
|
||||
expect(await present.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'on' } })
|
||||
expect(await present.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'on', environment: 'staging' } })
|
||||
const local = await setup({ SANDBOX_ENV: 'test' })
|
||||
expect(await local.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'off' } })
|
||||
expect(await local.h.call('GET', '/v1/health')).toEqual({ status: 200, body: { ok: true, keySwap: 'off', environment: 'test' } })
|
||||
})
|
||||
|
||||
it('a respond route compiles to a matched direct response, before the trailing deny', () => {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// In-memory Vercel Sandbox with the behaviours the bake-off measured: stop = reboot from an automatic
|
||||
// snapshot, resume keeps the name and route, and delete leaves automatic snapshots behind.
|
||||
import { DROP_SOLO_SCRIPT } from '../src/lifecycle'
|
||||
import { createCipheriv, createPublicKey, diffieHellman, generateKeyPairSync, hkdfSync, randomBytes } from 'node:crypto'
|
||||
import { GRANT_COMMAND } from '../src/grants'
|
||||
import { REVOKE_COMMAND } from '../src/grant-revokes'
|
||||
@@ -408,6 +409,10 @@ export function createFakeVercel(now: () => number): FakeVercel {
|
||||
}
|
||||
return { exitCode: 0, stdout: 'synced\n', stderr: '' }
|
||||
}
|
||||
// GH-SOLO: dropping the one-person mark before a grant (rm -f: always succeeds in a VM).
|
||||
if (script === DROP_SOLO_SCRIPT) {
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
}
|
||||
if (params.command === DRAIN_COMMAND) {
|
||||
return { exitCode: 0, stdout: '', stderr: '' }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,148 @@
|
||||
// GH-SOLO regression (orca-plugins#89): in a workspace only one person can use, the server acts as that person
|
||||
// (memberMayAct), but the VM picked a member only from an attested sender. Codex typed into directly in a
|
||||
// terminal has none, so gh and git went out as the bot. Now the VM acts as the solo member with no sender too.
|
||||
import { execFileSync, spawnSync } from 'node:child_process'
|
||||
import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { generateGrantRecipientKey } from '../../../../src/main/cloud-workspaces/sealed-grant-node'
|
||||
import { GRANT_COMMAND } from '../src/grants'
|
||||
import { DROP_SOLO_SCRIPT, MEMBERS_COMMAND } from '../src/lifecycle'
|
||||
import { soloMember } from '../src/member-git'
|
||||
import { getSandbox } from '../src/store'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
const IDENTITY = fileURLToPath(new URL('../image/vm/orca-git-identity', import.meta.url).href)
|
||||
const dirs: string[] = []
|
||||
afterEach(() => dirs.splice(0).forEach((dir) => rmSync(dir, { recursive: true, force: true })))
|
||||
|
||||
/** orca-git-identity as root would run it, against a scratch members dir, with no orcad (so no attested sender). */
|
||||
function identity(members: { solo?: string; files: Record<string, string> }, env: Record<string, string> = {}) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'orca-git-solo-'))
|
||||
dirs.push(root)
|
||||
const dir = join(root, 'members')
|
||||
mkdirSync(dir)
|
||||
mkdirSync(join(root, 'bin'))
|
||||
for (const [name, email] of Object.entries(members.files)) {
|
||||
execFileSync('git', ['config', '-f', join(dir, `${name}.gitconfig`), 'user.email', email])
|
||||
}
|
||||
if (members.solo) {
|
||||
writeFileSync(join(dir, 'solo'), `${members.solo}\n`)
|
||||
}
|
||||
// `sudo -u <caller> mktemp` and `pgrep` stand-ins: no orcad runs here.
|
||||
writeFileSync(join(root, 'bin/sudo'), '#!/usr/bin/env bash\nshift 2\nexec "$@"\n')
|
||||
writeFileSync(join(root, 'bin/pgrep'), '#!/usr/bin/env bash\nexit 1\n')
|
||||
chmodSync(join(root, 'bin/sudo'), 0o755)
|
||||
chmodSync(join(root, 'bin/pgrep'), 0o755)
|
||||
const script = join(root, 'orca-git-identity')
|
||||
writeFileSync(script, readFileSync(IDENTITY, 'utf8').replace('DIR=/etc/orca/members', `DIR=${dir}`))
|
||||
const run = spawnSync('bash', [script], { env: { PATH: `${join(root, 'bin')}:/usr/bin:/bin`, SUDO_USER: 'vercel-sandbox', ...env }, encoding: 'utf8' })
|
||||
const out = run.stdout.trim()
|
||||
return { status: run.status, stderr: run.stderr, email: run.status === 0 ? execFileSync('git', ['config', '-f', out, 'user.email'], { encoding: 'utf8' }).trim() : null }
|
||||
}
|
||||
|
||||
describe('orca-git-identity in a one-person workspace', () => {
|
||||
it('acts as the solo member with no attested sender (a TUI typed into directly)', () => {
|
||||
expect(identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } })).toMatchObject({ status: 0, email: '1+neil@users.noreply.github.com' })
|
||||
expect(identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } }, { ORCA_GIT_AS: 'user_neil' }).status).toBe(0)
|
||||
})
|
||||
|
||||
it('never for anyone else, and not at all once the workspace is shared (no solo mark)', () => {
|
||||
const other = identity({ solo: 'user_neil', files: { user_neil: '1+neil@users.noreply.github.com' } }, { ORCA_GIT_AS: 'user_bob' })
|
||||
expect(other.status).toBe(4)
|
||||
expect(identity({ files: { user_neil: '1+neil@users.noreply.github.com' } }).status).toBe(3)
|
||||
// A mark naming someone with no identity installed: the workspace identity.
|
||||
expect(identity({ solo: 'user_ghost', files: {} }).status).toBe(3)
|
||||
})
|
||||
})
|
||||
|
||||
const OP = 'o'.repeat(40)
|
||||
const REPO = 'https://github.com/acme/app'
|
||||
|
||||
async function workspace(extra: Record<string, string> = {}) {
|
||||
const h = await createHarness(
|
||||
{ EGRESS_PROXY_URL: 'https://sandbox.test/v1/egress/proxy', SECRETS_KEK: Buffer.alloc(32, 7).toString('base64'), OPERATOR_TOKEN: OP, ...extra },
|
||||
{
|
||||
credentials: { authorizationFor: async () => 'Bearer ghs_app' },
|
||||
github: { tokenForRepo: async () => ({ token: 'ghs_repo', expiresAt: h.now() + 3_600_000 }), installationForRepo: async () => null } as never
|
||||
}
|
||||
)
|
||||
const as = (sub: string) => h.token(sub, 'acme', 'sandbox', { org_role: 'member' })
|
||||
const created = await h.call('POST', '/v1/sandboxes', { bearer: await as('alice'), body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: REPO }, visibility: 'team' } })
|
||||
const id = created.body.sandbox.id as string
|
||||
const connect = (userId: string, githubUserId: number) =>
|
||||
h.call('POST', '/v1/internal/dev/member-github', { bearer: OP, body: { accountId: 'org:acme', userId, repoUrl: REPO, login: `${userId}-gh`, githubUserId, name: userId } })
|
||||
const grant = async (userId: string) =>
|
||||
h.call('POST', `/v1/team/workspaces/${id}/grants`, {
|
||||
bearer: await as(userId),
|
||||
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: userId, deviceKind: 'desktop' }
|
||||
})
|
||||
const syncs = () => h.vercel.commands.filter((c) => c.command === MEMBERS_COMMAND)
|
||||
const restart = async () => expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: await as('alice') })).status).toBe(200)
|
||||
return { h, as, id, connect, grant, syncs, restart }
|
||||
}
|
||||
|
||||
describe('the control plane marks a workspace solo only while one person can use it', () => {
|
||||
it('sends ORCA_SOLO_MEMBER for the owner alone; drops the mark before pairing anyone else, then sends none', async () => {
|
||||
const t = await workspace()
|
||||
await t.connect('alice', 11)
|
||||
await t.restart()
|
||||
expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBe('alice')
|
||||
const before = t.h.vercel.commands.length
|
||||
expect((await t.grant('bob')).status).toBe(200)
|
||||
const after = t.h.vercel.commands.slice(before)
|
||||
const drop = after.findIndex((c) => c.command === 'bash' && c.args?.includes(DROP_SOLO_SCRIPT))
|
||||
const pair = after.findIndex((c) => c.command === GRANT_COMMAND)
|
||||
expect(drop).toBeGreaterThanOrEqual(0)
|
||||
expect(drop).toBeLessThan(pair)
|
||||
expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBeUndefined()
|
||||
})
|
||||
|
||||
it('review HIGH: shared with the cap off, a grantee who sent last is never marked solo (the owner has no grant row)', async () => {
|
||||
const t = await workspace({ MEMBER_GIT_SHARED_MAX_MINUTES: '0' })
|
||||
await t.connect('alice', 11)
|
||||
await t.connect('bob', 22)
|
||||
expect((await t.grant('bob')).status).toBe(200)
|
||||
expect((await t.h.call('POST', `/v1/team/workspaces/${t.id}/sent`, { bearer: await t.as('bob') })).status).toBe(200)
|
||||
await t.restart()
|
||||
expect(t.syncs().at(-1)!.env.ORCA_SOLO_MEMBER).toBeUndefined()
|
||||
expect(await soloMember(t.h.env.SANDBOX_DB, (await getSandbox(t.h.env.SANDBOX_DB, t.id))!)).toBeNull()
|
||||
})
|
||||
|
||||
it('review medium: a grant that starts while the members write is in flight drops the mark again after it', async () => {
|
||||
const t = await workspace()
|
||||
await t.connect('alice', 11)
|
||||
// Bob's grant row appears (issuing) between the sync's read and its VM write.
|
||||
t.h.vercel.commandHandler = (params) => {
|
||||
if (params.command === MEMBERS_COMMAND) {
|
||||
t.h.raw
|
||||
.prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_race', ?, 'org:acme', 'bob', 'desktop', 'b', 'issuing', 1)`)
|
||||
.run(t.id)
|
||||
return { exitCode: 0, stdout: '{"members":1,"devices":0}\n', stderr: '' }
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
const before = t.h.vercel.commands.length
|
||||
await t.restart()
|
||||
const after = t.h.vercel.commands.slice(before)
|
||||
const write = after.findIndex((c) => c.command === MEMBERS_COMMAND && c.env.ORCA_SOLO_MEMBER === 'alice')
|
||||
const drop = after.findIndex((c, i) => i > write && c.command === 'bash' && c.args?.includes(DROP_SOLO_SCRIPT))
|
||||
expect(write).toBeGreaterThanOrEqual(0)
|
||||
expect(drop).toBeGreaterThan(write)
|
||||
})
|
||||
|
||||
it('a teammate whose grant is still being revoked (device not yet unpaired) keeps it from being solo', async () => {
|
||||
const t = await workspace()
|
||||
await t.connect('alice', 11)
|
||||
t.h.raw
|
||||
.prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_out', ?, 'org:acme', 'bob', 'desktop', 'b', 'revoking', 1)`)
|
||||
.run(t.id)
|
||||
const row = (await getSandbox(t.h.env.SANDBOX_DB, t.id))!
|
||||
expect(await soloMember(t.h.env.SANDBOX_DB, row)).toBeNull()
|
||||
t.h.raw.prepare(`UPDATE workspace_grants SET status = 'revoked' WHERE id = 'grt_out'`).run()
|
||||
expect(await soloMember(t.h.env.SANDBOX_DB, row)).toBe('alice')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -61,6 +61,8 @@ export async function createHarness(overrides: Partial<Env> = {}, extraDeps: Par
|
||||
VERCEL_PROJECT_ID: 'prj_orca',
|
||||
// Off unless a test turns it on (auto-environments.test.ts): it starts builds behind creates.
|
||||
AUTO_ENVIRONMENTS: 'off',
|
||||
// Team sharing is on for the suite (its behavior is what most team tests cover); test/team-sharing-hold.test.ts holds it.
|
||||
TEAM_SHARING: 'on',
|
||||
...overrides
|
||||
}
|
||||
// No live github.com from tests: repos count as public unless a test says otherwise.
|
||||
|
||||
@@ -240,7 +240,7 @@ describe('GIT-ACTOR: githubActing and you on the workspace view (list and detail
|
||||
}) as D1Database
|
||||
const row = (await getSandbox(db, t.id))!
|
||||
// Four rows of the same owner (ids differ): a list of any size.
|
||||
const results = [row, ...[1, 2, 3].map((n) => ({ ...row, id: `${row.id.slice(0, -1)}${n}` }))]
|
||||
const results = [row, ...[1, 2, 3].map((n) => ({ ...row, id: `${row.id}-copy${n}` }))]
|
||||
const options = { enabled: () => true, sharedMaxMs: 60 * 60_000 }
|
||||
const views = await githubActingViews(counting, results as never, 'alice', t.h.now(), options)
|
||||
expect([...views.values()].map((v) => v.githubActing)).toEqual(Array(4).fill({ actingAs: 'member', userId: 'alice', login: 'alice-gh' }))
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
// TEAM-SHARING hold (team-sharing.ts): with TEAM_SHARING off, nothing can be shared with the team, and a
|
||||
// workspace already stored as `team` acts private everywhere (owner only, plus org admins' metadata).
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { generateGrantRecipientKey } from '../../../../src/main/cloud-workspaces/sealed-grant-node'
|
||||
import { sweepHeldTeamGrants } from '../src/grants'
|
||||
import { lifecycleDeps } from '../src/index'
|
||||
import { resolveSandboxSecrets } from '../src/secrets'
|
||||
import { sharedWorkspaceMode } from '../src/shared-workspace'
|
||||
import { getSandbox } from '../src/store'
|
||||
import { configureTeamSharing } from '../src/team-sharing'
|
||||
import { createHarness } from './harness'
|
||||
|
||||
async function held(teamSharing: 'off' | undefined = 'off') {
|
||||
const h = await createHarness({ PUBLIC_API_URL: 'https://api.test', ...(teamSharing ? { TEAM_SHARING: teamSharing } : { TEAM_SHARING: undefined }) })
|
||||
const token = (sub: string, role: 'member' | 'admin' = 'member') => h.token(sub, 'acme', 'sandbox', { org_role: role })
|
||||
const created = await h.call('POST', '/v1/sandboxes', {
|
||||
bearer: await token('alice'),
|
||||
body: { workspaceId: 'ws-1', machineSize: 'standard', title: 'Fix login', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' }
|
||||
})
|
||||
expect(created.status).toBe(200)
|
||||
return { h, token, id: created.body.sandbox.id as string }
|
||||
}
|
||||
|
||||
describe('TEAM_SHARING held (the default)', () => {
|
||||
it('a create asking for team is private, a PATCH to team is refused, and the list says sharing is off', async () => {
|
||||
for (const setting of ['off', undefined] as const) {
|
||||
const t = await held(setting)
|
||||
expect(t.h.raw.prepare('SELECT visibility FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ visibility: 'private' })
|
||||
const patch = await t.h.call('PATCH', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice'), body: { visibility: 'team' } })
|
||||
expect(patch.status).toBe(400)
|
||||
expect(patch.body).toEqual({ error: 'invalid_request', reason: 'team_sharing_unavailable' })
|
||||
const list = await t.h.call('GET', '/v1/team/workspaces', { bearer: await t.token('alice') })
|
||||
expect(list.body.teamSharing).toBe(false)
|
||||
// Other edits still work, and making it private is always allowed.
|
||||
expect((await t.h.call('PATCH', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice'), body: { visibility: 'private', section: 'Auth' } })).status).toBe(200)
|
||||
}
|
||||
})
|
||||
|
||||
it('a workspace already stored as team acts private: owner only, admins see metadata, teammates nothing', async () => {
|
||||
const t = await held()
|
||||
t.h.raw.prepare("UPDATE sandboxes SET visibility = 'team' WHERE id = ?").run(t.id)
|
||||
const bob = await t.token('bob')
|
||||
// Team registry: not listed, not addressable, no grant, no follow.
|
||||
expect((await t.h.call('GET', '/v1/team/workspaces?scope=team', { bearer: bob })).body.workspaces).toEqual([])
|
||||
expect((await t.h.call('GET', `/v1/team/workspaces/${t.id}`, { bearer: bob })).status).toBe(404)
|
||||
const grant = await t.h.call('POST', `/v1/team/workspaces/${t.id}/grants`, {
|
||||
bearer: bob,
|
||||
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' }
|
||||
})
|
||||
expect(grant.status).toBe(404)
|
||||
expect((await t.h.call('PUT', `/v1/team/workspaces/${t.id}/follow`, { bearer: bob })).status).toBe(404)
|
||||
// Public API and MCP's rule (api/access.ts): nothing for a teammate.
|
||||
expect((await t.h.call('GET', '/v1/workspaces', { bearer: bob })).body.workspaces).toEqual([])
|
||||
expect((await t.h.call('GET', `/v1/workspaces/${t.id}`, { bearer: bob })).status).toBe(404)
|
||||
expect((await t.h.call('POST', `/v1/workspaces/${t.id}/messages`, { bearer: bob, body: { text: 'hi' } })).status).toBe(404)
|
||||
// The owner sees it as private (what access follows); the stored value is kept for when sharing ships.
|
||||
const own = await t.h.call('GET', `/v1/team/workspaces/${t.id}`, { bearer: await t.token('alice') })
|
||||
expect(own.body.workspace).toMatchObject({ visibility: 'private', access: 'owner' })
|
||||
expect(own.body.teamSharing).toBe(false)
|
||||
expect(t.h.raw.prepare('SELECT visibility FROM sandboxes WHERE id = ?').get(t.id)).toEqual({ visibility: 'team' })
|
||||
// An admin keeps today's management view (scope=all metadata), not the teammate view.
|
||||
const admin = await t.token('carol', 'admin')
|
||||
const all = await t.h.call('GET', '/v1/team/workspaces?scope=all', { bearer: admin })
|
||||
expect(all.body.workspaces.map((w: { id: string; visibility: string; access: string }) => [w.id, w.visibility, w.access])).toEqual([[t.id, 'private', 'none']])
|
||||
expect((await t.h.call('GET', '/v1/team/workspaces?scope=team', { bearer: admin })).body.workspaces).toEqual([])
|
||||
})
|
||||
|
||||
it('TEAM_SHARING=on restores each workspace’s own setting', async () => {
|
||||
const h = await createHarness()
|
||||
const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const created = await h.call('POST', '/v1/sandboxes', {
|
||||
bearer: alice,
|
||||
body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' }
|
||||
})
|
||||
const bob = await h.token('bob', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const list = await h.call('GET', '/v1/team/workspaces?scope=team', { bearer: bob })
|
||||
expect(list.body.teamSharing).toBe(true)
|
||||
expect(list.body.workspaces.map((w: { id: string; visibility: string }) => [w.id, w.visibility])).toEqual([[created.body.sandbox.id, 'team']])
|
||||
})
|
||||
|
||||
it('the sweep revokes teammates’ grants on a held team workspace; credentials stay shared until it has', async () => {
|
||||
// Shared while sharing was on: Bob holds a device grant.
|
||||
const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') })
|
||||
const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const created = await h.call('POST', '/v1/sandboxes', {
|
||||
bearer: alice,
|
||||
body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' }
|
||||
})
|
||||
const id = created.body.sandbox.id as string
|
||||
const grant = await h.call('POST', `/v1/team/workspaces/${id}/grants`, {
|
||||
bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }),
|
||||
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' }
|
||||
})
|
||||
expect(grant.status).toBe(200)
|
||||
// Now held.
|
||||
h.env.TEAM_SHARING = undefined
|
||||
configureTeamSharing(h.env)
|
||||
const db = h.env.SANDBOX_DB
|
||||
const row = (await getSandbox(db, id))!
|
||||
// Bob's grant is still active: shared mode (no personal credentials), though it acts private.
|
||||
expect(await sharedWorkspaceMode(db, row)).toBe(true)
|
||||
expect((await h.call('PUT', '/v1/secrets/personal/MY_TOKEN', { bearer: alice, body: { value: 'personal-value' } })).status).toBe(200)
|
||||
const life = (await lifecycleDeps(h.env, h.deps))!
|
||||
const keyring = await life.secrets!.keyring
|
||||
expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBeUndefined()
|
||||
expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 1, revoked: 1, queued: 0 })
|
||||
expect(h.raw.prepare('SELECT status, revoke_reason FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked', revoke_reason: 'team_sharing_held' })
|
||||
// Review M1: revoked during this session, so what Bob started may still run: shared until the next boot.
|
||||
expect(await sharedWorkspaceMode(db, row)).toBe(true)
|
||||
expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBeUndefined()
|
||||
// A new session (restart): the owner's alone, so it acts private for credentials too.
|
||||
h.advance(1_000)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: alice })).status).toBe(200)
|
||||
expect(await sharedWorkspaceMode(db, row)).toBe(false)
|
||||
expect((await resolveSandboxSecrets(db, keyring, row)).env.MY_TOKEN).toBe('personal-value')
|
||||
// Nothing left to sweep; and with sharing on again, nothing is swept at all.
|
||||
expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 0, revoked: 0, queued: 0 })
|
||||
configureTeamSharing({ TEAM_SHARING: 'on' })
|
||||
expect(await sharedWorkspaceMode(db, row)).toBe(true)
|
||||
})
|
||||
|
||||
it('review L1: the sweep leaves private workspaces alone', async () => {
|
||||
const t = await held()
|
||||
t.h.raw
|
||||
.prepare(`INSERT INTO workspace_grants (id, sandbox_id, account_id, user_id, device_kind, device_label, status, created_at) VALUES ('grt_p', ?, 'org:acme', 'bob', 'desktop', 'b', 'active', 1)`)
|
||||
.run(t.id)
|
||||
expect(await sweepHeldTeamGrants((await lifecycleDeps(t.h.env, t.h.deps))!)).toEqual({ workspaces: 0, revoked: 0, queued: 0 })
|
||||
})
|
||||
|
||||
it('review L2: concurrent sweeps revoke each grant once and agree on the end state', async () => {
|
||||
const h = await createHarness()
|
||||
const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const created = await h.call('POST', '/v1/sandboxes', {
|
||||
bearer: alice,
|
||||
body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' }
|
||||
})
|
||||
const id = created.body.sandbox.id as string
|
||||
for (const who of ['bob', 'dan']) {
|
||||
const g = await h.call('POST', `/v1/team/workspaces/${id}/grants`, {
|
||||
bearer: await h.token(who, 'acme', 'sandbox', { org_role: 'member' }),
|
||||
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: who, deviceKind: 'desktop' }
|
||||
})
|
||||
expect(g.status).toBe(200)
|
||||
}
|
||||
h.env.TEAM_SHARING = undefined
|
||||
configureTeamSharing(h.env)
|
||||
const life = (await lifecycleDeps(h.env, h.deps))!
|
||||
const [a, b] = await Promise.all([sweepHeldTeamGrants(life), sweepHeldTeamGrants(life)])
|
||||
expect(a.revoked + a.queued + b.revoked + b.queued).toBeGreaterThanOrEqual(2)
|
||||
expect(h.raw.prepare(`SELECT user_id, status, revoke_reason FROM workspace_grants WHERE user_id <> 'alice' ORDER BY user_id`).all()).toEqual([
|
||||
{ user_id: 'bob', status: 'revoked', revoke_reason: 'team_sharing_held' },
|
||||
{ user_id: 'dan', status: 'revoked', revoke_reason: 'team_sharing_held' }
|
||||
])
|
||||
expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 0, revoked: 0, queued: 0 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('Make private keeps shared credential mode until the next boot (same rule as the sweep)', () => {
|
||||
it('a teammate revoked by Make private leaves this session shared; a fresh boot is private', async () => {
|
||||
const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') })
|
||||
const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const created = await h.call('POST', '/v1/sandboxes', {
|
||||
bearer: alice,
|
||||
body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' }
|
||||
})
|
||||
const id = created.body.sandbox.id as string
|
||||
const g = await h.call('POST', `/v1/team/workspaces/${id}/grants`, {
|
||||
bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }),
|
||||
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' }
|
||||
})
|
||||
expect(g.status).toBe(200)
|
||||
expect((await h.call('PATCH', `/v1/team/workspaces/${id}`, { bearer: alice, body: { visibility: 'private' } })).status).toBe(200)
|
||||
const db = h.env.SANDBOX_DB
|
||||
expect(h.raw.prepare('SELECT status FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked' })
|
||||
const row = (await getSandbox(db, id))!
|
||||
expect(row.visibility).toBe('private')
|
||||
expect(await sharedWorkspaceMode(db, row)).toBe(true)
|
||||
h.advance(1_000)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${id}/restart`, { bearer: alice })).status).toBe(200)
|
||||
expect(await sharedWorkspaceMode(db, (await getSandbox(db, id))!)).toBe(false)
|
||||
})
|
||||
|
||||
it('a revoke queued while the workspace slept leaves its next session private (no lost sign-in after the deploy sweep)', async () => {
|
||||
const h = await createHarness({ SECRETS_KEK: Buffer.alloc(32, 7).toString('base64') })
|
||||
const alice = await h.token('alice', 'acme', 'sandbox', { org_role: 'member' })
|
||||
const created = await h.call('POST', '/v1/sandboxes', {
|
||||
bearer: alice,
|
||||
body: { workspaceId: 'ws-1', machineSize: 'standard', repo: { url: 'https://github.com/acme/app' }, visibility: 'team' }
|
||||
})
|
||||
const id = created.body.sandbox.id as string
|
||||
const g = await h.call('POST', `/v1/team/workspaces/${id}/grants`, {
|
||||
bearer: await h.token('bob', 'acme', 'sandbox', { org_role: 'member' }),
|
||||
body: { recipientPublicKeyB64: generateGrantRecipientKey().publicKeyB64, deviceLabel: 'b', deviceKind: 'desktop' }
|
||||
})
|
||||
expect(g.status).toBe(200)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${id}/suspend`, { bearer: alice })).status).toBe(200)
|
||||
h.env.TEAM_SHARING = undefined
|
||||
configureTeamSharing(h.env)
|
||||
const life = (await lifecycleDeps(h.env, h.deps))!
|
||||
// Asleep: queued, not applied.
|
||||
expect(await sweepHeldTeamGrants(life)).toEqual({ workspaces: 1, revoked: 0, queued: 1 })
|
||||
const db = h.env.SANDBOX_DB
|
||||
const queuedAt = (h.raw.prepare('SELECT revoked_at FROM workspace_grants WHERE user_id = ?').get('bob') as { revoked_at: number }).revoked_at
|
||||
expect(await sharedWorkspaceMode(db, (await getSandbox(db, id))!)).toBe(false)
|
||||
h.advance(60_000)
|
||||
expect((await h.call('POST', `/v1/sandboxes/${id}/resume`, { bearer: alice })).status).toBe(200)
|
||||
// Applied at boot, still stamped with the queue time; the new session is private.
|
||||
expect(h.raw.prepare('SELECT status, revoked_at FROM workspace_grants WHERE user_id = ?').get('bob')).toEqual({ status: 'revoked', revoked_at: queuedAt })
|
||||
expect(await sharedWorkspaceMode(db, (await getSandbox(db, id))!)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
},
|
||||
"triggers": { "crons": ["*/5 * * * *"] },
|
||||
"vars": {
|
||||
"SANDBOX_ENV": "local",
|
||||
// No SANDBOX_ENV here: a config copied from this one that forgets to set it leaves every dev-only route and
|
||||
// behavior off (dev-only.ts). `pnpm dev` passes SANDBOX_ENV=local itself.
|
||||
"SANDBOX_JWT_AUDIENCE": "orca-sandbox",
|
||||
"VERCEL_REGION": "pdx1",
|
||||
"VERCEL_FALLBACK_REGIONS": "iad1",
|
||||
|
||||
@@ -6,8 +6,6 @@ import type { SyncCall } from './cloud-sync-remote'
|
||||
const ParamsSchema = z.looseObject({
|
||||
relativePath: z.string().optional(),
|
||||
relativePaths: z.array(z.string()).optional(),
|
||||
candidatePaths: z.array(z.string()).optional(),
|
||||
includeIgnored: z.boolean().optional(),
|
||||
offset: z.number().optional(),
|
||||
length: z.number().optional()
|
||||
})
|
||||
@@ -17,7 +15,6 @@ export const VM_ROOT = '/vercel/sandbox/project'
|
||||
|
||||
export type FakeVm = {
|
||||
files: Map<string, { content: Buffer; mtime: number }>
|
||||
ignored: Set<string>
|
||||
calls: string[]
|
||||
statManySupported: boolean
|
||||
asleep: boolean
|
||||
@@ -36,13 +33,11 @@ function codeError(code: string, message = code): Error {
|
||||
|
||||
export function createFakeVm(): FakeVm {
|
||||
const files = new Map<string, { content: Buffer; mtime: number }>()
|
||||
const ignored = new Set<string>()
|
||||
const calls: string[] = []
|
||||
const watches = new Set<(event: unknown) => void>()
|
||||
let clock = 1_000
|
||||
const vm: FakeVm = {
|
||||
files,
|
||||
ignored,
|
||||
calls,
|
||||
statManySupported: true,
|
||||
asleep: false,
|
||||
@@ -92,16 +87,6 @@ export function createFakeVm(): FakeVm {
|
||||
}
|
||||
return [...names].map(([name, isDirectory]) => ({ name, isDirectory, isSymlink: false }))
|
||||
}
|
||||
case 'files.listAll': {
|
||||
const candidates = p.candidatePaths
|
||||
return [...files.keys()].filter(
|
||||
(path) =>
|
||||
// Like orcad: gitignored files are listed unless includeIgnored is false.
|
||||
(p.includeIgnored !== false || !ignored.has(path)) &&
|
||||
!path.startsWith('.context/') &&
|
||||
(!candidates || candidates.includes(path))
|
||||
)
|
||||
}
|
||||
case 'files.statMany': {
|
||||
if (!vm.statManySupported) {
|
||||
throw codeError('method_not_found', 'Unknown method: files.statMany')
|
||||
|
||||
@@ -125,18 +125,15 @@ export function installCloudSync(
|
||||
ipcMain.handle(CH.getState, (_event, workspaceId: unknown) =>
|
||||
typeof workspaceId === 'string' ? sync.getState(workspaceId) : null
|
||||
)
|
||||
ipcMain.handle(
|
||||
CH.setChoice,
|
||||
(_event, args: { workspaceId?: unknown; context?: unknown; mirror?: unknown }) => {
|
||||
if (typeof args?.workspaceId !== 'string') {
|
||||
return null
|
||||
}
|
||||
return sync.setChoice(args.workspaceId, {
|
||||
...(typeof args.context === 'boolean' ? { context: args.context } : {}),
|
||||
...(typeof args.mirror === 'boolean' ? { mirror: args.mirror } : {})
|
||||
})
|
||||
ipcMain.handle(CH.setChoice, (_event, args: { workspaceId?: unknown; context?: unknown }) => {
|
||||
if (typeof args?.workspaceId !== 'string') {
|
||||
return null
|
||||
}
|
||||
)
|
||||
return sync.setChoice(
|
||||
args.workspaceId,
|
||||
typeof args.context === 'boolean' ? { context: args.context } : {}
|
||||
)
|
||||
})
|
||||
ipcMain.handle(CH.openFolder, (_event, workspaceId: unknown) =>
|
||||
typeof workspaceId === 'string' ? sync.openFolder(workspaceId) : { ok: false }
|
||||
)
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
// A workspace's copy on this computer as a whole: where it is (from the runtime record), what
|
||||
// removing it would take with it, and removing it (archive, delete, both rows off).
|
||||
// removing it would take with it, and removing it (archive, delete, sync turned off).
|
||||
import { rm, rmdir } from 'node:fs/promises'
|
||||
import { basename, join } from 'node:path'
|
||||
import type { EphemeralVmRuntimeRecord } from '../../shared/ephemeral-vm-runtimes'
|
||||
import { getEphemeralVmRecipeResultConnection } from '../../shared/ephemeral-vm-recipes'
|
||||
import type { CloudSyncRemovalPreview } from '../../shared/cloud-sync/cloud-sync-contract'
|
||||
import { localStatAt, removeCopies } from './cloud-sync-local-writes'
|
||||
import { SYNC_TEMP_DIR, cloudSyncFolder, isContextPath } from './cloud-sync-paths'
|
||||
import { SYNC_TEMP_DIR, cloudSyncFolder } from './cloud-sync-paths'
|
||||
import { isLocalCopyEdited } from './cloud-sync-plan'
|
||||
import type { CloudSyncStore } from './cloud-sync-store'
|
||||
|
||||
@@ -74,20 +74,6 @@ export async function removeLocalCopy(
|
||||
await store.removeIndex(workspaceId)
|
||||
}
|
||||
|
||||
/** Mirror turned off while asleep: the mirrored files go now (they'd only get staler). */
|
||||
export async function removeMirroredFiles(
|
||||
store: CloudSyncStore,
|
||||
workspaceId: string,
|
||||
folder: string
|
||||
): Promise<void> {
|
||||
const index = await store.readIndex(workspaceId, folder)
|
||||
const outside = Object.keys(index.entries).filter((path) => !isContextPath(path))
|
||||
if (outside.length > 0) {
|
||||
await removeCopies(folder, outside, index.entries)
|
||||
await store.writeIndex(workspaceId, index)
|
||||
}
|
||||
}
|
||||
|
||||
export async function previewRemoval(
|
||||
store: CloudSyncStore,
|
||||
workspaceId: string,
|
||||
|
||||
@@ -48,7 +48,7 @@ export function displayPath(path: string, home: string = homedir()): string {
|
||||
}
|
||||
|
||||
/**
|
||||
* A cloud-relative path that is safe to mirror: forward slashes, no empty/`.`/`..` segments, no
|
||||
* A cloud-relative path that is safe to copy here: forward slashes, no empty/`.`/`..` segments, no
|
||||
* absolute or drive paths, no control characters, never inside `.git` or this sync's temp dir.
|
||||
*/
|
||||
export function isSafeSyncPath(path: string): boolean {
|
||||
|
||||
@@ -21,8 +21,8 @@ export type IndexEntry = {
|
||||
|
||||
export type LocalStat = { size: number; mtimeMs: number } | null
|
||||
|
||||
/** Which rows are on for a workspace (this member's choice on this computer). */
|
||||
export type CloudSyncChoice = { context: boolean; mirror: boolean }
|
||||
/** Whether `.context` sync is on for a workspace (this member's choice on this computer). */
|
||||
export type CloudSyncChoice = { context: boolean }
|
||||
|
||||
export type SyncLimits = {
|
||||
maxFiles: number
|
||||
@@ -30,25 +30,16 @@ export type SyncLimits = {
|
||||
maxFileBytes: number
|
||||
}
|
||||
|
||||
// Decimal units, as the window shows them ("2.0 GB", "100 MB").
|
||||
// Decimal units, as the window shows them ("250 MB", "50 MB").
|
||||
export const CONTEXT_LIMITS: SyncLimits = {
|
||||
maxFiles: 5_000,
|
||||
maxBytes: 250_000_000,
|
||||
maxFileBytes: 50_000_000
|
||||
}
|
||||
export const MIRROR_LIMITS: SyncLimits = {
|
||||
maxFiles: 100_000,
|
||||
maxBytes: 2_000_000_000,
|
||||
maxFileBytes: 100_000_000
|
||||
}
|
||||
|
||||
export function limitsFor(choice: CloudSyncChoice): SyncLimits {
|
||||
return choice.mirror ? MIRROR_LIMITS : CONTEXT_LIMITS
|
||||
}
|
||||
|
||||
export function limitsInfo(choice: CloudSyncChoice): CloudSyncLimitsInfo {
|
||||
const limits = limitsFor(choice)
|
||||
return { maxBytes: limits.maxBytes, maxFileBytes: limits.maxFileBytes }
|
||||
export const CONTEXT_LIMITS_INFO: CloudSyncLimitsInfo = {
|
||||
maxBytes: CONTEXT_LIMITS.maxBytes,
|
||||
maxFileBytes: CONTEXT_LIMITS.maxFileBytes
|
||||
}
|
||||
|
||||
export function emptySyncState(
|
||||
@@ -69,7 +60,7 @@ export function emptySyncState(
|
||||
editedHere: 0,
|
||||
skippedLarge: 0,
|
||||
overLimit: 0,
|
||||
limits: limitsInfo(choice),
|
||||
limits: CONTEXT_LIMITS_INFO,
|
||||
error: null
|
||||
}
|
||||
}
|
||||
@@ -164,7 +155,7 @@ export function planSync(input: {
|
||||
/**
|
||||
* Safety net for anything the watch missed. The VM's watcher can miss a directory created along
|
||||
* with its parent (`mkdir -p .context/shots`), so small folders are re-checked often (a few
|
||||
* calls each) and large mirrors less often: 30 ms per file, between 30 s and 10 min, and never
|
||||
* calls each) and large ones less often: 30 ms per file, between 30 s and 10 min, and never
|
||||
* more than 5% of the time (a slow pass, e.g. on an image without files.statMany, waits longer).
|
||||
*/
|
||||
export const SAFETY_TICK_MS = 30_000
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
// The cloud half of a sync pass, over the workspace's E2EE orcad connection: list what is in
|
||||
// scope (gitignore-aware), stat it in batches, and page files down. Replies are validated, never
|
||||
// The cloud half of a sync pass, over the workspace's E2EE orcad connection: walk `.context`,
|
||||
// stat it in batches, and page files down. Replies are validated, never
|
||||
// trusted: the VM is not this process.
|
||||
import { z } from 'zod'
|
||||
import { FILE_STAT_MANY_MAX } from '../../shared/file-access/file-stat-many'
|
||||
import { CONTEXT_DIR, isContextPath, isSafeSyncPath } from './cloud-sync-paths'
|
||||
import { CONTEXT_DIR, isSafeSyncPath } from './cloud-sync-paths'
|
||||
import type { RemoteEntry } from './cloud-sync-plan'
|
||||
|
||||
export type SyncCall = <T = unknown>(
|
||||
@@ -12,11 +12,8 @@ export type SyncCall = <T = unknown>(
|
||||
options?: { timeoutMs?: number; signal?: AbortSignal }
|
||||
) => Promise<T>
|
||||
|
||||
export type SyncScope = 'context' | 'workspace'
|
||||
|
||||
const LIST_TIMEOUT_MS = 60_000
|
||||
const STAT_TIMEOUT_MS = 60_000
|
||||
const CANDIDATE_BATCH = 100
|
||||
const FALLBACK_STAT_CONCURRENCY = 12
|
||||
const CONTEXT_MAX_DEPTH = 8
|
||||
|
||||
@@ -66,7 +63,6 @@ const WorktreeRows = z.looseObject({
|
||||
const DirEntries = z.array(
|
||||
z.looseObject({ name: z.string(), isDirectory: z.boolean(), isSymlink: z.boolean().optional() })
|
||||
)
|
||||
const PathList = z.array(z.string())
|
||||
const StatMany = z.object({
|
||||
entries: z.array(
|
||||
z.union([
|
||||
@@ -108,12 +104,12 @@ export async function resolveCloudWorktree(
|
||||
}
|
||||
|
||||
/** Every regular file under `.context` (it is usually gitignored, so it is walked, not listed). */
|
||||
async function listContext(
|
||||
export async function listContext(
|
||||
call: SyncCall,
|
||||
selector: string,
|
||||
maxFiles: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<string[]> {
|
||||
): Promise<{ paths: string[]; truncated: boolean }> {
|
||||
const out: string[] = []
|
||||
const walk = async (dir: string, depth: number): Promise<void> => {
|
||||
if (depth > CONTEXT_MAX_DEPTH || out.length >= maxFiles) {
|
||||
@@ -151,83 +147,7 @@ async function listContext(
|
||||
}
|
||||
}
|
||||
await walk(CONTEXT_DIR, 0)
|
||||
return out
|
||||
}
|
||||
|
||||
/** Paths in scope: `.context` always; the whole workspace (minus .gitignore) for a mirror. */
|
||||
export async function listScope(
|
||||
call: SyncCall,
|
||||
selector: string,
|
||||
scope: SyncScope,
|
||||
maxFiles: number,
|
||||
signal?: AbortSignal
|
||||
): Promise<{ paths: string[]; truncated: boolean }> {
|
||||
const context = await listContext(call, selector, maxFiles, signal)
|
||||
if (scope === 'context') {
|
||||
return { paths: context, truncated: context.length >= maxFiles }
|
||||
}
|
||||
const listed = PathList.parse(
|
||||
await call(
|
||||
'files.listAll',
|
||||
// Quick-open listing adds gitignored files unless told not to.
|
||||
{ worktree: selector, includeIgnored: false, maxResults: maxFiles + 1 },
|
||||
{ timeoutMs: LIST_TIMEOUT_MS, signal }
|
||||
)
|
||||
)
|
||||
const paths = new Set(context)
|
||||
for (const path of listed) {
|
||||
if (isSafeSyncPath(path) && !isContextPath(path)) {
|
||||
paths.add(path)
|
||||
}
|
||||
}
|
||||
const all = [...paths]
|
||||
return { paths: all.slice(0, maxFiles), truncated: all.length > maxFiles }
|
||||
}
|
||||
|
||||
/**
|
||||
* Of the changed paths a watch reported, the ones a mirror includes: `.context` always, others
|
||||
* only when the cloud's listing (which honours .gitignore) still has them.
|
||||
*/
|
||||
export async function filterIncluded(
|
||||
call: SyncCall,
|
||||
selector: string,
|
||||
scope: SyncScope,
|
||||
paths: readonly string[],
|
||||
signal?: AbortSignal
|
||||
): Promise<Set<string>> {
|
||||
const included = new Set<string>()
|
||||
const others: string[] = []
|
||||
for (const path of paths) {
|
||||
if (!isSafeSyncPath(path)) {
|
||||
continue
|
||||
}
|
||||
if (isContextPath(path)) {
|
||||
included.add(path)
|
||||
} else if (scope === 'workspace') {
|
||||
others.push(path)
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < others.length; i += CANDIDATE_BATCH) {
|
||||
const batch = others.slice(i, i + CANDIDATE_BATCH)
|
||||
const listed = PathList.parse(
|
||||
await call(
|
||||
'files.listAll',
|
||||
{
|
||||
worktree: selector,
|
||||
includeIgnored: false,
|
||||
candidatePaths: batch,
|
||||
maxResults: batch.length
|
||||
},
|
||||
{ timeoutMs: LIST_TIMEOUT_MS, signal }
|
||||
)
|
||||
)
|
||||
for (const path of listed) {
|
||||
if (batch.includes(path)) {
|
||||
included.add(path)
|
||||
}
|
||||
}
|
||||
}
|
||||
return included
|
||||
return { paths: out, truncated: out.length >= maxFiles }
|
||||
}
|
||||
|
||||
/** Hosts whose orcad predates `files.statMany` (an older sandbox image). */
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
@@ -61,6 +61,7 @@ async function setup() {
|
||||
return {
|
||||
vm,
|
||||
service,
|
||||
userData,
|
||||
folder,
|
||||
views,
|
||||
opened,
|
||||
@@ -82,7 +83,7 @@ describe('cloud sync service', () => {
|
||||
expect(await readFile(join(t.folder, '.context/plan.md'), 'utf8')).toBe('plan')
|
||||
const view = await t.service.getState('ws')
|
||||
expect(view).toMatchObject({
|
||||
choice: { context: true, mirror: false },
|
||||
choice: { context: true },
|
||||
displayPath: '~/orca/cloud/Hello-World/my-ws/.context'
|
||||
})
|
||||
await t.service.openFolder('ws')
|
||||
@@ -90,15 +91,21 @@ describe('cloud sync service', () => {
|
||||
await t.service.dispose()
|
||||
})
|
||||
|
||||
it('opens the workspace folder once the mirror is on', async () => {
|
||||
it('loads a choice saved by an older build that also had a mirror field', async () => {
|
||||
const t = await setup()
|
||||
await t.service.reconcile()
|
||||
await t.synced()
|
||||
const view = await t.service.setChoice('ws', { mirror: true })
|
||||
expect(view?.displayPath).toBe('~/orca/cloud/Hello-World/my-ws')
|
||||
await vi.waitFor(async () =>
|
||||
expect(await readFile(join(t.folder, 'src/a.ts'), 'utf8')).toBe('a')
|
||||
await mkdir(join(t.userData, 'orca-cloud-sync'), { recursive: true })
|
||||
await writeFile(
|
||||
join(t.userData, 'orca-cloud-sync', 'choices.json'),
|
||||
JSON.stringify({ version: 1, workspaces: { ws: { context: false, mirror: true } } })
|
||||
)
|
||||
expect(await t.service.getState('ws')).toMatchObject({
|
||||
choice: { context: false },
|
||||
phase: 'off'
|
||||
})
|
||||
const view = await t.service.setChoice('ws', { context: true })
|
||||
expect(view?.choice).toEqual({ context: true })
|
||||
await t.synced()
|
||||
expect(await readFile(join(t.folder, '.context/plan.md'), 'utf8')).toBe('plan')
|
||||
await t.service.dispose()
|
||||
})
|
||||
|
||||
@@ -149,7 +156,7 @@ describe('cloud sync service', () => {
|
||||
await t.service.dispose()
|
||||
})
|
||||
|
||||
it('turning both off removes the copy', async () => {
|
||||
it('turning sync off removes the copy', async () => {
|
||||
const t = await setup()
|
||||
await t.service.reconcile()
|
||||
await t.synced()
|
||||
|
||||
@@ -13,11 +13,10 @@ import {
|
||||
cloudRuntimesFrom,
|
||||
previewRemoval,
|
||||
removeLocalCopy,
|
||||
removeMirroredFiles,
|
||||
type CloudRuntime
|
||||
} from './cloud-sync-local-copy'
|
||||
import { CONTEXT_DIR, displayPath } from './cloud-sync-paths'
|
||||
import { limitsInfo, type CloudSyncChoice } from './cloud-sync-plan'
|
||||
import { CONTEXT_LIMITS_INFO, type CloudSyncChoice } from './cloud-sync-plan'
|
||||
import type { SyncCall } from './cloud-sync-remote'
|
||||
import {
|
||||
createCloudSyncSession,
|
||||
@@ -51,7 +50,7 @@ function idleState(
|
||||
workspaceId: runtime.workspaceId,
|
||||
choice,
|
||||
folder: runtime.folder,
|
||||
phase: !choice.context && !choice.mirror ? 'off' : 'waiting',
|
||||
phase: choice.context ? 'waiting' : 'off',
|
||||
files: previous?.files ?? 0,
|
||||
bytes: previous?.bytes ?? 0,
|
||||
progress: null,
|
||||
@@ -59,7 +58,7 @@ function idleState(
|
||||
editedHere: previous?.editedHere ?? 0,
|
||||
skippedLarge: previous?.skippedLarge ?? 0,
|
||||
overLimit: previous?.overLimit ?? 0,
|
||||
limits: limitsInfo(choice),
|
||||
limits: CONTEXT_LIMITS_INFO,
|
||||
error: null
|
||||
}
|
||||
}
|
||||
@@ -77,8 +76,7 @@ export function createCloudSyncService(deps: CloudSyncServiceDeps) {
|
||||
let disposed = false
|
||||
|
||||
const viewOf = (state: CloudSyncState): CloudSyncView => {
|
||||
const openPath =
|
||||
state.choice.mirror || !state.choice.context ? state.folder : join(state.folder, CONTEXT_DIR)
|
||||
const openPath = join(state.folder, CONTEXT_DIR)
|
||||
return { ...state, openPath, displayPath: displayPath(openPath, deps.home) }
|
||||
}
|
||||
|
||||
@@ -175,7 +173,7 @@ export function createCloudSyncService(deps: CloudSyncServiceDeps) {
|
||||
continue
|
||||
}
|
||||
const choice = await deps.store.choice(runtime.workspaceId)
|
||||
if (!runtime.running || (!choice.context && !choice.mirror)) {
|
||||
if (!runtime.running || !choice.context) {
|
||||
await reconcileIdle(runtime, choice)
|
||||
continue
|
||||
}
|
||||
@@ -269,17 +267,12 @@ export function createCloudSyncService(deps: CloudSyncServiceDeps) {
|
||||
return null
|
||||
}
|
||||
const choice = await deps.store.setChoice(workspaceId, patch)
|
||||
const session = sessions.get(workspaceId)
|
||||
if (!choice.context && !choice.mirror) {
|
||||
if (!choice.context) {
|
||||
await stopSession(workspaceId)
|
||||
await removeLocalCopy(deps.store, workspaceId, runtime.folder)
|
||||
states.delete(workspaceId)
|
||||
} else if (session) {
|
||||
void session.session.setChoice(choice)
|
||||
} else {
|
||||
if (!choice.mirror) {
|
||||
await removeMirroredFiles(deps.store, workspaceId, runtime.folder)
|
||||
}
|
||||
}
|
||||
// A running session's state stands; otherwise the reconcile below starts one (or goes idle).
|
||||
if (!sessions.has(workspaceId)) {
|
||||
states.delete(workspaceId)
|
||||
}
|
||||
await reconcile()
|
||||
|
||||
@@ -14,7 +14,7 @@ afterEach(async () => {
|
||||
await Promise.all(dirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
|
||||
})
|
||||
|
||||
async function setup(vm: FakeVm, choice: CloudSyncChoice = { context: true, mirror: false }) {
|
||||
async function setup(vm: FakeVm, choice: CloudSyncChoice = { context: true }) {
|
||||
const folder = await mkdtemp(join(tmpdir(), 'cloud-sync-folder-'))
|
||||
const userData = await mkdtemp(join(tmpdir(), 'cloud-sync-userdata-'))
|
||||
dirs.push(folder, userData)
|
||||
@@ -38,7 +38,7 @@ const settle = async (session: { resync: () => Promise<void> }): Promise<void> =
|
||||
}
|
||||
|
||||
describe('cloud sync session', () => {
|
||||
it('copies .context (gitignored, walked) read-only and leaves other files alone by default', async () => {
|
||||
it('copies .context (gitignored, walked) read-only and nothing outside it', async () => {
|
||||
const vm = createFakeVm()
|
||||
vm.write('.context/plan.md', '# Plan')
|
||||
vm.write('.context/shots/one.png', 'PNG')
|
||||
@@ -53,21 +53,23 @@ describe('cloud sync session', () => {
|
||||
await session.stop()
|
||||
})
|
||||
|
||||
it('mirrors the workspace minus .gitignore, then removes it when the mirror is turned off', async () => {
|
||||
it('removes files outside .context that an older build copied', async () => {
|
||||
const vm = createFakeVm()
|
||||
vm.write('.context/plan.md', 'p')
|
||||
vm.write('src/index.ts', 'code')
|
||||
vm.write('dist/bundle.js', 'built')
|
||||
vm.ignored.add('dist/bundle.js')
|
||||
const { folder, session, last } = await setup(vm, { context: true, mirror: true })
|
||||
const { folder, store, session } = await setup(vm)
|
||||
const { mkdir } = await import('node:fs/promises')
|
||||
await mkdir(join(folder, 'src'))
|
||||
await writeFile(join(folder, 'src/index.ts'), 'code')
|
||||
const copied = await stat(join(folder, 'src/index.ts'))
|
||||
await store.writeIndex('ws', {
|
||||
version: 1,
|
||||
folder,
|
||||
lastSyncedAt: 1,
|
||||
entries: { 'src/index.ts': { rs: 4, rm: 1, ls: copied.size, lm: copied.mtimeMs } }
|
||||
})
|
||||
await session.start()
|
||||
expect(await readFile(join(folder, 'src/index.ts'), 'utf8')).toBe('code')
|
||||
await expect(stat(join(folder, 'dist/bundle.js'))).rejects.toThrow()
|
||||
expect(last()).toMatchObject({ phase: 'synced', files: 2 })
|
||||
await session.setChoice({ context: true, mirror: false })
|
||||
await expect(stat(join(folder, 'src/index.ts'))).rejects.toThrow()
|
||||
// The emptied directory goes too; .context stays.
|
||||
await expect(stat(join(folder, 'src'))).rejects.toThrow()
|
||||
expect(await readFile(join(folder, '.context/plan.md'), 'utf8')).toBe('p')
|
||||
await session.stop()
|
||||
})
|
||||
@@ -75,16 +77,16 @@ describe('cloud sync session', () => {
|
||||
it('second pass is incremental: only changed files are read again', async () => {
|
||||
const vm = createFakeVm()
|
||||
for (let i = 0; i < 50; i++) {
|
||||
vm.write(`src/f${i}.ts`, `v${i}`)
|
||||
vm.write(`.context/f${i}.md`, `v${i}`)
|
||||
}
|
||||
const { folder, session } = await setup(vm, { context: true, mirror: true })
|
||||
const { folder, session } = await setup(vm)
|
||||
await session.start()
|
||||
vm.calls.length = 0
|
||||
vm.write('src/f7.ts', 'changed')
|
||||
vm.write('.context/f7.md', 'changed')
|
||||
await settle(session)
|
||||
expect(vm.calls.filter((method) => method === 'files.readChunk')).toHaveLength(1)
|
||||
expect(vm.calls.filter((method) => method === 'files.statMany')).toHaveLength(1)
|
||||
expect(await readFile(join(folder, 'src/f7.ts'), 'utf8')).toBe('changed')
|
||||
expect(await readFile(join(folder, '.context/f7.md'), 'utf8')).toBe('changed')
|
||||
await session.stop()
|
||||
})
|
||||
|
||||
@@ -220,7 +222,7 @@ describe('cloud sync session', () => {
|
||||
})
|
||||
|
||||
describe('safetyIntervalMs', () => {
|
||||
it('re-checks small folders every 30 s and large mirrors at most every 10 min', () => {
|
||||
it('re-checks small folders every 30 s and large ones at most every 10 min', () => {
|
||||
expect(safetyIntervalMs(0)).toBe(30_000)
|
||||
expect(safetyIntervalMs(21)).toBe(30_000)
|
||||
expect(safetyIntervalMs(2_000)).toBe(60_000)
|
||||
|
||||
@@ -12,23 +12,21 @@ import {
|
||||
} from './cloud-sync-local-writes'
|
||||
import { isContextPath, isSafeSyncPath } from './cloud-sync-paths'
|
||||
import {
|
||||
CONTEXT_LIMITS,
|
||||
CONTEXT_LIMITS_INFO,
|
||||
emptySyncState,
|
||||
safetyIntervalMs,
|
||||
SAFETY_TICK_MS,
|
||||
limitsFor,
|
||||
limitsInfo,
|
||||
planSync,
|
||||
type LocalStat,
|
||||
type RemoteEntry
|
||||
} from './cloud-sync-plan'
|
||||
import {
|
||||
filterIncluded,
|
||||
isWaitingError,
|
||||
listScope,
|
||||
listContext,
|
||||
resolveCloudWorktree,
|
||||
statFiles,
|
||||
type SyncCall,
|
||||
type SyncScope
|
||||
type SyncCall
|
||||
} from './cloud-sync-remote'
|
||||
import type { CloudSyncChoice, CloudSyncIndex, CloudSyncStore } from './cloud-sync-store'
|
||||
import {
|
||||
@@ -59,7 +57,7 @@ export type CloudSyncSessionDeps = {
|
||||
export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
const now = deps.now ?? Date.now
|
||||
const log = (line: string): void => deps.log?.(`[cloud-sync] ${deps.workspaceId}: ${line}`)
|
||||
let choice = deps.choice
|
||||
const choice = deps.choice
|
||||
let stopped = false
|
||||
let worktree: { selector: string; root: string } | null = null
|
||||
let index: CloudSyncIndex | null = null
|
||||
@@ -80,12 +78,10 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
})
|
||||
|
||||
const publish = (patch: Partial<CloudSyncState>): void => {
|
||||
state = { ...state, ...patch, choice, limits: limitsInfo(choice) }
|
||||
state = { ...state, ...patch, choice, limits: CONTEXT_LIMITS_INFO }
|
||||
deps.emit(state)
|
||||
}
|
||||
|
||||
const scope = (): SyncScope => (choice.mirror ? 'workspace' : 'context')
|
||||
|
||||
async function loadIndex(): Promise<CloudSyncIndex> {
|
||||
index ??= await deps.store.readIndex(deps.workspaceId, deps.folder)
|
||||
if (index.lastSyncedAt !== null && state.lastSyncedAt === null) {
|
||||
@@ -141,11 +137,10 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
lastFullPassAt = now()
|
||||
const { selector } = await ensureWorktree()
|
||||
const current = await loadIndex()
|
||||
const limits = limitsFor(choice)
|
||||
if (state.lastSyncedAt === null) {
|
||||
publish({ phase: 'starting', error: null })
|
||||
}
|
||||
const listed = await listScope(deps.call, selector, scope(), limits.maxFiles, abort.signal)
|
||||
const listed = await listContext(deps.call, selector, CONTEXT_LIMITS.maxFiles, abort.signal)
|
||||
const remote = await statFiles(deps.call, selector, listed.paths, abort.signal)
|
||||
const paths = new Set([...remote.keys(), ...Object.keys(current.entries)])
|
||||
// Manifest cost only (listing + stat), not the copying a first pass does.
|
||||
@@ -156,8 +151,8 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
async function incrementalPass(paths: string[]): Promise<void> {
|
||||
const { selector } = await ensureWorktree()
|
||||
await loadIndex()
|
||||
const included = await filterIncluded(deps.call, selector, scope(), paths, abort.signal)
|
||||
const remote = await statFiles(deps.call, selector, [...included], abort.signal)
|
||||
const included = paths.filter((path) => isSafeSyncPath(path) && isContextPath(path))
|
||||
const remote = await statFiles(deps.call, selector, included, abort.signal)
|
||||
await apply({ remote, paths: new Set(paths), scoped: new Set(paths), truncated: 0 })
|
||||
}
|
||||
|
||||
@@ -168,7 +163,7 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
truncated: number
|
||||
}): Promise<void> {
|
||||
const current = index!
|
||||
const limits = limitsFor(choice)
|
||||
const limits = CONTEXT_LIMITS
|
||||
await mkdir(deps.folder, { recursive: true })
|
||||
const local = new Map<string, LocalStat>()
|
||||
for (const path of input.paths) {
|
||||
@@ -176,11 +171,9 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
local.set(path, await localStatAt(deps.folder, path))
|
||||
}
|
||||
}
|
||||
// Paths that left scope (mirror turned off) are removed like cloud deletions.
|
||||
// Anything outside `.context` (copied by an older build) is removed like a cloud deletion.
|
||||
const remote = new Map(
|
||||
[...input.remote].filter(
|
||||
([path]) => isSafeSyncPath(path) && (choice.mirror || isContextPath(path))
|
||||
)
|
||||
[...input.remote].filter(([path]) => isSafeSyncPath(path) && isContextPath(path))
|
||||
)
|
||||
const plan = planSync({
|
||||
remote,
|
||||
@@ -232,7 +225,7 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
if (!worktree) {
|
||||
return
|
||||
}
|
||||
const batch = readWatchEvent(event, worktree.root, choice.mirror)
|
||||
const batch = readWatchEvent(event, worktree.root)
|
||||
if (batch.kind === 'ready') {
|
||||
watchRetryMs = WATCH_RETRY_MIN_MS
|
||||
} else if (batch.kind === 'rescan') {
|
||||
@@ -308,11 +301,6 @@ export function createCloudSyncSession(deps: CloudSyncSessionDeps) {
|
||||
void openWatch()
|
||||
return requestFullPass()
|
||||
},
|
||||
setChoice(next: CloudSyncChoice): Promise<void> {
|
||||
choice = next
|
||||
publish({})
|
||||
return requestFullPass()
|
||||
},
|
||||
/** Stops syncing; the files stay (asleep). */
|
||||
stop(): Promise<void> {
|
||||
stopped = true
|
||||
|
||||
@@ -9,14 +9,12 @@ import type { CloudSyncChoice, IndexEntry } from './cloud-sync-plan'
|
||||
export type { CloudSyncChoice }
|
||||
|
||||
/** `.context` is small and holds what people come back for (plans, screenshots): on by default. */
|
||||
export const DEFAULT_SYNC_CHOICE: CloudSyncChoice = { context: true, mirror: false }
|
||||
export const DEFAULT_SYNC_CHOICE: CloudSyncChoice = { context: true }
|
||||
|
||||
const ChoicesSchema = z.object({
|
||||
version: z.literal(1),
|
||||
workspaces: z.record(
|
||||
z.string(),
|
||||
z.object({ context: z.boolean().optional(), mirror: z.boolean().optional() })
|
||||
)
|
||||
// z.object drops keys it doesn't name, so records saved by older builds still load.
|
||||
workspaces: z.record(z.string(), z.object({ context: z.boolean().optional() }))
|
||||
})
|
||||
|
||||
const IndexEntrySchema = z.object({
|
||||
@@ -66,10 +64,7 @@ export function createCloudSyncStore(userDataPath: string) {
|
||||
dir,
|
||||
async choice(workspaceId: string): Promise<CloudSyncChoice> {
|
||||
const saved = (await loadChoices()).workspaces[workspaceId]
|
||||
return {
|
||||
context: saved?.context ?? DEFAULT_SYNC_CHOICE.context,
|
||||
mirror: saved?.mirror ?? DEFAULT_SYNC_CHOICE.mirror
|
||||
}
|
||||
return { context: saved?.context ?? DEFAULT_SYNC_CHOICE.context }
|
||||
},
|
||||
async setChoice(
|
||||
workspaceId: string,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// The cloud's file watch, read for sync: which workspace paths changed, or that a rescan is
|
||||
// The cloud's file watch, read for sync: which `.context` paths changed, or that a rescan is
|
||||
// needed (overflow, or a directory event that can stand for many files). Events come from the VM
|
||||
// and are validated like any other reply.
|
||||
import { z } from 'zod'
|
||||
@@ -28,7 +28,7 @@ export type WatchBatch =
|
||||
| { kind: 'paths'; paths: string[] }
|
||||
| { kind: 'none' }
|
||||
|
||||
export function readWatchEvent(event: unknown, root: string, mirror: boolean): WatchBatch {
|
||||
export function readWatchEvent(event: unknown, root: string): WatchBatch {
|
||||
const parsed = WatchEventSchema.safeParse(event)
|
||||
if (!parsed.success) {
|
||||
return { kind: 'none' }
|
||||
@@ -50,7 +50,7 @@ export function readWatchEvent(event: unknown, root: string, mirror: boolean): W
|
||||
}
|
||||
for (const candidate of [change.data.absolutePath, change.data.oldAbsolutePath]) {
|
||||
const rel = relativeToRoot(root, candidate)
|
||||
if (rel && isSafeSyncPath(rel) && (mirror || isContextPath(rel))) {
|
||||
if (rel && isSafeSyncPath(rel) && isContextPath(rel)) {
|
||||
paths.push(rel)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -187,7 +187,7 @@ export type PreloadApi = {
|
||||
plainSsh?: PlainSshTerminalApi
|
||||
/** Desktop only: streams files and folders from a paired runtime host to this machine. */
|
||||
runtimeDownloads?: RuntimeDownloadsApi
|
||||
/** Desktop only: Orca Cloud workspace files synced to this computer (.context and the mirror). */
|
||||
/** Desktop only: an Orca Cloud workspace's `.context` folder synced to this computer. */
|
||||
cloudSync?: CloudSyncApi
|
||||
/** Desktop only: the API keys Orca hands to agent launches. */
|
||||
agentApiKeys?: AgentApiKeysApi
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// PARITY-FOLLOW: the people on the cloud workspace in front, beside its W-123 chip: its creator,
|
||||
// its followers and who is here now, then Follow. Nothing for a local workspace, a personal
|
||||
// account, or a workspace only you are on and nobody else could follow.
|
||||
import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import React, { useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { useAppStore } from '@/store'
|
||||
@@ -47,7 +48,9 @@ export function CloudWorkspacePeople({
|
||||
const { directory } = useMemberDirectory(orgId ?? undefined, workspace ? [workspace] : [])
|
||||
// The live list row carries githubActing / you already.
|
||||
const actingLine = gitActingLine(workspace, t)
|
||||
if (!workspace) {
|
||||
// TEAM-SHARING-HOLD: followers and who's here only exist on a shared workspace.
|
||||
const teamSharing = useCloudTeamSharingEnabled()
|
||||
if (!workspace || !teamSharing) {
|
||||
return null
|
||||
}
|
||||
const following = followOffer(workspace, selfId)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// "Open cloud workspace…": cloud workspaces this computer's sidebar doesn't show, as the same rows
|
||||
// (and ⋯ menu) the team list had. Open goes through openCloudWorkspace and closes the picker.
|
||||
import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import React, { useCallback, useEffect, useMemo, useState } from 'react'
|
||||
import { RefreshCw, Search } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -55,10 +56,16 @@ function pickerCopy(
|
||||
case 'open':
|
||||
return {
|
||||
title: t('components.cloudWorkspaces.picker.title', 'Open cloud workspace'),
|
||||
description: t(
|
||||
'components.cloudWorkspaces.picker.description',
|
||||
'Cloud workspaces that aren’t in your sidebar: shared by teammates, or started on another computer.'
|
||||
)
|
||||
// TEAM-SHARING-HOLD: nothing is shared by teammates while sharing is held.
|
||||
description: cloudTeamSharingEnabled()
|
||||
? t(
|
||||
'components.cloudWorkspaces.picker.description',
|
||||
'Cloud workspaces that aren’t in your sidebar: shared by teammates, or started on another computer.'
|
||||
)
|
||||
: t(
|
||||
'components.cloudWorkspaces.picker.descriptionOwn',
|
||||
'Your cloud workspaces that aren’t in your sidebar, such as ones started on another computer.'
|
||||
)
|
||||
}
|
||||
case 'teammate':
|
||||
return {
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import { CloudStatusGlyph } from '@/components/orca-cloud/CloudStatusGlyph'
|
||||
import { cloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
import {
|
||||
cloudTeamSharingEnabled,
|
||||
useCloudTeamSharingEnabled
|
||||
} from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import React, { useId, useState } from 'react'
|
||||
import { GitBranch, Loader2 } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -113,6 +116,7 @@ export function CloudWorkspaceRow({
|
||||
hours,
|
||||
defaultValue_one: '{{hours}} sandbox hour'
|
||||
})
|
||||
const teamSharing = useCloudTeamSharingEnabled()
|
||||
const lastActive = formatRelative(w.lastActivityAt, now, t, intlLocale)
|
||||
const presence = presenceSummary(
|
||||
presentMembers(w.presence, selfId),
|
||||
@@ -151,7 +155,7 @@ export function CloudWorkspaceRow({
|
||||
return
|
||||
}
|
||||
if (
|
||||
cloudShareLinksEnabled() &&
|
||||
cloudTeamSharingEnabled() &&
|
||||
keybindingMatchesAction(
|
||||
'cloudWorkspace.copyLink',
|
||||
event.nativeEvent,
|
||||
@@ -272,12 +276,15 @@ export function CloudWorkspaceRow({
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<PresenceStack
|
||||
presence={w.presence}
|
||||
directory={directory}
|
||||
selfId={selfId}
|
||||
onGoToChat={canOpen ? (member) => actions.goToChat(w, member) : undefined}
|
||||
/>
|
||||
{/* TEAM-SHARING-HOLD: who's here only exists on a shared workspace. */}
|
||||
{teamSharing ? (
|
||||
<PresenceStack
|
||||
presence={w.presence}
|
||||
directory={directory}
|
||||
selfId={selfId}
|
||||
onGoToChat={canOpen ? (member) => actions.goToChat(w, member) : undefined}
|
||||
/>
|
||||
) : null}
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<span className="w-28 text-right text-xs tabular-nums text-muted-foreground">
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// The small marks after a cloud workspace's title in Open cloud workspace…: private, started by a
|
||||
// routine, and its W-number (shown on hover or focus; its space is held so nothing shifts).
|
||||
import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import React from 'react'
|
||||
import { CalendarClock, Lock } from 'lucide-react'
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
|
||||
@@ -23,9 +24,11 @@ export function CloudWorkspaceRowBadges({
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const revealOpen = revealNumber
|
||||
// TEAM-SHARING-HOLD: every workspace is private while sharing is held; no badge says so.
|
||||
const teamSharing = useCloudTeamSharingEnabled()
|
||||
return (
|
||||
<>
|
||||
{w.visibility === 'private' && (
|
||||
{teamSharing && w.visibility === 'private' && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Lock
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import React, { useRef } from 'react'
|
||||
import { useCloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import { ArchiveSnapshotTooltip } from '@/components/orca-cloud/ArchiveSnapshotTooltip'
|
||||
import {
|
||||
Archive,
|
||||
@@ -112,7 +112,7 @@ export function CloudWorkspaceRowMenu({
|
||||
const t = useTranslate()
|
||||
const keybindings = useAppStore((state) => state.keybindings)
|
||||
const copyShortcut = formatOptionalPrimaryShortcutLabel('cloudWorkspace.copyLink', keybindings)
|
||||
const shareLinks = useCloudShareLinksEnabled()
|
||||
const teamSharing = useCloudTeamSharingEnabled()
|
||||
// Read when the menu renders (it re-renders on open), not kept: focus moves between opens.
|
||||
const focused = open ? (actions.focusedItem?.(w) ?? null) : null
|
||||
const teammatesHere = canOpen
|
||||
@@ -187,8 +187,8 @@ export function CloudWorkspaceRowMenu({
|
||||
<DropdownMenuShortcut>↵</DropdownMenuShortcut>
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
{/* SHARE-LINKS-HOLD: the Copy link items only while share links are on. */}
|
||||
{shareLinks ? (
|
||||
{/* TEAM-SHARING-HOLD: share links only while team sharing is on. */}
|
||||
{teamSharing ? (
|
||||
<DropdownMenuItem onSelect={() => actions.copyLink(w)}>
|
||||
<Link2 />
|
||||
{w.number
|
||||
@@ -199,7 +199,7 @@ export function CloudWorkspaceRowMenu({
|
||||
{copyShortcut ? <DropdownMenuShortcut>{copyShortcut}</DropdownMenuShortcut> : null}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{shareLinks && focused ? (
|
||||
{teamSharing && focused ? (
|
||||
<DropdownMenuItem onSelect={() => actions.copyWorkspaceLink(w)}>
|
||||
{focused === 'terminal' ? <SquareTerminal /> : <MessageSquare />}
|
||||
{focused === 'terminal'
|
||||
@@ -248,7 +248,8 @@ export function CloudWorkspaceRowMenu({
|
||||
{canManage && (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{w.visibility === 'private' ? (
|
||||
{/* TEAM-SHARING-HOLD: no Share with team / Make private while sharing is held. */}
|
||||
{!teamSharing ? null : w.visibility === 'private' ? (
|
||||
<DropdownMenuItem onSelect={() => actions.patch(w, { visibility: 'team' })}>
|
||||
<Users />
|
||||
{t('auto.components.cloudWorkspaces.shareWithTeam', 'Share with team')}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
const teamSharing = vi.hoisted(() => ({ on: true }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink',
|
||||
cloudTeamSharingEnabled: () => teamSharing.on,
|
||||
useCloudTeamSharingEnabled: () => teamSharing.on
|
||||
}))
|
||||
import {
|
||||
cloudWorkspaceActionGroups,
|
||||
type CloudWorkspaceActionInput
|
||||
@@ -51,4 +57,20 @@ describe('one action list for every surface (JA-14)', () => {
|
||||
it('a teammate who cannot manage it only opens and copies links', () => {
|
||||
expect(flat({ canManage: false })).toEqual(['open:open,copyLink,copyWorkspaceLink'])
|
||||
})
|
||||
|
||||
it('TEAM-SHARING-HOLD: no Share with team or Make private while sharing is held', () => {
|
||||
teamSharing.on = false
|
||||
try {
|
||||
for (const visibility of ['private', 'team'] as const) {
|
||||
const actions = cloudWorkspaceActionGroups({ ...base, visibility }).flatMap(
|
||||
(g) => g.actions
|
||||
)
|
||||
expect(actions).not.toContain('share')
|
||||
expect(actions).not.toContain('makePrivate')
|
||||
expect(actions).toContain('archive')
|
||||
}
|
||||
} finally {
|
||||
teamSharing.on = true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
// workspace…" list's ⋯ menu and the sidebar's context menu both render these groups, in this order:
|
||||
// Open, Share, Lifecycle, Danger. Each surface leaves out only what it already shows elsewhere (the
|
||||
// sidebar row *is* the open workspace; the list has no local-only items) and never invents its own.
|
||||
import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
|
||||
export type CloudWorkspaceAction =
|
||||
@@ -37,6 +38,8 @@ export type CloudWorkspaceActionInput = Pick<
|
||||
canRestart: boolean
|
||||
/** Teammates to hand it to (the list only). */
|
||||
hasMembers?: boolean
|
||||
/** TEAM-SHARING-HOLD: Share with team / Make private offered (default: the account's capability). */
|
||||
teamSharing?: boolean
|
||||
}
|
||||
|
||||
export function cloudWorkspaceActionGroups(
|
||||
@@ -54,8 +57,10 @@ export function cloudWorkspaceActionGroups(
|
||||
open.push('copyWorkspaceLink')
|
||||
|
||||
const share: CloudWorkspaceAction[] = []
|
||||
if (input.canManage) {
|
||||
if (input.canManage && (input.teamSharing ?? cloudTeamSharingEnabled())) {
|
||||
share.push(input.visibility === 'private' ? 'share' : 'makePrivate')
|
||||
}
|
||||
if (input.canManage) {
|
||||
if (list && input.hasMembers) {
|
||||
share.push('reassignOwner')
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// App-level wiring for team cloud workspaces: orca://cloud links, presence for the workspace in
|
||||
// front, and the copy-link shortcut. Installed once from main.tsx; no React tree needed.
|
||||
import { cloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import { toast } from 'sonner'
|
||||
import { useAppStore } from '@/store'
|
||||
import { getShortcutPlatform } from '@/lib/keyboard/shortcut-platform'
|
||||
@@ -233,7 +233,7 @@ export function installCloudWorkspaceLinks(): () => void {
|
||||
const target = event.target instanceof HTMLElement ? event.target : null
|
||||
if (
|
||||
!event.defaultPrevented &&
|
||||
cloudShareLinksEnabled() &&
|
||||
cloudTeamSharingEnabled() &&
|
||||
!shortcutOwnedElsewhere(target) &&
|
||||
keybindingMatchesAction(
|
||||
'cloudWorkspace.copyLink',
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
const teamSharing = vi.hoisted(() => ({ on: true }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink',
|
||||
cloudTeamSharingEnabled: () => teamSharing.on,
|
||||
useCloudTeamSharingEnabled: () => teamSharing.on
|
||||
}))
|
||||
import {
|
||||
initialPickerControls,
|
||||
pickerListQuery,
|
||||
@@ -110,4 +116,18 @@ describe('what the picker lists', () => {
|
||||
expect(rows(`W-${mine.number}`)).toEqual(['Mine here'])
|
||||
expect(rows('nothing like this')).toEqual([])
|
||||
})
|
||||
|
||||
it('TEAM-SHARING-HOLD: no Team scope on a team while sharing is held; Open lists your own', () => {
|
||||
teamSharing.on = false
|
||||
try {
|
||||
expect(initialPickerControls(true).scope).toBe('mine')
|
||||
expect(pickerShowsScope({ kind: 'open' }, true)).toBe(false)
|
||||
expect(
|
||||
pickerListQuery({ kind: 'open' }, { scope: 'team', archived: false, search: '' }, true)
|
||||
.scope
|
||||
).toBe('mine')
|
||||
} finally {
|
||||
teamSharing.on = true
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// What "Open cloud workspace…" reads and lists for each focus. Pure, so the rules are tested apart
|
||||
// from the dialog.
|
||||
import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import type {
|
||||
CloudWorkspace,
|
||||
CloudWorkspaceListQuery
|
||||
@@ -14,14 +15,22 @@ export type CloudWorkspacePickerControls = {
|
||||
search: string
|
||||
}
|
||||
|
||||
/**
|
||||
* TEAM-SHARING-HOLD: with sharing held there is nothing of a teammate's to open, so "Open cloud
|
||||
* workspace…" has no Team scope and lists your own.
|
||||
*/
|
||||
function teamScope(hasOrg: boolean): boolean {
|
||||
return hasOrg && cloudTeamSharingEnabled()
|
||||
}
|
||||
|
||||
export function initialPickerControls(hasOrg: boolean): CloudWorkspacePickerControls {
|
||||
// On a team, what you can't open from the sidebar is mostly what teammates shared.
|
||||
return { scope: hasOrg ? 'team' : 'mine', archived: false, search: '' }
|
||||
return { scope: teamScope(hasOrg) ? 'team' : 'mine', archived: false, search: '' }
|
||||
}
|
||||
|
||||
/** Which controls the picker offers: a focused list (limit, teammate, team delete) is fixed. */
|
||||
export function pickerShowsScope(focus: CloudWorkspacePickerFocus, hasOrg: boolean): boolean {
|
||||
return focus.kind === 'open' && hasOrg
|
||||
return focus.kind === 'open' && teamScope(hasOrg)
|
||||
}
|
||||
|
||||
export function pickerShowsArchived(focus: CloudWorkspacePickerFocus): boolean {
|
||||
@@ -36,7 +45,7 @@ export function pickerListQuery(
|
||||
switch (focus.kind) {
|
||||
case 'open':
|
||||
return {
|
||||
scope: hasOrg ? controls.scope : 'mine',
|
||||
scope: teamScope(hasOrg) ? controls.scope : 'mine',
|
||||
archived: controls.archived ? 'only' : 'exclude'
|
||||
}
|
||||
case 'teammate':
|
||||
|
||||
@@ -5,8 +5,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const toasts = vi.hoisted(() => ({ success: vi.fn(), warning: vi.fn(), error: vi.fn() }))
|
||||
vi.mock('sonner', () => ({ toast: toasts }))
|
||||
const shareLinks = vi.hoisted(() => ({ on: true }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-share-links-flag', () => ({
|
||||
cloudShareLinksEnabled: () => shareLinks.on
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
cloudTeamSharingEnabled: () => shareLinks.on
|
||||
}))
|
||||
|
||||
import { copyCloudWorkspaceLink } from './cloud-workspace-share-link'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// A cloud workspace's share link: the org slug + W-number link when known, else the sandbox-id form.
|
||||
import { cloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import { toast } from 'sonner'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import {
|
||||
@@ -49,7 +49,7 @@ export async function copyCloudWorkspaceLink(
|
||||
options: { quiet?: boolean } = {}
|
||||
): Promise<boolean> {
|
||||
// SHARE-LINKS-HOLD: nothing is copied while share links are held.
|
||||
if (!cloudShareLinksEnabled()) {
|
||||
if (!cloudTeamSharingEnabled()) {
|
||||
return false
|
||||
}
|
||||
const link = await shareLinkFor(id, chatId)
|
||||
|
||||
@@ -3,8 +3,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }))
|
||||
vi.mock('sonner', () => ({ toast }))
|
||||
const shareLinks = vi.hoisted(() => ({ on: true }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-share-links-flag', () => ({
|
||||
cloudShareLinksEnabled: () => shareLinks.on
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
cloudTeamSharingEnabled: () => shareLinks.on
|
||||
}))
|
||||
|
||||
import { copyCloudWorkspaceLink, shareLinkFor } from './open-cloud-workspace'
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import { TriangleAlert } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -54,6 +55,7 @@ export function LocalCommandApprovalDialogView({
|
||||
/** Denies this request and turns local commands off for the workspace. */
|
||||
onTurnOff: () => void
|
||||
}): React.JSX.Element {
|
||||
const teamSharing = useCloudTeamSharingEnabled()
|
||||
const t = useTranslate()
|
||||
// A long command must be scrolled to its end before it can be allowed: nothing stays out of view.
|
||||
const [readToEnd, setReadToEnd] = useState(false)
|
||||
@@ -164,7 +166,8 @@ export function LocalCommandApprovalDialogView({
|
||||
)}
|
||||
</p>
|
||||
) : null}
|
||||
{prompt.shared ? (
|
||||
{/* TEAM-SHARING-HOLD: no teammates can message while sharing is held. */}
|
||||
{prompt.shared && teamSharing ? (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t(
|
||||
'localCommands.prompt.shared',
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
// @vitest-environment happy-dom
|
||||
// TEAM-SHARING-HOLD: the approval dialog says nothing about teammates while team sharing is held.
|
||||
import { act } from 'react'
|
||||
import { createRoot, type Root } from 'react-dom/client'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const teamSharing = vi.hoisted(() => ({ on: false }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
cloudTeamSharingEnabled: () => teamSharing.on,
|
||||
useCloudTeamSharingEnabled: () => teamSharing.on
|
||||
}))
|
||||
|
||||
import { Dialog } from '@/components/ui/dialog'
|
||||
import { TooltipProvider } from '@/components/ui/tooltip'
|
||||
import { LocalCommandApprovalDialogView } from './LocalCommandApprovalDialog'
|
||||
|
||||
globalThis.IS_REACT_ACT_ENVIRONMENT = true
|
||||
let root: Root | null = null
|
||||
afterEach(async () => {
|
||||
await act(async () => root?.unmount())
|
||||
root = null
|
||||
document.body.innerHTML = ''
|
||||
})
|
||||
|
||||
async function show(): Promise<string> {
|
||||
const container = document.createElement('div')
|
||||
document.body.appendChild(container)
|
||||
root = createRoot(container)
|
||||
const prompt = {
|
||||
requestId: 'r1',
|
||||
workspace: 'web',
|
||||
command: 'ls -la',
|
||||
cwd: '/tmp',
|
||||
shared: true,
|
||||
timeoutSeconds: 120
|
||||
}
|
||||
await act(async () =>
|
||||
root!.render(
|
||||
<TooltipProvider>
|
||||
<Dialog open>
|
||||
<LocalCommandApprovalDialogView
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the view reads only these prompt fields here.
|
||||
prompt={prompt as never}
|
||||
waitingCount={0}
|
||||
ready
|
||||
busy={false}
|
||||
onDecide={() => {}}
|
||||
onTurnOff={() => {}}
|
||||
/>
|
||||
</Dialog>
|
||||
</TooltipProvider>
|
||||
)
|
||||
)
|
||||
return document.body.textContent ?? ''
|
||||
}
|
||||
|
||||
describe('the teammates note on a local command request', () => {
|
||||
it('held: no mention of teammates', async () => {
|
||||
teamSharing.on = false
|
||||
expect(await show()).not.toContain('Teammates share this workspace')
|
||||
})
|
||||
|
||||
it('sharing on: says a teammate may have led to it', async () => {
|
||||
teamSharing.on = true
|
||||
expect(await show()).toContain('Teammates share this workspace')
|
||||
})
|
||||
})
|
||||
@@ -78,21 +78,21 @@ const entry = (status: HostedWorkspaceStatus): CloudStatusEntry => ({
|
||||
})
|
||||
|
||||
const FOLDER = '/Users/me/orca/cloud/Hello-World/fix-login-redirect'
|
||||
function syncView(id: string, mirror: boolean, empty = false): CloudSyncView {
|
||||
const openPath = mirror ? FOLDER : `${FOLDER}/.context`
|
||||
function syncView(id: string, empty = false): CloudSyncView {
|
||||
const openPath = `${FOLDER}/.context`
|
||||
return {
|
||||
workspaceId: id,
|
||||
choice: { context: true, mirror },
|
||||
choice: { context: true },
|
||||
folder: FOLDER,
|
||||
phase: 'synced',
|
||||
files: empty ? 0 : mirror ? 1_204 : 12,
|
||||
bytes: empty ? 0 : mirror ? 38_400_000 : 640_000,
|
||||
files: empty ? 0 : 12,
|
||||
bytes: empty ? 0 : 640_000,
|
||||
progress: null,
|
||||
lastSyncedAt: Date.now() - 2 * 60_000,
|
||||
editedHere: 0,
|
||||
skippedLarge: 0,
|
||||
overLimit: 0,
|
||||
limits: { maxBytes: 2_000_000_000, maxFileBytes: 100_000_000 },
|
||||
limits: { maxBytes: 250_000_000, maxFileBytes: 50_000_000 },
|
||||
error: null,
|
||||
openPath,
|
||||
displayPath: openPath.replace('/Users/me', '~')
|
||||
@@ -105,7 +105,6 @@ const AS_OF = new Date(new Date().setHours(14, 31, 0, 0)).getTime()
|
||||
function card({
|
||||
id,
|
||||
state = 'running',
|
||||
mirror = false,
|
||||
emptyContext = false,
|
||||
attention = null,
|
||||
layer = 'main',
|
||||
@@ -114,7 +113,6 @@ function card({
|
||||
}: {
|
||||
id: string
|
||||
state?: CloudDotState
|
||||
mirror?: boolean
|
||||
emptyContext?: boolean
|
||||
attention?: CloudCardAttention | null
|
||||
layer?: CloudCardLayer
|
||||
@@ -122,7 +120,7 @@ function card({
|
||||
paired?: boolean
|
||||
}) {
|
||||
// Seeded once, outside render: the card reads it through the same store as the live app.
|
||||
seedCloudSyncView(syncView(id, mirror, emptyContext))
|
||||
seedCloudSyncView(syncView(id, emptyContext))
|
||||
return defineFixture({
|
||||
width: 320,
|
||||
// A paired card is registered as paired (PAIRED-STATUS), as the app does for its row.
|
||||
@@ -168,10 +166,8 @@ export const runningNotStarted = card({
|
||||
})
|
||||
/** Details open: the bars, uptime and sandbox hours. */
|
||||
export const detailsOpen = card({ id: 'card-details', details: true })
|
||||
/** The sub-panel with the mirror off: the two switches and the .context status. */
|
||||
export const onComputerMirrorOff = card({ id: 'card-sync-off', layer: 'onComputer' })
|
||||
/** The sub-panel with the mirror on: where the files are, Open folder and Copy path. */
|
||||
export const onComputerMirrorOn = card({ id: 'card-sync-on', layer: 'onComputer', mirror: true })
|
||||
/** The sub-panel: the .context switch, its status, where the files are, Open folder and Copy path. */
|
||||
export const onComputer = card({ id: 'card-sync', layer: 'onComputer' })
|
||||
|
||||
/** The ⋯ menu open: Details, Restart, Move to this computer; Archive and Delete after a separator. */
|
||||
export const menuOpen = defineFixture({
|
||||
@@ -320,7 +316,7 @@ export const besideSidebar = defineFixture({
|
||||
idsLoaded: true,
|
||||
status: { [PLACEMENT_ID]: entry(running) }
|
||||
})
|
||||
seedCloudSyncView(syncView(PLACEMENT_ID, false))
|
||||
seedCloudSyncView(syncView(PLACEMENT_ID))
|
||||
},
|
||||
render: () => (
|
||||
<div className="flex h-[420px] bg-background">
|
||||
|
||||
@@ -10,7 +10,6 @@ import { useIsWorktreeGoingToSleep } from '@/lib/worktree-sleep-view'
|
||||
import { CloudWorkspaceStatusPanel } from './CloudWorkspaceStatusPanel'
|
||||
import { useCloudStatusPolling, useCloudWorkspaceView } from './use-cloud-workspace-view'
|
||||
import { useCloudPanelActions } from './use-cloud-panel-actions'
|
||||
import { onCloudSyncFocusRequest } from '@/lib/orca-cloud/cloud-sync-store'
|
||||
|
||||
const PANEL_POLL_MS = 5_000
|
||||
const HOVER_OPEN_MS = 250
|
||||
@@ -104,15 +103,6 @@ function CloudWorkspaceMarkInner({
|
||||
timer.current = setTimeout(() => setOpen(null), HOVER_CLOSE_MS)
|
||||
}
|
||||
}
|
||||
// "Mirror to this computer…" in the workspace menu opens this panel on its sync section.
|
||||
useEffect(
|
||||
() =>
|
||||
onCloudSyncFocusRequest(workspaceId, () => {
|
||||
clearTimer()
|
||||
setOpen('pinned')
|
||||
}),
|
||||
[workspaceId, clearTimer]
|
||||
)
|
||||
useCloudStatusPolling(workspaceId, PANEL_POLL_MS, open !== null)
|
||||
const close = useCallback(() => setOpen(null), [])
|
||||
const actions = useCloudPanelActions(workspaceId, close)
|
||||
|
||||
@@ -1,20 +1,11 @@
|
||||
import React, { useContext } from 'react'
|
||||
import { useCloudShareLinksEnabled } from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import { ArchiveSnapshotTooltip } from './ArchiveSnapshotTooltip'
|
||||
import { toast } from 'sonner'
|
||||
import {
|
||||
Archive,
|
||||
ArchiveRestore,
|
||||
HardDriveDownload,
|
||||
Link2,
|
||||
Lock,
|
||||
RotateCw,
|
||||
Users
|
||||
} from 'lucide-react'
|
||||
import { Archive, ArchiveRestore, Link2, Lock, RotateCw, Users } from 'lucide-react'
|
||||
import { DropdownMenuItem, DropdownMenuSeparator } from '@/components/ui/dropdown-menu'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { toastSharedWithTeam } from '@/components/cloud-workspaces/shared-with-team-toast'
|
||||
import { isCloudSyncAvailable, requestCloudSyncFocus } from '@/lib/orca-cloud/cloud-sync-store'
|
||||
import {
|
||||
ConfirmationDialogContext,
|
||||
type ConfirmationDialogContextValue
|
||||
@@ -32,8 +23,6 @@ import {
|
||||
type CloudWorkspace
|
||||
} from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import { useCloudWorkspaceView } from './use-cloud-workspace-view'
|
||||
import { useCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store'
|
||||
import { isPairedCloudStatusRow } from '@/lib/orca-cloud/orca-cloud-workspace-rows'
|
||||
import { useCloudPanelActions } from './use-cloud-panel-actions'
|
||||
import { useCloudWorkspaceRecord } from './use-cloud-workspace-record'
|
||||
|
||||
@@ -70,11 +59,9 @@ function CloudMenuRows({
|
||||
}): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const actions = useCloudPanelActions(worktreeId, noop)
|
||||
const { workspace, reload } = useCloudWorkspaceRecord(worktreeId, hostId)
|
||||
const { workspace, loaded, reload } = useCloudWorkspaceRecord(worktreeId, hostId)
|
||||
const confirm = useContext(ConfirmationDialogContext)
|
||||
const busy = view.pending !== undefined
|
||||
// Mirroring syncs this desktop's own cloud workspaces; a paired one has no synced copy here.
|
||||
const paired = useCloudWorkspace((state) => isPairedCloudStatusRow(state, worktreeId))
|
||||
const archived = view.state === 'archived'
|
||||
const groups = cloudWorkspaceActionGroups({
|
||||
surface: 'sidebar',
|
||||
@@ -97,12 +84,6 @@ function CloudMenuRows({
|
||||
{t('orcaCloudWorkspace.restart', 'Restart')}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{isCloudSyncAvailable() && view.state !== 'archived' && !paired ? (
|
||||
<DropdownMenuItem onSelect={() => requestCloudSyncFocus(worktreeId)}>
|
||||
<HardDriveDownload className="size-3.5" />
|
||||
{t('orcaCloudSync.menuItem', 'Mirror to this computer…')}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{has('archive') && actions.onArchive ? (
|
||||
<ArchiveSnapshotTooltip side="left">
|
||||
<DropdownMenuItem disabled={busy || view.state === 'waking'} onSelect={actions.onArchive}>
|
||||
@@ -117,12 +98,17 @@ function CloudMenuRows({
|
||||
{t('orcaCloudWorkspace.unarchive', 'Unarchive')}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{workspace && (has('share') || has('makePrivate')) ? (
|
||||
{/* Before the first answer for this row (it's fetched on row hover, so rarely), the rows
|
||||
show disabled instead of appearing under the pointer a moment later. */}
|
||||
{(workspace || !loaded) && (has('share') || has('makePrivate')) ? (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
{has('share') ? (
|
||||
<DropdownMenuItem
|
||||
onSelect={() => void setVisibility(workspace, 'team', { reload, t, confirm })}
|
||||
disabled={!workspace}
|
||||
onSelect={() =>
|
||||
workspace && void setVisibility(workspace, 'team', { reload, t, confirm })
|
||||
}
|
||||
>
|
||||
<Users className="size-3.5" />
|
||||
{t('auto.components.cloudWorkspaces.shareWithTeam', 'Share with team')}
|
||||
@@ -130,7 +116,10 @@ function CloudMenuRows({
|
||||
) : null}
|
||||
{has('makePrivate') ? (
|
||||
<DropdownMenuItem
|
||||
onSelect={() => void setVisibility(workspace, 'private', { reload, t, confirm })}
|
||||
disabled={!workspace}
|
||||
onSelect={() =>
|
||||
workspace && void setVisibility(workspace, 'private', { reload, t, confirm })
|
||||
}
|
||||
>
|
||||
<Lock className="size-3.5" />
|
||||
{t('auto.components.cloudWorkspaces.makePrivate', 'Make private')}
|
||||
@@ -202,16 +191,20 @@ export function CloudCopyWorkspaceLinkItem({
|
||||
hostId?: string | null
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const { workspace } = useCloudWorkspaceRecord(worktreeId, hostId ?? null)
|
||||
const { workspace, loaded } = useCloudWorkspaceRecord(worktreeId, hostId ?? null)
|
||||
// SHARE-LINKS-HOLD: no way to produce a share link while it's held.
|
||||
const shareLinks = useCloudShareLinksEnabled()
|
||||
if (!workspace || !shareLinks) {
|
||||
const shareLinks = useCloudTeamSharingEnabled()
|
||||
// Not asked yet: disabled in place rather than appearing a moment later.
|
||||
if ((!workspace && loaded) || !shareLinks) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
<DropdownMenuItem onSelect={() => void copyCloudWorkspaceLink(workspace.id)}>
|
||||
<DropdownMenuItem
|
||||
disabled={!workspace}
|
||||
onSelect={() => workspace && void copyCloudWorkspaceLink(workspace.id)}
|
||||
>
|
||||
<Link2 className="size-3.5" />
|
||||
{workspace.number
|
||||
{workspace?.number
|
||||
? t('auto.components.cloudWorkspaces.linkToNumber', 'Link to {{number}}', {
|
||||
number: formatWorkspaceNumber(workspace.number)
|
||||
})
|
||||
|
||||
@@ -312,8 +312,8 @@ export function CloudWorkspaceStatusPanel({
|
||||
</p>
|
||||
) : null}
|
||||
|
||||
{/* ARCHIVED-DEAD-ACTIONS: .context sync and mirroring run for this desktop's own cloud
|
||||
workspaces only, so a paired card doesn't offer them. */}
|
||||
{/* ARCHIVED-DEAD-ACTIONS: .context sync runs for this desktop's own cloud workspaces only,
|
||||
so a paired card doesn't offer it. */}
|
||||
{state === 'archived' || paired ? null : (
|
||||
<OnComputerRow view={sync} onOpen={() => setLayer('onComputer')} />
|
||||
)}
|
||||
|
||||
@@ -49,11 +49,10 @@ const entry = (status: HostedWorkspaceStatus): CloudStatusEntry => ({
|
||||
const FOLDER = '/Users/me/orca/cloud/Hello-World/fix-login-redirect'
|
||||
|
||||
function view(id: string, over: Partial<CloudSyncView>): CloudSyncView {
|
||||
const choice = over.choice ?? { context: true, mirror: false }
|
||||
const openPath = choice.mirror ? FOLDER : `${FOLDER}/.context`
|
||||
const openPath = `${FOLDER}/.context`
|
||||
return {
|
||||
workspaceId: id,
|
||||
choice,
|
||||
choice: { context: true },
|
||||
folder: FOLDER,
|
||||
phase: 'synced',
|
||||
files: 12,
|
||||
@@ -63,9 +62,7 @@ function view(id: string, over: Partial<CloudSyncView>): CloudSyncView {
|
||||
editedHere: 0,
|
||||
skippedLarge: 0,
|
||||
overLimit: 0,
|
||||
limits: choice.mirror
|
||||
? { maxBytes: 2_000_000_000, maxFileBytes: 100_000_000 }
|
||||
: { maxBytes: 250_000_000, maxFileBytes: 50_000_000 },
|
||||
limits: { maxBytes: 250_000_000, maxFileBytes: 50_000_000 },
|
||||
error: null,
|
||||
openPath,
|
||||
displayPath: openPath.replace('/Users/me', '~'),
|
||||
@@ -99,7 +96,7 @@ function panel(
|
||||
})
|
||||
}
|
||||
|
||||
/** Default: `.context` on, mirror off. */
|
||||
/** Default: `.context` on. */
|
||||
export const contextSynced = panel('fx-context', {})
|
||||
export const contextSyncing = panel('fx-context-start', {
|
||||
phase: 'starting',
|
||||
@@ -107,47 +104,31 @@ export const contextSyncing = panel('fx-context-start', {
|
||||
bytes: 0,
|
||||
lastSyncedAt: null
|
||||
})
|
||||
export const mirrorCopying = panel('fx-mirror-copying', {
|
||||
choice: { context: true, mirror: true },
|
||||
export const contextCopying = panel('fx-context-copying', {
|
||||
phase: 'copying',
|
||||
progress: { done: 120, total: 1_204 }
|
||||
})
|
||||
export const mirrorSynced = panel('fx-mirror', {
|
||||
choice: { context: true, mirror: true },
|
||||
files: 1_204,
|
||||
bytes: 38_400_000,
|
||||
lastSyncedAt: Date.now() - 2 * 60_000
|
||||
progress: { done: 12, total: 48 }
|
||||
})
|
||||
export const asleepWaiting = panel(
|
||||
'fx-asleep',
|
||||
{
|
||||
choice: { context: true, mirror: true },
|
||||
phase: 'waiting',
|
||||
files: 1_204,
|
||||
bytes: 38_400_000,
|
||||
lastSyncedAt: Date.now() - 63 * 60_000
|
||||
},
|
||||
'sleeping'
|
||||
)
|
||||
export const editedHere = panel('fx-edited', {
|
||||
choice: { context: true, mirror: true },
|
||||
files: 1_204,
|
||||
bytes: 38_400_000,
|
||||
editedHere: 3
|
||||
})
|
||||
export const editedHere = panel('fx-edited', { editedHere: 3 })
|
||||
export const overLimit = panel('fx-limit', {
|
||||
choice: { context: true, mirror: true },
|
||||
files: 61_000,
|
||||
bytes: 1_990_000_000,
|
||||
overLimit: 812,
|
||||
files: 4_820,
|
||||
bytes: 249_000_000,
|
||||
overLimit: 180,
|
||||
skippedLarge: 2
|
||||
})
|
||||
export const syncError = panel('fx-error', {
|
||||
phase: 'error',
|
||||
error: 'worktree_not_found'
|
||||
})
|
||||
export const bothOff = panel('fx-off', {
|
||||
choice: { context: false, mirror: false },
|
||||
export const syncOff = panel('fx-off', {
|
||||
choice: { context: false },
|
||||
phase: 'off',
|
||||
files: 0,
|
||||
bytes: 0,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// The card's "On this computer" sub-panel: `.context` sync (on by default) and the read-only mirror
|
||||
// (off by default); with the mirror on, where the files are and how current they are. Quiet by
|
||||
// design: no toasts; progress is announced politely and at most every ~10 s.
|
||||
// The card's "On this computer" sub-panel: `.context` sync (on by default), where the files are
|
||||
// and how current they are. Quiet by design: no toasts; progress is announced politely and at
|
||||
// most every ~10 s.
|
||||
import React, { useContext, useEffect, useId, useRef, useState } from 'react'
|
||||
import { ConfirmationDialogContext } from '@/components/confirmation-dialog-context'
|
||||
import { Copy, FolderOpen } from 'lucide-react'
|
||||
@@ -14,9 +14,7 @@ import {
|
||||
openCloudSyncFolder,
|
||||
retryCloudSync,
|
||||
setCloudSyncChoice,
|
||||
takeCloudSyncFocus,
|
||||
useCloudSync,
|
||||
useCloudSyncFocusRequest
|
||||
useCloudSync
|
||||
} from '@/lib/orca-cloud/cloud-sync-store'
|
||||
import type { CloudSyncView } from '../../../../shared/cloud-sync/cloud-sync-contract'
|
||||
|
||||
@@ -74,7 +72,7 @@ function ago(t: T, at: number, now: number): string {
|
||||
: t('orcaCloudSync.hoursAgo', '{{count}} h ago', { count: Math.floor(minutes / 60) })
|
||||
}
|
||||
|
||||
/** The status line under the switches. */
|
||||
/** The status line under the switch. */
|
||||
export function cloudSyncStatusLine(view: CloudSyncView, t: T, now: number): string | null {
|
||||
if (view.phase === 'off') {
|
||||
return null
|
||||
@@ -127,14 +125,12 @@ function SyncRow({
|
||||
label,
|
||||
description,
|
||||
checked,
|
||||
onCheckedChange,
|
||||
switchRef
|
||||
onCheckedChange
|
||||
}: {
|
||||
label: string
|
||||
description: string
|
||||
checked: boolean
|
||||
onCheckedChange: (next: boolean) => void
|
||||
switchRef?: React.Ref<HTMLButtonElement>
|
||||
}): React.JSX.Element {
|
||||
const id = useId()
|
||||
return (
|
||||
@@ -148,7 +144,6 @@ function SyncRow({
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
ref={switchRef}
|
||||
id={`${id}-switch`}
|
||||
aria-describedby={`${id}-desc`}
|
||||
checked={checked}
|
||||
@@ -201,21 +196,16 @@ export function CloudWorkspaceSyncSection({
|
||||
const live = useCloudSync(workspaceId)
|
||||
const view = injected === undefined ? live : injected
|
||||
const now = useNow(30_000)
|
||||
const section = useRef<HTMLElement | null>(null)
|
||||
const mirrorSwitch = useRef<HTMLButtonElement | null>(null)
|
||||
const focusRequested = useCloudSyncFocusRequest(workspaceId)
|
||||
const [copied, setCopied] = useState(false)
|
||||
const announcement = useAnnouncement(view, t)
|
||||
const confirm = useContext(ConfirmationDialogContext)
|
||||
|
||||
/** Turning a row off removes copies; changed ones are only removed after asking (as archive/delete). */
|
||||
const choose = async (patch: { context?: boolean; mirror?: boolean }): Promise<void> => {
|
||||
/** Turning sync off removes copies; changed ones are only removed after asking (as archive/delete). */
|
||||
const choose = async (context: boolean): Promise<void> => {
|
||||
if (!view) {
|
||||
return
|
||||
}
|
||||
const next = { ...view.choice, ...patch }
|
||||
const removes = (view.choice.mirror && !next.mirror) || (!next.context && !next.mirror)
|
||||
if (removes && view.editedHere > 0 && confirm) {
|
||||
if (!context && view.choice.context && view.editedHere > 0 && confirm) {
|
||||
const ok = await confirm({
|
||||
title: t('orcaCloudSync.removeConfirmTitle', 'Remove the copy on this computer?'),
|
||||
description: t(
|
||||
@@ -234,35 +224,19 @@ export function CloudWorkspaceSyncSection({
|
||||
return
|
||||
}
|
||||
}
|
||||
await setCloudSyncChoice(workspaceId, patch)
|
||||
await setCloudSyncChoice(workspaceId, { context })
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!focusRequested || !view) {
|
||||
return
|
||||
}
|
||||
// After the popover's own open-focus, which runs once this effect has.
|
||||
const frame = requestAnimationFrame(() => {
|
||||
if (takeCloudSyncFocus(workspaceId)) {
|
||||
section.current?.scrollIntoView({ block: 'nearest' })
|
||||
mirrorSwitch.current?.focus()
|
||||
}
|
||||
})
|
||||
return () => cancelAnimationFrame(frame)
|
||||
}, [focusRequested, view, workspaceId])
|
||||
|
||||
if (!view) {
|
||||
return null
|
||||
}
|
||||
const on = view.choice.context || view.choice.mirror
|
||||
const mirror = view.choice.mirror
|
||||
const on = view.choice.context
|
||||
const status = cloudSyncStatusLine(view, t, now)
|
||||
const tooLarge = view.skippedLarge > 0
|
||||
const overLimit = view.overLimit > 0
|
||||
|
||||
return (
|
||||
<section
|
||||
ref={section}
|
||||
aria-labelledby={labelledBy}
|
||||
className="flex flex-col gap-2.5"
|
||||
data-cloud-sync-section={workspaceId}
|
||||
@@ -274,30 +248,14 @@ export function CloudWorkspaceSyncSection({
|
||||
'Plans and screenshots from this workspace, synced to this computer.'
|
||||
)}
|
||||
checked={view.choice.context}
|
||||
onCheckedChange={(next) => void choose({ context: next })}
|
||||
onCheckedChange={(next) => void choose(next)}
|
||||
/>
|
||||
{on && !mirror && status ? (
|
||||
<p className="-mt-1 tabular-nums text-muted-foreground" data-cloud-sync-status="context">
|
||||
{on && status ? (
|
||||
<p className="-mt-1 tabular-nums text-muted-foreground" data-cloud-sync-status>
|
||||
{status}
|
||||
</p>
|
||||
) : null}
|
||||
<SyncRow
|
||||
switchRef={mirrorSwitch}
|
||||
label={t('orcaCloudSync.mirrorLabel', 'Mirror to this computer')}
|
||||
description={t(
|
||||
'orcaCloudSync.mirrorHelper',
|
||||
'A read-only copy of this workspace’s files, kept up to date while it runs.'
|
||||
)}
|
||||
checked={view.choice.mirror}
|
||||
onCheckedChange={(next) => void choose({ mirror: next })}
|
||||
/>
|
||||
|
||||
{mirror && status ? (
|
||||
<p className="-mt-1 tabular-nums text-muted-foreground" data-cloud-sync-status="mirror">
|
||||
{status}
|
||||
</p>
|
||||
) : null}
|
||||
{mirror ? (
|
||||
{on ? (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<code
|
||||
className="block min-w-0 break-words rounded bg-muted/50 px-1.5 py-0.5 font-mono text-[11px] text-foreground"
|
||||
@@ -365,7 +323,7 @@ export function CloudWorkspaceSyncSection({
|
||||
overLimit
|
||||
? t(
|
||||
'orcaCloudSync.overLimit',
|
||||
'The mirror is limited to {{size}}. Larger files and anything past the limit aren’t copied.',
|
||||
'The .context folder is limited to {{size}}. Larger files and anything past the limit aren’t copied.',
|
||||
{ size: syncSize(t, view.limits.maxBytes) }
|
||||
)
|
||||
: t('orcaCloudSync.tooLarge', 'Files over {{size}} aren’t copied.', {
|
||||
|
||||
@@ -56,16 +56,10 @@ describe('calm cloud workspace card', () => {
|
||||
|
||||
it('sums up On this computer in a few words', () => {
|
||||
expect(cloudCardOnComputerStatus(null, t)).toBe('Off')
|
||||
expect(cloudCardOnComputerStatus(sync({ context: false, mirror: false }, 'off'), t)).toBe('Off')
|
||||
expect(cloudCardOnComputerStatus(sync({ context: true, mirror: false }), t)).toBe(
|
||||
'.context synced'
|
||||
)
|
||||
expect(cloudCardOnComputerStatus(sync({ context: true, mirror: true }), t)).toBe(
|
||||
'Mirroring · .context synced'
|
||||
)
|
||||
expect(cloudCardOnComputerStatus(sync({ context: true, mirror: true }, 'error'), t)).toBe(
|
||||
'Couldn’t sync'
|
||||
)
|
||||
expect(cloudCardOnComputerStatus(sync({ context: false }, 'off'), t)).toBe('Off')
|
||||
expect(cloudCardOnComputerStatus(sync({ context: true }), t)).toBe('.context synced')
|
||||
expect(cloudCardOnComputerStatus(sync({ context: true }, 'copying'), t)).toBe('Syncing…')
|
||||
expect(cloudCardOnComputerStatus(sync({ context: true }, 'error'), t)).toBe('Couldn’t sync')
|
||||
})
|
||||
|
||||
it('keeps one footer action per state; Restart only where it is the fix', () => {
|
||||
|
||||
@@ -124,7 +124,7 @@ export function cloudCardAttentionLabel(item: CloudCardAttention, t: Translate):
|
||||
|
||||
/** The "On this computer ›" row's short status. */
|
||||
export function cloudCardOnComputerStatus(view: CloudSyncView | null, t: Translate): string {
|
||||
if (!view || (!view.choice.context && !view.choice.mirror)) {
|
||||
if (!view || !view.choice.context) {
|
||||
return t('orcaCloudWorkspace.card.syncOff', 'Off')
|
||||
}
|
||||
if (view.phase === 'error') {
|
||||
@@ -133,12 +133,7 @@ export function cloudCardOnComputerStatus(view: CloudSyncView | null, t: Transla
|
||||
if (view.phase === 'starting' || view.phase === 'copying') {
|
||||
return t('orcaCloudSync.syncing', 'Syncing…')
|
||||
}
|
||||
if (view.choice.mirror && view.choice.context) {
|
||||
return t('orcaCloudWorkspace.card.mirroringAndContext', 'Mirroring · .context synced')
|
||||
}
|
||||
return view.choice.mirror
|
||||
? t('orcaCloudWorkspace.card.mirroring', 'Mirroring')
|
||||
: t('orcaCloudWorkspace.card.contextSynced', '.context synced')
|
||||
return t('orcaCloudWorkspace.card.contextSynced', '.context synced')
|
||||
}
|
||||
|
||||
export type CloudCardPrimary = 'sleep' | 'wake' | 'restart' | 'unarchive' | null
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
// @vitest-environment happy-dom
|
||||
// Menu rows that need the team's record are there on the menu's first paint: the record is kept
|
||||
// per row and fetched on row hover, not first asked for when the menu opens.
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import {
|
||||
prefetchCloudWorkspaceRecord,
|
||||
RECORD_FRESH_MS,
|
||||
resetCloudWorkspaceRecordsForTests,
|
||||
useCloudWorkspaceRecord
|
||||
} from './use-cloud-workspace-record'
|
||||
|
||||
const T0 = 1_700_000_000_000
|
||||
|
||||
const bridge = {
|
||||
localWorkspaces: vi.fn(async () => [{ worktreeId: 'w', sandboxId: 'sbx' }]),
|
||||
environmentBindings: vi.fn(async () => ({})),
|
||||
get: vi.fn(async () => ({ ok: true, value: { id: 'sbx', visibility: 'private' } }))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: T0, toFake: ['Date'] })
|
||||
resetCloudWorkspaceRecordsForTests()
|
||||
vi.clearAllMocks()
|
||||
Object.assign(window, { api: { cloudWorkspaces: bridge } })
|
||||
})
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
Object.assign(window, { api: undefined })
|
||||
})
|
||||
|
||||
describe('useCloudWorkspaceRecord', () => {
|
||||
it('a menu opened after row hover has the record on its first render', async () => {
|
||||
await prefetchCloudWorkspaceRecord('w', null)
|
||||
const { result } = renderHook(() => useCloudWorkspaceRecord('w', null))
|
||||
expect(result.current.loaded).toBe(true)
|
||||
expect(result.current.workspace?.id).toBe('sbx')
|
||||
})
|
||||
|
||||
it('says not loaded until the first answer, then updates in place', async () => {
|
||||
const { result } = renderHook(() => useCloudWorkspaceRecord('w', null))
|
||||
expect(result.current.loaded).toBe(false)
|
||||
await act(() => prefetchCloudWorkspaceRecord('w', null))
|
||||
expect(result.current.loaded).toBe(true)
|
||||
expect(result.current.workspace?.id).toBe('sbx')
|
||||
})
|
||||
|
||||
it('hovering again while fresh asks nothing; a stale record is refreshed', async () => {
|
||||
await Promise.all([
|
||||
prefetchCloudWorkspaceRecord('w', null, T0),
|
||||
prefetchCloudWorkspaceRecord('w', null, T0)
|
||||
])
|
||||
expect(bridge.get).toHaveBeenCalledOnce()
|
||||
await prefetchCloudWorkspaceRecord('w', null, T0 + 1)
|
||||
expect(bridge.get).toHaveBeenCalledOnce()
|
||||
await prefetchCloudWorkspaceRecord('w', null, T0 + RECORD_FRESH_MS)
|
||||
expect(bridge.get).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
})
|
||||
@@ -1,37 +1,94 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { useCallback, useEffect, useSyncExternalStore } from 'react'
|
||||
import type { CloudWorkspace } from '../../../../shared/cloud-workspaces/cloud-workspaces-wire'
|
||||
import { toRuntimeExecutionHostId } from '../../../../shared/execution-host'
|
||||
|
||||
/**
|
||||
* The team's record of the cloud workspace behind a sidebar row (visibility, access), so the
|
||||
* sidebar menu can offer the same Share actions as Home. Owned workspaces are found through this
|
||||
* desktop's runtime; paired ones through their pairing. Null until loaded or when there is none.
|
||||
* desktop's runtime; paired ones through their pairing.
|
||||
*
|
||||
* Kept per row across menu openings (last known), and fetched before the menu opens (row hover),
|
||||
* so the menu's rows are there on its first paint instead of appearing a second later. A record
|
||||
* older than RECORD_FRESH_MS is shown and refreshed in the background.
|
||||
*/
|
||||
export const RECORD_FRESH_MS = 30_000
|
||||
|
||||
type Entry = { workspace: CloudWorkspace | null; at: number }
|
||||
|
||||
const records = new Map<string, Entry>()
|
||||
const inFlight = new Map<string, Promise<void>>()
|
||||
const listeners = new Set<() => void>()
|
||||
|
||||
function key(worktreeId: string, hostId: string | null | undefined): string {
|
||||
return `${worktreeId}\0${hostId ?? ''}`
|
||||
}
|
||||
|
||||
function api(): NonNullable<Window['api']>['cloudWorkspaces'] | undefined {
|
||||
return typeof window !== 'undefined' ? window.api?.cloudWorkspaces : undefined
|
||||
}
|
||||
|
||||
function fetchRecord(worktreeId: string, hostId: string | null | undefined): Promise<void> {
|
||||
const bridge = api()
|
||||
const k = key(worktreeId, hostId)
|
||||
if (!bridge) {
|
||||
return Promise.resolve()
|
||||
}
|
||||
const running = inFlight.get(k)
|
||||
if (running) {
|
||||
return running
|
||||
}
|
||||
const run = (async () => {
|
||||
const sandboxId = await resolveSandboxId(bridge, worktreeId, hostId)
|
||||
const result = sandboxId ? await bridge.get(sandboxId).catch(() => null) : null
|
||||
records.set(k, { workspace: result?.ok ? result.value : null, at: Date.now() })
|
||||
for (const listener of listeners) {
|
||||
listener()
|
||||
}
|
||||
})().finally(() => inFlight.delete(k))
|
||||
inFlight.set(k, run)
|
||||
return run
|
||||
}
|
||||
|
||||
/** Loads the record unless a fresh one is known; for row hover, before any menu opens. Resolves
|
||||
* when that load (or the one already running) is done. */
|
||||
export function prefetchCloudWorkspaceRecord(
|
||||
worktreeId: string,
|
||||
hostId: string | null | undefined,
|
||||
now = Date.now()
|
||||
): Promise<void> {
|
||||
const known = records.get(key(worktreeId, hostId))
|
||||
if (!known || now - known.at >= RECORD_FRESH_MS) {
|
||||
return fetchRecord(worktreeId, hostId)
|
||||
}
|
||||
return Promise.resolve()
|
||||
}
|
||||
|
||||
/**
|
||||
* `workspace`: the last known record, null when there is none. `loaded`: false only until the
|
||||
* first answer for this row, the one time a caller can't yet tell "none" from "not asked".
|
||||
*/
|
||||
export function useCloudWorkspaceRecord(
|
||||
worktreeId: string,
|
||||
hostId: string | null | undefined
|
||||
): { workspace: CloudWorkspace | null; reload: () => void } {
|
||||
const [workspace, setWorkspace] = useState<CloudWorkspace | null>(null)
|
||||
const [generation, setGeneration] = useState(0)
|
||||
): { workspace: CloudWorkspace | null; loaded: boolean; reload: () => void } {
|
||||
const entry = useSyncExternalStore(
|
||||
(listener) => {
|
||||
listeners.add(listener)
|
||||
return () => listeners.delete(listener)
|
||||
},
|
||||
() => records.get(key(worktreeId, hostId))
|
||||
)
|
||||
useEffect(() => {
|
||||
const api = typeof window !== 'undefined' ? window.api?.cloudWorkspaces : undefined
|
||||
if (!api) {
|
||||
return
|
||||
}
|
||||
let cancelled = false
|
||||
void (async () => {
|
||||
const sandboxId = await resolveSandboxId(api, worktreeId, hostId)
|
||||
const result = sandboxId ? await api.get(sandboxId).catch(() => null) : null
|
||||
if (!cancelled) {
|
||||
setWorkspace(result?.ok ? result.value : null)
|
||||
}
|
||||
})()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [worktreeId, hostId, generation])
|
||||
const reload = useCallback(() => setGeneration((value) => value + 1), [])
|
||||
return { workspace, reload }
|
||||
void prefetchCloudWorkspaceRecord(worktreeId, hostId)
|
||||
}, [worktreeId, hostId])
|
||||
const reload = useCallback(() => void fetchRecord(worktreeId, hostId), [worktreeId, hostId])
|
||||
return { workspace: entry?.workspace ?? null, loaded: entry !== undefined, reload }
|
||||
}
|
||||
|
||||
/** Tests: forget every record. */
|
||||
export function resetCloudWorkspaceRecordsForTests(): void {
|
||||
records.clear()
|
||||
inFlight.clear()
|
||||
}
|
||||
|
||||
async function resolveSandboxId(
|
||||
|
||||
@@ -29,6 +29,12 @@ const mocks = vi.hoisted(() => {
|
||||
return { state, open: vi.fn(), sleep: vi.fn(), archive: vi.fn() }
|
||||
})
|
||||
|
||||
const teamSharing = vi.hoisted(() => ({ on: true }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink',
|
||||
cloudTeamSharingEnabled: () => teamSharing.on,
|
||||
useCloudTeamSharingEnabled: () => teamSharing.on
|
||||
}))
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: Object.assign(
|
||||
(selector: (s: typeof mocks.state) => unknown) => selector(mocks.state),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// Settings › Workspaces: every cloud workspace on the team, for owners and admins to manage
|
||||
// (Neil, HOME-1: the listing comes back only here). Open, Sleep and Archive use the same flows as
|
||||
// the sidebar and "Open cloud workspace…"; an action the control plane would refuse is not shown.
|
||||
import { useCloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import React, { useEffect, useMemo, useState } from 'react'
|
||||
import { toast } from 'sonner'
|
||||
import { Lock, RefreshCw, Users } from 'lucide-react'
|
||||
@@ -49,6 +50,7 @@ const TEAM_QUERY = { scope: 'team', archived: 'include' } as const
|
||||
|
||||
export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): React.JSX.Element {
|
||||
const t = useTranslate()
|
||||
const teamSharing = useCloudTeamSharingEnabled()
|
||||
const intlLocale = useIntlLocale()
|
||||
const cloud = useAppStore((s) => s.orcaProfileAuthStatus?.cloud)
|
||||
const signIn = useAppStore((s) => s.connectCurrentOrcaProfile)
|
||||
@@ -147,7 +149,7 @@ export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): Rea
|
||||
<col className="w-36" />
|
||||
<col className="w-32" />
|
||||
<col className="w-20" />
|
||||
<col className="w-20" />
|
||||
{teamSharing ? <col className="w-20" /> : null}
|
||||
<col className="w-10" />
|
||||
</colgroup>
|
||||
<thead className="border-b border-border/60 text-left text-muted-foreground">
|
||||
@@ -167,9 +169,12 @@ export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): Rea
|
||||
<th className="px-2 py-2 font-medium">
|
||||
{t('settings.teamWorkspaces.colLastActive', 'Last active')}
|
||||
</th>
|
||||
<th className="px-2 py-2 font-medium">
|
||||
{t('settings.teamWorkspaces.colAccess', 'Access')}
|
||||
</th>
|
||||
{/* TEAM-SHARING-HOLD: no Access column while sharing is held (all private). */}
|
||||
{teamSharing ? (
|
||||
<th className="px-2 py-2 font-medium">
|
||||
{t('settings.teamWorkspaces.colAccess', 'Access')}
|
||||
</th>
|
||||
) : null}
|
||||
<th className="px-2 py-2">
|
||||
<span className="sr-only">
|
||||
{t('settings.teamWorkspaces.colActions', 'Actions')}
|
||||
@@ -219,18 +224,20 @@ export function TeamWorkspacesSettings({ orgId }: { orgId: string | null }): Rea
|
||||
<td className="px-2 py-2 text-muted-foreground tabular-nums">
|
||||
{formatRelative(w.lastActivityAt, now, t, intlLocale)}
|
||||
</td>
|
||||
<td className="px-2 py-2 text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
{w.visibility === 'private' ? (
|
||||
<Lock className="size-3 shrink-0" aria-hidden />
|
||||
) : (
|
||||
<Users className="size-3 shrink-0" aria-hidden />
|
||||
)}
|
||||
{w.visibility === 'private'
|
||||
? t('auto.components.cloudWorkspaces.private', 'Private')
|
||||
: t('settings.teamWorkspaces.shared', 'Shared')}
|
||||
</span>
|
||||
</td>
|
||||
{teamSharing ? (
|
||||
<td className="px-2 py-2 text-muted-foreground">
|
||||
<span className="flex items-center gap-1">
|
||||
{w.visibility === 'private' ? (
|
||||
<Lock className="size-3 shrink-0" aria-hidden />
|
||||
) : (
|
||||
<Users className="size-3 shrink-0" aria-hidden />
|
||||
)}
|
||||
{w.visibility === 'private'
|
||||
? t('auto.components.cloudWorkspaces.private', 'Private')
|
||||
: t('settings.teamWorkspaces.shared', 'Shared')}
|
||||
</span>
|
||||
</td>
|
||||
) : null}
|
||||
<td className="px-2 py-2 text-right">
|
||||
<RowActionsMenu
|
||||
workspace={w}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { cloudTeamSharingEnabled } from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import { SquareTerminal } from 'lucide-react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { InlineError } from '@/components/ui/inline-error'
|
||||
@@ -20,16 +21,22 @@ import { LocalCommandText } from '../../local-commands/LocalCommandText'
|
||||
|
||||
const AUDIT_ROWS = 20
|
||||
|
||||
function workspaceDetail(row: LocalCommandWorkspaceRow, t: Translate): string {
|
||||
function workspaceDetail(
|
||||
row: LocalCommandWorkspaceRow,
|
||||
t: Translate,
|
||||
teamSharing = cloudTeamSharingEnabled()
|
||||
): string {
|
||||
// TEAM-SHARING-HOLD: no mention of sharing while team sharing is held.
|
||||
const shared = teamSharing && row.shared
|
||||
if (row.isOwner === false) {
|
||||
return t('localCommands.settings.notOwner', 'Only the workspace owner can turn this on.')
|
||||
}
|
||||
if (!row.enabled) {
|
||||
return row.shared
|
||||
return shared
|
||||
? t('localCommands.settings.offShared', 'Off · Shared with your team')
|
||||
: t('localCommands.settings.off', 'Off')
|
||||
}
|
||||
const sharing = row.shared
|
||||
const sharing = shared
|
||||
? ` · ${t('localCommands.settings.sharedOn', 'Shared with your team')}`
|
||||
: ''
|
||||
return row.connected
|
||||
@@ -318,7 +325,12 @@ export function OrcaCloudLocalCommandsPane(): React.JSX.Element {
|
||||
surface: 'security',
|
||||
initialFocus: 'cancel'
|
||||
})
|
||||
if (enabling && row.shared && !(allowShared = await confirmShared())) {
|
||||
if (
|
||||
enabling &&
|
||||
row.shared &&
|
||||
cloudTeamSharingEnabled() &&
|
||||
!(allowShared = await confirmShared())
|
||||
) {
|
||||
return
|
||||
}
|
||||
setPendingSandboxId(row.sandboxId)
|
||||
|
||||
@@ -4,8 +4,8 @@ import {
|
||||
} from '../../../../../shared/keybindings/definitions'
|
||||
import {
|
||||
CLOUD_SHARE_LINK_ACTION_ID,
|
||||
cloudShareLinksEnabled
|
||||
} from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
cloudTeamSharingEnabled
|
||||
} from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import type {
|
||||
KeybindingActionId,
|
||||
KeybindingDefinition
|
||||
@@ -36,7 +36,7 @@ export function groupDefinitions(
|
||||
disabledAgentTabActionIds(disabledTuiAgents)
|
||||
)
|
||||
// SHARE-LINKS-HOLD: no ⌘⌥⇧L entry while share links are held.
|
||||
if (!cloudShareLinksEnabled()) {
|
||||
if (!cloudTeamSharingEnabled()) {
|
||||
hiddenAgentActionIds.add(CLOUD_SHARE_LINK_ACTION_ID)
|
||||
}
|
||||
const groups = new Map<string, KeybindingDefinition[]>()
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const shareLinks = vi.hoisted(() => ({ on: false }))
|
||||
vi.mock('@/lib/orca-cloud/cloud-share-links-flag', () => ({
|
||||
vi.mock('@/lib/orca-cloud/cloud-team-sharing-flag', () => ({
|
||||
CLOUD_SHARE_LINK_ACTION_ID: 'cloudWorkspace.copyLink',
|
||||
cloudShareLinksEnabled: () => shareLinks.on
|
||||
cloudTeamSharingEnabled: () => shareLinks.on
|
||||
}))
|
||||
|
||||
import { groupDefinitions } from './shortcut-groups'
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { KEYBINDING_DEFINITIONS } from '../../../../../shared/keybindings/definitions'
|
||||
import {
|
||||
CLOUD_SHARE_LINK_ACTION_ID,
|
||||
cloudShareLinksEnabled
|
||||
} from '@/lib/orca-cloud/cloud-share-links-flag'
|
||||
cloudTeamSharingEnabled
|
||||
} from '@/lib/orca-cloud/cloud-team-sharing-flag'
|
||||
import type { SettingsSearchEntry } from '../search/settings-search'
|
||||
import { translate } from '@/i18n/i18n'
|
||||
import { translateSearchKeyword } from '../search/settings-search-keywords'
|
||||
@@ -67,7 +67,7 @@ export function getShortcutsPaneSearchEntries(options?: {
|
||||
(includeManagedBrowser ||
|
||||
(actionId !== 'tab.newBrowser' && actionId !== 'tab.newBrowserSplitRight')) &&
|
||||
(includeMobileEmulator || actionId !== 'tab.newSimulator') &&
|
||||
(actionId !== CLOUD_SHARE_LINK_ACTION_ID || cloudShareLinksEnabled())
|
||||
(actionId !== CLOUD_SHARE_LINK_ACTION_ID || cloudTeamSharingEnabled())
|
||||
)
|
||||
.map(({ searchEntry }) => searchEntry),
|
||||
getTerminalShortcutPolicySearchEntry()
|
||||
|
||||
+9
-18
@@ -1,34 +1,25 @@
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import React from 'react'
|
||||
import { Monitor } from 'lucide-react'
|
||||
import { DropdownMenuItem } from '@/components/ui/dropdown-menu'
|
||||
import { useTranslate } from '@/i18n/use-translate'
|
||||
import { openMoveToThisComputer } from '@/lib/orca-cloud/orca-cloud-move-store'
|
||||
import { useIsCloudWorkspace } from '@/lib/orca-cloud/orca-cloud-workspace-store'
|
||||
import { useAppStore } from '@/store'
|
||||
import { findWorktreeById } from '@/store/github/refresh/worktree-refresh'
|
||||
|
||||
/** "Move to this computer" for Orca Cloud workspaces. Mounted only inside the open menu. */
|
||||
/**
|
||||
* "Move to this computer" for this desktop's own Orca Cloud workspaces. Reads the cloud workspace
|
||||
* store (the same list main serves, loaded before any menu opens), so it is there on the menu's
|
||||
* first paint instead of popping in after an IPC round trip.
|
||||
*/
|
||||
export function WorktreeCloudTransferMenuItem({
|
||||
worktreeId
|
||||
}: {
|
||||
worktreeId: string
|
||||
}): React.JSX.Element | null {
|
||||
const t = useTranslate()
|
||||
const [isCloud, setIsCloud] = useState(false)
|
||||
useEffect(() => {
|
||||
let live = true
|
||||
const api = window.api?.orcaCloudWorkspace
|
||||
if (!api?.prepareTransferToLocal) {
|
||||
return
|
||||
}
|
||||
void api
|
||||
.listCloudWorkspaceIds()
|
||||
.then((ids) => live && setIsCloud(ids.includes(worktreeId)))
|
||||
.catch(() => undefined)
|
||||
return () => {
|
||||
live = false
|
||||
}
|
||||
}, [worktreeId])
|
||||
if (!isCloud) {
|
||||
const isCloud = useIsCloudWorkspace(worktreeId)
|
||||
if (!isCloud || !window.api?.orcaCloudWorkspace?.prepareTransferToLocal) {
|
||||
return null
|
||||
}
|
||||
return (
|
||||
|
||||
+142
@@ -0,0 +1,142 @@
|
||||
// MENU-FIRST-PAINT (Neil): a cloud workspace's right-click menu is whole when it opens; nothing
|
||||
// appears a second later. The answers this menu used to wait for take 900 ms here (a slow link):
|
||||
// the cloud workspace list and the team's record. Running and asleep (one Sleep or Wake item).
|
||||
import { defineFixture } from '../../../../component-fixtures/component-fixture'
|
||||
import type { Repo } from '../../../../../../shared/repo-types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import type { HostedWorkspaceStatus } from '../../../../../../shared/hosted-sandbox/hosted-sandbox-wire'
|
||||
import { seedCloudWorkspaceSnapshot } from '@/lib/orca-cloud/orca-cloud-workspace-store'
|
||||
import WorktreeContextMenu from './WorktreeContextMenu'
|
||||
|
||||
const SLOW_MS = 900
|
||||
const slow = <T,>(value: T): Promise<T> =>
|
||||
new Promise((resolve) => setTimeout(() => resolve(value), SLOW_MS))
|
||||
|
||||
const repo: Repo = {
|
||||
id: 'cloud-repo',
|
||||
path: '/workspace/hello-world',
|
||||
displayName: 'hello-world',
|
||||
badgeColor: '',
|
||||
addedAt: 1
|
||||
}
|
||||
|
||||
function cloudWorktree(id: string, name: string): Worktree {
|
||||
return {
|
||||
id,
|
||||
repoId: repo.id,
|
||||
hostId: 'runtime:env-cloud',
|
||||
instanceId: `${id}-instance`,
|
||||
path: '/workspace/hello-world',
|
||||
displayName: name,
|
||||
branch: 'refs/heads/fix-login',
|
||||
head: 'abc123',
|
||||
isBare: false,
|
||||
isMainWorktree: false,
|
||||
comment: '',
|
||||
linkedIssue: null,
|
||||
linkedPR: null,
|
||||
linkedLinearIssue: null,
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1
|
||||
}
|
||||
}
|
||||
|
||||
const status = (state: 'ready' | 'sleeping'): HostedWorkspaceStatus => ({
|
||||
state,
|
||||
metrics: null,
|
||||
uptimeMs: null,
|
||||
usage: { totalMs: 0, centsPerHour: 100, costCents: 0 },
|
||||
archive: null,
|
||||
checkedAt: 1
|
||||
})
|
||||
|
||||
function firstPaint(asleep: boolean) {
|
||||
const worktree = cloudWorktree(asleep ? 'cloud-asleep' : 'cloud-running', 'fix login')
|
||||
return defineFixture({
|
||||
width: 420,
|
||||
store: {
|
||||
repos: [repo],
|
||||
worktreesByRepo: { [repo.id]: [worktree] },
|
||||
// Team sharing on, so the Share row (which needs the team's record) is in the menu.
|
||||
orcaProfileAuthStatus: {
|
||||
activeProfileId: 'p',
|
||||
configured: true,
|
||||
state: 'connected',
|
||||
persistence: 'encrypted',
|
||||
cloud: { cloudProfileId: 'c', userId: 'u', email: 'e', activeOrgId: 'o', linkedAt: 0 },
|
||||
organizations: [{ orgId: 'o', name: 'Team', role: 'Owner' }],
|
||||
capabilities: { flags: { cloudTeamSharing: true }, refreshedAt: 0 }
|
||||
},
|
||||
ephemeralVmRuntimesByWorkspaceId: {
|
||||
[worktree.id]: {
|
||||
id: 'vm-1',
|
||||
workspaceId: worktree.id,
|
||||
status: asleep ? 'suspended' : 'running',
|
||||
runtimeEnvironmentId: 'env-cloud',
|
||||
canSuspend: true
|
||||
}
|
||||
},
|
||||
// Restored panels on the asleep one: what made the local "Sleep" show beside Wake.
|
||||
browserTabsByWorktree: asleep
|
||||
? {
|
||||
[worktree.id]: [
|
||||
{
|
||||
id: 'browser-1',
|
||||
worktreeId: worktree.id,
|
||||
url: 'http://localhost:3000',
|
||||
title: 'App',
|
||||
loading: false,
|
||||
faviconUrl: null,
|
||||
canGoBack: false,
|
||||
canGoForward: false,
|
||||
loadError: null,
|
||||
createdAt: 1
|
||||
}
|
||||
]
|
||||
}
|
||||
: {}
|
||||
},
|
||||
setup: () => {
|
||||
seedCloudWorkspaceSnapshot({
|
||||
ids: new Set([worktree.id]),
|
||||
idsLoaded: true,
|
||||
status: {
|
||||
[worktree.id]: {
|
||||
status: status(asleep ? 'sleeping' : 'ready'),
|
||||
loading: false,
|
||||
error: null,
|
||||
fetchedAt: Date.now()
|
||||
}
|
||||
}
|
||||
})
|
||||
Object.assign(window.api.orcaCloudWorkspace, {
|
||||
listCloudWorkspaceIds: () => slow([worktree.id]),
|
||||
prepareTransferToLocal: () => slow(null)
|
||||
})
|
||||
Object.assign(window.api.cloudWorkspaces, {
|
||||
localWorkspaces: () => slow([{ worktreeId: worktree.id, sandboxId: 'sbx_1' }]),
|
||||
environmentBindings: () => slow({}),
|
||||
get: () =>
|
||||
slow({
|
||||
ok: true,
|
||||
value: { id: 'sbx_1', status: 'running', visibility: 'private', access: 'owner' }
|
||||
})
|
||||
})
|
||||
},
|
||||
render: () => (
|
||||
<div className="h-[520px] bg-background p-4 text-foreground">
|
||||
<WorktreeContextMenu worktree={worktree}>
|
||||
<div className="text-sm" data-first-paint-row>
|
||||
fix login
|
||||
</div>
|
||||
</WorktreeContextMenu>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
export const running = firstPaint(false)
|
||||
export const asleep = firstPaint(true)
|
||||
+12
@@ -15,6 +15,7 @@ import {
|
||||
CloudCopyWorkspaceLinkItem,
|
||||
CloudWorkspaceMenuItems
|
||||
} from '@/components/orca-cloud/CloudWorkspaceMenuItems'
|
||||
import { prefetchCloudWorkspaceRecord } from '@/components/orca-cloud/use-cloud-workspace-record'
|
||||
import { useIsCloudHostRow, usePrimeCloudRowBindings } from '@/lib/orca-cloud/cloud-host-rows'
|
||||
import { getWorktreeExecutionHostId } from '../../../../../../shared/execution-host'
|
||||
import { WorktreeOpenInAndSshSubMenus } from '../cloud-ssh/WorktreeOpenInAndSshSubMenus'
|
||||
@@ -104,6 +105,17 @@ export default function WorktreeContextMenuView({ model }: { model: WorktreeCont
|
||||
ref={scopeRef}
|
||||
className="relative"
|
||||
{...{ [WORKTREE_CONTEXT_MENU_SCOPE_ATTR]: 'worktree' }}
|
||||
// The cloud menu's Share and link rows need the team's record: fetch it while the pointer is
|
||||
// on the row, so it's there when the menu opens (cached; a fresh one isn't fetched again).
|
||||
onPointerEnter={
|
||||
isCloud
|
||||
? () =>
|
||||
void prefetchCloudWorkspaceRecord(
|
||||
worktree.id,
|
||||
getWorktreeExecutionHostId(worktree, repo ?? undefined)
|
||||
)
|
||||
: undefined
|
||||
}
|
||||
onContextMenuCapture={(event) => {
|
||||
if (!isEventTargetInsideCurrentTarget(event.currentTarget, event.target)) {
|
||||
return
|
||||
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { act, cleanup, renderHook } from '@testing-library/react'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
import { useAppStore } from '@/store'
|
||||
import { makeWorktree } from '@/store/slices/worktrees/worktree.test-fixture'
|
||||
import { TEST_REPO } from '@/store/repos/repo.test-fixture'
|
||||
import { makeTab } from '@/store/terminals/terminal-tab.test-fixture'
|
||||
import { useWorktreeContextMenuModel } from './use-worktree-context-menu-model'
|
||||
|
||||
afterEach(() => {
|
||||
cleanup()
|
||||
useAppStore.setState(useAppStore.getInitialState(), true)
|
||||
})
|
||||
|
||||
const worktree = makeWorktree({ id: 'repo1::/tmp/wt', repoId: TEST_REPO.id })
|
||||
const other = makeWorktree({
|
||||
id: 'repo1::/tmp/other',
|
||||
repoId: TEST_REPO.id,
|
||||
path: '/tmp/other'
|
||||
})
|
||||
|
||||
function renderOpenMenu() {
|
||||
useAppStore.setState({
|
||||
repos: [TEST_REPO],
|
||||
worktreesByRepo: { [TEST_REPO.id]: [worktree, other] },
|
||||
tabsByWorktree: { [worktree.id]: [makeTab({ id: 'tab-1', worktreeId: worktree.id })] },
|
||||
ptyIdsByTabId: {}
|
||||
})
|
||||
let renders = 0
|
||||
const hook = renderHook(() => {
|
||||
renders += 1
|
||||
return useWorktreeContextMenuModel({ worktree, children: null })
|
||||
})
|
||||
act(() => hook.result.current.setMenuOpenState(true))
|
||||
return { hook, renders: () => renders }
|
||||
}
|
||||
|
||||
// An open menu used to subscribe to whole activity maps, so every agent status, tab or PTY write
|
||||
// anywhere re-rendered the whole menu (about 200 components) while the pointer moved over it.
|
||||
describe('an open workspace menu ignores store writes that change nothing it shows', () => {
|
||||
it('another workspace’s agent status, tabs and PTYs do not re-render it', () => {
|
||||
const { renders } = renderOpenMenu()
|
||||
const before = renders()
|
||||
for (let i = 0; i < 20; i += 1) {
|
||||
act(() => {
|
||||
const state = useAppStore.getState()
|
||||
state.setAgentStatus(
|
||||
`pane-${i}`,
|
||||
{ state: 'working', prompt: `prompt ${i}`, agentType: 'codex' },
|
||||
'codex',
|
||||
{ updatedAt: i, stateStartedAt: i },
|
||||
{ tabId: `other-${i}`, worktreeId: other.id }
|
||||
)
|
||||
useAppStore.setState({
|
||||
tabsByWorktree: {
|
||||
...state.tabsByWorktree,
|
||||
[other.id]: [makeTab({ id: `other-${i}`, worktreeId: other.id })]
|
||||
},
|
||||
ptyIdsByTabId: { ...state.ptyIdsByTabId, [`other-${i}`]: [`pty-${i}`] },
|
||||
unifiedTabsByWorktree: { ...state.unifiedTabsByWorktree },
|
||||
deleteStateByWorktreeId: { ...state.deleteStateByWorktreeId }
|
||||
})
|
||||
})
|
||||
}
|
||||
expect(renders()).toBe(before)
|
||||
})
|
||||
|
||||
it('still updates live when this workspace becomes sleepable', () => {
|
||||
const { hook } = renderOpenMenu()
|
||||
expect(hook.result.current.sleepableWorktrees).toEqual([])
|
||||
act(() => useAppStore.setState({ ptyIdsByTabId: { 'tab-1': ['pty-1'] } }))
|
||||
expect(hook.result.current.sleepableWorktrees.map((item) => item.id)).toEqual([worktree.id])
|
||||
})
|
||||
})
|
||||
+30
-79
@@ -1,4 +1,3 @@
|
||||
import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep'
|
||||
import { useIsPairedCloudPrimaryRow } from '@/lib/orca-cloud/cloud-host-rows'
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||
import { useAppStore } from '@/store/index'
|
||||
@@ -7,20 +6,12 @@ import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
import { useContextWorkspaceStatuses } from '../../workspace-status/presentation/use-workspace-board-statuses'
|
||||
import { useMenuScopedWorktreeCatalog } from './use-menu-scoped-worktree-catalog'
|
||||
import { useMenuLineageParent } from './use-menu-lineage-parent'
|
||||
import {
|
||||
hasSleepableWorkspaceActivity,
|
||||
useWorkspaceLineageMenuActions
|
||||
} from './workspace-lineage-menu-actions'
|
||||
import { useWorkspaceMenuActivity } from './workspace-lineage-menu-actions'
|
||||
import { getWorkspaceDeleteLineage } from '../deletion/workspace-delete-lineage'
|
||||
import { parseWorkspaceKey } from '../../../../../../shared/workspace-scope'
|
||||
import { getDeleteStateForWorktreeHost } from '../deletion/worktree-delete-state-host-match'
|
||||
import {
|
||||
EMPTY_AGENT_STATUS_BY_PANE_KEY,
|
||||
EMPTY_BROWSER_TABS_BY_WORKTREE,
|
||||
EMPTY_DELETE_STATE_BY_WORKTREE_ID,
|
||||
EMPTY_STRUCTURED_CHAT_SLEPT_AT,
|
||||
EMPTY_PTY_IDS_BY_TAB_ID,
|
||||
EMPTY_TABS_BY_WORKTREE,
|
||||
EMPTY_UNIFIED_TABS_BY_WORKTREE,
|
||||
EMPTY_WORKTREES,
|
||||
EMPTY_WORKSPACE_LINEAGE_BY_CHILD_KEY,
|
||||
EMPTY_WORKTREE_LINEAGE_BY_ID,
|
||||
getSharedWorkspaceStatus,
|
||||
@@ -102,31 +93,6 @@ export function useWorktreeContextMenuModel({
|
||||
)
|
||||
)
|
||||
const updateWorktreeLineage = useAppStore((s) => s.updateWorktreeLineage)
|
||||
const tabsByWorktree = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.tabsByWorktree, EMPTY_TABS_BY_WORKTREE)
|
||||
)
|
||||
const ptyIdsByTabId = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.ptyIdsByTabId, EMPTY_PTY_IDS_BY_TAB_ID)
|
||||
)
|
||||
const browserTabsByWorktree = useAppStore((s) =>
|
||||
selectMenuScopedMap(
|
||||
menuOpen,
|
||||
selectAwakeBrowserTabsByWorktree(s),
|
||||
EMPTY_BROWSER_TABS_BY_WORKTREE
|
||||
)
|
||||
)
|
||||
const unifiedTabsByWorktree = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.unifiedTabsByWorktree, EMPTY_UNIFIED_TABS_BY_WORKTREE)
|
||||
)
|
||||
const agentStatusByPaneKey = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.agentStatusByPaneKey, EMPTY_AGENT_STATUS_BY_PANE_KEY)
|
||||
)
|
||||
const structuredChatSleptAtByPaneKey = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.structuredChatSleptAtByPaneKey, EMPTY_STRUCTURED_CHAT_SLEPT_AT)
|
||||
)
|
||||
const deleteStateByWorktreeId = useAppStore((s) =>
|
||||
selectMenuScopedMap(menuOpen, s.deleteStateByWorktreeId, EMPTY_DELETE_STATE_BY_WORKTREE_ID)
|
||||
)
|
||||
const scopeRef = useRef<HTMLDivElement>(null)
|
||||
const contextMenuOpenedAtRef = useRef<number | null>(null)
|
||||
const activeContextWorktrees = menuOpen ? contextWorktrees : effectiveSelectedWorktrees
|
||||
@@ -136,54 +102,42 @@ export function useWorktreeContextMenuModel({
|
||||
const workspaceScope = parseWorkspaceKey(worktree.id)
|
||||
const folderWorkspaceId =
|
||||
workspaceScope?.type === 'folder' ? workspaceScope.folderWorkspaceId : null
|
||||
const sleepActivity = useMemo(
|
||||
() => ({
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
browserTabsByWorktree,
|
||||
unifiedTabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
structuredChatSleptAtByPaneKey
|
||||
}),
|
||||
[
|
||||
agentStatusByPaneKey,
|
||||
browserTabsByWorktree,
|
||||
structuredChatSleptAtByPaneKey,
|
||||
ptyIdsByTabId,
|
||||
tabsByWorktree,
|
||||
unifiedTabsByWorktree
|
||||
]
|
||||
)
|
||||
// A paired cloud workspace can be running with nothing open here: its Sleep reaches the sandbox.
|
||||
const pairedCloudSleepable = useIsPairedCloudPrimaryRow(worktree) && !isMultiContext
|
||||
// Lineage reads only the catalog; per-workspace activity comes from narrow id selectors below.
|
||||
const lineageTargets = useMemo(
|
||||
() =>
|
||||
menuOpen && !isMultiContext
|
||||
? [
|
||||
worktree,
|
||||
...getWorkspaceDeleteLineage(worktree, allWorktrees, worktreeLineageById).descendants
|
||||
]
|
||||
: EMPTY_WORKTREES,
|
||||
[allWorktrees, isMultiContext, menuOpen, worktree, worktreeLineageById]
|
||||
)
|
||||
const activityCandidates = useMemo(
|
||||
() => [
|
||||
...activeContextWorktrees,
|
||||
...lineageTargets.filter((target) => !activeContextWorktrees.includes(target))
|
||||
],
|
||||
[activeContextWorktrees, lineageTargets]
|
||||
)
|
||||
const { sleepableIds, deletingIds } = useWorkspaceMenuActivity(menuOpen, activityCandidates)
|
||||
const sleepableWorktrees = useMemo(
|
||||
() =>
|
||||
activeContextWorktrees.filter(
|
||||
(item) =>
|
||||
hasSleepableWorkspaceActivity(item.id, sleepActivity) ||
|
||||
(pairedCloudSleepable && item.id === worktree.id)
|
||||
sleepableIds.includes(item.id) || (pairedCloudSleepable && item.id === worktree.id)
|
||||
),
|
||||
[activeContextWorktrees, sleepActivity, pairedCloudSleepable, worktree.id]
|
||||
[activeContextWorktrees, sleepableIds, pairedCloudSleepable, worktree.id]
|
||||
)
|
||||
const lineageMenuActions = useWorkspaceLineageMenuActions({
|
||||
enabled: menuOpen && !isMultiContext,
|
||||
parent: worktree,
|
||||
worktrees: allWorktrees,
|
||||
lineageById: worktreeLineageById,
|
||||
activity: sleepActivity
|
||||
})
|
||||
const lineageDescendantCount = lineageMenuActions.descendants.length
|
||||
const subtreeSleepableWorktrees = lineageMenuActions.sleepableTargets
|
||||
const deletingContext = useMemo(
|
||||
() =>
|
||||
activeContextWorktrees.some(
|
||||
(item) => getDeleteStateForWorktreeHost(item, deleteStateByWorktreeId)?.isDeleting
|
||||
),
|
||||
[activeContextWorktrees, deleteStateByWorktreeId]
|
||||
)
|
||||
const deletingSubtree = lineageMenuActions.targets.some(
|
||||
(item) => getDeleteStateForWorktreeHost(item, deleteStateByWorktreeId)?.isDeleting
|
||||
const lineageDescendantCount = Math.max(0, lineageTargets.length - 1)
|
||||
const subtreeSleepableWorktrees = useMemo(
|
||||
() => lineageTargets.filter((target) => sleepableIds.includes(target.id)),
|
||||
[lineageTargets, sleepableIds]
|
||||
)
|
||||
const deletingContext = activeContextWorktrees.some((item) => deletingIds.includes(item.id))
|
||||
const deletingSubtree = lineageTargets.some((item) => deletingIds.includes(item.id))
|
||||
const contextDeletePending = isMultiContext ? deletingContext : deletingSubtree
|
||||
const contextWorkspaceStatus = useMemo(
|
||||
() => getSharedWorkspaceStatus(activeContextWorktrees, statusesForWorktree),
|
||||
@@ -343,7 +297,6 @@ export function useWorktreeContextMenuModel({
|
||||
...commands,
|
||||
activeContextWorktrees,
|
||||
batchDeleteWorktrees,
|
||||
browserTabsByWorktree,
|
||||
children,
|
||||
contentClassName,
|
||||
contextDeletePending,
|
||||
@@ -373,7 +326,6 @@ export function useWorktreeContextMenuModel({
|
||||
parentPicker,
|
||||
parentPickerOpen,
|
||||
projectGroups,
|
||||
ptyIdsByTabId,
|
||||
removesProject,
|
||||
repo,
|
||||
scopeRef,
|
||||
@@ -385,7 +337,6 @@ export function useWorktreeContextMenuModel({
|
||||
sleepableWorktrees,
|
||||
subtreeSleepableWorktrees,
|
||||
suppressOpeningPointerEvent,
|
||||
tabsByWorktree,
|
||||
validParentWorktreeId,
|
||||
worktree,
|
||||
workspaceStatuses
|
||||
|
||||
+50
-46
@@ -1,4 +1,8 @@
|
||||
import { useMemo } from 'react'
|
||||
import { useShallow } from 'zustand/react/shallow'
|
||||
import { useAppStore } from '@/store'
|
||||
import type { AppState } from '@/store/types'
|
||||
import { selectAwakeBrowserTabsByWorktree } from '@/components/sidebar/workspace-actions/sleep/browser-tab-sleep'
|
||||
import { getDeleteStateForWorktreeHost } from '../deletion/worktree-delete-state-host-match'
|
||||
import { tabHasLivePty } from '../../../../../../shared/tab-has-live-pty'
|
||||
import type { WorktreeLineage } from '../../../../../../shared/worktree/lineage-types'
|
||||
import type { Worktree } from '../../../../../../shared/worktree/types'
|
||||
@@ -61,52 +65,52 @@ export function getWorkspaceLineageMenuActions(args: {
|
||||
}
|
||||
}
|
||||
|
||||
const EMPTY_LINEAGE_MENU_ACTIONS: WorkspaceLineageMenuActions = {
|
||||
descendants: [],
|
||||
targets: [],
|
||||
sleepableTargets: []
|
||||
const EMPTY_IDS: readonly string[] = []
|
||||
|
||||
function selectWorkspaceActivity(state: AppState): WorkspaceActivityMaps {
|
||||
const browserTabsByWorktree = selectAwakeBrowserTabsByWorktree(state)
|
||||
return {
|
||||
tabsByWorktree: state.tabsByWorktree,
|
||||
ptyIdsByTabId: state.ptyIdsByTabId,
|
||||
browserTabsByWorktree,
|
||||
unifiedTabsByWorktree: state.unifiedTabsByWorktree,
|
||||
agentStatusByPaneKey: state.agentStatusByPaneKey,
|
||||
structuredChatSleptAtByPaneKey: state.structuredChatSleptAtByPaneKey
|
||||
}
|
||||
}
|
||||
|
||||
export function useWorkspaceLineageMenuActions(
|
||||
args: Parameters<typeof getWorkspaceLineageMenuActions>[0] & { enabled: boolean }
|
||||
): WorkspaceLineageMenuActions {
|
||||
const { enabled, parent, worktrees, lineageById, activity } = args
|
||||
const {
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
browserTabsByWorktree,
|
||||
unifiedTabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
structuredChatSleptAtByPaneKey
|
||||
} = activity
|
||||
return useMemo(
|
||||
() =>
|
||||
enabled
|
||||
? getWorkspaceLineageMenuActions({
|
||||
parent,
|
||||
worktrees,
|
||||
lineageById,
|
||||
activity: {
|
||||
tabsByWorktree,
|
||||
ptyIdsByTabId,
|
||||
browserTabsByWorktree,
|
||||
unifiedTabsByWorktree,
|
||||
agentStatusByPaneKey,
|
||||
structuredChatSleptAtByPaneKey
|
||||
}
|
||||
})
|
||||
: EMPTY_LINEAGE_MENU_ACTIONS,
|
||||
[
|
||||
agentStatusByPaneKey,
|
||||
browserTabsByWorktree,
|
||||
enabled,
|
||||
structuredChatSleptAtByPaneKey,
|
||||
lineageById,
|
||||
parent,
|
||||
ptyIdsByTabId,
|
||||
tabsByWorktree,
|
||||
unifiedTabsByWorktree,
|
||||
worktrees
|
||||
]
|
||||
/**
|
||||
* Which of `worktrees` have something Sleep would close, and which are being deleted, as id lists
|
||||
* that keep their identity while unchanged. An open menu must not subscribe to the whole activity
|
||||
* and delete maps: agents, tabs and PTYs anywhere write them many times a second, and each write
|
||||
* re-rendered the whole menu under the pointer. Closed menus select a shared empty list.
|
||||
*/
|
||||
export function useWorkspaceMenuActivity(
|
||||
enabled: boolean,
|
||||
worktrees: readonly Worktree[]
|
||||
): { sleepableIds: readonly string[]; deletingIds: readonly string[] } {
|
||||
const sleepableIds = useAppStore(
|
||||
useShallow((state) => {
|
||||
if (!enabled) {
|
||||
return EMPTY_IDS
|
||||
}
|
||||
const activity = selectWorkspaceActivity(state)
|
||||
return worktrees
|
||||
.filter((item) => hasSleepableWorkspaceActivity(item.id, activity))
|
||||
.map((item) => item.id)
|
||||
})
|
||||
)
|
||||
const deletingIds = useAppStore(
|
||||
useShallow((state) =>
|
||||
enabled
|
||||
? worktrees
|
||||
.filter(
|
||||
(item) =>
|
||||
getDeleteStateForWorktreeHost(item, state.deleteStateByWorktreeId)?.isDeleting
|
||||
)
|
||||
.map((item) => item.id)
|
||||
: EMPTY_IDS
|
||||
)
|
||||
)
|
||||
return { sleepableIds, deletingIds }
|
||||
}
|
||||
|
||||
-7
@@ -25,13 +25,6 @@ const DELETE_POSITION_RESTORE_STABLE_FRAMES = 6
|
||||
export const PARENT_PICKER_EXIT_ANIMATION_MS = 200
|
||||
|
||||
// Closed menus reuse empty identities so teardown map churn cannot wake their subscriptions.
|
||||
export const EMPTY_TABS_BY_WORKTREE: AppState['tabsByWorktree'] = {}
|
||||
export const EMPTY_PTY_IDS_BY_TAB_ID: AppState['ptyIdsByTabId'] = {}
|
||||
export const EMPTY_BROWSER_TABS_BY_WORKTREE: AppState['browserTabsByWorktree'] = {}
|
||||
export const EMPTY_UNIFIED_TABS_BY_WORKTREE: AppState['unifiedTabsByWorktree'] = {}
|
||||
export const EMPTY_AGENT_STATUS_BY_PANE_KEY: AppState['agentStatusByPaneKey'] = {}
|
||||
export const EMPTY_STRUCTURED_CHAT_SLEPT_AT: AppState['structuredChatSleptAtByPaneKey'] = {}
|
||||
export const EMPTY_DELETE_STATE_BY_WORKTREE_ID: AppState['deleteStateByWorktreeId'] = {}
|
||||
export const EMPTY_WORKTREE_LINEAGE_BY_ID: AppState['worktreeLineageById'] = {}
|
||||
export const EMPTY_WORKSPACE_LINEAGE_BY_CHILD_KEY: AppState['workspaceLineageByChildKey'] = {}
|
||||
export const EMPTY_CROSS_STORE_LINEAGE_BY_STORE_KEY: AppState['crossStoreLineageByStoreKey'] = {}
|
||||
|
||||
+129
@@ -0,0 +1,129 @@
|
||||
// @vitest-environment happy-dom
|
||||
// Neil: an asleep cloud workspace's menu showed "Sleep" (the local close-panels item) beside "Wake".
|
||||
// A cloud row gets one lifecycle item for its state; local VM workspaces are unchanged.
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import React from 'react'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
type MenuState = {
|
||||
runtime: null | { status: string; canSuspend?: boolean }
|
||||
waking: boolean
|
||||
ownedCloud: boolean
|
||||
archived: boolean
|
||||
}
|
||||
|
||||
const { state } = vi.hoisted(() => {
|
||||
const initial: MenuState = { runtime: null, waking: false, ownedCloud: false, archived: false }
|
||||
return { state: initial }
|
||||
})
|
||||
|
||||
vi.mock('@/store', () => ({
|
||||
useAppStore: (select: (s: unknown) => unknown) =>
|
||||
select({
|
||||
ephemeralVmRuntimesByWorkspaceId: state.runtime ? { w: state.runtime } : {},
|
||||
wakingEphemeralVmWorkspaceIds: state.waking ? { w: true } : {}
|
||||
})
|
||||
}))
|
||||
vi.mock('@/lib/orca-cloud/orca-cloud-workspace-store', () => ({
|
||||
useIsCloudWorkspace: () => state.ownedCloud,
|
||||
useCloudWorkspace: () => state.archived
|
||||
}))
|
||||
vi.mock('@/lib/workspace/activation/sidebar-worktree-activation', () => ({
|
||||
resumeEphemeralVmWorkspace: vi.fn(),
|
||||
suspendEphemeralVmWorkspace: vi.fn()
|
||||
}))
|
||||
vi.mock('@/components/ui/dropdown-menu', () => ({
|
||||
DropdownMenuItem: ({ children, disabled }: { children: React.ReactNode; disabled?: boolean }) => (
|
||||
<div role="menuitem" aria-disabled={disabled || undefined}>
|
||||
{children}
|
||||
</div>
|
||||
)
|
||||
}))
|
||||
vi.mock('@/components/ui/tooltip', () => ({
|
||||
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipContent: () => null
|
||||
}))
|
||||
|
||||
import { WorkspaceVmLifecycleMenuItems } from './WorkspaceVmLifecycleMenuItems'
|
||||
|
||||
const PANEL_SLEEP = <div role="menuitem">Close panels sleep</div>
|
||||
|
||||
function items({ hasSleepableActivity = true } = {}): string[] {
|
||||
render(
|
||||
<WorkspaceVmLifecycleMenuItems
|
||||
worktreeId="w"
|
||||
hasSleepableActivity={hasSleepableActivity}
|
||||
disabled={false}
|
||||
onSleep={vi.fn()}
|
||||
hasActiveDescendants={false}
|
||||
onSleepSubtree={vi.fn()}
|
||||
sleepItems={PANEL_SLEEP}
|
||||
replacesSleep
|
||||
/>
|
||||
)
|
||||
return screen.queryAllByRole('menuitem').map((item) => {
|
||||
const label = item.textContent ?? ''
|
||||
return item.getAttribute('aria-disabled') ? `${label} (disabled)` : label
|
||||
})
|
||||
}
|
||||
|
||||
function set(patch: Partial<MenuState>): void {
|
||||
Object.assign(state, { runtime: null, waking: false, ownedCloud: false, archived: false }, patch)
|
||||
}
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
describe('a cloud workspace has one lifecycle item for its state', () => {
|
||||
it('running: Sleep, without the local close-panels Sleep', () => {
|
||||
set({ ownedCloud: true, runtime: { status: 'running' } })
|
||||
expect(items()).toEqual(['Sleep'])
|
||||
})
|
||||
|
||||
it('asleep with restored panels: Wake only (the bug: Sleep and Wake together)', () => {
|
||||
set({ ownedCloud: true, runtime: { status: 'suspended' } })
|
||||
expect(items()).toEqual(['Wake'])
|
||||
})
|
||||
|
||||
it('waking: Waking…, disabled', () => {
|
||||
set({ ownedCloud: true, runtime: { status: 'suspended' }, waking: true })
|
||||
expect(items()).toEqual(['Waking… (disabled)'])
|
||||
})
|
||||
|
||||
it('a wake that failed: Try waking again', () => {
|
||||
set({ ownedCloud: true, runtime: { status: 'resume_failed' } })
|
||||
expect(items()).toEqual(['Try waking again'])
|
||||
})
|
||||
|
||||
it('transitioning (provisioning): no lifecycle item, not the local Sleep', () => {
|
||||
set({ ownedCloud: true, runtime: { status: 'provisioning' } })
|
||||
expect(items()).toEqual([])
|
||||
})
|
||||
|
||||
it('paired (no VM record here): its Sleep is the one that reaches the sandbox', () => {
|
||||
set({ runtime: null })
|
||||
expect(items()).toEqual(['Close panels sleep'])
|
||||
})
|
||||
|
||||
it('archived: nothing', () => {
|
||||
set({ ownedCloud: true, runtime: { status: 'running' }, archived: true })
|
||||
expect(items()).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('local workspaces are unchanged', () => {
|
||||
it('no VM: the close-panels Sleep', () => {
|
||||
set({})
|
||||
expect(items()).toEqual(['Close panels sleep'])
|
||||
})
|
||||
|
||||
it('a suspended local VM with restored panels keeps both Sleep and Resume VM', () => {
|
||||
set({ runtime: { status: 'suspended' } })
|
||||
expect(items()).toEqual(['Close panels sleep', 'Resume VM'])
|
||||
})
|
||||
|
||||
it('a running local VM: Suspend VM in place of Sleep', () => {
|
||||
set({ runtime: { status: 'running' } })
|
||||
expect(items()).toEqual(['Suspend VM'])
|
||||
})
|
||||
})
|
||||
+7
-3
@@ -111,7 +111,9 @@ export function WorkspaceVmLifecycleMenuItems({
|
||||
return null
|
||||
}
|
||||
if (!action) {
|
||||
return <>{sleepItems}</>
|
||||
// This desktop's own cloud workspace mid-transition has no lifecycle item. (A paired one has no
|
||||
// VM record here; its Sleep is `sleepItems`, which reaches the sandbox.)
|
||||
return cloud ? null : <>{sleepItems}</>
|
||||
}
|
||||
const vmItem = (
|
||||
<VmLifecycleMenuItem
|
||||
@@ -134,8 +136,10 @@ export function WorkspaceVmLifecycleMenuItems({
|
||||
/>
|
||||
)
|
||||
// Sleep and Suspend VM are one action on a running VM. A VM still asleep or waking keeps Sleep
|
||||
// only while it has restored panels to close; otherwise Sleep would sit there disabled.
|
||||
return replacesSleep && (action === 'suspend' || !hasSleepableActivity) ? (
|
||||
// only while it has restored panels to close; otherwise Sleep would sit there disabled. Not on
|
||||
// Orca Cloud (Neil): there that "Sleep" read as a second, contradictory item beside Wake; the
|
||||
// cloud row has exactly one lifecycle item, Sleep or Wake.
|
||||
return cloud || (replacesSleep && (action === 'suspend' || !hasSleepableActivity)) ? (
|
||||
vmItem
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -24143,6 +24143,7 @@
|
||||
"picker": {
|
||||
"title": "Open cloud workspace",
|
||||
"description": "Cloud workspaces that aren’t in your sidebar: shared by teammates, or started on another computer.",
|
||||
"descriptionOwn": "Your cloud workspaces that aren’t in your sidebar, such as ones started on another computer.",
|
||||
"teammateTitle": "{{name}}’s cloud workspaces",
|
||||
"teammateDescription": "The ones they own or started that you can see.",
|
||||
"runningTitle": "Your running cloud workspaces",
|
||||
@@ -27579,8 +27580,6 @@
|
||||
"usage": "CPU {{cpu}}% · Memory {{used}} / {{total}} GB",
|
||||
"syncOff": "Off",
|
||||
"syncError": "Couldn’t sync",
|
||||
"mirroringAndContext": "Mirroring · .context synced",
|
||||
"mirroring": "Mirroring",
|
||||
"contextSynced": ".context synced",
|
||||
"more": "More actions",
|
||||
"details": "Details",
|
||||
@@ -29202,7 +29201,6 @@
|
||||
}
|
||||
},
|
||||
"orcaCloudSync": {
|
||||
"menuItem": "Mirror to this computer…",
|
||||
"gb": "{{value}} GB",
|
||||
"mb": "{{value}} MB",
|
||||
"kb": "{{value}} KB",
|
||||
@@ -29227,15 +29225,13 @@
|
||||
"syncedEmpty": "Synced · {{ago}}",
|
||||
"contextLabel": ".context folder",
|
||||
"contextHelper": "Plans and screenshots from this workspace, synced to this computer.",
|
||||
"mirrorLabel": "Mirror to this computer",
|
||||
"mirrorHelper": "A read-only copy of this workspace’s files, kept up to date while it runs.",
|
||||
"openFolder": "Open folder",
|
||||
"copied": "Copied",
|
||||
"copyPath": "Copy path",
|
||||
"tryAgain": "Try again",
|
||||
"editedHere_one": "{{count}} file changed on this computer. Edits here don’t sync back. The cloud copy replaces it when it changes.",
|
||||
"editedHere_other": "{{count}} files changed on this computer. Edits here don’t sync back. The cloud copy replaces them when it changes.",
|
||||
"overLimit": "The mirror is limited to {{size}}. Larger files and anything past the limit aren’t copied.",
|
||||
"overLimit": "The .context folder is limited to {{size}}. Larger files and anything past the limit aren’t copied.",
|
||||
"tooLarge": "Files over {{size}} aren’t copied.",
|
||||
"removal": "The copy on this computer is removed too."
|
||||
},
|
||||
|
||||
@@ -63,8 +63,8 @@ const RULES: Rule[] = [
|
||||
{
|
||||
term: 'this Mac',
|
||||
pattern: /Sync to a local directory|\bthis Mac\b/i,
|
||||
use: 'Mirror to this computer / this computer',
|
||||
row: 'Mirror to this computer'
|
||||
use: 'this computer',
|
||||
row: 'On this computer'
|
||||
},
|
||||
{ term: 'credits', pattern: /\bcredits?\b/i, use: 'sandbox hours', row: 'Time unit' },
|
||||
{
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
// SHARE-LINKS-HOLD (Neil): cloud workspace share links are held for this release. The code stays;
|
||||
// every way to produce a link (Copy › Workspace link / chat link, the cloud list's Copy link items,
|
||||
// ⌘⌥⇧L and its Settings entry) is off unless the account's capabilities turn on `cloudShareLinks`.
|
||||
// Opening an orca://cloud link someone already has still works. Share with team (visibility) stays.
|
||||
import { useAppStore } from '@/store'
|
||||
import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles'
|
||||
|
||||
export const CLOUD_SHARE_LINKS_FLAG = 'cloudShareLinks'
|
||||
export const CLOUD_SHARE_LINK_ACTION_ID = 'cloudWorkspace.copyLink'
|
||||
|
||||
function enabledFor(status: OrcaProfileAuthStatus | null | undefined): boolean {
|
||||
return status?.capabilities?.flags[CLOUD_SHARE_LINKS_FLAG] === true
|
||||
}
|
||||
|
||||
/** Outside React (keyboard handlers, the copy itself, Settings' shortcut list). */
|
||||
export function cloudShareLinksEnabled(): boolean {
|
||||
return enabledFor(useAppStore.getState().orcaProfileAuthStatus)
|
||||
}
|
||||
|
||||
export function useCloudShareLinksEnabled(): boolean {
|
||||
return useAppStore((state) => enabledFor(state.orcaProfileAuthStatus))
|
||||
}
|
||||
@@ -59,13 +59,9 @@ export function useCloudSync(workspaceId: string): CloudSyncView | null {
|
||||
return useSyncExternalStore(subscribe, () => views.get(workspaceId) ?? null)
|
||||
}
|
||||
|
||||
export function isCloudSyncAvailable(): boolean {
|
||||
return api() !== null
|
||||
}
|
||||
|
||||
export async function setCloudSyncChoice(
|
||||
workspaceId: string,
|
||||
patch: { context?: boolean; mirror?: boolean }
|
||||
patch: { context?: boolean }
|
||||
): Promise<void> {
|
||||
const bridge = api()
|
||||
const current = views.get(workspaceId)
|
||||
@@ -97,40 +93,3 @@ export function seedCloudSyncView(view: CloudSyncView): void {
|
||||
requested.add(view.workspaceId)
|
||||
put(view)
|
||||
}
|
||||
|
||||
/** "Mirror to this computer…" from the workspace menu: the popover opens on the sync section. */
|
||||
const focusRequests = new Set<string>()
|
||||
const focusListeners = new Set<() => void>()
|
||||
/** Lets the workspace menu finish closing (it hands focus back to its trigger) before the popover opens. */
|
||||
const MENU_CLOSE_SETTLE_MS = 150
|
||||
|
||||
export function requestCloudSyncFocus(workspaceId: string): void {
|
||||
setTimeout(() => {
|
||||
focusRequests.add(workspaceId)
|
||||
for (const listener of focusListeners) {
|
||||
listener()
|
||||
}
|
||||
}, MENU_CLOSE_SETTLE_MS)
|
||||
}
|
||||
export function takeCloudSyncFocus(workspaceId: string): boolean {
|
||||
return focusRequests.delete(workspaceId)
|
||||
}
|
||||
/** Calls `listener` when the menu asks for this workspace's sync section (an event, not state). */
|
||||
export function onCloudSyncFocusRequest(workspaceId: string, listener: () => void): () => void {
|
||||
const wrapped = (): void => {
|
||||
if (focusRequests.has(workspaceId)) {
|
||||
listener()
|
||||
}
|
||||
}
|
||||
focusListeners.add(wrapped)
|
||||
return () => focusListeners.delete(wrapped)
|
||||
}
|
||||
export function useCloudSyncFocusRequest(workspaceId: string): boolean {
|
||||
return useSyncExternalStore(
|
||||
(listener) => {
|
||||
focusListeners.add(listener)
|
||||
return () => focusListeners.delete(listener)
|
||||
},
|
||||
() => focusRequests.has(workspaceId)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
// TEAM-SHARING-HOLD (Neil): sharing cloud workspaces with the team is held for a future release. The
|
||||
// code stays; the desktop offers none of it unless the account's capabilities turn on
|
||||
// `cloudTeamSharing` (absent = off, so an older or unaware control plane never brings it back):
|
||||
// - Share with team / Make private (sidebar, the cloud list, the workspace panel);
|
||||
// - the private/shared badges and Settings' visibility labels;
|
||||
// - the "Team" scope of Open cloud workspace…, and the people chip on a workspace;
|
||||
// - share links (Copy › Workspace link / chat link, the list's Copy link items, ⌘⌥⇧L and its
|
||||
// Settings entry), since a link only helps someone else open a shared workspace.
|
||||
// Opening an orca://cloud link still works; one to a workspace you can't open shows the usual
|
||||
// no-access message.
|
||||
import { useAppStore } from '@/store'
|
||||
import type { OrcaProfileAuthStatus } from '../../../../shared/orca-profiles'
|
||||
|
||||
export const CLOUD_TEAM_SHARING_FLAG = 'cloudTeamSharing'
|
||||
export const CLOUD_SHARE_LINK_ACTION_ID = 'cloudWorkspace.copyLink'
|
||||
|
||||
function enabledFor(status: OrcaProfileAuthStatus | null | undefined): boolean {
|
||||
return status?.capabilities?.flags[CLOUD_TEAM_SHARING_FLAG] === true
|
||||
}
|
||||
|
||||
/** Outside React (keyboard handlers, the copy itself, action groups, Settings' shortcut list). */
|
||||
export function cloudTeamSharingEnabled(): boolean {
|
||||
return enabledFor(useAppStore.getState().orcaProfileAuthStatus)
|
||||
}
|
||||
|
||||
export function useCloudTeamSharingEnabled(): boolean {
|
||||
return useAppStore((state) => enabledFor(state.orcaProfileAuthStatus))
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
// Cloud → this computer file sync for Orca Cloud workspaces: `.context` (on by default) and an
|
||||
// optional read-only mirror of the whole workspace. Main owns the sync; the window shows state.
|
||||
// Cloud → this computer file sync for Orca Cloud workspaces: the `.context` folder (plans and
|
||||
// screenshots, on by default). Main owns the sync; the window shows state.
|
||||
|
||||
export const ORCA_CLOUD_SYNC_CHANNELS = {
|
||||
getState: 'orcaCloudSync:getState',
|
||||
@@ -10,10 +10,10 @@ export const ORCA_CLOUD_SYNC_CHANNELS = {
|
||||
changed: 'orcaCloudSync:changed'
|
||||
} as const
|
||||
|
||||
export type CloudSyncChoiceState = { context: boolean; mirror: boolean }
|
||||
export type CloudSyncChoiceState = { context: boolean }
|
||||
|
||||
export type CloudSyncPhase =
|
||||
/** Both rows off: nothing on this computer. */
|
||||
/** Sync off: nothing on this computer. */
|
||||
| 'off'
|
||||
/** First pass in flight, nothing copied yet. */
|
||||
| 'starting'
|
||||
@@ -57,11 +57,7 @@ export type CloudSyncRemovalPreview = { hasLocalCopy: boolean; editedHere: numbe
|
||||
|
||||
export type CloudSyncApi = {
|
||||
getState: (workspaceId: string) => Promise<CloudSyncView | null>
|
||||
setChoice: (args: {
|
||||
workspaceId: string
|
||||
context?: boolean
|
||||
mirror?: boolean
|
||||
}) => Promise<CloudSyncView | null>
|
||||
setChoice: (args: { workspaceId: string; context?: boolean }) => Promise<CloudSyncView | null>
|
||||
openFolder: (workspaceId: string) => Promise<{ ok: boolean }>
|
||||
retry: (workspaceId: string) => Promise<void>
|
||||
removalPreview: (workspaceId: string) => Promise<CloudSyncRemovalPreview>
|
||||
|
||||
Reference in New Issue
Block a user