From 72b226ec5d3d853eadef4d682e840b1cb092b646 Mon Sep 17 00:00:00 2001 From: reoring Date: Sat, 21 Nov 2026 12:29:04 +0900 Subject: [PATCH 1/2] Show the caller's development workspaces in a My workspaces drawer - Header entry (running count) opens a drawer grouped into Running, Sleeping and Stopped/Retired/Failed, from GET dev-workspaces?owner=me - Row actions come only from allowedActions: open/resume, extend lease, stop, delete (Dashboard warning, per-row Idempotency-Key); start or restart both call the restart route - Build and improve headers show the remaining lease, amber from five minutes before expiry; the owner can extend it - Requires @appthrust/api-schema 0.1.8 (platform #7290 + #7296); bun.lock is refreshed after that version is published --- web/README.md | 34 +++ web/e2e/stories/my-workspaces.mock.spec.ts | 86 ++++++ web/package.json | 2 +- .../api/contracts/platform/workspace.test.ts | 66 +++- web/src/api/contracts/platform/workspace.ts | 91 +++++- web/src/api/queries/workspaces.ts | 17 ++ web/src/api/workspace.ts | 30 +- web/src/dev/mock-platform.ts | 43 ++- web/src/dev/mock-workspaces.ts | 134 +++++++++ web/src/features/build/build-page.tsx | 3 +- web/src/features/build/console-build-page.tsx | 7 +- web/src/features/build/session-header.tsx | 9 +- web/src/features/improve/improve-page.tsx | 6 +- web/src/features/workspaces/copy.en.ts | 103 +++++++ web/src/features/workspaces/copy.ts | 106 +++++++ web/src/features/workspaces/delete-dialog.tsx | 127 ++++++++ web/src/features/workspaces/drawer.tsx | 283 ++++++++++++++++++ web/src/features/workspaces/index.ts | 3 + web/src/features/workspaces/lease-hint.tsx | 53 ++++ web/src/features/workspaces/model.test.ts | 136 +++++++++ web/src/features/workspaces/model.ts | 133 ++++++++ .../features/workspaces/use-my-workspaces.ts | 52 ++++ web/src/model/contracts/workspace.ts | 50 ++++ web/src/shell/shell.tsx | 7 +- web/src/styles.css | 9 + 25 files changed, 1573 insertions(+), 17 deletions(-) create mode 100644 web/e2e/stories/my-workspaces.mock.spec.ts create mode 100644 web/src/api/queries/workspaces.ts create mode 100644 web/src/dev/mock-workspaces.ts create mode 100644 web/src/features/workspaces/copy.en.ts create mode 100644 web/src/features/workspaces/copy.ts create mode 100644 web/src/features/workspaces/delete-dialog.tsx create mode 100644 web/src/features/workspaces/drawer.tsx create mode 100644 web/src/features/workspaces/index.ts create mode 100644 web/src/features/workspaces/lease-hint.tsx create mode 100644 web/src/features/workspaces/model.test.ts create mode 100644 web/src/features/workspaces/model.ts create mode 100644 web/src/features/workspaces/use-my-workspaces.ts create mode 100644 web/src/model/contracts/workspace.ts diff --git a/web/README.md b/web/README.md index a859143..74b4ef5 100644 --- a/web/README.md +++ b/web/README.md @@ -148,6 +148,40 @@ entries are unaffected. Only the image entry shows the existing registry prerequisite. Successful reads are unchanged. Registry 401, 5xx, network and contract failures—and every failure of the other reads—still fail the query. +## 自分の作業場所 (My workspaces) + +The header's laptop icon (badge: running count) opens a drawer with the +caller's own DevWorkspaces, read from `GET dev-workspaces?owner=me` +(`@appthrust/api-schema` ≥ 0.1.8). Admin work, Project policy and other +people's workspaces stay in the Dashboard. `src/features/workspaces/` holds the +drawer, the delete dialog, the lease hint and their model; the reader keeps only +the fields the drawer shows, with open `state`, `scope` and source volume state +(a server without `state` reads the state its phase stands for). + +- Groups: 動いている (Ready, Degraded, Committing, Starting), 休止中 (Sleeping) + and 停止・使用終了・失敗 (everything else, including states this console does + not know). Each row: name, state, target and one line — the lease countdown, + when the source data is released, 「停止した作業場所のデータは、削除するまで残ります」 + or, for Retired, when Platform deletes it. +- Actions come only from `allowedActions`: 開く/再開する (`open`, to the AI + session page that uses the workspace, else its draft's build page; no page, no + action), 延長する (`extendLease`, immediate), 停止する (`stop`, confirmed), + 再開する on a Stopped or Failed row (`start` or `restart`: there is no start + route, so both call restart) and 削除する (`delete`, not offered on running + rows). Retired workspaces cannot run again (both are false) and are deleted by Platform. +- The header line comes from `summary`; 片づける (shown while + `idleRetained > 0`) checks the idle Sleeping and Stopped rows by the server's + rule over `idleAfter`. Delete repeats the Dashboard warning (unpushed changes are + lost; rows without a pushed branch or pull request are named) and sends one + `DELETE` per row with its own `Idempotency-Key`, reused by 失敗したものをもう一度. +- The build and improve session headers show the session workspace's lease + (「あと 12 分で休止」, warning color from five minutes before); the owner + extends it with one click. + +The list is re-read every 30 seconds. The mock seeds six workspaces for 山田 +(Running 2, Sleeping 2, Stopped 1, Retired 1); see the top of +`src/dev/mock-platform.ts`. + ## Excel から作る diff --git a/web/e2e/stories/my-workspaces.mock.spec.ts b/web/e2e/stories/my-workspaces.mock.spec.ts new file mode 100644 index 0000000..b5cb4bc --- /dev/null +++ b/web/e2e/stories/my-workspaces.mock.spec.ts @@ -0,0 +1,86 @@ +import { test, expect, seed, captureWrite } from '../support/fixtures' + +const workspaces = `/api/v1/projects/${seed.projectId}/dev-workspaces` + +test.describe('My workspaces @workspaces', () => { + test('opens my workspaces in three groups, extends a lease, shows a Retired row, and deletes idle ones behind the unpushed-changes warning @mock @story', async ({ page }) => { + await page.goto('/') + // The header entry carries the running count (Ready + Degraded of the six seeded workspaces). + const entry = page.getByRole('button', { name: '自分の作業場所(動いているもの 2 件)', exact: true }) + await expect(entry).toBeVisible() + await expect(page.getByTestId('my-workspaces-badge')).toHaveText('2') + await entry.click() + + const drawer = page.getByRole('dialog', { name: '自分の作業場所', exact: true }) + await expect(drawer.getByTestId('my-workspaces-summary')).toHaveText('データを残している作業場所 6 件 · 7 日以上使っていないもの 2 件') + const group = (name: string) => drawer.getByRole('region', { name: new RegExp(`^${name}`) }) + const running = group('動いている') + const sleeping = group('休止中') + const other = group('停止・使用終了・失敗') + await expect(running.getByRole('listitem')).toHaveCount(2) + await expect(sleeping.getByRole('listitem')).toHaveCount(2) + await expect(other.getByRole('listitem')).toHaveCount(2) + + // Running rows: the lease countdown, the Degraded one inside the five-minute warning. + const ready = drawer.locator('[data-workspace-id="devws-mitsumori-fix"]') + await expect(ready.getByTestId('workspace-line')).toHaveText(/^あと 4[12] 分で休止します$/) + const degraded = drawer.locator('[data-workspace-id="devws-nippo-filter"]') + await expect(degraded.getByTestId('workspace-line')).toHaveText(/^あと [1-3] 分で休止します$/) + await expect(degraded.getByTestId('workspace-line')).toHaveClass(/text-busy-ink/) + // Sleeping: resumable, with when its data is released; running rows cannot be chosen for deletion. + await expect(sleeping.getByRole('listitem').first()).toContainText(/データは .+ まで残ります/) + await expect(running.getByRole('checkbox')).toHaveCount(0) + + // Extend lease: immediate, with Idempotency-Key, and the row shows the renewed hour. + const extended = await captureWrite(page, 'POST', `${workspaces}/devws-mitsumori-fix/extend-lease`, () => + ready.getByRole('button', { name: '「見積の明細を直す」を延長する', exact: true }).click()) + expect(await extended.request.headerValue('idempotency-key')).toBeTruthy() + expect((await extended.request.response())?.status()).toBe(202) + await expect(drawer.getByRole('status').filter({ hasText: '「見積の明細を直す」の休止までの時間を延ばしました。' })).toBeVisible() + await expect(ready.getByTestId('workspace-line')).toHaveText(/^あと (60|59) 分で休止します$/) + + // Stopped: Platform allows `start` (not `restart`); there is no start route, so 再開する calls restart. It sits beside 削除する. + const stopped = drawer.locator('[data-workspace-id="devws-kintai-csv"]') + await expect(stopped.getByRole('button')).toHaveText(['再開する', '削除する']) + await expect(stopped.getByRole('button', { name: '「勤怠を CSV で出す」を再開する', exact: true })).toBeEnabled() + + // Retired: unusable, deleted by Platform on its date; deleting is the only action. + const retired = drawer.locator('[data-workspace-id="devws-mitsumori-old"]') + await expect(retired).toContainText('使用終了') + await expect(retired.getByTestId('workspace-line')).toHaveText(/^もう使えません。.+ に自動で削除されます。$/) + await expect(retired.getByRole('button')).toHaveText(['削除する']) + await expect(retired.getByRole('link')).toHaveCount(0) + + // 片づける checks the idle Sleeping and Stopped rows, never the Retired one. + await drawer.getByRole('button', { name: '片づける', exact: true }).click() + await expect(drawer.getByRole('checkbox', { name: '「売上ダッシュボード」を選ぶ', exact: true })).toBeChecked() + await expect(drawer.getByRole('checkbox', { name: '「勤怠を CSV で出す」を選ぶ', exact: true })).toBeChecked() + await expect(drawer.getByRole('checkbox', { name: '「経費に領収書を添付する」を選ぶ', exact: true })).not.toBeChecked() + await expect(drawer.getByRole('checkbox', { name: '「見積の旧作業場所」を選ぶ', exact: true })).not.toBeChecked() + + // Delete: the Dashboard's warning, and rows whose work never left the workspace are named. + await drawer.getByRole('button', { name: '選んだ 2 件を削除', exact: true }).click() + const confirm = page.getByRole('dialog', { name: '作業場所 2 件を削除しますか?', exact: true }) + await expect(confirm).toContainText('置き場に送っていない変更は消えます。') + await expect(confirm).toContainText('2 件は置き場に送っていません。変更はこの作業場所にしかありません。') + const rows = confirm.getByRole('list', { name: '削除する作業場所', exact: true }).getByRole('listitem') + await expect(rows).toHaveCount(2) + await expect(rows.filter({ hasText: '置き場に未送信' })).toHaveCount(2) + + const deletes = ['devws-uriage-board', 'devws-kintai-csv'].map((id) => + page.waitForResponse((response) => response.request().method() === 'DELETE' && new URL(response.url()).pathname === `${workspaces}/${id}`)) + await confirm.getByRole('button', { name: '2 件を削除する', exact: true }).click() + for (const response of await Promise.all(deletes)) { + expect(response.status()).toBe(202) + expect(await response.request().headerValue('idempotency-key')).toBeTruthy() + } + await expect(rows.filter({ hasText: '削除を受け付けました' })).toHaveCount(2) + // The footer's 閉じる replaces 削除する once the run is over (the header ✕ is the other 閉じる). + await expect(confirm.getByRole('button', { name: '閉じる', exact: true })).toHaveCount(2) + await confirm.getByRole('button', { name: '閉じる', exact: true }).last().click() + await expect(confirm).toBeHidden() + await expect(drawer.locator('[data-workspace-id="devws-uriage-board"], [data-workspace-id="devws-kintai-csv"]')).toHaveCount(0) + await expect(drawer.getByTestId('my-workspaces-summary')).toHaveText('データを残している作業場所 4 件 · 7 日以上使っていないもの 0 件') + await expect(drawer.getByRole('button', { name: '片づける', exact: true })).toHaveCount(0) + }) +}) diff --git a/web/package.json b/web/package.json index cf32988..bdf68c8 100644 --- a/web/package.json +++ b/web/package.json @@ -18,7 +18,7 @@ "test:e2e:mock": "playwright test --config e2e/playwright.config.ts --grep @mock" }, "dependencies": { - "@appthrust/api-schema": "^0.1.7", + "@appthrust/api-schema": "^0.1.8", "@appthrust/app-launcher": "^0.1.5", "@appthrust/platform-dashboard-i18n": "^0.1.5", "@orpc/client": "^1.13.13", diff --git a/web/src/api/contracts/platform/workspace.test.ts b/web/src/api/contracts/platform/workspace.test.ts index 91d8734..244a419 100644 --- a/web/src/api/contracts/platform/workspace.test.ts +++ b/web/src/api/contracts/platform/workspace.test.ts @@ -2,7 +2,8 @@ import { describe, expect, test } from 'bun:test' import { isOneOf, type PreviewWorkspace } from '../../../model/contracts/build' import { previewDatabaseStatus } from '../../../features/build/implement/runtime' import { assertWireContractCases } from '../../testing/wire-contract-cases' -import { getDevWorkspaceContract, restartDevWorkspaceContract } from './workspace' +import type { MyWorkspace } from '../../../model/contracts/workspace' +import { deleteDevWorkspaceContract, extendDevWorkspaceLeaseContract, getDevWorkspaceContract, listDevWorkspacesContract, restartDevWorkspaceContract, stopDevWorkspaceContract } from './workspace' const SECRET = 'SENTINEL-workspace-91d4' const at = '2026-11-13T00:00:00Z' @@ -100,3 +101,66 @@ describe('DevWorkspace restart (platformApiRestartDevWorkspace)', () => { ]) }) }) + +/** A row of `GET dev-workspaces?owner=me` as Platform 0.1.8 marshals it (`state`, `lease`, `allowedActions`, `sourceVolume`). */ +const actions = { open: true, stop: true, start: false, restart: true, extendLease: true, keepLonger: false, delete: true, commit: true, blockedBy: {} } +const wireRow = { + ...wireWorkspace, ownedByCaller: true, state: 'Ready', lastActivityAt: at, + lease: { lastActivityAt: at, expiresAt: '2026-11-13T01:00:00Z', ttlSeconds: 3600, source: 'default' }, + sourceVolume: { state: 'Retained', releaseAt: '2026-11-20T00:00:00Z', retention: { class: null, project: null, effective: null, source: 'none', policyValid: true } }, + runtime: { ready: true, editorReady: true, previewReady: true, codexReady: true, claudeReady: false, sandboxRuntime: 'GVisor' }, + allowedActions: actions, +} +const domainRow: MyWorkspace = { + id: 'ws-1', projectId: 'project-1', displayName: '見積の作業場所', draftId: 'draft-1', ownedByCaller: true, lastActivityAt: at, + scope: { kind: 'known', value: 'applicationDraft' }, state: { kind: 'known', value: 'Ready' }, + lease: { lastActivityAt: at, expiresAt: '2026-11-13T01:00:00Z', ttlSeconds: 3600 }, + sourceVolume: { state: { kind: 'known', value: 'Retained' }, releaseAt: '2026-11-20T00:00:00Z' }, + allowedActions: actions, +} +const summary = { total: 1, active: 1, sleeping: 0, stopped: 0, retainedSourceVolumes: 1, idleRetained: 0, degraded: 0, retired: 0 } +const wireList = { data: [wireRow], meta: { total: 1 }, summary, idleAfter: '168h0m0s' } +const listWith = (row: unknown) => ({ ...wireList, data: [row] }) + +describe('My workspaces list (platformApiListDevWorkspaces, owner=me)', () => { + test('wire variants', () => { + assertWireContractCases(listDevWorkspacesContract, [ + { name: 'a row keeps only what the drawer shows', variant: 'present', path: '/', wire: wireList, expect: { accept: true, value: { data: [domainRow], summary, idleAfter: '168h0m0s' } } }, + { name: 'no workspaces', variant: 'empty', path: '/data', wire: { ...wireList, data: [], summary: { ...summary, total: 0, active: 0, retainedSourceVolumes: 0 } }, expect: { accept: true, check: (list) => expect(list.data).toEqual([]) } }, + { name: 'an unknown state is unknown, never running', variant: 'unknown', path: '/data/*/state', wire: listWith({ ...wireRow, state: SECRET }), expect: { accept: true, check: (list) => expect(list.data[0]?.state).toEqual({ kind: 'unknown' }) } }, + { name: 'a server without `state` reads the state its phase stands for', variant: 'absent', path: '/data/*/state', wire: listWith({ ...wireRow, state: undefined, phase: 'Stopping' }), expect: { accept: true, check: (list) => expect(list.data[0]?.state).toEqual({ kind: 'known', value: 'Stopped' }) } }, + { name: 'without `state`, an unknown phase is an unknown state', variant: 'unknown', path: '/data/*/phase', wire: listWith({ ...wireRow, state: undefined, phase: SECRET }), expect: { accept: true, check: (list) => expect(list.data[0]?.state).toEqual({ kind: 'unknown' }) } }, + { name: 'an unknown scope is unknown', variant: 'unknown', path: '/data/*/scope', wire: listWith({ ...wireRow, scope: SECRET }), expect: { accept: true, check: (list) => expect(list.data[0]?.scope).toEqual({ kind: 'unknown' }) } }, + { name: 'an unknown source volume state is unknown', variant: 'unknown', path: '/data/*/sourceVolume/state', wire: listWith({ ...wireRow, sourceVolume: { state: SECRET } }), expect: { accept: true, check: (list) => expect(list.data[0]?.sourceVolume?.state).toEqual({ kind: 'unknown' }) } }, + { name: 'an unknown lease source or sandbox runtime does not break the row', variant: 'unknown', path: '/data/*/lease/source', wire: listWith({ ...wireRow, lease: { ...wireRow.lease, source: SECRET }, runtime: { ...wireRow.runtime, sandboxRuntime: SECRET } }), expect: { accept: true, check: (list) => expect(list.data[0]?.lease).toEqual(domainRow.lease) } }, + { name: 'a server without allowed actions offers none', variant: 'absent', path: '/data/*/allowedActions', wire: listWith({ ...wireRow, allowedActions: undefined }), expect: { accept: true, check: (list) => expect(list.data[0]?.allowedActions).toBeUndefined() } }, + { name: 'a Retired row keeps when Platform deletes it', variant: 'present', path: '/data/*/retired', wire: listWith({ ...wireRow, state: 'Retired', phase: 'Failed', retired: { at, reason: 'RuntimeTargetReplaced', deleteAt: '2026-11-20T00:00:00Z' } }), expect: { accept: true, check: (list) => { expect(list.data[0]?.state).toEqual({ kind: 'known', value: 'Retired' }); expect(list.data[0]?.retired?.deleteAt).toBe('2026-11-20T00:00:00Z') } } }, + { name: 'broken allowed actions are broken, not "nothing allowed"', variant: 'unknown', path: '/data/*/allowedActions', wire: listWith({ ...wireRow, allowedActions: { ...actions, delete: SECRET } }), expect: { accept: false, issues: [{ path: '/data/*/allowedActions/delete', code: 'invalid_type' }] } }, + { name: 'a summary is required', variant: 'absent', path: '/summary', wire: { ...wireList, summary: undefined }, expect: { accept: false, issues: [{ path: '/summary', code: 'missing' }] } }, + { name: 'idleAfter is required', variant: 'absent', path: '/idleAfter', wire: { ...wireList, idleAfter: undefined }, expect: { accept: false, issues: [{ path: '/idleAfter', code: 'missing' }] } }, + { name: 'null data is broken', variant: 'null', path: '/data', wire: { ...wireList, data: null }, expect: { accept: false, issues: [{ path: '/data', code: 'invalid_type' }] } }, + ]) + }) +}) + +describe('My workspaces writes (extend-lease, stop, delete)', () => { + const operation = { id: 'op-2', type: 'devWorkspace.extendLease', state: 'accepted', writeChannel: 'A', resource: { kind: 'DevWorkspace', id: 'ws-1', projectId: 'project-1' }, createdAt: at, links: { self: '/api/v1/operations/op-2' } } + const wireWrite = { ...wireRow, operation, resource: wireRow } + + test('extend-lease and stop read the written row', () => { + for (const contract of [extendDevWorkspaceLeaseContract, stopDevWorkspaceContract]) { + assertWireContractCases(contract, [ + { name: 'the written workspace is the answer\'s resource', variant: 'present', path: '/resource', wire: wireWrite, expect: { accept: true, value: domainRow } }, + { name: 'an answer without its resource is broken', variant: 'absent', path: '/resource', wire: { ...wireRow, operation }, expect: { accept: false, issues: [{ path: '/resource', code: 'missing' }] } }, + { name: 'an unknown state of the written workspace is unknown', variant: 'unknown', path: '/resource/state', wire: { ...wireWrite, resource: { ...wireRow, state: SECRET } }, expect: { accept: true, check: (workspace) => expect(workspace.state).toEqual({ kind: 'unknown' }) } }, + ]) + } + }) + + test('delete reads the accepted workspace id', () => { + assertWireContractCases(deleteDevWorkspaceContract, [ + { name: 'the receipt names the workspace', variant: 'present', path: '/operation', wire: { pendingSync: false, operation: { ...operation, type: 'devWorkspace.delete' } }, expect: { accept: true, value: { id: 'ws-1' } } }, + { name: 'an answer without its receipt is broken', variant: 'absent', path: '/operation', wire: { pendingSync: false }, expect: { accept: false, issues: [{ path: '/operation', code: 'missing' }] } }, + ]) + }) +}) diff --git a/web/src/api/contracts/platform/workspace.ts b/web/src/api/contracts/platform/workspace.ts index a5e6fda..420046c 100644 --- a/web/src/api/contracts/platform/workspace.ts +++ b/web/src/api/contracts/platform/workspace.ts @@ -5,9 +5,24 @@ // unknown engine pauses only the preview database's own actions. `conditions` // is required: Go never omits it, and null (a nil slice) is a failure, not // "no conditions". -import { DevWorkspaceCondition, DevWorkspacePhase, DevWorkspacePreviewDatabase, DevWorkspacePreviewDatabaseEngine, DevWorkspaceRead } from '@appthrust/api-schema/platform-api' +// +// 「自分の作業場所」 rows (`owner=me` list, extend-lease, stop) read only the +// fields the drawer shows, with open `state`, `scope` and source volume state. +import { + DevWorkspaceCondition, + DevWorkspaceListSummary, + DevWorkspacePhase, + DevWorkspacePreviewDatabase, + DevWorkspacePreviewDatabaseEngine, + DevWorkspaceRead, + DevWorkspaceScope, + DevWorkspaceSourceVolume, + DevWorkspaceState, +} from '@appthrust/api-schema/platform-api' import { z } from 'zod' +import type { OpenValue } from '../../boundary' import type { PreviewWorkspace } from '../../../model/contracts/build' +import type { MyWorkspace, MyWorkspaceList, WorkspaceDeletion, WorkspaceState } from '../../../model/contracts/workspace' import { platformContract } from '../define' import { openCanonical } from './build' @@ -17,7 +32,41 @@ const workspaceReader: z.ZodType = DevWorkspaceRead.extend({ previewDatabase: DevWorkspacePreviewDatabase.extend({ engine: openCanonical(DevWorkspacePreviewDatabaseEngine) }).optional(), }) -const WORKSPACE = '/api/v1/projects/{projectId}/dev-workspaces/{id}' +/** The product state a phase stands for, on a server that predates `state` (platform-api deriveWorkspaceState). */ +const STATE_BY_PHASE: Record = { + Pending: 'Starting', Starting: 'Starting', Ready: 'Ready', Degraded: 'Degraded', Committing: 'Committing', + Sleeping: 'Sleeping', Stopping: 'Stopped', Stopped: 'Stopped', Failed: 'Failed', Deleting: 'Deleting', +} + +const fields = DevWorkspaceRead.shape +const myWorkspaceReader: z.ZodType = DevWorkspaceRead.pick({ + id: true, projectId: true, displayName: true, applicationId: true, applicationBranchId: true, draftId: true, + branchUrl: true, pullRequestUrl: true, lastActivityAt: true, ownedByCaller: true, retired: true, allowedActions: true, +}).extend({ + scope: openCanonical(DevWorkspaceScope), + phase: openCanonical(DevWorkspacePhase), + state: openCanonical(DevWorkspaceState).optional(), + lease: fields.lease.unwrap().pick({ lastActivityAt: true, expiresAt: true, ttlSeconds: true }).optional(), + sourceVolume: DevWorkspaceSourceVolume.pick({ releaseAt: true }).extend({ state: openCanonical(DevWorkspaceSourceVolume.shape.state) }).optional(), +}).transform(({ phase, state, ...workspace }): MyWorkspace => ({ + ...workspace, + state: state ?? (phase.kind === 'known' ? { kind: 'known', value: STATE_BY_PHASE[phase.value] } : phase) as OpenValue, +})) + +const myWorkspaceListReader: z.ZodType = z.object({ + data: z.array(myWorkspaceReader), + summary: DevWorkspaceListSummary, + idleAfter: z.string(), +}) + +/** The written workspace of a mutation answer (`resource`). */ +const resourceOf = (reader: z.ZodType) => z.object({ resource: reader }).transform(({ resource }) => resource) + +const deletionReader: z.ZodType = z.object({ operation: z.object({ resource: z.object({ id: z.string().min(1) }) }) }) + .transform(({ operation }) => ({ id: operation.resource.id })) + +const WORKSPACES = '/api/v1/projects/{projectId}/dev-workspaces' +const WORKSPACE = `${WORKSPACES}/{id}` export const getDevWorkspaceContract = platformContract({ operationId: 'platformApiGetDevWorkspace', @@ -33,5 +82,41 @@ export const restartDevWorkspaceContract = platformContract({ method: 'POST', routeTemplate: `${WORKSPACE}/restart`, successStatuses: [202], - reader: z.object({ resource: workspaceReader }).transform(({ resource }) => resource), + reader: resourceOf(workspaceReader), +}) + +/** The caller's workspaces with `owner: 'me'` (platform-api handler/dev_workspace.go list, 200). */ +export const listDevWorkspacesContract = platformContract({ + operationId: 'platformApiListDevWorkspaces', + method: 'GET', + routeTemplate: WORKSPACES, + successStatuses: [200], + reader: myWorkspaceListReader, +}) + +/** Renews the activity lease of the caller's own running workspace (202; 409 when it is not running). */ +export const extendDevWorkspaceLeaseContract = platformContract({ + operationId: 'platformApiExtendDevWorkspaceLease', + method: 'POST', + routeTemplate: `${WORKSPACE}/extend-lease`, + successStatuses: [202], + reader: resourceOf(myWorkspaceReader), +}) + +/** Stops compute; the source data stays until the workspace is deleted (202). */ +export const stopDevWorkspaceContract = platformContract({ + operationId: 'platformApiStopDevWorkspace', + method: 'POST', + routeTemplate: `${WORKSPACE}/stop`, + successStatuses: [202], + reader: resourceOf(myWorkspaceReader), +}) + +/** Deletes the workspace and its source data (202, replayed for the same Idempotency-Key). */ +export const deleteDevWorkspaceContract = platformContract({ + operationId: 'platformApiDeleteDevWorkspace', + method: 'DELETE', + routeTemplate: WORKSPACE, + successStatuses: [202], + reader: deletionReader, }) diff --git a/web/src/api/queries/workspaces.ts b/web/src/api/queries/workspaces.ts new file mode 100644 index 0000000..368deed --- /dev/null +++ b/web/src/api/queries/workspaces.ts @@ -0,0 +1,17 @@ +// 「自分の作業場所」: the caller's DevWorkspaces (`owner=me`). One read shared by +// the header badge, the drawer and the in-session lease hint. +import { queryOptions } from '@tanstack/react-query' +import { listMyWorkspaces } from '../workspace' + +/** Leases are minutes long and the hint counts down on its own clock, so the list is re-read every 30 s. */ +export const MY_WORKSPACES_POLL_MS = 30_000 + +export const workspaceKeys = { + mine: (projectId: string) => ['dev-workspaces', projectId, 'mine'] as const, +} + +export const myWorkspacesOptions = (projectId: string) => queryOptions({ + queryKey: workspaceKeys.mine(projectId), + queryFn: ({ signal }) => listMyWorkspaces(projectId, signal), + refetchInterval: MY_WORKSPACES_POLL_MS, +}) diff --git a/web/src/api/workspace.ts b/web/src/api/workspace.ts index 51cc44f..0b73335 100644 --- a/web/src/api/workspace.ts +++ b/web/src/api/workspace.ts @@ -1,6 +1,14 @@ import type { RestartDevWorkspaceRequest } from '@appthrust/api-schema/platform-api' import type { PreviewWorkspace } from '../model/contracts/build' -import { getDevWorkspaceContract, restartDevWorkspaceContract } from './contracts/platform/workspace' +import type { MyWorkspace, MyWorkspaceList, WorkspaceDeletion } from '../model/contracts/workspace' +import { + deleteDevWorkspaceContract, + extendDevWorkspaceLeaseContract, + getDevWorkspaceContract, + listDevWorkspacesContract, + restartDevWorkspaceContract, + stopDevWorkspaceContract, +} from './contracts/platform/workspace' import { apiGateway } from './gateway' /** Runtime URLs stay on the console proxy. The edge, not JavaScript, adds Authorization. */ @@ -21,6 +29,26 @@ export function restartWorkspace(projectId: string, workspaceId: string, body: R return apiGateway.platform(restartDevWorkspaceContract, { projectId, id: workspaceId, ...body }) } +/** The caller's own workspaces (`owner=me`); other people's never appear. */ +export function listMyWorkspaces(projectId: string, signal: AbortSignal): Promise { + return apiGateway.platform(listDevWorkspacesContract, { projectId, owner: 'me' }, { signal }) +} + +/** Renews the activity lease of the caller's running workspace. */ +export function extendWorkspaceLease(projectId: string, workspaceId: string): Promise { + return apiGateway.platform(extendDevWorkspaceLeaseContract, { projectId, id: workspaceId }) +} + +/** Stops compute; the source data stays until the workspace is deleted. */ +export function stopWorkspace(projectId: string, workspaceId: string): Promise { + return apiGateway.platform(stopDevWorkspaceContract, { projectId, id: workspaceId }) +} + +/** Deletes the workspace and its source data. `idempotencyKey`: one per workspace and user intent, reused by a retry. */ +export function deleteWorkspace(projectId: string, workspaceId: string, idempotencyKey: string): Promise { + return apiGateway.platform(deleteDevWorkspaceContract, { projectId, id: workspaceId }, { idempotencyKey }) +} + /** * The HTTP status of the preview page the iframe will load, or undefined when * nothing answered. Only the status is read: the page is the app's HTML, not diff --git a/web/src/dev/mock-platform.ts b/web/src/dev/mock-platform.ts index b4aa45f..39256c8 100644 --- a/web/src/dev/mock-platform.ts +++ b/web/src/dev/mock-platform.ts @@ -82,6 +82,10 @@ // `__mock/advance`). The `__mock/data` mode `forbidden` makes the list answer 403 too. // - `POST /api/v1/__mock/access-forbidden {forbidden}` denies access PUTs without changing policy. // Each accepted access write reports pending for one GET poll, then ready. +// - 「自分の作業場所」 (./mock-workspaces.ts): the signed-in person has six seeded workspaces (Running 2, Sleeping 2, +// Stopped 1, Retired 1). `GET dev-workspaces?owner=me` answers them with state, allowedActions, lease, summary and +// idleAfter; extend-lease renews a running one for an hour, stop stops it, DELETE removes it, and restart answers +// 409 for a Retired one. // - `POST /api/v1/__mock/reset` returns {reset: true} and reseeds the entire mock, // reapplying MOCK_ROLE (default Editor), MOCK_REGISTRY and MOCK_CODEX. import { createHash, randomBytes } from 'node:crypto' @@ -146,6 +150,7 @@ import { isFirstTurn, isKickoffReply, isPrepareTurn } from '../model/build/quest import { dataModeFailure, findTable, resetDatabaseData, selectRows, state as dataState, type DataMode } from './mock-database-data' import { dataWriteRoutes } from './mock-database-rows' import { mockOwnerSubjects, mockProposalRefusal, mockSubject } from './mock-console' +import { MOCK_IDLE_AFTER, MOCK_LEASE_TTL_SECONDS, presentWorkspace, seedMyWorkspaces, summarizeWorkspaces } from './mock-workspaces' export const MOCK_PROJECT_ID = 'commerce' const TEAM_SLUG = 'commerce-team' @@ -948,7 +953,7 @@ function advanceDraft(draft: ApplicationDraft): boolean { return moved } -/** The application-scoped workspace a draft's runs (and improvement turns) reuse, created Ready on first use. */ +/** The application-scoped workspace a draft's runs (and improvement turns) reuse, created Ready on first use with an hour's lease. */ function ensureApplicationWorkspace(draft: ApplicationDraft, now: string): string { const id = draft.implementationWorkspaceId ?? nextId('ws') draft.implementationWorkspaceId = id @@ -958,6 +963,7 @@ function ensureApplicationWorkspace(draft: ApplicationDraft, now: string): strin id, projectId: draft.projectId, scope: 'application', applicationId: draft.createdApplicationId, componentId: `${draft.createdApplicationId}-web`, displayName: draft.title, ownerUserId: draft.ownerUserId, phase: 'Ready', branchName: draft.kind === 'improvement' ? `appthrust/proposal/${draft.id}` : 'main', baseRef: 'main', createdAt: now, conditions: [], + lastActivityAt: now, expiresAt: new Date(Date.parse(now) + MOCK_LEASE_TTL_SECONDS * 1_000).toISOString(), codexUrl: `${base}/codex/`, previewUrl: `${base}/proxy/preview/`, }) } @@ -1226,7 +1232,7 @@ function seedPlatform() { proposals: new Map(), draftReviewers: new Map(), workbooks: new Map>(), - workspaces: new Map(), + workspaces: new Map(seedMyWorkspaces(MOCK_PROJECT_ID).map((workspace) => [workspace.id, workspace])), documents: new Map>(), workspaceTodos: new Map(), workspaceOperations: new Map(), @@ -1716,12 +1722,45 @@ const routes: Array<[method: string, pattern: RegExp, handler: Handler]> = [ const workspace = state.workspaces.get(m[2]!) return workspace ? json(workspace) : error(404, 'not_found', 'workspace not found') }], + ['GET', new RegExp(`^${P}/dev-workspaces$`), (m, _, url) => { + const caller = mockSubject() + const rows = [...state.workspaces.values()] + .filter((workspace) => workspace.projectId === m[1] && (url.searchParams.get('owner') !== 'me' || workspace.ownerUserId === caller)) + .map((workspace) => presentWorkspace(workspace, caller, state.role !== 'Viewer')) + .sort((a, b) => Date.parse(b.lastActivityAt ?? b.createdAt ?? '') - Date.parse(a.lastActivityAt ?? a.createdAt ?? '')) + return json({ ...list(rows), summary: summarizeWorkspaces(rows, Date.now()), idleAfter: MOCK_IDLE_AFTER }) + }], ['POST', new RegExp(`^${P}/dev-workspaces/([^/]+)/restart$`), (m) => { const workspace = state.workspaces.get(m[2]!) if (!workspace) return error(404, 'not_found', 'workspace not found') + if (workspace.state === 'Retired') return error(409, 'conflict', 'a retired workspace cannot restart') workspace.phase = 'Starting' return json(mutation('DevWorkspace', workspace.id, workspace), 202) }], + ['POST', new RegExp(`^${P}/dev-workspaces/([^/]+)/extend-lease$`), (m) => { + const workspace = state.workspaces.get(m[2]!) + if (!workspace) return error(404, 'not_found', 'workspace not found') + if (workspace.ownerUserId !== mockSubject()) return error(403, 'dev_workspace_owner_required', 'only the workspace owner can extend its lease') + if (!presentWorkspace(workspace, mockSubject(), state.role !== 'Viewer').allowedActions?.extendLease) return error(409, 'conflict', 'workspace is not running') + const now = stamp() + const expiresAt = new Date(Date.parse(now) + MOCK_LEASE_TTL_SECONDS * 1_000).toISOString() + Object.assign(workspace, { lastActivityAt: now, expiresAt, lease: { ...workspace.lease, lastActivityAt: now, expiresAt, ttlSeconds: workspace.lease?.ttlSeconds ?? MOCK_LEASE_TTL_SECONDS, source: workspace.lease?.source ?? 'default' } }) + return json(mutation('DevWorkspace', workspace.id, presentWorkspace(workspace, mockSubject(), true)), 202) + }], + ['POST', new RegExp(`^${P}/dev-workspaces/([^/]+)/stop$`), (m) => { + const workspace = state.workspaces.get(m[2]!) + if (!workspace) return error(404, 'not_found', 'workspace not found') + if (!presentWorkspace(workspace, mockSubject(), state.role !== 'Viewer').allowedActions?.stop) return error(403, 'forbidden', 'workspace cannot be stopped') + workspace.phase = 'Stopped' + return json(mutation('DevWorkspace', workspace.id, presentWorkspace(workspace, mockSubject(), true)), 202) + }], + ['DELETE', new RegExp(`^${P}/dev-workspaces/([^/]+)$`), (m) => { + const workspace = state.workspaces.get(m[2]!) + if (!workspace) return error(404, 'not_found', 'workspace not found') + if (!presentWorkspace(workspace, mockSubject(), state.role !== 'Viewer').allowedActions?.delete) return error(403, 'forbidden', 'only the owner can delete this workspace') + state.workspaces.delete(workspace.id) + return json({ pendingSync: false, operation: operation('DevWorkspace', workspace.id) }, 202) + }], ['GET', new RegExp(`^${P}/dev-workspaces/([^/]+)/proxy/preview/$`), (m) => { const workspace = state.workspaces.get(m[2]!) if (!workspace) return error(404, 'not_found', 'workspace not found') diff --git a/web/src/dev/mock-workspaces.ts b/web/src/dev/mock-workspaces.ts new file mode 100644 index 0000000..e613f67 --- /dev/null +++ b/web/src/dev/mock-workspaces.ts @@ -0,0 +1,134 @@ +// 「自分の作業場所」 in the mock Platform (`GET dev-workspaces?owner=me`, +// extend-lease, stop, delete): six seeded workspaces of the signed-in person and +// the read model Platform derives for every row (platform-api +// handler/dev_workspace_management.go deriveWorkspaceState / decideWorkspaceActions, +// handler/dev_workspace.go summarizeDevWorkspaces). Routes live in ./mock-platform.ts. +import type { DevWorkspaceListSummary, DevWorkspacePhase, DevWorkspaceRead, DevWorkspaceState } from '@appthrust/api-schema/platform-api' + +type Actions = NonNullable + +/** Platform's default lease (pkg/devworkspacelease DefaultTTLSeconds) and idle threshold (`idleAfter`). */ +export const MOCK_LEASE_TTL_SECONDS = 3_600 +export const MOCK_IDLE_AFTER = '168h0m0s' +const IDLE_AFTER_MS = 168 * 3_600_000 + +const ACTIVE_PHASES: readonly DevWorkspacePhase[] = ['Pending', 'Starting', 'Ready', 'Degraded', 'Committing'] + +/** The stored `state` (only a Retired seed has one), else the state the phase stands for. */ +export function mockWorkspaceState(workspace: DevWorkspaceRead): DevWorkspaceState { + if (workspace.state) return workspace.state + switch (workspace.phase) { + case 'Deleting': return 'Deleting' + case 'Failed': return 'Failed' + case 'Stopping': case 'Stopped': return 'Stopped' + case 'Sleeping': case 'Degraded': case 'Committing': case 'Ready': return workspace.phase + default: return 'Starting' + } +} + +function decideActions(state: DevWorkspaceState, owner: boolean, write: boolean): Actions { + owner = owner && write + const running = state === 'Ready' || state === 'Degraded' + const stoppable = running || state === 'Starting' || state === 'Sleeping' + const actions: Actions = { + open: owner && (stoppable || state === 'Committing'), stop: write && stoppable, start: write && (state === 'Stopped' || state === 'Sleeping'), + // Exactly Platform's values: a Stopped workspace has `start`, not `restart`; the console runs `start` through the restart route. + restart: write && (running || state === 'Failed'), extendLease: owner && running, keepLonger: false, commit: owner && state === 'Ready', delete: owner, + blockedBy: {}, + } + if (!actions.open) actions.blockedBy.open = 'NotRunnable' + if (!actions.extendLease) actions.blockedBy.extendLease = 'NotRunning' + if (!actions.commit) actions.blockedBy.commit = 'NotRunning' + if (!owner) for (const key of ['open', 'extendLease', 'commit']) actions.blockedBy[key] = 'NotOwner' + if (!actions.start) actions.blockedBy.start = 'NotAllowed' + if (!actions.restart) actions.blockedBy.restart = 'NotAllowed' + if (state === 'Retired') Object.assign(actions.blockedBy, { start: 'Retired', restart: 'Retired' }) + if (!actions.stop) actions.blockedBy.stop = write ? 'Terminal' : 'NotAllowed' + if (!actions.delete) actions.blockedBy.delete = 'NotAllowed' + return actions +} + +/** The row as Platform answers it for `caller`: product state, allowed actions, lease and source volume. */ +export function presentWorkspace(workspace: DevWorkspaceRead, caller: string, write: boolean): DevWorkspaceRead { + const state = mockWorkspaceState(workspace) + const owner = workspace.ownerUserId === caller + const lastActivityAt = workspace.lastActivityAt ?? workspace.createdAt + return { + ...workspace, + state, + ownedByCaller: owner, + allowedActions: decideActions(state, owner, write), + lease: workspace.lease ?? { lastActivityAt, expiresAt: workspace.expiresAt, ttlSeconds: MOCK_LEASE_TTL_SECONDS, source: 'default' }, + sourceVolume: workspace.sourceVolume ?? { state: 'Retained' }, + } +} + +/** The list `summary` over the returned rows. */ +export function summarizeWorkspaces(rows: readonly DevWorkspaceRead[], now: number): DevWorkspaceListSummary { + const summary = { total: rows.length, active: 0, sleeping: 0, stopped: 0, retainedSourceVolumes: 0, idleRetained: 0, degraded: 0, retired: 0 } + for (const row of rows) { + const active = ACTIVE_PHASES.includes(row.phase) + if (active) summary.active++ + else if (row.phase === 'Sleeping') summary.sleeping++ + else if (row.phase === 'Stopping' || row.phase === 'Stopped' || row.phase === 'Failed') summary.stopped++ + if (row.state === 'Degraded') summary.degraded++ + if (row.state === 'Retired') summary.retired++ + if (row.sourceVolume?.state !== 'Retained') continue + summary.retainedSourceVolumes++ + const last = row.lastActivityAt ? Date.parse(row.lastActivityAt) : 0 + if (!active && last < now - IDLE_AFTER_MS) summary.idleRetained++ + } + return summary +} + +const at = (minutesFromNow: number) => new Date(Date.now() + minutesFromNow * 60_000).toISOString() +const DAY = 24 * 60 + +/** + * The seeded owner: 山田 太郎 (`p-yamada` in ./mock-console.ts), the signed-in person under the default console + * role. Another caller (`__mock/role`) sees none of these as theirs. A literal, because the Platform mock is + * seeded while ./mock-console.ts is still loading. + */ +const SEEDED_OWNER = 'sub-yamada' + +/** + * The signed-in person's six workspaces: Running 2 (one Ready with 42 minutes of + * lease, one Degraded inside the five-minute warning), Sleeping 2 (one idle for + * nine days, without a published branch), Stopped 1 (idle, kept until deleted) + * and Retired 1 (deleted by Platform in five days). + */ +export function seedMyWorkspaces(projectId: string): DevWorkspaceRead[] { + const base = (id: string) => `/api/v1/projects/${projectId}/dev-workspaces/${id}` + const workspace = (id: string, fields: Partial & Pick): DevWorkspaceRead => ({ + id, projectId, scope: 'application', ownerUserId: SEEDED_OWNER, branchName: `appthrust/${id}`, baseRef: 'main', conditions: [], ...fields, + }) + const lease = (lastActivity: number, expires: number) => ({ lastActivityAt: at(lastActivity), expiresAt: at(expires), ttlSeconds: MOCK_LEASE_TTL_SECONDS, source: 'default' as const }) + return [ + workspace('devws-mitsumori-fix', { + displayName: '見積の明細を直す', applicationId: 'mitsumori', phase: 'Ready', createdAt: at(-90), lastActivityAt: at(-18), lease: lease(-18, 42), + branchUrl: 'https://github.com/acme/mitsumori/tree/appthrust/devws-mitsumori-fix', editorUrl: `${base('devws-mitsumori-fix')}/editor/`, + sourceVolume: { state: 'Retained' }, + }), + workspace('devws-nippo-filter', { + displayName: '日報に絞り込みを足す', applicationId: 'nippo', phase: 'Degraded', createdAt: at(-75), lastActivityAt: at(-57), lease: lease(-57, 3), + degraded: [{ reason: 'PreviewNotListening', message: 'preview is not listening yet' }], sourceVolume: { state: 'Retained' }, + }), + workspace('devws-keihi-receipt', { + displayName: '経費に領収書を添付する', applicationId: 'keihi', phase: 'Sleeping', createdAt: at(-4 * DAY), lastActivityAt: at(-2 * DAY), lease: lease(-2 * DAY, -2 * DAY + 60), + pullRequestUrl: 'https://github.com/acme/keihi/pull/12', sourceVolume: { state: 'Retained', releaseAt: at(5 * DAY) }, + }), + workspace('devws-uriage-board', { + displayName: '売上ダッシュボード', scope: 'applicationDraft', draftId: 'draft-uriage-board', phase: 'Sleeping', createdAt: at(-12 * DAY), lastActivityAt: at(-9 * DAY), + lease: lease(-9 * DAY, -9 * DAY + 60), sourceVolume: { state: 'Retained', releaseAt: at(DAY) }, + }), + workspace('devws-kintai-csv', { + displayName: '勤怠を CSV で出す', applicationId: 'kintai', phase: 'Stopped', createdAt: at(-20 * DAY), lastActivityAt: at(-12 * DAY), lease: lease(-12 * DAY, -12 * DAY + 60), + sourceVolume: { state: 'Retained' }, + }), + workspace('devws-mitsumori-old', { + displayName: '見積の旧作業場所', applicationId: 'mitsumori', phase: 'Failed', state: 'Retired', createdAt: at(-6 * DAY), lastActivityAt: at(-3 * DAY), + lease: lease(-3 * DAY, -3 * DAY + 60), retired: { at: at(-2 * DAY), reason: 'RuntimeTargetReplaced', deleteAt: at(5 * DAY) }, + sourceVolume: { state: 'Retained' }, + }), + ] +} diff --git a/web/src/features/build/build-page.tsx b/web/src/features/build/build-page.tsx index 7d7dab3..dcb46ad 100644 --- a/web/src/features/build/build-page.tsx +++ b/web/src/features/build/build-page.tsx @@ -43,6 +43,7 @@ import { BuildFailureNotice } from './build-failure-notice' import { useCreatedAppView } from './use-created-app-view' import { BuildOutcomeTurn } from './build-outcome' import { shareScopeLabel } from '../../model/access' +import { sessionWorkspaceId } from '../workspaces' export function BuildPage({ draftId }: { draftId: string }) { const { me, groups, currentGroup } = useShell() @@ -131,7 +132,7 @@ function Session({ draft, groupId, stale }: { draft: BuildDraft; groupId: string publish={{ label: buildCopy.primary.publish, enabled: primary.action === 'publish' && primary.enabled, onClick: onPrimary }} retry={retryable ? { pending: Boolean(build.implementation.state.retryPending), onClick: build.implementation.retry } : undefined} /> return
- } /> + } /> {/* Page-level notices share one inset place under the header, whatever raised them. */} {stale || build.result.unsupported || draft.buildFailure || creationAccess.error ?
{stale} diff --git a/web/src/features/build/console-build-page.tsx b/web/src/features/build/console-build-page.tsx index cd33478..9463c4e 100644 --- a/web/src/features/build/console-build-page.tsx +++ b/web/src/features/build/console-build-page.tsx @@ -28,6 +28,7 @@ import { text } from './copy' import { SessionHeader } from './session-header' import { UnconfirmedNotice } from './unconfirmed-notice' import { useConsoleBuildSession, type ConsoleBuildActions } from './use-console-build-session' +import { sessionWorkspaceId } from '../workspaces' export function ConsoleBuildPage({ sessionId }: { sessionId: string }) { const build = useConsoleBuildSession(sessionId) @@ -57,10 +58,10 @@ function ConsoleWithDraft({ view, actions, stale, draftId }: { view: ConsoleBuil function ConsoleDraftView({ view, actions, stale, draft, me, groups }: { view: ConsoleBuildView; actions: ConsoleBuildActions; stale: ReactNode; draft: BuildDraft; me: Me; groups: Group[] }) { const [openArtifact, setOpenArtifact] = useState(0) const stages = useConsoleDraftStages({ view, actions, draft, me, groups, onOpenArtifact: () => setOpenArtifact((count) => count + 1) }) - return + return } -function ConsoleLayout({ view, actions, stale, stages, draftError, openArtifact = 0 }: { view: ConsoleBuildView; actions: ConsoleBuildActions; stale: ReactNode; stages?: ConsoleStages; draftError?: unknown; openArtifact?: number }) { +function ConsoleLayout({ view, actions, stale, stages, draftError, openArtifact = 0, workspaceId }: { view: ConsoleBuildView; actions: ConsoleBuildActions; stale: ReactNode; stages?: ConsoleStages; draftError?: unknown; openArtifact?: number; workspaceId?: string }) { const { session } = view const name = parseSpec(session.specification.markdown).spec.name || text.session.newApp useDocumentTitle(text.page.title(name)) @@ -88,7 +89,7 @@ function ConsoleLayout({ view, actions, stale, stages, draftError, openArtifact : undefined) const busy = Boolean(planWaiting) || stages?.stage === 'build' return
- + ] : []), ...(stages?.notices ?? []), diff --git a/web/src/features/build/session-header.tsx b/web/src/features/build/session-header.tsx index bdaebf6..f3d6a39 100644 --- a/web/src/features/build/session-header.tsx +++ b/web/src/features/build/session-header.tsx @@ -8,6 +8,7 @@ import { buildStages, stageLabels } from './session' import { localized } from '../../shell/language' import { text, textJa } from './copy' import { textEn } from './copy.en' +import { WorkspaceLeaseHint } from '../workspaces' /** `unsupported`: the draft is in a state this console does not know, so no step is marked as the current one. */ export function StageRail({ stage, unsupported = false }: { stage: BuildStage; unsupported?: boolean }) { @@ -46,8 +47,9 @@ function outcomeState(stage: BuildStage, outcome: BuildOutcome | undefined): { s * One row from lg: back · name · state · rail · stage action. When the width runs * out (390px) the rail and the action wrap to a second row, action right-aligned. * While the implementation runs, the state word is followed by its tasks done and the run's 経過. + * `workspaceId`: the session's workspace; while it runs, its lease countdown follows (devworkspace builder-console.md §4). */ -export function SessionHeader({ name, stage, action, released = false, unsupported = false, outcome }: { name: string; stage: BuildStage; action?: ReactNode; released?: boolean; unsupported?: boolean; outcome?: BuildOutcome }) { +export function SessionHeader({ name, stage, action, released = false, unsupported = false, outcome, workspaceId }: { name: string; stage: BuildStage; action?: ReactNode; released?: boolean; unsupported?: boolean; outcome?: BuildOutcome; workspaceId?: string }) { const back = stage === 'publish' ? { href: paths.mine(), label: text.header.myApps } : { href: paths.drafts(), label: text.header.drafts } const state = outcomeState(stage, outcome) const running = stage === 'build' && outcome?.kind === 'implementing' ? outcome : undefined @@ -64,7 +66,10 @@ export function SessionHeader({ name, stage, action, released = false, unsupport
- {action ?
{action}
: null} + {workspaceId || action ?
+ {workspaceId ? : null} + {action} +
: null}
} diff --git a/web/src/features/improve/improve-page.tsx b/web/src/features/improve/improve-page.tsx index f5f1ca5..875e804 100644 --- a/web/src/features/improve/improve-page.tsx +++ b/web/src/features/improve/improve-page.tsx @@ -21,6 +21,7 @@ import { ImproveSidePane } from './side-pane' import { useImproveSession } from './use-improve-session' import { text as proposalText } from '../proposals/copy' import { ProposalOutcome, ProposalStatus } from '../proposals/proposal-ui' +import { sessionWorkspaceId, WorkspaceLeaseHint } from '../workspaces' const PILL: Record = { asking: 'unfinished', proposed: 'unfinished', running: 'deploying', failed: 'failed', done: 'live', unsupported: 'unfinished' } @@ -72,7 +73,10 @@ function Session({ draft, stale }: { draft: BuildDraft; stale: ReactNode }) {
text.stageLabels[stage])} /> - {action ?
{action}
: null} +
+ + {action} +
{/* Page-level notices share one inset place under the header, whatever raised them. */} diff --git a/web/src/features/workspaces/copy.en.ts b/web/src/features/workspaces/copy.en.ts new file mode 100644 index 0000000..dd57b47 --- /dev/null +++ b/web/src/features/workspaces/copy.en.ts @@ -0,0 +1,103 @@ +import type { workspacesJa } from './copy' + +const plural = (n: number, one: string, many: string) => (n === 1 ? `1 ${one}` : `${n} ${many}`) + +export const workspacesEn: typeof workspacesJa = { + title: 'My workspaces', + entry: (running: number) => (running > 0 ? `My workspaces (${running} running)` : 'My workspaces'), + description: 'Your own workspaces for building with AI.', + groups: { + running: 'Running', + sleeping: 'Sleeping', + other: 'Stopped · Retired · Failed', + }, + groupCount: (n: number) => String(n), + state: { + Ready: 'Ready', + Starting: 'Starting', + Degraded: 'Degraded', + Committing: 'Saving', + Sleeping: 'Sleeping', + Stopped: 'Stopped', + Retired: 'Retired', + Failed: 'Failed', + Deleting: 'Deleting', + unknown: 'Unknown', + }, + target: { + draft: 'New app', + application: (app: string) => `App ${app}`, + branch: (app: string, branch: string) => `App ${app} / ${branch}`, + unknown: 'Unknown target', + }, + line: { + lease: (minutes: number) => `Sleeps in ${minutes} min`, + leaseExpired: 'Sleeping soon', + dataUntil: (date: string) => `Data until ${date}`, + dataKept: 'Data kept until deleted', + dataReleasing: 'Releasing data', + dataReleased: 'Data released', + stopped: 'Stopped workspaces keep source data until deleted', + retired: (date: string) => `Unusable, auto-deleted ${date}.`, + retiredUndated: 'Unusable, deleted automatically.', + unknown: 'This state cannot be shown yet', + }, + summary: { + kept: (n: number) => `${plural(n, 'workspace keeps', 'workspaces keep')} source data`, + idle: (n: number, idleAfter: string) => `${n} idle ≥ ${idleAfter}`, + separator: ' · ', + }, + duration: { + days: (n: number) => plural(n, 'day', 'days'), + hours: (n: number) => plural(n, 'hour', 'hours'), + }, + cleanup: 'Clean up', + cleanupSelected: (n: number) => `Selected ${plural(n, 'idle workspace', 'idle workspaces')}. Review them, then delete.`, + select: (name: string) => `Select ${name}`, + selection: (n: number) => `${n} selected`, + clearSelection: 'Clear selection', + deleteSelected: (n: number) => `Delete ${n} selected`, + action: { + open: 'Open', + resume: 'Resume', + restart: 'Restart', + extend: 'Extend', + stop: 'Stop', + delete: 'Delete', + }, + actionLabel: (name: string, action: string) => `${action} ${name}`, + extended: (name: string) => `Extended the lease of ${name}.`, + stopped: (name: string) => `Stopped ${name}.`, + restarted: (name: string) => `Restarting ${name}.`, + stop: { + title: (name: string) => `Stop ${name}?`, + body: 'Stopped workspaces keep source data until deleted.', + confirm: 'Stop', + }, + remove: { + title: (n: number) => (n === 1 ? 'Delete workspace?' : `Delete ${n} workspaces?`), + warning: 'Unpushed changes in these workspaces are lost.', + body: 'The workspace and its source data are deleted. Pushed branches and pull requests stay in the repository.', + rows: 'Workspaces to delete', + unpublished: 'No published branch', + retired: 'Retired · already unusable', + unpublishedNote: (n: number) => (n === 1 + ? '1 workspace has no published branch; its work exists only in the workspace.' + : `${n} workspaces have no published branch; their work exists only in the workspace.`), + confirm: (n: number) => (n === 1 ? 'Delete' : `Delete ${n} workspaces`), + deleting: 'Deleting', + deleted: 'Deletion started', + retryFailed: 'Retry failed', + }, + empty: { + title: 'No workspaces yet', + body: 'Workspaces appear here once you build with AI.', + }, + leaseHint: { + remaining: (minutes: number) => `Expires in ${minutes} min`, + expired: 'Sleeping soon', + extendLabel: (shown: string) => `${shown} (press to extend the lease)`, + extended: 'Lease extended', + failed: 'Could not extend the lease', + }, +} diff --git a/web/src/features/workspaces/copy.ts b/web/src/features/workspaces/copy.ts new file mode 100644 index 0000000..1d8d77f --- /dev/null +++ b/web/src/features/workspaces/copy.ts @@ -0,0 +1,106 @@ +// 「自分の作業場所」 wording (devworkspace builder-console.md §1–§4). 敬体; +// headings ≤ 20 字, explanations ≤ 40 字. 作業場所 = DevWorkspace, 置き場 = repository, +// 休止 = Sleeping (compute stops when the lease runs out; the data stays). +import { localized } from '../../shell/language' +import { workspacesEn } from './copy.en' + +export const workspacesJa = { + title: '自分の作業場所', + entry: (running: number) => (running > 0 ? `自分の作業場所(動いているもの ${running} 件)` : '自分の作業場所'), + description: 'AI と作るときに使う、あなた専用の作業場所です。', + groups: { + running: '動いている', + sleeping: '休止中', + other: '停止・使用終了・失敗', + }, + groupCount: (n: number) => `${n} 件`, + state: { + Ready: '稼働中', + Starting: '起動中', + Degraded: '一部不調', + Committing: '保存中', + Sleeping: '休止中', + Stopped: '停止', + Retired: '使用終了', + Failed: '失敗', + Deleting: '削除中', + unknown: '不明', + }, + target: { + draft: '新しいアプリ', + application: (app: string) => `アプリ ${app}`, + branch: (app: string, branch: string) => `アプリ ${app} / ${branch}`, + unknown: '対象不明', + }, + line: { + lease: (minutes: number) => `あと ${minutes} 分で休止します`, + leaseExpired: 'まもなく休止します', + dataUntil: (date: string) => `データは ${date} まで残ります`, + dataKept: 'データは削除するまで残ります', + dataReleasing: 'データを解放しています', + dataReleased: 'データは解放されました', + stopped: '停止した作業場所のデータは、削除するまで残ります', + retired: (date: string) => `もう使えません。${date} に自動で削除されます。`, + retiredUndated: 'もう使えません。自動で削除されます。', + unknown: 'この状態はまだ表示できません', + }, + summary: { + kept: (n: number) => `データを残している作業場所 ${n} 件`, + idle: (n: number, idleAfter: string) => `${idleAfter}以上使っていないもの ${n} 件`, + separator: ' · ', + }, + duration: { + days: (n: number) => `${n} 日`, + hours: (n: number) => `${n} 時間`, + }, + cleanup: '片づける', + cleanupSelected: (n: number) => `使っていない ${n} 件を選びました。内容を確かめて削除してください。`, + select: (name: string) => `「${name}」を選ぶ`, + selection: (n: number) => `${n} 件を選択中`, + clearSelection: '選択を外す', + deleteSelected: (n: number) => `選んだ ${n} 件を削除`, + action: { + open: '開く', + resume: '再開する', + restart: '再開する', + extend: '延長する', + stop: '停止する', + delete: '削除する', + }, + actionLabel: (name: string, action: string) => `「${name}」を${action}`, + extended: (name: string) => `「${name}」の休止までの時間を延ばしました。`, + stopped: (name: string) => `「${name}」を停止しました。`, + restarted: (name: string) => `「${name}」を再開しています。`, + stop: { + title: (name: string) => `「${name}」を停止しますか?`, + body: '停止した作業場所のデータは、削除するまで残ります。', + confirm: '停止する', + }, + remove: { + title: (n: number) => (n === 1 ? '作業場所を削除しますか?' : `作業場所 ${n} 件を削除しますか?`), + warning: '置き場に送っていない変更は消えます。', + body: '作業場所とそのデータを削除します。置き場に送った変更と提案は残ります。', + rows: '削除する作業場所', + unpublished: '置き場に未送信', + retired: '使用終了・もう使えません', + unpublishedNote: (n: number) => `${n} 件は置き場に送っていません。変更はこの作業場所にしかありません。`, + confirm: (n: number) => (n === 1 ? '削除する' : `${n} 件を削除する`), + deleting: '削除しています', + deleted: '削除を受け付けました', + retryFailed: '失敗したものをもう一度', + }, + empty: { + title: '作業場所はまだありません', + body: 'AI と作り始めると、ここに出ます。', + }, + leaseHint: { + remaining: (minutes: number) => `あと ${minutes} 分で休止`, + expired: 'まもなく休止', + /** The button's name starts with what it shows, then says what pressing it does. */ + extendLabel: (shown: string) => `${shown}(押すと休止までの時間を延ばします)`, + extended: '休止までの時間を延ばしました', + failed: '延ばせませんでした', + }, +} + +export const workspacesText = localized({ ja: workspacesJa, en: workspacesEn }) diff --git a/web/src/features/workspaces/delete-dialog.tsx b/web/src/features/workspaces/delete-dialog.tsx new file mode 100644 index 0000000..4b7ee3d --- /dev/null +++ b/web/src/features/workspaces/delete-dialog.tsx @@ -0,0 +1,127 @@ +// Deletes one or more of the caller's workspaces with the Dashboard's warning +// (Workspaces tab, delete-workspaces-dialog): unpushed changes are lost, and +// rows whose work never left the workspace are named. One DELETE per row, in +// order, each with its own Idempotency-Key that a retry of that row reuses. +import { useQueryClient } from '@tanstack/react-query' +import { AlertTriangle, CheckCircle2, Loader2 } from 'lucide-react' +import { useRef, useState } from 'react' +import { mintIdempotencyKey } from '../../api/build-sessions' +import { useMe } from '../../api/queries/console' +import { workspaceKeys } from '../../api/queries/workspaces' +import { deleteWorkspace } from '../../api/workspace' +import { isOneOf } from '../../model/contracts/build' +import type { MyWorkspace } from '../../model/contracts/workspace' +import { ActionError, Button, Dialog } from '../../ui' +import { copy } from '../../copy' +import { workspacesText as text } from './copy' +import { hasPublishedBranch } from './model' + +type RowResult = { state: 'deleting' } | { state: 'deleted' } | { state: 'failed'; error: unknown } + +/** Open while `workspaces` is non-empty; `onDeleted` gets the ids Platform accepted, once per run. */ +export function DeleteWorkspacesDialog({ workspaces, onOpenChange, onDeleted }: { + workspaces: readonly MyWorkspace[] + onOpenChange: (open: boolean) => void + onDeleted: (ids: string[]) => void +}) { + const { data: me } = useMe() + const client = useQueryClient() + const keys = useRef(new Map()) + const [results, setResults] = useState>({}) + const [running, setRunning] = useState(false) + const count = workspaces.length + const finished = !running && workspaces.some((workspace) => results[workspace.id]) + const failed = workspaces.filter((workspace) => results[workspace.id]?.state === 'failed').length + const unpublished = workspaces.filter((workspace) => !hasPublishedBranch(workspace)).length + + async function run() { + setRunning(true) + const deleted: string[] = [] + for (const workspace of workspaces) { + if (results[workspace.id]?.state === 'deleted') continue + setResults((current) => ({ ...current, [workspace.id]: { state: 'deleting' } })) + const key = keys.current.get(workspace.id) ?? mintIdempotencyKey() + keys.current.set(workspace.id, key) + try { + await deleteWorkspace(me.projectId, workspace.id, key) + deleted.push(workspace.id) + setResults((current) => ({ ...current, [workspace.id]: { state: 'deleted' } })) + } catch (error) { + setResults((current) => ({ ...current, [workspace.id]: { state: 'failed', error } })) + } + } + // The run is over once Platform answered every row; the drawer catches up when the re-read lands. + void client.invalidateQueries({ queryKey: workspaceKeys.mine(me.projectId) }) + setRunning(false) + onDeleted(deleted) + } + + function change(next: boolean) { + if (running) return + if (!next) { + setResults({}) + keys.current.clear() + } + onOpenChange(next) + } + + return ( + 0} + onOpenChange={change} + title={text.remove.title(count)} + footer={finished ? ( + <> + {failed > 0 ? : null} + + + ) : ( + <> + + + + )} + > +
+

+ + {text.remove.warning} +

+

{text.remove.body}

+
    + {workspaces.map((workspace) => ( +
  • + {workspace.displayName} + {isOneOf(workspace.state, 'Retired') ? {text.remove.retired} : null} + {hasPublishedBranch(workspace) ? null : {text.remove.unpublished}} + +
  • + ))} +
+ {unpublished > 0 && !finished ?

{text.remove.unpublishedNote(unpublished)}

: null} +
+
+ ) +} + +function Tag({ tone, children }: { tone: 'neutral' | 'warning'; children: string }) { + return ( + + {children} + + ) +} + +function RowOutcome({ result }: { result: RowResult | undefined }) { + if (!result) return null + if (result.state === 'deleting') { + return {text.remove.deleting} + } + if (result.state === 'deleted') { + return {text.remove.deleted} + } + return
+} diff --git a/web/src/features/workspaces/drawer.tsx b/web/src/features/workspaces/drawer.tsx new file mode 100644 index 0000000..1efbac9 --- /dev/null +++ b/web/src/features/workspaces/drawer.tsx @@ -0,0 +1,283 @@ +// 「自分の作業場所」 (devworkspace builder-console.md §1–§3): the header entry with +// the running count, and the drawer with the caller's own workspaces in three +// groups. Every row action comes from Platform's `allowedActions`; Admin work, +// Project policy and other people's workspaces belong to the Dashboard. +import { useQuery } from '@tanstack/react-query' +import { useRouterState } from '@tanstack/react-router' +import { Laptop, X } from 'lucide-react' +import { Dialog as RDialog } from 'radix-ui' +import { useEffect, useState, type ReactNode } from 'react' +import { draftsOptions } from '../../api/queries/build' +import { useMe } from '../../api/queries/console' +import { copy, type ConsoleStatus } from '../../copy' +import { isOneOf, knownValue } from '../../model/contracts/build' +import type { MyWorkspace, MyWorkspaceList, WorkspaceState } from '../../model/contracts/workspace' +import { locale } from '../../shell/language' +import { ActionError, Button, Checkbox, cn, ConfirmDialog, EmptyState, LinkButton, LoadFailed, Loading, StatusPill } from '../../ui' +import { useClock } from '../improve/use-clock' +import { workspacesText as text } from './copy' +import { DeleteWorkspacesDialog } from './delete-dialog' +import { + cleanupSelection, + durationLabel, + groupWorkspaces, + isDeletable, + leaseHint, + openHref, + parseGoDuration, + runningCount, + WORKSPACE_GROUPS, + type WorkspaceGroup, +} from './model' +import { useExtendLease, useMyWorkspaces, useRestartWorkspace, useStopWorkspace } from './use-my-workspaces' + +const PILL: Record = { + Ready: 'live', Starting: 'deploying', Committing: 'deploying', Deleting: 'deploying', Degraded: 'failed', Failed: 'failed', + Sleeping: 'unfinished', Stopped: 'unfinished', Retired: 'unknown', +} + +/** The header entry: hidden for someone who cannot create apps and has no workspace. */ +export function MyWorkspacesEntry() { + const { data: me } = useMe() + const query = useMyWorkspaces() + const [open, setOpen] = useState(false) + const location = useRouterState({ select: (state) => state.location.href }) + // Following 開く (or any navigation) leaves the drawer. + useEffect(() => setOpen(false), [location]) + const workspaces = query.data?.data ?? [] + if (!me.canCreateApps && workspaces.length === 0) return null + const running = runningCount(workspaces) + return ( + + + + {running > 0 ? ( + + {running} + + ) : null} + + + + +
+
+ {text.title} + {text.description} +
+ + + +
+ {query.data ? : query.isError ? ( +
void query.refetch()} />
+ ) : } +
+
+
+ ) +} + +function idleAfterText(idleAfter: string): string { + const ms = parseGoDuration(idleAfter) + if (ms === undefined) return idleAfter + const label = durationLabel(ms) + return text.duration[label.unit](label.value) +} + +function Drawer({ list }: { list: MyWorkspaceList }) { + const { data: me } = useMe() + // Only to find the AI session page a workspace belongs to; the shell already reads this list. + const drafts = useQuery({ ...draftsOptions(me.projectId), refetchInterval: false }).data?.data ?? [] + const now = useClock(true) + const [selected, setSelected] = useState>(new Set()) + const [deleting, setDeleting] = useState([]) + const [stopping, setStopping] = useState() + const [notice, setNotice] = useState() + useEffect(() => { + if (!notice) return + const timer = setTimeout(() => setNotice(undefined), 6_000) + return () => clearTimeout(timer) + }, [notice]) + const extend = useExtendLease((workspace) => setNotice(text.extended(workspace.displayName))) + const stop = useStopWorkspace((workspace) => { + setStopping(undefined) + setNotice(text.stopped(workspace.displayName)) + }) + const restart = useRestartWorkspace((workspace) => setNotice(text.restarted(workspace.displayName))) + + const groups = groupWorkspaces(list.data) + // A row that left the list (deleted, or no longer deletable) leaves the selection. + const chosen = list.data.filter((workspace) => selected.has(workspace.id) && isDeletable(workspace)) + const toggle = (id: string, on: boolean) => setSelected((current) => { + const next = new Set(current) + if (on) next.add(id) + else next.delete(id) + return next + }) + const cleanUp = () => { + const ids = cleanupSelection(list.data, now, list.idleAfter) + setSelected(new Set(ids)) + setNotice(text.cleanupSelected(ids.length)) + } + + return ( + <> +
+

+ {text.summary.kept(list.summary.retainedSourceVolumes)} + {text.summary.separator} + {text.summary.idle(list.summary.idleRetained, idleAfterText(list.idleAfter))} +

+ {list.summary.idleRetained > 0 ? : null} +
+

{notice}

+
+ {list.data.length === 0 ? ( +
} title={text.empty.title} body={text.empty.body} />
+ ) : WORKSPACE_GROUPS.map((group) => groups[group].length ? ( +
+

+ {text.groups[group]} + {text.groupCount(groups[group].length)} +

+
    + {groups[group].map((workspace) => ( + toggle(workspace.id, on)} + extend={{ pending: extend.isPending && extend.variables?.id === workspace.id, error: extend.variables?.id === workspace.id ? extend.error : null, run: () => extend.mutate(workspace) }} + restart={{ pending: restart.isPending && restart.variables?.id === workspace.id, error: restart.variables?.id === workspace.id ? restart.error : null, run: () => restart.mutate(workspace) }} + onStop={() => { stop.reset(); setStopping(workspace) }} + onDelete={() => setDeleting([workspace])} + /> + ))} +
+
+ ) : null)} +
+ {chosen.length > 0 ? ( +
+

{text.selection(chosen.length)}

+ + +
+ ) : null} + { if (!open) setStopping(undefined) }} + title={stopping ? text.stop.title(stopping.displayName) : ''} + body={text.stop.body} + confirmLabel={text.stop.confirm} + onConfirm={() => stopping && stop.mutate(stopping)} + pending={stop.isPending} + error={stop.error} + /> + { if (!open) setDeleting([]) }} + onDeleted={(ids) => setSelected((current) => new Set([...current].filter((id) => !ids.includes(id))))} + /> + + ) +} + +const dateTime = (iso: string) => new Date(iso).toLocaleString(locale(), { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' }) + +/** The row's one line under its name: the lease while it runs, the source data otherwise, or why it is unusable. */ +function rowLine(workspace: MyWorkspace, group: WorkspaceGroup, now: number): { text: string; warning: boolean } | undefined { + const state = knownValue(workspace.state) + if (!state) return { text: text.line.unknown, warning: false } + if (group === 'running') { + const hint = leaseHint(workspace, now) + return hint ? { text: hint.expired ? text.line.leaseExpired : text.line.lease(hint.minutes), warning: hint.warning } : undefined + } + if (state === 'Retired') return { text: workspace.retired?.deleteAt ? text.line.retired(dateTime(workspace.retired.deleteAt)) : text.line.retiredUndated, warning: false } + const volume = workspace.sourceVolume + if (isOneOf(volume?.state, 'Released')) return { text: text.line.dataReleased, warning: false } + if (isOneOf(volume?.state, 'Releasing')) return { text: text.line.dataReleasing, warning: false } + if (volume?.releaseAt) return { text: text.line.dataUntil(dateTime(volume.releaseAt)), warning: false } + if (state === 'Stopped') return { text: text.line.stopped, warning: false } + return volume ? { text: text.line.dataKept, warning: false } : undefined +} + +function targetText(workspace: MyWorkspace): string { + const scope = knownValue(workspace.scope) + if (scope === 'applicationDraft') return text.target.draft + if (scope === 'application' && workspace.applicationId) { + return workspace.applicationBranchId ? text.target.branch(workspace.applicationId, workspace.applicationBranchId) : text.target.application(workspace.applicationId) + } + return text.target.unknown +} + +function Row({ workspace, group, now, href, selected, onSelect, extend, restart, onStop, onDelete }: { + workspace: MyWorkspace + group: WorkspaceGroup + now: number + href: string | undefined + selected: boolean + onSelect: (on: boolean) => void + extend: { pending: boolean; error: unknown; run: () => void } + /** Stopped or Failed → Running when Platform allows `start` or `restart`; there is no start route, both call restart. */ + restart: { pending: boolean; error: unknown; run: () => void } + onStop: () => void + onDelete: () => void +}) { + const name = workspace.displayName + const state = knownValue(workspace.state) + const allowed = workspace.allowedActions + const line = rowLine(workspace, group, now) + const deletable = isDeletable(workspace) + const label = (action: string) => text.actionLabel(name, action) + const actions: ReactNode[] = [] + if (allowed?.open && href) { + const action = group === 'sleeping' ? text.action.resume : text.action.open + actions.push({action}) + } + if (group === 'running' && allowed?.extendLease) { + actions.push() + } + if (group === 'running' && allowed?.stop) { + actions.push() + } + if (group === 'other' && (allowed?.start || allowed?.restart)) { + actions.push() + } + if (deletable) { + actions.push() + } + return ( +
  • +
    + {deletable ? : null} +
    +
    +
    +

    {name}

    + +
    +

    + {targetText(workspace)} + {line ? ( + <> + · + {line.text} + + ) : null} +

    + {actions.length ?
    {actions}
    : null} + {extend.error || restart.error ?
    : null} +
    +
  • + ) +} diff --git a/web/src/features/workspaces/index.ts b/web/src/features/workspaces/index.ts new file mode 100644 index 0000000..0287670 --- /dev/null +++ b/web/src/features/workspaces/index.ts @@ -0,0 +1,3 @@ +export { MyWorkspacesEntry } from './drawer' +export { WorkspaceLeaseHint } from './lease-hint' +export { sessionWorkspaceId } from './model' diff --git a/web/src/features/workspaces/lease-hint.tsx b/web/src/features/workspaces/lease-hint.tsx new file mode 100644 index 0000000..d3f2854 --- /dev/null +++ b/web/src/features/workspaces/lease-hint.tsx @@ -0,0 +1,53 @@ +// The lease countdown inside an AI session (devworkspace builder-console.md §4): +// how long until the workspace on screen sleeps, in the warning color from five +// minutes before, and one click to extend it when Platform allows the caller to. +import { Clock, Loader2 } from 'lucide-react' +import { useState } from 'react' +import { cn } from '../../ui' +import { useClock } from '../improve/use-clock' +import { workspacesText as text } from './copy' +import { leaseHint } from './model' +import { useExtendLease, useMyWorkspaces } from './use-my-workspaces' + +const PILL = 'inline-flex h-7 items-center gap-1.5 rounded-full px-2.5 text-xs font-medium whitespace-nowrap ring-1 ring-inset tabular-nums [&_svg]:size-3.5 [&_svg]:shrink-0' + +/** Nothing unless `workspaceId` is one of the caller's own running workspaces with a lease expiry. */ +export function WorkspaceLeaseHint({ workspaceId }: { workspaceId: string | undefined }) { + const workspaces = useMyWorkspaces().data?.data + const workspace = workspaceId ? workspaces?.find((item) => item.id === workspaceId) : undefined + const [extended, setExtended] = useState(false) + const extend = useExtendLease(() => setExtended(true)) + const now = useClock(workspace !== undefined) + const hint = workspace ? leaseHint(workspace, now) : undefined + if (!workspace || !hint) return null + const label = hint.expired ? text.leaseHint.expired : text.leaseHint.remaining(hint.minutes) + const tone = hint.warning ? 'bg-busy-soft text-busy-ink ring-amber-200' : 'bg-white text-stone-600 ring-stone-200' + const status = {extended && !extend.isPending ? text.leaseHint.extended : ''} + const name = text.leaseHint.extendLabel(label) + if (!hint.canExtend) { + return {label} + } + return ( + <> + + {extend.isError ? {text.leaseHint.failed} : null} + {status} + + ) +} diff --git a/web/src/features/workspaces/model.test.ts b/web/src/features/workspaces/model.test.ts new file mode 100644 index 0000000..e785ca3 --- /dev/null +++ b/web/src/features/workspaces/model.test.ts @@ -0,0 +1,136 @@ +import { describe, expect, test } from 'bun:test' +import type { BuildDraft } from '../../model/contracts/build' +import type { MyWorkspace, WorkspaceActions, WorkspaceState } from '../../model/contracts/workspace' +import { cleanupSelection, durationLabel, groupWorkspaces, hasPublishedBranch, isIdle, leaseHint, openHref, parseGoDuration, runningCount, sessionWorkspaceId } from './model' + +const NOW = Date.parse('2026-11-21T12:00:00Z') +const minutes = (n: number) => new Date(NOW + n * 60_000).toISOString() +const days = (n: number) => minutes(n * 24 * 60) +const allowed = (overrides: Partial = {}): WorkspaceActions => ({ + open: true, stop: true, start: false, restart: true, extendLease: true, keepLonger: false, delete: true, commit: true, blockedBy: {}, ...overrides, +}) + +function row(id: string, state: WorkspaceState | 'future', fields: Partial = {}): MyWorkspace { + return { + id, projectId: 'commerce', displayName: id, scope: { kind: 'known', value: 'application' }, + state: state === 'future' ? { kind: 'unknown' } : { kind: 'known', value: state }, + sourceVolume: { state: { kind: 'known', value: 'Retained' } }, + allowedActions: allowed(), + ...fields, + } +} + +describe('grouping (builder-console.md §2)', () => { + const rows = [ + row('ready', 'Ready'), row('sleeping', 'Sleeping'), row('degraded', 'Degraded'), row('committing', 'Committing'), row('starting', 'Starting'), + row('stopped', 'Stopped'), row('retired', 'Retired'), row('failed', 'Failed'), row('deleting', 'Deleting'), row('future', 'future'), row('sleeping-2', 'Sleeping'), + ] + + test('Running is Ready, Degraded, Committing and Starting; Sleeping alone; everything else in the third group, in server order', () => { + const groups = groupWorkspaces(rows) + expect(groups.running.map((workspace) => workspace.id)).toEqual(['ready', 'degraded', 'committing', 'starting']) + expect(groups.sleeping.map((workspace) => workspace.id)).toEqual(['sleeping', 'sleeping-2']) + expect(groups.other.map((workspace) => workspace.id)).toEqual(['stopped', 'retired', 'failed', 'deleting', 'future']) + }) + + test('the badge counts running workspaces only; an unknown state is never running', () => { + expect(runningCount(rows)).toBe(4) + expect(runningCount([row('future', 'future')])).toBe(0) + }) +}) + +describe('idle rows and 片づける', () => { + const idleAfter = '168h0m0s' + const week = parseGoDuration(idleAfter)! + + test('Go durations parse; anything else does not', () => { + expect(week).toBe(7 * 24 * 3_600_000) + expect(parseGoDuration('1h30m')).toBe(90 * 60_000) + expect(parseGoDuration('0')).toBe(0) + expect(parseGoDuration('7 days')).toBeUndefined() + expect(parseGoDuration('')).toBeUndefined() + expect(durationLabel(week)).toEqual({ unit: 'days', value: 7 }) + expect(durationLabel(36 * 3_600_000)).toEqual({ unit: 'hours', value: 36 }) + }) + + test('idle is the server rule: retained, not running, last activity strictly older than idleAfter (none counts as idle)', () => { + expect(isIdle(row('a', 'Stopped', { lastActivityAt: days(-8) }), NOW, week)).toBe(true) + expect(isIdle(row('a', 'Stopped', { lastActivityAt: days(-7) }), NOW, week)).toBe(false) + expect(isIdle(row('a', 'Stopped'), NOW, week)).toBe(true) + expect(isIdle(row('a', 'Ready', { lastActivityAt: days(-30) }), NOW, week)).toBe(false) + expect(isIdle(row('a', 'Sleeping', { lastActivityAt: days(-30), sourceVolume: { state: { kind: 'known', value: 'Released' } } }), NOW, week)).toBe(false) + expect(isIdle(row('a', 'Sleeping', { lastActivityAt: days(-30), sourceVolume: { state: { kind: 'unknown' } } }), NOW, week)).toBe(false) + }) + + test('selects idle Sleeping and Stopped rows the caller may delete, never Retired, Failed or running ones', () => { + const rows = [ + row('idle-sleeping', 'Sleeping', { lastActivityAt: days(-9) }), + row('recent-sleeping', 'Sleeping', { lastActivityAt: days(-2) }), + row('idle-stopped', 'Stopped', { lastActivityAt: days(-12) }), + row('idle-retired', 'Retired', { lastActivityAt: days(-12) }), + row('idle-failed', 'Failed', { lastActivityAt: days(-12) }), + row('not-mine', 'Stopped', { lastActivityAt: days(-12), allowedActions: allowed({ delete: false }) }), + row('old-actions', 'Stopped', { lastActivityAt: days(-12), allowedActions: undefined }), + ] + expect(cleanupSelection(rows, NOW, idleAfter)).toEqual(['idle-sleeping', 'idle-stopped']) + expect(cleanupSelection(rows, NOW, 'forever')).toEqual([]) + }) +}) + +describe('lease hint (builder-console.md §4)', () => { + const lease = (expiresAt: string) => ({ ttlSeconds: 3600, expiresAt }) + + test('whole minutes left, rounded up', () => { + expect(leaseHint(row('a', 'Ready', { lease: lease(minutes(12)) }), NOW)).toEqual({ minutes: 12, expired: false, warning: false, canExtend: true }) + expect(leaseHint(row('a', 'Ready', { lease: lease(new Date(NOW + 11 * 60_000 + 1).toISOString()) }), NOW)?.minutes).toBe(12) + }) + + test('warning from five minutes before expiry, and once it has passed', () => { + expect(leaseHint(row('a', 'Ready', { lease: lease(new Date(NOW + 5 * 60_000 + 1).toISOString()) }), NOW)?.warning).toBe(false) + expect(leaseHint(row('a', 'Ready', { lease: lease(minutes(5)) }), NOW)).toEqual({ minutes: 5, expired: false, warning: true, canExtend: true }) + expect(leaseHint(row('a', 'Degraded', { lease: lease(minutes(-1)) }), NOW)).toEqual({ minutes: 0, expired: true, warning: true, canExtend: true }) + }) + + test('extending follows allowedActions only', () => { + expect(leaseHint(row('a', 'Ready', { lease: lease(minutes(12)), allowedActions: allowed({ extendLease: false }) }), NOW)?.canExtend).toBe(false) + expect(leaseHint(row('a', 'Ready', { lease: lease(minutes(12)), allowedActions: undefined }), NOW)?.canExtend).toBe(false) + }) + + test('no hint without a running state or an expiry', () => { + expect(leaseHint(row('a', 'Sleeping', { lease: lease(minutes(12)) }), NOW)).toBeUndefined() + expect(leaseHint(row('a', 'future', { lease: lease(minutes(12)) }), NOW)).toBeUndefined() + expect(leaseHint(row('a', 'Ready', { lease: { ttlSeconds: 3600 } }), NOW)).toBeUndefined() + expect(leaseHint(row('a', 'Ready', { lease: lease('not a time') }), NOW)).toBeUndefined() + }) +}) + +describe('where a workspace opens', () => { + type Draft = Pick + const draft = (id: string, fields: Partial = {}): Draft => ({ id, implementationRuns: [], ...fields }) + const run = (devWorkspaceId: string) => ({ devWorkspaceId }) as BuildDraft['implementationRuns'][number] + + test('the AI session using it: improve for an improvement, build otherwise', () => { + const drafts = [draft('improve-1', { kind: 'improvement', activeWorkspaceId: 'ws-app' }), draft('build-1', { implementationRuns: [run('ws-run')] })] + expect(openHref(row('ws-app', 'Ready'), drafts)).toBe('/-/improve/improve-1') + expect(openHref(row('ws-run', 'Sleeping'), drafts)).toBe('/-/build/build-1') + }) + + test('a draft workspace without a listed session opens its draft; anything else has no page', () => { + expect(openHref(row('ws-1', 'Ready', { scope: { kind: 'known', value: 'applicationDraft' }, draftId: 'draft-9' }), [])).toBe('/-/build/draft-9') + expect(openHref(row('ws-1', 'Ready', { applicationId: 'mitsumori' }), [])).toBeUndefined() + expect(openHref(row('ws-1', 'Ready', { scope: { kind: 'unknown' }, draftId: 'draft-9' }), [])).toBeUndefined() + }) + + test("a session page's workspace: latest run first, then active, implementation, conversation", () => { + expect(sessionWorkspaceId({ implementationRuns: [run('ws-old'), run('ws-new')], activeWorkspaceId: 'ws-active' })).toBe('ws-new') + expect(sessionWorkspaceId({ implementationRuns: [run('')], activeWorkspaceId: 'ws-active', devWorkspaceId: 'ws-chat' })).toBe('ws-active') + expect(sessionWorkspaceId({ implementationRuns: [], devWorkspaceId: 'ws-chat' })).toBe('ws-chat') + expect(sessionWorkspaceId({ implementationRuns: [] })).toBeUndefined() + }) +}) + +test('a pushed branch or a pull request means the work survives deletion', () => { + expect(hasPublishedBranch({})).toBe(false) + expect(hasPublishedBranch({ branchUrl: 'https://github.com/acme/a/tree/x' })).toBe(true) + expect(hasPublishedBranch({ pullRequestUrl: 'https://github.com/acme/a/pull/1' })).toBe(true) +}) diff --git a/web/src/features/workspaces/model.ts b/web/src/features/workspaces/model.ts new file mode 100644 index 0000000..59af655 --- /dev/null +++ b/web/src/features/workspaces/model.ts @@ -0,0 +1,133 @@ +// 「自分の作業場所」 (builder-console.md §2–§4): how the caller's workspaces are +// grouped, which ones 「片づける」 selects, the lease countdown, and where 開く +// goes. Actions come only from Platform's `allowedActions`; nothing here infers +// readiness from URLs or messages, and an unknown state is never "running". +import { isOneOf, knownValue, type BuildDraft } from '../../model/contracts/build' +import type { MyWorkspace, WorkspaceState } from '../../model/contracts/workspace' +import { isImprovementDraft } from '../../model/improve' +import { paths } from '../../routes/paths' + +export type WorkspaceGroup = 'running' | 'sleeping' | 'other' + +export const WORKSPACE_GROUPS: readonly WorkspaceGroup[] = ['running', 'sleeping', 'other'] + +/** Compute is up or coming up (platform-api counts these as active). */ +const RUNNING_STATES: readonly WorkspaceState[] = ['Ready', 'Degraded', 'Committing', 'Starting'] + +/** Running, Sleeping, or everything else (Stopped, Retired, Failed, Deleting and states this console does not know). */ +export function workspaceGroup(workspace: Pick): WorkspaceGroup { + if (isOneOf(workspace.state, ...RUNNING_STATES)) return 'running' + if (isOneOf(workspace.state, 'Sleeping')) return 'sleeping' + return 'other' +} + +/** The three groups, each in the server's order (newest activity first). */ +export function groupWorkspaces>(workspaces: readonly W[]): Record { + const groups: Record = { running: [], sleeping: [], other: [] } + for (const workspace of workspaces) groups[workspaceGroup(workspace)].push(workspace) + return groups +} + +/** The header badge: workspaces whose compute is running. */ +export function runningCount(workspaces: readonly Pick[]): number { + return workspaces.filter((workspace) => workspaceGroup(workspace) === 'running').length +} + +const GO_UNIT_MS: Record = { ns: 1e-6, us: 1e-3, µs: 1e-3, ms: 1, s: 1_000, m: 60_000, h: 3_600_000 } + +/** Milliseconds of a Go `time.Duration` string such as `168h0m0s`; undefined when it does not parse. */ +export function parseGoDuration(value: string | undefined): number | undefined { + const text = value?.trim() + if (!text) return undefined + if (text === '0') return 0 + let total = 0 + let consumed = 0 + for (const match of text.matchAll(/(\d+(?:\.\d+)?)(ns|us|µs|ms|s|m|h)/gy)) { + total += Number(match[1]) * GO_UNIT_MS[match[2]!]! + consumed += match[0].length + } + return consumed === text.length ? total : undefined +} + +/** A duration as whole days when it is a whole number of days, else whole hours (`idleAfter` labels). */ +export type DurationLabel = { unit: 'days' | 'hours'; value: number } + +export function durationLabel(ms: number): DurationLabel { + const day = 24 * 3_600_000 + return ms >= day && ms % day === 0 ? { unit: 'days', value: ms / day } : { unit: 'hours', value: Math.max(1, Math.round(ms / 3_600_000)) } +} + +/** + * The server's `idleRetained` rule applied to one row: the source data is + * retained, compute is not running, and the last activity is strictly older + * than `idleAfterMs` (a row without a time counts as idle, as the server reads + * a missing time as the zero time). + */ +export function isIdle(workspace: Pick, now: number, idleAfterMs: number): boolean { + if (!isOneOf(workspace.sourceVolume?.state, 'Retained') || workspaceGroup(workspace) === 'running') return false + const last = workspace.lastActivityAt ? Date.parse(workspace.lastActivityAt) : Number.NaN + return Number.isNaN(last) || last < now - idleAfterMs +} + +/** Rows that can be chosen for deletion: not running, and Platform allows the delete. */ +export function isDeletable(workspace: Pick): boolean { + return workspaceGroup(workspace) !== 'running' && workspace.allowedActions?.delete === true +} + +/** 「片づける」: the idle Sleeping and Stopped rows the caller may delete. Nothing when `idleAfter` does not parse. */ +export function cleanupSelection(workspaces: readonly MyWorkspace[], now: number, idleAfter: string): string[] { + const idleAfterMs = parseGoDuration(idleAfter) + if (idleAfterMs === undefined) return [] + return workspaces + .filter((workspace) => isOneOf(workspace.state, 'Sleeping', 'Stopped') && isDeletable(workspace) && isIdle(workspace, now, idleAfterMs)) + .map((workspace) => workspace.id) +} + +/** Warning color from five minutes before the lease runs out (§4). */ +export const LEASE_WARNING_MS = 5 * 60_000 + +/** + * The lease countdown of a running workspace: whole minutes left (rounded up, + * 0 once expired), whether it is in the warning window, and whether the caller + * may extend it. None for a workspace that is not running or has no expiry. + */ +export type LeaseHint = { minutes: number; expired: boolean; warning: boolean; canExtend: boolean } + +export function leaseHint(workspace: Pick, now: number): LeaseHint | undefined { + if (workspaceGroup(workspace) !== 'running' || !workspace.lease?.expiresAt) return undefined + const expiresAt = Date.parse(workspace.lease.expiresAt) + if (Number.isNaN(expiresAt)) return undefined + const remaining = expiresAt - now + return { + minutes: Math.max(0, Math.ceil(remaining / 60_000)), + expired: remaining <= 0, + warning: remaining <= LEASE_WARNING_MS, + canExtend: workspace.allowedActions?.extendLease === true, + } +} + +/** Whether the work is reachable outside the workspace (a pushed branch or a pull request); deleting loses the rest. */ +export function hasPublishedBranch(workspace: Pick): boolean { + return Boolean(workspace.branchUrl || workspace.pullRequestUrl) +} + +type DraftWorkspaces = Pick + +/** The workspace an AI session page shows: its latest run's, else the session's active, implementation or conversation workspace. */ +export function sessionWorkspaceId(draft: Omit): string | undefined { + return draft.implementationRuns.at(-1)?.devWorkspaceId || draft.activeWorkspaceId || draft.implementationWorkspaceId || draft.devWorkspaceId || undefined +} + +/** + * Where 開く / 再開する go: the AI session (build or improve page) that uses the + * workspace, else the build page of the draft it was made for. Undefined when + * the console has no page for it; then no open action is shown. + */ +export function openHref(workspace: Pick, drafts: readonly DraftWorkspaces[]): string | undefined { + const session = drafts.find((draft) => + draft.activeWorkspaceId === workspace.id || draft.implementationWorkspaceId === workspace.id || draft.devWorkspaceId === workspace.id || + draft.implementationRuns.some((run) => run.devWorkspaceId === workspace.id)) + ?? drafts.find((draft) => draft.id === workspace.draftId) + if (session) return isImprovementDraft(session) ? paths.improve(session.id) : paths.build(session.id) + return knownValue(workspace.scope) === 'applicationDraft' && workspace.draftId ? paths.build(workspace.draftId) : undefined +} diff --git a/web/src/features/workspaces/use-my-workspaces.ts b/web/src/features/workspaces/use-my-workspaces.ts new file mode 100644 index 0000000..f985c73 --- /dev/null +++ b/web/src/features/workspaces/use-my-workspaces.ts @@ -0,0 +1,52 @@ +// The caller's workspaces and the writes on one of them. Every write replaces +// that row in the shared list with Platform's answer and then re-reads the list, +// so the badge, the drawer and the lease hint move together. +import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query' +import { useMe } from '../../api/queries/console' +import { myWorkspacesOptions, workspaceKeys } from '../../api/queries/workspaces' +import { extendWorkspaceLease, restartWorkspace, stopWorkspace } from '../../api/workspace' +import type { MyWorkspace, MyWorkspaceList } from '../../model/contracts/workspace' + +/** Read only for a Project member while Platform answers the console. */ +export function useMyWorkspaces() { + const { data: me } = useMe() + return useQuery({ ...myWorkspacesOptions(me.projectId), enabled: !me.notMember && !me.platformUnavailable }) +} + +function replaceRow(client: QueryClient, projectId: string, written: MyWorkspace) { + client.setQueryData(workspaceKeys.mine(projectId), (list) => list && { + ...list, + data: list.data.map((workspace) => (workspace.id === written.id ? written : workspace)), + }) + void client.invalidateQueries({ queryKey: workspaceKeys.mine(projectId) }) +} + +/** A write on one row; `variables` names the row, so a failure is shown on that row only. */ +function useRowWrite(write: (projectId: string, workspaceId: string) => Promise, onDone?: (workspace: MyWorkspace) => void) { + const { data: me } = useMe() + const client = useQueryClient() + return useMutation({ + mutationFn: (workspace: Pick) => write(me.projectId, workspace.id), + onSuccess: (written) => { + replaceRow(client, me.projectId, written) + onDone?.(written) + }, + }) +} + +export const useExtendLease = (onDone?: (workspace: MyWorkspace) => void) => useRowWrite(extendWorkspaceLease, onDone) + +export const useStopWorkspace = (onDone?: (workspace: MyWorkspace) => void) => useRowWrite(stopWorkspace, onDone) + +/** Brings a Stopped or Failed workspace back (`start` or `restart`): there is no start route, so both call restart. The list is re-read for its new state. */ +export function useRestartWorkspace(onDone?: (workspace: Pick) => void) { + const { data: me } = useMe() + const client = useQueryClient() + return useMutation({ + mutationFn: (workspace: Pick) => restartWorkspace(me.projectId, workspace.id, {}), + onSuccess: (_, workspace) => { + void client.invalidateQueries({ queryKey: workspaceKeys.mine(me.projectId) }) + onDone?.(workspace) + }, + }) +} diff --git a/web/src/model/contracts/workspace.ts b/web/src/model/contracts/workspace.ts new file mode 100644 index 0000000..7e9e928 --- /dev/null +++ b/web/src/model/contracts/workspace.ts @@ -0,0 +1,50 @@ +// 「自分の作業場所」 (My workspaces) domain values that arrive through the +// response boundary (api/contracts/platform/workspace.ts). Feature and model code +// reads these types, never the wire. +// +// A row keeps only what the drawer and the lease hint use, so a field this +// console never shows cannot break the list. Server enums a newer Platform may +// extend (`state`, `scope`, the source volume state) are open values: an +// unknown one is `{ kind: 'unknown' }`, never mapped onto a known one. +import type { + DevWorkspaceListSummary, + DevWorkspaceRead, + DevWorkspaceScope, + DevWorkspaceSourceVolume, + DevWorkspaceState, +} from '@appthrust/api-schema/platform-api' +import type { OpenValue } from '../../api/boundary' + +export type WorkspaceState = DevWorkspaceState +export type WorkspaceScope = DevWorkspaceScope +export type SourceVolumeState = DevWorkspaceSourceVolume['state'] + +/** What the caller may do with the workspace, decided by Platform. Absent on a server that predates it: nothing is offered. */ +export type WorkspaceActions = NonNullable + +/** The activity lease: compute sleeps at `expiresAt` unless it is renewed. */ +export type WorkspaceLease = { lastActivityAt?: string; expiresAt?: string; ttlSeconds: number } + +/** A Retired workspace cannot run again; Platform deletes it at `deleteAt`. */ +export type WorkspaceRetirement = NonNullable + +export type MyWorkspace = Pick & { + scope: OpenValue + /** The server's product state; on a server without `state`, the state its phase stands for. */ + state: OpenValue + retired?: WorkspaceRetirement + lease?: WorkspaceLease + sourceVolume?: { state: OpenValue; releaseAt?: string } + allowedActions?: WorkspaceActions +} + +/** `GET dev-workspaces?owner=me`: the caller's workspaces (newest activity first) and the server's counts over them. */ +export type MyWorkspaceList = { + data: MyWorkspace[] + summary: DevWorkspaceListSummary + /** Go duration (`168h0m0s`): the server's idle threshold behind `summary.idleRetained`. */ + idleAfter: string +} + +/** A delete Platform accepted; the workspace and its source data go away asynchronously. */ +export type WorkspaceDeletion = { id: string } diff --git a/web/src/shell/shell.tsx b/web/src/shell/shell.tsx index 6b9ca09..e7f31d0 100644 --- a/web/src/shell/shell.tsx +++ b/web/src/shell/shell.tsx @@ -13,6 +13,7 @@ import { Dialog as RDialog } from 'radix-ui' import { useEffect, type ReactNode } from 'react' import { useMe } from '../api/queries/console' import { useConsoleView } from '../features/inbox' +import { MyWorkspacesEntry } from '../features/workspaces' import { copy } from '../copy' import { paths } from '../routes/paths' import { @@ -178,7 +179,8 @@ function TopBar() { aria-label={`${copy.topbar.switchContext}(${contextLabel}: ${contextName})`} className="flex min-h-10 min-w-0 items-center gap-1 rounded-md px-1.5 py-1.5 text-sm hover:bg-stone-100 data-[state=open]:bg-stone-100 md:min-h-0 sm:px-2" > - {contextLabel}: + {/* Phones keep the group name; the trigger's accessible name still says 所属 / 表示中. */} + {contextLabel}: {contextName} @@ -209,6 +211,7 @@ function TopBar() {

    ) : null} {onCreate ? null : } +
    @@ -223,7 +226,7 @@ function CreateButton({ groupPath }: { groupPath: string | undefined }) { const view = useConsoleView() if (!me.canCreateApps) return null return ( - + {copy.nav.create} ) diff --git a/web/src/styles.css b/web/src/styles.css index b854c1d..a67a4b7 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -32,6 +32,7 @@ --animate-fade-in: fade-in 150ms ease-out; --animate-slide-in-left: slide-in-left 200ms ease-out; + --animate-slide-in-right: slide-in-right 200ms ease-out; --animate-pop-in: pop-in 150ms ease-out; @keyframes fade-in { @@ -50,6 +51,14 @@ transform: translateX(0); } } + @keyframes slide-in-right { + from { + transform: translateX(100%); + } + to { + transform: translateX(0); + } + } @keyframes pop-in { from { opacity: 0; From cfd3aaeb7800b3ab5c198016da224c220313600b Mon Sep 17 00:00:00 2001 From: reoring Date: Sat, 21 Nov 2026 13:39:12 +0900 Subject: [PATCH 2/2] Pin @appthrust/api-schema 0.1.8 in the lockfile 0.1.8 (npm/v0.1.8, platform b19ece4003) carries the DevWorkspace owner filter, summary, lease, runtime and extend-lease contract. --- web/bun.lock | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/bun.lock b/web/bun.lock index b82c2ad..dce5d9a 100644 --- a/web/bun.lock +++ b/web/bun.lock @@ -5,7 +5,7 @@ "": { "name": "@appthrust/builder-console", "dependencies": { - "@appthrust/api-schema": "^0.1.7", + "@appthrust/api-schema": "^0.1.8", "@appthrust/app-launcher": "^0.1.5", "@appthrust/platform-dashboard-i18n": "^0.1.5", "@orpc/client": "^1.13.13", @@ -39,7 +39,7 @@ }, }, "packages": { - "@appthrust/api-schema": ["@appthrust/api-schema@0.1.7", "https://npm.pkg.github.com/download/@appthrust/api-schema/0.1.7/494cb49cd505d7b5b09c595ea9a81c4a18013adb", { "dependencies": { "@orpc/contract": "^1.13.13", "@orpc/openapi": "^1.13.13", "@orpc/server": "^1.13.13", "@orpc/zod": "^1.13.13", "zod": "^4.3.6" } }, "sha512-zzN8arDaBYTdfprpQkQGDIJpzNb3+xhib6YUa+SmLbETNQz/7OaC5FOLugmuJjfqfhJ3ytygaVYNRZy/ua8+Xg=="], + "@appthrust/api-schema": ["@appthrust/api-schema@0.1.8", "https://npm.pkg.github.com/download/@appthrust/api-schema/0.1.8/2a75b45c885940f7cb835d40ee47e2115aa68d75", { "dependencies": { "@orpc/contract": "^1.13.13", "@orpc/openapi": "^1.13.13", "@orpc/server": "^1.13.13", "@orpc/zod": "^1.13.13", "zod": "^4.3.6" } }, "sha512-zA7ZBOOgAYdMHhB7s6B93a+QTk5n+IQNEV7owiMFIQRYiIEddl9aWVPyXQkUY7+qTo/NCqoyPz5bsdQ6KLfF2A=="], "@appthrust/app-launcher": ["@appthrust/app-launcher@0.1.5", "https://npm.pkg.github.com/download/@appthrust/app-launcher/0.1.5/cd4111ef52949489dad41c9f20fc588fd443bd13", { "dependencies": { "@appthrust/platform-dashboard-i18n": "0.1.3", "@tanstack/react-query": "^5.90.21", "lucide-react": "^0.563.0", "radix-ui": "^1.4.3", "zod": "^4.3.6" }, "peerDependencies": { "react": "^19.2.4" } }, "sha512-guI3Gm0ZDm+JSq2C31CtRo4zGbzAZ4ljbTkoSJWNkZS41GL2iEH7nOU/bD58V/e2W3twNnDEJizWP3ZaKexWyA=="],