diff --git a/README.md b/README.md index b463e91..4c257da 100644 --- a/README.md +++ b/README.md @@ -139,10 +139,12 @@ fixtures after reviewing a writer change: UPDATE_CONSOLE_WIRE_FIXTURES=1 go test ./cmd/server/internal/api -run '^TestConsoleWriterContract$' ``` -The existing served `openapi.json` remains byte-identical to the public -`appserver-go v0.5.0` Console contract. Compatibility tests check its listApps / -getApp fields and fixtures against the internal schema. Replacing that public -document needs separate review. This intentionally deviates from the design's +The served `openapi.json` is the committed public Console contract. It is +maintained separately and may add Console features while preserving every SDK +field from `appserver-go`. A server test checks served bytes against the committed +file; compatibility tests check its listApps / getApp fields and fixtures against +both the SDK and internal schema. +This intentionally deviates from the design's single generated public document and separate `B/api-schema` package: the schema currently has one TypeScript consumer, so it shares the SPA's Zod installation. A package boundary is deferred until a second consumer needs it, avoiding @@ -154,6 +156,11 @@ feature/model imports of the canonical schema directory, including type-only imports, barrels, and assertions. PostgreSQL handler contract tests use the same opt-in DSN and isolated-schema cleanup as the other server integration tests. +The role-based views contract adds `me.view`, app `permissions` and `contribution`, +the maintainer inbox, and comment-seen writes. Regenerate the internal artifact +with the command above after canonical schema changes. Comment-seen writes use +fetch keepalive so opening another page does not cancel the read receipt. + ### NEW-APP conversation contracts (APT-753 / S4) The same canonical schema directory now owns `build-sessions.ts` and diff --git a/cmd/server/console.go b/cmd/server/console.go index bc76e28..f1c41b7 100644 --- a/cmd/server/console.go +++ b/cmd/server/console.go @@ -26,7 +26,7 @@ const storeOpenTimeout = 30 * time.Second // Tests shorten it. var storeRetryInitial = time.Second -// The database-backed API can appear after HTTP startup. Reviewer enrichment +// The database-backed API can appear after HTTP startup. Console authority // follows that same readiness transition instead of bypassing the pending handler. type consoleAPI struct { *pending.Handler @@ -103,6 +103,7 @@ func consoleHandler(upstreamURL, projectID string) (*consoleAPI, func(), error) } connected := api.New(database, auth, upstream, links, publicURL) connected.ConfigureBuildSessions(conversations, installationID) + connected.ConfigureConsoleAuthority(conversationPlatform) console.current.Store(connected) console.Swap(connected) return database, nil diff --git a/cmd/server/internal/api/access_requests.go b/cmd/server/internal/api/access_requests.go index 0b5f80b..6d5cd2f 100644 --- a/cmd/server/internal/api/access_requests.go +++ b/cmd/server/internal/api/access_requests.go @@ -110,38 +110,13 @@ func (a *API) pendingAccessRequests(s *request) (any, int, error) { if s.r.URL.Query().Get("status") != "pending" { return nil, 0, httpx.Invalid("status must be pending") } - // EditApp includes group managers even for private apps they cannot view. - // Union owned apps with topmost managed subtrees instead of widening Visible. - scope := "mine" - if s.actor.IsConsoleAdmin { - scope = "all" - } - apps, err := s.tx.Apps(s.actor, scope, "", "") + apps, err := s.tx.MaintainedApps(s.actor) if err != nil { return nil, 0, err } - ids := make([]string, 0, len(apps)) - seen := make(map[string]bool, len(apps)) - add := func(apps []domain.App) { - for _, app := range apps { - if !seen[app.ID] && s.actor.EditApp(app) { - seen[app.ID] = true - ids = append(ids, app.ID) - } - } - } - add(apps) - if !s.actor.IsConsoleAdmin { - for _, group := range s.groups { - if !s.actor.ManageGroup(group.ID) || (group.ParentID != nil && s.actor.ManageGroup(*group.ParentID)) { - continue - } - apps, err := s.tx.AppsInSubtree(group.Path) - if err != nil { - return nil, 0, err - } - add(apps) - } + ids := make([]string, len(apps)) + for i := range apps { + ids[i] = apps[i].ID } requests, err := s.tx.PendingAccessRequests(ids) return requests, http.StatusOK, err @@ -215,7 +190,7 @@ func (a *API) approveAccessRequest(s *request) (any, int, error) { return struct { Request domain.AppAccessRequest `json:"request"` App domain.App `json:"app"` - }{r, updated}, http.StatusOK, err + }{r, s.appForCaller(updated)}, http.StatusOK, err } func (a *API) declineAccessRequest(s *request) (any, int, error) { diff --git a/cmd/server/internal/api/api.go b/cmd/server/internal/api/api.go index fdf4c0e..aa1a187 100644 --- a/cmd/server/internal/api/api.go +++ b/cmd/server/internal/api/api.go @@ -37,6 +37,7 @@ type API struct { stackURLs map[string]cachedStackURLs builds *buildsession.Service installationID string + authorityStacks consoleStackReader } type request struct { @@ -52,6 +53,8 @@ type request struct { bearer string platformUnavailable bool claims identity.Identity + authorityApps map[authorityRoute][]domain.App + authorityStackCache map[string]buildsession.ConsoleStack } type endpoint func(*request) (any, int, error) @@ -68,6 +71,7 @@ func New(database *store.Store, auth *identity.Authenticator, upstream *platform a.mux.Handle("GET /launcher/entries", launcher.NewEntriesHandler(appEntrySource{api: a}, a.identity.Authenticate)) a.mux.HandleFunc("GET /api/console/openapi.json", a.openAPI) a.route("GET /api/console/me", false, true, a.me) + a.route("GET /api/console/inbox", false, true, a.inbox) a.route("GET /api/console/resolve", false, true, a.resolve) a.mux.Handle("/api/console/directory/", a.directoryProxy()) a.route("POST /api/console/admin/directory-migrate", true, true, a.migrateDirectory) @@ -83,6 +87,7 @@ func New(database *store.Store, auth *identity.Authenticator, upstream *platform a.route("DELETE /api/console/apps/{id}", true, true, a.deleteApp) a.route("GET /api/console/apps/{id}/comments", false, true, a.comments) a.route("POST /api/console/apps/{id}/comments", true, true, a.createComment) + a.route("POST /api/console/apps/{id}/comments/seen", true, true, a.markCommentsSeen) a.route("DELETE /api/console/apps/{id}/comments/{cid}", true, true, a.deleteComment) a.route("GET /api/console/apps/{id}/screenshots/{sid}", false, true, a.screenshot) a.route("POST /api/console/apps/{id}/screenshots", true, true, a.uploadScreenshot) diff --git a/cmd/server/internal/api/apps.go b/cmd/server/internal/api/apps.go index 7474088..7f27685 100644 --- a/cmd/server/internal/api/apps.go +++ b/cmd/server/internal/api/apps.go @@ -36,11 +36,15 @@ func (a *API) apps(s *request) (any, int, error) { } entries := make([]domain.DirectoryEntry, len(apps)) for i, app := range apps { - entries[i] = domain.EntryOf(app, s.actor.Visible(app)) + app = s.appForCaller(app) + entries[i] = domain.EntryOf(app, app.Permissions.Use) } return appList[domain.DirectoryEntry]{Items: entries}, 200, nil } apps, err := s.tx.Apps(s.actor, scope, groupPath, query.Get("q")) + for i := range apps { + apps[i] = s.appForCaller(apps[i]) + } return appList[domain.App]{Items: apps}, 200, err } @@ -48,6 +52,11 @@ type appList[T any] struct { Items []T `json:"items"` } +func (s *request) appForCaller(app domain.App) domain.App { + app.Permissions = domain.Capabilities(s.actor, app) + return app +} + func (a *API) app(s *request) (any, int, error) { app, err := s.tx.App(s.r.PathValue("id")) if err != nil { @@ -56,7 +65,7 @@ func (a *API) app(s *request) (any, int, error) { if !s.actor.Visible(app) { return nil, 0, httpx.NotFound() } - return app, 200, nil + return s.appForCaller(app), 200, nil } func (s *request) boundApp() (domain.App, error) { @@ -75,7 +84,8 @@ func (a *API) directoryEntry(s *request) (any, int, error) { if err != nil { return nil, 0, err } - return domain.EntryOf(app, s.actor.Visible(app)), 200, nil + app = s.appForCaller(app) + return domain.EntryOf(app, app.Permissions.Use), 200, nil } func (a *API) appByPath(s *request) (any, int, error) { @@ -90,7 +100,7 @@ func (a *API) appByPath(s *request) (any, int, error) { if !s.actor.Visible(app) { return nil, 0, httpx.NotFound() } - return app, 200, nil + return s.appForCaller(app), 200, nil } type appInput struct { @@ -103,6 +113,7 @@ type appInput struct { GroupID *string `json:"groupId"` Slug *string `json:"slug"` Share *domain.SharePolicy `json:"share"` + Contribution *domain.ContributionPolicy `json:"contribution"` OwnerIDs *[]string `json:"ownerIds"` } @@ -152,6 +163,14 @@ func (s *request) applyApp(input appInput, app *domain.App, creating bool) error if input.Share != nil { app.Share = *input.Share } + if input.Contribution != nil { + switch input.Contribution.Scope { + case "off", "group", "company": + app.Contribution = *input.Contribution + default: + return httpx.Invalid("contribution.scope must be off, group, or company") + } + } if app.Tags == nil { app.Tags = []string{} } @@ -211,7 +230,7 @@ func (a *API) createApp(s *request) (any, int, error) { if input.OwnerIDs != nil { return nil, 0, httpx.Invalid("ownerIds can only be changed after creation") } - app := domain.App{ID: uuid.NewString(), CreatedBy: s.person, Share: domain.SharePolicy{Scope: "group"}} + app := domain.App{ID: uuid.NewString(), CreatedBy: s.person, Share: domain.SharePolicy{Scope: "group"}, Contribution: domain.ContributionPolicy{Scope: "group"}} if input.GroupID != nil { app.Share.GroupIDs = []string{*input.GroupID} } @@ -246,7 +265,7 @@ func (a *API) createApp(s *request) (any, int, error) { return nil, 0, err } created, err := s.tx.App(app.ID) - return created, 201, err + return s.appForCaller(created), 201, err } func (s *request) editableApp() (domain.App, error) { @@ -313,7 +332,7 @@ func (a *API) patchApp(s *request) (any, int, error) { return nil, 0, err } updated, err = s.tx.App(app.ID) - return updated, 200, err + return s.appForCaller(updated), 200, err } func (a *API) bindApp(s *request) (any, int, error) { @@ -341,7 +360,7 @@ func (a *API) bindApp(s *request) (any, int, error) { return nil, 0, err } app, err = s.tx.App(app.ID) - return app, 200, err + return s.appForCaller(app), 200, err } func (a *API) deleteApp(s *request) (any, int, error) { diff --git a/cmd/server/internal/api/console-spa.openapi.json b/cmd/server/internal/api/console-spa.openapi.json index 00d7d93..75a843b 100644 --- a/cmd/server/internal/api/console-spa.openapi.json +++ b/cmd/server/internal/api/console-spa.openapi.json @@ -755,6 +755,66 @@ } } }, + "/apps/{id}/comments/seen": { + "post": { + "operationId": "consoleMarkCommentsSeen", + "x-console-operation-id": "consoleMarkCommentsSeen", + "parameters": [ + { + "name": "id", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "responses": { + "204": { + "description": "No content" + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, + "/inbox": { + "get": { + "operationId": "consoleGetInbox", + "x-console-operation-id": "consoleGetInbox", + "parameters": [], + "responses": { + "200": { + "description": "Successful response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Inbox" + } + } + } + }, + "default": { + "description": "HTTP error; never a success", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + } + } + } + }, "/apps/{id}/screenshots": { "post": { "operationId": "consoleUploadScreenshot", @@ -11819,6 +11879,52 @@ }, "updatedAt": { "type": "string" + }, + "contribution": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "enum": [ + "off", + "group", + "company" + ] + } + }, + "required": [ + "scope" + ], + "additionalProperties": false + }, + "permissions": { + "presence": "optionalObservation", + "type": "object", + "properties": { + "use": { + "type": "boolean" + }, + "comment": { + "type": "boolean" + }, + "propose": { + "type": "boolean" + }, + "maintain": { + "type": "boolean" + }, + "data": { + "type": "boolean" + } + }, + "required": [ + "use", + "comment", + "propose", + "maintain", + "data" + ], + "additionalProperties": false } }, "required": [ @@ -11838,7 +11944,8 @@ "share", "createdBy", "createdAt", - "updatedAt" + "updatedAt", + "contribution" ], "additionalProperties": false }, @@ -12127,6 +12234,52 @@ }, "updatedAt": { "type": "string" + }, + "contribution": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "enum": [ + "off", + "group", + "company" + ] + } + }, + "required": [ + "scope" + ], + "additionalProperties": false + }, + "permissions": { + "presence": "optionalObservation", + "type": "object", + "properties": { + "use": { + "type": "boolean" + }, + "comment": { + "type": "boolean" + }, + "propose": { + "type": "boolean" + }, + "maintain": { + "type": "boolean" + }, + "data": { + "type": "boolean" + } + }, + "required": [ + "use", + "comment", + "propose", + "maintain", + "data" + ], + "additionalProperties": false } }, "required": [ @@ -12146,7 +12299,8 @@ "share", "createdBy", "createdAt", - "updatedAt" + "updatedAt", + "contribution" ], "additionalProperties": false }, @@ -12330,6 +12484,52 @@ "updatedAt": { "type": "string" }, + "contribution": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "enum": [ + "off", + "group", + "company" + ] + } + }, + "required": [ + "scope" + ], + "additionalProperties": false + }, + "permissions": { + "presence": "optionalObservation", + "type": "object", + "properties": { + "use": { + "type": "boolean" + }, + "comment": { + "type": "boolean" + }, + "propose": { + "type": "boolean" + }, + "maintain": { + "type": "boolean" + }, + "data": { + "type": "boolean" + } + }, + "required": [ + "use", + "comment", + "propose", + "maintain", + "data" + ], + "additionalProperties": false + }, "path": { "type": "string" }, @@ -12351,6 +12551,7 @@ "appName", "createdAt", "updatedAt", + "contribution", "path", "canOpen" ], @@ -12534,6 +12735,52 @@ "updatedAt": { "type": "string" }, + "contribution": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "enum": [ + "off", + "group", + "company" + ] + } + }, + "required": [ + "scope" + ], + "additionalProperties": false + }, + "permissions": { + "presence": "optionalObservation", + "type": "object", + "properties": { + "use": { + "type": "boolean" + }, + "comment": { + "type": "boolean" + }, + "propose": { + "type": "boolean" + }, + "maintain": { + "type": "boolean" + }, + "data": { + "type": "boolean" + } + }, + "required": [ + "use", + "comment", + "propose", + "maintain", + "data" + ], + "additionalProperties": false + }, "path": { "type": "string" }, @@ -12555,6 +12802,7 @@ "appName", "createdAt", "updatedAt", + "contribution", "path", "canOpen" ], @@ -13158,6 +13406,13 @@ "pending" ], "additionalProperties": false + }, + "view": { + "type": "string", + "enum": [ + "user", + "maker" + ] } }, "required": [ @@ -13168,7 +13423,8 @@ "canCreateApps", "projectId", "directoryPublicURL", - "migration" + "migration", + "view" ], "additionalProperties": false }, @@ -14167,6 +14423,52 @@ }, "updatedAt": { "type": "string" + }, + "contribution": { + "type": "object", + "properties": { + "scope": { + "type": "string", + "enum": [ + "off", + "group", + "company" + ] + } + }, + "required": [ + "scope" + ], + "additionalProperties": false + }, + "permissions": { + "presence": "optionalObservation", + "type": "object", + "properties": { + "use": { + "type": "boolean" + }, + "comment": { + "type": "boolean" + }, + "propose": { + "type": "boolean" + }, + "maintain": { + "type": "boolean" + }, + "data": { + "type": "boolean" + } + }, + "required": [ + "use", + "comment", + "propose", + "maintain", + "data" + ], + "additionalProperties": false } }, "required": [ @@ -14186,7 +14488,8 @@ "share", "createdBy", "createdAt", - "updatedAt" + "updatedAt", + "contribution" ], "additionalProperties": false } @@ -14560,6 +14863,71 @@ ], "additionalProperties": false }, + "Inbox": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "items": { + "type": "array", + "items": { + "type": "object", + "properties": { + "kind": { + "type": "string", + "enum": [ + "accessRequest", + "feedback" + ] + }, + "app": { + "type": "object", + "properties": { + "id": { + "type": "string", + "minLength": 1 + }, + "path": { + "type": "string" + }, + "displayName": { + "type": "string" + }, + "icon": { + "type": "string" + } + }, + "required": [ + "id", + "path", + "displayName", + "icon" + ], + "additionalProperties": false + }, + "count": { + "type": "integer", + "minimum": 0, + "maximum": 9007199254740991 + }, + "since": { + "type": "string" + } + }, + "required": [ + "kind", + "app", + "count", + "since" + ], + "additionalProperties": false + }, + "presence": "total" + } + }, + "required": [ + "items" + ] + }, "Error": { "$schema": "https://json-schema.org/draft/2020-12/schema", "type": "object", diff --git a/cmd/server/internal/api/console_authority.go b/cmd/server/internal/api/console_authority.go new file mode 100644 index 0000000..6e21a86 --- /dev/null +++ b/cmd/server/internal/api/console_authority.go @@ -0,0 +1,284 @@ +package api + +import ( + "bytes" + "context" + "database/sql" + "encoding/json" + "errors" + "io" + "log" + "net/http" + "net/url" + "strings" + "time" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/appserver-go/appserver/identity" + "github.com/appthrust/appserver-go/appserver/requestlog" + "github.com/appthrust/builder-console/cmd/server/internal/buildsession" + "github.com/appthrust/builder-console/cmd/server/internal/domain" +) + +type consoleStackReader interface { + ConsoleStack(context.Context, string, string) (buildsession.ConsoleStack, error) +} + +func (a *API) ConfigureConsoleAuthority(stacks consoleStackReader) { + a.authorityStacks = stacks +} + +type authorityRoute struct { + required, databaseID, componentID, applicationID, branchID string +} + +// These paths are the Platform operations used by the app panels and data API. +// Match segments, not prefixes, so unrelated resources remain pass-through. +func consoleRoute(method, path, projectID string) authorityRoute { + parts := strings.Split(path, "/") + for i := range parts { + var err error + parts[i], err = url.PathUnescape(parts[i]) + if err != nil || (i != 0 && parts[i] == "") { + return authorityRoute{} + } + } + if len(parts) < 6 || parts[0] != "" || parts[1] != "api" || parts[2] != "v1" || parts[3] != "projects" || parts[4] != projectID { + return authorityRoute{} + } + parts = parts[5:] + if method == http.MethodPost && len(parts) == 1 && parts[0] == "application-drafts" { + return authorityRoute{required: "propose"} + } + read := method == http.MethodGet || method == http.MethodHead + if len(parts) >= 3 && parts[0] == "databases" { + data := len(parts) == 3 && method == http.MethodPost && + (parts[2] == "sql" || parts[2] == "script" || parts[2] == "temporary-credentials") + data = data || (len(parts) == 6 && parts[2] == "tables" && parts[5] == "rows" && (read || method == http.MethodPost)) + data = data || (len(parts) == 7 && parts[2] == "tables" && parts[5] == "rows" && (method == http.MethodPatch || method == http.MethodDelete)) + data = data || (parts[2] == "changes" && ( + (len(parts) == 3 && (read || method == http.MethodPost)) || + (len(parts) == 4 && ((read && (parts[3] == "ledger" || parts[3] == "sources" || parts[3] == "source-paths")) || + (method == http.MethodPost && (parts[3] == "from-dev-workspace" || parts[3] == "source-preview")))) || + (len(parts) == 5 && method == http.MethodPost && + ((parts[3] == "ledger" && parts[4] == "acknowledgements") || parts[4] == "approvals" || parts[4] == "archive" || parts[4] == "execute" || parts[4] == "retry")))) + if data { + return authorityRoute{required: "data", databaseID: parts[1]} + } + } + if read && len(parts) == 3 && parts[0] == "components" && parts[2] == "logs" { + return authorityRoute{required: "maintain", componentID: parts[1]} + } + if method == http.MethodPost && len(parts) == 7 && parts[0] == "applications" && + parts[2] == "branches" && parts[4] == "components" && parts[6] == "rollback" { + return authorityRoute{required: "maintain", applicationID: parts[1], branchID: parts[3], componentID: parts[5]} + } + return authorityRoute{} +} + +func requireCapability(actor domain.Actor, app domain.App, required string) error { + permissions := domain.Capabilities(actor, app) + switch required { + case "propose": + if permissions.Propose { + return nil + } + if permissions.Use && actor.CanCreateApps && app.Contribution.Scope == "off" { + return httpx.Fail(403, "contribution_not_accepted", "このアプリは、いま提案を受け付けていません。") + } + case "data": + if permissions.Data { + return nil + } + case "maintain": + if permissions.Maintain { + return nil + } + } + return httpx.Forbidden() +} + +// WithConsoleAuthority gates only console-owned actions before the same-origin +// proxy. The Platform still enforces project authority and proposal lifecycle. +func WithConsoleAuthority(next http.Handler, projectID string, current func() *API) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + route := consoleRoute(r.Method, r.URL.EscapedPath(), projectID) + if route.required == "" { + next.ServeHTTP(w, r) + return + } + var payload []byte + var body map[string]json.RawMessage + var stackID string + if route.required == "propose" { + var err error + payload, err = io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) + if err != nil { + writeAuthorityError(w, r, httpx.Invalid("Request body exceeds the size limit")) + return + } + var kind string + if json.Unmarshal(payload, &body) == nil { + _ = json.Unmarshal(body["kind"], &kind) + _ = json.Unmarshal(body["applicationStackId"], &stackID) + } + if kind != "improvement" { + r.Body = io.NopCloser(bytes.NewReader(payload)) + next.ServeHTTP(w, r) + return + } + } + a := current() + if a == nil { + writeAuthorityError(w, r, httpx.Fail(503, "console_store_unavailable", "The console database is not available")) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) + defer cancel() + claims, bearer, err := a.identity.Authenticate(ctx, r.Header.Get("Authorization")) + if err != nil { + if errors.Is(err, identity.ErrUnavailable) { + writeAuthorityError(w, r, httpx.Fail(503, "identity_unavailable", "The identity provider is temporarily unavailable")) + } else if errors.Is(err, identity.ErrRawKeyNotAccepted) { + writeAuthorityError(w, r, httpx.Fail(401, "raw_key_not_accepted", "Exchange the access key for an assertion before calling this API")) + } else { + writeAuthorityError(w, r, httpx.Fail(401, "unauthenticated", "A valid bearer token is required")) + } + return + } + err = a.withRequest(ctx, claims, bearer, false, true, false, true, func(s *request) error { + s.bearer = r.Header.Get("Authorization") + if route.required != "propose" { + return a.authorizePlatformResource(ctx, s, route) + } + app, err := s.tx.AppByStackID(stackID) + if errors.Is(err, sql.ErrNoRows) { + return httpx.Forbidden() + } + if err != nil { + return err + } + if err := requireCapability(s.actor, app, "propose"); err != nil { + return err + } + reviewers := ownerSubjects(app.Owners) + if len(reviewers) == 0 { + return httpx.Fail(412, "reviewers_unavailable", "An app owner must sign in before a proposal can be created") + } + body["reviewers"], err = json.Marshal(reviewers) + return err + }) + if err != nil { + writeAuthorityError(w, r, directoryError(err)) + return + } + if route.required == "propose" { + payload, err = json.Marshal(body) + if err != nil { + writeAuthorityError(w, r, httpx.Invalid("Invalid draft request")) + return + } + r.Body = io.NopCloser(bytes.NewReader(payload)) + r.ContentLength = int64(len(payload)) + r.Header.Del("Content-Length") + } + next.ServeHTTP(w, r) + }) +} + +// Resolve only stacks bound to Console apps, never a project-wide stack list. +// The target-to-app result (including absence) is cached on this request alone. +func (a *API) authorizePlatformResource(ctx context.Context, s *request, route authorityRoute) error { + if s.actor.IsConsoleAdmin { + return nil + } + if a.authorityStacks == nil { + return upstreamError() + } + apps, cached := s.authorityApps[route] + if !cached { + candidates, err := s.tx.DirectoryApps("", "", "") + if err != nil { + return err + } + for _, app := range candidates { + stack, err := a.authorityStack(ctx, s, *app.StackID) + if err != nil { + return upstreamError() + } + matches := route.databaseID != "" && stack.DatabaseComponentID == route.databaseID + if route.componentID != "" { + matches = stack.WebComponentID == route.componentID && + (route.applicationID == "" || (stack.ApplicationID == route.applicationID && stack.BranchID == route.branchID)) + } + if matches { + apps = append(apps, app) + } + } + if s.authorityApps == nil { + s.authorityApps = make(map[authorityRoute][]domain.App) + } + s.authorityApps[route] = apps + } + if len(apps) == 0 { + return httpx.Forbidden() + } + // A shared database must be authorized for every owning app. + for _, app := range apps { + if err := requireCapability(s.actor, app, route.required); err != nil { + return err + } + } + return nil +} + +func (a *API) authorityStack(ctx context.Context, s *request, id string) (buildsession.ConsoleStack, error) { + if stack, ok := s.authorityStackCache[id]; ok { + return stack, nil + } + stack, err := a.authorityStacks.ConsoleStack(ctx, s.bearer, id) + if err != nil { + var failure *buildsession.Failure + if !errors.As(err, &failure) || failure.Status != http.StatusNotFound { + return stack, err + } + stack = buildsession.ConsoleStack{} + } + if s.authorityStackCache == nil { + s.authorityStackCache = make(map[string]buildsession.ConsoleStack) + } + s.authorityStackCache[id] = stack + return stack, nil +} + +func ownerSubjects(owners []domain.Person) []string { + subjects := make([]string, 0, len(owners)) + seen := make(map[string]bool, len(owners)) + for _, owner := range owners { + if owner.Subject != "" && !seen[owner.Subject] { + subjects = append(subjects, owner.Subject) + seen[owner.Subject] = true + } + } + return subjects +} + +// This middleware is on /api/v1, so errors use the Platform API envelope, not +// the flat console envelope. The SPA must be able to distinguish prerequisites. +func writeAuthorityError(w http.ResponseWriter, r *http.Request, err error) { + var detail *httpx.Error + if !errors.As(err, &detail) { + if requestlog.ID(r.Context()) == "" { + log.Printf("console authority request failed: %v", err) + } + detail = &httpx.Error{Status: 500, Code: "internal_error", Message: "The console could not complete this request"} + } + requestlog.SetError(r, detail) + type errorDetail struct { + Code string `json:"code"` + Message string `json:"message"` + } + httpx.WriteJSON(w, detail.Status, struct { + Error errorDetail `json:"error"` + }{Error: errorDetail{Code: detail.Code, Message: detail.Message}}) +} diff --git a/cmd/server/internal/api/console_authority_test.go b/cmd/server/internal/api/console_authority_test.go new file mode 100644 index 0000000..9155f2a --- /dev/null +++ b/cmd/server/internal/api/console_authority_test.go @@ -0,0 +1,260 @@ +package api + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/builder-console/cmd/server/internal/buildsession" + "github.com/appthrust/builder-console/cmd/server/internal/domain" + "github.com/appthrust/builder-console/cmd/server/internal/store" + "github.com/stretchr/testify/require" +) + +func TestDraftReviewerSubjects(t *testing.T) { + require.Equal(t, []string{"owner", "other"}, ownerSubjects([]domain.Person{ + {ID: "pending"}, {ID: "one", Subject: "owner"}, {ID: "two", Subject: "owner"}, {ID: "three", Subject: "other"}, + })) + require.Empty(t, ownerSubjects([]domain.Person{{ID: "pending"}})) +} + +func TestConsoleAuthorityProxy(t *testing.T) { + h := newHarness(t) + group := createTestGroup(h, "sales", nil) + h.setMember(group.ID, h.directory.person("editor").ID, "member") + app := call[domain.App](h, "editor", "POST", "/apps", map[string]any{"displayName": "Quotes", "groupId": group.ID}, 201) + call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/bind", map[string]string{"stackId": "quotes", "appName": "quotes"}, 200) + var current *API + var received map[string]any + proxy := WithConsoleAuthority(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "request-key", r.Header.Get("Idempotency-Key")) + require.NoError(t, json.NewDecoder(r.Body).Decode(&received)) + w.WriteHeader(http.StatusCreated) + }), "pj-test", func() *API { return current }) + unavailable := httptest.NewRecorder() + request := httptest.NewRequest(http.MethodPost, "/api/v1/projects/pj-test/application-drafts", bytes.NewBufferString(`{"kind":"improvement","applicationStackId":"quotes"}`)) + proxy.ServeHTTP(unavailable, request) + require.Equal(t, http.StatusServiceUnavailable, unavailable.Code) + require.JSONEq(t, `{"error":{"code":"console_store_unavailable","message":"The console database is not available"}}`, unavailable.Body.String()) + require.Nil(t, received) + current = h.server.Config.Handler.(*API) + for _, kind := range []string{"improvement", "creation"} { + body := []byte(`{"kind":"` + kind + `","applicationStackId":"quotes","intent":"Filter quotes","reviewers":["attacker"]}`) + r := httptest.NewRequest(http.MethodPost, "/api/v1/projects/pj-test/application-drafts", bytes.NewReader(body)) + r.Header.Set("Authorization", "Bearer "+token("editor")) + r.Header.Set("Idempotency-Key", "request-key") + w := httptest.NewRecorder() + proxy.ServeHTTP(w, r) + require.Equal(t, 201, w.Code, w.Body.String()) + want := "attacker" + if kind == "improvement" { + want = "editor" + } + require.Equal(t, []any{want}, received["reviewers"]) + require.Equal(t, "Filter quotes", received["intent"]) + } +} + +func TestConsoleAuthorityDecisions(t *testing.T) { + app := domain.App{Group: domain.AppGroup{ID: "sales"}, Owners: []domain.Person{{ID: "owner"}}, Share: domain.SharePolicy{Scope: "company"}, Contribution: domain.ContributionPolicy{Scope: "group"}} + for _, tc := range []struct { + name, required, person, scope, code string + create, member bool + }{ + {"member proposes", "propose", "member", "group", "", true, true}, + {"member cannot build", "propose", "member", "group", "forbidden", false, true}, + {"outsider cannot propose", "propose", "outsider", "group", "forbidden", true, false}, + {"contribution off", "propose", "member", "off", "contribution_not_accepted", true, true}, + {"off and cannot build", "propose", "member", "off", "forbidden", false, true}, + {"owner bypasses off", "propose", "owner", "off", "", false, false}, + {"member cannot read data", "data", "member", "company", "forbidden", true, true}, + {"owner reads data", "data", "owner", "off", "", false, false}, + {"member cannot maintain", "maintain", "member", "group", "forbidden", true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + actor := domain.Actor{PersonID: tc.person, Roles: domain.Roles{CanCreateApps: tc.create}} + if tc.member { + actor.GroupRoles = map[string]string{"sales": "member"} + } + target := app + target.Contribution.Scope = tc.scope + err := requireCapability(actor, target, tc.required) + if tc.code == "" { + require.NoError(t, err) + return + } + var failure *httpx.Error + require.ErrorAs(t, err, &failure) + require.Equal(t, 403, failure.Status) + require.Equal(t, tc.code, failure.Code) + if tc.code == "contribution_not_accepted" { + require.Equal(t, "このアプリは、いま提案を受け付けていません。", failure.Message) + } + }) + } +} + +func TestConsoleAuthorityRoutes(t *testing.T) { + for _, tc := range []struct{ method, path, permission string }{ + {"POST", "application-drafts", "propose"}, + {"POST", "%61pplication-drafts", "propose"}, + {"GET", "databases/db/tables/public/table/rows", "data"}, + {"HEAD", "databases/db/tables/public/table/rows", "data"}, + {"POST", "databases/db/tables/public/table/rows", "data"}, + {"PATCH", "databases/db/tables/public/table/rows/key%2Fvalue", "data"}, + {"DELETE", "databases/db/tables/public/table/rows/key", "data"}, + {"POST", "databases/db/sql", "data"}, + {"POST", "databases/db/script", "data"}, + {"POST", "databases/db/temporary-credentials", "data"}, + {"GET", "databases/db/changes", "data"}, + {"POST", "databases/db/changes", "data"}, + {"GET", "databases/db/changes/ledger", "data"}, + {"POST", "databases/db/changes/ledger/acknowledgements", "data"}, + {"POST", "databases/db/changes/from-dev-workspace", "data"}, + {"GET", "databases/db/changes/sources", "data"}, + {"GET", "databases/db/changes/source-paths", "data"}, + {"POST", "databases/db/changes/source-preview", "data"}, + {"POST", "databases/db/changes/change/approvals", "data"}, + {"POST", "databases/db/changes/change/archive", "data"}, + {"POST", "databases/db/changes/change/execute", "data"}, + {"POST", "databases/db/changes/change/retry", "data"}, + {"GET", "components/web/logs", "maintain"}, + {"HEAD", "components/web/logs", "maintain"}, + {"POST", "applications/app/branches/production/components/web/rollback", "maintain"}, + {"GET", "application-drafts", ""}, + {"GET", "databases/db/schema/tables", ""}, + {"GET", "databases/db/changes/unknown", ""}, + {"POST", "databases/db/changes/change/unknown", ""}, + {"GET", "components/web/logs/unknown", ""}, + {"GET", "applications/app/releases", ""}, + } { + t.Run(tc.method+" "+tc.path, func(t *testing.T) { + route := consoleRoute(tc.method, "/api/v1/projects/pj-test/"+tc.path, "pj-test") + require.Equal(t, tc.permission, route.required) + }) + } + require.Empty(t, consoleRoute("POST", "/api/v1/projects/other/databases/db/sql", "pj-test").required) +} + +func TestConsoleAuthorityUnmatchedPassthrough(t *testing.T) { + for _, tc := range []struct{ method, path, body string }{ + {"GET", "/api/v1/projects/pj-test/applications", ""}, + {"POST", "/api/v1/projects/pj-test/application-drafts", `{"kind":"creation","intent":"same bytes"}`}, + } { + t.Run(tc.method+tc.path, func(t *testing.T) { + forwarded := false + proxy := WithConsoleAuthority(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, err := io.ReadAll(r.Body) + require.NoError(t, err) + require.Equal(t, tc.body, string(body)) + forwarded = true + w.WriteHeader(http.StatusAccepted) + }), "pj-test", func() *API { + t.Fatal("unmatched request consulted Console authority") + return nil + }) + w := httptest.NewRecorder() + proxy.ServeHTTP(w, httptest.NewRequest(tc.method, tc.path, bytes.NewBufferString(tc.body))) + require.True(t, forwarded) + require.Equal(t, http.StatusAccepted, w.Code) + }) + } +} + +func TestConsoleAuthorityUnavailable(t *testing.T) { + proxy := WithConsoleAuthority(http.HandlerFunc(func(http.ResponseWriter, *http.Request) { + t.Fatal("gated request forwarded without the store") + }), "pj-test", func() *API { return nil }) + for _, path := range []string{"databases/db/tables/public/table/rows", "components/web/logs"} { + w := httptest.NewRecorder() + proxy.ServeHTTP(w, httptest.NewRequest("GET", "/api/v1/projects/pj-test/"+path, nil)) + require.Equal(t, 503, w.Code) + require.JSONEq(t, `{"error":{"code":"console_store_unavailable","message":"The console database is not available"}}`, w.Body.String()) + } +} + +type fakeAuthorityStacks struct { + calls int + err error +} + +func (f *fakeAuthorityStacks) ConsoleStack(_ context.Context, bearer, id string) (buildsession.ConsoleStack, error) { + f.calls++ + if bearer == "" { + return buildsession.ConsoleStack{}, errors.New("missing caller bearer") + } + return buildsession.ConsoleStack{ID: id, ApplicationID: "quotes", BranchID: "production", WebComponentID: "quotes-web", DatabaseComponentID: "quotes-db"}, f.err +} + +func TestConsoleAuthorityResources(t *testing.T) { + h := newHarness(t) + group := createTestGroup(h, "sales", nil) + h.setMember(group.ID, h.directory.person("editor").ID, "member") + app := call[domain.App](h, "editor", "POST", "/apps", map[string]any{"displayName": "Quotes", "groupId": group.ID, "share": domain.SharePolicy{Scope: "company"}}, 201) + call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/bind", map[string]string{"stackId": "quotes", "appName": "quotes"}, 200) + a := h.server.Config.Handler.(*API) + stacks := &fakeAuthorityStacks{} + a.ConfigureConsoleAuthority(stacks) + for _, tc := range []struct{ person, method, path string; status int }{ + {"viewer", "GET", "databases/quotes-db/tables/public/quotes/rows", 403}, + {"editor", "GET", "databases/quotes-db/tables/public/quotes/rows", 204}, + {"viewer", "GET", "components/quotes-web/logs", 403}, + {"editor", "POST", "applications/quotes/branches/production/components/quotes-web/rollback", 204}, + {"viewer", "POST", "applications/quotes/branches/production/components/quotes-web/rollback", 403}, + {"editor", "POST", "applications/wrong/branches/production/components/quotes-web/rollback", 403}, + {"editor", "POST", "databases/unowned/sql", 403}, + {"admin", "POST", "databases/unowned/sql", 204}, + } { + t.Run(tc.person+tc.path, func(t *testing.T) { + forwarded := false + proxy := WithConsoleAuthority(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { forwarded = true; w.WriteHeader(204) }), "pj-test", func() *API { return a }) + r := httptest.NewRequest(tc.method, "/api/v1/projects/pj-test/"+tc.path, nil) + r.Header.Set("Authorization", "Bearer "+token(tc.person)) + w := httptest.NewRecorder() + proxy.ServeHTTP(w, r) + require.Equal(t, tc.status, w.Code, w.Body.String()) + require.Equal(t, tc.status == 204, forwarded) + }) + } + before := stacks.calls + require.NoError(t, h.database.Do(t.Context(), false, func(tx *store.Tx) error { + s := &request{tx: tx, bearer: "Bearer caller", actor: domain.Actor{PersonID: app.Owners[0].ID}} + route := authorityRoute{required: "data", databaseID: "quotes-db"} + require.NoError(t, a.authorizePlatformResource(t.Context(), s, route)) + require.NoError(t, a.authorizePlatformResource(t.Context(), s, route)) + return nil + })) + require.Equal(t, before+1, stacks.calls, "same target resolves once in a request") +} + +func TestConsoleAuthorityStackClient(t *testing.T) { + for _, body := range []string{ + `{"id":"stack","databaseComponentId":"db","webComponentId":"web","applicationId":"app","branchId":"production"}`, + `{"id":"other","databaseComponentId":"db"}`, + } { + t.Run(body, func(t *testing.T) { + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + require.Equal(t, "/api/v1/projects/project/application-stacks/stack", r.URL.Path) + require.Equal(t, "Bearer caller", r.Header.Get("Authorization")) + _, _ = w.Write([]byte(body)) + })) + defer upstream.Close() + client, err := buildsession.NewClient(upstream.URL, "project", nil) + require.NoError(t, err) + stack, err := client.ConsoleStack(t.Context(), "Bearer caller", "stack") + if stack.ID == "other" { + require.Error(t, err) + } else { + require.NoError(t, err) + require.Equal(t, "db", stack.DatabaseComponentID) + require.Equal(t, "web", stack.WebComponentID) + } + }) + } +} diff --git a/cmd/server/internal/api/draft_reviewers.go b/cmd/server/internal/api/draft_reviewers.go deleted file mode 100644 index d0d0c4d..0000000 --- a/cmd/server/internal/api/draft_reviewers.go +++ /dev/null @@ -1,124 +0,0 @@ -package api - -import ( - "bytes" - "context" - "encoding/json" - "errors" - "io" - "log" - "net/http" - "time" - - "github.com/appthrust/appserver-go/appserver/httpx" - "github.com/appthrust/appserver-go/appserver/identity" - "github.com/appthrust/appserver-go/appserver/requestlog" - "github.com/appthrust/builder-console/cmd/server/internal/domain" -) - -// WithDraftReviewers enriches improvement creation only. Owners remain console -// data; decision authorization and the draft lifecycle belong to the Platform API. -func WithDraftReviewers(next http.Handler, projectID string, current func() *API) http.Handler { - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodPost || r.URL.Path != "/api/v1/projects/"+projectID+"/application-drafts" { - next.ServeHTTP(w, r) - return - } - payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) - if err != nil { - writeDraftError(w, r, httpx.Invalid("Request body exceeds the size limit")) - return - } - var body map[string]json.RawMessage - var kind, stackID string - if json.Unmarshal(payload, &body) == nil { - _ = json.Unmarshal(body["kind"], &kind) - _ = json.Unmarshal(body["applicationStackId"], &stackID) - } - if kind == "improvement" { - a := current() - if a == nil { - writeDraftError(w, r, httpx.Fail(503, "console_store_unavailable", "The console database is not available")) - return - } - ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) - defer cancel() - claims, bearer, err := a.identity.Authenticate(ctx, r.Header.Get("Authorization")) - if err != nil { - if errors.Is(err, identity.ErrUnavailable) { - writeDraftError(w, r, httpx.Fail(503, "identity_unavailable", "The identity provider is temporarily unavailable")) - return - } - if errors.Is(err, identity.ErrRawKeyNotAccepted) { - writeDraftError(w, r, httpx.Fail(401, "raw_key_not_accepted", "Exchange the access key for an assertion before calling this API")) - return - } - writeDraftError(w, r, httpx.Fail(401, "unauthenticated", "A valid bearer token is required")) - return - } - err = a.withRequest(ctx, claims, bearer, false, true, false, false, func(s *request) error { - apps, err := s.tx.Apps(s.actor, "all", "", "") - if err != nil { - return err - } - for _, app := range apps { - if app.StackID == nil || *app.StackID != stackID { - continue - } - reviewers := ownerSubjects(app.Owners) - if len(reviewers) == 0 { - return httpx.Fail(412, "reviewers_unavailable", "An app owner must sign in before a proposal can be created") - } - body["reviewers"], err = json.Marshal(reviewers) - return err - } - return httpx.NotFound() - }) - if err != nil { - writeDraftError(w, r, directoryError(err)) - return - } - payload, err = json.Marshal(body) - if err != nil { - writeDraftError(w, r, httpx.Invalid("Invalid draft request")) - return - } - } - r.Body = io.NopCloser(bytes.NewReader(payload)) - r.ContentLength = int64(len(payload)) - r.Header.Del("Content-Length") - next.ServeHTTP(w, r) - }) -} - -func ownerSubjects(owners []domain.Person) []string { - subjects := make([]string, 0, len(owners)) - seen := make(map[string]bool, len(owners)) - for _, owner := range owners { - if owner.Subject != "" && !seen[owner.Subject] { - subjects = append(subjects, owner.Subject) - seen[owner.Subject] = true - } - } - return subjects -} - -// This middleware is on /api/v1, so errors use the Platform API envelope, not -// the flat console envelope. The SPA must be able to distinguish prerequisites. -func writeDraftError(w http.ResponseWriter, r *http.Request, err error) { - var detail *httpx.Error - if !errors.As(err, &detail) { - if requestlog.ID(r.Context()) == "" { - log.Printf("console draft request failed: %v", err) - } - detail = &httpx.Error{Status: 500, Code: "internal_error", Message: "The console could not complete this request"} - } - requestlog.SetError(r, detail) - type errorDetail struct { - Code string `json:"code"` - Message string `json:"message"` - } - httpx.WriteJSON(w, detail.Status, struct { - Error errorDetail `json:"error"` - }{Error: errorDetail{Code: detail.Code, Message: detail.Message}}) -} diff --git a/cmd/server/internal/api/draft_reviewers_test.go b/cmd/server/internal/api/draft_reviewers_test.go deleted file mode 100644 index 0727a11..0000000 --- a/cmd/server/internal/api/draft_reviewers_test.go +++ /dev/null @@ -1,56 +0,0 @@ -package api - -import ( - "bytes" - "encoding/json" - "net/http" - "net/http/httptest" - "testing" - - "github.com/appthrust/builder-console/cmd/server/internal/domain" - "github.com/stretchr/testify/require" -) - -func TestDraftReviewerSubjects(t *testing.T) { - require.Equal(t, []string{"owner", "other"}, ownerSubjects([]domain.Person{ - {ID: "pending"}, {ID: "one", Subject: "owner"}, {ID: "two", Subject: "owner"}, {ID: "three", Subject: "other"}, - })) - require.Empty(t, ownerSubjects([]domain.Person{{ID: "pending"}})) -} - -func TestDraftReviewersProxy(t *testing.T) { - h := newHarness(t) - group := createTestGroup(h, "sales", nil) - h.setMember(group.ID, h.directory.person("editor").ID, "member") - app := call[domain.App](h, "editor", "POST", "/apps", map[string]any{"displayName": "Quotes", "groupId": group.ID}, 201) - call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/bind", map[string]string{"stackId": "quotes", "appName": "quotes"}, 200) - var current *API - var received map[string]any - proxy := WithDraftReviewers(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - require.Equal(t, "request-key", r.Header.Get("Idempotency-Key")) - require.NoError(t, json.NewDecoder(r.Body).Decode(&received)) - w.WriteHeader(http.StatusCreated) - }), "pj-test", func() *API { return current }) - unavailable := httptest.NewRecorder() - request := httptest.NewRequest(http.MethodPost, "/api/v1/projects/pj-test/application-drafts", bytes.NewBufferString(`{"kind":"improvement","applicationStackId":"quotes"}`)) - proxy.ServeHTTP(unavailable, request) - require.Equal(t, http.StatusServiceUnavailable, unavailable.Code) - require.JSONEq(t, `{"error":{"code":"console_store_unavailable","message":"The console database is not available"}}`, unavailable.Body.String()) - require.Nil(t, received) - current = h.server.Config.Handler.(*API) - for _, kind := range []string{"improvement", "creation"} { - body := []byte(`{"kind":"` + kind + `","applicationStackId":"quotes","intent":"Filter quotes","reviewers":["attacker"]}`) - r := httptest.NewRequest(http.MethodPost, "/api/v1/projects/pj-test/application-drafts", bytes.NewReader(body)) - r.Header.Set("Authorization", "Bearer "+token("editor")) - r.Header.Set("Idempotency-Key", "request-key") - w := httptest.NewRecorder() - proxy.ServeHTTP(w, r) - require.Equal(t, 201, w.Code, w.Body.String()) - want := "attacker" - if kind == "improvement" { - want = "editor" - } - require.Equal(t, []any{want}, received["reviewers"]) - require.Equal(t, "Filter quotes", received["intent"]) - } -} diff --git a/cmd/server/internal/api/groups.go b/cmd/server/internal/api/groups.go index ab94ea2..12a371a 100644 --- a/cmd/server/internal/api/groups.go +++ b/cmd/server/internal/api/groups.go @@ -20,6 +20,7 @@ type meResponse struct { TeamSlug string `json:"teamSlug,omitempty"` DirectoryPublicURL string `json:"directoryPublicURL"` Migration store.MigrationStatus `json:"migration"` + View string `json:"view"` } func (a *API) me(s *request) (any, int, error) { @@ -35,11 +36,23 @@ func (a *API) me(s *request) (any, int, error) { if effective == nil || s.access.NotMember { effective = []string{} } + view := "user" + if s.actor.IsConsoleAdmin || len(managed) > 0 { + view = "maker" + } else { + owns, err := s.tx.OwnsAnyApp(s.person.ID) + if err != nil { + return nil, 0, err + } + if owns { + view = "maker" + } + } binding, resolveErr := a.links.Resolver().Resolve(s.r.Context(), s.bearer, "directory") if resolveErr != nil { return nil, 0, resolveErr } - return meResponse{Person: s.person, Roles: domain.Roles(s.access.Roles), EffectiveGroupIDs: effective, ManagedGroupIDs: managed, ProjectID: a.platform.ProjectID, PlatformUnavailable: s.platformUnavailable, NotMember: s.access.NotMember, DirectoryPublicURL: binding.PublicURL, Migration: migration}, 200, err + return meResponse{Person: s.person, Roles: domain.Roles(s.access.Roles), EffectiveGroupIDs: effective, ManagedGroupIDs: managed, ProjectID: a.platform.ProjectID, PlatformUnavailable: s.platformUnavailable, NotMember: s.access.NotMember, DirectoryPublicURL: binding.PublicURL, Migration: migration, View: view}, 200, err } func (a *API) migrateDirectory(s *request) (any, int, error) { if !s.actor.IsConsoleAdmin { diff --git a/cmd/server/internal/api/inbox.go b/cmd/server/internal/api/inbox.go new file mode 100644 index 0000000..328e007 --- /dev/null +++ b/cmd/server/internal/api/inbox.go @@ -0,0 +1,35 @@ +package api + +import ( + "net/http" + + "github.com/appthrust/builder-console/cmd/server/internal/domain" +) + +type inboxResponse struct { + Items []domain.InboxItem `json:"items"` +} + +func (a *API) inbox(s *request) (any, int, error) { + apps, err := s.tx.MaintainedApps(s.actor) + if err != nil { + return nil, 0, err + } + ids := make([]string, len(apps)) + for i := range apps { + ids[i] = apps[i].ID + } + activity, err := s.tx.InboxActivity(ids, s.actor.PersonID) + if err != nil { + return nil, 0, err + } + return inboxResponse{Items: domain.DeriveInbox(s.actor, apps, activity)}, http.StatusOK, nil +} + +func (a *API) markCommentsSeen(s *request) (any, int, error) { + app, err := s.accessRequestApp() + if err != nil { + return nil, 0, err + } + return nil, http.StatusNoContent, s.tx.MarkCommentsSeen(app.ID, s.actor.PersonID) +} diff --git a/cmd/server/internal/api/openapi.json b/cmd/server/internal/api/openapi.json index 6331bc0..f5dd856 100644 --- a/cmd/server/internal/api/openapi.json +++ b/cmd/server/internal/api/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Builder Console built-in app API", "version": "1.0.0", - "description": "Viewer-authorized app catalog for built-in app links. Existing console SPA routes share this API." + "description": "Viewer-authorized app catalog and Console role-based views. App permissions are derived for the caller. Contribution defaults to group; only maintainers can change it. The inbox contains pending access requests and unseen feedback from other people on maintained apps, with zero counts omitted, ordered by kind (accessRequest, feedback) then latest activity descending. Same-origin Platform data, logs, rollback and improvement creation also enforce Console authority." }, "x-appthrust-definition": "builder-console", "servers": [ @@ -17,6 +17,62 @@ } ], "paths": { + "/me": { + "get": { + "operationId": "getMe", + "summary": "Get the caller and relationship-based user or maker view", + "responses": { + "200": { + "description": "Maker when a Console admin, group manager, or owner of any app; otherwise user", + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Me"}}} + } + } + } + }, + "/inbox": { + "get": { + "operationId": "getInbox", + "summary": "List pending access requests and unseen feedback for maintained apps", + "responses": { + "200": { + "description": "Caller-specific inbox", + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Inbox"}}} + } + } + } + }, + "/apps/{id}/comments/seen": { + "post": { + "operationId": "markCommentsSeen", + "summary": "Mark this app's feedback seen by the caller", + "description": "Requires maintain authority. Upserts the caller's last-seen timestamp to now.", + "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}], + "responses": { + "204": {"description": "Feedback marked seen"}, + "403": {"description": "Caller cannot maintain this app", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}} + } + } + }, + "/apps/by-path/{path}": { + "get": { + "operationId": "getAppByPath", + "summary": "Get a visible app by group path and slug", + "parameters": [{"name": "path", "in": "path", "required": true, "schema": {"type": "string"}}], + "responses": { + "200": {"description": "App with caller permissions", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/App"}}}} + } + } + }, + "/apps/{id}/directory-entry": { + "get": { + "operationId": "getDirectoryEntry", + "summary": "Get a bound app's introduction", + "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}], + "responses": { + "200": {"description": "Introduction with caller permissions", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/DirectoryEntry"}}}} + } + } + }, "/apps": { "get": { "operationId": "listApps", @@ -103,6 +159,21 @@ } } } + }, + "patch": { + "operationId": "updateApp", + "summary": "Update an app maintained by the caller", + "description": "All fields, including contribution.scope and sharing, require maintain authority. Contribution uses the existing PATCH transaction semantics; no additional ETag or idempotency preconditions.", + "parameters": [{"name": "id", "in": "path", "required": true, "schema": {"type": "string"}}], + "requestBody": { + "required": true, + "content": {"application/json": {"schema": {"$ref": "#/components/schemas/AppPatch"}}} + }, + "responses": { + "200": {"description": "Updated app with caller permissions", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/App"}}}}, + "400": {"description": "Invalid contribution scope or input", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}}, + "403": {"description": "Caller cannot maintain this app", "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}} + } } } }, @@ -114,6 +185,114 @@ } }, "schemas": { + "ContributionPolicy": { + "type": "object", + "required": ["scope"], + "properties": {"scope": {"type": "string", "enum": ["off", "group", "company"], "default": "group"}} + }, + "Permissions": { + "type": "object", + "required": ["use", "comment", "propose", "maintain", "data"], + "properties": { + "use": {"type": "boolean"}, + "comment": {"type": "boolean"}, + "propose": {"type": "boolean"}, + "maintain": {"type": "boolean"}, + "data": {"type": "boolean", "description": "Interim policy equals maintain; remains a separate capability"} + } + }, + "AppPatch": { + "type": "object", + "properties": { + "displayName": {"type": "string"}, + "description": {"type": "string"}, + "icon": {"type": "string"}, + "tags": {"type": "array", "items": {"type": "string"}}, + "guide": {"type": "string", "maxLength": 4000}, + "capabilities": {"type": "array", "maxItems": 10, "items": {"type": "string", "maxLength": 60}}, + "groupId": {"type": "string"}, + "slug": {"type": "string"}, + "ownerIds": {"type": "array", "minItems": 1, "items": {"type": "string"}}, + "share": {"$ref": "#/components/schemas/SharePolicy"}, + "contribution": {"$ref": "#/components/schemas/ContributionPolicy"} + } + }, + "Me": { + "type": "object", + "required": ["person", "isConsoleAdmin", "canCreateApps", "effectiveGroupIds", "managedGroupIds", "projectId", "directoryPublicURL", "migration", "view"], + "properties": { + "person": {"$ref": "#/components/schemas/Person"}, + "isConsoleAdmin": {"type": "boolean"}, + "canCreateApps": {"type": "boolean"}, + "effectiveGroupIds": {"type": "array", "items": {"type": "string"}}, + "managedGroupIds": {"type": "array", "items": {"type": "string"}}, + "projectId": {"type": "string"}, + "directoryPublicURL": {"type": "string"}, + "platformUnavailable": {"type": "boolean"}, + "notMember": {"type": "boolean"}, + "teamSlug": {"type": "string"}, + "migration": { + "type": "object", + "required": ["pending", "groups", "memberships", "people"], + "properties": { + "pending": {"type": "boolean"}, + "groups": {"type": "integer"}, + "memberships": {"type": "integer"}, + "people": {"type": "integer"} + } + }, + "view": {"type": "string", "enum": ["user", "maker"]} + } + }, + "Inbox": { + "type": "object", + "required": ["items"], + "properties": { + "items": {"type": "array", "items": {"$ref": "#/components/schemas/InboxItem"}} + } + }, + "InboxItem": { + "type": "object", + "required": ["kind", "app", "count", "since"], + "properties": { + "kind": {"type": "string", "enum": ["accessRequest", "feedback"]}, + "app": { + "type": "object", + "required": ["id", "path", "displayName", "icon"], + "properties": { + "id": {"type": "string"}, + "path": {"type": "string"}, + "displayName": {"type": "string"}, + "icon": {"type": "string"} + } + }, + "count": {"type": "integer", "minimum": 1}, + "since": {"type": "string", "format": "date-time"} + } + }, + "DirectoryEntry": { + "type": "object", + "required": ["id", "path", "displayName", "description", "icon", "tags", "capabilities", "screenshots", "group", "owners", "appName", "stackId", "createdAt", "updatedAt", "canOpen", "contribution", "permissions"], + "properties": { + "id": {"type": "string"}, + "path": {"type": "string"}, + "displayName": {"type": "string"}, + "description": {"type": "string"}, + "icon": {"type": "string"}, + "tags": {"type": "array", "items": {"type": "string"}}, + "capabilities": {"type": "array", "items": {"type": "string"}}, + "screenshots": {"type": "array", "items": {"$ref": "#/components/schemas/Screenshot"}}, + "group": {"$ref": "#/components/schemas/AppGroup"}, + "owners": {"type": "array", "items": {"$ref": "#/components/schemas/Person"}}, + "appName": {"type": "string", "nullable": true}, + "stackId": {"type": "string", "nullable": true}, + "createdAt": {"type": "string", "format": "date-time"}, + "updatedAt": {"type": "string", "format": "date-time"}, + "canOpen": {"type": "boolean"}, + "contribution": {"$ref": "#/components/schemas/ContributionPolicy"}, + "permissions": {"$ref": "#/components/schemas/Permissions"} + } + }, "Person": { "type": "object", "required": [ @@ -240,6 +419,8 @@ "stackId", "appName", "share", + "contribution", + "permissions", "createdBy", "createdAt", "updatedAt" @@ -303,6 +484,8 @@ "share": { "$ref": "#/components/schemas/SharePolicy" }, + "contribution": {"$ref": "#/components/schemas/ContributionPolicy"}, + "permissions": {"$ref": "#/components/schemas/Permissions"}, "createdBy": { "$ref": "#/components/schemas/Person" }, diff --git a/cmd/server/internal/api/public_wire_contract_test.go b/cmd/server/internal/api/public_wire_contract_test.go index 03a1e33..c6e7f60 100644 --- a/cmd/server/internal/api/public_wire_contract_test.go +++ b/cmd/server/internal/api/public_wire_contract_test.go @@ -13,15 +13,17 @@ import ( "github.com/stretchr/testify/require" ) -// Public link clients keep their SDK-owned document. The internal canonical -// writer can be stricter, but must not change any shared field's JSON type. +// The served document may add Console features while preserving every SDK field. +// The internal canonical writer must agree with both published contracts. func TestPublicAndCanonicalConsoleContractsAgree(t *testing.T) { - require.Equal(t, consolecontract.Document, openAPIDocument) var public, canonical map[string]any require.NoError(t, json.Unmarshal(openAPIDocument, &public)) require.NoError(t, json.Unmarshal(consoleSPADocument, &canonical)) publicSchemas := public["components"].(map[string]any)["schemas"].(map[string]any) canonicalSchemas := canonical["components"].(map[string]any)["schemas"].(map[string]any) + var sdk map[string]any + require.NoError(t, json.Unmarshal(consolecontract.Document, &sdk)) + sdkSchemas := sdk["components"].(map[string]any)["schemas"].(map[string]any) compiler := jsonschema.NewCompiler() require.NoError(t, compiler.AddResource("https://console.test/public.json", openAPI30JSONSchema(public))) for _, name := range []string{"App", "AppList"} { @@ -29,6 +31,11 @@ func TestPublicAndCanonicalConsoleContractsAgree(t *testing.T) { newFields := map[string][]string{} fieldTypes(publicSchemas[name], publicSchemas, "", oldFields) fieldTypes(canonicalSchemas[name], canonicalSchemas, "", newFields) + sdkFields := map[string][]string{} + fieldTypes(sdkSchemas[name], sdkSchemas, "", sdkFields) + for path, kinds := range sdkFields { + require.Equal(t, kinds, oldFields[path], "SDK compatibility: "+name+path) + } for path, kinds := range oldFields { require.Equal(t, kinds, newFields[path], name+path) } diff --git a/cmd/server/internal/api/role_views_test.go b/cmd/server/internal/api/role_views_test.go new file mode 100644 index 0000000..16f9d69 --- /dev/null +++ b/cmd/server/internal/api/role_views_test.go @@ -0,0 +1,84 @@ +package api + +import ( + "testing" + + "github.com/appthrust/appserver-go/appserver/httpx" + "github.com/appthrust/builder-console/cmd/server/internal/domain" + "github.com/stretchr/testify/require" +) + +func TestRoleViewsAppResponsesAndMutationAuthority(t *testing.T) { + h := newHarness(t) + group := createTestGroup(h, "sales", nil) + h.setMember(group.ID, h.directory.person("editor").ID, "member") + require.Equal(t, "user", call[meResponse](h, "editor", "GET", "/me", nil, 200).View) + app := call[domain.App](h, "editor", "POST", "/apps", map[string]any{"displayName": "Quotes", "groupId": group.ID, "share": domain.SharePolicy{Scope: "company"}}, 201) + require.Equal(t, "group", app.Contribution.Scope) + require.True(t, app.Permissions.Maintain) + require.True(t, app.Permissions.Data) + require.Equal(t, "maker", call[meResponse](h, "editor", "GET", "/me", nil, 200).View) + require.Equal(t, "user", call[meResponse](h, "viewer", "GET", "/me", nil, 200).View) + require.Equal(t, "maker", call[meResponse](h, "admin", "GET", "/me", nil, 200).View) + h.setMember(group.ID, h.directory.person("manager").ID, "manager") + require.Equal(t, "maker", call[meResponse](h, "manager", "GET", "/me", nil, 200).View) + app = call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/bind", map[string]string{"stackId": "quotes", "appName": "quotes"}, 200) + for _, path := range []string{"/apps/" + app.ID, "/apps/by-path/" + app.Path()} { + got := call[domain.App](h, "viewer", "GET", path, nil, 200) + require.Equal(t, "group", got.Contribution.Scope) + require.Equal(t, domain.Permissions{Use: true, Comment: true}, got.Permissions) + } + apps := call[list[domain.App]](h, "viewer", "GET", "/apps", nil, 200).Data + require.Len(t, apps, 1) + require.Equal(t, domain.Permissions{Use: true, Comment: true}, apps[0].Permissions) + entry := call[domain.DirectoryEntry](h, "viewer", "GET", "/apps/"+app.ID+"/directory-entry", nil, 200) + require.Equal(t, "group", entry.Contribution.Scope) + require.Equal(t, domain.Permissions{Use: true, Comment: true}, entry.Permissions) + for _, body := range []any{ + map[string]any{"contribution": map[string]string{"scope": "off"}}, + map[string]string{"displayName": "Changed"}, + map[string]any{"share": domain.SharePolicy{Scope: "private"}}, + } { + call[httpx.Error](h, "viewer", "PATCH", "/apps/"+app.ID, body, 403) + } + call[httpx.Error](h, "viewer", "POST", "/apps/"+app.ID+"/screenshots", nil, 403) + call[httpx.Error](h, "viewer", "PATCH", "/apps/"+app.ID+"/screenshots", map[string]any{"order": []string{}}, 403) + call[httpx.Error](h, "viewer", "DELETE", "/apps/"+app.ID+"/screenshots/missing", nil, 403) + for _, scope := range []string{"off", "company", "group"} { + updated := call[domain.App](h, "editor", "PATCH", "/apps/"+app.ID, map[string]any{"contribution": map[string]string{"scope": scope}}, 200) + require.Equal(t, scope, updated.Contribution.Scope) + require.True(t, updated.Permissions.Propose) + } + bad := call[httpx.Error](h, "editor", "PATCH", "/apps/"+app.ID, map[string]any{"contribution": map[string]string{"scope": "unknown"}}, 400) + require.Equal(t, "contribution.scope must be off, group, or company", bad.Message) +} + +func TestRoleViewsInboxAndSeen(t *testing.T) { + h := newHarness(t) + group := createTestGroup(h, "sales", nil) + h.setMember(group.ID, h.directory.person("editor").ID, "member") + app := call[domain.App](h, "editor", "POST", "/apps", map[string]any{"displayName": "Quotes", "groupId": group.ID}, 201) + call[domain.App](h, "editor", "POST", "/apps/"+app.ID+"/bind", map[string]string{"stackId": "quotes", "appName": "quotes"}, 200) + require.Empty(t, call[inboxResponse](h, "editor", "GET", "/inbox", nil, 200).Items) + call[createAccessRequestResponse](h, "viewer", "POST", "/access-requests", map[string]string{"appName": "quotes", "message": "Please"}, 201) + call[domain.AppComment](h, "editor", "POST", "/apps/"+app.ID+"/comments", map[string]string{"body": "Own comment"}, 201) + comment := call[domain.AppComment](h, "viewer", "POST", "/apps/"+app.ID+"/comments", map[string]string{"body": "Feedback"}, 201) + items := call[inboxResponse](h, "editor", "GET", "/inbox", nil, 200).Items + require.Len(t, items, 2) + require.Equal(t, "accessRequest", items[0].Kind) + require.Equal(t, 1, items[0].Count) + require.Equal(t, "feedback", items[1].Kind) + require.Equal(t, 1, items[1].Count) + require.Equal(t, app.Path(), items[1].App.Path) + require.Empty(t, call[inboxResponse](h, "viewer", "GET", "/inbox", nil, 200).Items) + call[httpx.Error](h, "viewer", "POST", "/apps/"+app.ID+"/comments/seen", nil, 403) + call[any](h, "editor", "POST", "/apps/"+app.ID+"/comments/seen", nil, 204) + items = call[inboxResponse](h, "editor", "GET", "/inbox", nil, 200).Items + require.Len(t, items, 1) + require.Equal(t, "accessRequest", items[0].Kind) + call[any](h, "viewer", "DELETE", "/apps/"+app.ID+"/comments/"+comment.ID, nil, 204) + h.setMember(group.ID, h.directory.person("manager").ID, "manager") + items = call[inboxResponse](h, "manager", "GET", "/inbox", nil, 200).Items + require.Len(t, items, 2, "read markers are per maintainer; deleted comments do not count") + require.Equal(t, 1, items[1].Count, "the other maintainer's comment is unread") +} diff --git a/cmd/server/internal/api/testdata/console-wire.json b/cmd/server/internal/api/testdata/console-wire.json index f6a91b9..b472817 100644 --- a/cmd/server/internal/api/testdata/console-wire.json +++ b/cmd/server/internal/api/testdata/console-wire.json @@ -72,6 +72,8 @@ "groupIds": [], "extraPersonIds": [] }, + "contribution": {"scope": "group"}, + "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true}, "createdBy": { "id": "person", "email": "person@example.test", @@ -126,6 +128,8 @@ "groupIds": [], "extraPersonIds": [] }, + "contribution": {"scope": "group"}, + "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true}, "createdBy": { "id": "person", "email": "person@example.test", @@ -183,7 +187,9 @@ "stackId": null, "createdAt": "2026-11-01T00:00:00Z", "updatedAt": "2026-11-01T00:00:00Z", - "canOpen": false + "canOpen": false, + "contribution": {"scope": "group"}, + "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true} } }, { @@ -208,7 +214,9 @@ "stackId": null, "createdAt": "0001-01-01T00:00:00Z", "updatedAt": "0001-01-01T00:00:00Z", - "canOpen": false + "canOpen": false, + "contribution": {"scope": "group"}, + "permissions": {"use": false, "comment": false, "propose": false, "maintain": false, "data": false} } }, { @@ -249,7 +257,9 @@ "stackId": null, "createdAt": "2026-11-01T00:00:00Z", "updatedAt": "2026-11-01T00:00:00Z", - "canOpen": false + "canOpen": false, + "contribution": {"scope": "group"}, + "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true} } ] } @@ -406,6 +416,7 @@ "effectiveGroupIds": [], "managedGroupIds": [], "projectId": "project", + "view": "maker", "directoryPublicURL": "", "migration": { "pending": false, @@ -432,6 +443,7 @@ "effectiveGroupIds": [], "managedGroupIds": [], "projectId": "project", + "view": "user", "platformUnavailable": true, "notMember": true, "teamSlug": "team", @@ -630,6 +642,8 @@ "groupIds": [], "extraPersonIds": [] }, + "contribution": {"scope": "group"}, + "permissions": {"use": true, "comment": true, "propose": true, "maintain": true, "data": true}, "createdBy": { "id": "person", "email": "person@example.test", @@ -688,6 +702,16 @@ "defaultTemplateId": "nextjs-postgres" } }, + { + "name": "inbox", + "schema": "Inbox", + "body": {"items": [{"kind": "feedback", "app": {"id": "app", "path": "group/app", "displayName": "", "icon": ""}, "count": 2, "since": "2026-11-01T00:00:00Z"}]} + }, + { + "name": "empty-inbox", + "schema": "Inbox", + "body": {"items": []} + }, { "name": "empty-tools", "schema": "Tools", diff --git a/cmd/server/internal/api/wire_contract_test.go b/cmd/server/internal/api/wire_contract_test.go index 8f0d7e6..67f12f8 100644 --- a/cmd/server/internal/api/wire_contract_test.go +++ b/cmd/server/internal/api/wire_contract_test.go @@ -42,6 +42,8 @@ func consoleWriterFixtures(t *testing.T) []writerFixture { unknown := domain.Person{ID: "removed", Unknown: true} upstreamPerson := directory.Person{ID: person.ID, Subject: &subject, Email: person.Email, DisplayName: person.DisplayName} app := domain.App{ID: "app", Slug: "app", Group: domain.AppGroup{ID: "group", Name: "Group", Path: "group"}, Owners: []domain.Person{person, unknown}, CreatedBy: person, Share: domain.SharePolicy{Scope: "private", GroupIDs: []string{}, ExtraPersonIDs: []string{}}, Tags: []string{}, Capabilities: []string{}, Screenshots: []domain.Screenshot{}, CreatedAt: at, UpdatedAt: at} + app.Contribution = domain.ContributionPolicy{Scope: "group"} + app.Permissions = domain.Capabilities(domain.Actor{PersonID: person.ID}, app) group := directory.Group{ID: "group", Name: "Group", Slug: "group", Path: "group", CreatedAt: at, UpdatedAt: at} request := domain.AppAccessRequest{ID: "request", AppID: app.ID, Requester: unknown, Status: domain.RequestPending, RequestedAt: at} shot := domain.Screenshot{ID: "screenshot", Width: 2, Height: 3} @@ -49,7 +51,7 @@ func consoleWriterFixtures(t *testing.T) []writerFixture { fixtures := []writerFixture{ {"resolved-person", "Person", person}, {"pending-person", "Person", pending}, {"unknown-person", "UnknownPerson", unknown}, {"app", "App", app}, {"app-list", "AppList", appList[domain.App]{Items: []domain.App{app}}}, {"empty-app-list", "AppList", appList[domain.App]{Items: []domain.App{}}}, - {"directory-entry", "DirectoryEntry", domain.EntryOf(app, false)}, {"empty-entry-collections", "DirectoryEntry", domain.EntryOf(domain.App{ID: "empty", Group: app.Group}, false)}, + {"directory-entry", "DirectoryEntry", domain.EntryOf(app, false)}, {"empty-entry-collections", "DirectoryEntry", domain.EntryOf(domain.App{ID: "empty", Group: app.Group, Contribution: domain.ContributionPolicy{Scope: "group"}}, false)}, {"directory-list", "DirectoryEntryList", appList[domain.DirectoryEntry]{Items: []domain.DirectoryEntry{domain.EntryOf(app, false)}}}, {"empty-directory-list", "DirectoryEntryList", appList[domain.DirectoryEntry]{Items: []domain.DirectoryEntry{}}}, {"groups", "GroupList", directory.GroupList{Items: []directory.Group{group}}}, {"empty-groups", "GroupList", directory.GroupList{Items: []directory.Group{}}}, @@ -59,8 +61,8 @@ func consoleWriterFixtures(t *testing.T) []writerFixture { {"empty-members", "MembershipList", directory.MembershipList{Items: []directory.Membership{}}}, {"directory-users", "DirectoryUserList", map[string]any{"items": []any{map[string]string{"id": "realm-person", "email": "person@example.test", "displayName": "Person"}}}}, {"migration", "MigrationResult", migrationResponse(directory.ImportResult{})}, - {"me", "Me", meResponse{Person: person, ProjectID: "project", EffectiveGroupIDs: []string{}, ManagedGroupIDs: []string{}, Migration: store.MigrationStatus{}}}, - {"me-degraded", "Me", meResponse{Person: person, ProjectID: "project", EffectiveGroupIDs: []string{}, ManagedGroupIDs: []string{}, PlatformUnavailable: true, NotMember: true, TeamSlug: "team"}}, + {"me", "Me", meResponse{Person: person, ProjectID: "project", EffectiveGroupIDs: []string{}, ManagedGroupIDs: []string{}, Migration: store.MigrationStatus{}, View: "maker"}}, + {"me-degraded", "Me", meResponse{Person: person, ProjectID: "project", EffectiveGroupIDs: []string{}, ManagedGroupIDs: []string{}, PlatformUnavailable: true, NotMember: true, TeamSlug: "team", View: "user"}}, {"config", "Config", map[string]any{"projectId": "project", "dashboardUrl": "https://dashboard.example.test/dashboard/settings", "newAppConversation": false}}, {"comment", "Comment", comment}, {"comments", "CommentList", []domain.AppComment{comment}}, {"empty-comments", "CommentList", []domain.AppComment{}}, {"screenshot", "Screenshot", shot}, {"screenshots", "ScreenshotList", []domain.Screenshot{shot}}, {"empty-screenshots", "ScreenshotList", []domain.Screenshot{}}, @@ -79,6 +81,10 @@ func consoleWriterFixtures(t *testing.T) []writerFixture { {"resolved-path", "Resolved", resolution{Kind: "app", ID: app.ID, CurrentPath: "/group/app"}}, {"settings", "Settings", platform.Settings{ProjectID: "project", DefaultTemplateID: "nextjs-postgres"}}, } + fixtures = append(fixtures, + writerFixture{"inbox", "Inbox", inboxResponse{Items: []domain.InboxItem{{Kind: "feedback", App: domain.InboxApp{ID: app.ID, Path: app.Path(), DisplayName: app.DisplayName, Icon: app.Icon}, Count: 2, Since: at}}}}, + writerFixture{"empty-inbox", "Inbox", inboxResponse{Items: []domain.InboxItem{}}}, + ) tools, status, err := (&API{}).toolsForApp(nil, domain.App{}) require.NoError(t, err) require.Equal(t, 200, status) diff --git a/cmd/server/internal/buildsession/console_stacks.go b/cmd/server/internal/buildsession/console_stacks.go new file mode 100644 index 0000000..c2dd659 --- /dev/null +++ b/cmd/server/internal/buildsession/console_stacks.go @@ -0,0 +1,32 @@ +package buildsession + +import ( + "context" + "errors" + "net/http" +) + +// ConsoleStack is the Platform ownership evidence used by the console proxy. +// The public SDK stack reader currently omits databaseComponentId. +type ConsoleStack struct { + ID string `json:"id"` + ApplicationID string `json:"applicationId"` + BranchID string `json:"branchId"` + WebComponentID string `json:"webComponentId"` + DatabaseComponentID string `json:"databaseComponentId"` +} + +func (c *Client) ConsoleStack(ctx context.Context, bearer, id string) (ConsoleStack, error) { + var stack ConsoleStack + path, err := resourcePath(c.prefix+"/application-stacks", id) + if err != nil { + return stack, err + } + if _, err := c.json(ctx, bearer, http.MethodGet, path, "", "", nil, &stack); err != nil { + return stack, err + } + if stack.ID != id { + return stack, errors.New("platform stack ownership response has an unexpected stack ID") + } + return stack, nil +} diff --git a/cmd/server/internal/domain/inbox.go b/cmd/server/internal/domain/inbox.go new file mode 100644 index 0000000..8246d70 --- /dev/null +++ b/cmd/server/internal/domain/inbox.go @@ -0,0 +1,79 @@ +package domain + +import ( + "cmp" + "slices" + "time" +) + +type InboxApp struct { + ID string `json:"id"` + Path string `json:"path"` + DisplayName string `json:"displayName"` + Icon string `json:"icon"` +} + +type InboxItem struct { + Kind string `json:"kind"` + App InboxApp `json:"app"` + Count int `json:"count"` + Since time.Time `json:"since"` +} + +// InboxActivity carries only the evidence needed to count an item, never its body. +type InboxActivity struct { + AppID, Kind, AuthorID string + Status RequestStatus + At, LastSeenAt time.Time +} + +func DeriveInbox(actor Actor, apps []App, activity []InboxActivity) []InboxItem { + maintained := make(map[string]InboxApp, len(apps)) + for _, app := range apps { + if Capabilities(actor, app).Maintain { + maintained[app.ID] = InboxApp{ID: app.ID, Path: app.Path(), DisplayName: app.DisplayName, Icon: app.Icon} + } + } + type key struct{ app, kind string } + indices := make(map[key]int) + items := []InboxItem{} + for _, event := range activity { + app, ok := maintained[event.AppID] + if !ok { + continue + } + switch event.Kind { + case "accessRequest": + if event.Status != RequestPending { + continue + } + case "feedback": + if event.AuthorID == actor.PersonID || !event.At.After(event.LastSeenAt) { + continue + } + default: + continue + } + k := key{event.AppID, event.Kind} + i, exists := indices[k] + if !exists { + i = len(items) + indices[k] = i + items = append(items, InboxItem{Kind: event.Kind, App: app, Since: event.At}) + } + items[i].Count++ + if event.At.After(items[i].Since) { + items[i].Since = event.At + } + } + slices.SortFunc(items, func(a, b InboxItem) int { + if order := cmp.Compare(a.Kind, b.Kind); order != 0 { + return order + } + if order := b.Since.Compare(a.Since); order != 0 { + return order + } + return cmp.Compare(a.App.ID, b.App.ID) + }) + return items +} diff --git a/cmd/server/internal/domain/inbox_test.go b/cmd/server/internal/domain/inbox_test.go new file mode 100644 index 0000000..4b1aee4 --- /dev/null +++ b/cmd/server/internal/domain/inbox_test.go @@ -0,0 +1,45 @@ +package domain + +import ( + "testing" + "time" +) + +func TestDeriveInbox(t *testing.T) { + at := time.Date(2026, 11, 19, 0, 0, 0, 0, time.UTC) + actor := Actor{PersonID: "owner"} + apps := []App{ + {ID: "first", Slug: "first", Group: AppGroup{Path: "sales"}, Owners: []Person{{ID: "owner"}}}, + {ID: "second", Owners: []Person{{ID: "owner"}}}, + {ID: "zero", Owners: []Person{{ID: "owner"}}}, + {ID: "not-maintained"}, + } + events := []InboxActivity{ + {AppID: "first", Kind: "accessRequest", Status: RequestPending, At: at}, + {AppID: "first", Kind: "accessRequest", Status: RequestPending, At: at.Add(time.Minute)}, + {AppID: "first", Kind: "accessRequest", Status: RequestApproved, At: at.Add(time.Hour)}, + {AppID: "second", Kind: "accessRequest", Status: RequestPending, At: at.Add(2 * time.Minute)}, + {AppID: "first", Kind: "feedback", AuthorID: "other", At: at.Add(time.Hour), LastSeenAt: at}, + {AppID: "first", Kind: "feedback", AuthorID: "owner", At: at.Add(2 * time.Hour)}, + {AppID: "first", Kind: "feedback", AuthorID: "other", At: at, LastSeenAt: at}, + {AppID: "first", Kind: "feedback", AuthorID: "other", At: at.Add(-time.Hour), LastSeenAt: at}, + {AppID: "second", Kind: "feedback", AuthorID: "other", At: at.Add(3 * time.Hour)}, + {AppID: "not-maintained", Kind: "feedback", AuthorID: "other", At: at}, + } + items := DeriveInbox(actor, apps, events) + if len(items) != 4 { + t.Fatalf("items = %+v", items) + } + for i, want := range []struct{ kind, app string; count int }{{"accessRequest", "second", 1}, {"accessRequest", "first", 2}, {"feedback", "second", 1}, {"feedback", "first", 1}} { + got := items[i] + if got.Kind != want.kind || got.App.ID != want.app || got.Count != want.count { + t.Fatalf("item %d = %+v, want %+v", i, got, want) + } + } + if items[1].App.Path != "sales/first" || !items[1].Since.Equal(at.Add(time.Minute)) || !items[3].Since.Equal(at.Add(time.Hour)) { + t.Fatalf("incorrect app path or latest activity: %+v", items) + } + if empty := DeriveInbox(actor, apps, nil); empty == nil || len(empty) != 0 { + t.Fatalf("empty inbox must be [], got %#v", empty) + } +} diff --git a/cmd/server/internal/domain/model.go b/cmd/server/internal/domain/model.go index 03a6c7f..b9195e3 100644 --- a/cmd/server/internal/domain/model.go +++ b/cmd/server/internal/domain/model.go @@ -87,6 +87,18 @@ type SharePolicy struct { ExtraPersonIDs []string `json:"extraPersonIds"` } +type ContributionPolicy struct { + Scope string `json:"scope"` +} + +type Permissions struct { + Use bool `json:"use"` + Comment bool `json:"comment"` + Propose bool `json:"propose"` + Maintain bool `json:"maintain"` + Data bool `json:"data"` +} + type AppGroup struct { ID string `json:"id"` Path string `json:"path"` @@ -117,6 +129,8 @@ type App struct { StackID *string `json:"stackId"` AppName *string `json:"appName"` Share SharePolicy `json:"share"` + Contribution ContributionPolicy `json:"contribution"` + Permissions Permissions `json:"permissions"` CreatedBy Person `json:"createdBy"` CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` @@ -148,6 +162,8 @@ type DirectoryEntry struct { CreatedAt time.Time `json:"createdAt"` UpdatedAt time.Time `json:"updatedAt"` CanOpen bool `json:"canOpen"` + Contribution ContributionPolicy `json:"contribution"` + Permissions Permissions `json:"permissions"` } func EntryOf(app App, canOpen bool) DirectoryEntry { @@ -170,6 +186,7 @@ func EntryOf(app App, canOpen bool) DirectoryEntry { ID: app.ID, Path: app.Path(), DisplayName: app.DisplayName, Description: app.Description, Icon: app.Icon, Tags: tags, Capabilities: capabilities, Screenshots: screenshots, Group: app.Group, Owners: owners, AppName: app.AppName, StackID: app.StackID, CreatedAt: app.CreatedAt, UpdatedAt: app.UpdatedAt, CanOpen: canOpen, + Contribution: app.Contribution, Permissions: app.Permissions, } } @@ -380,6 +397,19 @@ func (a Actor) EditApp(app App) bool { return a.IsConsoleAdmin || app.OwnedBy(a.PersonID) || a.ManageGroup(app.Group.ID) } +// Capabilities is the single authority for a caller's relationship to an app. +// Data stays separate even while its interim policy equals maintain. +func Capabilities(actor Actor, app App) Permissions { + maintain := actor.EditApp(app) + use := maintain || actor.Visible(app) + inScope := app.Contribution.Scope == "company" || + (app.Contribution.Scope == "group" && actor.GroupRoles[app.Group.ID] != "") + return Permissions{ + Use: use, Comment: use, Propose: maintain || (use && actor.CanCreateApps && inScope), + Maintain: maintain, Data: maintain, + } +} + func (a Actor) DeleteComment(app App, c AppComment) bool { return c.Author.ID == a.PersonID || a.EditApp(app) } @@ -421,7 +451,11 @@ func NewActor(personID string, roles Roles, effectiveGroupIDs []string, groups [ } } } - return Actor{PersonID: personID, Roles: roles, GroupRoles: map[string]string{}, ShareGroupIDs: share} + rolesByGroup := make(map[string]string, len(effectiveGroupIDs)) + for _, id := range effectiveGroupIDs { + rolesByGroup[id] = "member" + } + return Actor{PersonID: personID, Roles: roles, GroupRoles: rolesByGroup, ShareGroupIDs: share} } var slugPattern = regexp.MustCompile(`^[a-z0-9]([a-z0-9-]*[a-z0-9])?$`) diff --git a/cmd/server/internal/domain/permissions_test.go b/cmd/server/internal/domain/permissions_test.go new file mode 100644 index 0000000..95a31c3 --- /dev/null +++ b/cmd/server/internal/domain/permissions_test.go @@ -0,0 +1,50 @@ +package domain + +import "testing" + +func TestCapabilities(t *testing.T) { + all := Permissions{Use: true, Comment: true, Propose: true, Maintain: true, Data: true} + use := Permissions{Use: true, Comment: true} + propose := Permissions{Use: true, Comment: true, Propose: true} + for _, tc := range []struct { + name, person, role, contribution, share string + create, admin, invited bool + want Permissions + }{ + {"owner off private", "owner", "", "off", "private", false, false, false, all}, + {"inherited manager off private", "manager", "manager", "off", "private", false, false, false, all}, + {"console admin off private", "admin", "", "off", "private", false, true, false, all}, + {"member group", "member", "member", "group", "group", true, false, false, propose}, + {"member off", "member", "member", "off", "group", true, false, false, use}, + {"member company", "member", "member", "company", "group", true, false, false, propose}, + {"member cannot build", "member", "member", "company", "group", false, false, false, use}, + {"nonmember company", "other", "", "company", "company", true, false, false, propose}, + {"nonmember group", "other", "", "group", "company", true, false, false, use}, + {"cannot use", "other", "", "company", "private", true, false, false, Permissions{}}, + {"invited outside group", "other", "", "group", "private", true, false, true, use}, + {"invited company", "other", "", "company", "private", true, false, true, propose}, + {"unknown scope", "member", "member", "future", "group", true, false, false, use}, + } { + t.Run(tc.name, func(t *testing.T) { + actor := Actor{PersonID: tc.person, Roles: Roles{CanCreateApps: tc.create, IsConsoleAdmin: tc.admin}, GroupRoles: map[string]string{"child": tc.role}} + if tc.role != "" { + actor.ShareGroupIDs = []string{"child"} + } + app := App{Group: AppGroup{ID: "child"}, Owners: []Person{{ID: "owner"}}, Share: SharePolicy{Scope: tc.share, GroupIDs: []string{"child"}}, Contribution: ContributionPolicy{Scope: tc.contribution}} + if tc.invited { + app.Share.ExtraPersonIDs = []string{tc.person} + } + if got := Capabilities(actor, app); got != tc.want { + t.Fatalf("Capabilities() = %+v, want %+v", got, tc.want) + } + }) + } +} + +func TestCapabilitiesEffectiveMembership(t *testing.T) { + actor := NewActor("person", Roles{CanCreateApps: true}, []string{"parent", "child"}, []Group{{ID: "parent", Path: "parent"}, {ID: "child", Path: "parent/child"}}) + app := App{Group: AppGroup{ID: "child"}, Share: SharePolicy{Scope: "group", GroupIDs: []string{"child"}}, Contribution: ContributionPolicy{Scope: "group"}} + if !Capabilities(actor, app).Propose { + t.Fatal("effective inherited membership must permit proposals") + } +} diff --git a/cmd/server/internal/store/apps.go b/cmd/server/internal/store/apps.go index 43a2813..079905a 100644 --- a/cmd/server/internal/store/apps.go +++ b/cmd/server/internal/store/apps.go @@ -18,7 +18,7 @@ const visibleSQL = `$2 OR a.share_scope IN ('company','public') OR $1=ANY(a.shar const appSelect = `SELECT a.id,a.slug,a.display_name,a.description,a.icon,a.tags,a.guide,a.capabilities,a.stack_id,a.app_name, a.share_scope,a.share_group_ids,a.share_extra_person_ids,a.created_at,a.updated_at, - a.group_id,a.created_by, + a.group_id,a.created_by,a.contribution_scope, COALESCE((SELECT jsonb_agg(jsonb_build_object('id',o.person_id) ORDER BY o.person_id) FROM app_owners o WHERE o.app_id=a.id),'[]'::jsonb), COALESCE((SELECT jsonb_agg(jsonb_build_object('id',s.id,'caption',s.caption,'width',s.width,'height',s.height) ORDER BY s.position) @@ -32,7 +32,7 @@ func scanApp(row scanner) (domain.App, error) { var owners, screenshots []byte err := row.Scan(&a.ID, &a.Slug, &a.DisplayName, &a.Description, &a.Icon, pq.Array(&a.Tags), &a.Guide, pq.Array(&a.Capabilities), &a.StackID, &a.AppName, &a.Share.Scope, pq.Array(&a.Share.GroupIDs), pq.Array(&a.Share.ExtraPersonIDs), &a.CreatedAt, &a.UpdatedAt, - &a.Group.ID, &a.CreatedBy.ID, &owners, &screenshots) + &a.Group.ID, &a.CreatedBy.ID, &a.Contribution.Scope, &owners, &screenshots) if err == nil { err = json.Unmarshal(owners, &a.Owners) } @@ -58,6 +58,33 @@ func (t *Tx) App(id string) (domain.App, error) { return apps[0], err } +func (t *Tx) AppByStackID(stackID string) (domain.App, error) { + var id string + if err := t.SQL.QueryRowContext(t.Context, `SELECT id FROM apps WHERE stack_id=$1`, stackID).Scan(&id); err != nil { + return domain.App{}, err + } + return t.App(id) +} + +func (t *Tx) OwnsAnyApp(personID string) (bool, error) { + var owns bool + err := t.SQL.QueryRowContext(t.Context, `SELECT EXISTS(SELECT 1 FROM app_owners WHERE person_id=$1)`, personID).Scan(&owns) + return owns, err +} + +func (t *Tx) MaintainedApps(actor domain.Actor) ([]domain.App, error) { + managed := make([]string, 0, len(actor.GroupRoles)) + for id, role := range actor.GroupRoles { + if role == "manager" { + managed = append(managed, id) + } + } + apps, err := collectApps(t.SQL.QueryContext(t.Context, appSelect+` WHERE $2 OR a.group_id=ANY($3::text[]) + OR EXISTS(SELECT 1 FROM app_owners o WHERE o.app_id=a.id AND o.person_id=$1) + ORDER BY a.id`, actor.PersonID, actor.IsConsoleAdmin, pq.Array(managed))) + return t.filterApps(apps, err, "", "") +} + func (t *Tx) AppByPath(path string) (domain.App, error) { groupPath, slug, ok := strings.Cut(path, "/") if i := strings.LastIndex(path, "/"); i >= 0 { @@ -174,9 +201,12 @@ func (t *Tx) SuggestAppName(base string) (string, error) { } func (t *Tx) CreateApp(a domain.App) error { - if err := t.Exec(`INSERT INTO apps(id,group_id,slug,display_name,description,icon,tags,app_name,share_scope,share_group_ids,share_extra_person_ids,created_by,guide,capabilities) - VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,COALESCE($14::text[],'{}'))`, a.ID, a.Group.ID, a.Slug, a.DisplayName, a.Description, a.Icon, pq.Array(a.Tags), a.AppName, - a.Share.Scope, pq.Array(a.Share.GroupIDs), pq.Array(a.Share.ExtraPersonIDs), a.CreatedBy.ID, a.Guide, pq.Array(a.Capabilities)); err != nil { + if a.Contribution.Scope == "" { + a.Contribution.Scope = "group" + } + if err := t.Exec(`INSERT INTO apps(id,group_id,slug,display_name,description,icon,tags,app_name,share_scope,share_group_ids,share_extra_person_ids,created_by,guide,capabilities,contribution_scope) + VALUES($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11,$12,$13,COALESCE($14::text[],'{}'),$15)`, a.ID, a.Group.ID, a.Slug, a.DisplayName, a.Description, a.Icon, pq.Array(a.Tags), a.AppName, + a.Share.Scope, pq.Array(a.Share.GroupIDs), pq.Array(a.Share.ExtraPersonIDs), a.CreatedBy.ID, a.Guide, pq.Array(a.Capabilities), a.Contribution.Scope); err != nil { return err } return t.SaveOwners(a.ID, []string{a.CreatedBy.ID}) @@ -189,8 +219,8 @@ func (t *Tx) SaveApp(old, a domain.App) error { } } return t.Exec(`UPDATE apps SET group_id=$2,slug=$3,display_name=$4,description=$5,icon=$6,tags=$7, - share_scope=$8,share_group_ids=$9,share_extra_person_ids=$10,guide=$11,capabilities=COALESCE($12::text[],'{}'),updated_at=now() WHERE id=$1`, - a.ID, a.Group.ID, a.Slug, a.DisplayName, a.Description, a.Icon, pq.Array(a.Tags), a.Share.Scope, pq.Array(a.Share.GroupIDs), pq.Array(a.Share.ExtraPersonIDs), a.Guide, pq.Array(a.Capabilities)) + share_scope=$8,share_group_ids=$9,share_extra_person_ids=$10,guide=$11,capabilities=COALESCE($12::text[],'{}'),contribution_scope=$13,updated_at=now() WHERE id=$1`, + a.ID, a.Group.ID, a.Slug, a.DisplayName, a.Description, a.Icon, pq.Array(a.Tags), a.Share.Scope, pq.Array(a.Share.GroupIDs), pq.Array(a.Share.ExtraPersonIDs), a.Guide, pq.Array(a.Capabilities), a.Contribution.Scope) } func (t *Tx) SaveOwners(appID string, ids []string) error { diff --git a/cmd/server/internal/store/inbox.go b/cmd/server/internal/store/inbox.go new file mode 100644 index 0000000..e27b595 --- /dev/null +++ b/cmd/server/internal/store/inbox.go @@ -0,0 +1,38 @@ +package store + +import ( + "database/sql" + + "github.com/appthrust/builder-console/cmd/server/internal/domain" + "github.com/lib/pq" +) + +func (t *Tx) MarkCommentsSeen(appID, personID string) error { + return t.Exec(`INSERT INTO app_comment_seen(app_id,person_id,last_seen_at) VALUES($1,$2,now()) + ON CONFLICT(app_id,person_id) DO UPDATE SET last_seen_at=EXCLUDED.last_seen_at`, appID, personID) +} + +func (t *Tx) InboxActivity(appIDs []string, personID string) ([]domain.InboxActivity, error) { + rows, err := t.SQL.QueryContext(t.Context, `SELECT r.app_id,'accessRequest',r.requester_id,r.status,r.requested_at,NULL::timestamptz + FROM app_access_requests r WHERE r.app_id=ANY($1::text[]) AND r.status='pending' + UNION ALL + SELECT c.app_id,'feedback',c.author_id,'',c.created_at,s.last_seen_at + FROM app_comments c LEFT JOIN app_comment_seen s ON s.app_id=c.app_id AND s.person_id=$2 + WHERE c.app_id=ANY($1::text[]) AND c.deleted_at IS NULL AND c.author_id<>$2 + AND (s.last_seen_at IS NULL OR c.created_at>s.last_seen_at)`, pq.Array(appIDs), personID) + if err != nil { + return nil, err + } + defer rows.Close() + var result []domain.InboxActivity + for rows.Next() { + var event domain.InboxActivity + var seen sql.NullTime + if err := rows.Scan(&event.AppID, &event.Kind, &event.AuthorID, &event.Status, &event.At, &seen); err != nil { + return nil, err + } + event.LastSeenAt = seen.Time + result = append(result, event) + } + return result, rows.Err() +} diff --git a/cmd/server/internal/store/migrations/010_contribution.sql b/cmd/server/internal/store/migrations/010_contribution.sql new file mode 100644 index 0000000..5fb3259 --- /dev/null +++ b/cmd/server/internal/store/migrations/010_contribution.sql @@ -0,0 +1,10 @@ +ALTER TABLE apps ADD COLUMN contribution_scope text NOT NULL DEFAULT 'group' + CHECK (contribution_scope IN ('off', 'group', 'company')); + +-- Directory person IDs are opaque; no reference to the retired local people table. +CREATE TABLE app_comment_seen ( + app_id text NOT NULL REFERENCES apps(id) ON DELETE CASCADE, + person_id text NOT NULL, + last_seen_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (app_id, person_id) +); diff --git a/cmd/server/server.go b/cmd/server/server.go index c5deb49..9d8c642 100644 --- a/cmd/server/server.go +++ b/cmd/server/server.go @@ -98,7 +98,7 @@ func newHandler(staticDir, upstreamURL, projectID string, console http.Handler, mux.Handle("/authz", console) mux.Handle("/authz/", console) mux.Handle("GET /launcher/entries", console) - platformProxy := api.WithDraftReviewers(proxy, projectID, func() *api.API { + platformProxy := api.WithConsoleAuthority(proxy, projectID, func() *api.API { if current, ok := console.(interface{ CurrentAPI() *api.API }); ok { return current.CurrentAPI() } diff --git a/cmd/server/server_test.go b/cmd/server/server_test.go index 82df5d6..baa8917 100644 --- a/cmd/server/server_test.go +++ b/cmd/server/server_test.go @@ -17,7 +17,6 @@ import ( "testing" "time" - consolecontract "github.com/appthrust/appserver-go/appserver/contract/console" "github.com/appthrust/appserver-go/appserver/identity" "github.com/appthrust/appserver-go/appserver/pgstore/testutil" platform "github.com/appthrust/appserver-go/appserver/platformclient" @@ -532,7 +531,10 @@ func TestLauncherRejectsInvalidIdentityCA(t *testing.T) { } func TestServedOpenAPIEqualsCommittedContract(t *testing.T) { - document := consolecontract.Document + document, err := os.ReadFile("internal/api/openapi.json") + if err != nil { + t.Fatal(err) + } for _, tc := range []struct { name string authorization bool diff --git a/web/e2e/stories/app-access-request.mock.spec.ts b/web/e2e/stories/app-access-request.mock.spec.ts index 1bec011..e9e6344 100644 --- a/web/e2e/stories/app-access-request.mock.spec.ts +++ b/web/e2e/stories/app-access-request.mock.spec.ts @@ -6,7 +6,9 @@ test('an owner approves a request as a viewer and pending badges disappear @mock const app = seed.apps.keihi await mock.console('caller', { personId: seed.me.id }) await page.goto('/') - await expect(page.getByTestId(badge)).toHaveText('1') + const pending = page.getByRole('list', { name: '対応待ちの一覧', exact: true }) + .getByRole('listitem').filter({ has: page.getByRole('link', { name: `${app.name}: 申請を見る`, exact: true }) }) + await expect(pending).toContainText('利用申請 1 件') await page.goto('/mine') const row = page.getByRole('row').filter({ hasText: app.name }) await expect(row.getByTestId(badge)).toHaveText('1') @@ -39,8 +41,8 @@ test('an owner approves a request as a viewer and pending badges disappear @mock await expect(page.getByRole('row').filter({ hasText: app.name })).toBeVisible() await expect(page.getByTestId(badge)).toHaveCount(0) await page.goto('/') - await expect(page.getByRole('link').filter({ hasText: app.name })).toBeVisible() - await expect(page.getByTestId(badge)).toHaveCount(0) + await expect(page.getByRole('heading', { name: /^使えるアプリ/, level: 2 })).toBeVisible() + await expect(pending).toHaveCount(0) }) test('a non-owner submits an access request and sees the pending view @mock @story', async ({ page, mock }, testInfo) => { diff --git a/web/e2e/stories/app-delete.mock.spec.ts b/web/e2e/stories/app-delete.mock.spec.ts index 8ea5730..c910ab5 100644 --- a/web/e2e/stories/app-delete.mock.spec.ts +++ b/web/e2e/stories/app-delete.mock.spec.ts @@ -11,7 +11,7 @@ test.describe('App delete @app', () => { await page.goto('/mine') await expect(page.getByRole('heading', { level: 1, name: '自分のアプリ', exact: true })).toBeVisible() - await expect(main.getByRole('link', { name: new RegExp(app.name) })).toBeVisible() + await expect(main.getByRole('table').getByRole('link', { name: new RegExp(app.name) })).toBeVisible() await page.goto(groupApps) await expect(page.getByRole('heading', { level: 1, name: seed.groups.teamA.name, exact: true })).toBeVisible() await expect(main.getByRole('link', { name: new RegExp(app.name) })).toBeVisible() @@ -59,7 +59,7 @@ test.describe('App delete @app', () => { await page.goto('/mine') await expect(page.getByRole('heading', { level: 1, name: '自分のアプリ', exact: true })).toBeVisible() - await expect(main.getByRole('link', { name: new RegExp(seed.apps.mitsumori.name) })).toBeVisible() + await expect(main.getByRole('table').getByRole('link', { name: new RegExp(seed.apps.mitsumori.name) })).toBeVisible() await expect(main.getByRole('link', { name: new RegExp(app.name) })).toHaveCount(0) await withExpectedFailures([{ method: 'GET', path: '/api/console/resolve', status: 404, count: 1, reason: 'the deleted app\'s URL resolves to nothing' }], async () => { diff --git a/web/e2e/stories/directory-cutover.mock.spec.ts b/web/e2e/stories/directory-cutover.mock.spec.ts index 7b49f45..0bbf2b7 100644 --- a/web/e2e/stories/directory-cutover.mock.spec.ts +++ b/web/e2e/stories/directory-cutover.mock.spec.ts @@ -57,13 +57,13 @@ test.describe('Directory cutover @directory', () => { await page.goto('/-/admin/platform') const main = page.getByRole('main') const banner = main.getByRole('status').filter({ hasText: '人とグループをディレクトリへ移す' }) - await expect(banner).toContainText('人 4 人・グループ 6 件・所属 5 件') + await expect(banner).toContainText('人 5 人・グループ 6 件・所属 6 件') await banner.getByRole('button', { name: 'ディレクトリへ移す', exact: true }).click() const dialog = page.getByRole('dialog', { name: '人とグループをディレクトリへ移しますか?', exact: true }) const migrate = await captureWrite(page, 'POST', '/api/console/admin/directory-migrate', () => dialog.getByRole('button', { name: '移す', exact: true }).click()) expect(migrate.request.method()).toBe('POST') const done = main.getByRole('status').filter({ hasText: 'ディレクトリへ移しました' }) - await expect(done).toContainText('移した数: 人 4 人・グループ 6 件・所属 5 件') + await expect(done).toContainText('移した数: 人 5 人・グループ 6 件・所属 6 件') await expect(main.getByRole('button', { name: 'ディレクトリへ移す', exact: true })).toHaveCount(0) await page.reload() diff --git a/web/e2e/stories/discover-navigation.mock.spec.ts b/web/e2e/stories/discover-navigation.mock.spec.ts index 1d1c0c2..d5f95b4 100644 --- a/web/e2e/stories/discover-navigation.mock.spec.ts +++ b/web/e2e/stories/discover-navigation.mock.spec.ts @@ -8,22 +8,38 @@ test.describe('Discover navigation @discover', () => { const nav = page.getByRole('navigation', { name: 'メインメニュー' }) const main = page.getByRole('main') + // Home: every usable app as a card under 「使えるアプリ」, narrowed by membership chips (the draft is not usable yet). + const details = (name: string) => `${name}をくわしく見る` await page.goto('/') - await expect(page.getByRole('heading', { name: `${seed.groups.teamA.name} のアプリ`, exact: true })).toBeVisible() + await expect(main.getByRole('heading', { name: /^使えるアプリ/, level: 2 })).toBeVisible() + const usable = main.getByRole('list', { name: '使えるアプリ', exact: true }) + await expect(usable.getByRole('listitem')).toHaveCount(6) for (const name of [seed.apps.mitsumori.name, seed.apps.nippo.name, seed.apps.keihi.name, '引っ越し見積', seed.apps.kintai.name, '会議室予約']) { - await expect(main.getByRole('link', { name: new RegExp(`^${name}`) })).toBeVisible() + await expect(usable.getByRole('link', { name: details(name), exact: true })).toBeVisible() } + await expect(usable.getByRole('listitem').filter({ hasText: draftName })).toHaveCount(0) + const chips = main.getByRole('group', { name: '使えるアプリの絞り込み', exact: true }) + await chips.getByRole('button', { name: seed.groups.teamA.name, exact: true }).click() + await expect(chips.getByRole('button', { name: seed.groups.teamA.name, exact: true })).toHaveAttribute('aria-pressed', 'true') + const teamCards = main.getByRole('list', { name: `使えるアプリ: ${seed.groups.teamA.name}`, exact: true }) + await expect(teamCards.getByRole('listitem')).toHaveCount(3) + for (const app of [seed.apps.mitsumori, seed.apps.nippo, seed.apps.keihi]) { + await expect(teamCards.getByRole('link', { name: details(app.name), exact: true })).toBeVisible() + } + await chips.getByRole('button', { name: 'すべて', exact: true }).click() + await expect(usable.getByRole('listitem')).toHaveCount(6) + await page.getByRole('searchbox', { name: 'アプリを探す', exact: true }).fill('見積') await page.getByRole('button', { name: '探す', exact: true }).click() await expect(page).toHaveURL((url) => url.pathname === '/' && url.searchParams.get('q') === '見積') - const results = page.getByRole('table', { name: '「見積」の検索結果', exact: true }) - await expect(results.getByRole('row')).toHaveCount(3) - await expect(results.getByRole('link', { name: /^見積作成/ })).toBeVisible() - await expect(results.getByRole('link', { name: /^引っ越し見積/ })).toBeVisible() - await expect(results.getByRole('link', { name: /^経費精算/ })).toHaveCount(0) + const results = main.getByRole('list', { name: '「見積」の検索結果', exact: true }) + await expect(results.getByRole('listitem')).toHaveCount(2) + await expect(results.getByRole('link', { name: details('見積作成'), exact: true })).toBeVisible() + await expect(results.getByRole('link', { name: details('引っ越し見積'), exact: true })).toBeVisible() + await expect(results.getByRole('link', { name: details('経費精算'), exact: true })).toHaveCount(0) await page.reload() await expect(page.getByRole('searchbox', { name: 'アプリを探す', exact: true })).toHaveValue('見積') - await expect(results.getByRole('row')).toHaveCount(3) + await expect(results.getByRole('listitem')).toHaveCount(2) // 自分のアプリ lists apps that exist; the half-made wizard app is under 作りかけ. await nav.getByRole('link', { name: '自分のアプリ', exact: true }).click() @@ -72,13 +88,27 @@ test.describe('Discover navigation @discover', () => { await expect(soumu.getByRole('link', { name: /^勤怠申請/ })).toBeVisible() await expect(soumu.getByRole('link', { name: /^会議室予約/ })).toBeVisible() + // Directory → group → app → back to the group. + await soumu.getByRole('link', { name: seed.groups.soumu.name, exact: true }).click() + await expect(page).toHaveURL(`/${seed.groups.soumu.path}`) + await expect(main.getByRole('heading', { name: seed.groups.soumu.name, exact: true, level: 1 })).toBeVisible() + await main.getByRole('link', { name: seed.apps.kintai.name, exact: true }).click() + await expect(page).toHaveURL(`/${seed.apps.kintai.groupPath}/${seed.apps.kintai.slug}`) + await expect(main.getByRole('heading', { name: seed.apps.kintai.name, exact: true, level: 1 })).toBeVisible() + await page.goBack() + await expect(page).toHaveURL(`/${seed.groups.soumu.path}`) + await expect(main.getByRole('heading', { name: seed.groups.soumu.name, exact: true, level: 1 })).toBeVisible() + // Arriving at a group page reveals its ancestors even after manual collapse. await nav.getByRole('button', { name: `${seed.groups.salesEast.name} を閉じる`, exact: true }).click() await nav.getByRole('button', { name: `${seed.groups.sales.name} を閉じる`, exact: true }).click() await expect(nav.getByRole('link', { name: seed.groups.teamA.name, exact: true })).not.toBeVisible() - await nav.getByRole('link', { name: 'ホーム', exact: true }).click() - await page.getByRole('region', { name: `${seed.groups.teamA.name} のアプリ`, exact: true }) - .getByRole('link', { name: 'すべて見る →', exact: true }).click() + // The maker's home link carries the inbox count in its name (「ホーム(あなたの対応待ち N 件)」). + await nav.getByRole('link', { name: /^ホーム/ }).click() + await expect(page).toHaveURL('/') + await main.getByRole('list', { name: '使えるアプリ', exact: true }).getByRole('link', { name: details(seed.apps.mitsumori.name), exact: true }).click() + await expect(main.getByRole('heading', { name: seed.apps.mitsumori.name, exact: true, level: 1 })).toBeVisible() + await main.getByRole('link', { name: `${seed.groups.teamA.name} のアプリ`, exact: true }).click() await expect(page).toHaveURL(`/${seed.groups.teamA.path}`) await expect(main.getByRole('heading', { name: seed.groups.teamA.name, exact: true, level: 1 })).toBeVisible() await page.getByRole('navigation', { name: 'グループのページ', exact: true }).getByRole('link', { name: 'アプリ', exact: true }).click() diff --git a/web/src/api/console.test.ts b/web/src/api/console.test.ts index 5467730..a2a4404 100644 --- a/web/src/api/console.test.ts +++ b/web/src/api/console.test.ts @@ -76,6 +76,14 @@ describe('Console gateway transport', () => { expect(calls[1]).toMatchObject({ input: '/api/console/apps/x', init: { method: 'DELETE' } }) }) + test('comment seen writes survive navigation without keeping other requests alive', async () => { + const { api, calls } = recorder([new Response(null, { status: 204 }), new Response(null, { status: 204 })]) + await api(contracts.markCommentsSeen, 'a-keihi') + await api(contracts.removeComment, { appId: 'a-keihi', commentId: 'comment' }) + expect(calls[0]).toMatchObject({ input: '/api/console/apps/a-keihi/comments/seen', init: { method: 'POST', keepalive: true } }) + expect(calls[1].init.keepalive).toBeUndefined() + }) + test('surfaces the contract error code', async () => { const { api } = recorder([Response.json({ error: 'already_bound', message: 'already bound' }, { status: 409 })]) const error = await api(contracts.bindApp, { appId: 'a', stackId: 's', appName: 'a' }).catch((caught: unknown) => caught) diff --git a/web/src/api/console.ts b/web/src/api/console.ts index 8c4cec3..de762da 100644 --- a/web/src/api/console.ts +++ b/web/src/api/console.ts @@ -69,6 +69,8 @@ export interface ConsoleRequest { /** JSON body; a `FormData` body is sent as multipart (the browser sets the boundary). */ body?: unknown cache?: RequestCache + /** Small background writes that must finish even if the page navigates away. */ + keepalive?: boolean /** Request preconditions (`Idempotency-Key`, `If-Match`); never logged. */ headers?: Readonly> } @@ -104,7 +106,7 @@ async function readBody(response: Response): Promise { export function createConsoleTransport(fetcher: Fetcher = (input, init) => fetch(input, init)): ConsoleTransport { return { - async send({ method, path, body, cache, headers }) { + async send({ method, path, body, cache, headers, keepalive }) { assertSessionActive() const read = method === 'GET' const form = body instanceof FormData @@ -119,6 +121,7 @@ export function createConsoleTransport(fetcher: Fetcher = (input, init) => fetch redirect: 'manual', signal: read ? AbortSignal.timeout(READ_TIMEOUT_MS) : undefined, ...(cache ? { cache } : {}), + ...(keepalive ? { keepalive } : {}), }) } catch { // Network failure or read timeout: nothing answered (status 0). diff --git a/web/src/api/contracts/console/bootstrap.test.ts b/web/src/api/contracts/console/bootstrap.test.ts index 2e6db33..7ce326c 100644 --- a/web/src/api/contracts/console/bootstrap.test.ts +++ b/web/src/api/contracts/console/bootstrap.test.ts @@ -7,12 +7,13 @@ import { assertWireContractCases } from '../../testing/wire-contract-cases' import { configContract } from './config' import { groupsContract } from './groups' import { meContract } from './me' +import type { ConsoleView } from '../../../model/contracts/console' const SECRET = 'SENTINEL-bootstrap-9d1e' const person = { id: 'p-1', subject: 'sub-1', pending: false, email: 'yamada@example.test', displayName: '山田', avatarVersion: null } const me = { person, isConsoleAdmin: false, canCreateApps: true, effectiveGroupIds: ['g-1'], managedGroupIds: [], projectId: 'commerce', - directoryPublicURL: 'https://directory.example.test', migration: { pending: false, people: 0, groups: 0, memberships: 0 }, + directoryPublicURL: 'https://directory.example.test', migration: { pending: false, people: 0, groups: 0, memberships: 0 }, view: 'user' as ConsoleView, } const group = { id: 'g-1', parentId: null, name: '営業', slug: 'sales', path: 'sales', description: '', about: '', aboutUpdatedBy: person, diff --git a/web/src/api/contracts/console/comments.ts b/web/src/api/contracts/console/comments.ts index f8ff1f7..8000178 100644 --- a/web/src/api/contracts/console/comments.ts +++ b/web/src/api/contracts/console/comments.ts @@ -31,3 +31,9 @@ export const removeCommentContract = consoleEmptyContract({ path: `${appComments(appId)}/${encodeURIComponent(commentId)}`, }), }) + +/** Maintainers only: everything in the thread so far counts as read for the caller's inbox. */ +export const markCommentsSeenContract = consoleEmptyContract({ + ...operations.markCommentsSeen, + request: (appId: string) => ({ method: 'POST', path: `${appComments(appId)}/seen`, keepalive: true }), +}) diff --git a/web/src/api/contracts/console/field-policies.test.ts b/web/src/api/contracts/console/field-policies.test.ts index beccd48..2bb48a3 100644 --- a/web/src/api/contracts/console/field-policies.test.ts +++ b/web/src/api/contracts/console/field-policies.test.ts @@ -44,6 +44,8 @@ function optionalSample(schema: Schema): unknown { if (schema.anyOf) return optionalSample(schema.anyOf.find((branch) => branch.type !== 'null')!) if (schema.type === 'boolean') return true if (schema.type === 'number' || schema.type === 'integer') return 1 + // An optional object observation (App.permissions) is sampled with every required field present. + if (schema.type === 'object') return Object.fromEntries((schema.required ?? []).map((key) => [key, optionalSample(schema.properties![key]!)])) return 'https://optional.example.test/' } function changed(root: unknown, path: (string | number)[], key: string, value: unknown, omit = false): unknown { @@ -81,8 +83,10 @@ for (const [name, operation] of Object.entries(operations)) { const safePath = `/${[...path, key].map((part) => typeof part === 'number' ? '*' : part).join('/')}` const required = schema.required?.includes(key) ?? false const absent = changed(fixture.body, path, key, undefined, true) - // Config deliberately drops an unvouched optional navigation URL. - const nullAccepted = acceptsNull(child) || (operation.schema === 'Config' && key === 'dashboardUrl') + // Config deliberately drops an unvouched optional navigation URL; an app's + // permissions fail closed to no grant (tested below) instead of failing the app. + const failsClosed = key === 'permissions' && (operation.schema === 'App' || operation.schema === 'AppList' || operation.schema === 'DirectoryEntry' || operation.schema === 'DirectoryEntryList' || operation.schema === 'ApproveAccessRequest') + const nullAccepted = acceptsNull(child) || (operation.schema === 'Config' && key === 'dashboardUrl') || failsClosed assertWireContractCases(contract, [ { name: `${fixture.name}: absent`, variant: 'absent', path: safePath, wire: absent, expect: { accept: !required } }, { name: `${fixture.name}: null`, variant: 'null', path: safePath, wire: changed(fixture.body, path, key, null), expect: { accept: nullAccepted } }, @@ -100,7 +104,7 @@ for (const [name, operation] of Object.entries(operations)) { { name: 'broken list element', variant: 'unknown', path: safePath, wire: changed(fixture.body, path, key, [null]), expect: { accept: false } }, ]) } - if (Object.hasOwn(object, key)) visit(child, object[key], [...path, key]) + if (Object.hasOwn(object, key) && !failsClosed) visit(child, object[key], [...path, key]) } } visit(schemaMap[operation.schema]!, fixture.body) @@ -114,3 +118,27 @@ test('unknown membership roles, request states and tool errors cannot become kno assertWireContractCases(consoleContracts.myAccessRequest, [{ name: 'new state', variant: 'unknown', path: '/state', wire: { exists: true, appName: 'app', state: SECRET }, expect: { accept: true, check: (value) => { expect(value.exists && value.state).toEqual({ kind: 'unknown' }) } } }]) assertWireContractCases(consoleContracts.tools, [{ name: 'new tool failure', variant: 'unknown', path: '/error', wire: { available: true, tools: [], error: SECRET }, expect: { accept: true, check: (value) => { expect(value.available && value.error).toEqual({ kind: 'unknown' }) } } }]) }) + +test('an app\'s permissions fail closed: absent, null, partial, mistyped or unknown-only sets grant nothing, never the app list', () => { + const none = { use: false, comment: false, propose: false, maintain: false, data: false } + const granted = { use: true, comment: true, propose: false, maintain: false, data: false } + const app = fixtures.find((item) => item.schema === 'App')!.body as Record + const entry = fixtures.find((item) => item.schema === 'DirectoryEntry')!.body as Record + const malformed: [string, unknown][] = [ + ['absent', undefined], ['null', null], ['partial', { use: true, comment: true }], ['mistyped', { ...granted, maintain: 'yes' }], + ['unknown-only', { futureGrant: true }], ['not an object', SECRET], + ] + // The app and its directory entry read permissions the same way; each contract is checked with its own value type. + const failsClosed = (contract: ResponseContract, body: Record) => { + for (const [name, permissions] of malformed) { + const wire = { ...body, permissions } + if (permissions === undefined) delete wire.permissions + assertWireContractCases(contract, [{ name, variant: 'unknown', path: '/permissions', wire, expect: { accept: true, check: (value) => expect(value.permissions).toEqual(none) } }]) + } + assertWireContractCases(contract, [{ name: 'known set with a future grant', variant: 'present', path: '/permissions', wire: { ...body, permissions: { ...granted, futureGrant: true } }, expect: { accept: true, check: (value) => expect(value.permissions).toEqual(granted) } }]) + } + failsClosed(consoleContracts.app, app) + failsClosed(consoleContracts.directoryEntry, entry) + // One app's broken grants never drop the list. + assertWireContractCases(consoleContracts.apps, [{ name: 'list with an unknown-only set', variant: 'unknown', path: '/items/*/permissions', wire: { items: [{ ...app, permissions: { futureGrant: true } }, { ...app, id: 'other', permissions: granted }] }, expect: { accept: true, check: (value) => expect(value.map((item) => item.permissions)).toEqual([none, granted]) } }]) +}) diff --git a/web/src/api/contracts/console/me.ts b/web/src/api/contracts/console/me.ts index f7ace71..2051519 100644 --- a/web/src/api/contracts/console/me.ts +++ b/web/src/api/contracts/console/me.ts @@ -1,6 +1,7 @@ // `GET /api/console/me` (cmd/server/internal/api/groups.go meResponse). The // caller is always a resolved person with a subject; missing roles or group -// lists are failures, never an empty grant. +// lists are failures, never an empty grant. An unknown view reads as `user`: +// the UI may widen it, never the wire. import { z } from 'zod' import { me } from './schema/schemas' import { operations } from './schema/operations' @@ -11,6 +12,7 @@ import { personReader } from './person' const meReader: z.ZodType = me.strip().extend({ person: personReader.and(z.object({ subject: z.string().min(1) })), migration: me.shape.migration.strip(), + view: z.string().transform((value): Me['view'] => (value === 'maker' ? 'maker' : 'user')), }) export const meContract = consoleContract({ diff --git a/web/src/api/contracts/console/mock-wires.test.ts b/web/src/api/contracts/console/mock-wires.test.ts index 27b50e4..52720da 100644 --- a/web/src/api/contracts/console/mock-wires.test.ts +++ b/web/src/api/contracts/console/mock-wires.test.ts @@ -37,6 +37,7 @@ test('the in-memory Console API emits canonical wires for every supported SPA op } try { await call(contracts.me, undefined) + await call(contracts.inbox, undefined) await call(contracts.groups, undefined) await call(contracts.people, { ids: ['p-yamada'] }) await call(contracts.person, 'p-yamada') @@ -58,10 +59,12 @@ test('the in-memory Console API emits canonical wires for every supported SPA op await call(contracts.migrateDirectory, undefined) const app = await call(contracts.createApp, { displayName: 'Wire parity', groupId: 'g-team-a', slug: 'wire-parity', share: { scope: 'private', groupIds: [], extraPersonIds: [] } }) await call(contracts.updateApp, { appId: app.id, input: { description: 'Updated' } }) + await call(contracts.updateApp, { appId: app.id, input: { contribution: { scope: 'off' } } }) await call(contracts.bindApp, { appId: app.id, stackId: 'wire-parity-stack', appName: app.appName! }) await call(contracts.comments, app.id) const comment = await call(contracts.postComment, { appId: app.id, body: 'Wire comment' }) await call(contracts.removeComment, { appId: app.id, commentId: comment.id }) + await call(contracts.markCommentsSeen, app.id) const screenshot = await call(contracts.uploadScreenshot, { appId: app.id, file: new File([mockScreenPng([10, 20, 30], 0, 2, 3)], 'screen.png', { type: 'image/png' }) }) await call(contracts.reorderScreenshots, { appId: app.id, order: [screenshot.id] }) await call(contracts.removeScreenshot, { appId: app.id, screenshotId: screenshot.id }) diff --git a/web/src/api/contracts/console/operations.ts b/web/src/api/contracts/console/operations.ts index cac6d4e..e067980 100644 --- a/web/src/api/contracts/console/operations.ts +++ b/web/src/api/contracts/console/operations.ts @@ -3,17 +3,18 @@ import { directoryUser } from './schema/schemas' import { operations } from './schema/operations' import { consoleContract, consoleEmptyContract } from '../define' import { personReader } from './person' -import { accessRequestReader, appReader, createdAccessRequestReader, entryReader, membershipReader, migrationReader, myAccessRequestReader, profileReader, resolvedReader, screenshotReader, settingsReader, toolsReader } from './readers' +import { accessRequestReader, appReader, createdAccessRequestReader, entryReader, inboxReader, membershipReader, migrationReader, myAccessRequestReader, profileReader, resolvedReader, screenshotReader, settingsReader, toolsReader } from './readers' import { meContract } from './me' import { configContract } from './config' import { groupsContract } from './groups' -import { listCommentsContract, postCommentContract, removeCommentContract } from './comments' +import { listCommentsContract, markCommentsSeenContract, postCommentContract, removeCommentContract } from './comments' export type AppListInput = { scope?: 'mine' | 'company' | 'all'; groupId?: string; q?: string } export type DirectoryAppsInput = { groupId?: string; q?: string; ownerId?: string } export type ShareInput = { scope: 'private' | 'group' | 'company' | 'public'; groupIds: string[]; extraPersonIds: string[] } export type CreateAppInput = { displayName: string; groupId: string; description?: string; icon?: string; tags?: string[]; slug?: string; share?: ShareInput } -export type UpdateAppInput = Partial & { guide?: string; capabilities?: string[]; ownerIds?: string[] } +export type ContributionInput = { scope: 'off' | 'group' | 'company' } +export type UpdateAppInput = Partial & { guide?: string; capabilities?: string[]; ownerIds?: string[]; contribution?: ContributionInput } const appPath = (id: string) => `/api/console/apps/${encodeURIComponent(id)}` function query(params: Record): string { const search = new URLSearchParams() @@ -55,6 +56,7 @@ export const approveAccessRequestContract = consoleContract({ ...operations.appr export const declineAccessRequestContract = consoleContract({ ...operations.declineAccessRequest, reader: z.object({ request: accessRequestReader }), request: ({ appId, requestId }: { appId: string; requestId: string }) => ({ method: 'POST', path: `${appPath(appId)}/access-requests/${encodeURIComponent(requestId)}/decline` }) }) export const settingsContract = consoleContract({ ...operations.settings, reader: settingsReader, request: () => ({ method: 'GET', path: '/api/console/admin/platform' }) }) export const migrateDirectoryContract = consoleContract({ ...operations.migrateDirectory, reader: migrationReader, request: () => ({ method: 'POST', path: '/api/console/admin/directory-migrate' }) }) +export const inboxContract = consoleContract({ ...operations.inbox, reader: inboxReader, request: () => ({ method: 'GET', path: '/api/console/inbox' }) }) export const consoleContracts = { me: meContract, config: configContract, groups: groupsContract, people: peopleContract, person: personContract, @@ -62,10 +64,10 @@ export const consoleContracts = { resolve: resolveContract, apps: appsContract, app: appContract, appByPath: appByPathContract, createApp: createAppContract, updateApp: updateAppContract, bindApp: bindAppContract, removeApp: removeAppContract, directoryApps: directoryAppsContract, directoryEntry: directoryEntryContract, tools: toolsContract, - comments: listCommentsContract, postComment: postCommentContract, removeComment: removeCommentContract, + comments: listCommentsContract, postComment: postCommentContract, removeComment: removeCommentContract, markCommentsSeen: markCommentsSeenContract, uploadScreenshot: uploadScreenshotContract, removeScreenshot: removeScreenshotContract, reorderScreenshots: reorderScreenshotsContract, myAccessRequest: myAccessRequestContract, createAccessRequest: createAccessRequestContract, pendingAccessRequests: pendingAccessRequestsContract, appAccessRequests: appAccessRequestsContract, approveAccessRequest: approveAccessRequestContract, declineAccessRequest: declineAccessRequestContract, - settings: settingsContract, migrateDirectory: migrateDirectoryContract, + settings: settingsContract, migrateDirectory: migrateDirectoryContract, inbox: inboxContract, } satisfies Record diff --git a/web/src/api/contracts/console/readers.ts b/web/src/api/contracts/console/readers.ts index be83204..93ff694 100644 --- a/web/src/api/contracts/console/readers.ts +++ b/web/src/api/contracts/console/readers.ts @@ -1,16 +1,33 @@ import { z } from 'zod' import * as wire from './schema/schemas' import { openEnum, openUnion, selectVariant } from '../../boundary' -import type { AccessRequest, AppTools, BusinessApp, CreatedAccessRequest, DirectoryEntry, DirectoryMigrationResult, Membership, MyAccessRequest, PersonProfile, PlatformSettings, Resolved, Screenshot } from '../../../model/contracts/console' +import type { AccessRequest, AppPermissions, AppTools, BusinessApp, Contribution, CreatedAccessRequest, DirectoryEntry, DirectoryMigrationResult, InboxServerItem, Membership, MyAccessRequest, PersonProfile, PlatformSettings, Resolved, Screenshot } from '../../../model/contracts/console' +import { NO_APP_PERMISSIONS } from '../../../model/contracts/console' import { personReader, personRefReader } from './person' export const screenshotReader: z.ZodType = wire.screenshot.strip() const shareReader = wire.share.strip().extend({ scope: openEnum(wire.shareScopes) }) const appGroupReader = wire.appGroup +const contributionReader: z.ZodType = wire.contribution.strip().extend({ scope: openEnum(wire.contributionScopes) }) +// The caller's grants fail closed without failing the app: a set that is absent, +// null, partial or not the five known booleans reads as no grant at all (never a +// partial one); unknown extra keys are dropped. The writer schema stays strict. +const permissionsReader: z.ZodType = z.unknown().optional().transform((value) => { + const known = wire.permissions.strip().safeParse(value) + return known.success ? known.data : { ...NO_APP_PERMISSIONS } +}) export const appReader: z.ZodType = wire.app.strip().extend({ group: appGroupReader, screenshots: z.array(screenshotReader), owners: z.array(personRefReader), createdBy: personRefReader, share: shareReader, + contribution: contributionReader, permissions: permissionsReader, +}) +export const entryReader: z.ZodType = wire.directoryEntry.strip().extend({ + group: appGroupReader, screenshots: z.array(screenshotReader), owners: z.array(personRefReader), contribution: contributionReader, permissions: permissionsReader, }) -export const entryReader: z.ZodType = wire.directoryEntry.strip().extend({ group: appGroupReader, screenshots: z.array(screenshotReader), owners: z.array(personRefReader) }) +const inboxItem = wire.inbox.shape.items.element +// A kind this build cannot render is not work it can route to; drop it rather than miscount. +export const inboxReader: z.ZodType = z.object({ + items: z.array(inboxItem.strip().extend({ kind: openEnum(wire.inboxKinds), app: inboxItem.shape.app.strip() })), +}).transform(({ items }) => items.flatMap(({ kind, ...item }) => kind.kind === 'known' ? [{ ...item, kind: kind.value }] : [])) const memberRole = openEnum(wire.memberRoles) export const membershipReader: z.ZodType = wire.membership.extend({ person: personReader, role: memberRole }) export const profileReader: z.ZodType = wire.personProfile.extend({ diff --git a/web/src/api/contracts/console/schema/operations.ts b/web/src/api/contracts/console/schema/operations.ts index 2f5718a..c1f22a2 100644 --- a/web/src/api/contracts/console/schema/operations.ts +++ b/web/src/api/contracts/console/schema/operations.ts @@ -35,6 +35,8 @@ export const operations = { comments: op({ operationId: 'consoleListAppComments', method: 'GET', routeTemplate: '/api/console/apps/{id}/comments', successStatuses: [200], schema: 'CommentList' }), postComment: op({ operationId: 'consolePostAppComment', method: 'POST', routeTemplate: '/api/console/apps/{id}/comments', successStatuses: [201], schema: 'Comment' }), removeComment: op({ operationId: 'consoleDeleteAppComment', method: 'DELETE', routeTemplate: '/api/console/apps/{id}/comments/{cid}', successStatuses: [204], schema: null }), + markCommentsSeen: op({ operationId: 'consoleMarkCommentsSeen', method: 'POST', routeTemplate: '/api/console/apps/{id}/comments/seen', successStatuses: [204], schema: null }), + inbox: op({ operationId: 'consoleGetInbox', method: 'GET', routeTemplate: '/api/console/inbox', successStatuses: [200], schema: 'Inbox' }), uploadScreenshot: op({ operationId: 'consoleUploadScreenshot', method: 'POST', routeTemplate: '/api/console/apps/{id}/screenshots', successStatuses: [201], schema: 'Screenshot', multipart: true }), removeScreenshot: op({ operationId: 'consoleDeleteScreenshot', method: 'DELETE', routeTemplate: '/api/console/apps/{id}/screenshots/{sid}', successStatuses: [204], schema: null }), reorderScreenshots: op({ operationId: 'consoleReorderScreenshots', method: 'PATCH', routeTemplate: '/api/console/apps/{id}/screenshots', successStatuses: [200], schema: 'ScreenshotList' }), diff --git a/web/src/api/contracts/console/schema/schemas.ts b/web/src/api/contracts/console/schema/schemas.ts index 88a9b64..b281668 100644 --- a/web/src/api/contracts/console/schema/schemas.ts +++ b/web/src/api/contracts/console/schema/schemas.ts @@ -14,6 +14,9 @@ export const shareScopes = ['private', 'group', 'company', 'public'] as const export const memberRoles = ['member', 'manager'] as const export const requestStatuses = ['pending', 'approved', 'declined'] as const export const requestStates = ['none', 'granted', 'pending', 'declined'] as const +export const contributionScopes = ['off', 'group', 'company'] as const +export const views = ['user', 'maker'] as const +export const inboxKinds = ['accessRequest', 'feedback'] as const export const person = z.object({ id, subject: text.nullable(), pending: z.boolean(), email: text, displayName: text, avatarVersion: text.nullable() }) export const unknownPerson = z.strictObject({ id, displayName: z.literal(''), unknown: z.literal(true) }) @@ -21,10 +24,14 @@ export const personRef = z.union([person.strict(), unknownPerson]) export const appGroup = z.object({ id, path: text, name: text }) export const screenshot = z.strictObject({ id, caption: text, width: count, height: count }) export const share = z.strictObject({ scope: z.enum(shareScopes), groupIds: total(id), extraPersonIds: total(id) }) +export const contribution = z.strictObject({ scope: z.enum(contributionScopes) }) +/** Derived per caller by the server (domain.Capabilities); absent grants nothing. */ +export const permissions = z.strictObject({ use: z.boolean(), comment: z.boolean(), propose: z.boolean(), maintain: z.boolean(), data: z.boolean() }) export const app = z.strictObject({ id, slug: text, displayName: text, description: text, icon: text, tags: total(text), guide: text, capabilities: total(text), screenshots: total(screenshot), group: appGroup.strict(), owners: total(personRef), stackId: text.nullable(), appName: text.nullable(), share, createdBy: personRef, createdAt: text, updatedAt: text, + contribution, permissions: observed(permissions), }) export const directoryEntry = app.omit({ slug: true, guide: true, share: true, createdBy: true }).extend({ path: text, canOpen: z.boolean() }) export const group = z.object({ @@ -44,7 +51,7 @@ export const me = z.strictObject({ person: person.strict().extend({ subject: id }), effectiveGroupIds: total(id), managedGroupIds: total(id), isConsoleAdmin: z.boolean(), canCreateApps: z.boolean(), projectId: id, platformUnavailable: observed(z.boolean()), notMember: observed(z.boolean()), teamSlug: observed(text), - directoryPublicURL: text, migration: migrationCounts.extend({ pending: z.boolean() }), + directoryPublicURL: text, migration: migrationCounts.extend({ pending: z.boolean() }), view: z.enum(views), }) export const config = z.strictObject({ projectId: text.max(63).regex(/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/), dashboardUrl: observed(text), newAppConversation: z.boolean() }) export const comment = z.strictObject({ id, appId: id, author: personRef, body: text, createdAt: text }) @@ -70,6 +77,10 @@ export const settings = z.strictObject({ projectId: id, teamSlug: observed(text.nullable()), github: z.strictObject({ connected: z.boolean(), connectionId: text.nullable() }), registry: z.strictObject({ connected: z.boolean(), connectionId: text.nullable() }), defaultTemplateId: text, }) +/** Console-held work for the caller on apps they maintain; zero counts are omitted by the writer. */ +export const inbox = z.object({ + items: total(z.strictObject({ kind: z.enum(inboxKinds), app: z.strictObject({ id, path: text, displayName: text, icon: text }), count, since: text })), +}) export const conversationModes = ['off', 'allowlist', 'on'] as const export const conversationSubject = z.string().min(1).max(255).regex(/^[!-~]+$/) @@ -113,6 +124,6 @@ export const schemas = { Me: me, Config: config, Comment: comment, CommentList: total(comment), ScreenshotList: total(screenshot), AccessRequestList: total(accessRequest), MyAccessRequest: myAccessRequest, CreateAccessRequest: createAccessRequest, ApproveAccessRequest: z.strictObject({ request: accessRequest, app }), DeclineAccessRequest: z.strictObject({ request: accessRequest }), - Tools: tools, Resolved: resolved, Settings: settings, Error: error, + Tools: tools, Resolved: resolved, Settings: settings, Inbox: inbox, Error: error, } export type SchemaName = keyof typeof schemas diff --git a/web/src/api/queries/app-cache.test.ts b/web/src/api/queries/app-cache.test.ts index 4940376..667abcd 100644 --- a/web/src/api/queries/app-cache.test.ts +++ b/web/src/api/queries/app-cache.test.ts @@ -13,7 +13,6 @@ import { groupsQuery, appQuery, approveAccessRequest, updateApp, writeAppCache } import { consoleRoutes } from '../../dev/mock-console' import { platformRoutes } from '../../dev/mock-platform' import { bindCreatedConsoleApp } from '../../features/build/bind-created-console-app' -import { canEditApp } from '../../features/app/permissions' import { knownValue } from '../../model/contracts/build' import type { BusinessApp } from '../../model/contracts/console' import { shareSentence } from '../../model/share' @@ -49,7 +48,7 @@ async function expectOneShape(answered: BusinessApp) { // What appQuery's consumers read of it works on the cached value as written. expect(knownValue(cached.share.scope)).toBe(knownValue(read.share.scope)) expect(shareSentence(cached.share, [], cached.group)).toBe(shareSentence(read.share, [], read.group)) - expect(canEditApp(cached, undefined)).toBe(false) + expect(cached.permissions.maintain).toBe(read.permissions.maintain) } describe('the app query cache holds one shape', () => { diff --git a/web/src/api/queries/console.ts b/web/src/api/queries/console.ts index 4468649..fffa4a7 100644 --- a/web/src/api/queries/console.ts +++ b/web/src/api/queries/console.ts @@ -4,7 +4,7 @@ import { queryOptions, useQuery, useSuspenseQuery, type QueryClient } from '@tanstack/react-query' import { isResponseContractError } from '../boundary' import { isConsoleError } from '../console' -import { listCommentsContract, postCommentContract, removeCommentContract } from '../contracts/console/comments' +import { listCommentsContract, markCommentsSeenContract, postCommentContract, removeCommentContract } from '../contracts/console/comments' import { configContract } from '../contracts/console/config' import { groupsContract } from '../contracts/console/groups' import { meContract } from '../contracts/console/me' @@ -19,6 +19,7 @@ import { directoryAppsContract, directoryEntryContract, directoryUsersContract, + inboxContract, membersContract, migrateDirectoryContract, myAccessRequestContract, @@ -34,18 +35,19 @@ import { updateAppContract, uploadScreenshotContract, type AppListInput, + type ContributionInput, type DirectoryAppsInput, type UpdateAppInput, } from '../contracts/console/operations' import { conversationSettingApi } from '../conversation-setting' import { apiGateway } from '../gateway' import { isTransientError } from '../platform-error' -import type { BusinessApp, Person } from '../../model/contracts/console' +import type { BusinessApp, InboxServerItem, Person } from '../../model/contracts/console' import { POLL_INTERVAL_MS, readRetryDelay, retryReadQuery, retryTransient, TRANSIENT_RETRIES } from './shared' export type AppListParams = AppListInput export type DirectoryAppsParams = DirectoryAppsInput -export type { UpdateAppInput } +export type { ContributionInput, InboxServerItem, UpdateAppInput } export const consoleKeys = { me: ['console', 'me'] as const, @@ -67,6 +69,7 @@ export const consoleKeys = { directoryUsers: (query: string) => ['console', 'directory', 'users', query] as const, platform: ['console', 'admin', 'platform'] as const, conversationSetting: ['console', 'admin', 'conversation'] as const, + inbox: ['console', 'inbox'] as const, } /** Not-found answers and contract failures are final; a call nothing answered gets the transient retries, anything else two retries. */ @@ -145,6 +148,9 @@ export const pendingAccessRequestsQuery = queryOptions({ queryFn: () => apiGateway.console(pendingAccessRequestsContract, undefined), }) +/** Console-held inbox rows (access requests, unread feedback) on apps the caller maintains; `useInbox` adds the Platform-side rows. */ +export const inboxQuery = queryOptions({ queryKey: consoleKeys.inbox, queryFn: (): Promise => apiGateway.console(inboxContract, undefined) }) + export const appAccessRequestsQuery = (appId: string) => queryOptions({ queryKey: consoleKeys.accessRequestsOfApp(appId), queryFn: () => apiGateway.console(appAccessRequestsContract, appId) }) @@ -185,6 +191,8 @@ export function useApps(params: AppListParams, enabled = true) { export const postComment = (appId: string, body: string) => apiGateway.console(postCommentContract, { appId, body }) export const removeComment = (appId: string, commentId: string) => apiGateway.console(removeCommentContract, { appId, commentId }) +/** Maintainers only: the thread so far counts as read for the caller's inbox feedback count. */ +export const markCommentsSeen = (appId: string): Promise => apiGateway.console(markCommentsSeenContract, appId) // Console writes of the app screens. A 2xx answer that breaks its contract // rejects with a typed failure: nothing is cached from it, and callers read the diff --git a/web/src/api/testing/catalog-domain.ts b/web/src/api/testing/catalog-domain.ts index a819e62..f2ba8c3 100644 --- a/web/src/api/testing/catalog-domain.ts +++ b/web/src/api/testing/catalog-domain.ts @@ -42,6 +42,16 @@ export function resolvedDestinationOf(patch: { revision?: string; registryNamesp return read } +/** + * The app wire fields most fixtures do not care about, for spreading into an + * app wire: the default contribution scope and the caller's capabilities as the + * app's owner (the creator of a draft maintains it). + */ +export const appWireDefaults = { + contribution: { scope: 'group' }, + permissions: { use: true, comment: true, propose: true, maintain: true, data: true }, +} as const + /** A Console app as `GET /api/console/apps/{id}` answers it. */ export function appOf(wire: unknown): BusinessApp { const result = decodeResponse(appContract, wire) diff --git a/web/src/copy/shell.en.ts b/web/src/copy/shell.en.ts index 371b27d..764bdd5 100644 --- a/web/src/copy/shell.en.ts +++ b/web/src/copy/shell.en.ts @@ -40,6 +40,7 @@ export const shellEn: typeof shell = { noGroups: 'No groups yet.', problems: (n: number) => `${n} ${n === 1 ? 'issue' : 'issues'}`, problemsLabel: (n: number) => `${n} ${n === 1 ? 'app needs' : 'apps need'} attention`, + inboxLabel: (n: number) => `Home (${n} waiting for you)`, skip: 'Skip to content', }, topbar: { @@ -50,10 +51,7 @@ export const shellEn: typeof shell = { switchContext: 'Switch group', userMenu: 'User menu', profile: 'Profile', - cannotCreateTitle: 'You cannot create apps yet', - cannotCreateBody: 'Ask your admin to give you access to create apps.', platformUnavailable: 'App creation is unavailable', - platformUnavailableBody: 'Wait a moment, then reload the page.', notMemberTitle: 'You are not a project member', notMemberBody: (teamSlug?: string) => teamSlug ? `This project is managed by the team “${teamSlug}”. Ask an admin to add you.` @@ -67,13 +65,25 @@ export const shellEn: typeof shell = { searchClear: 'Clear search', resultsTitle: (q: string) => `Results for “${q}”`, noResults: 'No apps found. Try a different search.', - groupApps: (name: string) => `${name} apps`, - seeAll: 'View all →', - groupEmpty: 'This group has no apps yet.', - shared: 'Shared by parent groups', - sharedEmpty: 'No shared apps yet.', - companyNew: 'New across the company', - companyEmpty: 'No apps have been shared with the company yet.', + usable: 'Apps you can use', + count: (n: number) => (n === 1 ? '1 app' : `${n} apps`), + filterLabel: 'Filter apps you can use', + filterAll: 'All', + filterOther: 'Other teams', + filterCompany: 'Company-wide', + hint: 'Choose an app to open it in a new tab.', + hintClose: 'Dismiss tip', + more: 'Show more', + directoryPrompt: 'Can’t find the app you need?', + directoryLink: 'Search the directory →', + emptyTitle: 'No apps you can use yet', + emptyBody: 'Find an app in the directory and select “Request access” to ask its owner.', + emptyAction: 'Search the directory', + noGroupTitle: 'You have not joined a group yet', + noGroupBody: 'Ask your admin to add you. You can use company-wide apps below.', + noUsableMatch: 'No apps you can use match your search.', + otherMatches: (n: number) => (n === 1 ? '1 other app in the company matches.' : `${n} other apps in the company match.`), + otherMatchesLabel: 'Other apps in the company', noMembership: 'You have not joined a group yet. Ask your admin to add you.', }, mine: { @@ -154,7 +164,50 @@ export const shellEn: typeof shell = { help: { title: 'Help', toc: 'Contents', + order: { + user: ['find', 'access', 'ask', 'create'], + maker: ['publish', 'share', 'proposals', 'trouble'], + }, articles: [ + { + id: 'find', + title: 'Find and open apps', + body: [ + 'Home lists the apps you can use under “Apps you can use”.', + 'Select a card to open the app in a new tab.', + 'Select “Details” to read what the app does and how to use it.', + 'Use the search box at the top to find an app by name or purpose.', + ], + }, + { + id: 'access', + title: 'When you can’t open an app', + body: [ + 'Apps that are not on Home can be found by team in the directory.', + 'For an app you cannot open, select “Request access” to ask its owner.', + 'Once your request is approved, the app appears under “Apps you can use”.', + 'If an app says it is not ready yet, wait until it is ready.', + ], + }, + { + id: 'ask', + title: 'Need help? Ask the owner', + body: [ + 'Open the app’s “Details” and write under “Tell the owner”.', + 'Share feedback, requests, or problems. Anyone who can see the app can read it.', + 'If it is urgent, use “Email the owner”.', + 'If an app seems to be having trouble, wait a moment and try again.', + ], + }, + { + id: 'create', + title: 'Want to create an app?', + body: [ + 'If you can create apps, “+ New app” appears in the top-right corner.', + 'Name your app and choose who can see it.', + 'If you don’t see the button, ask your admin to give you access to create apps.', + ], + }, { id: 'publish', title: 'Publish your app', @@ -179,6 +232,17 @@ export const shellEn: typeof shell = { 'The invited person needs an account they can sign in with. Ask your workspace admin if they cannot sign in.', ], }, + { + id: 'proposals', + title: 'Accept and send proposals', + body: [ + 'People who don’t own an app can still propose changes to it.', + 'Proposals can come from people in the app’s team who can create apps.', + 'To propose a change, select “Propose a change” on the app’s page.', + 'A proposal changes nothing until an owner reviews it and selects “Apply”.', + 'Owners choose whether to accept proposals in the app’s settings.', + ], + }, { id: 'trouble', title: 'When something goes wrong', diff --git a/web/src/copy/shell.ts b/web/src/copy/shell.ts index f57da32..f3b960b 100644 --- a/web/src/copy/shell.ts +++ b/web/src/copy/shell.ts @@ -41,6 +41,7 @@ export const shell = { noGroups: 'グループはまだありません。', problems: (n: number) => `問題あり ${n}`, problemsLabel: (n: number) => `問題ありのアプリが ${n} 件あります`, + inboxLabel: (n: number) => `ホーム(あなたの対応待ち ${n} 件)`, skip: '本文へ移動', }, topbar: { @@ -51,10 +52,7 @@ export const shell = { switchContext: '所属を切り替える', userMenu: 'ユーザーメニュー', profile: 'プロフィール', - cannotCreateTitle: 'アプリを作る権限がありません', - cannotCreateBody: '管理者に「作れる人」への追加を依頼してください。', platformUnavailable: 'いまアプリの作成状態を確認できません', - platformUnavailableBody: 'しばらくしてからページを再読み込みしてください。', notMemberTitle: 'この基盤(Project)のメンバーではありません', notMemberBody: (teamSlug?: string) => teamSlug ? `この基盤は Team「${teamSlug}」が管理しています。管理者に追加を依頼してください。` @@ -68,13 +66,25 @@ export const shell = { searchClear: '検索をやめる', resultsTitle: (q: string) => `「${q}」の検索結果`, noResults: '見つかりませんでした。言葉を変えてお試しください。', - groupApps: (name: string) => `${name} のアプリ`, - seeAll: 'すべて見る →', - groupEmpty: 'このグループのアプリはまだありません。', - shared: '上位グループから共有されたアプリ', - sharedEmpty: '共有されたアプリはありません。', - companyNew: '全社の新着', - companyEmpty: '全社に公開されたアプリはまだありません。', + usable: '使えるアプリ', + count: (n: number) => `${n} 件`, + filterLabel: '使えるアプリの絞り込み', + filterAll: 'すべて', + filterOther: 'ほかの部署', + filterCompany: '全社', + hint: '使いたいアプリを選ぶと、新しいタブで開きます。', + hintClose: '案内を閉じる', + more: 'もっと見る', + directoryPrompt: '探しているアプリがないときは', + directoryLink: 'ディレクトリで探す →', + emptyTitle: 'まだ使えるアプリがありません', + emptyBody: 'ディレクトリから探して「使いたい」を押すと、担当者に申請できます。', + emptyAction: 'ディレクトリで探す', + noGroupTitle: 'まだグループに所属していません', + noGroupBody: '管理者に配置を依頼してください。全社に公開されたアプリは、下から使えます。', + noUsableMatch: '使えるアプリには見つかりませんでした。', + otherMatches: (n: number) => `会社のほかのアプリに ${n} 件あります。`, + otherMatchesLabel: '会社のほかのアプリ', noMembership: 'まだどのグループにも所属していません。管理者に配置を依頼してください。', }, mine: { @@ -155,7 +165,51 @@ export const shell = { help: { title: 'ヘルプ', toc: '目次', + /** Article order by view (role-based-views ux-design §6.9); a `#id` outside the list is appended. */ + order: { + user: ['find', 'access', 'ask', 'create'], + maker: ['publish', 'share', 'proposals', 'trouble'], + }, articles: [ + { + id: 'find', + title: 'アプリを探す・開く', + body: [ + 'ホームの「使えるアプリ」に、あなたが使えるアプリが並んでいます。', + 'カードを押すと、アプリが新しいタブで開きます。', + '「くわしく」を押すと、できることや使いかたを読めます。', + '名前や用途で探すときは、上の検索を使ってください。', + ], + }, + { + id: 'access', + title: '使いたいアプリが開けないとき', + body: [ + 'ホームにないアプリは、ディレクトリで部署からたどれます。', + '開けないアプリは「使いたい」を押すと、担当者に申請できます。', + '申請が通ると、ホームの「使えるアプリ」に出ます。', + '「準備中です。まだ開けません」と出るときは、準備ができるまでお待ちください。', + ], + }, + { + id: 'ask', + title: '困ったとき(担当者に聞く)', + body: [ + 'アプリの「くわしく」を開き、「担当者に伝える」に書いてください。', + '感想・要望・困りごとを書けます。このアプリを見られる人に見えます。', + '急ぐときは「メールで連絡する」から担当者にメールを送れます。', + '「いま調子が悪いようです」と出るときは、少し待ってからお試しください。', + ], + }, + { + id: 'create', + title: 'アプリを作りたいとき', + body: [ + 'アプリを作れる人には、右上に「+ 新しいアプリ」が出ます。', + 'アプリの名前と、誰に見せるかを選ぶだけで作れます。', + 'ボタンがないときは、管理者に「作れる人」への追加を依頼してください。', + ], + }, { id: 'publish', title: 'アプリを出すまで', @@ -180,6 +234,17 @@ export const shell = { '招待先のアカウントでログインできる必要があります。使えない場合は基盤の管理者に依頼してください。', ], }, + { + id: 'proposals', + title: '提案を受け付ける・提案する', + body: [ + '担当者でない人も、アプリの直しを提案できます。', + '提案できるのは、アプリと同じ部署の、アプリを作れる人です。', + '提案するときは、アプリのページで「直しを提案する」を押します。', + '提案は、担当者が確認して「反映する」を押すまで、アプリに反映されません。', + '受け付けるかどうかは、アプリの設定「提案の受け付け」で変えられます。', + ], + }, { id: 'trouble', title: '失敗したとき', diff --git a/web/src/dev/mock-console.test.ts b/web/src/dev/mock-console.test.ts index 1ca1529..ef2d6fb 100644 --- a/web/src/dev/mock-console.test.ts +++ b/web/src/dev/mock-console.test.ts @@ -361,7 +361,7 @@ describe('directory and comment routes', () => { test('the console role toggle exposes a private bound entry without changing the caller toggle', async () => { expect((await call('POST', `${root}/__mock/role`, { role: 'Viewer' })).body).toMatchObject({ - person: { id: 'p-tanaka' }, isConsoleAdmin: false, canCreateApps: false, + person: { id: 'p-kobayashi' }, isConsoleAdmin: false, canCreateApps: false, view: 'user', }) expect((await call('GET', `${root}/resolve?path=sales/east/team-a/keihi`)).body.kind).toBe('entry') await caller('p-yamada', 'Viewer') @@ -375,7 +375,9 @@ describe('directory and comment routes', () => { const members = (await call('GET', `${root}/directory/groups/g-team-a/members`)).body.items as Array<{ person: { id: string }; inheritedFrom: string | null }> expect(members.map((member) => [member.person.id, member.inheritedFrom]).sort()).toEqual([['p-sato', 'g-sales'], ['p-suzuki', null], ['p-yamada', null]]) // A direct membership stays a direct row even when an ancestor grants a stronger role; the role is the strongest. - expect((await call('GET', `${root}/directory/groups/g-planning/members`)).body.items).toMatchObject([{ person: { id: 'p-sato' }, role: 'manager', inheritedFrom: null }]) + expect((await call('GET', `${root}/directory/groups/g-planning/members`)).body.items).toMatchObject([ + { person: { id: 'p-sato' }, role: 'manager', inheritedFrom: null }, { person: { id: 'p-kobayashi' }, role: 'member', inheritedFrom: null }, + ]) expect((await call('GET', `${root}/directory/groups/missing/members`)).status).toBe(404) expect((await call('GET', `${root}/directory/people?ids=p-sato,p-missing`)).body.items).toMatchObject([{ id: 'p-sato' }]) expect((await call('GET', `${root}/directory/people?q=yamada`)).body.items).toMatchObject([{ id: 'p-yamada' }]) @@ -402,10 +404,10 @@ describe('directory and comment routes', () => { expect((await call('POST', `${root}/admin/directory-migrate`)).status).toBe(403) await call('POST', `${root}/__mock/caller`, { personId: 'p-yamada', role: 'Admin' }) const pending = (await call('POST', `${root}/__mock/migration`, {})).body - expect(pending).toEqual({ pending: true, people: 4, groups: 6, memberships: 5 }) + expect(pending).toEqual({ pending: true, people: 5, groups: 6, memberships: 6 }) expect((await call('GET', `${root}/me`)).body.migration).toEqual(pending) const result = await call('POST', `${root}/admin/directory-migrate`) - expect(result).toEqual({ status: 200, body: { imported: { people: 4, groups: 6, memberships: 5 }, conflicts: [], merged: [] } }) + expect(result).toEqual({ status: 200, body: { imported: { people: 5, groups: 6, memberships: 6 }, conflicts: [], merged: [] } }) expect((await call('GET', `${root}/me`)).body.migration.pending).toBe(false) expect(await call('POST', `${root}/admin/directory-migrate`)).toEqual(result) }) @@ -651,7 +653,7 @@ describe('store routes: screenshots, people and owner filter', () => { expect((await call('GET', `${root}/me`)).body.person.avatarVersion).toBe(seeded) const people = (await call('GET', `${root}/directory/people`)).body.items as Array<{ id: string; avatarVersion: string | null }> expect(Object.fromEntries(people.map((entry) => [entry.id, entry.avatarVersion]))).toEqual({ - 'p-yamada': seeded, 'p-sato': seeded, 'p-suzuki': null, 'p-tanaka': seeded, + 'p-yamada': seeded, 'p-sato': seeded, 'p-suzuki': null, 'p-tanaka': seeded, 'p-kobayashi': null, }) expect((await call('GET', mitsumori)).body.owners[0].avatarVersion).toBe(seeded) const comments = (await call('GET', `${mitsumori}/comments`)).body as Array<{ author: { id: string; avatarVersion: string | null } }> @@ -810,3 +812,100 @@ describe('creation needs a membership of the target group (like the server)', () }) }) }) + +describe('role-based views: personas, permissions, contribution and the inbox (like the server)', () => { + const root = '/api/console' + const role = (name: string) => call('POST', `${root}/__mock/role`, { role: name }) + const permissionsOf = async () => Object.fromEntries(((await call('GET', `${root}/apps`)).body.items as Array<{ id: string; permissions: Record }>).map((app) => [app.id, app.permissions])) + const none = { use: false, comment: false, propose: false, maintain: false, data: false } + const user = { use: true, comment: true, propose: false, maintain: false, data: false } + const maintainer = { use: true, comment: true, propose: true, maintain: true, data: true } + beforeEach(async () => { await call('POST', `${root}/__mock/reset`) }) + afterEach(async () => { await call('POST', `${root}/__mock/reset`) }) + + test('the default persona is a maker who maintains every app; group scope is seeded except one company and one off', async () => { + expect((await call('GET', `${root}/me`)).body).toMatchObject({ person: { id: 'p-yamada' }, isConsoleAdmin: true, view: 'maker' }) + const apps = (await call('GET', `${root}/apps`)).body.items as Array<{ id: string; contribution: { scope: string }; permissions: unknown }> + expect(Object.fromEntries(apps.map((app) => [app.id, app.contribution.scope]))).toEqual({ + 'a-mitsumori': 'group', 'a-nippo': 'group', 'a-keihi': 'group', 'a-hikkoshi': 'group', 'a-kintai': 'company', 'a-kaigishitsu': 'off', + }) + for (const app of apps) expect(app.permissions).toEqual(maintainer) + const entry = (await call('GET', `${root}/apps/a-kaigishitsu/directory-entry`)).body + expect(entry).toMatchObject({ contribution: { scope: 'off' }, permissions: maintainer }) + }) + + test('Viewer is a user who can neither maintain nor propose; Editor proposes only where the scope admits them', async () => { + expect((await role('Viewer')).body).toMatchObject({ person: { id: 'p-kobayashi' }, canCreateApps: false, view: 'user', managedGroupIds: [] }) + expect(await permissionsOf()).toEqual({ 'a-hikkoshi': user, 'a-kintai': user, 'a-kaigishitsu': user }) + expect((await call('GET', `${root}/apps/a-keihi/directory-entry`)).body.permissions).toEqual(none) + + expect((await role('Editor')).body).toMatchObject({ person: { id: 'p-kobayashi' }, canCreateApps: true, view: 'user' }) + // 引っ越し見積: own group with scope group; 勤怠申請: scope company; 会議室予約: scope off. + expect(await permissionsOf()).toEqual({ 'a-hikkoshi': { ...user, propose: true }, 'a-kintai': { ...user, propose: true }, 'a-kaigishitsu': user }) + expect((await call('PATCH', `${root}/apps/a-hikkoshi`, { contribution: { scope: 'off' } })).status).toBe(403) + expect((await call('POST', `${root}/apps/a-hikkoshi/comments/seen`)).status).toBe(403) + expect((await call('POST', `${root}/apps/a-keihi/comments/seen`)).status).toBe(404) + expect((await call('GET', `${root}/inbox`)).body).toEqual({ items: [] }) + }) + + test('owners and group managers start from the maker view', async () => { + await call('POST', `${root}/__mock/caller`, { personId: 'p-suzuki', role: 'Viewer' }) + expect((await call('GET', `${root}/me`)).body).toMatchObject({ view: 'maker', managedGroupIds: [] }) + expect((await permissionsOf())['a-nippo']).toEqual(maintainer) + await call('POST', `${root}/__mock/caller`, { personId: 'p-kobayashi', role: 'Viewer' }) + expect((await call('GET', `${root}/me`)).body.view).toBe('user') + }) + + test('maintainers change the contribution scope through the app PATCH; anything else is refused', async () => { + const saved = await call('PATCH', `${root}/apps/a-hikkoshi`, { contribution: { scope: 'company', extra: true } }) + expect(saved).toMatchObject({ status: 200, body: { contribution: { scope: 'company' } } }) + expect(saved.body.contribution).toEqual({ scope: 'company' }) + for (const contribution of [{ scope: 'public' }, {}, null, 'off']) { + expect((await call('PATCH', `${root}/apps/a-hikkoshi`, { contribution }))).toEqual({ + status: 400, body: { error: 'invalid_request', message: 'contribution.scope must be off, group or company' }, + }) + } + await role('Editor') + expect((await permissionsOf())['a-hikkoshi'].propose).toBe(true) + await role('Admin') + await call('PATCH', `${root}/apps/a-hikkoshi`, { contribution: { scope: 'off' } }) + await role('Editor') + expect((await permissionsOf())['a-hikkoshi'].propose).toBe(false) + }) + + test('an improvement draft passes the console gate only with propose: scope off is contribution_not_accepted, else forbidden', async () => { + const propose = (stackId: string) => call('POST', '/api/v1/projects/commerce/application-drafts', { kind: 'improvement', applicationStackId: stackId, intent: '直したい' }) + try { + await role('Editor') + expect(await propose('kaigishitsu')).toEqual({ status: 403, body: { error: { code: 'contribution_not_accepted', message: 'このアプリは、いま提案を受け付けていません。' } } }) + expect((await propose('hikkoshi')).status).not.toBe(403) + await role('Viewer') + expect(await propose('hikkoshi')).toMatchObject({ status: 403, body: { error: { code: 'forbidden' } } }) + // A creation draft is not the console's to gate. + expect((await call('POST', '/api/v1/projects/commerce/application-drafts', { intent: '作りたい' })).status).not.toBe(403) + } finally { + await call('POST', '/api/v1/__mock/reset') + } + }) + + test('the inbox lists pending requests and unread feedback by others; reading the thread and deciding clear them', async () => { + const inbox = async () => (await call('GET', `${root}/inbox`)).body.items as Array<{ kind: string; app: { id: string; path: string; displayName: string; icon: string }; count: number; since: string }> + expect(await inbox()).toEqual([ + { kind: 'accessRequest', app: { id: 'a-keihi', path: 'sales/east/team-a/keihi', displayName: '経費精算', icon: '💴' }, count: 1, since: '2026-10-10T09:00:00.000Z' }, + { kind: 'feedback', app: { id: 'a-keihi', path: 'sales/east/team-a/keihi', displayName: '経費精算', icon: '💴' }, count: 1, since: '2026-10-10T09:00:00.000Z' }, + ]) + // A newer comment by someone else on a thread already read counts again; the caller's own never does. + await call('POST', `${root}/__mock/caller`, { personId: 'p-suzuki', role: 'Viewer' }) + expect((await call('POST', `${root}/apps/a-mitsumori/comments`, { body: '検索が速くなりました。' })).status).toBe(201) + await call('POST', `${root}/__mock/caller`, { personId: 'p-yamada', role: 'Admin' }) + expect((await call('POST', `${root}/apps/a-mitsumori/comments`, { body: 'ありがとうございます。' })).status).toBe(201) + const feedback = (await inbox()).filter((item) => item.kind === 'feedback') + expect(feedback.map((item) => [item.app.id, item.count])).toEqual([['a-mitsumori', 1], ['a-keihi', 1]]) + + expect(await call('POST', `${root}/apps/a-mitsumori/comments/seen`)).toEqual({ status: 204, body: undefined }) + expect(await call('POST', `${root}/apps/a-keihi/comments/seen`)).toEqual({ status: 204, body: undefined }) + expect((await call('POST', `${root}/apps/a-keihi/access-requests/aar-keihi-suzuki/decline`)).status).toBe(200) + expect(await inbox()).toEqual([]) + expect((await call('POST', `${root}/apps/missing/comments/seen`)).status).toBe(404) + }) +}) diff --git a/web/src/dev/mock-console.ts b/web/src/dev/mock-console.ts index 1ec3b1f..864b439 100644 --- a/web/src/dev/mock-console.ts +++ b/web/src/dev/mock-console.ts @@ -2,18 +2,25 @@ // and of the slice of the Directory API the console uses: the same-origin proxy // `/api/console/directory/*` and the public `/api/directory/v1/*` origin (avatars). // `me.directoryPublicURL` is the request origin, so avatars load through Vite's -// `/api` proxy. Fixtures: a 3-level org, 4 people (+2 realm-only users), 6 apps +// `/api` proxy. Fixtures: a 3-level org, 5 people (+2 realm-only users), 6 apps // bound to the platform mock's seeded stacks, and one redirect for a moved group // (`sales/tokyo` → `sales/east`). Authorization mirrors the contract closely -// enough to exercise the UI; the real rules live in cmd/server. +// enough to exercise the UI; the real rules live in cmd/server (`domain.Capabilities` +// is mirrored by `permissionsOf`: every app answer carries the caller's permissions). +// Personas (`MOCK_ROLE`, or `POST /api/console/__mock/role`): Admin (default) is Yamada, a console admin who owns +// apps (view maker; inbox: an access request and unread feedback on 経費精算). Viewer and Editor are Kobayashi, a +// 営業企画部 member who owns and manages nothing (view user); Editor can create apps, so Kobayashi may propose on +// 引っ越し見積 (own group, scope group) and 勤怠申請 (scope company). 会議室予約 accepts no proposals (scope off). +// `GET /inbox` derives access requests and unread feedback on apps the caller maintains, like the server; +// `POST /apps/{id}/comments/seen` (maintainers) marks the thread read. Yamada has already read 見積作成. // `POST /api/console/__mock/bare-500 {times?}` makes the next writes answer a // bare gateway 500 (no JSON envelope), as during a console rollout. // `POST /api/console/__mock/not-member {notMember?, teamSlug?}` denies Project // access (default true); /me still answers with the non-member notice metadata. // `POST /api/console/__mock/caller {personId, role?}` switches signed-in people -// (default role Viewer) for requester/approver stories; reset restores Yamada. -// `POST /api/console/__mock/role {role}` switches role and caller: Viewer uses -// Tanaka (who cannot open the private keihi app); Admin/Editor use Yamada. +// (default role Viewer) for requester/approver stories; reset restores the MOCK_ROLE persona. +// `POST /api/console/__mock/role {role}` switches role and caller: Admin uses Yamada, Viewer and Editor use +// Kobayashi (who cannot open the private keihi app). // `POST /api/console/__mock/leave-groups {personId?}` removes every direct membership of the person (default the // caller), who then belongs to no group: no creation entry opens and `POST /apps` refuses every group, like the server. // `POST /api/console/__mock/comments {state: 'empty' | 'many' | 'quota'}` replaces @@ -69,7 +76,11 @@ type Person = z.output type Role = 'Admin' | 'Editor' | 'Viewer' type StoredGroup = Omit -type StoredApp = Omit & { groupId: string; ownerIds: string[]; createdById: string } +type StoredApp = Omit & { groupId: string; ownerIds: string[]; createdById: string } +type Permissions = z.output +type ContributionScope = z.output['scope'] +type InboxItem = z.output['items'][number] +const CONTRIBUTION_SCOPES: readonly ContributionScope[] = ['off', 'group', 'company'] type StoredComment = { comment: AppComment; deletedAt: string | null; deletedBy: string | null } type StoredScreenshotFile = { appId: string; contentType: ScreenshotType; bytes: Uint8Array } type StoredAvatar = { contentType: ScreenshotType; bytes: Uint8Array } @@ -122,17 +133,23 @@ const app = ( stackId: slug, appName: slug, share: policy, + contribution: { scope: 'group' }, createdById: owner, createdAt: at(days), updatedAt: at(days + 1), }) +/** Who a persona signs in as: Admin is Yamada (owns apps); Viewer and Editor are Kobayashi (owns and manages nothing). */ +const callerFor = (role: Role) => (role === 'Admin' ? 'p-yamada' : 'p-kobayashi') +const ROLES: readonly Role[] = ['Admin', 'Editor', 'Viewer'] + function seedConsole() { const people: Person[] = [ { id: 'p-yamada', subject: 'sub-yamada', pending: false, email: 'yamada@example.com', displayName: '山田 太郎', avatarVersion: null }, { id: 'p-sato', subject: 'sub-sato', pending: false, email: 'sato@example.com', displayName: '佐藤 花子', avatarVersion: null }, { id: 'p-suzuki', subject: 'sub-suzuki', pending: false, email: 'suzuki@example.com', displayName: '鈴木 一郎', avatarVersion: null }, { id: 'p-tanaka', subject: 'sub-tanaka', pending: false, email: 'tanaka@example.com', displayName: '田中 美咲', avatarVersion: null }, + { id: 'p-kobayashi', subject: 'sub-kobayashi', pending: false, email: 'kobayashi@example.com', displayName: '小林 由紀', avatarVersion: null }, ] const avatarFiles = new Map() const seedAvatars: Record = { 'p-yamada': [13, 148, 136], 'p-sato': [219, 39, 119], 'p-tanaka': [79, 70, 229] } @@ -165,7 +182,7 @@ function seedConsole() { const memberships = new Map>([ ['g-sales', new Map([['p-sato', 'manager']])], ['g-team-a', new Map([['p-yamada', 'member'], ['p-suzuki', 'member']])], - ['g-planning', new Map([['p-sato', 'member']])], + ['g-planning', new Map([['p-sato', 'member'], ['p-kobayashi', 'member']])], ['g-soumu', new Map([['p-tanaka', 'manager']])], ]) const apps: StoredApp[] = [ @@ -177,8 +194,12 @@ function seedConsole() { app('nippo', '日報', 'g-team-a', 'p-suzuki', share('group', ['g-sales-east']), 5, '毎日の営業報告をまとめます。', '📝', ['営業']), app('keihi', '経費精算', 'g-team-a', 'p-yamada', share('private'), 20, '交通費と経費を申請します。', '💴', ['経理']), app('hikkoshi', '引っ越し見積', 'g-planning', 'p-sato', share('group', ['g-sales']), 30, '引っ越し案件の概算を出します。', '🚚', ['企画']), - { ...app('kintai', '勤怠申請', 'g-soumu', 'p-tanaka', share('company'), 10, '休暇と残業を申請します。', '🕘', ['総務']), capabilities: ['休暇を申請できる', '残業の時間を記録できる', '上長が承認できる'] }, - app('kaigishitsu', '会議室予約', 'g-soumu', 'p-tanaka', share('public'), 25, '会議室の空きを確認して予約します。', '🏢', ['総務']), + { + ...app('kintai', '勤怠申請', 'g-soumu', 'p-tanaka', share('company'), 10, '休暇と残業を申請します。', '🕘', ['総務']), + capabilities: ['休暇を申請できる', '残業の時間を記録できる', '上長が承認できる'], + contribution: { scope: 'company' }, + }, + { ...app('kaigishitsu', '会議室予約', 'g-soumu', 'p-tanaka', share('public'), 25, '会議室の空きを確認して予約します。', '🏢', ['総務']), contribution: { scope: 'off' } }, ] const screenshotFiles = new Map() const seedShots: Record = { @@ -219,9 +240,10 @@ function seedConsole() { deletedAt: null, deletedBy: null, }, ] + const role = (process.env.MOCK_ROLE as Role | undefined) ?? 'Admin' return { - callerId: 'p-yamada', - role: (process.env.MOCK_ROLE as Role | undefined) ?? 'Admin', + callerId: callerFor(role), + role, platformUnavailable: process.env.MOCK_PLATFORM_UNAVAILABLE === '1', notMember: false, teamSlug: 'commerce-team', @@ -238,6 +260,8 @@ function seedConsole() { apps, accessRequests, comments, + /** Person id → app id → when they last marked the thread read (`POST /apps/{id}/comments/seen`). */ + commentsSeen: new Map>([['p-yamada', new Map([['a-mitsumori', at(38)]])]]), /** App id → what `GET /apps/{id}/tools` answers; missing ids have no Tools built-in app. */ tools: new Map([['a-mitsumori', 'list'], ['a-nippo', 'empty'], ['a-kintai', 'pending'], ['a-kaigishitsu', 'unavailable']]), screenshotFiles, @@ -301,6 +325,22 @@ export const mockOwnerSubjects = (stackId: string): string[] => (state.apps.find((app) => app.stackId === stackId)?.ownerIds ?? []) .flatMap((id) => person(id)?.subject ? [person(id).subject!] : []) +/** + * The console's gate in front of `POST application-drafts {kind: 'improvement'}` (server `requireCapability(…, "propose")`): + * undefined when the caller may propose to the app on that stack, or when no console app owns it (the Platform answers); + * otherwise the 403 the console returns instead of forwarding. + */ +export function mockProposalRefusal(stackId: string): { code: 'contribution_not_accepted' | 'forbidden'; message: string } | undefined { + const stored = state.apps.find((app) => app.stackId === stackId) + if (!stored) return undefined + const permissions = permissionsOf(stored) + if (permissions.propose) return undefined + if (permissions.use && canCreateApps() && stored.contribution.scope === 'off') { + return { code: 'contribution_not_accepted', message: 'このアプリは、いま提案を受け付けていません。' } + } + return { code: 'forbidden', message: 'You do not have permission for this action' } +} + /** * Direct rows plus rows inherited from ancestors (Directory rule): a direct membership always stays a direct * row carrying the strongest effective role; otherwise the strongest role wins, then the nearest source. @@ -333,7 +373,8 @@ function personGroups(personId: string): Map state.role === 'Admin' && !state.platformUnavailable && !state.notMember const canManage = (groupId: string) => isAdmin() || personGroups(state.callerId).get(groupId)?.role === 'manager' -const canEditApp = (stored: StoredApp) => stored.ownerIds.includes(state.callerId) || canManage(stored.groupId) +const maintains = (stored: StoredApp) => stored.ownerIds.includes(state.callerId) || canManage(stored.groupId) +const canCreateApps = () => !state.notMember && !state.platformUnavailable && (state.role === 'Admin' || state.role === 'Editor') function visible(stored: StoredApp, personId = state.callerId): boolean { if ((personId === state.callerId && isAdmin()) || stored.ownerIds.includes(personId) || stored.share.extraPersonIds.includes(personId)) return true @@ -343,6 +384,37 @@ function visible(stored: StoredApp, personId = state.callerId): boolean { return stored.share.groupIds.some((groupId) => [...subtree(groupId)].some((id) => mine.has(id))) } +/** The caller's authority on one app: the server's `domain.Capabilities` (data equals maintain for now). */ +function permissionsOf(stored: StoredApp): Permissions { + const maintain = maintains(stored) + const use = maintain || visible(stored) + const { scope } = stored.contribution + const inScope = scope === 'company' || (scope === 'group' && personGroups(state.callerId).has(stored.groupId)) + return { use, comment: use, propose: maintain || (use && canCreateApps() && inScope), maintain, data: maintain } +} + +/** `GET /inbox`: pending access requests and others' comments after the caller last read the thread, on apps they maintain. */ +function inbox(): InboxItem[] { + const seen = state.commentsSeen.get(state.callerId) + const events = [ + ...state.accessRequests.filter((entry) => entry.status === 'pending').map((entry) => ({ kind: 'accessRequest' as const, appId: entry.appId, at: entry.requestedAt })), + ...state.comments + .filter(({ comment, deletedAt }) => deletedAt === null && comment.author.id !== state.callerId && comment.createdAt > (seen?.get(comment.appId) ?? '')) + .map(({ comment }) => ({ kind: 'feedback' as const, appId: comment.appId, at: comment.createdAt })), + ] + const items = new Map() + for (const event of events) { + const stored = state.apps.find((entry) => entry.id === event.appId) + if (!stored || !maintains(stored)) continue + const key = `${event.kind}/${stored.id}` + const item = items.get(key) ?? { kind: event.kind, app: { id: stored.id, path: `${pathOf(stored.groupId)}/${stored.slug}`, displayName: stored.displayName, icon: stored.icon }, count: 0, since: event.at } + item.count++ + if (event.at > item.since) item.since = event.at + items.set(key, item) + } + return [...items.values()].sort((a, b) => a.kind.localeCompare(b.kind) || b.since.localeCompare(a.since) || a.app.id.localeCompare(b.app.id)) +} + function toApp(stored: StoredApp): BusinessApp { const owner = state.groups.find((g) => g.id === stored.groupId) as StoredGroup const { groupId: _groupId, ownerIds, createdById, ...rest } = stored @@ -351,6 +423,7 @@ function toApp(stored: StoredApp): BusinessApp { group: { id: owner.id, path: pathOf(owner.id), name: owner.name }, owners: ownerIds.map(person), createdBy: person(createdById), + permissions: permissionsOf(stored), } } @@ -372,6 +445,8 @@ function toEntry(stored: StoredApp): DirectoryEntry { createdAt: app.createdAt, updatedAt: app.updatedAt, canOpen: visible(stored), + contribution: app.contribution, + permissions: app.permissions, } } @@ -387,7 +462,9 @@ function me(): Me { effectiveGroupIds: [...mine.keys()], managedGroupIds: [...mine].filter(([, row]) => row.role === 'manager').map(([groupId]) => groupId), isConsoleAdmin: isAdmin(), - canCreateApps: !state.notMember && !state.platformUnavailable && (state.role === 'Admin' || state.role === 'Editor'), + canCreateApps: canCreateApps(), + // Like the server: admins, group managers and owners start from the maker home. + view: isAdmin() || [...mine.values()].some((row) => row.role === 'manager') || state.apps.some((entry) => entry.ownerIds.includes(state.callerId)) ? 'maker' : 'user', projectId: state.projectId, teamSlug: state.teamSlug, directoryPublicURL: requestOrigin, @@ -418,7 +495,7 @@ function appTools(stored: StoredApp): AppTools { if (toolsState === 'pending') return { available: false, pending: true } if (toolsState === 'unavailable') return { available: true, error: 'tools_unavailable', tools: [] } const tools = toolsState === 'list' ? mockTools(stored) : [] - return me().canCreateApps || isAdmin() ? { available: true, tools, editUrl: `${toolsOrigin()}/edit` } : { available: true, tools } + return canCreateApps() || isAdmin() ? { available: true, tools, editUrl: `${toolsOrigin()}/edit` } : { available: true, tools } } // ---------- resolve ---------- @@ -581,16 +658,16 @@ export async function consoleRoutes(request: Request, url: URL): Promise(request) if (!state.people.some((entry) => entry.id === input.personId && entry.subject)) return notFound() - if (input.role && !['Admin', 'Editor', 'Viewer'].includes(input.role)) return fail(400, 'invalid_request', 'invalid role') + if (input.role && !ROLES.includes(input.role)) return fail(400, 'invalid_request', 'invalid role') state.callerId = input.personId state.role = input.role ?? 'Viewer' return json(me()) } if (head === '__mock' && id === 'role' && method === 'POST') { const input = await body<{ role: Role }>(request) - if (!['Admin', 'Editor', 'Viewer'].includes(input.role)) return fail(400, 'invalid_request', 'invalid role') + if (!ROLES.includes(input.role)) return fail(400, 'invalid_request', 'invalid role') state.role = input.role - state.callerId = input.role === 'Viewer' ? 'p-tanaka' : 'p-yamada' + state.callerId = callerFor(input.role) return json(me()) } if (head === '__mock' && id === 'comments' && method === 'POST') { @@ -677,12 +754,13 @@ export async function consoleRoutes(request: Request, url: URL): Promise entry.id)) + const editable = new Set(state.apps.filter(maintains).map((entry) => entry.id)) return json(state.accessRequests .filter((entry) => entry.status === 'pending' && editable.has(entry.appId)) .sort((a, b) => a.requestedAt.localeCompare(b.requestedAt))) @@ -775,7 +853,7 @@ export async function consoleRoutes(request: Request, url: URL): Promise() + seen.set(stored.id, new Date().toISOString()) + state.commentsSeen.set(state.callerId, seen) + return new Response(null, { status: 204 }) + } if (subId && method === 'DELETE') { const entry = state.comments.find((entry) => entry.comment.id === subId && entry.comment.appId === stored.id && entry.deletedAt === null) if (!entry) return notFound() - if (entry.comment.author.id !== state.callerId && !canEditApp(stored)) return forbidden() + if (entry.comment.author.id !== state.callerId && !maintains(stored)) return forbidden() entry.deletedAt = new Date().toISOString() entry.deletedBy = state.callerId return new Response(null, { status: 204 }) @@ -873,7 +959,7 @@ export async function consoleRoutes(request: Request, url: URL): Promise undefined) const file = form?.get('file') @@ -911,7 +997,7 @@ export async function consoleRoutes(request: Request, url: URL): Promise entry.appId === stored.id) const pending = requests.filter((entry) => entry.status === 'pending').sort((a, b) => a.requestedAt.localeCompare(b.requestedAt)) @@ -938,11 +1024,16 @@ export async function consoleRoutes(request: Request, url: URL): Promise> & { ownerIds?: string[] }>(request) + const input = await body> & { ownerIds?: string[] }>(request) + if (input.contribution !== undefined) { + const scope = CONTRIBUTION_SCOPES.find((known) => known === (input.contribution as { scope?: unknown } | null)?.scope) + if (!scope) return fail(400, 'invalid_request', 'contribution.scope must be off, group or company') + input.contribution = { scope } + } if (input.guide !== undefined && (typeof input.guide !== 'string' || [...input.guide].length > 4000)) { return fail(400, 'invalid_request', 'guide must be at most 4000 characters') } diff --git a/web/src/dev/mock-platform.ts b/web/src/dev/mock-platform.ts index ceb5223..dd57e20 100644 --- a/web/src/dev/mock-platform.ts +++ b/web/src/dev/mock-platform.ts @@ -30,6 +30,8 @@ // created and bound to that seeded stack (412 without a source repository, e.g. `nippo`). While // read, their turns answer after ~2 s (first a clarifying question, then a 3-task proposal whose // first reply is 「この内容で直して」) and their runs move one step every ~1.5 s. +// Like the console gate, a caller without `permissions.propose` on the console app is refused with +// 403 `contribution_not_accepted` (scope `off`) or `forbidden` before any Platform check. // Completion submits a proposal; only Accept creates a live release and version. // Toggles: // - `POST /api/v1/__mock/role {role}` switches the caller's Team role (Viewer → create calls answer 403). @@ -141,7 +143,7 @@ import { buildCopy, textJa as buildTextJa } from '../model/build/copy' import { isFirstTurn, isKickoffReply, isPrepareTurn } from '../model/build/questions' import { dataModeFailure, findTable, resetDatabaseData, selectRows, state as dataState, type DataMode } from './mock-database-data' import { dataWriteRoutes } from './mock-database-rows' -import { mockOwnerSubjects, mockSubject } from './mock-console' +import { mockOwnerSubjects, mockProposalRefusal, mockSubject } from './mock-console' export const MOCK_PROJECT_ID = 'commerce' const TEAM_SLUG = 'commerce-team' @@ -2088,6 +2090,9 @@ const routes: Array<[method: string, pattern: RegExp, handler: Handler]> = [ if (body.kind !== undefined && body.kind !== 'creation' && !improvement) return error(400, 'invalid_argument', "'kind' must be creation or improvement") if (improvement && !body.applicationStackId) return error(400, 'invalid_argument', 'applicationStackId is required for an improvement draft') if (!improvement && body.applicationStackId) return error(400, 'invalid_argument', 'applicationStackId is only accepted for an improvement draft') + // The console gate (console_authority) answers before the Platform sees an improvement draft. + const refusal = improvement ? mockProposalRefusal(body.applicationStackId!) : undefined + if (refusal) return error(403, refusal.code, refusal.message) // Like platform-api: the target stack must resolve to an application with a source repository. const stack = improvement ? state.stacks.get(body.applicationStackId!) : undefined if (improvement && !stack) return error(412, 'failed_precondition', 'the application stack has no application') diff --git a/web/src/features/app/app-page-wire.test.tsx b/web/src/features/app/app-page-wire.test.tsx index dd47cbe..2d66f16 100644 --- a/web/src/features/app/app-page-wire.test.tsx +++ b/web/src/features/app/app-page-wire.test.tsx @@ -122,12 +122,12 @@ function DeletionProbe() { } /** The app page on the app's query defaults (retry policy included), with polling left to the test. */ -async function renderApp(tab: AppTab, scene: 'app' | 'mine' | 'mine-problems' | 'drafts' | 'deletion-probe' | { improve: string } = 'app') { +async function renderApp(tab: AppTab, scene: 'app' | 'mine' | 'mine-problems' | 'drafts' | 'deletion-probe' | { improve: string } = 'app', search = '') { client = new QueryClient({ defaultOptions: { queries: { ...appQueryClient.getDefaultOptions().queries, retryDelay: 0, refetchInterval: false, refetchOnWindowFocus: false } } }) await Promise.all([client.fetchQuery(meQuery), client.fetchQuery(groupsQuery), client.fetchQuery(appQuery(APP_ID))]) const rootRoute = createRootRoute() const anyRoute = createRoute({ getParentRoute: () => rootRoute, path: '$', component: () => null }) - router = createRouter({ routeTree: rootRoute.addChildren([anyRoute]), history: createMemoryHistory({ initialEntries: [`${APP_PATH}/-/${tab}`] }) }) + router = createRouter({ routeTree: rootRoute.addChildren([anyRoute]), history: createMemoryHistory({ initialEntries: [`${APP_PATH}/-/${tab}${search}`] }) }) await router.load() container = document.createElement('div') document.body.append(container) @@ -140,6 +140,8 @@ async function renderApp(tab: AppTab, scene: 'app' | 'mine' | 'mine-problems' | const pageText = () => document.body.textContent ?? '' const count = (method: string, path: RegExp) => requests.filter((item) => item.method === method && path.test(item.path)).length +/** Writes the page made, except opening 概要 marking the app's comments seen (利用者の声), which no scenario here is about. */ +const writes = () => requests.filter((item) => item.method !== 'GET' && !/^\/api\/console\/apps\/[^/]+\/comments\/seen$/.test(item.path)) const refreshFailed = copy.common.refreshFailed(copy.relative.justNow) /** Every value the page holds in its query cache, serialized: nothing from an unreadable answer may be in it. */ const cachedWire = () => JSON.stringify(client.getQueryCache().getAll().map((query) => query.state.data)) @@ -454,7 +456,7 @@ describe('APT-1109: isolated rows keep the rest of the project readable', () => expect(row('見積').textContent).toContain(text.unsupported.label) expect(rows().filter((item) => !item.textContent?.includes('見積')).map((item) => item.textContent)).toEqual(before.filter((value) => !value?.includes('見積'))) expect(row('見積').textContent).not.toContain(discoverText.list.resume) - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) // Without an id only apps lacking their own readable stack become unknown. rewrites = [{ method: 'GET', path: stackList, once: false, body: (wire) => ({ ...wire, data: (wire.data as Json[]).map((stack) => stack.id === 'mitsumori' ? { templateId: 'Bad Id!' } : stack) }) }] await tick(keys.stacks('commerce')) @@ -469,7 +471,7 @@ describe('APT-1109: isolated rows keep the rest of the project readable', () => expect(buttons().some((item) => item.textContent?.trim() === text.header.menu && !item.disabled)).toBe(false) expect(container.querySelector('[data-testid=\"improve-with-ai\"]')).toBeNull() expect(pageText()).not.toContain(discoverText.list.statusFailed) - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) }) test('an unreadable plan in the draft list does not change normal app statuses', async () => { @@ -492,7 +494,7 @@ describe('APT-1109: isolated rows keep the rest of the project readable', () => expect(pageText()).not.toContain(discoverText.list.statusFailed) const created = await beginBuild('commerce', 'a different app', { groupId: 'g-team-a', ownerSubject: 'owner' }) expect(created.id).not.toBe('broken-draft') - expect(requests.filter((item) => item.method !== 'GET')).toEqual([{ method: 'POST', path: `${PROJECT}/application-drafts`, status: 201 }]) + expect(writes()).toEqual([{ method: 'POST', path: `${PROJECT}/application-drafts`, status: 201 }]) expect(requests.some((item) => item.path.endsWith('/broken-draft'))).toBe(false) // An independently readable exact match still resumes as before. expect((await beginBuild('commerce', storedDraftWire.intent, { groupId: 'g-team-a', ownerSubject: 'owner' })).id).toBe(storedDraftWire.id) @@ -530,7 +532,7 @@ describe('APT-1136: a reported failure of the latest build of an app that runs a // 「詳しい人向け」 carries the same fact as its one place outside the notice. await click(button(copy.app.overview.advanced.toggle)) expect(container.querySelector('[data-testid="advanced-latest-build"]')?.textContent).toContain(behind.latestFailed) - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) await act(async () => { root?.unmount() }) await renderApp('overview', 'mine') @@ -552,7 +554,7 @@ describe('APT-1136: a reported failure of the latest build of an app that runs a expect(buttons(notice).some((item) => item.textContent?.includes('AI に直させる'))).toBe(true) // One notice: the 0.5.9 error notice for the same cause is replaced, not repeated. expect(container.querySelectorAll('[data-testid="build-failure-cause"]')).toHaveLength(1) - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) }) test('an app with no running release keeps the build failure as its status, without the secondary notice', async () => { @@ -599,7 +601,7 @@ test('an unreadable improvement offers no generation and the app can start a new expect(buttons().some((item) => item.textContent?.trim() === buildCopy.failure.plan.replan)).toBe(false) expect(container.querySelector('textarea')?.disabled).toBe(true) expect([...container.querySelectorAll('a')].some((link) => link.getAttribute('href') === APP_PATH)).toBe(true) - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) await act(async () => { root?.unmount() }) container.remove() client.clear() @@ -674,7 +676,7 @@ test.each(['platform-v1', 'console-v1'] as const)('an unreadable creating-draft expect(dialog()).not.toBeNull() expect([...dialog()!.querySelectorAll('[role="radio"]')].every((item) => item.disabled)).toBe(true) expect(buttons(dialog()!).some((item) => item.textContent?.trim() === copy.app.settings.save)).toBe(false) - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) expect(pageText()).not.toContain(discoverText.list.statusFailed) for (const tab of ['settings', 'releases'] as const) { await act(async () => { root?.unmount() }) @@ -688,7 +690,7 @@ test.each(['platform-v1', 'console-v1'] as const)('an unreadable creating-draft await click(edit) } expect(dialog()).toBeNull() - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) } }) @@ -707,7 +709,7 @@ test.each(['stack', 'build'] as const)('delete and discard hooks refuse an unrea await click(button('Attempt delete')) await click(button('Attempt discard')) expect(pageText()).toContain('Both writes refused') - expect(requests.filter((item) => item.method !== 'GET')).toEqual([]) + expect(writes()).toEqual([]) }) test.each(['improve', 'repair'] as const)('an unreadable draft row does not block a new %s', async (entry) => { @@ -722,9 +724,63 @@ test.each(['improve', 'repair'] as const)('an unreadable draft row does not bloc await act(async () => { type(input, 'Improve this app') }) await click(button(improveText.entry.submit, dialog()!)) } - expect(requests.filter((item) => item.method !== 'GET')).toEqual([ + expect(writes()).toEqual([ { method: 'POST', path: `${PROJECT}/application-drafts`, status: 201 }, { method: 'POST', path: expect.stringMatching(/\/application-drafts\/[^/]+\/conversation-turns$/), status: 202 }, ]) expect(requests.some((item) => item.path.includes('/unreadable-row'))).toBe(false) }) + +describe('role-based views: people who do not maintain the app get the intro page (ux-design §6.5, §6.6)', () => { + const USE_ONLY = { use: true, comment: true, propose: false, maintain: false, data: false } + const PROPOSER = { ...USE_ONLY, propose: true } + const asCaller = (permissions: typeof USE_ONLY) => rewrites.push({ method: 'GET', path: CONSOLE_APP, once: false, body: (wire) => ({ ...wire, permissions }) }) + const tabs = () => container.querySelector(`nav[aria-label="${text.header.tabsLabel}"]`) + + test.each(['overview', 'settings', 'logs', 'data'] as const)('every tab URL (%s) shows the tab-less intro with 担当者に伝える and no engineering words', async (tab) => { + asCaller(USE_ONLY) + await renderApp(tab) + expect(tabs()).toBeNull() + expect(container.querySelector('[data-testid="intro-open"]')!.textContent).toContain(text.intro.open) + expect(pageText()).toContain(text.feedback.title) + expect(pageText()).toContain(text.feedback.lead) + expect(pageText()).not.toContain(sharingCopy.title) + expect(pageText()).not.toContain(text.propose.action) + for (const word of ['ログ', 'イメージ', 'ポート', text.overview.placement, text.settings.advanced]) expect(pageText()).not.toContain(word) + expect(pageText()).not.toMatch(/\bv\d+\b/) + // Nothing behind the tabs is read for someone who cannot see them. + expect(count('GET', LOGS)).toBe(0) + expect(count('GET', ENV)).toBe(0) + }) + + test('someone who may propose gets 「直しを提案する」; a closed contribution scope refuses in the dialog with the server reason', async () => { + asCaller(PROPOSER) + rewrites.push({ method: 'POST', path: new RegExp(`^${PROJECT}/application-drafts$`), once: true, body: () => Response.json({ error: { code: 'contribution_not_accepted', message: text.propose.refused } }, { status: 403 }) }) + await renderApp('overview') + expect(tabs()).toBeNull() + await click(button(text.propose.action, container)) + const open = dialog()! + expect(open.textContent).toContain(text.propose.title) + expect(open.textContent).toMatch(/さんが確認してから反映されます。/) + const field = open.querySelector('textarea')! + await act(async () => { type(field, '一覧に絞り込みを足したい') }) + await submit(open.querySelector('form')!) + expect(dialog()!.textContent).toContain(text.propose.refused) + }) + + test('a maintainer previews it with ?as=user under a banner, and 「もとに戻る」 brings the tabs back', async () => { + await renderApp('overview', 'app', '?as=user') + expect(container.querySelector('[data-testid="user-preview-banner"]')!.textContent).toContain(text.intro.preview) + expect(tabs()).toBeNull() + // Users delete only their own comments, so the preview does too: moderation stays on the guide tab. + const myName = client.getQueryData(meQuery.queryKey)!.person.displayName + const rows = [...section('comments').closest('section')!.querySelectorAll('li')] + expect(rows.length).toBeGreaterThan(rows.filter((row) => row.textContent?.startsWith(myName)).length) + expect(rows.filter((row) => row.querySelector(`button[aria-label="${text.comments.menu}"]`)).length).toBe(rows.filter((row) => row.textContent?.startsWith(myName)).length) + await click(button(text.intro.previewExit, container)) + expect(router.state.location.searchStr).not.toContain('as=user') + expect(container.querySelector('[data-testid="user-preview-banner"]')).toBeNull() + expect(tabs()).not.toBeNull() + expect(container.querySelector('[data-testid="user-view-link"]')!.getAttribute('href')).toContain('?as=user') + }) +}) diff --git a/web/src/features/app/app-page.tsx b/web/src/features/app/app-page.tsx index 69862a1..2b711ff 100644 --- a/web/src/features/app/app-page.tsx +++ b/web/src/features/app/app-page.tsx @@ -1,6 +1,6 @@ -// App detail (ux-design §7.3): header with the app URL as the hero, then tabs -// 概要 / つかいかた / データ / 更新履歴 / 設定 / ログ. The route resolves `//` to the -// BusinessApp; the platform side is joined by `stackId` (src/model/app.ts). +// App detail (ux-design §6.5, §6.7): people who maintain the app get the header with the app URL as the hero, then +// tabs 概要 / つかいかた / データ / 更新履歴 / 設定 / ログ; everyone else gets the tab-less intro page for every tab URL. +// The route resolves `//` to the BusinessApp; the platform side is joined by `stackId` (src/model/app.ts). import { ExternalLink, Lock, MoreHorizontal, Pencil, Trash2, Users } from 'lucide-react' import { useQuery } from '@tanstack/react-query' import { useState } from 'react' @@ -43,8 +43,8 @@ import { dataText } from './data/copy' import { DeleteAppDialog } from './delete-dialog' import { GuideTab } from './guide-tab' import { LogsTab } from './logs-tab' -import { OverviewTab } from './overview-tab' -import { canEditApp } from './permissions' +import { OverviewTab, UserViewLink } from './overview-tab' +import { IntroPage, useUserPreview } from './intro-page' import { lastUpdate, sourceRepositoryFor } from './platform' import { ReleasesTab } from './releases-tab' import { SettingsTab } from './settings-tab' @@ -61,6 +61,14 @@ const TABS: readonly AppTab[] = ['overview', 'guide', 'data', 'releases', 'setti /** `app` comes from the route's live `appQuery`, so edits made here flow back in. */ export function AppPage({ app, tab }: { app: BusinessApp; tab: AppTab }) { + const preview = useUserPreview() + // Not maintaining the app: the intro page for every tab URL (settings, data, logs, …), never a tab (§6.5). + if (!app.permissions.maintain) return + if (preview.active) return + return +} + +function MaintainerAppPage({ app, tab }: { app: BusinessApp; tab: AppTab }) { useDocumentTitle(app.displayName) const me = useMe().data const projectId = me.projectId @@ -75,7 +83,7 @@ export function AppPage({ app, tab }: { app: BusinessApp; tab: AppTab }) { const logs = useComponentLogs(projectId, view.platform?.webComponentId, view.platform?.branchId, tab === 'logs') const logsForbidden = isLogsForbidden(logs.error) const sharing = shareSentence(app.share, groups, app.group) - const canEdit = !view.unreadableStack && !view.unreadableBuild && canEditApp(app, me) + const canEdit = !view.unreadableStack && !view.unreadableBuild && app.permissions.maintain const requests = useQuery({ ...appAccessRequestsQuery(app.id), enabled: canEdit }) const pendingCount = canEdit ? requests.data?.filter((request) => isOneOf(request.status, 'pending')).length ?? 0 : 0 // Phase 1: the データ tab exposes every row, so only people who may edit the app see it (design "Authorization and privacy"). @@ -107,8 +115,14 @@ export function AppPage({ app, tab }: { app: BusinessApp; tab: AppTab }) { setShareOpen(true)} onDelete={() => setDeleting(true)} /> -
- + {/* 「利用者にはこう見えます →」 continues the tab row's rule on wide screens and sits above the tabs on phones. */} +
+
+ +
+
+ +
diff --git a/web/src/features/app/comments-panel.test.tsx b/web/src/features/app/comments-panel.test.tsx index 39c4079..f8ac5e1 100644 --- a/web/src/features/app/comments-panel.test.tsx +++ b/web/src/features/app/comments-panel.test.tsx @@ -13,7 +13,7 @@ const at = new Date().toISOString() const person = { id: 'p-1', subject: 'sub-1', pending: false, email: 'yamada@example.test', displayName: '山田', avatarVersion: null } const me: Me = { person, isConsoleAdmin: false, canCreateApps: true, effectiveGroupIds: [], managedGroupIds: [], projectId: 'commerce', - directoryPublicURL: '', migration: { pending: false, people: 0, groups: 0, memberships: 0 }, + directoryPublicURL: '', migration: { pending: false, people: 0, groups: 0, memberships: 0 }, view: 'user', } const thread = [ { id: 'c-1', appId: 'app-1', author: person, body: '使ってみました', createdAt: at }, diff --git a/web/src/features/app/comments.tsx b/web/src/features/app/comments.tsx index f06fdae..f2d7a7e 100644 --- a/web/src/features/app/comments.tsx +++ b/web/src/features/app/comments.tsx @@ -1,6 +1,6 @@ import { useQuery } from '@tanstack/react-query' import { MoreHorizontal, Trash2 } from 'lucide-react' -import { useId, useState } from 'react' +import { useId, useState, type ReactNode } from 'react' import { isConsoleError } from '../../api/console' import { isUnknownPerson, membershipRoots, type AppComment, type Group, type Me, type PersonRef } from '../../model/contracts/console' import { commentsQuery, useGroups, useMe } from '../../api/queries/console' @@ -42,15 +42,21 @@ export function commentErrorText(error: unknown): string | undefined { return undefined } -type CommentsProps = { appId: string; owners: readonly PersonRef[]; canDeleteAny: boolean } +/** The section's heading; the default is 「コメント(N)」, the intro page passes 「担当者に伝える」 (ux-design §6.10). */ +export type CommentsHeading = { title: ReactNode; lead?: ReactNode; actions?: ReactNode } -/** Shared by the guide and the directory entry; never needs the full app or its visibility policy. */ +type CommentsProps = { appId: string; owners: readonly PersonRef[]; canDeleteAny: boolean; heading?: CommentsHeading } + +/** Anchor of the comments section (the maintainer's 「利用者の声」 links to it on the guide tab). */ +export const COMMENTS_ANCHOR = 'comments' + +/** Shared by the guide, the intro page and the directory entry; never needs the full app or its visibility policy. */ export function Comments(props: CommentsProps) { // Changing apps must discard the previous thread's composer and delete target. return } -function CommentThread({ appId, owners, canDeleteAny }: CommentsProps) { +function CommentThread({ appId, owners, canDeleteAny, heading }: CommentsProps) { const me = useMe().data const groups = useGroups().data const comments = useQuery(commentsQuery(appId)) @@ -65,10 +71,10 @@ function CommentThread({ appId, owners, canDeleteAny }: CommentsProps) { // An owner the server can no longer resolve is not marked as one. const ownerIds = new Set(owners.filter((owner) => !isUnknownPerson(owner)).map((owner) => owner.id)) const showCounter = input.length > COMMENT_COUNTER_THRESHOLD - const title = comments.data ? text.comments.title(comments.data.length) : text.comments.loadingTitle + const title = heading?.title ?? (comments.data ? text.comments.title(comments.data.length) : text.comments.loadingTitle) return ( -
+
{ event.preventDefault() if (!input.canSend || post.isPending) return diff --git a/web/src/features/app/copy.en.ts b/web/src/features/app/copy.en.ts index 9a69f2d..b8b6838 100644 --- a/web/src/features/app/copy.en.ts +++ b/web/src/features/app/copy.en.ts @@ -113,6 +113,52 @@ export const textEn: typeof textJa = { deleteBody: (preview: string) => `Delete “${preview}”. This cannot be undone.`, draft: 'You will be able to comment once the app is further along.', }, + feedback: { + title: 'Tell the owners', + lead: 'Share impressions, requests or problems. Anyone who can see this app can read them.', + mail: 'Email the owners', + }, + intro: { + back: 'Home', + ofGroup: (name: string) => `An app of ${name}`, + owner: 'Owner', + open: 'Open app', + preparingTitle: 'Getting ready', + preparing: 'It cannot be opened yet. Once it is ready, you can open it here.', + troubleTitle: 'Something seems wrong right now', + trouble: 'If it does not open, wait a moment and try again.', + askSoon: (owner: string) => `If it is urgent, ask the owner, ${owner}.`, + askStill: (owner: string) => `If it still does not work, ask the owner, ${owner}.`, + preview: 'You are seeing this page as users do.', + previewExit: 'Go back', + }, + propose: { + action: 'Suggest a fix', + title: 'Suggest a fix', + description: (app: string, owner?: string) => `Describe what you want to change in “${app}”. AI drafts the change, and ${owner ? `${owner} reviews` : 'the owners review'} it before it is applied.`, + refused: 'This app is not accepting suggestions right now.', + resume: 'Continue', + view: 'View suggestion', + dismiss: 'Dismiss', + drafting: 'Your suggestion is being drafted.', + reviewing: (owner?: string) => `${owner ?? 'The owners'} ${owner ? 'is' : 'are'} reviewing your suggestion.`, + changesRequested: (owner?: string) => `${owner ?? 'The owners'} asked for changes to your suggestion.`, + applied: 'Your suggestion was applied.', + rejected: 'Your suggestion was declined.', + }, + maintainer: { + userView: 'See it as users do →', + gapTitle: 'The introduction is incomplete', + gapItems: { description: 'a description', capabilities: '“What it does”', screenshots: 'screenshots', guide: '“How to use”' }, + gapDetail: (missing: readonly string[]) => `Missing ${missing.length > 1 ? `${missing.slice(0, -1).join(', ')} and ${missing.at(-1)}` : missing[0]}. Users can't tell what this app is for from their home page.`, + gapWrite: 'Write the introduction', + gapDismiss: 'Dismiss', + voicesTitle: 'User feedback', + voicesNew: (count: number) => `${count} new`, + voicesAll: 'See all', + voicesFix: 'Fix this with AI', + voicesEmpty: 'No feedback from users yet.', + }, releases: { lead: 'Saved changes become a new version automatically.', columns: { version: 'Version', at: 'Date', phase: 'Status', reason: 'Reason', action: 'Actions' }, @@ -126,7 +172,7 @@ export const textEn: typeof textJa = { settings: { generalLead: 'The name and description shown in lists and search.', navigation: 'Settings sections', - sections: { name: 'Name', owners: 'Owners', share: 'Sharing', env: 'Settings', danger: 'Danger zone' }, + sections: { name: 'Name', owners: 'Owners', share: 'Sharing', contribution: 'Proposals', env: 'Settings', danger: 'Danger zone' }, unsaved: (section: string) => `Your changes in “${section}” have not been saved.`, automatic: (count: number) => `Automatic settings (${count})`, advanced: 'Advanced', @@ -159,6 +205,15 @@ export const textEn: typeof textJa = { envAdding: 'Setting to add', dangerLead: 'These actions cannot be undone.', deleteDialogTitle: (name: string) => `Delete “${name}”?`, + contribution: 'Accepting proposals', + contributionSwitch: 'Accept proposals from people in the same department who can build apps', + contributionHelp: 'A proposal reaches the app only after an owner reviews it and selects “Apply”.', + contributionOff: 'Not accepting proposals. Only owners and group managers can change this app.', + contributionWho: 'Who can propose', + contributionWhoGroup: (group: string) => `Members of ${group} and its parent groups who can build apps`, + contributionWhoCompany: 'Anyone who can use this app and build apps', + contributionReviewer: 'Who reviews', + contributionReviewerValue: (names: string) => `Owners (${names})`, }, logs: { lead: 'Messages from your app, refreshed every 5 seconds.', @@ -184,6 +239,7 @@ export const textEn: typeof textJa = { label: 'Status unknown', releasePhase: 'Unknown', share: 'This screen cannot handle the sharing setting, so it cannot be changed here.', + contribution: 'This screen cannot handle the proposal setting. It cannot be changed here.', env: 'Some settings cannot be handled on this screen, so saving is paused.', tools: 'This screen cannot handle the state of Tools.', role: 'Role unknown', diff --git a/web/src/features/app/copy.ts b/web/src/features/app/copy.ts index c80b98a..289bb65 100644 --- a/web/src/features/app/copy.ts +++ b/web/src/features/app/copy.ts @@ -117,6 +117,55 @@ export const textJa = { deleteBody: (preview: string) => `「${preview}」を削除します。この操作は取り消せません。`, draft: 'アプリの準備が進むと、コメントを書けるようになります。', }, + /** The comments section on the intro page (ux-design §6.10). */ + feedback: { + title: '担当者に伝える', + lead: '感想・要望・困りごとを書けます。このアプリを見られる人に見えます。', + mail: 'メールで連絡する', + }, + /** The tab-less page for people who use the app but do not maintain it (ux-design §6.5, §9). */ + intro: { + back: 'ホーム', + ofGroup: (name: string) => `${name} のアプリ`, + owner: '担当', + open: 'アプリを開く', + preparingTitle: '準備中', + preparing: 'まだ開けません。準備ができると、ここから開けます。', + troubleTitle: 'いま調子が悪いようです', + trouble: '開けないときは、少し待ってからお試しください。', + askSoon: (owner: string) => `急ぐときは、担当の ${owner} さんに聞いてください。`, + askStill: (owner: string) => `解決しないときは、担当の ${owner} さんに聞いてください。`, + preview: '利用者の見え方を表示しています。', + previewExit: 'もとに戻る', + }, + /** 「直しを提案する」 for people who may propose but not maintain (ux-design §6.6, §8). */ + propose: { + action: '直しを提案する', + title: '直しを提案する', + description: (app: string, owner?: string) => `「${app}」のどこを直したいか書いてください。AI が直しかたを作り、${owner ? `担当の ${owner} さん` : '担当者'}が確認してから反映されます。`, + refused: 'このアプリは、いま提案を受け付けていません。', + resume: '続きから直す', + view: '提案を見る', + dismiss: '閉じる', + drafting: '提案を作っています。', + reviewing: (owner?: string) => `あなたの提案を、${owner ? `${owner} さん` : '担当者'}が確認しています。`, + changesRequested: (owner?: string) => `${owner ? `${owner} さん` : '担当者'}から、やり直しの依頼が届いています。`, + applied: 'あなたの提案が反映されました。', + rejected: 'あなたの提案は見送られました。', + }, + maintainer: { + userView: '利用者にはこう見えます →', + gapTitle: '紹介がまだ足りません', + gapItems: { description: '説明', capabilities: '「できること」', screenshots: '画面の写真', guide: '「つかいかた」' }, + gapDetail: (missing: readonly string[]) => `${missing.length > 1 ? `${missing.slice(0, -1).join('、')}と${missing.at(-1)}` : missing[0]}がありません。利用者のホームで、何のアプリか伝わりません。`, + gapWrite: '紹介を書く', + gapDismiss: '閉じる', + voicesTitle: '利用者の声', + voicesNew: (count: number) => `新着 ${count}`, + voicesAll: 'すべて見る', + voicesFix: 'これを AIで直す', + voicesEmpty: 'まだ利用者の声は届いていません。', + }, releases: { lead: '置き場に入れた変更は、新しい版として自動で出ます。', columns: { version: '版', at: '日時', phase: '状態', reason: '理由', action: '操作' }, @@ -130,7 +179,7 @@ export const textJa = { settings: { generalLead: '一覧や検索に出る名前と説明です。', navigation: '設定の項目', - sections: { name: '名前', owners: '担当', share: '公開範囲', env: '設定値', danger: '危険な操作' }, + sections: { name: '名前', owners: '担当', share: '公開範囲', contribution: '提案', env: '設定値', danger: '危険な操作' }, unsaved: (section: string) => `「${section}」に入力した内容は保存されていません。`, automatic: (count: number) => `自動で設定される値(${count} 件)`, advanced: '詳しい人向け', @@ -163,6 +212,15 @@ export const textJa = { envAdding: '追加する設定値', dangerLead: '元に戻せない操作です。', deleteDialogTitle: (name: string) => `「${name}」を削除しますか?`, + contribution: '提案の受け付け', + contributionSwitch: '同じ部署の、アプリを作れる人からの提案を受け付ける', + contributionHelp: '提案は、担当者が確認して「反映する」を押すまで、アプリに反映されません。', + contributionOff: '提案は受け付けていません。直せるのは、担当者とグループの管理者だけです。', + contributionWho: '提案できる人', + contributionWhoGroup: (group: string) => `${group} と上位グループのメンバーのうち、アプリを作れる人`, + contributionWhoCompany: 'このアプリを使える人のうち、アプリを作れる人', + contributionReviewer: '確認する人', + contributionReviewerValue: (names: string) => `担当者(${names})`, }, logs: { lead: 'アプリが出したメッセージです。5 秒ごとに新しくなります。', @@ -190,6 +248,7 @@ export const textJa = { label: '状態不明', releasePhase: '不明', share: '公開範囲をこの画面では扱えません。変更はできません。', + contribution: '提案の受け付けをこの画面では扱えません。変更はできません。', env: 'この画面で扱えない設定値があるため、いまは保存できません。', tools: 'Tools の状態をこの画面では扱えません。', role: '役割不明', diff --git a/web/src/features/app/index.ts b/web/src/features/app/index.ts index a950169..cbd2dd9 100644 --- a/web/src/features/app/index.ts +++ b/web/src/features/app/index.ts @@ -3,7 +3,6 @@ export { AppPage } from './app-page' export { Comments } from './comments' export { OwnerLinks } from './owner-links' export { ScreenshotStrip } from './screenshots' -export { canEditApp } from './permissions' export { ProgressList } from './progress-list' export { useAppViews, type AppViews } from './use-app-views' export { versionLabel, appSecondLine } from '../../model/app' diff --git a/web/src/features/app/intro-gap-notice.test.tsx b/web/src/features/app/intro-gap-notice.test.tsx new file mode 100644 index 0000000..f142603 --- /dev/null +++ b/web/src/features/app/intro-gap-notice.test.tsx @@ -0,0 +1,70 @@ +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router' +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import { preserveLanguage } from '../../../test/language' +import { setLanguage } from '../../shell/language' +import { text } from './copy' +import { IntroGapNotice, introGapHref, introGaps } from './intro-gap-notice' + +const full = { + id: 'app-1', slug: 'keihi', group: { id: 'g', path: 'sales/east', name: '東日本' }, + description: '経費を申請します。', capabilities: ['申請する'], screenshots: [{ id: 's', caption: '', width: 1, height: 1 }], guide: '# つかいかた', +} + +let restoreLanguage: () => void +const storage = Object.getOwnPropertyDescriptor(globalThis, 'localStorage') +beforeEach(() => { + restoreLanguage = preserveLanguage() + setLanguage('ja') + Object.defineProperty(globalThis, 'localStorage', { configurable: true, value: window.localStorage }) + localStorage.clear() +}) +afterEach(() => { + if (storage) Object.defineProperty(globalThis, 'localStorage', storage) + else Reflect.deleteProperty(globalThis, 'localStorage') + restoreLanguage() +}) + +test('gaps are the empty parts in page order; the link goes to the first gap’s editor', () => { + expect(introGaps(full)).toEqual([]) + expect(introGaps({ ...full, description: ' ', guide: '\n' })).toEqual(['description', 'guide']) + expect(introGaps({ ...full, capabilities: [], screenshots: [] })).toEqual(['capabilities', 'screenshots']) + expect(introGapHref(full, ['description', 'screenshots'])).toBe('/sales/east/keihi/-/settings#name') + expect(introGapHref(full, ['capabilities'])).toBe('/sales/east/keihi/-/guide') + expect(introGapHref(full, ['screenshots'])).toBe('/sales/east/keihi#screenshots') + expect(text.maintainer.gapDetail([text.maintainer.gapItems.capabilities, text.maintainer.gapItems.screenshots])) + .toBe('「できること」と画面の写真がありません。利用者のホームで、何のアプリか伝わりません。') +}) + +test('the notice names the gaps, hides when complete, and stays closed for that app once dismissed', async () => { + const container = document.createElement('div') + document.body.append(container) + const root = createRoot(container) + const render = async (app: typeof full) => { + const rootRoute = createRootRoute({ component: () => }) + const router = createRouter({ routeTree: rootRoute.addChildren([createRoute({ getParentRoute: () => rootRoute, path: '/' })]), history: createMemoryHistory({ initialEntries: ['/'] }) }) + await router.load() + await act(async () => { root.render() }) + } + try { + await render(full) + expect(container.querySelector('[data-testid="intro-gap-notice"]')).toBeNull() + const lacking = { ...full, screenshots: [] } + await render(lacking) + const notice = container.querySelector('[data-testid="intro-gap-notice"]')! + expect(notice.textContent).toContain(text.maintainer.gapTitle) + expect(notice.textContent).toContain('画面の写真がありません。') + expect(notice.querySelector('a')?.getAttribute('href')).toBe('/sales/east/keihi#screenshots') + const dismiss = [...notice.querySelectorAll('button')].find((button) => button.textContent === text.maintainer.gapDismiss)! + await act(async () => { dismiss.click() }) + expect(container.querySelector('[data-testid="intro-gap-notice"]')).toBeNull() + await render({ ...lacking, id: 'app-2' }) + expect(container.querySelector('[data-testid="intro-gap-notice"]')).not.toBeNull() + await render(lacking) + expect(container.querySelector('[data-testid="intro-gap-notice"]')).toBeNull() + } finally { + await act(async () => { root.unmount() }) + container.remove() + } +}) diff --git a/web/src/features/app/intro-gap-notice.tsx b/web/src/features/app/intro-gap-notice.tsx new file mode 100644 index 0000000..0526bae --- /dev/null +++ b/web/src/features/app/intro-gap-notice.tsx @@ -0,0 +1,64 @@ +import { useState } from 'react' +import type { BusinessApp } from '../../model/contracts/console' +import { paths } from '../../routes/paths' +import { Button, LinkButton, Notice } from '../../ui' +import { text } from './copy' + +export type IntroPart = 'description' | 'capabilities' | 'screenshots' | 'guide' + +type IntroFields = Pick + +/** The parts of the store face (WF-03) a user sees nothing in, in the order the page shows them. */ +export function introGaps(app: IntroFields): IntroPart[] { + const gaps: IntroPart[] = [] + if (!app.description.trim()) gaps.push('description') + if (app.capabilities.length === 0) gaps.push('capabilities') + if (app.screenshots.length === 0) gaps.push('screenshots') + if (!app.guide.trim()) gaps.push('guide') + return gaps +} + +/** + * Where 「紹介を書く」 goes: the first gap's editor. The description is written in 設定; できること and つかいかた in + * the つかいかた tab; pictures in the strip right below this notice on 概要. + */ +export function introGapHref(app: Pick, gaps: readonly IntroPart[]): string { + if (gaps.includes('description')) return `${paths.app(app.group.path, app.slug, 'settings')}#name` + if (gaps.includes('capabilities') || gaps.includes('guide')) return paths.app(app.group.path, app.slug, 'guide') + return `${paths.app(app.group.path, app.slug)}#screenshots` +} + +const dismissKey = (appId: string) => `builder-console:intro-gap-dismissed:${appId}` + +// Static page imports also run outside a browser, before storage is installed. +function readDismissed(appId: string): boolean { + return typeof localStorage !== 'undefined' && localStorage.getItem(dismissKey(appId)) === '1' +} + +/** + * 「紹介がまだ足りません」 (ux-design §6.7, WF-05 ③): names the empty parts of the introduction until all four are + * filled. Closing it hides it for this app in this browser. + */ +export function IntroGapNotice({ app }: { app: Pick & IntroFields }) { + const [dismissed, setDismissed] = useState(() => readDismissed(app.id)) + const gaps = introGaps(app) + if (dismissed || gaps.length === 0) return null + const dismiss = () => { + localStorage.setItem(dismissKey(app.id), '1') + setDismissed(true) + } + return ( +
+ + {text.maintainer.gapWrite} + + } + > + {text.maintainer.gapDetail(gaps.map((gap) => text.maintainer.gapItems[gap]))} + +
+ ) +} diff --git a/web/src/features/app/intro-page.test.ts b/web/src/features/app/intro-page.test.ts new file mode 100644 index 0000000..737ef3c --- /dev/null +++ b/web/src/features/app/intro-page.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, test } from 'bun:test' +import { ORPCError } from '@orpc/client' +import { NO_APP_PERMISSIONS } from '../../model/contracts/console' +import { introOpenState } from './intro-page' +import { canPropose, ownerNames, proposalRefusal, proposalStatus } from './propose-button' +import { text } from './copy' + +const settled = { loading: false, failed: false } + +describe('whether the intro page can open the app (§6.4, §9)', () => { + test('a URL opens it and nothing more is said; 問題あり keeps it open and says so', () => { + expect(introOpenState(settled, { status: 'live', url: 'https://app.example.test' })).toBe('ready') + expect(introOpenState(settled, { status: 'deploying', url: 'https://app.example.test' })).toBe('ready') + expect(introOpenState(settled, { status: 'failed', url: 'https://app.example.test' })).toBe('trouble') + }) + + test('no URL yet is 準備中 and cannot be opened, even when the app is 問題あり', () => { + expect(introOpenState(settled, { status: 'deploying' })).toBe('preparing') + expect(introOpenState(settled, { status: 'unknown' })).toBe('preparing') + expect(introOpenState(settled, { status: 'failed' })).toBe('preparing') + }) + + test('an unanswered or failed platform read claims no state', () => { + expect(introOpenState({ loading: true, failed: false }, { status: 'unknown' })).toBe('loading') + expect(introOpenState({ loading: false, failed: true }, { status: 'live', url: 'https://app.example.test' })).toBe('unavailable') + }) +}) + +describe('proposals by people who do not maintain the app (§6.6)', () => { + test('only someone who may propose and does not maintain a bound app gets the button', () => { + expect(canPropose({ stackId: 's', permissions: { ...NO_APP_PERMISSIONS, use: true, propose: true } })).toBe(true) + expect(canPropose({ stackId: 's', permissions: { ...NO_APP_PERMISSIONS, use: true, propose: true, maintain: true } })).toBe(false) + expect(canPropose({ stackId: 's', permissions: { ...NO_APP_PERMISSIONS, use: true } })).toBe(false) + expect(canPropose({ stackId: null, permissions: { ...NO_APP_PERMISSIONS, use: true, propose: true } })).toBe(false) + }) + + test('the status follows the session and its proposal phase; unread, withdrawn, expired and unknown phases say nothing', () => { + const known = (value: string) => ({ kind: 'known', value }) as never + expect(proposalStatus(undefined, undefined)).toBeUndefined() + expect(proposalStatus({}, undefined)).toBe('drafting') + expect(proposalStatus({ proposalId: 'p' }, undefined)).toBeUndefined() + for (const phase of ['Proposed', 'Accepted', 'Applying']) expect(proposalStatus({ proposalId: 'p' }, known(phase))).toBe('reviewing') + expect(proposalStatus({ proposalId: 'p' }, known('ChangesRequested'))).toBe('changes') + expect(proposalStatus({ proposalId: 'p' }, known('Applied'))).toBe('applied') + expect(proposalStatus({ proposalId: 'p' }, known('Rejected'))).toBe('rejected') + expect(proposalStatus({ proposalId: 'p' }, known('Withdrawn'))).toBeUndefined() + expect(proposalStatus({ proposalId: 'p' }, known('Expired'))).toBeUndefined() + expect(proposalStatus({ proposalId: 'p' }, { kind: 'unknown', value: 'Later' } as never)).toBeUndefined() + }) + + test('only the server refusal for a closed contribution scope is worded as such', () => { + const refused = new ORPCError('FORBIDDEN', { status: 403, data: { error: { code: 'contribution_not_accepted', message: 'このアプリは、いま提案を受け付けていません。' } } }) + expect(proposalRefusal(refused)).toBe(text.propose.refused) + expect(proposalRefusal(new ORPCError('FORBIDDEN', { status: 403, data: { error: { code: 'forbidden', message: 'no' } } }))).toBeUndefined() + expect(proposalRefusal(new Error('network'))).toBeUndefined() + }) + + test('the owners are named in 「△△ さん」 without people the server can no longer resolve', () => { + const person = { id: 'p1', subject: 's', pending: false, email: 'a@example.test', displayName: '鈴木 一郎', avatarVersion: null } + expect(ownerNames({ owners: [person] })).toBe('鈴木 一郎') + expect(ownerNames({ owners: [] })).toBeUndefined() + }) +}) diff --git a/web/src/features/app/intro-page.tsx b/web/src/features/app/intro-page.tsx new file mode 100644 index 0000000..1c2a221 --- /dev/null +++ b/web/src/features/app/intro-page.tsx @@ -0,0 +1,174 @@ +// The app's introduction for people who use it but do not maintain it +// (ux-design §6.5, WF-03/04/07): no tabs, sharing, status sentence or +// engineering details, only what the app is, a way to open it, and a way to +// reach its owners. `EntryPage` (people who cannot open the app) shares the +// layout; only the primary action differs (「使いたい」 vs 「アプリを開く」). +import { useNavigate, useLocation } from '@tanstack/react-router' +import { ArrowLeft, ExternalLink } from 'lucide-react' +import type { ReactNode } from 'react' +import { useMe } from '../../api/queries/console' +import { copy } from '../../copy' +import type { AppView } from '../../model/app' +import type { BusinessApp, DirectoryEntry } from '../../model/contracts/console' +import { paths } from '../../routes/paths' +import { AppIcon, Button, CopyButton, HrefLink, LinkButton, LoadFailed, Markdown, Notice, Section, useDocumentTitle } from '../../ui' +import { AppAbout } from './app-about' +import { Comments } from './comments' +import { text } from './copy' +import { OwnerContact } from './owner-contact' +import { OwnerLinks } from './owner-links' +import { ownerNames, ProposalStatusLine, ProposeButton } from './propose-button' +import { ScreenshotStrip } from './screenshots' +import { useAppViews } from './use-app-views' + +type IntroSubject = Pick + +/** + * WF-03's order: back link, header, primary actions with the state under them, + * pictures, about, guide, feedback. `propose` sits right of the name (under the + * primary actions on phones, WF-08) with its status line above the actions. + */ +export function IntroLayout({ subject, banner, propose, proposeStatus, primary, state, guide, feedback }: { + subject: IntroSubject + banner?: ReactNode + propose?: ReactNode + proposeStatus?: ReactNode + primary: ReactNode + state?: ReactNode + guide?: string + feedback: ReactNode +}) { + useDocumentTitle(subject.displayName) + return ( +
+
+ {banner} + + {text.intro.back} + +
+
+ +
+

{subject.displayName}

+

+ {text.intro.ofGroup(subject.group.name)} + ・ + {text.intro.owner} +

+
+
+ {propose ?
{propose}
: null} + {proposeStatus ?
{proposeStatus}
: null} +
{primary}
+ {state ?
{state}
: null} +
+
+ + + + {guide?.trim() ? ( +
+ +
+ ) : null} + {feedback} +
+ ) +} + +/** 「担当者に伝える」: the comment thread re-headed for the people who use the app, with the owners' mail beside it. */ +export function FeedbackSection({ subject, canDeleteAny, unavailable }: { + subject: Pick + canDeleteAny: boolean + /** A draft app has no thread yet: the heading stays and says why. */ + unavailable?: boolean +}) { + const heading = { title: text.feedback.title, lead: text.feedback.lead, actions: } + return unavailable ? ( +

{text.comments.draft}

+ ) : +} + +/** The intro's large primary action (アプリを開く / 使いたい): 44px tall, full width on phones (WF-08). */ +export const INTRO_PRIMARY = 'h-11 w-full px-5 text-base md:h-11 sm:w-auto' + +/** + * Whether the app can be opened, from the platform view (§6.4 table, §9): + * - `loading`: the platform has not answered yet; + * - `unavailable`: the platform could not be read; no state is claimed; + * - `trouble`: 問題あり with a URL; the button stays usable (WF-07 E); + * - `preparing`: no URL yet, 問題あり included; the button cannot be pressed (WF-07 D); + * - `ready`: open it; nothing more is said. + */ +export type IntroOpenState = 'loading' | 'unavailable' | 'trouble' | 'preparing' | 'ready' + +export function introOpenState(views: { loading: boolean; failed: boolean }, view: Pick): IntroOpenState { + if (views.failed) return 'unavailable' + if (views.loading && !view.url) return 'loading' + if (!view.url) return 'preparing' + return view.status === 'failed' ? 'trouble' : 'ready' +} + +/** `?as=user` on the app page: a maintainer previews what people who use the app see (WF-05 ②). */ +export function useUserPreview(): { active: boolean; exit: () => void } { + const location = useLocation() + const navigate = useNavigate() + const search = new URLSearchParams(location.searchStr) + const active = search.get('as') === 'user' + return { + active, + exit: () => { + search.delete('as') + void navigate({ href: `${location.pathname}${search.size ? `?${search}` : ''}`, replace: true }) + }, + } +} + +/** The intro page for one app the caller may use; `preview` shows it to a maintainer under a banner. */ +export function IntroPage({ app, onExitPreview }: { app: BusinessApp; onExitPreview?: () => void }) { + const me = useMe().data + const projectId = me.projectId + const views = useAppViews(projectId) + const view = views.viewFor(app) + const state = introOpenState(views, view) + const owner = ownerNames(app) + const openLabel = <>{text.intro.open} + + return ( + +

{text.intro.preview}

+ +
+ ) : undefined} + propose={} + proposeStatus={} + primary={view.url && state !== 'unavailable' ? ( + <> + {openLabel} + + + ) : ( + + )} + state={state === 'unavailable' ? + : state === 'preparing' ? ( + +

{text.intro.preparing}

+ {owner ?

{text.intro.askSoon(owner)}

: null} +
+ ) : state === 'trouble' ? ( + +

{text.intro.trouble}

+ {owner ?

{text.intro.askStill(owner)}

: null} +
+ ) : undefined} + guide={app.guide} + // Users delete only their own comments; a maintainer's ?as=user preview shows the same, and moderation stays on the guide tab. + feedback={} + /> + ) +} diff --git a/web/src/features/app/logs-tab.test.tsx b/web/src/features/app/logs-tab.test.tsx index d24b71b..40687ad 100644 --- a/web/src/features/app/logs-tab.test.tsx +++ b/web/src/features/app/logs-tab.test.tsx @@ -11,7 +11,8 @@ const app = businessAppOf({ id: 'app-1', slug: 'shop', displayName: 'Shop', description: '', icon: '', tags: [], guide: '', capabilities: [], screenshots: [], group: { id: 'sales', path: 'sales', name: 'Sales' }, owners: [person], stackId: 'shop-stack', appName: 'shop', share: { scope: 'public', groupIds: [], extraPersonIds: [] }, - createdBy: person, createdAt: '2026-10-08T00:00:00Z', updatedAt: '2026-10-08T00:00:00Z', + createdBy: person, createdAt: '2026-10-08T00:00:00Z', updatedAt: '2026-10-08T00:00:00Z', contribution: { scope: 'group' }, + permissions: { use: true, comment: true, propose: true, maintain: true, data: true }, }) const view: AppView = { status: 'live', label: '公開中', text: '', second: '', draft: false, url: 'https://shop.example.test/', diff --git a/web/src/features/app/mutations.ts b/web/src/features/app/mutations.ts index 70abff2..ea6dcf1 100644 --- a/web/src/features/app/mutations.ts +++ b/web/src/features/app/mutations.ts @@ -10,6 +10,7 @@ import { consoleKeys, createPerson, declineAccessRequest, + markCommentsSeen, postComment, removeApp, removeComment, @@ -18,6 +19,7 @@ import { searchPeople, updateApp, uploadScreenshot, + type ContributionInput, type UpdateAppInput, writeAppCache, } from '../../api/queries/console' @@ -54,6 +56,21 @@ export function useUpdateApp(app: BusinessApp) { }) } +/** Who may propose improvements (maintainers only): the same PATCH as every other app field, answered with the app. */ +export const updateContribution = (appId: string, scope: ContributionInput['scope']): Promise => updateApp(appId, { contribution: { scope } }) + +/** `updateContribution` for one app; its answer enters the app cache like any app write. */ +export function useUpdateContribution(app: BusinessApp) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (scope: ContributionInput['scope']) => updateContribution(app.id, scope), + onSuccess: async (updated) => { + await writeAppCache(queryClient, updated) + await queryClient.invalidateQueries({ queryKey: CONSOLE_ROOT }) + }, + }) +} + /** Reads the app record back: the confirmation after an app write whose answer could not be read. */ export function useAppReadBack(appId: string) { const queryClient = useQueryClient() @@ -89,7 +106,21 @@ export function useRemoveComment(appId: string) { return useMutation({ mutationFn: (commentId: string) => removeComment(appId, commentId), onSettled: async () => { - await queryClient.invalidateQueries({ queryKey: consoleKeys.comments(appId) }) + await Promise.all([ + queryClient.invalidateQueries({ queryKey: consoleKeys.comments(appId) }), + queryClient.invalidateQueries({ queryKey: consoleKeys.inbox }), + ]) + }, + }) +} + +/** Maintainers: the thread so far counts as read; the inbox feedback count is read back after any outcome. */ +export function useMarkCommentsSeen(appId: string) { + const queryClient = useQueryClient() + return useMutation({ + mutationFn: () => markCommentsSeen(appId), + onSettled: async () => { + await queryClient.invalidateQueries({ queryKey: consoleKeys.inbox }) }, }) } @@ -126,6 +157,7 @@ export function useApproveAccessRequest(appId: string) { await Promise.all([ queryClient.invalidateQueries({ queryKey: consoleKeys.accessRequestsOfApp(appId) }), queryClient.invalidateQueries({ queryKey: consoleKeys.accessRequestsPending }), + queryClient.invalidateQueries({ queryKey: consoleKeys.inbox }), ]) }, }) @@ -139,6 +171,7 @@ export function useDeclineAccessRequest(appId: string) { await Promise.all([ queryClient.invalidateQueries({ queryKey: consoleKeys.accessRequestsOfApp(appId) }), queryClient.invalidateQueries({ queryKey: consoleKeys.accessRequestsPending }), + queryClient.invalidateQueries({ queryKey: consoleKeys.inbox }), ]) }, }) diff --git a/web/src/features/app/overview-tab.tsx b/web/src/features/app/overview-tab.tsx index e1c8767..c7a53db 100644 --- a/web/src/features/app/overview-tab.tsx +++ b/web/src/features/app/overview-tab.tsx @@ -12,6 +12,7 @@ import { deriveCreateProgress, repositoryLabel, showsCreateProgress, type Progre import { paths } from '../../routes/paths' import { ActionError, Button, Card, CardBody, CardHeader, Disclosure, HrefLink, LinkButton, StatusPill } from '../../ui' import { AppAbout, GuideSummary } from './app-about' +import { IntroGapNotice } from './intro-gap-notice' import { text } from './copy' import { DatabaseChanges } from './database-changes' import { ProgressList } from './progress-list' @@ -21,6 +22,20 @@ import { OwnerLinks } from './owner-links' import { isSourceBuildFailed } from './platform' import { ScreenshotStrip } from './screenshots' import { ToolsPanel } from './tools-panel' +import { VoicesPanel } from './voices-panel' + +/** 「利用者にはこう見えます →」 (WF-05 ②): the same page drawn as a user sees it (`?as=user`, app-page.tsx). */ +export function UserViewLink({ app }: { app: Pick }) { + return ( + + {text.maintainer.userView} + + ) +} export function OverviewTab({ projectId, @@ -73,13 +88,24 @@ export function OverviewTab({ const face = (
{/* Pictures are served only for bound apps, so a draft has nowhere to show them yet. */} - {app.stackId !== null ? : null} + {app.stackId !== null ?
: null}
) + // A maintainer's additions (ux-design §6.7): what the introduction still lacks, then what users have said. + // A bound app only: a draft has no users yet. AI improvement never competes with an unfinished build session. + const improvable = !(view.build && view.build.phase !== 'done') + const maintainer = canEdit && !creating && app.stackId !== null ? ( + // Keyed by app: the dismissal and the pinned new count belong to one app's page. +
+ + +
+ ) : null + const details = (
@@ -201,7 +227,7 @@ export function OverviewTab({
) - return
{creating ? <>{details}{face} : <>{face}{details}}
+ return
{maintainer}{creating ? <>{details}{face} : <>{face}{details}}
} function Row({ label, children }: { label: string; children: ReactNode }) { diff --git a/web/src/features/app/owner-contact.tsx b/web/src/features/app/owner-contact.tsx index 1c53d3a..d220ed1 100644 --- a/web/src/features/app/owner-contact.tsx +++ b/web/src/features/app/owner-contact.tsx @@ -3,12 +3,16 @@ import { isUnknownPerson, type BusinessApp, type Person } from '../../model/cont import { LinkButton } from '../../ui' import { text } from './copy' -/** Only resolved owners with a usable address are contacted; an unknown person has no contact to invent. */ -export function OwnerContact({ app }: { app: Pick }) { +/** + * Only resolved owners with a usable address are contacted; an unknown person has no contact to invent. + * `compact` is the small 「メールで連絡する」 beside a heading: without an address it shows nothing. + */ +export function OwnerContact({ app, compact = false }: { app: Pick; compact?: boolean }) { const owners = app.owners.filter((owner): owner is Person => !isUnknownPerson(owner) && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(owner.email)) - return owners.length ? ( - encodeURIComponent(owner.email)).join(',')}?subject=${encodeURIComponent(text.overview.emailSubject(app.displayName))}`} icon={}> - {text.overview.ask(owners.map((owner) => owner.displayName))} + if (!owners.length) return compact ? null :

{text.overview.noContact}

+ return ( + encodeURIComponent(owner.email)).join(',')}?subject=${encodeURIComponent(text.overview.emailSubject(app.displayName))}`} icon={}> + {compact ? text.feedback.mail : text.overview.ask(owners.map((owner) => owner.displayName))} - ) :

{text.overview.noContact}

+ ) } diff --git a/web/src/features/app/permissions.ts b/web/src/features/app/permissions.ts deleted file mode 100644 index debed12..0000000 --- a/web/src/features/app/permissions.ts +++ /dev/null @@ -1,10 +0,0 @@ -import { canManageGroup, isUnknownPerson, type BusinessApp, type Me } from '../../model/contracts/console' - -/** - * Owners, managers of the owning group (inherited management included), and console admins may edit. - * An owner the server can no longer resolve grants nothing. - */ -export function canEditApp(app: Pick, me: Me | undefined): boolean { - if (!me) return false - return app.owners.some((owner) => !isUnknownPerson(owner) && owner.id === me.person.id) || canManageGroup(me, app.group.id) -} diff --git a/web/src/features/app/propose-button.tsx b/web/src/features/app/propose-button.tsx new file mode 100644 index 0000000..d2c1a75 --- /dev/null +++ b/web/src/features/app/propose-button.tsx @@ -0,0 +1,129 @@ +// 「直しを提案する」 (ux-design §6.6, WF-04): people who may propose but not +// maintain start the same improvement session as 「AIで直す」; what differs is +// the wording, that the owners review the result, and the one-line status of +// the caller's own proposal while it is moving. +import { useQuery } from '@tanstack/react-query' +import { X } from 'lucide-react' +import { useState } from 'react' +import { draftsOptions } from '../../api/queries/build' +import { proposalOptions } from '../../api/queries/proposal' +import { platformErrorEnvelope } from '../../api/platform-error' +import type { OpenValue } from '../../api/boundary' +import { isOneOf } from '../../model/contracts/build' +import type { BusinessApp } from '../../model/contracts/console' +import { resolvedPeople } from '../../model/directory' +import type { ProposalPhase } from '../../model/contracts/proposal' +import { improvementFor } from '../../model/improve' +import { paths } from '../../routes/paths' +import { HrefLink, IconButton } from '../../ui' +import { ImproveButton } from '../improve/entry' +import { proposalTerminal } from '../proposals/model' +import { text } from './copy' + +/** Shown only to people who may propose and do not maintain the app; maintainers keep 「AIで直す」. */ +export function canPropose(app: Pick): boolean { + return app.permissions.propose && !app.permissions.maintain && !!app.stackId +} + +/** The owners as one name for 「△△ さん」; undefined when none can be named (the copy then says 「担当者」). */ +export function ownerNames(app: Pick): string | undefined { + const names = resolvedPeople(app.owners).map((owner) => owner.displayName) + return names.length ? text.names.people(names) : undefined +} + +/** The server refuses a proposal to an app whose contribution scope is `off` (console_authority). */ +export function proposalRefusal(error: unknown): string | undefined { + const envelope = platformErrorEnvelope(error) + return envelope?.status === 403 && envelope.code === 'contribution_not_accepted' ? text.propose.refused : undefined +} + +/** + * The caller's own proposal, from their newest open improvement session and its proposal phase: + * - `drafting`: talking or fixing, nothing sent yet → 続きから直す + * - `reviewing`: sent, the owners decide or apply → 提案を見る + * - `changes`: the owners asked for another round → 続きから直す + * - `applied` / `rejected`: closed; shown until dismissed + * Nothing while the proposal is unread, withdrawn, expired or in a phase this console does not know. + */ +export type ProposalStatus = 'drafting' | 'reviewing' | 'changes' | 'applied' | 'rejected' + +export function proposalStatus(session: { proposalId?: string } | undefined, phase: OpenValue | undefined): ProposalStatus | undefined { + if (!session) return undefined + if (!session.proposalId) return 'drafting' + if (!phase) return undefined + if (isOneOf(phase, 'Proposed', 'Accepted', 'Applying')) return 'reviewing' + if (isOneOf(phase, 'ChangesRequested')) return 'changes' + if (isOneOf(phase, 'Applied')) return 'applied' + if (isOneOf(phase, 'Rejected')) return 'rejected' + return undefined +} + +/** A closed proposal's line stays dismissed in this browser: `.` = '1'. */ +const DISMISSED_KEY = 'builder-console.proposal-status-dismissed' + +/** The newest open improvement session for this app and its proposal; both reads are shared with ImproveButton's cache. */ +function useOwnProposal(projectId: string, stackId: string) { + const drafts = useQuery(draftsOptions(projectId)) + const session = improvementFor(drafts.data?.data, stackId) + const proposal = useQuery(proposalOptions(projectId, session?.proposalId)) + return { session, proposal: proposal.data, status: proposalStatus(session, proposal.data?.phase) } +} + +/** The button: 「直しを提案する」, or 「続きから直す」 while the caller's proposal is still open. */ +export function ProposeButton({ app, projectId }: { app: BusinessApp; projectId: string }) { + const stackId = app.stackId + if (!stackId || !canPropose(app)) return null + return +} + +function ProposeAction({ app, projectId, stackId }: { app: BusinessApp; projectId: string; stackId: string }) { + const { session, proposal } = useOwnProposal(projectId, stackId) + const owner = ownerNames(app) + const open = session !== undefined && !(proposal && proposalTerminal(proposal.phase)) + return ( + text.propose.description(name, owner) }} + refusal={proposalRefusal} + /> + ) +} + +/** One line under the header while the caller's own proposal is moving (§6.6 table). */ +export function ProposalStatusLine({ app, projectId }: { app: BusinessApp; projectId: string }) { + const stackId = app.stackId + if (!stackId || !canPropose(app)) return null + return +} + +function OwnProposalStatus({ app, projectId, stackId }: { app: BusinessApp; projectId: string; stackId: string }) { + const { session, proposal, status } = useOwnProposal(projectId, stackId) + const [dismissed, setDismissed] = useState() + if (!session || !status) return null + const proposalId = session.proposalId + if (proposalId && (dismissed === proposalId || localStorage.getItem(`${DISMISSED_KEY}.${proposalId}`) === '1')) return null + const owner = ownerNames(app) + const sentence = status === 'drafting' ? text.propose.drafting + : status === 'reviewing' ? text.propose.reviewing(owner) + : status === 'changes' ? text.propose.changesRequested(owner) + : status === 'applied' ? text.propose.applied : text.propose.rejected + // 続きから直す (drafting, changes) is the button itself, which says so while the proposal is open; the line adds only what it cannot. + const action = (status === 'reviewing' || status === 'rejected') && proposal ? { href: paths.proposal(proposal.id), label: text.propose.view } : undefined + const closable = (status === 'applied' || status === 'rejected') && proposalId + return ( +
+

{sentence}

+
+ {action ? {action.label} : null} + {closable ? } onClick={() => { + localStorage.setItem(`${DISMISSED_KEY}.${proposalId}`, '1') + setDismissed(proposalId) + }} /> : null} +
+
+ ) +} diff --git a/web/src/features/app/settings-tab.tsx b/web/src/features/app/settings-tab.tsx index 818c818..f5d8abf 100644 --- a/web/src/features/app/settings-tab.tsx +++ b/web/src/features/app/settings-tab.tsx @@ -7,6 +7,7 @@ import { Button, Notice } from '../../ui' import { text } from './copy' import { deleteHelpText } from './delete-dialog' import { webScope, type SourceRepositoryRef } from './platform' +import { ContributionSection } from './settings/contribution-section' import { EnvSection } from './settings/env-section' import { GeneralSection } from './settings/general-section' import { SettingsCard } from './settings/parts' @@ -45,6 +46,7 @@ export function SettingsTab({ +
diff --git a/web/src/features/app/settings/contribution-section.test.tsx b/web/src/features/app/settings/contribution-section.test.tsx new file mode 100644 index 0000000..0d47085 --- /dev/null +++ b/web/src/features/app/settings/contribution-section.test.tsx @@ -0,0 +1,136 @@ +// 提案の受け付け (WF-06) over the real section, queries, gateway and contracts against the in-memory Console mock: +// the switch shows the rule it makes, turning it off and saving PATCHes `contribution.scope` = `off` and the +// record follows; an app open to the company keeps `company` while the switch stays on; an unknown scope offers +// nothing to save. +import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test' +import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query' +import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterContextProvider } from '@tanstack/react-router' +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { appQuery, meQuery } from '../../../api/queries/console' +import { queryClient as appQueryClient } from '../../../api/queries/shared' +import { createConsoleMockFetch, resetMocks, type ConsoleMockFetch } from '../../../api/testing/console-mock-fetch' +import { copy } from '../../../copy' +import type { BusinessApp } from '../../../model/contracts/console' +import { setLanguage } from '../../../shell/language' +import { UnsavedChangesProvider } from '../../../ui/use-unsaved-changes-guard' +import { preserveLanguage } from '../../../../test/language' +import { text } from '../copy' +import { ContributionSection, contributionScopeFor } from './contribution-section' + +const APP = 'a-keihi' + +let mock: ConsoleMockFetch +let client: QueryClient +let root: Root | undefined +let container: HTMLDivElement +const restore: (() => void)[] = [] +const originalFetch = globalThis.fetch + +beforeEach(async () => { + restore.push(preserveLanguage()) + setLanguage('ja') + await resetMocks() + mock = createConsoleMockFetch() + globalThis.fetch = mock.fetch as typeof globalThis.fetch + const warn = spyOn(console, 'warn').mockImplementation(() => {}) + // Radix Switch checks `closest('form') instanceof HTMLFormElement`; the shared DOM preload does not expose it. + const form = Object.getOwnPropertyDescriptor(globalThis, 'HTMLFormElement') + Object.defineProperty(globalThis, 'HTMLFormElement', { configurable: true, value: window.HTMLFormElement }) + restore.push(() => form ? Object.defineProperty(globalThis, 'HTMLFormElement', form) : Reflect.deleteProperty(globalThis, 'HTMLFormElement')) + restore.push(() => warn.mockRestore()) +}) + +afterEach(async () => { + await act(async () => { root?.unmount() }) + root = undefined + container?.remove() + client?.clear() + globalThis.fetch = originalFetch + for (const undo of restore.splice(0).reverse()) undo() +}) + +async function settle(rounds = 12) { + for (let tick = 0; tick < rounds; tick++) await act(async () => { await Bun.sleep(5) }) +} + +/** The section on the live app record, the way the settings tab passes it; `override` replaces the record once. */ +async function render(override?: (app: BusinessApp) => BusinessApp) { + client = new QueryClient({ defaultOptions: { queries: { ...appQueryClient.getDefaultOptions().queries, retryDelay: 0, refetchInterval: false, refetchOnWindowFocus: false } } }) + await client.fetchQuery(meQuery) + const app = await client.fetchQuery(appQuery(APP)) + if (override) client.setQueryData(appQuery(APP).queryKey, override(app)) + function Live() { + const current = useQuery({ ...appQuery(APP), staleTime: Infinity }).data + return current ? : null + } + const rootRoute = createRootRoute() + const page = createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => null }) + const router = createRouter({ routeTree: rootRoute.addChildren([page]), history: createMemoryHistory({ initialEntries: ['/'] }) }) + await router.load() + container = document.createElement('div') + document.body.append(container) + root = createRoot(container) + await act(async () => { + root!.render() + }) + await settle() + return app +} + +const section = () => container.querySelector('#contribution')! +const toggle = () => section().querySelector('[role="switch"]')! +const saveButton = () => [...section().querySelectorAll('button')].find((item) => item.textContent?.trim() === copy.app.settings.save)! +const patches = () => mock.requests.filter((item) => item.method === 'PATCH' && item.path === `/api/console/apps/${APP}`) + +test('on writes group, keeps an existing company scope, and off writes off', () => { + expect(contributionScopeFor(true, 'off')).toBe('group') + expect(contributionScopeFor(true, 'group')).toBe('group') + expect(contributionScopeFor(true, 'company')).toBe('company') + expect(contributionScopeFor(false, 'company')).toBe('off') +}) + +test('the switch shows the rule; turning it off and saving PATCHes off and the record follows', async () => { + const app = await render() + expect(app.contribution.scope).toEqual({ kind: 'known', value: 'group' }) + expect(section().getAttribute('aria-label')).toBe(text.settings.contribution) + expect(toggle().getAttribute('aria-checked')).toBe('true') + expect(section().textContent).toContain(text.settings.contributionSwitch) + expect(section().textContent).toContain(text.settings.contributionHelp) + const rule = section().querySelector('[data-testid="contribution-rule"]')! + expect(rule.textContent).toContain(text.settings.contributionWhoGroup(app.group.name)) + expect(rule.textContent).toContain(text.settings.contributionReviewer) + expect(saveButton().disabled).toBe(true) + + await act(async () => { toggle().click() }) + await settle(2) + expect(toggle().getAttribute('aria-checked')).toBe('false') + expect(section().textContent).toContain(text.settings.contributionOff) + expect(section().querySelector('[data-testid="contribution-rule"]')).toBeNull() + expect(saveButton().disabled).toBe(false) + + await act(async () => { section().querySelector('form')!.requestSubmit() }) + await settle() + expect(patches().map((item) => item.status)).toEqual([200]) + expect(client.getQueryData(appQuery(APP).queryKey)?.contribution.scope).toEqual({ kind: 'known', value: 'off' }) + expect(toggle().getAttribute('aria-checked')).toBe('false') + expect(section().querySelector('[role="status"]')?.textContent).toBe(copy.app.settings.saved) + expect(saveButton().disabled).toBe(true) + // The mock stored it: a fresh read says off. + const reread = await (await mock.fetch(`/api/console/apps/${APP}`)).json() as { contribution: { scope: string } } + expect(reread.contribution.scope).toBe('off') +}) + +test('an app open to the company stays company while on, with the company rule', async () => { + await render((app) => ({ ...app, contribution: { scope: { kind: 'known', value: 'company' } } })) + expect(toggle().getAttribute('aria-checked')).toBe('true') + expect(section().querySelector('[data-testid="contribution-rule"]')!.textContent).toContain(text.settings.contributionWhoCompany) + expect(saveButton().disabled).toBe(true) +}) + +test('an unknown scope is named as such and offers no switch or save', async () => { + await render((app) => ({ ...app, contribution: { scope: { kind: 'unknown' } } })) + expect(section().textContent).toContain(text.unsupported.contribution) + expect(toggle().disabled).toBe(true) + expect(saveButton().disabled).toBe(true) +}) diff --git a/web/src/features/app/settings/contribution-section.tsx b/web/src/features/app/settings/contribution-section.tsx new file mode 100644 index 0000000..f2492a6 --- /dev/null +++ b/web/src/features/app/settings/contribution-section.tsx @@ -0,0 +1,98 @@ +import { Switch } from 'radix-ui' +import { useId, useState } from 'react' +import { isUnknownPerson, type BusinessApp, type ContributionScope, type Person } from '../../../model/contracts/console' +import { ActionError, Notice, useUnsavedChangesGuard } from '../../../ui' +import { text } from '../copy' +import { useAppReadBack, useUpdateContribution } from '../mutations' +import { UnconfirmedNotice, useWriteConfirmation } from '../notices' +import { SaveRow, SettingsCard } from './parts' + +/** + * The scope the switch writes (ux-design §6.8): on = `group`. `company` is not offered yet, so an app already + * open to the company keeps it while the switch stays on; turning it off is `off`. + */ +export function contributionScopeFor(accepting: boolean, saved: ContributionScope): ContributionScope { + if (!accepting) return 'off' + return saved === 'company' ? 'company' : 'group' +} + +/** 提案の受け付け (WF-06): one switch, the rule it makes in two rows, and its own 保存. */ +export function ContributionSection({ app, canEdit }: { app: BusinessApp; canEdit: boolean }) { + const mutation = useUpdateContribution(app) + const confirmation = useWriteConfirmation([mutation.error], mutation.reset, useAppReadBack(app.id)) + const scope = app.contribution.scope + const saved = scope.kind === 'known' ? scope.value : undefined + const [accepting, setAccepting] = useState(saved !== 'off') + // The record changed under the form (saved here, or read back): the switch follows it. + const [shownSaved, setShownSaved] = useState(saved) + if (shownSaved !== saved) { + setShownSaved(saved) + setAccepting(saved !== 'off') + } + const next = saved ? contributionScopeFor(accepting, saved) : undefined + const dirty = next !== undefined && next !== saved + useUnsavedChangesGuard(canEdit && dirty && !mutation.isPending, text.settings.unsaved(text.settings.sections.contribution)) + const switchId = useId() + const owners = app.owners.filter((owner): owner is Person => !isUnknownPerson(owner)).map((owner) => owner.displayName) + const disabled = !canEdit || !saved || mutation.isPending || confirmation.unconfirmed + + return ( + + { + event.preventDefault() + if (next && dirty && !disabled) mutation.mutate(next) + }} + > + {!saved ? {text.unsupported.contribution} : null} +
+ + + +
+ +

+ {accepting ? text.settings.contributionHelp : text.settings.contributionOff} +

+
+
+ {accepting ? ( +
+
+
{text.settings.contributionWho}
+
+ {next === 'company' ? text.settings.contributionWhoCompany : text.settings.contributionWhoGroup(app.group.name)} +
+
+
+
{text.settings.contributionReviewer}
+
{text.settings.contributionReviewerValue(text.names.people(owners))}
+
+
+ ) : null} +
+ + {confirmation.unconfirmed ? ( +
+ void confirmation.confirm()} confirming={confirmation.confirming} /> +
+ ) : mutation.isError ? ( +
+ +
+ ) : null} +
+ +
+ ) +} diff --git a/web/src/features/app/voices-panel.test.tsx b/web/src/features/app/voices-panel.test.tsx new file mode 100644 index 0000000..6a329c2 --- /dev/null +++ b/web/src/features/app/voices-panel.test.tsx @@ -0,0 +1,93 @@ +import { afterEach, expect, test } from 'bun:test' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterContextProvider } from '@tanstack/react-router' +import { act } from 'react' +import { createRoot } from 'react-dom/client' +import { appQuery, commentsQuery, consoleKeys, meQuery } from '../../api/queries/console' +import { consoleRoutes } from '../../dev/mock-console' +import { platformRoutes } from '../../dev/mock-platform' +import type { AppComment } from '../../model/contracts/console' +import { VoicesPanel } from './voices-panel' + +const APP_ID = 'a-keihi' +const originalFetch = globalThis.fetch +const cleanups: (() => Promise)[] = [] +afterEach(async () => { + for (const cleanup of cleanups.splice(0)) await cleanup() + globalThis.fetch = originalFetch +}) + +async function settle() { + for (let tick = 0; tick < 4; tick++) await act(async () => { await Bun.sleep(5) }) +} + +async function renderPanel({ unread, author, delayed = false }: { unread: number; author?: 'viewer' | 'other'; delayed?: boolean }) { + const writes: { keepalive: boolean | undefined }[] = [] + let comments: AppComment[] = [] + const { promise, resolve: releaseComments } = Promise.withResolvers() + const commentsReady = delayed ? promise : Promise.resolve() + globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const request = input instanceof Request ? input : new Request(new URL(String(input), window.location.href), init) + const url = new URL(request.url) + if (request.method === 'GET' && url.pathname === `/api/console/apps/${APP_ID}/comments`) { + await commentsReady + return Response.json(comments) + } + if (request.method === 'GET' && url.pathname === '/api/console/inbox') { + return Response.json({ items: unread > 0 ? [{ kind: 'feedback', app: { id: APP_ID, path: 'sales/east/team-a/keihi', displayName: '経費精算', icon: '💴' }, count: unread, since: '2026-10-10T09:00:00.000Z' }] : [] }) + } + if (request.method === 'POST' && url.pathname === `/api/console/apps/${APP_ID}/comments/seen`) writes.push({ keepalive: init?.keepalive }) + return await (url.pathname.startsWith('/api/console/') ? consoleRoutes : platformRoutes)(request, url) ?? new Response(null, { status: 404 }) + }) as typeof globalThis.fetch + for (const path of ['/api/v1/__mock/reset', '/api/console/__mock/reset']) await fetch(path, { method: 'POST' }) + const client = new QueryClient({ defaultOptions: { queries: { retry: false, staleTime: Infinity, refetchInterval: false } } }) + const [me, app] = await Promise.all([client.fetchQuery(meQuery), client.fetchQuery(appQuery(APP_ID))]) + if (author) comments = [{ id: 'c-voices', appId: APP_ID, author: { ...me.person, id: author === 'viewer' ? me.person.id : 'p-other' }, body: '使ってみました', createdAt: '2026-10-10T09:00:00.000Z' }] + const rootRoute = createRootRoute() + const route = createRoute({ getParentRoute: () => rootRoute, path: '$', component: () => null }) + const router = createRouter({ routeTree: rootRoute.addChildren([route]), history: createMemoryHistory({ initialEntries: ['/'] }) }) + await router.load() + const container = document.createElement('div') + document.body.append(container) + const root = createRoot(container) + cleanups.push(async () => { + releaseComments() + await act(async () => { root.unmount() }) + container.remove() + client.clear() + }) + await act(async () => { root.render() }) + await settle() + return { client, container, writes, releaseComments } +} + +test.each([0, 1])('no comments makes no seen request, even with unread=%s', async (unread) => { + const { writes } = await renderPanel({ unread }) + expect(writes).toHaveLength(0) +}) + +test('comments without unread feedback make no seen request', async () => { + const { writes } = await renderPanel({ unread: 0, author: 'other' }) + expect(writes).toHaveLength(0) +}) + +test('only the viewer’s comments make no seen request', async () => { + const { writes } = await renderPanel({ unread: 1, author: 'viewer' }) + expect(writes).toHaveLength(0) +}) + +test('unread feedback waits for another author’s comment and marks seen exactly once', async () => { + const { client, container, writes, releaseComments } = await renderPanel({ unread: 1, author: 'other', delayed: true }) + expect(writes).toHaveLength(0) + await act(async () => { releaseComments() }) + await settle() + expect(writes).toHaveLength(1) + expect(writes[0]?.keepalive).toBe(true) + await act(async () => { + client.setQueryData(consoleKeys.inbox, []) + await client.refetchQueries({ queryKey: commentsQuery(APP_ID).queryKey }) + }) + await settle() + expect(writes).toHaveLength(1) + expect(container.querySelector('[data-testid="voices-new"]')).not.toBeNull() +}) diff --git a/web/src/features/app/voices-panel.tsx b/web/src/features/app/voices-panel.tsx new file mode 100644 index 0000000..9d80fbf --- /dev/null +++ b/web/src/features/app/voices-panel.tsx @@ -0,0 +1,110 @@ +import { useQuery } from '@tanstack/react-query' +import { Sparkles } from 'lucide-react' +import { useEffect, useRef, useState } from 'react' +import { commentsQuery, useMe } from '../../api/queries/console' +import { copy, relativeTime } from '../../copy' +import { isUnknownPerson, type AppComment, type BusinessApp } from '../../model/contracts/console' +import { paths } from '../../routes/paths' +import { Avatar, Button, Card, CardBody, HrefLink, ResourceBoundary } from '../../ui' +import { useInbox } from '../inbox' +import { ImproveDialog } from '../improve/entry' +import { text } from './copy' +import { useMarkCommentsSeen } from './mutations' + +const SHOWN = 2 + +/** + * 「利用者の声」 on a maintainer's 概要 (ux-design §6.7/§6.10, WF-05 ④): the two newest comments, how many were new + * when the page opened, the way to the whole thread, and 「これを AIで直す」 per comment. Opening it counts as + * having seen the comments; the new count stays as it was on arrival so the badge does not vanish under the reader. + * `stackId`: the app's stack while it can be improved (no build session running); without it there is no AI entry. + */ +export function VoicesPanel({ app, projectId, stackId }: { app: BusinessApp; projectId: string; stackId: string | undefined }) { + const comments = useQuery(commentsQuery(app.id)) + const { data: me } = useMe() + const inbox = useInbox() + const unread = inbox.items.find((item) => item.kind === 'feedback' && item.app.id === app.id)?.count ?? 0 + const { mutate: markSeen } = useMarkCommentsSeen(app.id) + const [arrival, setArrival] = useState() + const marked = useRef(false) + // Pin the arrival count, but only mark a loaded thread with unread comments from others. + useEffect(() => { + if (!inbox.ready) return + setArrival((count) => count ?? unread) + if (marked.current || unread <= 0 || !comments.data?.some((comment) => comment.author.id !== me.person.id)) return + marked.current = true + markSeen() + }, [inbox.ready, unread, comments.data, me.person.id, markSeen]) + const [fixing, setFixing] = useState() + const ownerIds = new Set(app.owners.filter((owner) => !isUnknownPerson(owner)).map((owner) => owner.id)) + const newCount = arrival ?? unread + + return ( +
+ +
+

{text.maintainer.voicesTitle}

+ {newCount > 0 ? ( + {text.maintainer.voicesNew(newCount)} + ) : null} + + {text.maintainer.voicesAll} + +
+ + + {(list, stale) => ( + <> + {stale ?
{stale}
: null} + {list.length === 0 ? ( +

{text.maintainer.voicesEmpty}

+ ) : ( +
    + {list.slice(0, SHOWN).map((comment) => { + // A removed person keeps their comment, shown without a name that no longer exists. + const author = isUnknownPerson(comment.author) ? undefined : comment.author + const authorName = author ? author.displayName : copy.common.unknownPerson + return ( +
  • +
    + +
    +

    + {authorName} + {ownerIds.has(comment.author.id) ? {text.comments.ownerBadge} : null} + +

    +

    {comment.body}

    +
    +
    + {stackId ? ( + + ) : null} +
  • + ) + })} +
+ )} + + )} +
+
+
+ {stackId ? ( + { if (!open) setFixing(undefined) }} + draft={fixing?.body ?? ''} + /> + ) : null} +
+ ) +} diff --git a/web/src/features/build/build-page.tsx b/web/src/features/build/build-page.tsx index 05f4c3d..4ff0f9f 100644 --- a/web/src/features/build/build-page.tsx +++ b/web/src/features/build/build-page.tsx @@ -30,7 +30,6 @@ import { setArtifactCollapsed, shellStore } from '../../shell/store' import { useShell } from '../../shell/use-shell' import { ActionError, Button, cn, EmptyState, focusHeading, LinkButton, Loading, Notice, ResourceBoundary, useDocumentTitle } from '../../ui' import { DatabaseChanges } from '../app/database-changes' -import { canEditApp } from '../app/permissions' import { ArtifactPane } from './artifact-pane' import { ConversationPane, PlanRejectionActions } from './conversation-pane' import { PublishStep } from './publish-step' @@ -135,7 +134,7 @@ function Session({ draft, groupId, stale }: { draft: BuildDraft; groupId: string {stale || build.result.unsupported || draft.buildFailure || creationAccess.error ?
{stale} {build.result.unsupported ? {buildCopy.unsupported.detail} : null} - + {creationAccess.error ? : null}
: null} {build.waitingForPublish || creationAccess.waitingForPublish ?

{text.page.waitingForPublish}

: null} @@ -149,7 +148,7 @@ function Session({ draft, groupId, stale }: { draft: BuildDraft; groupId: string
- setArtifactCollapsed(true)} databaseChanges={} shareStep={sharing && build.app && !appReadOnly ? <>{behind} { build.published(); setSharing(false) }} onCancel={() => setSharing(false)} /> : undefined} /> + setArtifactCollapsed(true)} databaseChanges={} shareStep={sharing && build.app && !appReadOnly ? <>{behind} { build.published(); setSharing(false) }} onCancel={() => setSharing(false)} /> : undefined} />
{artifactCollapsed ? (
diff --git a/web/src/features/build/console-draft-stages.tsx b/web/src/features/build/console-draft-stages.tsx index e61b2cb..9765dad 100644 --- a/web/src/features/build/console-draft-stages.tsx +++ b/web/src/features/build/console-draft-stages.tsx @@ -30,7 +30,6 @@ import type { Group, Me } from '../../model/contracts/console' import { setArtifactCollapsed } from '../../shell/store' import { ActionError, Button, Disclosure, Notice } from '../../ui' import { DatabaseChanges } from '../app/database-changes' -import { canEditApp } from '../app/permissions' import { ArtifactPane } from './artifact-pane' import { ConsolePublishSettings, publishReady } from './console-publish-settings' import { readConsoleCreation, saveConsoleCreation } from './console-session-state' @@ -243,7 +242,7 @@ export function useConsoleDraftStages({ view, actions, draft: observed, me, grou artifact: setArtifactCollapsed(true)} - databaseChanges={} + databaseChanges={} shareStep={sharing && app && !appReadOnly ? <>{behind} { void effects.markPublished(); setSharing(false) }} onCancel={() => setSharing(false)} /> : undefined} />, } : {}), notices: [ diff --git a/web/src/features/build/use-build-session.test.tsx b/web/src/features/build/use-build-session.test.tsx index 62d5ab3..2296d06 100644 --- a/web/src/features/build/use-build-session.test.tsx +++ b/web/src/features/build/use-build-session.test.tsx @@ -6,7 +6,7 @@ import { act, useLayoutEffect, useSyncExternalStore } from 'react' import { createRoot, type Root } from 'react-dom/client' import * as api from '../../api/build' import { draftOf, turnOf, generationOf } from '../../api/testing/build-domain' -import { appOf } from '../../api/testing/catalog-domain' +import { appOf, appWireDefaults } from '../../api/testing/catalog-domain' import type { BuildDraft } from '../../model/contracts/build' import { buildKeys } from '../../api/queries/build' import { consoleKeys } from '../../api/queries/console' @@ -29,7 +29,7 @@ import { useBuildSession } from './use-build-session' const me: Me = { projectId: 'project-session-test', person: { id: 'person-1', subject: 'owner-1', pending: false, email: 'owner@example.test', displayName: 'Owner', avatarVersion: null }, effectiveGroupIds: ['sales'], managedGroupIds: [], isConsoleAdmin: false, canCreateApps: true, - teamSlug: 'team', directoryPublicURL: '', migration: { pending: false, people: 0, groups: 0, memberships: 0 }, + teamSlug: 'team', directoryPublicURL: '', migration: { pending: false, people: 0, groups: 0, memberships: 0 }, view: 'user', } const at = '2026-10-26T00:00:00Z' const turn = (id: string, userMessage: string, minute: number): ApplicationDraftConversationTurn => ({ @@ -593,7 +593,7 @@ const publishedDraft: ApplicationDraft = { const publishedApp = { id: 'app-console', slug: 'ledger', displayName: draft.title, description: '', icon: '', tags: [], guide: '', capabilities: [], screenshots: [], group: { id: 'sales', path: 'sales', name: 'Sales' }, owners: [me.person], stackId: 'stack-1', appName: 'app-platform', - share: { scope: 'group', groupIds: ['sales'], extraPersonIds: [] }, createdBy: me.person, createdAt: at, updatedAt: at, + share: { scope: 'group', groupIds: ['sales'], extraPersonIds: [] }, createdBy: me.person, createdAt: at, updatedAt: at, ...appWireDefaults, } async function mountPublished(current = publishedDraft, session = initial) { diff --git a/web/src/features/create/availability.test.ts b/web/src/features/create/availability.test.ts index 81c7fae..dacf46c 100644 --- a/web/src/features/create/availability.test.ts +++ b/web/src/features/create/availability.test.ts @@ -2,7 +2,7 @@ // the network is in memory (wire answers as Platform and the Console send them). import { describe, expect, test } from 'bun:test' import { createCreateApi } from '../../api/create' -import { appOf, definitionOf, resolvedDestinationOf, templateOf } from '../../api/testing/catalog-domain' +import { appOf, appWireDefaults, definitionOf, resolvedDestinationOf, templateOf } from '../../api/testing/catalog-domain' import { createTestGateway } from '../../api/testing/gateway' import { resolveCreateCatalog } from '../../model/create' import { checkNameAvailability, suggestFreeUrlName, type AvailabilityDeps, type AvailabilityRequest } from './availability' @@ -44,7 +44,7 @@ const person = { id: 'p1', subject: 's', pending: false, email: 'a@example.test' const ownDraft = appOf({ id: 'draft-1', slug: 'mitsumori', displayName: '見積', description: '', icon: '', tags: [], guide: '', capabilities: [], screenshots: [], group: { id: 'g1', path: 'sales/east', name: '営業1課' }, owners: [person], createdBy: person, stackId: null, appName: null, - share: { scope: 'private', groupIds: [], extraPersonIds: [] }, createdAt: '2026-10-06T00:00:00Z', updatedAt: '2026-10-06T00:00:00Z', + share: { scope: 'private', groupIds: [], extraPersonIds: [] }, createdAt: '2026-10-06T00:00:00Z', updatedAt: '2026-10-06T00:00:00Z', ...appWireDefaults, }) const json = (body: unknown, status = 200) => Response.json(body, { status }) diff --git a/web/src/features/create/persistence.test.ts b/web/src/features/create/persistence.test.ts index 68aadc6..0cf5af3 100644 --- a/web/src/features/create/persistence.test.ts +++ b/web/src/features/create/persistence.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from 'bun:test' -import { appOf } from '../../api/testing/catalog-domain' +import { appOf, appWireDefaults } from '../../api/testing/catalog-domain' import { initialValues } from './form' import { clearCreateSession, readCreateSession, restoreCreateDraft, saveCreateSession, type CreateSession } from './persistence' @@ -9,7 +9,7 @@ const wireDraft = { id: 'app-draft', slug: 'stock', displayName: '在庫管理', description: '備品の在庫', icon: '', tags: ['備品'], guide: '', capabilities: [], screenshots: [], group: { id: 'sales', path: 'sales', name: '営業部' }, owners: [person], createdBy: person, stackId: null, appName: 'stock', share: { scope: 'group', groupIds: ['sales'], extraPersonIds: [] }, - createdAt: '2026-10-07T00:00:00Z', updatedAt: '2026-10-07T00:00:00Z', + createdAt: '2026-10-07T00:00:00Z', updatedAt: '2026-10-07T00:00:00Z', ...appWireDefaults, } const draft = appOf(wireDraft) function storage() { diff --git a/web/src/features/create/submit.test.ts b/web/src/features/create/submit.test.ts index 4e30840..cb81e28 100644 --- a/web/src/features/create/submit.test.ts +++ b/web/src/features/create/submit.test.ts @@ -5,7 +5,7 @@ import { describe, expect, test } from 'bun:test' import { createCreateApi, type CreateApi } from '../../api/create' import { decodeResponse } from '../../api/boundary' import { getRepositoryDestinationContract } from '../../api/contracts/platform/catalog' -import { appOf, definitionOf, resolvedDestinationOf, sourceConnectionOf, templateOf } from '../../api/testing/catalog-domain' +import { appOf, appWireDefaults, definitionOf, resolvedDestinationOf, sourceConnectionOf, templateOf } from '../../api/testing/catalog-domain' import { createTestGateway } from '../../api/testing/gateway' import { copy } from '../../copy' import { MOCK_PROJECT_ID, platformRoutes } from '../../dev/mock-platform' @@ -64,7 +64,7 @@ const wireDraft = { id: 'app-1', slug: 'mitsumori', displayName: '見積作成', description: '', icon: '', tags: [], guide: '', capabilities: [], screenshots: [], group: { id: 'g1', path: 'sales/east', name: '営業1課' }, owners: [person], stackId: null, appName: 'mitsumori', share: { scope: 'group', groupIds: ['g1'], extraPersonIds: [] }, createdBy: person, - createdAt: '2026-10-06T00:00:00Z', updatedAt: '2026-10-06T00:00:00Z', + createdAt: '2026-10-06T00:00:00Z', updatedAt: '2026-10-06T00:00:00Z', ...appWireDefaults, } const draft = appOf(wireDraft) diff --git a/web/src/features/discover/app-list.tsx b/web/src/features/discover/app-list.tsx index 9e381b4..ade5f4b 100644 --- a/web/src/features/discover/app-list.tsx +++ b/web/src/features/discover/app-list.tsx @@ -1,6 +1,6 @@ -// App cards, compact rows and the sortable app table shared by home, mine, -// company and group pages. Each page calls `useAppViews(projectId)` once (one -// project-wide platform read-model load) and passes it down as `lookup`. +// The sortable app table and status cells shared by mine, group and drafts +// pages. Each page calls `useAppViews(projectId)` once (one project-wide +// platform read-model load) and passes it down as `lookup`. import { createColumnHelper, getCoreRowModel, @@ -17,10 +17,8 @@ import { pendingAccessRequestsQuery } from '../../api/queries/console' import { copy, relativeTime } from '../../copy' import { paths } from '../../routes/paths' import { locale } from '../../shell/language' -import { useShell } from '../../shell/use-shell' import { AppIcon, Button, ConfirmDialog, CopyButton, DataTable, HrefLink, Notice, OpenLink, Skeleton, StatusPill } from '../../ui' import { useDiscardDraft } from '../app/mutations' -import { canEditApp } from '../app/permissions' import { PendingBadge } from '../app/pending-badge' import type { AppViews } from '../app/use-app-views' import { StaleNotice, UnconfirmedNotice, useWriteConfirmation } from '../app/notices' @@ -72,13 +70,12 @@ export function AppStatus({ app, lookup }: { app: BusinessApp; lookup: AppViews /** 作りかけ: carry on, or drop the draft (it has no stack, so nothing else is removed). */ function UnfinishedActions({ app, view }: { app: BusinessApp; view: AppView }) { - const { me } = useShell() const [open, setOpen] = useState(false) const queryClient = useQueryClient() const discard = useDiscardDraft(app, view) // A discard whose answer could not be read may have happened: the lists are read back before it is offered again. const confirmation = useWriteConfirmation([discard.error], discard.reset, () => queryClient.refetchQueries({ queryKey: ['console', 'apps'] })) - if (view.unreadableStack || view.unreadableBuild || !canEditApp(app, me)) return null + if (view.unreadableStack || view.unreadableBuild || !app.permissions.maintain) return null return (
{text.list.resume} @@ -137,54 +134,6 @@ export function StatusLoadNotice({ lookup }: { lookup: AppViews }) { ) } -/** Home-page cards (ux-design §7.2): icon, name, status, 担当者. */ -export function AppCards({ apps, lookup, pendingCounts }: { apps: BusinessApp[]; lookup: AppViews; pendingCounts?: ReadonlyMap }) { - return ( -
    - {apps.map((app) => ( -
  • - - - - {app.displayName} - {ownerNames(app)} - - - -
    - -
  • - ))} -
- ) -} - -/** Compact rows: group name, app, status and (optionally) when it was added. */ -export function AppLines({ apps, lookup, showTime = false, pendingCounts }: { apps: BusinessApp[]; lookup: AppViews; showTime?: boolean; pendingCounts?: ReadonlyMap }) { - return ( -
    - {apps.map((app) => { - const added = showTime ? relativeTime(app.createdAt) : undefined - return ( -
  • - - - - {app.displayName} - {app.group.name} - - - -
    - {added ? {text.list.created(added)} : null} - -
  • - ) - })} -
- ) -} - const STATUS_ORDER = { failed: 0, unfinished: 1, deploying: 2, live: 3, unknown: 4 } as const const column = createColumnHelper() @@ -314,23 +263,3 @@ export function AppListSkeleton({ rows = 3 }: { rows?: number }) {
) } - -/** Placeholder cards for the home group section. */ -export function AppCardsSkeleton({ count = 4 }: { count?: number }) { - return ( -
- {Array.from({ length: count }, (_, index) => ( -
-
- -
- - -
-
- -
- ))} -
- ) -} diff --git a/web/src/features/discover/app-store-card.tsx b/web/src/features/discover/app-store-card.tsx index d7021f2..3e444e7 100644 --- a/web/src/features/discover/app-store-card.tsx +++ b/web/src/features/discover/app-store-card.tsx @@ -1,11 +1,11 @@ import { Check } from 'lucide-react' import { screenshotUrl } from '../../api/console' -import { type DirectoryEntry } from '../../model/contracts/console' +import { type BusinessApp, type DirectoryEntry } from '../../model/contracts/console' import { copy } from '../../copy' import type { AppView } from '../../model/app' import { resolvedPeople } from '../../model/directory' import { paths } from '../../routes/paths' -import { AppIcon, Avatar, Button, HrefLink, LinkButton, PersonLink, Skeleton, StatusPill } from '../../ui' +import { AppIcon, Avatar, Button, buttonClasses, cn, HrefLink, LinkButton, PersonLink, Skeleton, StatusPill } from '../../ui' import type { AppViews } from '../app' import { text } from './copy' @@ -137,3 +137,133 @@ export function AppStoreGridSkeleton({ count = 3 }: { count?: number }) {
) } + +/** How a home card opens its app (role-based-views ux-design §6.4). No `url` → the card cannot open it. */ +export type CardLaunch = { + url?: string + tone: 'primary' | 'secondary' + /** Shown only when something is not as usual; a healthy app says nothing. */ + note?: 'failed' | 'stopped' | 'notReady' + /** Statuses are still loading: the list is shown first, the state lands later. */ + pending?: true +} + +export function cardLaunch(view: AppView, lookup: Pick): CardLaunch { + if (lookup.loading) return { tone: 'primary', pending: true } + // An unreadable state claims nothing; the list carries one 「状態を確認できませんでした」 line instead. + if (lookup.failed || view.unreadableStack || view.unreadableBuild) return { url: view.url, tone: 'primary' } + if (view.status === 'failed') return { url: view.url, tone: 'secondary', note: 'failed' } + if (view.status === 'unknown') return { url: view.url, tone: 'secondary', note: 'stopped' } + if (!view.url) return { tone: 'primary', note: 'notReady' } + return { url: view.url, tone: 'primary' } +} + +const NOTE_TONE: Record, string> = { + failed: 'bg-busy-soft text-busy-ink ring-amber-200', + stopped: 'bg-stone-100 text-stone-600 ring-stone-200', + notReady: 'bg-stone-100 text-stone-600 ring-stone-200', +} + +const cardLink = 'relative z-10 inline-flex min-h-10 items-center text-sm text-accent-strong underline underline-offset-2 hover:text-accent md:min-h-8' + +/** + * Home card (ux-design §6.4, WF-01): icon, name, group and the description's + * first line. The whole card opens the app in a new tab; 「開く ↗」 marks that + * target and is not a second tab stop. 「くわしく」 leads to the intro page, + * 「管理」 (maintainers only) to the same page with tabs. No owner, no version. + */ +export function AppLaunchCard({ app, launch, heading = 'h3' }: { app: BusinessApp; launch: CardLaunch; heading?: HeadingLevel }) { + const Heading = heading + const line = app.description.split('\n')[0].trim() || app.capabilities[0] || '' + const appPage = paths.app(app.group.path, app.slug) + // Maintainers get tabs on the app page; 「くわしく」 shows them the intro page as users see it (app-page.tsx `?as=user`). + const details = app.permissions.maintain ? `${appPage}?as=user` : appPage + return ( +
+
+ +
+ + {launch.url ? ( + + {app.displayName} + + ) : ( + {app.displayName} + )} + +

{app.group.name}

+
+
+ {line ?

{line}

: null} + {launch.note ? ( +

+ {text.card[launch.note]} +

+ ) : null} +
+ + {text.card.open} + + + {text.card.details} + + {app.permissions.maintain ? ( + + {text.card.manage} + + ) : null} +
+
+ ) +} + +/** One column on phones, two from 768px, three from 1280px; entries keep the caller's order. */ +export function AppLaunchGrid({ apps, lookup, label }: { apps: BusinessApp[]; lookup: AppViews; label?: string }) { + return ( +
    + {apps.map((app) => ( +
  • + +
  • + ))} +
+ ) +} + +export function AppLaunchGridSkeleton({ count = 6 }: { count?: number }) { + return ( +
+ {Array.from({ length: count }, (_, index) => ( +
+
+ +
+ + +
+
+ + +
+ ))} +
+ ) +} diff --git a/web/src/features/discover/copy.en.ts b/web/src/features/discover/copy.en.ts index 48ae17c..61d1bba 100644 --- a/web/src/features/discover/copy.en.ts +++ b/web/src/features/discover/copy.en.ts @@ -4,9 +4,6 @@ export const textEn: typeof textJa = { home: { searching: 'Searching…', resultsCount: (n: number) => n === 1 ? '1 result' : `${n} results`, - groupLead: (name: string) => `Apps in ${name} and its subgroups.`, - sharedLead: 'Apps shared from parent groups that you can use.', - companyLead: 'New apps everyone in your company can use.', }, list: { ownerSeparator: ', ', @@ -14,7 +11,6 @@ export const textEn: typeof textJa = { open: 'Open ↗', copyUrl: 'Copy URL', statusFailed: 'Could not check app status.', - created: (time: string) => `Added ${time}`, resume: 'Continue building', check: 'Check status', discard: 'Delete', @@ -47,10 +43,8 @@ export const textEn: typeof textJa = { createHere: 'Create an app here', }, entry: { - ofGroup: (name: string) => `Apps in ${name}`, wantToUse: 'Request access', restricted: (name: string) => `This app is shared with people in ${name}. Choose “Request access” if you would like to use it.`, - owner: 'Owner', requestUnavailable: 'We could not find where to send your request. Ask the owner for help.', }, store: { @@ -61,6 +55,17 @@ export const textEn: typeof textJa = { open: (name: string) => `Open ${name}`, want: (name: string) => `Request access to ${name}`, }, + card: { + open: 'Open ↗', + openLabel: (name: string) => `${name} (opens in a new tab)`, + details: 'Details', + detailsLabel: (name: string) => `Details about ${name}`, + manage: 'Manage', + manageLabel: (name: string) => `Manage ${name}`, + failed: 'Seems to be having trouble', + stopped: 'Stopped for now', + notReady: 'Getting ready. You can’t open it yet', + }, person: { apps: (n: number) => `Apps created (${n})`, appsLoading: 'Apps created', diff --git a/web/src/features/discover/copy.ts b/web/src/features/discover/copy.ts index 508a972..c5056af 100644 --- a/web/src/features/discover/copy.ts +++ b/web/src/features/discover/copy.ts @@ -8,9 +8,6 @@ export const textJa = { home: { searching: '探しています…', resultsCount: (n: number) => `${n} 件`, - groupLead: (name: string) => `${name} と、その下のグループのアプリです。`, - sharedLead: '上位のグループから共有されて、あなたも使えるアプリです。', - companyLead: '会社の全員が使える、最近できたアプリです。', }, list: { ownerSeparator: '、', @@ -18,7 +15,6 @@ export const textJa = { open: '開く ↗', copyUrl: 'URL をコピー', statusFailed: 'アプリの状態を確認できませんでした。', - created: (time: string) => `${time}に追加`, resume: '続きから作る', check: '状況を確認する', discard: '削除', @@ -51,10 +47,8 @@ export const textJa = { createHere: 'このグループにアプリを作る', }, entry: { - ofGroup: (name: string) => `${name} のアプリ`, wantToUse: '使いたい', restricted: (name: string) => `このアプリは ${name} の人向けに公開されています。使いたいときは「使いたい」から申請できます。`, - owner: '担当', requestUnavailable: '申請先を確認できません。担当者に聞いてみてください。', }, store: { @@ -65,6 +59,17 @@ export const textJa = { open: (name: string) => `${name}を開く`, want: (name: string) => `${name}を使いたい`, }, + card: { + open: '開く ↗', + openLabel: (name: string) => `${name}(新しいタブで開きます)`, + details: 'くわしく', + detailsLabel: (name: string) => `${name}をくわしく見る`, + manage: '管理', + manageLabel: (name: string) => `${name}を管理する`, + failed: 'いま調子が悪いようです', + stopped: 'いまは止まっています', + notReady: '準備中です。まだ開けません', + }, person: { apps: (n: number) => `作ったアプリ(${n} 件)`, appsLoading: '作ったアプリ', diff --git a/web/src/features/discover/entry.tsx b/web/src/features/discover/entry.tsx index 28b9847..4c8140b 100644 --- a/web/src/features/discover/entry.tsx +++ b/web/src/features/discover/entry.tsx @@ -1,39 +1,23 @@ import type { DirectoryEntry } from '../../model/contracts/console' -import { copy, relativeTime } from '../../copy' import { paths } from '../../routes/paths' -import { AppIcon, Button, HrefLink, LinkButton, Notice, PageHeader, useDocumentTitle } from '../../ui' -import { AppAbout, Comments, OwnerLinks, ScreenshotStrip } from '../app' +import { Button, LinkButton, Notice } from '../../ui' +import { FeedbackSection, INTRO_PRIMARY, IntroLayout } from '../app/intro-page' import { text } from './copy' /** - * The app page for people who cannot open the app (store-ux §3.4): the same - * order as 概要 — pictures, what it does — but a directory projection only: - * no app URL, guide, sharing policy or settings. + * The app page for people who cannot open the app (store-ux §3.4, ux-design §6.5): the intro page's + * layout with 「使いたい」 as the primary action, from a directory projection only: no app URL, sharing + * policy or settings, and no guide (it is not part of the projection). */ export function EntryPage({ entry }: { entry: DirectoryEntry }) { - useDocumentTitle(entry.displayName) - const updated = relativeTime(entry.updatedAt) return ( -
- {entry.displayName}} - actions={entry.appName ? ( - {text.entry.wantToUse} - ) : } - > -

- {text.entry.ofGroup(entry.group.name)} - ・ - {text.entry.owner} - {updated ? <>・{copy.group.lastUpdated} : null} -

-
- - - - {text.entry.restricted(entry.group.name)} - - -
+ {text.entry.wantToUse}
+ ) : } + state={{text.entry.restricted(entry.group.name)}} + feedback={} + /> ) } diff --git a/web/src/features/discover/help.tsx b/web/src/features/discover/help.tsx index bf9dff5..8fa5588 100644 --- a/web/src/features/discover/help.tsx +++ b/web/src/features/discover/help.tsx @@ -3,21 +3,29 @@ import { ChevronDown } from 'lucide-react' import { useEffect, useState } from 'react' import { copy } from '../../copy' import { Collapsible, CollapsibleContent, CollapsibleTrigger, PageHeader, useDocumentTitle } from '../../ui' +import { useConsoleView } from '../inbox' import { text } from './copy' -type ArticleId = (typeof copy.help.articles)[number]['id'] +type Article = (typeof copy.help.articles)[number] -/** Three short articles (ux-design §7.1 ヘルプ). `/help#share` opens 公開範囲とは. */ +/** + * Four short articles in the order of the caller's view (role-based-views + * ux-design §6.9). A `#id` link to an article of the other view (e.g. + * `/help#share`) still opens it, after the four. + */ export function HelpPage() { useDocumentTitle(copy.help.title) + const view = useConsoleView() const hash = useLocation({ select: (location) => location.hash }) - const [open, setOpen] = useState>>(() => ({ - [copy.help.articles.some((article) => article.id === hash) ? (hash as ArticleId) : copy.help.articles[0].id]: true, - })) + const ids = copy.help.order[view] + const articles = copy.help.articles + .filter((article) => ids.includes(article.id) || article.id === hash) + .sort((a, b) => (ids.indexOf(a.id) + 1 || Infinity) - (ids.indexOf(b.id) + 1 || Infinity)) + const target = articles.find((article) => article.id === hash) + const [open, setOpen] = useState>>(() => ({ [target?.id ?? articles[0].id]: true })) // `#share` arriving while mounted (in-page link) opens that article; scrolling is a DOM effect. const [followedHash, setFollowedHash] = useState(hash) - const target = copy.help.articles.find((article) => article.id === hash) if (followedHash !== hash) { setFollowedHash(hash) if (target) setOpen((current) => ({ ...current, [target.id]: true })) @@ -30,7 +38,7 @@ export function HelpPage() {
- {copy.help.articles.map((article, index) => ( + {articles.map((article, index) => ( void +beforeEach(() => { + restoreLanguage = preserveLanguage() + setLanguage('ja') +}) +afterEach(() => restoreLanguage()) + +const owner = { id: 'owner', subject: 's', pending: false, displayName: '鈴木 一郎', email: 'suzuki@example.com', avatarVersion: null } +const noPermissions = { use: true, comment: true, propose: false, maintain: false, data: false } + +function app(id: string, displayName: string, groupId: string, scope: 'private' | 'group' | 'company' | 'public', extra: Record = {}) { + return businessAppOf({ + id, slug: id, displayName, description: `${displayName}の説明\n二行目`, icon: '', tags: [], + group: { id: groupId, path: groupId, name: groupId }, owners: [owner], createdBy: owner, + stackId: `stack-${id}`, appName: id, share: { scope, groupIds: [], extraPersonIds: [] }, createdAt: '', updatedAt: '', + guide: '', capabilities: ['一覧を出す'], screenshots: [], contribution: { scope: 'group' }, permissions: noPermissions, + ...extra, + }) +} + +function group(id: string, parentId: string | null, name: string): Group { + return { + id, parentId, name, slug: id, path: parentId ? `${parentId}/${id}` : id, description: '', about: '', aboutUpdatedBy: null, + aboutUpdatedAt: null, subgroupCount: 0, memberCount: 0, createdAt: '', updatedAt: '', + } +} + +describe('usableFilters', () => { + const groups = [group('hr', null, '人事部'), group('hr-pay', 'hr', '給与課'), group('acc', null, '経理部'), group('ga', null, '総務部')] + const apps = [ + app('wage', '評価・賃金', 'hr', 'group'), + app('payslip', '給与明細', 'hr-pay', 'private'), + app('expense', '経費精算', 'acc', 'group'), + app('kintai', '勤怠申請', 'ga', 'company'), + app('room', '会議室予約', 'ga', 'public'), + app('draft', '作りかけ', 'hr', 'group', { stackId: null }), + ] + + test('one chip per membership (its subtree), then ほかの部署 and 全社; すべて keeps that order and leaves out drafts', () => { + const filters = usableFilters(apps, [groups[0]], groups) + expect(filters.map((filter) => filter.label)).toEqual(['すべて', '人事部', 'ほかの部署', '全社']) + expect(filters.map((filter) => filter.apps.map((item) => item.id))).toEqual([ + ['payslip', 'wage', 'expense', 'room', 'kintai'], + ['payslip', 'wage'], + ['expense'], + ['room', 'kintai'], + ]) + }) + + test('an app inside the membership is not repeated under 全社, and an empty chip is not offered', () => { + const filters = usableFilters([app('kintai', '勤怠申請', 'hr', 'company')], [groups[0]], groups) + expect(filters.map((filter) => filter.label)).toEqual(['すべて', '人事部']) + }) + + test('without a membership every app still lands in a chip', () => { + const filters = usableFilters(apps, [], groups) + expect(filters.map((filter) => filter.label)).toEqual(['すべて', 'ほかの部署', '全社']) + expect(filters[0].apps).toHaveLength(5) + }) +}) + +describe('cardLaunch', () => { + const view = (patch: Partial): AppView => ({ status: 'live', label: '公開中', text: '', second: '最新の版 (v3・3 時間前) が動いています。', draft: false, url: 'https://wage.example.test', ...patch }) + const known = { loading: false, failed: false } + + test('a healthy app says nothing and opens with the primary button', () => { + expect(cardLaunch(view({}), known)).toEqual({ url: 'https://wage.example.test', tone: 'primary' }) + expect(cardLaunch(view({ status: 'deploying' }), known)).toEqual({ url: 'https://wage.example.test', tone: 'primary' }) + }) + + test('only unusual states speak; 問題あり and 停止中 stay openable with the quiet button', () => { + expect(cardLaunch(view({ status: 'failed' }), known)).toEqual({ url: 'https://wage.example.test', tone: 'secondary', note: 'failed' }) + expect(cardLaunch(view({ status: 'unknown' }), known)).toEqual({ url: 'https://wage.example.test', tone: 'secondary', note: 'stopped' }) + expect(cardLaunch(view({ status: 'deploying', url: undefined }), known)).toEqual({ tone: 'primary', note: 'notReady' }) + }) + + test('loading and unreadable statuses claim no state', () => { + expect(cardLaunch(view({}), { loading: true, failed: false })).toEqual({ tone: 'primary', pending: true }) + expect(cardLaunch(view({ status: 'unknown' }), { loading: false, failed: true })).toEqual({ url: 'https://wage.example.test', tone: 'primary' }) + expect(cardLaunch(view({ status: 'unknown', unreadableStack: true }), known)).toEqual({ url: 'https://wage.example.test', tone: 'primary' }) + }) +}) + +describe('AppLaunchCard', () => { + async function render(item: BusinessApp, launch: CardLaunch) { + const router = createRouter({ routeTree: createRootRoute(), history: createMemoryHistory({ initialEntries: ['/'] }), isServer: true }) + await router.load() + return renderToStaticMarkup() + } + const hrefOf = (html: string, label: string) => + html.match(new RegExp(`]*aria-label="${label}"[^>]*>`))?.[0].match(/href="([^"]*)"/)?.[1] + + test('the whole card opens the app in a new tab; 「くわしく」 goes to the intro page; no owner, version or status words', async () => { + const html = await render(app('wage', '評価・賃金', 'hr', 'group'), { url: 'https://wage.example.test', tone: 'primary' }) + expect(html).toContain('href="https://wage.example.test" target="_blank"') + expect(html).toContain('aria-label="評価・賃金(新しいタブで開きます)"') + expect(html).toContain('開く ↗') + expect(hrefOf(html, '評価・賃金をくわしく見る')).toBe('/hr/wage') + expect(html).toContain('くわしく') + expect(html).toContain('評価・賃金の説明') + expect(html).not.toContain('二行目') + for (const hidden of ['鈴木 一郎', 'v3', '最新の版', '公開中', '管理']) expect(html).not.toContain(hidden) + }) + + test('maintainers: 「くわしく」 previews the intro page as users see it, 「管理」 opens the page with tabs', async () => { + const maintained = app('wage', '評価・賃金', 'hr', 'group', { permissions: { ...noPermissions, maintain: true } }) + const html = await render(maintained, { url: 'https://wage.example.test', tone: 'primary' }) + expect(hrefOf(html, '評価・賃金をくわしく見る')).toBe('/hr/wage?as=user') + expect(hrefOf(html, '評価・賃金を管理する')).toBe('/hr/wage') + }) + + test('a card that cannot open yet is no link and says so', async () => { + const notReady = await render(app('hire', '採用管理', 'hr', 'group'), { tone: 'primary', note: 'notReady' }) + expect(notReady).toContain('準備中です。まだ開けません') + expect(notReady).not.toContain('target="_blank"') + }) + + test('without a description the first capability stands in', async () => { + const html = await render(app('wage', '評価・賃金', 'hr', 'group', { description: '' }), { url: 'https://wage.example.test', tone: 'primary' }) + expect(html).toContain('一覧を出す') + }) +}) diff --git a/web/src/features/discover/home.tsx b/web/src/features/discover/home.tsx index 59118dc..c3f4e37 100644 --- a/web/src/features/discover/home.tsx +++ b/web/src/features/discover/home.tsx @@ -1,34 +1,78 @@ import { useQuery } from '@tanstack/react-query' import { useNavigate } from '@tanstack/react-router' +import { useSelector } from '@tanstack/react-store' import { Search, X } from 'lucide-react' -import { useMemo, useState, type FormEvent, type ReactNode } from 'react' -import { subtreeIds } from '../../model/contracts/console' +import { useMemo, useState, type FormEvent } from 'react' +import { subtreeIds, type BusinessApp, type DirectoryEntry, type Group } from '../../model/contracts/console' import { isOneOf } from '../../model/contracts/build' -import { appsQuery } from '../../api/queries/console' +import { appsQuery, directoryAppsQuery } from '../../api/queries/console' import { copy } from '../../copy' import { paths } from '../../routes/paths' +import { locale } from '../../shell/language' +import { dismissLaunchHint, shellStore } from '../../shell/store' import { useShell } from '../../shell/use-shell' -import { Button, EmptyState, HrefLink, LoadFailed, useDocumentTitle } from '../../ui' +import { AppIcon, Button, cn, EmptyState, HrefLink, IconButton, LinkButton, LoadFailed, useDocumentTitle } from '../../ui' import { useAppViews, type AppViews } from '../app/use-app-views' import { StaleNotice } from '../app/notices' -import { AppCards, AppCardsSkeleton, AppLines, AppListSkeleton, AppTable, StatusLoadNotice, usePendingAccessRequestCounts } from './app-list' +import { InboxPanel, useConsoleView } from '../inbox' +import { AppListSkeleton, StatusLoadNotice } from './app-list' +import { AppLaunchGrid, AppLaunchGridSkeleton, entryHref } from './app-store-card' import { text } from './copy' import { matchesAppSearch } from './search' -const CARD_LIMIT = 8 -const NEW_LIMIT = 5 +/** Cards shown before 「もっと見る」, and how many more each press adds. */ +export const PAGE_SIZE = 24 -/** Home is for finding apps (ux-design §6-7, §7.2): search, the 所属 group, shared-from-above, company news. */ +export type UsableFilter = { id: string; label: string; apps: BusinessApp[] } + +/** + * 「使えるアプリ」 chips (role-based-views ux-design §6.2): すべて, one per + * membership root (its subtree), ほかの部署, 全社. Only apps bound to the + * platform (no 作りかけ); a chip with no apps is not offered. すべて keeps the + * chip order, each chip is name-ordered. + */ +export function usableFilters(apps: readonly BusinessApp[], homeGroups: readonly Group[], groups: readonly Group[]): UsableFilter[] { + const byName = (a: BusinessApp, b: BusinessApp) => a.displayName.localeCompare(b.displayName, locale()) + const remaining = apps.filter((app) => app.stackId) + const take = (keep: (app: BusinessApp) => boolean) => { + const taken = remaining.filter(keep).sort(byName) + for (const app of taken) remaining.splice(remaining.indexOf(app), 1) + return taken + } + const memberships = homeGroups.map((group) => { + const ids = subtreeIds([...groups], group.id) + return { id: `group:${group.id}`, label: group.name, apps: take((app) => ids.has(app.group.id)) } + }) + const company = { id: 'company', label: copy.home.filterCompany, apps: take((app) => isOneOf(app.share.scope, 'company', 'public')) } + const other = { id: 'other', label: copy.home.filterOther, apps: take(() => true) } + const chips = [...memberships, other, company].filter((chip) => chip.apps.length > 0) + return [{ id: 'all', label: copy.home.filterAll, apps: chips.flatMap((chip) => chip.apps) }, ...chips] +} + +/** + * Home (role-based-views ux-design §6.2–6.3, WF-01/02): search, then for makers + * 「あなたの対応待ち」, for users a one-time tip, then the same 「使えるアプリ」. + */ export function HomePage({ q }: { q: string }) { useDocumentTitle(copy.home.title) const { me } = useShell() + const view = useConsoleView() const lookup = useAppViews(me.projectId) - const pendingCounts = usePendingAccessRequestCounts() return ( -
- +
+

{copy.home.title}

+
+ + {q ? null : view === 'maker' ? : } +
- {q ? : } + {q ? : } +

+ {copy.home.directoryPrompt}{' '} + + {copy.home.directoryLink} + +

) } @@ -46,7 +90,6 @@ function SearchBox({ q }: { q: string }) { if (term !== q) setValue(q) } - const submit = (event: FormEvent) => { event.preventDefault() if (term !== q) void navigate({ search: { q: term } }) @@ -77,143 +120,152 @@ function SearchBox({ q }: { q: string }) { ) } -function SectionHeading({ id, title, lead, more, level = 2 }: { id: string; title: string; lead?: string; more?: ReactNode; level?: 1 | 2 }) { - const Heading = level === 1 ? 'h1' : 'h2' +/** Shown until closed once in this browser (ux-design §6.2 初回の案内). */ +function LaunchHint() { + const dismissed = useSelector(shellStore, (state) => state.launchHintDismissed) + if (dismissed) return null return ( -
-
- - {title} - - {lead ?

{lead}

: null} -
- {more} +
+

{copy.home.hint}

+ } onClick={dismissLaunchHint} className="text-accent-strong hover:bg-white/60" />
) } -function MoreLink({ href, children }: { href: string; children: ReactNode }) { +function DirectoryButton() { + return {copy.home.emptyAction} +} + +function UsableApps({ lookup }: { lookup: AppViews }) { + const { groups, homeGroups } = useShell() + // The server already hid what the caller cannot see. + const visible = useQuery(appsQuery({ scope: 'all' })) + const filters = useMemo(() => usableFilters(visible.data ?? [], homeGroups, groups), [visible.data, homeGroups, groups]) + const [filterId, setFilterId] = useState('all') + const [shown, setShown] = useState(PAGE_SIZE) + const current = filters.find((filter) => filter.id === filterId) ?? filters[0] + const noGroup = homeGroups.length === 0 + + if (visible.isLoadingError) return void visible.refetch()} /> + if (visible.isSuccess && filters[0].apps.length === 0) { + return noGroup + ? } /> + : } /> + } + + const select = (id: string) => { + setFilterId(id) + setShown(PAGE_SIZE) + } return ( - - {children} - +
+ {visible.isRefetchError ? void visible.refetch()} /> : null} + {noGroup ? : null} +
+

+ {copy.home.usable} + {visible.isSuccess ? {copy.home.count(current.apps.length)} : null} +

+ {filters.length > 2 ? ( +
+ {filters.map((filter) => { + const selected = filter.id === current.id + return ( + + ) + })} +
+ ) : null} +
+ {visible.isPending ? ( + + ) : ( + + )} +
+ {visible.isSuccess && current.apps.length > shown ? ( +
+ +
+ ) : null} +
+
) } -function SearchResults({ q, lookup, pendingCounts }: { q: string; lookup: AppViews; pendingCounts: ReadonlyMap }) { +function SearchResults({ q, lookup }: { q: string; lookup: AppViews }) { // The API has no owner filter. Match the authorized, fully loaded list so // searching a person's name never loses apps to the server's narrower `q`. const results = useQuery(appsQuery({ scope: 'all' })) - const matches = (results.data ?? []).filter((app) => matchesAppSearch(app, q)) + const matches = (results.data ?? []) + .filter((app) => app.stackId && matchesAppSearch(app, q)) + .sort((a, b) => a.displayName.localeCompare(b.displayName, locale())) + // Nothing usable matched: offer what the directory knows, with 「使いたい」 (WF-07 C). + const directory = useQuery({ ...directoryAppsQuery({ q }), enabled: results.isSuccess && matches.length === 0 }) + const others = (directory.data ?? []).filter((entry) => !entry.canOpen) return (
- - - {copy.home.searchClear} - - } - /> -

- {results.isFetching ? text.home.searching : results.data ? text.home.resultsCount(matches.length) : ''} -

+
+

+ {copy.home.resultsTitle(q)} + + {results.isFetching ? text.home.searching : results.data ? text.home.resultsCount(matches.length) : ''} + +

+ + + {copy.home.searchClear} + +
{results.isRefetchError ? void results.refetch()} /> : null} {results.isPending ? ( - + ) : results.isLoadingError ? ( void results.refetch()} /> + ) : matches.length > 0 ? ( + + ) : directory.isPending ? ( + + ) : others.length > 0 ? ( +
+

{copy.home.noUsableMatch}

+

{copy.home.otherMatches(others.length)}

+
    + {others.map((entry) => )} +
+
) : ( - } title={copy.home.noResults} />} - /> + } title={copy.home.noResults} /> )}
) } -function Sections({ lookup, pendingCounts }: { lookup: AppViews; pendingCounts: ReadonlyMap }) { - const { me, groups, currentGroup } = useShell() - // One visible-apps load feeds every section; the server already hid what the caller cannot see. - const visible = useQuery(appsQuery({ scope: 'all' })) - const sections = useMemo(() => { - const apps = visible.data ?? [] - const contextIds = currentGroup ? subtreeIds(groups, currentGroup.id) : new Set() - const myGroupIds = new Set(me.effectiveGroupIds) - return { - group: apps.filter((app) => contextIds.has(app.group.id)), - // Visible through a `group` share although owned outside the caller's groups: shared from above. - shared: apps.filter((app) => isOneOf(app.share.scope, 'group') && !myGroupIds.has(app.group.id)), - company: apps - .filter((app) => isOneOf(app.share.scope, 'company', 'public')) - .sort((a, b) => b.createdAt.localeCompare(a.createdAt)) - .slice(0, NEW_LIMIT), - } - }, [visible.data, currentGroup, groups, me.effectiveGroupIds]) - - if (visible.isLoadingError) return void visible.refetch()} /> - const loading = visible.isPending - +/** An app the caller cannot open yet: its intro page and 「使いたい」. */ +function WantRow({ entry }: { entry: DirectoryEntry }) { return ( - <> - {visible.isRefetchError ? void visible.refetch()} /> : null} -
- {copy.home.seeAll} : null} - /> - {!currentGroup ? ( - - ) : loading ? ( - - ) : sections.group.length === 0 ? ( - - ) : ( - - )} -
- -
- - {loading ? ( - - ) : sections.shared.length === 0 ? ( -

{copy.home.sharedEmpty}

- ) : ( - - )} -
- -
- {copy.home.seeAll}} - /> - {loading ? ( - - ) : sections.company.length === 0 ? ( -

{copy.home.companyEmpty}

- ) : ( - - )} -
- +
  • + + + {entry.displayName} + {entry.group.name} + + {entry.appName ? ( + {text.entry.wantToUse} + ) : ( + + )} +
  • ) } diff --git a/web/src/features/discover/mine.tsx b/web/src/features/discover/mine.tsx index 7ab6aaf..c40d13c 100644 --- a/web/src/features/discover/mine.tsx +++ b/web/src/features/discover/mine.tsx @@ -7,12 +7,14 @@ import { useShell } from '../../shell/use-shell' import { EmptyState, LinkButton, LoadFailed, PageHeader, useDocumentTitle } from '../../ui' import { useAppViews } from '../app/use-app-views' import { StaleNotice } from '../app/notices' +import { InboxPanel } from '../inbox' import { AppListSkeleton, AppTable, StatusLoadNotice, usePendingAccessRequestCounts } from './app-list' import { text } from './copy' /** * Apps whose 担当者 includes the caller (ux-design §7.1 自分のアプリ); empty → the create path. * Only apps that exist (bound to the platform); anything half-made is under 作りかけ (drafts.tsx). + * Every 「あなたの対応待ち」 row sits above the list: home's 「すべて見る」 leads here. */ export function MinePage({ status }: { status?: 'problem' }) { useDocumentTitle(copy.mine.title) @@ -27,6 +29,7 @@ export function MinePage({ status }: { status?: 'problem' }) {
    {text.mine.seeAll} : undefined} /> + {problemOnly ? null : } {apps.isRefetchError ? void apps.refetch()} /> : null} {apps.isPending || (problemOnly && lookup.loading) ? ( diff --git a/web/src/features/discover/search.test.ts b/web/src/features/discover/search.test.ts index fec8507..dff233b 100644 --- a/web/src/features/discover/search.test.ts +++ b/web/src/features/discover/search.test.ts @@ -8,7 +8,7 @@ const app = businessAppOf({ id: 'inventory', slug: 'inventory', displayName: '備品棚卸', description: '在庫と発注を確認', icon: '', tags: ['備品'], group: { id: 'team-a', path: 'sales/team-a', name: '営業1課' }, owners: [owner], createdBy: owner, stackId: null, appName: null, share: { scope: 'company', groupIds: [], extraPersonIds: [] }, createdAt: '', updatedAt: '', - guide: '月末に集計してください', capabilities: ['PDF で一覧を出す', '注文書を作る'], screenshots: [], + guide: '月末に集計してください', capabilities: ['PDF で一覧を出す', '注文書を作る'], screenshots: [], contribution: { scope: 'group' }, }) describe('matchesAppSearch', () => { @@ -40,7 +40,7 @@ const entry: DirectoryEntry = { id: app.id, path: `${app.group.path}/${app.slug}`, displayName: app.displayName, description: app.description, icon: app.icon, tags: app.tags, capabilities: app.capabilities, screenshots: [], group: app.group, owners: app.owners, appName: 'inventory', stackId: 'stack-inventory', - createdAt: app.createdAt, updatedAt: app.updatedAt, canOpen: false, + createdAt: app.createdAt, updatedAt: app.updatedAt, canOpen: false, contribution: app.contribution, permissions: app.permissions, } describe('matchesDirectoryEntrySearch', () => { diff --git a/web/src/features/improve/copy.en.ts b/web/src/features/improve/copy.en.ts index ea62cb4..3e37f2a 100644 --- a/web/src/features/improve/copy.en.ts +++ b/web/src/features/improve/copy.en.ts @@ -15,6 +15,7 @@ export const textEn: typeof textJa = { noSource: 'This app has no source location, so the AI cannot change it.', noReviewers: 'No owner has signed in yet. Ask an owner to sign in, then try again.', busy: 'Another conversation is in progress. Wait a moment and try again.', + openSession: 'A conversation is already in progress, and only one can run at a time. Continue that one.', }, page: { title: (name: string) => `${name} — Improve with AI`, diff --git a/web/src/features/improve/copy.ts b/web/src/features/improve/copy.ts index 11bb00e..e355b42 100644 --- a/web/src/features/improve/copy.ts +++ b/web/src/features/improve/copy.ts @@ -19,6 +19,7 @@ export const textJa = { noSource: 'このアプリには置き場がないため、AI では直せません。', noReviewers: '所有者がまだログインしていません。所有者がログインしてから、もう一度試してください。', busy: 'いま別の相談を進めています。少し待ってから、もう一度試してください。', + openSession: '進めている相談があります。同時に進められる相談は 1 つです。続きから直してください。', }, page: { title: (name: string) => `${name} — AI で直す`, diff --git a/web/src/features/improve/entry.test.tsx b/web/src/features/improve/entry.test.tsx new file mode 100644 index 0000000..e7e88e0 --- /dev/null +++ b/web/src/features/improve/entry.test.tsx @@ -0,0 +1,139 @@ +import { afterEach, beforeEach, expect, spyOn, test } from 'bun:test' +import type { ApplicationDraft } from '@appthrust/api-schema/platform-api' +import { QueryClient, QueryClientProvider } from '@tanstack/react-query' +import { createMemoryHistory, createRootRoute, createRoute, createRouter, RouterProvider } from '@tanstack/react-router' +import { act, useState, type ReactNode } from 'react' +import { createRoot } from 'react-dom/client' +import { preserveLanguage } from '../../../test/language' +import * as api from '../../api/build' +import { draftOf, turnOf } from '../../api/testing/build-domain' +import { setLanguage } from '../../shell/language' +import { text } from './copy' +import { ImproveButton, ImproveDialog } from './entry' + +const at = '2026-11-01T00:00:00Z' +const wire = (overrides: Partial = {}): ApplicationDraft => ({ + id: 'improve-draft', projectId: 'pj-demo', title: '台帳', kind: 'improvement', intent: '直したい', phase: 'specifying', specMarkdown: '', architectureMarkdown: '', + creationPlanGenerations: [], conversationTurns: [], creationExecutions: [], implementationRuns: [], createdSourceRepositories: [], ownerUserId: 'owner', createdAt: at, updatedAt: at, + ...overrides, +}) + +let restoreLanguage: () => void +let cleanups: (() => void | Promise)[] = [] +beforeEach(() => { + restoreLanguage = preserveLanguage() + setLanguage('ja') +}) +afterEach(async () => { + for (const cleanup of cleanups.reverse()) await cleanup() + cleanups = [] + restoreLanguage() +}) + +function spies(existing: ApplicationDraft[] = []) { + const create = spyOn(api, 'createDraft').mockImplementation(async (_projectId, input) => draftOf(wire({ intent: input.intent }))) + const list = spyOn(api, 'listDrafts').mockResolvedValue({ data: existing.map(draftOf), unreadable: [] }) + const turn = spyOn(api, 'createTurn').mockImplementation(async (_projectId, _draftId, payload) => turnOf({ id: 'turn-1', kind: 'conversation', userMessage: payload.message, status: 'pending', startedAt: at, devWorkspaceId: 'workspace' })) + cleanups.push(() => { create.mockRestore(); list.mockRestore(); turn.mockRestore() }) + return { create, list, turn } +} + +async function render(node: ReactNode) { + const client = new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + const container = document.createElement('div') + document.body.append(container) + const root = createRoot(container) + const rootRoute = createRootRoute() + const route = createRoute({ getParentRoute: () => rootRoute, path: '/', component: () => <>{node} }) + const destination = createRoute({ getParentRoute: () => rootRoute, path: '/-/improve/$draftId', component: () =>

    改善

    }) + const router = createRouter({ routeTree: rootRoute.addChildren([route, destination]), history: createMemoryHistory({ initialEntries: ['/'] }) }) + await router.load() + await act(async () => { root.render() }) + cleanups.push(async () => { + await act(async () => { root.unmount() }) + container.remove() + client.clear() + }) + return { router } +} + +async function settle() { + for (let tick = 0; tick < 4; tick++) await act(async () => { await Bun.sleep(5) }) +} + +const textarea = () => document.querySelector('[role="dialog"] textarea') +const submit = () => [...document.querySelectorAll('[role="dialog"] button')].find((button) => button.textContent === text.entry.submit) + +/** React tracks the textarea value itself; set it the way typing does. */ +function type(element: HTMLTextAreaElement, value: string) { + Object.getOwnPropertyDescriptor(window.HTMLTextAreaElement.prototype, 'value')!.set!.call(element, value) + element.dispatchEvent(new Event('input', { bubbles: true })) +} + +function Fix({ body }: { body: string }) { + const [open, setOpen] = useState(false) + return <> + + + +} + +test('a draft opens the question filled in, nothing is sent until 「相談をはじめる」, and the edited text is what starts', async () => { + const { create, turn } = spies() + const { router } = await render() + await act(async () => { document.querySelector('[data-testid="fix"]')!.click() }) + await settle() + expect(textarea()?.value).toBe('一覧を部署で絞り込みたいです。') + expect(create).not.toHaveBeenCalled() + await act(async () => { type(textarea()!, '一覧を部署と期間で絞り込めるようにする') }) + await act(async () => { submit()!.click() }) + await settle() + expect(create).toHaveBeenCalledWith('pj-demo', { kind: 'improvement', applicationStackId: 'stack-web', title: '台帳', intent: '一覧を部署と期間で絞り込めるようにする' }) + expect(turn).toHaveBeenCalledWith('pj-demo', 'improve-draft', { message: '一覧を部署と期間で絞り込めるようにする' }) + expect(router.state.location.pathname).toBe('/-/improve/improve-draft') +}) + +test('without a draft or a first message the button asks with an empty question, as before', async () => { + const { create } = spies() + await render() + await settle() + await act(async () => { document.querySelector('[data-testid="improve-with-ai"]')!.click() }) + await settle() + expect(textarea()?.value).toBe('') + expect(submit()?.disabled).toBe(true) + expect(create).not.toHaveBeenCalled() +}) + +test('a caller refusal is worded first, the caller wording and tone replace the defaults', async () => { + spies() + const create = spyOn(api, 'createDraft').mockRejectedValue(new Error('forbidden')) + cleanups.push(() => create.mockRestore()) + const wording = { action: '直しを提案する', title: '直しを提案する', description: (app: string) => `「${app}」の提案` } + await render( 'このアプリは、いま提案を受け付けていません。'} />) + await settle() + const button = document.querySelector('[data-testid="improve-with-ai"]')! + expect(button.textContent).toBe('直しを提案する') + expect(button.className).toContain('border-stone-300') + await act(async () => { button.click() }) + await settle() + expect(document.querySelector('[role="dialog"]')?.textContent).toContain('「台帳」の提案') + expect(textarea()?.value).toBe('下書き') + await act(async () => { submit()!.click() }) + await settle() + expect(document.querySelector('[role="dialog"] [role="alert"]')?.textContent).toBe('このアプリは、いま提案を受け付けていません。') +}) + +test('opened from elsewhere while a session runs on the stack, the dialog offers that session instead of a second start', async () => { + const { create } = spies([wire({ id: 'running', createdApplicationStackId: 'stack-web' } as Partial)]) + const { router } = await render() + await act(async () => { document.querySelector('[data-testid="fix"]')!.click() }) + await settle() + const dialog = document.querySelector('[role="dialog"]')! + expect(dialog.textContent).toContain(text.entry.openSession) + expect(submit()?.disabled).toBe(true) + const resume = [...dialog.querySelectorAll('button')].find((button) => button.textContent === text.drafts.resume)! + await act(async () => { resume.click() }) + await settle() + expect(create).not.toHaveBeenCalled() + expect(router.state.location.pathname).toBe('/-/improve/running') +}) diff --git a/web/src/features/improve/entry.tsx b/web/src/features/improve/entry.tsx index fc23aef..b8b6042 100644 --- a/web/src/features/improve/entry.tsx +++ b/web/src/features/improve/entry.tsx @@ -17,21 +17,19 @@ import { UnconfirmedNotice } from '../build/unconfirmed-notice' import { proposalOptions } from '../../api/queries/proposal' import { proposalTerminal } from '../proposals/model' +/** The words of the entry: 「AIで直す」 by default; a proposer's entry passes its own (ux-design §8). */ +export type ImproveWording = { action: string; title: string; description: (app: string) => string } + +type ImproveTarget = { app: Pick; stackId: string; projectId: string } + /** - * 「AIで直す」 on a bound app: resumes the newest open improvement session for - * the app's stack, or asks what to change and starts one. The first message is - * also the session's first turn, so the AI answers as soon as the page opens. + * Starting a session: the first message is also its first turn, so the AI answers as soon as the page opens. + * After an unreadable answer the session may exist: `confirmLatest` reads the list back and opens the one that + * was made; nothing is resent from here. */ -export function ImproveButton({ app, stackId, projectId, initialMessage, actionLabel }: { - app: Pick; stackId: string; projectId: string - initialMessage?: string; actionLabel?: string -}) { +function useImproveStart({ app, stackId, projectId }: ImproveTarget) { const navigate = useNavigate() const queryClient = useQueryClient() - const drafts = useQuery(draftsOptions(projectId)) - const [open, setOpen] = useState(false) - const [intent, setIntent] = useState('') - const inputId = useId() const start = useMutation({ mutationFn: async (message: string) => { const draft = await createDraft(projectId, { kind: 'improvement', applicationStackId: stackId, intent: message, title: app.displayName }) @@ -44,22 +42,36 @@ export function ImproveButton({ app, stackId, projectId, initialMessage, actionL await navigate({ href: paths.improve(draft.id) }) }, // The session may have been created even though its answer could not be read: read the list back so - // the button resumes it instead of starting another one. Nothing is resent. + // the entry resumes it instead of starting another one. Nothing is resent. onError: (error) => { if (isResponseContractError(error)) void queryClient.invalidateQueries({ queryKey: buildKeys.drafts(projectId) }) }, }) - const status = platformErrorEnvelope(start.error)?.status - const unconfirmed = isResponseContractError(start.error) - /** After an unreadable start: read the sessions back and open the one that was made; never start another from here. */ - const confirmLatest = async () => { + const confirmLatest = async (onFound?: () => void) => { const latest = await queryClient.fetchQuery({ ...draftsOptions(projectId), staleTime: 0 }).catch(() => undefined) start.reset() const made = improvementFor(latest?.data, stackId) - if (made) { setOpen(false); await navigate({ href: paths.improve(made.id) }) } + if (made) { onFound?.(); await navigate({ href: paths.improve(made.id) }) } } - const trimmed = intent.trim() - const ready = trimmed.length > 0 && trimmed.length <= MAX_LENGTH && !start.isPending + return { start, unconfirmed: isResponseContractError(start.error), confirmLatest } +} + +/** + * 「AIで直す」 on a bound app: resumes the newest open improvement session for the app's stack, or asks what to + * change and starts one. `initialMessage` starts at once with that text (the build failure's one-click repair); + * `draft` instead opens the question with that text filled in, to be edited before 「相談をはじめる」. + */ +export function ImproveButton({ app, stackId, projectId, initialMessage, draft, actionLabel, wording, tone = 'primary', refusal }: ImproveTarget & { + initialMessage?: string; draft?: string; actionLabel?: string + wording?: ImproveWording; tone?: 'primary' | 'secondary' + /** A refusal this caller words itself (checked before the generic 412/409 wording); undefined falls through. */ + refusal?: (error: unknown) => string | undefined +}) { + const navigate = useNavigate() + const queryClient = useQueryClient() + const drafts = useQuery(draftsOptions(projectId)) + const [open, setOpen] = useState(false) + const oneClick = useImproveStart({ app, stackId, projectId }) const onClick = async () => { - if (initialMessage) { start.mutate(initialMessage); return } + if (initialMessage) { oneClick.start.mutate(initialMessage); return } const existing = improvementFor(drafts.data?.data, stackId) if (existing?.proposalId) { try { @@ -72,25 +84,65 @@ export function ImproveButton({ app, stackId, projectId, initialMessage, actionL if (existing) void navigate({ href: paths.improve(existing.id) }) else setOpen(true) } + return <> + + {initialMessage && oneClick.start.error ? oneClick.unconfirmed ? void oneClick.confirmLatest()} /> : : null} + + +} + +/** + * The question 「どこを直しますか?」 and its start. `draft` fills the answer in each time the dialog opens; the + * person edits it before starting. Opened by a caller of its own (「これを AIで直す」 on a comment), the dialog + * itself checks for an open session on the stack: that one is resumed instead, since a stack takes one at a time. + */ +export function ImproveDialog({ app, stackId, projectId, open, onOpenChange, draft, wording, refusal }: ImproveTarget & { + open: boolean + onOpenChange: (open: boolean) => void + draft?: string + wording?: ImproveWording + refusal?: (error: unknown) => string | undefined +}) { + const navigate = useNavigate() + const { start, unconfirmed, confirmLatest } = useImproveStart({ app, stackId, projectId }) + const [intent, setIntent] = useState(draft ?? '') + // Each opening starts from the caller's draft; without one, what was typed stays across a cancel (as before). + const [shownOpen, setShownOpen] = useState(open) + if (shownOpen !== open) { + setShownOpen(open) + if (open && draft !== undefined) setIntent(draft) + } + const drafts = useQuery({ ...draftsOptions(projectId), enabled: open && draft !== undefined }) + const existing = draft !== undefined ? improvementFor(drafts.data?.data, stackId) : undefined + const existingProposal = useQuery({ ...proposalOptions(projectId, existing?.proposalId), enabled: open && Boolean(existing?.proposalId) }) + const resumable = existing && !(existingProposal.data && proposalTerminal(existingProposal.data.phase)) ? existing : undefined + const inputId = useId() + const status = platformErrorEnvelope(start.error)?.status + const trimmed = intent.trim() + const ready = trimmed.length > 0 && trimmed.length <= MAX_LENGTH && !start.isPending && !resumable + const refused = start.error ? refusal?.(start.error) : undefined const change = (next: boolean) => { if (start.isPending) return if (!next) start.reset() - setOpen(next) + onOpenChange(next) } - return <> - - {initialMessage && start.error ? unconfirmed ? void confirmLatest()} /> : : null} + return ( } >
    { event.preventDefault(); if (ready && !unconfirmed) start.mutate(trimmed) }}> + {resumable ? ( + { onOpenChange(false); void navigate({ href: paths.improve(resumable.id) }) }}>{text.drafts.resume}}> + {text.entry.openSession} + + ) : null}