wcz-layout 10.2.1 → 11.0.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 (122) hide show
  1. package/dist/ChatLayout-B0MBrI-Y.mjs +2394 -0
  2. package/dist/ChatLayout-B0MBrI-Y.mjs.map +1 -0
  3. package/dist/{Employee-C8xIlBxY.d.mts → ExtractFile-BQUXpuBS.d.mts} +44 -3
  4. package/dist/FileMeta-B5VU-eCi.d.mts +55 -0
  5. package/dist/FileMeta-BexXC_45.mjs +35 -0
  6. package/dist/FileMeta-BexXC_45.mjs.map +1 -0
  7. package/dist/QueryClientParam-BG9Q_9XU.d.mts +6 -0
  8. package/dist/Translate-Ad784Dps.d.mts +24 -0
  9. package/dist/{Approval-D1TfISUL.mjs → Translate-C43AmXYW.mjs} +44 -36
  10. package/dist/Translate-C43AmXYW.mjs.map +1 -0
  11. package/dist/User-CvLutatT.d.mts +10 -0
  12. package/dist/ai.d.mts +31 -4
  13. package/dist/ai.mjs +154 -10
  14. package/dist/ai.mjs.map +1 -1
  15. package/dist/auth.d.mts +7 -14
  16. package/dist/auth.mjs +15 -38
  17. package/dist/auth.mjs.map +1 -1
  18. package/dist/authMiddleware-ANa9Tlmp.mjs +45 -0
  19. package/dist/authMiddleware-ANa9Tlmp.mjs.map +1 -0
  20. package/dist/{ChatLayout-BmLySLXy.d.mts → components-2HKj8GpC.d.mts} +219 -255
  21. package/dist/components.d.mts +2 -126
  22. package/dist/components.mjs +876 -916
  23. package/dist/components.mjs.map +1 -1
  24. package/dist/data/client.d.mts +313 -55
  25. package/dist/data/client.mjs +10 -5
  26. package/dist/data/client.mjs.map +1 -1
  27. package/dist/data/server.d.mts +19 -3
  28. package/dist/data/server.mjs +3 -5
  29. package/dist/data/server.mjs.map +1 -1
  30. package/dist/env-C4WLVJMm.mjs +32 -0
  31. package/dist/env-C4WLVJMm.mjs.map +1 -0
  32. package/dist/file-DBqTibcr.mjs +176 -0
  33. package/dist/file-DBqTibcr.mjs.map +1 -0
  34. package/dist/file-hecCQszp.mjs +114 -0
  35. package/dist/file-hecCQszp.mjs.map +1 -0
  36. package/dist/generatedChart-k7NEdi5Z.mjs.map +1 -1
  37. package/dist/hooks.d.mts +13 -93
  38. package/dist/hooks.mjs +353 -1059
  39. package/dist/hooks.mjs.map +1 -1
  40. package/dist/i18n-ZRiIIdpb.mjs +563 -0
  41. package/dist/i18n-ZRiIIdpb.mjs.map +1 -0
  42. package/dist/index.d.mts +3 -35
  43. package/dist/index.mjs +630 -680
  44. package/dist/index.mjs.map +1 -1
  45. package/dist/layout-DeTB6Ai1.mjs +224 -0
  46. package/dist/layout-DeTB6Ai1.mjs.map +1 -0
  47. package/dist/middleware.d.mts +1 -1
  48. package/dist/middleware.mjs +2 -46
  49. package/dist/middleware.mjs.map +1 -1
  50. package/dist/models.d.mts +35 -43
  51. package/dist/models.mjs +4 -6
  52. package/dist/models.mjs.map +1 -1
  53. package/dist/oidc--D2ox365.mjs +97 -0
  54. package/dist/oidc--D2ox365.mjs.map +1 -0
  55. package/dist/peoplesoft-DhwB8jrM.d.mts +204 -0
  56. package/dist/tokens-C4djIAhl.mjs +97 -0
  57. package/dist/tokens-C4djIAhl.mjs.map +1 -0
  58. package/dist/useDialogs-QER-2rVG.mjs +297 -0
  59. package/dist/useDialogs-QER-2rVG.mjs.map +1 -0
  60. package/dist/user-DQx1BanQ.mjs +120 -0
  61. package/dist/user-DQx1BanQ.mjs.map +1 -0
  62. package/dist/{utils-CNYCSgip.d.mts → utils-BnyAEKW7.d.mts} +7 -9
  63. package/dist/utils-H4BskGF8.mjs +132 -0
  64. package/dist/utils-H4BskGF8.mjs.map +1 -0
  65. package/dist/utils.d.mts +21 -4
  66. package/dist/utils.mjs +5 -4
  67. package/dist/vite.mjs +98 -32
  68. package/dist/vite.mjs.map +1 -1
  69. package/package.json +23 -29
  70. package/skills/ai/SKILL.md +105 -75
  71. package/skills/general/SKILL.md +15 -8
  72. package/skills/general/references/auth.md +15 -17
  73. package/skills/general/references/languages.md +56 -0
  74. package/skills/migrations/versions/migrate-v10-to-v11.md +98 -22
  75. package/skills/migrations/versions/migrate-v9-to-v10.md +22 -22
  76. package/skills/services/SKILL.md +41 -7
  77. package/skills/services/docs/email.md +2 -2
  78. package/skills/services/docs/file.md +100 -85
  79. package/skills/services/docs/layout.md +129 -0
  80. package/skills/start/steps/02-project-name-setup.md +1 -1
  81. package/skills/start/steps/03-apm-setup.md +8 -1
  82. package/skills/start/steps/06-entra-setup.md +1 -1
  83. package/skills/start/steps/08-generate-favicon.md +1 -1
  84. package/skills/table/SKILL.md +18 -5
  85. package/src/lib/locales/cs.json +120 -0
  86. package/src/lib/locales/en.json +119 -0
  87. package/src/lib/locales/uk.json +121 -0
  88. package/src/lib/locales/zh-TW.json +118 -0
  89. package/dist/Approval-D1TfISUL.mjs.map +0 -1
  90. package/dist/ChatLayout-BpRj5rlH.mjs +0 -1639
  91. package/dist/ChatLayout-BpRj5rlH.mjs.map +0 -1
  92. package/dist/DialogsContext-D23fJjYR.mjs +0 -6
  93. package/dist/DialogsContext-D23fJjYR.mjs.map +0 -1
  94. package/dist/Email-Dz5k0UWE.d.mts +0 -15
  95. package/dist/FileMeta-B39e2FLC.d.mts +0 -17
  96. package/dist/FileMeta-CPBWI_jA.mjs +0 -18
  97. package/dist/FileMeta-CPBWI_jA.mjs.map +0 -1
  98. package/dist/QueryClientParam-CTV1vj76.d.mts +0 -8
  99. package/dist/RouterListItemButton-CF-8w-08.mjs +0 -62
  100. package/dist/RouterListItemButton-CF-8w-08.mjs.map +0 -1
  101. package/dist/User-aJksXItw.d.mts +0 -12
  102. package/dist/approval-B3ZQn9aH.mjs +0 -83
  103. package/dist/approval-B3ZQn9aH.mjs.map +0 -1
  104. package/dist/createApi-BXjkj4fM.mjs +0 -25
  105. package/dist/createApi-BXjkj4fM.mjs.map +0 -1
  106. package/dist/env-BwFl7nWc.mjs +0 -48
  107. package/dist/env-BwFl7nWc.mjs.map +0 -1
  108. package/dist/file-BQ-Bu2g8.mjs +0 -150
  109. package/dist/file-BQ-Bu2g8.mjs.map +0 -1
  110. package/dist/file-DZ0KYhoB.mjs +0 -151
  111. package/dist/file-DZ0KYhoB.mjs.map +0 -1
  112. package/dist/peoplesoft-C-zPdRVj.d.mts +0 -161
  113. package/dist/peoplesoft-CvwdApCK.mjs +0 -125
  114. package/dist/peoplesoft-CvwdApCK.mjs.map +0 -1
  115. package/dist/providers-BfFg_3eo.mjs +0 -56
  116. package/dist/providers-BfFg_3eo.mjs.map +0 -1
  117. package/dist/session-B_jK90RC.mjs +0 -23
  118. package/dist/session-B_jK90RC.mjs.map +0 -1
  119. package/dist/tokens-CkWpu7Qp.mjs +0 -150
  120. package/dist/tokens-CkWpu7Qp.mjs.map +0 -1
  121. package/dist/utils-DJx-7b4M.mjs +0 -244
  122. package/dist/utils-DJx-7b4M.mjs.map +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wcz-layout",
3
- "version": "10.2.1",
3
+ "version": "11.0.0",
4
4
  "private": false,
5
5
  "keywords": [
6
6
  "tanstack-intent"
@@ -12,7 +12,8 @@
12
12
  "files": [
13
13
  "dist",
14
14
  "skills",
15
- "!skills/_artifacts"
15
+ "!skills/_artifacts",
16
+ "src/lib/locales"
16
17
  ],
17
18
  "type": "module",
18
19
  "sideEffects": [
@@ -72,38 +73,30 @@
72
73
  "prepublishOnly": "npm run build"
73
74
  },
74
75
  "dependencies": {
75
- "@t3-oss/env-core": "^0.13.11",
76
- "@tanstack/ai-react": "^1.0.2",
77
- "@tanstack/markdown": "^1.2.0",
78
- "i18next": "^26.7.1",
79
- "i18next-browser-languagedetector": "^8.3.0",
80
- "iron-session": "^9.0.1",
81
- "jose": "^6.2.15",
82
- "react-dropzone": "^20.1.4",
83
- "react-i18next": "^17.1.12",
76
+ "i18next": "^27.2.10",
77
+ "iron-session": "^9.1.1",
78
+ "jose": "^6.2.18",
79
+ "react-dropzone": "^20.2.1",
80
+ "react-i18next": "^18.0.3",
84
81
  "react-intersection-observer": "^11.0.1",
85
82
  "react-number-format": "^5.4.5",
86
- "tus-js-client": "^4.3.1",
87
83
  "uuidv7": "^1.2.1"
88
84
  },
89
85
  "devDependencies": {
90
86
  "@arethetypeswrong/core": "^0.18.5",
91
- "@tanstack/ai": "^1.1.0",
92
- "@tanstack/ai-openai": "^1.1.0",
93
- "@tanstack/highlight": "^1.2.11",
87
+ "@tanstack/highlight": "^1.2.12",
94
88
  "@tanstack/intent": "^0.5.6",
95
- "@tanstack/react-pacer": "^0.24.1",
96
- "@types/node": "^26.6.6",
97
- "@types/react": "^19.3.0",
89
+ "@types/node": "^26.6.11",
90
+ "@types/react": "^19.3.3",
98
91
  "@types/react-dom": "^19.3.0",
99
- "@vitejs/plugin-react": "^6.2.1",
100
- "jsdom": "^30.1.3",
101
- "nitro": "3.0.261103-rc",
92
+ "@vitejs/plugin-react": "^6.3.0",
93
+ "jsdom": "^31.0.1",
94
+ "nitro": "",
102
95
  "oxc-transform-react": "^0.156.0",
103
96
  "publint": "^0.3.25",
104
97
  "typescript": "^7.0.2",
105
- "vite": "npm:@voidzero-dev/vite-plus-core@1.5.0",
106
- "vite-plus": "1.5.0"
98
+ "vite": "npm:@voidzero-dev/vite-plus-core@8.3.8001",
99
+ "vite-plus": "1.8.0"
107
100
  },
108
101
  "peerDependencies": {
109
102
  "@emotion/cache": "11.x",
@@ -112,8 +105,14 @@
112
105
  "@mui/icons-material": "9.x",
113
106
  "@mui/material": "9.x",
114
107
  "@mui/x-date-pickers": "9.x",
108
+ "@tanstack/ai": "1.x",
109
+ "@tanstack/ai-code-mode": "1.x",
110
+ "@tanstack/ai-compaction": "1.x",
111
+ "@tanstack/ai-isolate-quickjs": "1.x",
115
112
  "@tanstack/ai-openai": "1.x",
113
+ "@tanstack/ai-react": "1.x",
116
114
  "@tanstack/charts": "1.x",
115
+ "@tanstack/markdown": "1.x",
117
116
  "@tanstack/react-form": "1.x",
118
117
  "@tanstack/react-hotkeys": "0.x",
119
118
  "@tanstack/react-pacer": "0.x",
@@ -129,13 +128,8 @@
129
128
  "react-dom": "19.x",
130
129
  "zod": "4.x"
131
130
  },
132
- "peerDependenciesMeta": {
133
- "@tanstack/ai-openai": {
134
- "optional": true
135
- }
136
- },
137
131
  "overrides": {
138
132
  "vite": "$vite"
139
133
  },
140
- "packageManager": "npm@12.2.2"
134
+ "packageManager": "npm@12.2.3"
141
135
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ai
3
- description: "Use when adding LLM features (chat, streamed text, structured output, tools, media generation)"
3
+ description: "Use when adding LLM features (the assistant, chat, streamed text, structured output, tools, media generation)"
4
4
  metadata:
5
5
  type: convention
6
6
  library: wcz-layout
@@ -11,18 +11,47 @@ metadata:
11
11
 
12
12
  ## Rules
13
13
 
14
- - Install `@tanstack/ai` and `@tanstack/ai-openai` in the app (if missing); the server function imports it directly.
15
- `@tanstack/charts` is a peer of wcz-layout, which npm installs with it; the chat loads it with
16
- the first chart the model draws, so an app never defines a chart tool of its own.
14
+ - Install `@tanstack/ai` and `@tanstack/ai-openai` in the app (if missing). An app with the
15
+ assistant also installs `@tanstack/ai-code-mode`, `@tanstack/ai-isolate-quickjs` and
16
+ `@tanstack/ai-compaction`: `layoutChat` loads them on its first call. `@tanstack/charts` is a peer of wcz-layout, which npm
17
+ installs with it; the chat loads it with the first chart the model draws.
18
+ - Code mode runs the model's programs in QuickJS, whose WebAssembly a production bundle leaves
19
+ behind: give the app's `nitro()` plugin `traceDeps: ["quickjs-emscripten"]` in `vite.config.ts`.
17
20
  - Require the gateway env in the app's `src/env.ts` `server` block, so a missing value fails at
18
21
  startup: `AI_BASE_URL: z.url()` and `AI_SUBSCRIPTION_KEY: z.string()`. The gateway token also
19
22
  uses the Entra app registration: `ENTRA_TENANT_ID`, `ENTRA_CLIENT_ID`, `ENTRA_CLIENT_SECRET`.
20
23
  Values come from `.env.local` or Vault.
21
- - Import the adapter from `wcz-layout/ai`: `adapter: await chatAdapter("gpt-5.5")`, created
22
- per request inside the server function. It sends the app token and the subscription key itself.
23
- Never build an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups
24
- with `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments.
25
- - Call `chatAdapter` only in server functions (`src/server/...`): it reads server env and tokens.
24
+ - The assistant is one server function that returns `layoutChat({ data, user, systemPrompts,
25
+ tools, guides })` from `wcz-layout/ai`, and nothing else. `layoutChat` brings what every app's
26
+ assistant shares: the model, code mode, the guides, the shared rules (how to read and change
27
+ data, deletes, charts, attached files, the page, the reply's language), who the user is, a
28
+ conversation bounded at 100k tokens and a `[chat]` line in the server log with the tokens of
29
+ each model call. Never call `chat()` for the assistant yourself, and never repeat those rules
30
+ in the app's prompt.
31
+ - `systemPrompts` say only what the app is: what its records are called and mean, what the
32
+ assistant cannot do there, and the paths of its pages (`[name](/orders/<id>)`), so the model
33
+ links the records it mentions. Keep it the same for every user and every request: no user,
34
+ date or page in it, or the provider's prompt cache misses. `layoutChat` adds the user; the
35
+ model reads the time with `get_time` and the page with `read_page` when a request needs them.
36
+ - `tools` are server tools (`toolDefinition(...).server(...)`) that call the app's own server
37
+ functions, `deleteOrder({ data: id })`: called on the server they run in the same request, with
38
+ the screens' middleware, validation and permission checks. Never reimplement a server function
39
+ for a tool. After a write, `context?.emitCustomEvent("invalidate", { queryKey })` makes the
40
+ chat invalidate that query, so open screens refetch.
41
+ - A tool without `needsApproval` becomes a function of the programs the model runs
42
+ (`execute_typescript`): it reads, filters, joins and counts on the server, and creates or
43
+ changes many records in one program, e.g. a device per row of an attached spreadsheet. Only
44
+ the program's answer enters the conversation. So a reading tool takes no filters: it returns
45
+ every record the user may see, with an `outputSchema` that gives the model the rows' shape.
46
+ - Only tools that delete get `needsApproval: true`. They stay tool calls of their own, and the
47
+ chat asks "Are you sure?" (Cancel / Confirm) before one runs.
48
+ - Give feature tools `lazy: true`: the model sees names and first sentences, and loads a
49
+ feature's types only when a request needs them. Write each description's first sentence to
50
+ stand alone.
51
+ - `guides` is how the app works, as markdown by topic, each starting with a `# Title` line:
52
+ `import orders from "./guides/orders.md?raw"`. Only the titles ride on every request; the
53
+ model reads a guide when a question touches it. Write them from the user's view: the rules,
54
+ who may do what, what happens next. This is what lets a new user ask anything about the app.
26
55
  - Build every chat with `createLayoutChatHook(chatFn)` from `wcz-layout/hooks`. Its labels are
27
56
  `Layout.Chat.*` keys: copy the `Layout.Chat` object from wcz-layout's `src/lib/locales/*.json`
28
57
  into each of the app's locale files, or the chat shows raw keys.
@@ -31,48 +60,45 @@ metadata:
31
60
  `options.chat`. It shows for a signed-in user, opens from the app bar and mounts on the first
32
61
  open. From `lg` up it docks beside the page and remembers its width and whether it is open;
33
62
  below `lg` it covers the page right of the navigation rail, opens only from the button and
34
- closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its own sits in a
35
- parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root, e.g. a background;
36
- it has none of its own.
63
+ closes when a page opens, so a link, `navigate` or the rail shows the page. A chat page of its
64
+ own sits in a parent with a height (e.g. `Fullscreen`). `LayoutChat` takes `sx` for its root,
65
+ e.g. a background; it has none of its own.
66
+ - The chat brings these without any app code. Never build them again:
67
+ - Files: the user drops them anywhere on the chat, pastes them or picks them. They travel in
68
+ the message, never to the file service, and the model reads them as they are: images, PDF,
69
+ Word, Excel, PowerPoint, CSV and text, up to 10 MB each. Nothing is parsed in the app. Of a
70
+ spreadsheet the model sees the first 1000 rows of each sheet.
71
+ - A message sent while a reply streams waits in a queue above the input, where it can be
72
+ cancelled.
73
+ - The conversation survives a reload and ends with the tab (`sessionStorage`, per user).
74
+ - Each tool shows as one line with its name, and a program with the functions it calls.
37
75
  - Every chat has these client tools built in: `show_ui` (the model renders MUI components, and
38
76
  charts: a `Chart` node with TanStack Charts marks as children, their official options as
39
- props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme` (light,
40
- dark or system), `navigate` (opens one of the app's pages, listed from its route tree, and
41
- leaves a page whose record was just deleted), `get_time` (the user's current time and zone,
42
- so the prompt never states it), and `read_page`, `click`, `fill` and `press_key` (the model
43
- uses the page the user is on as they would: it reads the text and numbered controls, clicks,
44
- types and presses keys, and never answers a `useDialogs` confirmation). Never define them
45
- again. The client sends its tools with every request, so the
46
- server function only merges them: `tools: mergeAgentTools(serverTools, tools)`. It must also
47
- forward `parentRunId` and `resume`, or tool results and approvals never continue the run.
48
- - The chat sends the page the user is on as AG-UI context. Put it in the prompt: each
49
- `aguiContext` item becomes a `"<description>: <value>"` line in `systemPrompts` (see the example).
50
- - Data and writes are server tools (`toolDefinition(...).server(...)`) in `serverTools` that
51
- call the app's own server functions, `deleteOrder({ data: id })`: called on the server they run
52
- in the same request, with the screens' middleware, validation and permission checks. Never
53
- reimplement a server function for a tool. After a write,
54
- `context?.emitCustomEvent("invalidate", { queryKey })` makes the chat invalidate that query, so
55
- open screens refetch.
56
- - Only tools that delete get `needsApproval: true`: the chat asks "Are you sure?" (Cancel /
57
- Confirm) before they run, so the prompt tells the model to say first what it will delete.
58
- Creating and changing run straight away, and the model says what it did.
59
- - Give feature tools `lazy: true` and pass `lazyToolsConfig: { includeDescription:
60
- "first-sentence" }` to `chat()`: the model sees names and first sentences, and loads a feature's
61
- schemas only when a request needs them. Write each description's first sentence to stand alone.
62
- Pass `agentLoopStrategy: maxIterations(20)` too: the default 5 turns end a run without a reply
63
- once discovering, looking up and saving add up.
77
+ props), `ask_user` (asks with an MUI form), `get_user` (the signed-in user), `set_app_theme`
78
+ (light, dark or system), `navigate` (opens one of the app's pages, listed from its route tree,
79
+ and leaves a page whose record was just deleted), `get_time` (the user's current time and
80
+ zone), and `read_page`, `click`, `fill` and `press_key` (the model uses the page the user is on
81
+ as they would: it reads the address, the text, the numbered controls and the one the user was
82
+ last in, clicks, types and presses keys, and never answers a `useDialogs` confirmation). Never
83
+ define them again.
64
84
  - The page tools read what a screen reader would, so a page the model can use has a name on
65
85
  every control: a `Tooltip` title or `aria-label` on each icon button, a label on each field,
66
86
  and a button, link or `CardActionArea` for anything clickable. Deletes confirm through
67
87
  `useDialogs`, which the model never clicks.
68
88
  - Other browser actions are client tools:
69
89
  `useLayoutChat({ threadId, tools: [def.client(run)] })`, with `run` using the screen's hooks.
70
- - The chat renders markdown links to the app's own pages (`/...`) through the router; tell the
71
- model the page paths so it links the records it mentions.
90
+ - One-off calls (a translation, a typed answer, reading a document) are `chat()` with
91
+ `adapter: await chatAdapter("gpt-5.5")` from `wcz-layout/ai`, created per request in a server
92
+ function (`src/server/...`): it reads server env and tokens, and sends the app token and the
93
+ subscription key itself. It is the one adapter for everything, files included: a `document`
94
+ part with `source: { type: "data", value: base64, mimeType }` and `metadata: { filename }`
95
+ reaches the model as the file itself (PDF, Word, Excel, PowerPoint, CSV, text). Never build
96
+ an OpenAI adapter in the app: `createOpenaiChat` (Responses API) fails on follow-ups with
97
+ `400 invalid_encrypted_content`, because the gateway load-balances Azure deployments, and
98
+ TanStack's own Chat Completions adapter refuses documents.
72
99
  - Structured output (one typed object, e.g. a generated document) stays raw `useChat` with
73
- `outputSchema` and `partial`, not the chat.
74
- - Render streamed text outside the chat with `@tanstack/markdown` (install if missing):
75
- `<Markdown>` from `@tanstack/markdown/react`.
100
+ `outputSchema` and `partial`, not the chat. Render streamed text outside the chat with
101
+ `@tanstack/markdown` (install if missing): `<Markdown>` from `@tanstack/markdown/react`.
76
102
 
77
103
  ## Example
78
104
 
@@ -82,22 +108,39 @@ AI_BASE_URL: z.url(),
82
108
  AI_SUBSCRIPTION_KEY: z.string(),
83
109
 
84
110
  // src/server/actions/assistant.ts
85
- import {
86
- chat,
87
- chatParamsFromRequestBody,
88
- maxIterations,
89
- mergeAgentTools,
90
- toServerSentEventsResponse,
91
- toolDefinition,
92
- } from "@tanstack/ai";
111
+ import { toolDefinition } from "@tanstack/ai";
93
112
  import type { RunAgentInput } from "@tanstack/ai/client";
94
113
  import { createServerFn } from "@tanstack/react-start";
114
+ import { layoutChat } from "wcz-layout/ai";
95
115
  import { authMiddleware } from "wcz-layout/middleware";
96
- import { chatAdapter } from "wcz-layout/ai";
97
116
  import z from "zod";
98
- import { deleteOrder } from "./order"; // the server function the screens call
117
+ import { OrderSchema } from "~/lib/schemas/order";
118
+ import orders from "../guides/orders.md?raw";
119
+ import { deleteOrder, insertOrder, selectOrders } from "./order"; // the screens' server functions
99
120
 
100
- const orderTools = () => [
121
+ const SYSTEM_PROMPT =
122
+ "You are the assistant in Orders, the application in which departments order material. " +
123
+ "Link an order to its page with a markdown link: [number](/orders/<id>).";
124
+
125
+ const orderTools = [
126
+ toolDefinition({
127
+ name: "list_orders",
128
+ description: "Every order the user can see, with its lines and state.",
129
+ inputSchema: z.object({}),
130
+ outputSchema: OrderSchema.array(),
131
+ lazy: true,
132
+ }).server(() => selectOrders()),
133
+ toolDefinition({
134
+ name: "create_order",
135
+ description: "Create an order. It needs a supplier and at least one line.",
136
+ inputSchema: OrderSchema.omit({ id: true }),
137
+ lazy: true,
138
+ }).server(async (order, context) => {
139
+ const id = crypto.randomUUID();
140
+ await insertOrder({ data: { ...order, id } });
141
+ context?.emitCustomEvent("invalidate", { queryKey: ["orders"] });
142
+ return { id, page: `/orders/${id}` };
143
+ }),
101
144
  toolDefinition({
102
145
  name: "delete_order",
103
146
  description: "Delete one of the user's orders.",
@@ -114,28 +157,15 @@ const orderTools = () => [
114
157
  export const assistant = createServerFn({ method: "POST" })
115
158
  .validator(z.custom<RunAgentInput>())
116
159
  .middleware([authMiddleware()])
117
- .handler(async ({ data }) => {
118
- const { messages, threadId, runId, parentRunId, resume, tools, aguiContext } =
119
- await chatParamsFromRequestBody(data);
120
- const abortController = new AbortController();
121
- const stream = chat({
122
- adapter: await chatAdapter("gpt-5.5"),
123
- threadId,
124
- runId,
125
- parentRunId,
126
- resume,
127
- systemPrompts: [
128
- SYSTEM_PROMPT,
129
- ...aguiContext.map(({ description, value }) => `${description}: ${value}`),
130
- ],
131
- messages,
132
- tools: mergeAgentTools(orderTools(), tools),
133
- lazyToolsConfig: { includeDescription: "first-sentence" },
134
- agentLoopStrategy: maxIterations(20),
135
- abortController,
136
- });
137
- return toServerSentEventsResponse(stream, { abortController });
138
- });
160
+ .handler(({ data, context: { user } }) =>
161
+ layoutChat({
162
+ data,
163
+ user,
164
+ systemPrompts: [SYSTEM_PROMPT],
165
+ tools: orderTools,
166
+ guides: { orders },
167
+ }),
168
+ );
139
169
  ```
140
170
 
141
171
  ```tsx
@@ -32,7 +32,9 @@ the wcz-layout skill wins. Permissions, scopes, the signed-in user and downstrea
32
32
 
33
33
  - Every screen works in light and dark (`theme.applyStyles("dark", …)`; the theme sets
34
34
  `colorSchemeSelector: "data-mui-color-scheme"`) and on desktop and mobile (breakpoints).
35
- - Dates: `dayjs(value).format("L LT")`, or `"L"` for a date alone.
35
+ - Dates: `dayjs(value).locale(i18n.language).format("L LT")`, or `"L"` for a date alone, with
36
+ `i18n` from `useTranslation()`. The React Compiler caches a bare `dayjs(value).format()`, so
37
+ without the locale a date keeps its old format after a language switch.
36
38
  - Loading states are skeletons of the final layout.
37
39
  - A component fetching its own `useQuery` waits until visible:
38
40
  `const { ref, inView } = useInView({ triggerOnce: true })` (`wcz-layout/hooks`),
@@ -51,9 +53,14 @@ the wcz-layout skill wins. Permissions, scopes, the signed-in user and downstrea
51
53
  - Every user-facing string goes through `t`: `useTranslation()` from `wcz-layout/hooks` in
52
54
  components, `t` from `wcz-layout/utils`. `t()` translates when called, so never at module scope (Zod messages: see
53
55
  db-schema).
54
- - Add each key to `src/lib/locales/*.json`.
56
+ - Add each key to every `src/lib/locales/*.json`; the type-check names a key a locale lacks.
55
57
  Feature keys go under the feature's namespace (`"Feature": { "Name": "Name" }`), shared ones at the root.
56
- Counts use plural keys: `_one`, `_other`, and `_few` in Czech.
58
+ Counts use plural keys: `_one`, `_other`, plus `_few` in Czech and `_few`, `_many` in
59
+ Ukrainian; Traditional Chinese (`zh-TW`) has only `_other`.
60
+ - On the server `t` translates into the language of the request; `getLanguage()`
61
+ (`wcz-layout/utils`) returns it for anything else, e.g. dates in an email.
62
+ - Adding a language, how the language is chosen and server-side translations:
63
+ [references/languages.md](references/languages.md).
57
64
 
58
65
  ## Building a feature
59
66
 
@@ -84,20 +91,20 @@ src/
84
91
  │ └── queries/<entity>.ts # live query options
85
92
  ├── lib/ # isomorphic: client and server
86
93
  │ ├── auth/ # permissions.ts, scopes.ts
87
- │ ├── locales/ # en.json, cs.json
94
+ │ ├── locales/ # en.json, cs.json, uk.json, zh-TW.json
88
95
  │ └── schemas/<entity>.ts # Zod schema + type
89
96
  ├── routes/
90
97
  │ ├── __root.tsx # shell, navigation, root beforeLoad
91
- │ ├── index.tsx, login.tsx, health.ts, auth/ # from the template, keep
98
+ │ ├── index.tsx, health.ts, auth/ # from the template, keep
92
99
  │ ├── api/<entities>/ # REST routes, only for a requested public API
93
100
  │ └── <entities>/ # feature pages; -components/, -hooks/
94
101
  ├── server/ # server-only
95
102
  │ ├── actions/<entity>.ts # server functions
96
103
  │ ├── db/ # index.ts, schemas/<entity>.ts, schemas/relations.ts, migrations/
97
104
  │ └── middleware/databaseMiddleware.ts
98
- ├── env.ts # clientEnv, serverEnv (createEnv)
105
+ ├── env.ts # Zod shapes server, client (VITE_)
99
106
  ├── router.tsx # QueryClient, DbClient, router defaults
100
- └── types/ # i18next.d.ts, wcz-layout.d.ts
107
+ └── types/ # i18next.gen.ts, wcz-layout.d.ts
101
108
  ```
102
109
 
103
110
  ## Tests
@@ -108,7 +115,7 @@ bug), not coverage. `vp test` runs `tests/unit` and `tests/integration`, paths m
108
115
 
109
116
  - No globals: import from `vite-plus/test`. Component tests start with
110
117
  `// @vitest-environment jsdom` and call `afterEach(cleanup)`.
111
- - Without an initialized i18n fixture, assert Zod issue `path` and `code`, not messages.
118
+ - Assert Zod issue `path` and `code`, not messages: messages follow the language.
112
119
  - Collection tests mock the select server function, not TanStack DB. Use a fresh `DbClient`
113
120
  per case; for one query, await `preloadLiveQuery(q)` and read
114
121
  `dehydrate().liveQueries?.[0]?.snapshot?.rows.map(({ value }) => value)`.
@@ -14,8 +14,7 @@
14
14
  - Permissions are evaluated per request, so moving an existing group between keys applies
15
15
  immediately. A group name new to `permissions.ts` applies only after the user signs in
16
16
  again (the cookie keeps only groups listed there).
17
- - AWS users have no groups, so `requireAuth(key)` / `authMiddleware(key)` always reject them.
18
- Use the bare form for routes AWS users must reach.
17
+
19
18
  - Offline, guards use a cached user snapshot from `localStorage` — UI state only, the server still authorizes every call.
20
19
 
21
20
  ```ts
@@ -30,33 +29,32 @@ export const permissions = {
30
29
  import type { Scopes } from "wcz-layout/models";
31
30
 
32
31
  export const scopes = {
33
- graph: "User.Read", // bare string = Entra only
34
- file: {
35
- entra: "api://wistron.com/file-api/access_as_user",
36
- aws: "https://file-api.wistron.com/access_as_user",
37
- },
32
+ graph: "User.Read",
33
+ file: "api://wistron.com/file-api/access_as_user",
38
34
  } as const satisfies Scopes;
39
35
  ```
40
36
 
41
37
  ## Gates
42
38
 
43
- | Gate | Route `beforeLoad` | Server function / API route |
44
- | ----------------------- | ------------------ | --------------------------- |
45
- | Anyone (default) | — | — or `userMiddleware` |
46
- | Signed in, any provider | `requireAuth()` | `authMiddleware()` |
47
- | Signed in + permission | `requireAuth(key)` | `authMiddleware(key)` |
39
+ | Gate | Route `beforeLoad` | Server function / API route |
40
+ | ---------------------- | ------------------ | --------------------------- |
41
+ | Anyone (default) | — | — or `userMiddleware` |
42
+ | Signed in | `requireAuth()` | `authMiddleware()` |
43
+ | Signed in + permission | `requireAuth(key)` | `authMiddleware(key)` |
48
44
 
49
45
  ## Tokens for downstream APIs
50
46
 
51
47
  From `wcz-layout/auth`, server-only (call inside a server function or server route):
52
48
 
53
- - `getAccessToken(scopeKey)` — delegated token for the signed-in user from their session.
54
- Requires a browser session (a Bearer caller has none). An expired session clears the cookie
55
- and throws a 401 `Response`.
49
+ - `getAccessToken(scopeKey)` — delegated token for the user behind the request: minted from
50
+ their session, or, when a sibling service calls with an Entra user token as Bearer, exchanged
51
+ for it on behalf of that user (OBO). OBO needs this app's registration to hold the delegated
52
+ permission for the downstream API, with admin consent; an app token as Bearer counts as no
53
+ user and throws. An expired session clears the cookie and
54
+ throws a 401 `Response`. `createApi` services use it whenever there is a user, and fall back
55
+ to `getAppToken` otherwise.
56
56
  - `getAppToken(scopeKey)` — app-only Entra token (client credentials, `<resource>/.default`),
57
57
  cached in memory. For background jobs and calls with no user.
58
- - Downstream APIs must trust both issuers to accept AWS users; Cognito tokens have no `aud`
59
- and are authorized by the `scope` claim.
60
58
 
61
59
  ## Example
62
60
 
@@ -0,0 +1,56 @@
1
+ # wcz-layout languages
2
+
3
+ ## Rules
4
+
5
+ - A language is a file: `src/lib/locales/<code>.json`, `<code>` a BCP 47 tag (`de`, `zh-TW`).
6
+ The language menu lists exactly these files; `en.json` is the fallback for missing keys.
7
+ - The server renders the `i18next` cookie the menu writes, else the browser's
8
+ `Accept-Language`. A switch re-renders in place: typed form values stay, while texts, MUI
9
+ components, pickers, Zod messages and shown errors change language.
10
+ - `src/types/i18next.gen.ts` is generated from the locale files on `vp dev` and `vp build`;
11
+ commit it, never edit it. It types `t()` from `en.json` and fails the type-check, naming the
12
+ key, when another locale lacks one of `en.json`'s keys.
13
+ - wcz-layout's own strings (`Layout.*`) ship with the package in `en`, `cs`, `uk` and `zh-TW`;
14
+ never copy them into an app. For another language they show in English until that locale has its own
15
+ `"Layout"` object, which overrides wcz-layout's key by key.
16
+
17
+ ## Adding a language
18
+
19
+ 1. Create `src/lib/locales/<code>.json` with every key of `en.json`, translated. Plurals use
20
+ the suffixes that language needs (`_one`, `_few`, `_many`, `_other`, ...), not English's.
21
+ 2. For wcz-layout's own strings in that language, add a `"Layout"` object: copy it from
22
+ `node_modules/wcz-layout/src/lib/locales/en.json` and translate it.
23
+ 3. Nothing else: the running dev server picks the file up and reloads, and wcz-layout loads
24
+ the dayjs, Zod and MUI locales for it.
25
+
26
+ Removing a language is deleting its file.
27
+
28
+ ## Server
29
+
30
+ `t` from `wcz-layout/utils` translates into the language of the request it runs in, and
31
+ `getLanguage()` returns that language, for anything `t` does not cover. Outside a request
32
+ (startup, background jobs) both use `en`.
33
+
34
+ ```ts
35
+ import { createServerFn } from "@tanstack/react-start";
36
+ import dayjs from "dayjs";
37
+ import { sendEmail } from "wcz-layout/data/server";
38
+ import { authMiddleware } from "wcz-layout/middleware";
39
+ import { getLanguage, t } from "wcz-layout/utils";
40
+
41
+ export const sendReminder = createServerFn({ method: "POST" })
42
+ .middleware([authMiddleware()])
43
+ .handler(async ({ context }) => {
44
+ const due = dayjs().add(1, "day").locale(getLanguage()).format("L");
45
+ await sendEmail({
46
+ data: {
47
+ subject: t("Reminder.Subject"),
48
+ body: `<p>${t("Reminder.Body", { due })}</p>`,
49
+ to: [context.user.email],
50
+ },
51
+ });
52
+ });
53
+ ```
54
+
55
+ A message for someone other than the caller needs the recipient's language, stored with
56
+ them: `i18next.getFixedT(language)` (`i18next` from `wcz-layout/utils`) is a `t` in it.