create-signet-app 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +31 -8
  2. package/base/api/api/app.ts +57 -8
  3. package/base/api/api/db/schema.ts +16 -4
  4. package/base/api/api/env.ts +8 -0
  5. package/base/api/api/server.ts +6 -0
  6. package/base/api/api/services.ts +43 -3
  7. package/base/api/drizzle/0002_ai_paywalls_workflows.sql +77 -0
  8. package/base/api/drizzle/meta/0002_snapshot.json +1759 -0
  9. package/base/api/drizzle/meta/_journal.json +7 -0
  10. package/base/shared/README.md +87 -0
  11. package/base/web/index.html +5 -0
  12. package/base/web/src/main.tsx +2 -0
  13. package/base/web/src/routeTree.gen.ts +25 -0
  14. package/base/web/src/router.test.ts +1 -0
  15. package/base/web/src/routes/_app/index.tsx +7 -0
  16. package/base/web/src/routes/_app.tsx +96 -49
  17. package/package.json +5 -2
  18. package/parts/ai/api/api/routes/ai.ts +28 -0
  19. package/parts/ai/api/test/ai.test.ts +52 -0
  20. package/parts/ai/part.ts +16 -0
  21. package/parts/dashboard/part.ts +6 -0
  22. package/parts/dashboard/web/src/components/overview.test.tsx +16 -0
  23. package/parts/dashboard/web/src/components/overview.tsx +175 -0
  24. package/parts/paywalls/api/api/routes/paywall.ts +126 -0
  25. package/parts/paywalls/api/test/paywalls.test.ts +71 -0
  26. package/parts/paywalls/part.ts +8 -0
  27. package/parts/pwa/part.ts +6 -0
  28. package/parts/pwa/web/public/icon.svg +6 -0
  29. package/parts/pwa/web/public/manifest.webmanifest +10 -0
  30. package/parts/pwa/web/public/sw.js +69 -0
  31. package/parts/pwa/web/src/components/install-button.tsx +14 -0
  32. package/parts/pwa/web/src/lib/pwa.ts +39 -0
  33. package/parts/workflows/api/api/workflows.ts +33 -0
  34. package/parts/workflows/api/test/workflows.test.ts +44 -0
  35. package/parts/workflows/part.ts +7 -0
  36. package/parts/workflows/web/src/routes/_app/approvals.tsx +34 -0
  37. package/src/compose.ts +107 -30
  38. package/src/desktop.ts +1 -1
  39. package/src/index.ts +49 -8
@@ -15,6 +15,13 @@
15
15
  "when": 1794721249978,
16
16
  "tag": "0001_orgs",
17
17
  "breakpoints": true
18
+ },
19
+ {
20
+ "idx": 2,
21
+ "version": "6",
22
+ "when": 1795005508302,
23
+ "tag": "0002_ai_paywalls_workflows",
24
+ "breakpoints": true
18
25
  }
19
26
  ]
20
27
  }
@@ -14,6 +14,9 @@ It has:
14
14
  - an in-app inbox <!-- @notifications -->
15
15
  - privacy (DPDP consent and data requests) <!-- @privacy -->
16
16
  - plans and billing <!-- @payments -->
17
+ - remote paywalls <!-- @paywalls -->
18
+ - AI spend caps and a sample AI route <!-- @ai -->
19
+ - durable workflows with approval steps <!-- @workflows -->
17
20
  - an admin panel over the whole database <!-- @admin -->
18
21
  - MCP for agents at `/mcp` <!-- @mcp -->
19
22
  <!-- auth:end -->
@@ -134,6 +137,84 @@ each plan allows, `PLAN_DISPLAY` the name, description and price the page shows.
134
137
  Keep it in step with the API.
135
138
  <!-- !api:end -->
136
139
  <!-- payments:end -->
140
+ <!-- paywalls:begin -->
141
+
142
+ ### Paywalls (2 minutes)
143
+
144
+ A placement ("onboarding", "upgrade") serves an offering: products mapped to
145
+ plans, and what the paywall says. `GET /api/paywall/<placement>?country=IN&platform=web`
146
+ returns the one for the caller: the first audience override that matches,
147
+ else the placement's own, and 404 until the placement exists. Each publish is
148
+ a new version and a published one never changes, so what a paywall sells
149
+ changes without a release.
150
+ <!-- admin:begin -->
151
+
152
+ Admins and staff publish with `POST /api/admin/paywalls/offerings/<key>`
153
+ (`{ products, paywall }`) and point a placement at it with
154
+ `PUT /api/admin/paywalls/placements/<placement>` (`{ offering, overrides? }`).
155
+ The admin panel lists both tables read only.
156
+ <!-- admin:end -->
157
+ <!-- !admin:begin -->
158
+
159
+ Publish from code, e.g. in a seed script:
160
+
161
+ ```ts
162
+ const actor = { type: "system" as const, id: "seed" }
163
+ const products = [{ id: "plan_pro_monthly", store: "web", plan: "pro" }]
164
+ await s.offerings.publish("standard", { products, paywall: { title: "Go further" } }, { actor })
165
+ await s.offerings.setPlacement("upgrade", { offering: "standard" }, { actor })
166
+ ```
167
+ <!-- !admin:end -->
168
+ <!-- paywalls:end -->
169
+ <!-- ai:begin -->
170
+
171
+ ### AI (2 minutes)
172
+
173
+ `POST /api/ai/summary` with `{ "text": "..." }` answers from a canned
174
+ provider, so it runs with no key. Each call costs $0.001, charged to the
175
+ caller's daily cap (`AI_CAP_USER_DAY`) and the app's monthly one
176
+ (`AI_CAP_GLOBAL_MONTH`), in cost units: 1,000,000 is one US dollar. Over a
177
+ cap, every `/api/ai` route answers 429 with `Retry-After` before it runs.
178
+ Spend is counted in `usage_counters`; a cap stored in `ai_spend_caps` wins
179
+ over the env ones.
180
+ Admins read spend and set caps per user or for the app under <!-- @admin -->
181
+ `/api/admin/ai-spend` (`GET /usage`, `GET /caps`, `PUT /caps`). <!-- @admin -->
182
+ Set one from code with `s.aiSpend.setCap({ scope, subject, period, units })`. <!-- @!admin -->
183
+
184
+ For a real model, replace the fake provider in `api/services.ts` with yours
185
+ (a signet-ai `Provider`: name, model, `pricing`, and `generate`); its pricing
186
+ is what the caps count. Copy `api/routes/ai.ts` for your own AI routes.
187
+ <!-- ai:end -->
188
+ <!-- workflows:begin -->
189
+
190
+ ### Workflows (5 minutes)
191
+
192
+ <!-- api:begin -->
193
+ `api/workflows.ts` has one workflow, a generic approval request: someone
194
+ asks, one of the listed approvers approves or rejects, and the run ends with
195
+ the decision. `api/server.ts` runs the runner: every second it takes the runs
196
+ that are due, including any a restart cut short.
197
+ <!-- web:begin -->
198
+ **Approvals** lists the approval steps waiting on you.
199
+ <!-- web:end -->
200
+
201
+ Start one with `POST /api/workflows/runs` and
202
+ `{ "workflow": "approval-request", "input": { "summary": "...", "approvers": ["<user id>"] } }`.
203
+ Approvers find it at `GET /api/workflows/approvals` and decide with
204
+ `POST /api/workflows/runs/<id>/steps/approval/approve` (or `reject`); admins
205
+ see every run at `GET /api/workflows/runs`.
206
+
207
+ Add your own with `defineWorkflow` in `api/workflows.ts` and list it in
208
+ `WORKFLOWS`. Put each side effect in `step.run`, so a replay after a restart
209
+ does not repeat it. Who may start which workflow over HTTP is `canStart` in
210
+ `api/app.ts`.
211
+ <!-- api:end -->
212
+ <!-- !api:begin -->
213
+ **Approvals** lists the approval steps waiting on you, from your API's
214
+ `/api/workflows` (an app made with `--api --with workflows` serves it), each
215
+ with Approve and Reject.
216
+ <!-- !api:end -->
217
+ <!-- workflows:end -->
137
218
 
138
219
  ### Build your first feature (the rest of the day)
139
220
 
@@ -208,6 +289,7 @@ your lockfile.
208
289
  api/
209
290
  app.ts routes, the signed-in gate, MCP; exports AppType for the client
210
291
  plans.ts plans and what the billing page shows (shared with the browser) <!-- @payments -->
292
+ workflows.ts the workflows the runner runs <!-- @workflows -->
211
293
  services.ts what the routes use, built once per process
212
294
  routes/ one file per area <!-- @auth -->
213
295
  db/schema.ts every table; drizzle/ holds the migrations
@@ -267,6 +349,11 @@ Before production:
267
349
  Fulfil them with `privacy.fulfil(id, { actor })` (export returns the data to
268
350
  send; erasure deletes the user's rows listed in `userTables`).
269
351
  <!-- privacy:end -->
352
+ <!-- ai:begin -->
353
+ - **AI.** `api/services.ts` answers from a canned provider. Put a real one
354
+ there, and set `AI_CAP_USER_DAY` and `AI_CAP_GLOBAL_MONTH` to what you will
355
+ pay.
356
+ <!-- ai:end -->
270
357
  <!-- auth:end -->
271
358
  <!-- api:end -->
272
359
  <!-- !api:begin -->
@@ -4,6 +4,11 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>__APP_NAME__</title>
7
+ <!-- pwa:begin -->
8
+ <link rel="manifest" href="/manifest.webmanifest" />
9
+ <link rel="icon" href="/icon.svg" type="image/svg+xml" />
10
+ <meta name="theme-color" content="#ffffff" />
11
+ <!-- pwa:end -->
7
12
  <!-- Applies the stored theme before first paint. React mounts too late;
8
13
  without this there is a visible flash of the wrong theme on load. -->
9
14
  <script>
@@ -6,11 +6,13 @@ import { RouterProvider } from "@tanstack/react-router"
6
6
  import { StrictMode } from "react"
7
7
  import { createRoot } from "react-dom/client"
8
8
  import { Toaster } from "./components/toaster"
9
+ import { registerPwa } from "./lib/pwa" // @pwa
9
10
  import { createAppRouter } from "./router"
10
11
  import "./app.css"
11
12
 
12
13
  const queryClient = new QueryClient({ defaultOptions: queryDefaults() })
13
14
  const router = createAppRouter()
15
+ registerPwa() // @pwa
14
16
  // auth:begin
15
17
 
16
18
  // One redirect on session expiry, however many requests fail at once. A full
@@ -14,6 +14,7 @@ import { Route as LoginRouteImport } from "./routes/login" // @auth
14
14
  import { Route as AppIndexRouteImport } from "./routes/_app/index"
15
15
  import { Route as AppAccountRouteImport } from "./routes/_app/account" // @account
16
16
  import { Route as AppAdminRouteImport } from "./routes/_app/admin" // @admin
17
+ import { Route as AppApprovalsRouteImport } from "./routes/_app/approvals" // @workflows
17
18
  import { Route as AppBillingRouteImport } from "./routes/_app/billing" // @payments
18
19
  import { Route as AppNotificationsRouteImport } from "./routes/_app/notifications" // @notifications
19
20
  import { Route as AppPrivacyRouteImport } from "./routes/_app/privacy" // @privacy
@@ -52,6 +53,13 @@ const AppAdminRoute = AppAdminRouteImport.update({
52
53
  getParentRoute: () => AppRoute,
53
54
  } as any)
54
55
  // admin:end
56
+ // workflows:begin
57
+ const AppApprovalsRoute = AppApprovalsRouteImport.update({
58
+ id: "/approvals",
59
+ path: "/approvals",
60
+ getParentRoute: () => AppRoute,
61
+ } as any)
62
+ // workflows:end
55
63
  // payments:begin
56
64
  const AppBillingRoute = AppBillingRouteImport.update({
57
65
  id: "/billing",
@@ -107,6 +115,7 @@ export interface FileRoutesByFullPath {
107
115
  "/login": typeof LoginRoute // @auth
108
116
  "/account": typeof AppAccountRoute // @account
109
117
  "/admin": typeof AppAdminRoute // @admin
118
+ "/approvals": typeof AppApprovalsRoute // @workflows
110
119
  "/billing": typeof AppBillingRoute // @payments
111
120
  "/notifications": typeof AppNotificationsRoute // @notifications
112
121
  "/privacy": typeof AppPrivacyRoute // @privacy
@@ -119,6 +128,7 @@ export interface FileRoutesByTo {
119
128
  "/login": typeof LoginRoute // @auth
120
129
  "/account": typeof AppAccountRoute // @account
121
130
  "/admin": typeof AppAdminRoute // @admin
131
+ "/approvals": typeof AppApprovalsRoute // @workflows
122
132
  "/billing": typeof AppBillingRoute // @payments
123
133
  "/notifications": typeof AppNotificationsRoute // @notifications
124
134
  "/privacy": typeof AppPrivacyRoute // @privacy
@@ -134,6 +144,7 @@ export interface FileRoutesById {
134
144
  "/login": typeof LoginRoute // @auth
135
145
  "/_app/account": typeof AppAccountRoute // @account
136
146
  "/_app/admin": typeof AppAdminRoute // @admin
147
+ "/_app/approvals": typeof AppApprovalsRoute // @workflows
137
148
  "/_app/billing": typeof AppBillingRoute // @payments
138
149
  "/_app/notifications": typeof AppNotificationsRoute // @notifications
139
150
  "/_app/privacy": typeof AppPrivacyRoute // @privacy
@@ -150,6 +161,7 @@ export interface FileRouteTypes {
150
161
  | "/login" // @auth
151
162
  | "/account" // @account
152
163
  | "/admin" // @admin
164
+ | "/approvals" // @workflows
153
165
  | "/billing" // @payments
154
166
  | "/notifications" // @notifications
155
167
  | "/privacy" // @privacy
@@ -162,6 +174,7 @@ export interface FileRouteTypes {
162
174
  | "/login" // @auth
163
175
  | "/account" // @account
164
176
  | "/admin" // @admin
177
+ | "/approvals" // @workflows
165
178
  | "/billing" // @payments
166
179
  | "/notifications" // @notifications
167
180
  | "/privacy" // @privacy
@@ -176,6 +189,7 @@ export interface FileRouteTypes {
176
189
  | "/login" // @auth
177
190
  | "/_app/account" // @account
178
191
  | "/_app/admin" // @admin
192
+ | "/_app/approvals" // @workflows
179
193
  | "/_app/billing" // @payments
180
194
  | "/_app/notifications" // @notifications
181
195
  | "/_app/privacy" // @privacy
@@ -235,6 +249,15 @@ declare module "@tanstack/react-router" {
235
249
  parentRoute: typeof AppRoute
236
250
  }
237
251
  // admin:end
252
+ // workflows:begin
253
+ "/_app/approvals": {
254
+ id: "/_app/approvals"
255
+ path: "/approvals"
256
+ fullPath: "/approvals"
257
+ preLoaderRoute: typeof AppApprovalsRouteImport
258
+ parentRoute: typeof AppRoute
259
+ }
260
+ // workflows:end
238
261
  // payments:begin
239
262
  "/_app/billing": {
240
263
  id: "/_app/billing"
@@ -304,6 +327,7 @@ declare module "@tanstack/react-router" {
304
327
  interface AppRouteChildren {
305
328
  AppAccountRoute: typeof AppAccountRoute // @account
306
329
  AppAdminRoute: typeof AppAdminRoute // @admin
330
+ AppApprovalsRoute: typeof AppApprovalsRoute // @workflows
307
331
  AppBillingRoute: typeof AppBillingRoute // @payments
308
332
  AppNotificationsRoute: typeof AppNotificationsRoute // @notifications
309
333
  AppPrivacyRoute: typeof AppPrivacyRoute // @privacy
@@ -316,6 +340,7 @@ interface AppRouteChildren {
316
340
  const AppRouteChildren: AppRouteChildren = {
317
341
  AppAccountRoute: AppAccountRoute, // @account
318
342
  AppAdminRoute: AppAdminRoute, // @admin
343
+ AppApprovalsRoute: AppApprovalsRoute, // @workflows
319
344
  AppBillingRoute: AppBillingRoute, // @payments
320
345
  AppNotificationsRoute: AppNotificationsRoute, // @notifications
321
346
  AppPrivacyRoute: AppPrivacyRoute, // @privacy
@@ -13,6 +13,7 @@ test.each([
13
13
  ["/privacy", "/_app/privacy"], // @privacy
14
14
  ["/billing", "/_app/billing"], // @payments
15
15
  ["/admin", "/_app/admin"], // @admin
16
+ ["/approvals", "/_app/approvals"], // @workflows
16
17
  // orgs:begin
17
18
  ["/org", "/_app/org/"],
18
19
  ["/org/members", "/_app/org/members"],
@@ -1,8 +1,12 @@
1
+ // !dashboard:begin
1
2
  import { Card, CardContent, CardHeader, CardTitle } from "@dapplelight/signet-ui/components/card"
2
3
  import { useQuery } from "@tanstack/react-query" // @auth
3
4
  import { createFileRoute, Link } from "@tanstack/react-router" // @payments
4
5
  import { createFileRoute } from "@tanstack/react-router" // @!payments
5
6
  import { meQuery } from "../../lib/api" // @auth
7
+ // !dashboard:end
8
+ import { createFileRoute } from "@tanstack/react-router" // @dashboard
9
+ import { Overview } from "../../components/overview" // @dashboard
6
10
 
7
11
  export const Route = createFileRoute("/_app/")({
8
12
  component: Home,
@@ -11,6 +15,8 @@ export const Route = createFileRoute("/_app/")({
11
15
  // Your product goes here. The other pages are already wired; this one is
12
16
  // yours.
13
17
  function Home() {
18
+ return <Overview /> // @dashboard
19
+ // !dashboard:begin
14
20
  // auth:begin
15
21
  const me = useQuery(meQuery).data
16
22
  return (
@@ -52,4 +58,5 @@ function Home() {
52
58
  </Card>
53
59
  )
54
60
  // !auth:end
61
+ // !dashboard:end
55
62
  }
@@ -1,5 +1,15 @@
1
1
  import { Badge } from "@dapplelight/signet-ui/components/badge" // @notifications
2
2
  import { Button } from "@dapplelight/signet-ui/components/button" // @auth
3
+ // dashboard:begin
4
+ import {
5
+ Sidebar,
6
+ SidebarContent,
7
+ SidebarHeader,
8
+ SidebarInset,
9
+ SidebarProvider,
10
+ SidebarTrigger,
11
+ } from "@dapplelight/signet-ui/components/sidebar"
12
+ // dashboard:end
3
13
  import { ThemeToggle } from "@dapplelight/signet-ui/components/theme-toggle"
4
14
  import { OrgSwitcher } from "@dapplelight/signet-ui/screens/org-screens" // @orgs
5
15
  import { useQuery } from "@tanstack/react-query" // @orgs
@@ -8,6 +18,7 @@ import { useQuery } from "@tanstack/react-query" // @notifications
8
18
  // !orgs:end
9
19
  import { createFileRoute, Link, Outlet, useNavigate } from "@tanstack/react-router" // @orgs
10
20
  import { createFileRoute, Link, Outlet } from "@tanstack/react-router" // @!orgs
21
+ import { InstallButton } from "../components/install-button" // @pwa
11
22
  // auth:begin
12
23
  import { api, currentOrgQuery, meQuery, orgsQuery, switchOrg } from "../lib/api" // @admin
13
24
  // !admin:begin
@@ -29,6 +40,7 @@ const NAV = [
29
40
  { to: "/billing", label: "Billing" }, // @payments
30
41
  { to: "/account", label: "Account" }, // @account
31
42
  { to: "/privacy", label: "Privacy" }, // @privacy
43
+ { to: "/approvals", label: "Approvals" }, // @workflows
32
44
  { to: "/org", label: "Org" }, // @orgs
33
45
  ] as const
34
46
 
@@ -47,65 +59,100 @@ function AppLayout() {
47
59
  const current = useQuery({ ...currentOrgQuery, retry: false }).data
48
60
  // orgs:end
49
61
 
62
+ const link =
63
+ "rounded-md px-2 py-1 text-muted-foreground data-[status=active]:bg-muted data-[status=active]:text-foreground"
64
+ const nav = (
65
+ <>
66
+ {NAV.map((n) => (
67
+ <Link key={n.to} to={n.to} className={link}>
68
+ {n.label}
69
+ {/* notifications:begin */}
70
+ {n.to === "/notifications" && unread ? <Badge className="ml-1">{unread}</Badge> : null}
71
+ {/* notifications:end */}
72
+ </Link>
73
+ ))}
74
+ {/* admin:begin */}
75
+ {staff ? (
76
+ <Link to="/admin" className={link}>
77
+ Admin
78
+ </Link>
79
+ ) : null}
80
+ {/* admin:end */}
81
+ </>
82
+ )
83
+ // orgs:begin
84
+ // Every org you belong to; switching reloads into the other one.
85
+ const switcher = (
86
+ <OrgSwitcher
87
+ className="w-48"
88
+ orgs={orgs}
89
+ currentId={current?.org.id ?? null}
90
+ onSwitch={(id) => switchOrg(id)}
91
+ onCreate={() => navigate({ to: "/org/new" })}
92
+ />
93
+ )
94
+ // orgs:end
95
+ const actions = (
96
+ <>
97
+ <InstallButton /> {/* @pwa */}
98
+ <ThemeToggle />
99
+ {/* auth:begin */}
100
+ <Button
101
+ variant="ghost"
102
+ size="sm"
103
+ onClick={async () => {
104
+ await api.auth["sign-out"].$post()
105
+ window.location.assign("/login")
106
+ }}
107
+ >
108
+ Sign out
109
+ </Button>
110
+ {/* auth:end */}
111
+ </>
112
+ )
113
+
114
+ // dashboard:begin
115
+ // The nav in a sidebar: a drawer on phones, collapsed with Ctrl+B / Cmd+B.
116
+ return (
117
+ <SidebarProvider>
118
+ <Sidebar collapsible="offcanvas" aria-label="Main">
119
+ <SidebarHeader className="px-4 py-3">
120
+ <Link to="/" className="font-medium">
121
+ __APP_NAME__
122
+ </Link>
123
+ {switcher} {/* @orgs */}
124
+ </SidebarHeader>
125
+ <SidebarContent>
126
+ <nav className="flex flex-col gap-1 p-2 text-sm">{nav}</nav>
127
+ </SidebarContent>
128
+ </Sidebar>
129
+ <SidebarInset>
130
+ <header className="flex items-center gap-2 border-b border-border px-4 py-3">
131
+ <SidebarTrigger />
132
+ <div className="flex flex-1 items-center justify-end gap-2">{actions}</div>
133
+ </header>
134
+ <div className="mx-auto w-full max-w-6xl p-6">
135
+ <Outlet />
136
+ </div>
137
+ </SidebarInset>
138
+ </SidebarProvider>
139
+ )
140
+ // dashboard:end
141
+ // !dashboard:begin
50
142
  return (
51
143
  <>
52
144
  <header className="flex flex-wrap items-center gap-4 border-b border-border px-6 py-3">
53
145
  <Link to="/" className="font-medium">
54
146
  __APP_NAME__
55
147
  </Link>
56
- {/* orgs:begin */}
57
- {/* Every org you belong to; switching reloads into the other one. */}
58
- <OrgSwitcher
59
- className="w-48"
60
- orgs={orgs}
61
- currentId={current?.org.id ?? null}
62
- onSwitch={(id) => switchOrg(id)}
63
- onCreate={() => navigate({ to: "/org/new" })}
64
- />
65
- {/* orgs:end */}
66
- <nav className="flex flex-1 flex-wrap items-center gap-1 text-sm">
67
- {NAV.map((n) => (
68
- <Link
69
- key={n.to}
70
- to={n.to}
71
- className="rounded-md px-2 py-1 text-muted-foreground data-[status=active]:bg-muted data-[status=active]:text-foreground"
72
- >
73
- {n.label}
74
- {/* notifications:begin */}
75
- {n.to === "/notifications" && unread ? (
76
- <Badge className="ml-1">{unread}</Badge>
77
- ) : null}
78
- {/* notifications:end */}
79
- </Link>
80
- ))}
81
- {/* admin:begin */}
82
- {staff ? (
83
- <Link
84
- to="/admin"
85
- className="rounded-md px-2 py-1 text-muted-foreground data-[status=active]:bg-muted data-[status=active]:text-foreground"
86
- >
87
- Admin
88
- </Link>
89
- ) : null}
90
- {/* admin:end */}
91
- </nav>
92
- <ThemeToggle />
93
- {/* auth:begin */}
94
- <Button
95
- variant="ghost"
96
- size="sm"
97
- onClick={async () => {
98
- await api.auth["sign-out"].$post()
99
- window.location.assign("/login")
100
- }}
101
- >
102
- Sign out
103
- </Button>
104
- {/* auth:end */}
148
+ {switcher} {/* @orgs */}
149
+ <nav className="flex flex-1 flex-wrap items-center gap-1 text-sm">{nav}</nav>
150
+ {actions}
105
151
  </header>
106
152
  <main className="mx-auto max-w-3xl p-6">
107
153
  <Outlet />
108
154
  </main>
109
155
  </>
110
156
  )
157
+ // !dashboard:end
111
158
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-signet-app",
3
- "version": "0.5.0",
3
+ "version": "0.7.0",
4
4
  "license": "MIT",
5
5
  "description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
6
6
  "keywords": [
@@ -38,7 +38,10 @@
38
38
  ],
39
39
  "scripts": {
40
40
  "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
41
- "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/describe.ts"
41
+ "test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/describe.ts",
42
+ "test:parts": "bun run test/scaffold-parts.ts",
43
+ "test:pm": "bun run test/scaffold-pm.ts",
44
+ "test:runtime": "bun run test/scaffold-runtime.ts"
42
45
  },
43
46
  "dependencies": {
44
47
  "@dapplelight/signet-mcp": "^0.1.5"
@@ -0,0 +1,28 @@
1
+ import { spendKey } from "@dapplelight/signet-db/ai-spend"
2
+ import { zValidator } from "@dapplelight/signet-server/http/validate"
3
+ import { Hono } from "hono"
4
+ import { z } from "zod"
5
+ import type { AppEnv } from "../app.ts"
6
+ import type { Services } from "../services.ts"
7
+
8
+ /**
9
+ * AI routes. app.ts refuses any /api/ai call once the caller's or the app's
10
+ * spend cap is reached (requireAiSpend, 429 with Retry-After); each call is
11
+ * charged to the caller through `spendKey`. Copy this one for your own.
12
+ *
13
+ * POST /summary { text } → { summary, costUsd }
14
+ */
15
+ export const aiRoutes = (s: Services) =>
16
+ new Hono<AppEnv>().post(
17
+ "/summary",
18
+ zValidator("json", z.object({ text: z.string().min(1).max(10_000) })),
19
+ async (c) => {
20
+ const { value, meta } = await s.ai.extract({
21
+ schema: z.object({ summary: z.string() }),
22
+ instructions: "Summarise the text in one sentence.",
23
+ input: c.req.valid("json").text,
24
+ budget: { key: spendKey({ userId: c.get("user").id }) },
25
+ })
26
+ return c.json({ summary: value.summary, costUsd: meta.costUsd })
27
+ },
28
+ )
@@ -0,0 +1,52 @@
1
+ import { expect, test } from "bun:test"
2
+ import { eq } from "drizzle-orm" // @admin
3
+ import { spendCaps, users } from "../api/db/schema.ts" // @admin
4
+ import { spendCaps } from "../api/db/schema.ts" // @!admin
5
+ import { app, db, post, signIn } from "./helpers.ts"
6
+
7
+ const userId = async (cookie: string) => {
8
+ const me = await app.request("/api/account/me", { headers: { cookie } })
9
+ return ((await me.json()) as { user: { id: string } }).user.id
10
+ }
11
+
12
+ test("an AI call answers with no provider key, charged to the caller", async () => {
13
+ expect((await post("/api/ai/summary", { text: "Some text." })).status).toBe(401)
14
+ const cookie = await signIn("+919000000041")
15
+ const res = await post("/api/ai/summary", { text: "Some text to sum up." }, cookie)
16
+ expect(res.status).toBe(200)
17
+ expect(await res.json()).toEqual({ summary: "Some text to sum up.", costUsd: 0.001 })
18
+ })
19
+
20
+ test("over the caller's cap: 429 with Retry-After, and the route does not run", async () => {
21
+ const cookie = await signIn("+919000000042")
22
+ const id = await userId(cookie)
23
+ db.orm
24
+ .insert(spendCaps)
25
+ .values({ id: `user:${id}:day`, scope: "user", subject: id, period: "day", units: 0 })
26
+ .run()
27
+ const res = await post("/api/ai/summary", { text: "Some text." }, cookie)
28
+ expect(res.status).toBe(429)
29
+ expect(Number(res.headers.get("retry-after"))).toBeGreaterThan(0)
30
+ expect(((await res.json()) as { code: string }).code).toBe("AI_SPEND_CAP_EXCEEDED")
31
+ })
32
+ // admin:begin
33
+
34
+ test("admins read AI spend and set caps; everyone else gets 403", async () => {
35
+ const user = await signIn("+919000000043")
36
+ const headers = { cookie: user }
37
+ expect((await app.request("/api/admin/ai-spend/usage", { headers })).status).toBe(403)
38
+ const admin = await signIn("+919000000044")
39
+ db.orm.update(users).set({ role: "admin" }).where(eq(users.phone, "+919000000044")).run()
40
+ const cap = { scope: "user", subject: "*", period: "month", units: 50_000_000 }
41
+ const put = await app.request("/api/admin/ai-spend/caps", {
42
+ method: "PUT",
43
+ headers: { "content-type": "application/json", cookie: admin },
44
+ body: JSON.stringify(cap),
45
+ })
46
+ expect(put.status).toBe(200)
47
+ const caps = (await (
48
+ await app.request("/api/admin/ai-spend/caps", { headers: { cookie: admin } })
49
+ ).json()) as { caps: { id: string }[] }
50
+ expect(caps.caps.map((c) => c.id)).toContain("user:*:month")
51
+ })
52
+ // admin:end
@@ -0,0 +1,16 @@
1
+ import type { Part } from "../../src/compose.js"
2
+
3
+ export default {
4
+ description: "AI spend caps per user and app, and a sample /api/ai route on signet-ai",
5
+ needs: ["auth"],
6
+ apiOnly: true,
7
+ // signet-ai's main entry needs signet-lib (its error type) as a peer.
8
+ api: { deps: { "@dapplelight/signet-ai": "^0.5.0", "@dapplelight/signet-lib": "^0.4.0" } },
9
+ env: () => [
10
+ "# AI spend caps in cost units (1000000 = one US dollar); a cap stored in ai_spend_caps wins.",
11
+ "AI_CAP_USER_DAY=200000",
12
+ "AI_CAP_GLOBAL_MONTH=50000000",
13
+ ],
14
+ // usage_counters is payments' table too: it stays when either part is chosen.
15
+ tables: ["usage_counters", "ai_spend_caps"],
16
+ } satisfies Part
@@ -0,0 +1,6 @@
1
+ import type { Part } from "../../src/compose.js"
2
+
3
+ export default {
4
+ description: "a sidebar shell, and a home page of stat tiles, a chart and a table",
5
+ webOnly: true,
6
+ } satisfies Part
@@ -0,0 +1,16 @@
1
+ import { expect, test } from "bun:test"
2
+ import { renderToStaticMarkup } from "react-dom/server"
3
+ import { type OverviewData, OverviewView, SAMPLE_OVERVIEW } from "./overview"
4
+
5
+ // Each state renders its own thing, and only that.
6
+ test.each<["loading" | "error" | "ready", OverviewData | undefined, string]>([
7
+ ["loading", undefined, "Loading overview"],
8
+ ["error", undefined, "The overview did not load."],
9
+ ["ready", { stats: [], series: [], rows: [] }, "Nothing here yet"],
10
+ ["ready", SAMPLE_OVERVIEW, "Recent activity"],
11
+ ])("%s shows %#", (state, data, text) => {
12
+ const html = renderToStaticMarkup(<OverviewView state={state} data={data} />)
13
+ expect(html).toContain(text)
14
+ for (const other of ["Loading overview", "did not load", "Nothing here yet", "Recent activity"])
15
+ if (!text.includes(other)) expect(html).not.toContain(other)
16
+ })