reboot alterflixhub
This commit is contained in:
commit
1e84023a44
188 files changed
+31629
No files matched your search
@@ -0,0 +1,214 @@
|
||||
---
|
||||
name: actions
|
||||
description: >-
|
||||
How to create and run agent actions. Actions are the single source of truth
|
||||
for app operations — the agent calls them as tools and frontend code calls
|
||||
them through client hooks. Use when creating a new action, adding an API
|
||||
integration, or wiring up frontend data fetching.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Agent Actions
|
||||
|
||||
## Rule
|
||||
|
||||
Actions in `actions/` are the **single source of truth** for app operations. The agent calls them as tools, the frontend calls them through `useActionQuery` / `useActionMutation`, and the framework owns the HTTP transport behind those hooks — no duplicate `/api/` routes.
|
||||
|
||||
Before creating any custom route for app data, check `actions/` and the action table in `AGENTS.md`. An action already exists? Call it directly. Missing? Create or update a `defineAction`. **Stop trigger:** about to add a file under `server/routes/api/` (or middleware to guard one)? Check it against the exception list in *Custom `/api/` Routes* below first — even if you already started the route.
|
||||
|
||||
## Keep Actions Deterministic
|
||||
|
||||
An action may call a provider API, validate data, and persist records without being an AI feature — keep it deterministic, focused, and independently useful to the agent. Don't put LLM calls or a second model runtime in app actions.
|
||||
|
||||
When a workflow is research, analysis, generation, recommendation, or synthesis — or spans several provider calls and writes — route it to the AgentSidebar via `sendToAgentChat({ openSidebar: true })` and let the agent orchestrate focused actions instead of hiding an AI-shaped workflow behind one opaque `generate-*`/`create-*` action just because its implementation happens to be deterministic.
|
||||
|
||||
## How to Create an Action
|
||||
|
||||
**One action per file, default-exported. The filename is the action name** (kebab-case): `actions/list-meals.ts` is the `list-meals` action. Don't put several `defineAction`s as named exports in one file — the registry keys actions by filename and only the default export is registered, so extra named exports never become callable and won't match `.generated/action-types.d.ts`.
|
||||
|
||||
```ts
|
||||
// actions/list-meals.ts
|
||||
import { z } from "zod";
|
||||
import { defineAction } from "@agent-native/core/action";
|
||||
import { getDb } from "../server/db/index.js";
|
||||
import { meals } from "../server/db/schema.js";
|
||||
|
||||
export default defineAction({
|
||||
description: "List all meals",
|
||||
schema: z.object({}),
|
||||
http: { method: "GET" },
|
||||
run: async () => {
|
||||
const db = getDb();
|
||||
const rows = await db.select().from(meals);
|
||||
return rows; // Return objects/arrays, NOT JSON.stringify()
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
`schema` (Zod or Standard Schema-compatible) gives runtime validation, TS inference for `run()` args, and an auto-generated JSON Schema for the tool. Write it so an agent can call the tool correctly on the first try: `.describe()` every param and state enum values and the default in that text (`z.enum(["open","closed"]).default("open").describe('Filter status: "open" or "closed"; defaults to "open"')`); mark a field `.optional()` only when the action truly tolerates its absence — a silent default the caller cannot see is a required field in disguise; name the primary id the same way across a family (`create-/get-/update-/delete-<thing>` all take `id`, not a mix of `id` and `<thing>Id`), and if one action must differ, accept both with `.or()`; give nested objects a real schema, never a prose description; keep the one-line `description` complete enough to call the tool without a second lookup, because compact catalogs and `tool-search` show only that line. Use `z.coerce.number()` for numeric HTTP params, but write an explicit boolean parser instead of `z.coerce.boolean()`, which treats `"false"` as truthy.
|
||||
|
||||
Use Drizzle's PostgreSQL query builder, not raw SQL/`getDbExec()` or direct driver imports, unless Drizzle can't express the query. Never hardcode API keys/tokens/secrets - read via `readAppSecret` / `resolveCredential` / OAuth helpers; `process.env` is deploy-level config only.
|
||||
|
||||
**Decision order:** existing action → extend/create a `defineAction` → custom route as last resort (*Custom `/api/` Routes* below). Actions are already callable by agents, CLIs, hooks, HTTP, and MCP/A2A — don't wrap them in an umbrella REST API.
|
||||
|
||||
## Keep the Action Surface Small and Orthogonal
|
||||
|
||||
Every agent-exposed action is a tool in the model's context window; more tools degrades tool-selection quality. Add the fewest, most orthogonal actions that cover the capability.
|
||||
|
||||
- **One orthogonal `update` per resource**, not one per field — `update-<thing>` taking an optional-fields patch, not `update-<thing>-name` + `update-<thing>-order` + …
|
||||
- **Reach for a generic escape hatch before minting a new read action** — the `provider-api-catalog`/`docs`/`request` trio for provider data (`references/provider-apis.md`), `db-query` for ad hoc app-data reads in dev.
|
||||
- **`agentTool: false`** hides a UI-only/programmatic action from the model while keeping it frontend/HTTP-callable — not `toolCallable: false`, which only blocks the sandboxed extension bridge and leaves the action visible everywhere else; reserve that one for high-blast-radius operations.
|
||||
- **Delete or hide stale actions** once you confirm neither the UI nor an agent workflow uses them.
|
||||
|
||||
## Key Actions — One Index, Every Surface
|
||||
|
||||
Document the app's primary actions in the `AGENTS.md` action table. For first-turn loading, add those action names to the plugin's `initialToolNames` (`INITIAL_TOOL_NAMES` in some templates), or mark the full starter set `deferLoading: false` on the actions. When one action opts into per-action eager loading, unmarked actions are deferred; the remaining actions stay discoverable through `tool-search`.
|
||||
|
||||
When MCP is enabled, its `Key tools` line is generated from `mcp.keyToolNames ?? initialToolNames` and filtered to the actions served on that surface. A configured `mcp.keyToolNames` overrides the advertised MCP/WebMCP key list; it does not change the in-app agent's first-turn list. Keep the advertised subset consistent with the primary actions in the `AGENTS.md` table and the external catalog; the table may also document other in-app actions. Do not hand-write another action list in `mcp.instructions`, a skill, or an external skill; describe when to use actions there.
|
||||
|
||||
## The `http` Option
|
||||
|
||||
Controls HTTP exposure:
|
||||
|
||||
| Value | Behavior | Use for |
|
||||
| --- | --- | --- |
|
||||
| _(omitted)_ | `POST /_agent-native/actions/:name` | Write operations (default) |
|
||||
| `{ method: "GET" }` | `GET /_agent-native/actions/:name` | Read-only queries |
|
||||
| `{ method: "PUT"/"DELETE" }` | matching verb | Update / delete |
|
||||
| `{ method: "GET", path: "x" }` | custom route path | Non-default path |
|
||||
| `false` | never exposed as HTTP | `navigate`, `view-screen`, internal |
|
||||
|
||||
Mutating actions (anything but `GET`) auto-refresh the UI on success — don't call `refresh-screen` after a normal action. Overrides (`readOnly`, `parallelSafe`) and exact trigger rules: `references/action-fields.md`.
|
||||
|
||||
## Return Values
|
||||
|
||||
Return **structured data** (objects, arrays), never `JSON.stringify()` — the framework serializes the response and only tries to parse a returned string as JSON, which isn't the same contract.
|
||||
|
||||
```ts
|
||||
run: async (args) => await fetchEvents(args.from, args.to); // good
|
||||
run: async (args) => JSON.stringify(await fetchEvents(...)); // bad
|
||||
```
|
||||
|
||||
A create/update result is read by more than the caller. These keys are well-known and survive result truncation:
|
||||
|
||||
- `id` — the created or updated record. Pair it with a pure, synchronous `link` builder on the action (`link: (result) => ({ url: buildDeepLink({ app, view, params: { id: result.id } }), label })`) so MCP hosts and the desktop app surface an "Open …" deep link that lands in the editing view focused on the record; returning `url`/`urlPath` in the result works too.
|
||||
- `nextRequiredAction` — the name of the next **tool** to call when the operation is one step of a flow the agent should keep driving (`nextRequiredAction: "update-slide"`). Never phrase it as waiting for the user: an MCP/WebMCP/A2A caller cannot receive an in-app answer. The agent loop keeps this field in continuation prompts even when the rest of a large result is dropped, and MCP callers see it as `Next: …`.
|
||||
- `message`/`summary` — the one-line status external callers read; everything else stays in the structured result.
|
||||
- `designSystem` — when a record can link a brand or design system, expose it as `designSystem: AgentDesignSystemContext | null` via `loadAgentDesignSystemContext(id, getDesignSystemAction)` from core's shared `design-system-agent-context`. Reads get the bounded summary (`scope: "summary"`, with a `next` line naming the full read); only the create action and `get-design-system` itself pass `{ full: true }`. `status: "unavailable"` is not `null`: keep the id and the message. Print it in text results with `formatAgentDesignSystemContext`; do not name the field anything else.
|
||||
|
||||
For actions that attach a `chatUI` renderer, use `chatUI.projectResult` to return
|
||||
only the small structured fields the renderer needs. `chatUI.when` is evaluated
|
||||
against the full successful result first; the projection is used live and saved
|
||||
for interrupted-run recovery.
|
||||
|
||||
An action that hands control back to the user (question form, intake dialog) sets `endsTurn: true`; that hides it from MCP/WebMCP/A2A unless `mcpTool: true` is explicit — `references/action-fields.md`. For external-agent integrations, use the external-agents documentation slug listed by `agent-native-docs`.
|
||||
|
||||
Reach for `outputSchema` (validate the return), `_agentImages` (attach images the agent can see), `authorize` (gate who may call it), or `needsApproval` (require human sign-off per call) only when the action needs that guarantee — examples in `references/action-fields.md`.
|
||||
|
||||
### Write receipts
|
||||
|
||||
A write action that can check its own effect returns a plain-object result with a reserved `_receipt`, so the final answer is reconciled with what the write did, not with the model's reading of a JSON string that may be truncated:
|
||||
|
||||
```ts
|
||||
import type { WriteReceipt } from "@agent-native/core/action";
|
||||
|
||||
const _receipt: WriteReceipt = {
|
||||
changed: true,
|
||||
verified: false,
|
||||
summary: "Saved; panel 3 returned no rows.",
|
||||
checks: [{ id: "panel-3", ok: false, detail: "0 rows" }],
|
||||
};
|
||||
return { id, _receipt };
|
||||
```
|
||||
|
||||
`verified` is `true` (the effect was observed), `false` (checked and did not hold), or `"unverified"` (could not be checked); `checks` and `warnings` are optional. The agent loop reads the receipt before the result is stringified and truncated (summary 200 chars, 8 checks, 5 warnings):
|
||||
|
||||
- `verified: false` or `changed: false` forces one honest-reconciliation retry per turn: the model must say what the receipt shows and may not call the change visible or working. If the retry is spent, the answer is prefixed with the receipt block.
|
||||
- `verified: "unverified"` only prefixes that note; no retry.
|
||||
- A receipt that is present but malformed counts as `unverified`, never clean. `changed: false` also records the call as `completedSideEffect: false`, unless a write nested in the action also entered its handler: a receipt, like `retrySafe`, speaks only for the action's own write.
|
||||
- Set `subject` (the stable target, such as a dashboard id) so a later `changed: true, verified: true` receipt for the same subject can supersede an earlier flagged one in the same turn. When the earlier receipt had failing or unverified `checks`, the later receipts (from this action or another that writes the same subject) must carry an `ok: true` check with the same `id` for each; a receipt without checks never clears one that had them. A flagged receipt with no failing checks is superseded only by the same action. Receipts without a `subject` are never superseded.
|
||||
|
||||
A receipt is not an error channel. A write that did not achieve the requested state throws (`fail()`); return `changed: false` only for a benign no-op, such as the record already being in the requested state.
|
||||
|
||||
## Frontend Hooks
|
||||
|
||||
Import from focused `@agent-native/core/client/*` entry points; the broad
|
||||
`@agent-native/core/client` barrel is deprecated. Use action hooks, not
|
||||
hand-written `fetch("/_agent-native/actions/...")`.
|
||||
|
||||
```ts
|
||||
import { useActionQuery, useActionMutation, callAction } from "@agent-native/core/client/hooks";
|
||||
|
||||
const { data: meals } = useActionQuery("list-meals", { date: "2025-01-01" }); // GET, types auto-inferred
|
||||
const { mutate } = useActionMutation("log-meal"); // POST/PUT/DELETE
|
||||
mutate({ name: "Salad", calories: 350 });
|
||||
const people = await callAction("search-people", { query }, { method: "GET" }); // imperative (debounce, prefetch)
|
||||
```
|
||||
|
||||
Don't add manual generics like `useActionQuery<Meal[]>(...)` — types come from `.generated/action-types.d.ts`. Mutations auto-invalidate all `["action"]` query keys, so GET queries refetch. A revisit paints the persisted result for the signed-in user and org before that refetch; see `references/action-fields.md` for `persistInBrowser: false`.
|
||||
|
||||
When a query result varies by viewer or another client context that is not part of the action arguments, pass that stable context through `queryKeyScope`. It partitions only the local query cache; it is not sent to the action and never replaces server-side authorization.
|
||||
|
||||
## How to Run (Agent)
|
||||
|
||||
```bash
|
||||
pnpm action log-meal --name "Salad" --calories 350
|
||||
```
|
||||
|
||||
CLI flags become action input fields (`--key value` or `--key=value`); the runner does not read or write files for `--input` or `--output`. The default template dispatches through core's `runScript()` in `actions/run.ts`. Action names are lowercase-with-hyphens (`pnpm action my-action` → `actions/my-action.ts`).
|
||||
|
||||
After adding or changing several related actions, smoke-test **once** (one
|
||||
happy-path call that proves the wire-up), then typecheck once. Do not run
|
||||
`pnpm action …` for every method unless a smoke test failed and you need to
|
||||
isolate which action broke.
|
||||
|
||||
## CRUD + Drizzle in this starter
|
||||
|
||||
Before hunting through `node_modules` for DB helpers, read:
|
||||
|
||||
1. `drizzle/START_HERE.md` — where tables live + migrate commands
|
||||
2. `drizzle/crud-action-example.ts` — copy-paste list/create/update/delete pattern
|
||||
|
||||
DB client: `getDb` / `schema` from `server/db.ts`.
|
||||
|
||||
## Custom `/api/` Routes
|
||||
|
||||
Complete exception list — justified only when the caller isn't your own UI/agent, or the payload isn't JSON: **file uploads** (actions take JSON, not multipart), **streaming** (SSE/chunked needing direct H3 control), **webhooks**, **OAuth callbacks** (fixed redirect URL patterns), **public unauthenticated endpoints** (SEO/OG images, share links), **binary/non-JSON responses**.
|
||||
|
||||
Everything else — CRUD, settings, search, list/detail reads, auth state, anything the UI fetches as JSON — is an action. Needing middleware to scope a route to the current user is itself a signal it should be an action. Existing template `/api/*` CRUD routes are being migrated; do not add new ones.
|
||||
|
||||
## Do / Don't
|
||||
|
||||
- **Do** keep one action, one job; document a reusable action (when to use it, key args, return fields to preserve) in `AGENTS.md` once it's called from outside one narrow screen; promote workflow-heavy actions (provider-backed, cross-app, MCP/A2A, multi-step) into a skill.
|
||||
- **Do** use `fail(message, { errorCode, statusCode })` for user-friendly errors and import primitives from `@agent-native/core`(`/action`) instead of redefining them; use the core `upload-image` action or `uploadFile()` for durable images/files — never base64 into SQL, markdown, or action results.
|
||||
- **Do** signal failure by throwing, using `fail()` for expected caller-readable failures. Never return `{ error: ... }` as a failure result: a normal return is treated as a successful action. Reserve bare errors for unexpected internal faults.
|
||||
- **Do** use `fail()` rather than a bare `Error` for caller-readable failures. It carries the action's message, `errorCode`, and `details` to the browser and to agents; unexpected errors become a generic 500. Reserve bare throws for internal faults.
|
||||
- **Do** give `fail()` the status that matches the cause: it defaults to `400`, and `useActionQuery` retries only `429`, `502`, `503`, and `504`. Mutations do not retry; use transient statuses only for retryable failures.
|
||||
- **Do** throw `NoWriteError(message, { errorCode, statusCode })` instead of `fail()` for a rejection raised before the action's first write, such as an edit that matches nothing or a missing target. The agent then retries with corrected arguments instead of stopping on a write whose outcome is unknown. Throw it only before the first write: the framework rejects the claim when a nested write action ran, but it cannot see the handler's own writes.
|
||||
- **Do** render `actionErrorMessage(error) ?? yourCopy` in UI, never bare `error.message`. The message keeps an `Action <name> failed:` prefix that belongs in a console, so a toast built from it reads "Action update-brand-kit failed: That name is taken." The helper returns only what the action wrote, and `undefined` when nothing did (network drop, proxy HTML page), which is why the fallback is not optional.
|
||||
- **Do** pass a real `errorCode` when the agent should branch on the failure rather than re-read it. Codes other than the default `action_failed` are appended to the tool result as `(errorCode: not_found)`, on both the in-app agent and MCP. `details` follow as an `Error details: {...}` JSON line, and as `structuredContent.error` over MCP, capped at 2,000 characters, so keep them to what the agent acts on next: ids, limits, field names. The status never reaches either.
|
||||
- **Don't** re-export actions as REST — `/_agent-native/actions/:name` is already the REST surface; duplicating it under `/api/*` hides the operation from agents.
|
||||
- **Don't** reach for provider integrations, `outputSchema`, `authorize`, `needsApproval`, or `_agentImages` without checking `references/` first — each has sharp edges covered there, not here.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- **Action not found / type mismatch** — filename must match the command (`pnpm action foo-bar` → `actions/foo-bar.ts`), and the action must be the file's **default** export. Multiple `defineAction` named exports in one file register only the default; split them into one file each.
|
||||
- **Args not parsing** — use `--key value` / `--key=value`; boolean flags are `--flag` (sets `"true"`).
|
||||
- **Frontend 405** — `http.method` doesn't match the hook (`useActionQuery` for GET, `useActionMutation` for POST/PUT/DELETE).
|
||||
- **Frontend gets undefined** — action must return structured data, not `JSON.stringify()`.
|
||||
|
||||
## References
|
||||
|
||||
- `references/provider-apis.md` — wiring a credentialed provider (HubSpot, Gong, Slack, …) for querying, reporting, or cross-source research.
|
||||
- `references/action-fields.md` — `outputSchema`, `authorize`, `needsApproval`, `_agentImages`, and exact auto-refresh rules.
|
||||
- `references/examples.md` — a second worked example and legacy bare-export patterns.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- **storing-data** — Actions read/write data in SQL
|
||||
- **delegate-to-agent** — The agent invokes actions via `pnpm action <name>`
|
||||
- **real-time-sync** — Database writes from actions trigger change events to update the UI
|
||||
- **adding-a-feature** — Actions are area 2 of the four-area checklist
|
||||
- **client-methods** — Client code uses named helpers/hooks instead of raw REST calls
|
||||
@@ -0,0 +1,145 @@
|
||||
# Action Field Reference
|
||||
|
||||
Full detail on the less-common `defineAction` fields and automatic behaviors.
|
||||
Read this when you need output validation, authorization, human approval,
|
||||
image results, or the exact rules for the auto-refresh behavior — the happy
|
||||
path in SKILL.md doesn't need any of these.
|
||||
|
||||
## Screen Refresh (automatic)
|
||||
|
||||
The framework auto-refreshes the UI after any successful mutating action. On completion of a non-`GET` action, the framework emits a change event with `source: "action"` that the client's `useDbSync` picks up and uses to invalidate `["action"]` React Query keys — so `list-*` / `get-*` hooks refetch without a full page reload. In-process calls emit directly; dev-mode `pnpm action ...` calls also write a durable marker so the web server sees child-process action changes.
|
||||
|
||||
Rules:
|
||||
|
||||
- `http: { method: "GET" }` → read-only, does NOT trigger a refresh (inferred automatically).
|
||||
- Any other action (default `POST`, `PUT`, `DELETE`, or `http: false`) → treated as mutating, triggers a refresh on success.
|
||||
- To override the inference on an unusual action (e.g. a `POST` that only reads), pass `readOnly: true` on the action definition.
|
||||
- To let a mutating action run concurrently with other same-turn tool calls, pass `parallelSafe: true`. Only do this when the action is internally concurrency-safe and order-independent (for example, it uses an app-level lock or idempotent upsert semantics). Mutating actions remain serialized by default.
|
||||
- If a successful call hands control to the user — it renders a question, an intake form, or anything else the turn must wait on — pass `endsTurn: true` and make it the first or only call in the turn. It stops subsequent model steps and later calls, but cannot undo calls emitted before it. Without it a completion guard sees a turn that legitimately paused as one that failed to finish. `endsTurn: true` also hides the action from MCP, WebMCP, and A2A callers by default (`isActionExposedToExternalAgents` in core `action.ts`) — an external host has no in-app chat to receive the answer on. Pass `mcpTool: true` alongside it only when an external caller can complete the same operation without that answer.
|
||||
- Read results persist in the browser per signed-in user and org, so a revisit paints the last result before it refetches. Pass `persistInBrowser: false` on a read that must not outlive the page (secrets, one-time codes, another user's private data). Mutations never persist.
|
||||
- MCP hosts read tool annotations to decide how carefully to treat a call. Every MCP catalog advertises declared `mcpAnnotations` (`readOnlyHint`, `destructiveHint`, `openWorldHint`, optional `idempotentHint`); otherwise `/mcp` derives only `readOnlyHint` and an approval-based `destructiveHint`. Declare them on every action MCP advertises that is not read-only, with `destructiveHint: true` when it removes, overwrites, or replaces user content — recoverable Trash included — and mark idempotency-key-guarded writes `idempotentHint: true`. A contract test fails on a new undeclared write.
|
||||
|
||||
Agents do NOT need to call `refresh-screen` after a normal action — it's already handled. `refresh-screen` is only needed when the agent mutates data via a path the framework can't see (e.g. writing to an external system the app mirrors) or when the agent wants to pass a `scope` hint for narrower invalidation.
|
||||
|
||||
## Returning Images the Agent Can See (`_agentImages`)
|
||||
|
||||
An action's return object may include the well-known optional field
|
||||
`_agentImages` to attach vision images (screenshots, chart previews, rendered
|
||||
designs) to the tool result. The agent literally sees them — enabling visual
|
||||
self-review loops — while the field itself is stripped from the JSON text the
|
||||
model reads.
|
||||
|
||||
```ts
|
||||
run: async ({ dashboardId }) => {
|
||||
const shot = await renderDashboardPng(dashboardId); // Buffer
|
||||
return {
|
||||
dashboardId,
|
||||
panelCount: 6,
|
||||
_agentImages: [
|
||||
// Either a public https URL (preferred — the provider fetches it)…
|
||||
{ url: "https://cdn.example.com/previews/dash-1.png", label: "overview" },
|
||||
// …or base64 without a data: prefix (mediaType required; a full
|
||||
// data:image/png;base64,… URL in `data` is also accepted and parsed).
|
||||
{ data: shot.toString("base64"), mediaType: "image/png" },
|
||||
],
|
||||
};
|
||||
},
|
||||
```
|
||||
|
||||
Rules and limits:
|
||||
|
||||
- Shape: `Array<{ url?: string; data?: string; mediaType?: string; label?: string }>`.
|
||||
Each entry needs `url` (https only) **or** `data`. Supported media types:
|
||||
`image/jpeg`, `image/png`, `image/gif`, `image/webp`.
|
||||
- Caps: max **4 images** per result; max **~2MB of base64** per image.
|
||||
Over-cap or invalid entries never fail the call — they become text notes in
|
||||
the result telling the model what was dropped and why.
|
||||
- Persistence: the run ledger stores only the string result plus compact
|
||||
`[image: …]` notes (URLs verbatim; base64 as a byte-count placeholder) —
|
||||
never the payload. Images are re-attached only for the live turn; replayed
|
||||
history is text-only, so prefer stable `url` images the model can re-request.
|
||||
- Engine support: native Anthropic and vision-capable AI-SDK providers
|
||||
(anthropic, openai, google, openrouter) receive real image blocks; other
|
||||
paths (Builder gateway, non-vision providers) degrade to the text notes.
|
||||
- External MCP tools need no changes — standard MCP `image` content parts are
|
||||
converted automatically under the same caps.
|
||||
|
||||
## Validating Return Values (`outputSchema`)
|
||||
|
||||
`schema` validates inputs; `outputSchema` validates what the action **returns**. Pass any Standard Schema-compatible schema (Zod, Valibot, ArkType) and the framework validates the result _after_ `run()` resolves — input validated before `run`, output after.
|
||||
|
||||
```ts
|
||||
export default defineAction({
|
||||
description: "Summarize a thread.",
|
||||
schema: z.object({ threadId: z.string() }),
|
||||
outputSchema: z.object({ summary: z.string(), messageCount: z.number() }),
|
||||
outputErrorStrategy: "warn", // default; "strict" | "fallback"
|
||||
// outputFallback: { summary: "", messageCount: 0 }, // used only by "fallback"
|
||||
run: async ({ threadId }) => {
|
||||
/* ... */
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
- `"warn"` (default) — `console.warn` the issues and return the **original** result unchanged. Non-breaking, with one exception: a connection request or stop signal thrown while the result is checked (from a transform or refinement) still ends the call as that signal, with a framework message in place of its own.
|
||||
- `"strict"` — throw `ActionOutputContractError` (`errorCode: "output_contract_violation"`) so a buggy action surfaces loudly.
|
||||
- `"fallback"` — return `outputFallback` in place of the invalid result.
|
||||
|
||||
On success the validated value is returned, so coercion/defaults on `outputSchema` apply. Omit `outputSchema` and behavior is byte-for-byte unchanged (no wrapping).
|
||||
|
||||
The strict error and such a signal run after `run()`, so they carry `effect`: `"committed"` once a write entered its handler, in the call or in one nested in it (even under a read-only action), and `"none"` otherwise. Writes are classified from the validated arguments, defaults applied. The agent loop, the plan-mode registry, HTTP action routes, and MCP prepare each call once (validated arguments plus that classification) and run exactly that preparation: approval, plan mode, write blocking, batching, and replay all read it, and the run does not parse the arguments again. Preparation reads the validated arguments once into a frozen, plain-data snapshot and hashes it; each gate and `run()` gets its own copy of that snapshot, never the snapshot itself, so mutating `args` in a gate or a handler changes nothing anyone else reads. Validated arguments must therefore be plain data: objects, arrays, strings, numbers, booleans, `null`, `undefined`, BigInts, and valid Dates. A schema whose output holds anything else (a getter or setter, a `Map` or `Set`, a class instance, a function) makes every call fail as invalid. Preparation, its refusals and the per-consumer copies cover calls the agent loop, plan mode, HTTP action routes, and MCP dispatch; a direct `action.run()` (one action composing another, the dev action bridge) gets schema validation only. A call whose arguments are invalid fails before any of them and never reaches the handler. Every reuse of a call's outcome keys on the snapshot's hash, never on the raw input: a continued turn replays a call only when it recorded a committed effect for the same hash, reads are reused only for the same hash, and an interrupted write recovers only a result recorded for the same hash, otherwise it stops instead of running again. The message names only declared field paths and issue codes, never output values, and tells the caller not to retry a committed write. A connection request keeps its `provider`, `reason`, `appId`, and `source` in its fields, in its message, and in HTTP `details`.
|
||||
|
||||
MCP clients see no `outputSchema` by default. Set `mcpOutputSchema: true` (requires `outputErrorStrategy: "strict"`) only after auditing that every real result matches: the tool then advertises the schema as MCP sees it (an array root becomes `{ items }`, linked actions gain `openLink`/`url`), and each `structuredContent` is validated against it before it is returned. Roots must be an object, an object-only union, or an array, and schemas with transforms cannot opt in. The advertised schema allows for MCP's redaction (embed ticket fields dropped; a string holding an embed start URL arrives as `"[hidden embed URL]"`, so required fields stay required). A schema is refused at definition time if it uses a keyword or `format` the check cannot enforce (`not`, `$async`, an unknown format), if redaction could break its `const`, `enum`, or `uniqueItems`, or if a linked action's root limits its property names or count.
|
||||
|
||||
## Authorization (`authorize`)
|
||||
|
||||
`authorize` decides whether the caller may run the action at all. It wraps
|
||||
`run`, so it holds at **all six dispatch sites** — agent tool, HTTP, frontend
|
||||
hook, MCP, A2A, CLI. Use `authorize` for "not everyone may do this"; use
|
||||
`needsApproval` to ask a human to bless one call a permitted caller is already
|
||||
allowed to make.
|
||||
|
||||
```ts
|
||||
import { coachAccess } from "../lib/access.js"; // defineAppRoles(...)
|
||||
|
||||
export default defineAction({
|
||||
description: "Archive a client roster.",
|
||||
schema: z.object({ id: z.string() }),
|
||||
authorize: coachAccess.requireAny("coach-admin"),
|
||||
run: async (args) => {
|
||||
/* ... */
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
The wrappers compose as `validate input -> authorize -> run -> validate output
|
||||
-> audit`: the gate sits inside input validation, so a guard reading `args` gets
|
||||
the parsed, coerced value, and auditing is outermost, so denials are recorded.
|
||||
|
||||
A guard that throws denies with its own message; returning `false` denies
|
||||
generically; anything else (including `undefined`) allows. A guarded action
|
||||
needs a user identity, so an unattended CLI/cron caller with no user email is
|
||||
denied. `authorize` gates the operation; `accessFilter` / `assertAccess` still
|
||||
scope which rows a permitted caller may touch. Use `agent-native-docs` to find
|
||||
the current authentication and sharing documentation when adding role checks.
|
||||
|
||||
## Human-in-the-Loop Approval (`needsApproval`)
|
||||
|
||||
For high-consequence, outward-facing, hard-to-undo actions (sending an email, charging a card, deleting an account), set `needsApproval` so the agent **cannot** run the action without a human approving the specific call:
|
||||
|
||||
```ts
|
||||
export default defineAction({
|
||||
description: "Send an email via Gmail.",
|
||||
schema: z.object({ to: z.string(), subject: z.string(), body: z.string() }),
|
||||
needsApproval: true, // boolean, or (args, ctx) => boolean | Promise<boolean>
|
||||
run: async (args) => {
|
||||
/* ...actually send... */
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
When the gate is truthy and the call isn't yet approved, the loop emits an `approval_required` event and **stops the turn — `run()` never executes**. A predicate gates conditionally (e.g. only external recipients) and **fails closed**: a throw is treated as "approval required". It receives its own copy of the prepared snapshot of the validated arguments, defaults applied, and the approval binds to the snapshot's hash, so an approved call runs only with the arguments that were approved (a Date binds by its time). The human approves via the chat UI's Approve affordance, which re-issues the turn with the call's `approvalKey`, and only then does the action run.
|
||||
|
||||
Approval is given in the app, so HTTP never grants it. The HTTP action route and the generated Workers entry run a gated call only for the proven app UI (a frontend call from the signed-in user, same origin, holding the short-lived UI capability; `isProvenUiRequest`, the proof `uiOnly` uses) or the app's MCP directory widget. Every other direct HTTP caller (bearer or API key, MCP OAuth token, org service token, extension iframe, or mobile app) gets `409 approval_required`, and a service identity can never approve. A2A tasks use their separate approval flow. The task pauses until its owner approves, then replays the approved tool call under its approval lease. The shared client presents the capability with every write from a signed-in session (minted once per user, reused for nine minutes, never for reads or public pages), so a gated button works on its first request. A call without proof gets `403 ui_capability_required`; the client then re-mints and retries once, which is only the fallback for an expired or rejected capability. The agent loop, plan mode registry, HTTP action route, generated Workers entry, and MCP dispatch evaluate the gate through `preparedCallNeedsApproval`, so a throwing predicate asks there too. The local `pnpm action ...` CLI calls `handler.run()` directly and does not evaluate `needsApproval`. Treat it as a local development tool, not an approval boundary. A caller that must run unattended needs a different action, never a bypass of the gate.
|
||||
|
||||
**Keep approvals rare** — the default is off and almost every action should leave it off. The canonical example is Mail's `send-email` (`needsApproval: true`). See the `security` skill and the Human Approval doc.
|
||||
@@ -0,0 +1,96 @@
|
||||
# Extra Action Examples and Compatibility Patterns
|
||||
|
||||
Read this for a second worked example beyond the one in SKILL.md, for the
|
||||
legacy `parameters` form or CLI-only bare-export action you may find in
|
||||
existing code.
|
||||
|
||||
## Common Patterns
|
||||
|
||||
**Read action (GET):**
|
||||
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
import { defineAction } from "@agent-native/core/action";
|
||||
|
||||
export default defineAction({
|
||||
description: "List calendar events",
|
||||
schema: z.object({
|
||||
from: z.string().describe("Start date"),
|
||||
to: z.string().describe("End date"),
|
||||
}),
|
||||
http: { method: "GET" },
|
||||
run: async (args) => {
|
||||
return await fetchEvents(args.from, args.to);
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
**Write action (POST, default):**
|
||||
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
import { defineAction } from "@agent-native/core/action";
|
||||
|
||||
export default defineAction({
|
||||
description: "Log a meal",
|
||||
schema: z.object({
|
||||
name: z.string().describe("Meal name"),
|
||||
calories: z.coerce.number().describe("Calorie count"),
|
||||
}),
|
||||
run: async (args) => {
|
||||
// args.calories is a number — z.coerce.number() handles string-to-number conversion from HTTP
|
||||
const meal = await insertMeal(args);
|
||||
return meal;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
**Agent-only action:**
|
||||
|
||||
```ts
|
||||
import { z } from "zod";
|
||||
import { defineAction, fail } from "@agent-native/core/action";
|
||||
import { writeAppStateForCurrentTab } from "@agent-native/core/application-state";
|
||||
|
||||
export default defineAction({
|
||||
description: "Navigate the UI to a view or path",
|
||||
schema: z.object({
|
||||
view: z.string().optional().describe("Target view"),
|
||||
path: z.string().optional().describe("URL path to navigate to"),
|
||||
}),
|
||||
http: false,
|
||||
run: async (args) => {
|
||||
if (!args.view && !args.path) {
|
||||
fail("At least --view or --path is required.", {
|
||||
errorCode: "invalid_navigation",
|
||||
});
|
||||
}
|
||||
const navigation: Record<string, string> = {};
|
||||
if (args.view) navigation.view = args.view;
|
||||
if (args.path) navigation.path = args.path;
|
||||
navigation._writeId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
await writeAppStateForCurrentTab("navigate", navigation);
|
||||
return { message: `Navigating to ${args.view || args.path}` };
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
## Legacy `parameters` Field
|
||||
|
||||
The older `defineAction` form accepts a JSON Schema object through `parameters`. It still supplies the agent's input schema and infers TypeScript args for supported parameter shapes, but does not provide the Standard Schema validation and transforms of `schema`. Prefer `schema: z.object({...})` for new actions and when updating existing ones.
|
||||
|
||||
## Legacy Pattern (bare export)
|
||||
|
||||
Older actions use a bare async function export with `parseArgs`:
|
||||
|
||||
```ts
|
||||
import { parseArgs, loadEnv, fail } from "@agent-native/core";
|
||||
|
||||
export default async function myAction(args: string[]) {
|
||||
loadEnv();
|
||||
const parsed = parseArgs(args);
|
||||
// ...
|
||||
}
|
||||
```
|
||||
|
||||
The CLI runner still accepts this function form, but it is CLI-only: it is not registered as an agent tool, does not mount an HTTP endpoint, and has no typed frontend hook. Prefer `defineAction` for actions shared with the agent or UI. See `actions-advanced` for this legacy form and its helpers.
|
||||
@@ -0,0 +1,95 @@
|
||||
# Provider API Integrations
|
||||
|
||||
Read this when an action needs to call an external provider API — HubSpot,
|
||||
Gong, Slack, any credentialed third-party service — for ad hoc analysis,
|
||||
querying, reporting, or cross-source research.
|
||||
|
||||
For provider integrations used in ad hoc analysis, querying, reporting, or
|
||||
cross-source research, do not hardcode every provider endpoint as a separate
|
||||
rigid action and do not encode one lookback window, filter shape, or pagination
|
||||
strategy as the only path the agent can take. Expose the shared provider API
|
||||
action trio instead:
|
||||
|
||||
- `provider-api-catalog`: lists provider base URLs, auth style, credential keys,
|
||||
docs/spec URLs, placeholders, and examples without exposing secrets.
|
||||
- `provider-api-docs`: fetches public provider docs/spec/changelog URLs when
|
||||
the exact endpoint, filter operator, payload shape, or pagination contract is
|
||||
uncertain. Registered docs URLs are curated starting points. Use
|
||||
`responseMode: "markdown"` for clean readable docs, or
|
||||
`responseMode: "matches"` with `search: { query | terms | regex }` for
|
||||
compact snippets instead of flooding context with raw HTML.
|
||||
- `provider-api-request`: makes a constrained authenticated HTTP request to the
|
||||
provider host, injects configured credentials, blocks private/internal URLs,
|
||||
and redacts secrets.
|
||||
|
||||
Use `@agent-native/core/provider-api` as the shared substrate, and build these
|
||||
actions as thin factory imports rather than copying `defineAction` schemas and
|
||||
handlers into each template:
|
||||
|
||||
```ts
|
||||
import {
|
||||
createProviderApiCatalogAction,
|
||||
createProviderApiDocsAction,
|
||||
createProviderApiRequestAction,
|
||||
} from "@agent-native/core/provider-api/actions/provider-api";
|
||||
import {
|
||||
createDeleteStagedDatasetAction,
|
||||
createListStagedDatasetsAction,
|
||||
createQueryStagedDatasetAction,
|
||||
} from "@agent-native/core/provider-api/actions/staged-datasets";
|
||||
```
|
||||
|
||||
Pass the app's existing provider runtime to the provider factories, and pass
|
||||
its app id to the staged-dataset factories. Keep app-specific descriptions,
|
||||
provider allow-lists, HTTP/tool-callability settings, and credential adapters
|
||||
as factory options. Only add a thin credential adapter when the app has
|
||||
app-specific credential lookup rules. If the app stores a built-in provider's
|
||||
OAuth grant under a narrower local provider id, use the runtime's
|
||||
`oauthProviderOverrides` instead of duplicating provider config. If credentials
|
||||
are stored on shareable/resource rows rather than in the shared credential or
|
||||
OAuth-token stores, build a resolver that enforces those access checks before
|
||||
exposing raw provider requests. Keep `provider-api-request` `http: false`
|
||||
unless a separate UI permission model authorizes arbitrary provider writes.
|
||||
Specific actions such as `search-records`, `search-emails`, or `sync-source`
|
||||
are convenience shortcuts, not capability limits; agents should fall back to
|
||||
the provider API trio when a question requires an endpoint or filter that the
|
||||
shortcut does not model.
|
||||
|
||||
This is a framework tenet. The safety boundary should be provider host
|
||||
allow-listing, credential scoping, auth injection, private-network blocking,
|
||||
secret redaction, and user/org access checks, not an artificially small set of
|
||||
hand-authored read actions. If the upstream provider API supports a capability,
|
||||
the agent should normally be able to reach it through `provider-api-request`
|
||||
with the user's configured credentials. For large responses, expose staging
|
||||
(`stageAs`, `itemsPath`, pagination, and `query-staged-dataset`) or sandboxed
|
||||
code execution so the agent can reduce data without flooding context.
|
||||
|
||||
For broad provider questions, cross-source joins, corpus-wide mention/search
|
||||
work, classification, or any answer where absence matters, design the action
|
||||
surface for full coverage instead of convenience-only samples. The agent should
|
||||
be able to fetch every relevant page or an explicitly bounded cohort, stage or
|
||||
save the raw provider response outside chat, and then use
|
||||
`query-staged-dataset`, `run-code`, or provider-side search to count, join,
|
||||
grep, classify, and aggregate. Tool descriptions and AGENTS.md guidance should
|
||||
teach agents to report source, filters, time window, row/record counts,
|
||||
pagination status, truncation, failed pages, and uncovered gaps. They must not
|
||||
turn default limits, sampled rows, truncated excerpts, or aborted calls into a
|
||||
confident "none found", "all records", or exhaustive conclusion.
|
||||
|
||||
For public web pages and docs, prefer the token-efficient path: `web-search`
|
||||
to find likely URLs, `web-request` or `provider-api-docs` with clean
|
||||
`responseMode` output to read a page, and `run-code` with `webRead()` /
|
||||
`webFetch()` when you need to grep, aggregate, or compare many pages before
|
||||
returning a small result.
|
||||
|
||||
For LONG compute, `run-code` supports durable background executions: pass
|
||||
`background: true` and the code is enqueued to a `sandbox_executions` row and
|
||||
executed out-of-band with a generous budget (default 10 min), surviving the
|
||||
hosted agent run's ~40s soft timeout. The call returns
|
||||
`{ executionId, status: "queued" }` immediately with polling guidance; check
|
||||
progress with `run-code` `{ executionId }` (or the `get-code-execution` tool
|
||||
where registered) — results persist after completion. Use background for big
|
||||
cross-source joins, multi-page provider sweeps, and heavy analysis scripts;
|
||||
keep quick scripts in the default foreground mode. Agents should continue
|
||||
other work between polls, and on `failed`/`timed_out` split the computation or
|
||||
persist intermediate progress with `workspaceWrite` and re-run.
|
||||
@@ -0,0 +1,236 @@
|
||||
---
|
||||
name: adding-a-feature
|
||||
description: >-
|
||||
The four-area checklist every new feature must complete. Use when adding any
|
||||
feature, integration, or capability to ensure the agent and UI stay in parity.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Adding a Feature — The Four-Area Checklist
|
||||
|
||||
## Rule
|
||||
|
||||
Every new feature MUST update all four areas. Skipping any one breaks the agent-native contract — the agent and UI must always be equal partners.
|
||||
|
||||
Scope check first: this is the checklist for a feature that adds app data or a new capability. A restyle, a copy change, or a screen with no new data model and no new agent-visible operation only needs the areas it actually touches — do not manufacture actions, state keys, or a skill for it.
|
||||
|
||||
## Why
|
||||
|
||||
Agent-Native apps are defined by parity: everything the UI can do, the agent can do, and vice versa. A feature that only has UI is invisible to the agent. A feature that only has scripts is invisible to the user. A feature without app-state sync means the agent is blind to what the user is doing.
|
||||
|
||||
## The Checklist
|
||||
|
||||
When you add a new feature, work through these four areas in order:
|
||||
|
||||
### 1. UI Component
|
||||
|
||||
Build the user-facing interface — a page, component, dialog, or route. Use `useActionQuery` and `useActionMutation` from `@agent-native/core/client/hooks` to call actions for data fetching and mutations. Do not create a custom REST endpoint just so React can call action-backed data; the action endpoint already exists.
|
||||
|
||||
**Agent edits must refresh the UI without a background poll.** Local chat-run
|
||||
tool completions invalidate action queries and source counters after each
|
||||
side-effecting tool and again at run end. There are two query paths:
|
||||
|
||||
- **`useActionQuery` / `useActionMutation`** — local action mutations invalidate `['action']` observers, and chat-run tool completions invalidate them for agent writes. No background sync opt-in is needed for the current user's agent run. **Prefer this path.**
|
||||
- **Raw `useQuery` with custom keys** — fold `useChangeVersions([<source>, "action"])` from `@agent-native/core/client/hooks` into the `queryKey` and set `placeholderData: (prev) => prev`. Local chat-run side effects bump those counters too. Remote changes require the page's explicit `useDbSync({ realtime: { reason } })` opt-in only when data changes without the current user acting and must appear before refresh.
|
||||
|
||||
Never opt in public, anonymous, marketing, docs, or SSR routes, settings,
|
||||
forms, or read-mostly lists. Refetch those on focus or navigation. Shared Slides
|
||||
editing and the Mail inbox are the current first-party examples that need
|
||||
remote updates. Each opted-in open tab adds a shared background transport and
|
||||
one poll per idle interval; hidden tabs pause, and idle polling backs off to 1,
|
||||
2, then 5 minutes. See `real-time-sync` for the decision rule and examples.
|
||||
|
||||
```tsx
|
||||
import { useChangeVersions } from "@agent-native/core/client/hooks";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
|
||||
const v = useChangeVersions(["dashboards", "action"]);
|
||||
useQuery({
|
||||
queryKey: ["dashboard", id, v],
|
||||
queryFn: () => fetchDashboard(id),
|
||||
placeholderData: (prev) => prev, // no flicker on refetch
|
||||
});
|
||||
```
|
||||
|
||||
See the `real-time-sync` skill for the full pattern and source catalog.
|
||||
|
||||
### 2. Action
|
||||
|
||||
Create an action in `actions/` using `defineAction`. This serves double duty: the agent calls it as a tool, and the UI calls it through `useActionQuery` / `useActionMutation` while the framework owns the HTTP transport. Set `http: { method: "GET" }` for read actions, leave default for writes, or set `http: false` for agent-only actions like `navigate` and `view-screen`.
|
||||
|
||||
Before adding a new route or endpoint, inspect the existing actions. Reuse an
|
||||
action if it already covers the business operation, extend it if the shared
|
||||
contract is incomplete, or create a new `defineAction` if the agent and UI both
|
||||
need the capability. Do not add pass-through `/api/*` routes that re-export
|
||||
actions. If client code needs a new framework/app route, expose a named helper
|
||||
or hook first and use that helper from components and docs.
|
||||
|
||||
For provider-backed analysis/query/reporting integrations, do not turn every
|
||||
provider endpoint or filter into a rigid action. Prefer the shared
|
||||
`provider-api-catalog` / `provider-api-docs` / `provider-api-request` pattern
|
||||
from `@agent-native/core/provider-api`, then add narrow convenience actions only
|
||||
for workflows that truly deserve a first-class shortcut. Treat this as a
|
||||
capability requirement, not a nice-to-have: convenience actions must not become
|
||||
the ceiling of what the agent can ask the provider to do. Pair broad provider
|
||||
access with staging or sandboxed code execution when responses may be too large
|
||||
for chat context. If provider credentials live on resource/share rows, add the
|
||||
scoped resolver first so broad access preserves the same ownership boundary as
|
||||
the app UI.
|
||||
|
||||
If the feature needs credentials, design the credential path in the same change.
|
||||
Never hardcode credentials or include personal or customer data in source,
|
||||
fixtures, docs, prompts, or generated app content. Register required secrets,
|
||||
use OAuth helpers, or read scoped values from the credential store.
|
||||
|
||||
Before writing custom setup or credential UI, perform the shared-primitive
|
||||
preflight from `agent-native-toolkit`: inspect the workspace/provider connection
|
||||
catalog first, then settings, secrets/vault, OAuth, onboarding, and provider API
|
||||
support. Reuse an existing connection's app grant and scoped credential
|
||||
resolver; only use app-local vault or OAuth primitives when no reusable
|
||||
connection exists. Keep any wizard thin and provider-specific - it may explain
|
||||
prerequisites, ordering, or readiness, but must not become a second vault or
|
||||
custom credential transport. Do not mark each field `required` by reflex;
|
||||
model onboarding around the logical connection outcome.
|
||||
|
||||
If the feature involves attachments, images, recordings, screenshots, exports,
|
||||
or other file-like payloads, design the upload path in the same change:
|
||||
provider upload first, then URL/id/blob handle in SQL. Do not add base64/binary
|
||||
columns or stuff files into `application_state`.
|
||||
|
||||
If the feature adds a heavy server-side dependency, read the startup guidance in
|
||||
`performance` before adding it. Keep expensive setup and processing out of
|
||||
request-startup paths; use a background job when the work does not need to block
|
||||
the current request.
|
||||
|
||||
**If the action produces or lists a navigable resource**, add a `link` builder that returns `{ url: buildDeepLink({ app, view, params }), label }`. MCP hosts can surface a deep link that returns the user to the running app at that record. If a compatible host should render an inline review or edit surface, also add `mcpApp` with `embedApp()` so the action embeds the real app route. Keep `link` and `mcpApp` metadata pure and synchronous. Use the external-agent documentation when exposing actions to other agent hosts.
|
||||
|
||||
Scaffolding a new app of a known type (slides, design, content, forms)? Start from that template's `AGENTS.md` and `.agents/skills/`, not a blank app.
|
||||
|
||||
### 3. Skills / Instructions
|
||||
|
||||
Update `AGENTS.md` and/or create a skill in `.agents/skills/` if the feature introduces patterns the agent needs to know. At minimum, add the new actions to the action table in the template's `AGENTS.md`.
|
||||
|
||||
Before completing this area, identify the feature's primary actions:
|
||||
|
||||
- Document primary workflows in the `AGENTS.md` action table.
|
||||
- If the app configures `initialToolNames` (`INITIAL_TOOL_NAMES` in some
|
||||
templates), add the primary actions there. If it uses per-action loading,
|
||||
mark the complete starter set `deferLoading: false`; once one action opts in,
|
||||
unmarked actions are deferred. The remaining actions stay discoverable through
|
||||
`tool-search`.
|
||||
- If `mcp.keyToolNames` is configured, align it with primary actions actually
|
||||
served on MCP/WebMCP. It controls the external key-tools list and does not
|
||||
change the in-app agent's first-turn list.
|
||||
|
||||
Reusable actions are part of the app contract, not just implementation detail. When an action is useful outside one screen, update agent instructions in the same change so app agents know when to call it, which arguments matter, and what output to preserve. If the capability is workflow-heavy, cross-app, provider-backed, or has a non-obvious sequence of actions, add or update a skill instead of burying the behavior in one long `AGENTS.md` paragraph.
|
||||
|
||||
- For chat prompt dispatch, put the readiness gate at the shared dispatch boundary and cover submits, retries, edits/forks, queue drains, continuations, and imperative sends. Dispatch only after readiness is authoritatively configured; return a typed setup-required error and preserve the draft when readiness is missing or unavailable. Composer checks and setup cards are UX, not enforcement, and no new `...ChecksEnabled={false}` bypass is allowed.
|
||||
|
||||
Instruction examples may name secret keys like `SLACK_WEBHOOK`, but must use
|
||||
placeholders such as `${keys.SLACK_WEBHOOK}` or `<SLACK_WEBHOOK>`. Do not paste
|
||||
real keys, internal data, or customer data into instructions as examples.
|
||||
|
||||
If the feature adds or changes visible UI copy, prompts, toasts, labels, empty
|
||||
states, or formatting, edit the English strings inline in components. Do **not**
|
||||
add i18n catalogs unless the user explicitly asks for localization; only then
|
||||
read the `internationalization` skill.
|
||||
|
||||
For app-backed skills, declare skill visibility in the app-skill manifest:
|
||||
|
||||
- `internal` — only the app's own agents should use it.
|
||||
- `exported` — marketplace installs receive it, but the app does not need it loaded internally.
|
||||
- `both` — shared between the app's internal agents and exported marketplace bundles.
|
||||
|
||||
### 4. Application State Sync
|
||||
|
||||
Expose navigation and selection state so the agent knows what the user is looking at. Write to the `navigation` app-state key on route changes. Update the `view-screen` action to fetch relevant data for the new feature. Add a `navigate` command if the agent needs to open the new view. Text resources participate in `export-resource-pack`; binaries and secrets do not.
|
||||
|
||||
## Examples
|
||||
|
||||
### Adding "compose email" to a mail app
|
||||
|
||||
| Area | What to build |
|
||||
| --- | --- |
|
||||
| UI | Compose panel with tabs, to/cc/bcc fields, body editor. Use `useActionQuery`/`useActionMutation` for data. |
|
||||
| Action | `manage-draft` action (create/update/delete drafts), `send-email` action |
|
||||
| Skills/AGENTS | Document compose state shape, draft lifecycle, action args in AGENTS.md |
|
||||
| App-state sync | `compose-{id}` keys for each draft tab, `navigation` includes compose state |
|
||||
|
||||
### Adding "create form" to a forms app
|
||||
|
||||
| Area | What to build |
|
||||
| --- | --- |
|
||||
| UI | Form builder page with drag-and-drop fields, preview, settings. Use `useActionQuery` for lists. |
|
||||
| Action | `create-form` action, `update-form` action, `list-forms` action (GET) |
|
||||
| Skills/AGENTS | Document form schema shape, field types, validation rules in AGENTS.md |
|
||||
| App-state sync | `navigation` includes `{ view: "form-builder", formId: "..." }`, `view-screen` fetches form data |
|
||||
|
||||
### Adding "chart type" to an analytics app
|
||||
|
||||
| Area | What to build |
|
||||
| --- | --- |
|
||||
| UI | New chart component, chart type selector in dashboard |
|
||||
| Action | `create-chart` or `update-dashboard` action that sets chart type and config |
|
||||
| Skills/AGENTS | Document supported chart types, config options, data requirements |
|
||||
| App-state sync | `navigation` includes selected chart/dashboard, `view-screen` returns chart config |
|
||||
|
||||
## Adding a new route
|
||||
|
||||
Templates are single-page apps with client-side routing. The app shell (AgentSidebar + top-level nav) MUST persist across navigation — it is mounted once, either in `root.tsx` around `<Outlet />` or via a pathless `_app.tsx` layout route that all authed routes nest under.
|
||||
|
||||
**Never wrap each new route in its own `<AppLayout>` / `<Layout>`.** That causes React to unmount the entire app shell on every navigation, reloading the agent sidebar and destroying in-progress work.
|
||||
|
||||
- If the template has `<AppLayout>` in `root.tsx` — just render page content in your new route file, nothing else.
|
||||
- If the template has `app/routes/_app.tsx` (pathless layout) — name your new route `_app.<segment>.tsx` to inherit the shell, or bare `<segment>.tsx` for public routes that should NOT have the shell.
|
||||
- If a page needs per-route data (e.g. highlighting the active item in the sidebar), read it in the layout from `useParams()` / `useLocation()`. Don't pass it as a prop through every route file.
|
||||
|
||||
See the "Client-Side Routing" section in the root `CLAUDE.md` for full details.
|
||||
|
||||
## Anti-Patterns
|
||||
|
||||
- **Per-route `<AppLayout>` wrappers** — Every route file wraps its content in `<AppLayout>` or `<Layout>`. React sees a different component at the outlet on each nav and unmounts the whole shell, causing the agent sidebar to reload on every click. Mount the shell once above `<Outlet />` (root.tsx or `_app.tsx` pathless layout).
|
||||
- **UI without actions** — The user can create forms but the agent cannot. The agent says "I don't have access to that" when it should be able to do it.
|
||||
- **Actions without AGENTS.md** — The actions exist but the agent doesn't know about them because they're not documented. The agent reinvents solutions instead of using the actions.
|
||||
- **Duplicate API routes** — Creating `/api/` routes for operations that actions already handle, including pass-through routes that just call or repackage an action. Use `useActionQuery`/`useActionMutation` instead.
|
||||
- **Raw client route calls** — Teaching or adding `fetch("/_agent-native/...")`,
|
||||
`fetch(agentNativePath(...))`, or template `/api/*` calls in components for
|
||||
normal app work. Add a named client helper/hook and call that instead.
|
||||
- **Features without app-state** — The agent cannot see that the user is looking at a specific form, email, or chart. It asks "which one?" instead of acting on the current selection.
|
||||
- **Actions without UI** — The agent can do something the user cannot. This is less common but still breaks parity.
|
||||
|
||||
## Verification
|
||||
|
||||
After completing all four areas, verify:
|
||||
|
||||
1. Can the user perform the operation from the UI?
|
||||
2. Can the agent perform the same operation via actions?
|
||||
3. Does `pnpm action view-screen` show the relevant state when the user is using the feature?
|
||||
4. Can the agent navigate to the feature view via the `navigate` action?
|
||||
5. Is the feature documented in AGENTS.md with action names and args?
|
||||
6. Are credentials supplied through approved runtime channels, with no
|
||||
hardcoded keys, tokens, or user data?
|
||||
|
||||
## One more area — sharing
|
||||
|
||||
If the feature stores **user-authored resources** (documents, dashboards, forms, decks, etc.), make them ownable so they get private-by-default semantics and a share dialog for free. See the `sharing` skill.
|
||||
|
||||
TL;DR: spread `ownableColumns()` into the resource table, pair it with `createSharesTable(...)`, call `registerShareableResource(...)`, wrap list/read queries with `accessFilter`, guard writes with `assertAccess`, and drop `<ShareButton>` in the resource header. The `share-resource`, `unshare-resource`, `list-resource-shares`, and `set-resource-visibility` actions are auto-mounted framework-wide.
|
||||
|
||||
## One more area — who inside the app may do it
|
||||
|
||||
If only some teammates may perform a feature (such as an admin-only import), use a per-app role rather than creating an organization or using a share grant. Use `agent-native-docs` to find the current role guide if needed.
|
||||
|
||||
TL;DR: declare the vocabulary once with `defineAppRoles({ appId, roles, defaultRole })`, guard the action with `authorize: appAccess.requireAny("...")`, and render the picker with `<TeamPage appRoles={descriptor} />`. `defaultRole` is display only — it never satisfies a guard — and `authorize` gates the operation while `accessFilter` / `assertAccess` still scope the rows.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- **sharing** — How to make a new resource ownable (private by default, share with users/orgs/public)
|
||||
- **context-awareness** — How to expose UI state to the agent (area 4 in detail)
|
||||
- **actions** — How to create actions with `defineAction` and the `http` option (area 2 in detail)
|
||||
- **build-an-app** — Start a complete app from a vague domain prompt
|
||||
- **storing-data** — Where to store the feature's data
|
||||
- **real-time-sync** — How the UI stays in sync when the agent writes data
|
||||
- **performance** — Query/load cost and expensive startup work
|
||||
- **agent-native-docs** — Find current docs for roles, external agents, or localization
|
||||
@@ -0,0 +1,232 @@
|
||||
---
|
||||
name: agent-engines
|
||||
description: >-
|
||||
How to inspect and configure the AI engine (model provider) powering the
|
||||
agent. Use when the user asks to switch models, check which engine is active,
|
||||
test a new provider, or register a custom engine.
|
||||
---
|
||||
|
||||
# Agent Engines
|
||||
|
||||
## Overview
|
||||
|
||||
The framework supports pluggable AI engines beneath the agent loop. The **Anthropic engine** is the default and best-in-class path (Claude models). Additional engines can be added via the Vercel AI SDK (OpenAI, Google Gemini, Groq, Mistral, Cohere, Ollama).
|
||||
|
||||
## Available Tools
|
||||
|
||||
| Tool | Purpose |
|
||||
|---|---|
|
||||
| `list-agent-engines` | List all registered engines, their capabilities, the current selection, and whether you can change the organization default (`canUpdateDefault`) |
|
||||
| `set-agent-engine` | Set the organization's default engine and model (owners and admins only) |
|
||||
| `test-agent-engine` | Send a trivial prompt to verify the engine works (connectivity + API key) |
|
||||
| `check-provider-key` | Check a provider API key by listing the models it reaches, before saving it |
|
||||
| `get-provider-models` | Read which models each provider shows in the model picker and default-model select |
|
||||
| `manage-provider-models` | Choose those models (`set`) or go back to the recommended ones (`reset`) |
|
||||
| `list-model-providers` | What Settings › Model shows: each provider's organization and personal key (masked), rejections, the restriction, and the stored default |
|
||||
|
||||
## Checking the Current Engine
|
||||
|
||||
```
|
||||
list-agent-engines
|
||||
```
|
||||
|
||||
Returns the registry of all engines (name, label, capabilities, supported models) plus the currently active engine and model. `supportedModels` is what the model picker offers: the provider's checked models when `modelSelection.state` is `"selected"`, otherwise its `recommendedModels`. `credentialRejected: true` means the provider rejected that engine's saved key (`credentialRejectedAt` says when); chats with it stop until the key is replaced, so tell the user.
|
||||
|
||||
## Switching Engines
|
||||
|
||||
```
|
||||
set-agent-engine --engine "ai-sdk:openai" --model "gpt-4o"
|
||||
```
|
||||
|
||||
Changes take effect on the next conversation. The default belongs to the organization (the `agent-engine` org setting), and only owners and admins can change it. A member's call is refused with an error to relay: ask an owner or admin, or pick a model for this chat in the model picker. A user with no organization sets their own default.
|
||||
|
||||
Resolution order (highest priority first):
|
||||
1. Explicit `engine` option passed to `createAgentChatPlugin()` in the server plugin
|
||||
2. The organization's default (`agent-engine` org setting)
|
||||
3. `AGENT_ENGINE` environment variable
|
||||
4. Default: `"anthropic"` (requires `ANTHROPIC_API_KEY`)
|
||||
|
||||
## Settings › Model
|
||||
|
||||
The Model page (`/settings/model`, page id `model`) has three groups:
|
||||
|
||||
- **Organization providers:** the organization's Builder.io connection and each organization key. Owners and admins manage them; members see only "N models".
|
||||
- **Personal providers:** a member's own Builder.io connection, their own keys, and the ChatGPT subscription while its lab is on. A personal key is used before the organization's, for that person only.
|
||||
- **Organization settings:** Default model (`manage-agent-engine` `set`, organization models only), Restrict personal API keys (`manage-provider-key-policy`), and Max iterations (`manage-agent-loop-settings`, 1 to 1000). Owners and admins change them; members see the values.
|
||||
|
||||
Read the page's state with `list-model-providers`, and the models each provider shows with `get-provider-models`. Keys are added and replaced in the provider dialog, which checks a pasted key by listing its models; you can't save a key for the user, so check one with `check-provider-key` and send them to Model (`open-settings-page`) to paste it. Before they remove a provider, run `preview-secret-removal` with the provider's key name and scope and tell them what stops.
|
||||
|
||||
## Restricting Personal API Keys
|
||||
|
||||
`manage-provider-key-policy` reads or changes the organization's "Restrict personal API keys" setting. While it is on, members (not owners or admins) can't use or save their own provider keys or a personal Builder.io connection, so their chats use organization providers; with none, a chat fails with "Owners and admins restricted personal API keys." Nothing is deleted, and turning it off restores their keys.
|
||||
|
||||
```
|
||||
manage-provider-key-policy # read; owners/admins also get affectedMembers
|
||||
manage-provider-key-policy --set true # owners and admins only
|
||||
```
|
||||
|
||||
Read it first and tell the user which members lose which providers before turning it on.
|
||||
|
||||
## Testing a New Engine
|
||||
|
||||
Before switching, verify the engine is working:
|
||||
|
||||
```
|
||||
test-agent-engine --engine "ai-sdk:openai" --model "gpt-4o"
|
||||
```
|
||||
|
||||
Returns `{ ok, latencyMs, response, capabilities }`. If `ok: false`, the error message explains what's wrong (missing API key, package not installed, etc.).
|
||||
|
||||
To check a key without sending a prompt, for example one the user just gave you:
|
||||
|
||||
```
|
||||
check-provider-key --provider "anthropic" --key "<the key>"
|
||||
```
|
||||
|
||||
Returns `{ ok: true, models }` or `{ ok: false, code, reason }` (`rejected`, `wrong-provider`, `missing-key`, `invalid-endpoint`, `unreachable`, `provider-error`). Relay the reason. Omit `--key` to re-check the saved key; it is only checked against its saved endpoint, so `--baseUrl` needs `--key` (except for Ollama). `--scope org` is for owners and admins.
|
||||
|
||||
## Choosing Which Models Show
|
||||
|
||||
Each provider (Builder.io included) keeps the models its owner checked. Only checked models appear in the chat model picker and the default-model select; Builder.io and providers with their own key show side by side.
|
||||
|
||||
```
|
||||
get-provider-models --provider "openai"
|
||||
manage-provider-models --action "set" --provider "openai" --models '["gpt-6-sol"]'
|
||||
manage-provider-models --action "reset" --provider "openai"
|
||||
```
|
||||
|
||||
- A selection lives at the same scope as the provider's key: `--scope user` is the caller's own, `--scope org` is the organization's (owners and admins only; members get an error to relay). Without `--scope`, the call changes the selection in effect, which follows the key in effect (a member's personal key uses their personal selection).
|
||||
- A member's personal selection never changes the organization's. The default-model select always offers the organization's checked models.
|
||||
- `set` with an empty list hides the provider's chat models, for a key used only by services. Builder.io accepts only its own catalog.
|
||||
- A chat already on an unchecked model keeps running on it. When nothing picked a model and the engine default is unchecked, chats use the first checked model.
|
||||
- A row with `models: null` has nothing chosen and shows the recommended models. `state: "unreadable"` means the selection couldn't be read, not that it is empty.
|
||||
|
||||
## Built-in Engines
|
||||
|
||||
| Engine Name | Provider | Requires |
|
||||
|---|---|---|
|
||||
| `anthropic` | Anthropic Claude SDK | `ANTHROPIC_API_KEY` |
|
||||
| `ai-sdk:anthropic` | Claude via Vercel AI SDK | `ANTHROPIC_API_KEY` |
|
||||
| `ai-sdk:openai` | OpenAI via Vercel AI SDK | `OPENAI_API_KEY` |
|
||||
| `ai-sdk:openrouter` | 300+ models (Anthropic, OpenAI, Google, Meta, …) routed through OpenRouter | `OPENROUTER_API_KEY` |
|
||||
| `ai-sdk:google` | Google Gemini via Vercel AI SDK | `GOOGLE_GENERATIVE_AI_API_KEY` |
|
||||
| `ai-sdk:groq` | Groq LPU via Vercel AI SDK | `GROQ_API_KEY` |
|
||||
| `ai-sdk:mistral` | Mistral via Vercel AI SDK | `MISTRAL_API_KEY` |
|
||||
| `ai-sdk:cohere` | Cohere via Vercel AI SDK | `COHERE_API_KEY` |
|
||||
| `ai-sdk:ollama` | Local Ollama via Vercel AI SDK | None (local) |
|
||||
|
||||
## Engine Capabilities
|
||||
|
||||
Each engine advertises its capabilities:
|
||||
|
||||
| Capability | Anthropic | AI SDK: Anthropic | AI SDK: OpenAI | AI SDK: Google |
|
||||
|---|---|---|---|---|
|
||||
| `thinking` | ✓ | ✓ | ✗ | ✓ |
|
||||
| `promptCaching` | ✓ | ✓ | ✗ | ✗ |
|
||||
| `vision` | ✓ | ✓ | ✓ | ✓ |
|
||||
| `computerUse` | ✓ | ✗ | ✗ | ✗ |
|
||||
| `parallelToolCalls` | ✓ | ✓ | ✓ | ✓ |
|
||||
|
||||
## Anthropic-Exclusive Features
|
||||
|
||||
When using the `anthropic` engine (or `ai-sdk:anthropic`):
|
||||
|
||||
- **Prompt caching** is applied automatically to the system prompt — cutting latency and cost on repeated turns.
|
||||
- **Extended thinking** can be enabled via `providerOptions.anthropic.thinking` — the agent reasons longer before responding.
|
||||
|
||||
These features are silently ignored when a non-Anthropic engine is active (capability-gated, no breakage).
|
||||
|
||||
## Using OpenRouter
|
||||
|
||||
`ai-sdk:openrouter` gives access to 300+ models from many providers through a single API. Model IDs use the `vendor/model` form:
|
||||
|
||||
```
|
||||
set-agent-engine --engine "ai-sdk:openrouter" --model "anthropic/claude-sonnet-4.5"
|
||||
set-agent-engine --engine "ai-sdk:openrouter" --model "openai/gpt-4o"
|
||||
set-agent-engine --engine "ai-sdk:openrouter" --model "google/gemini-2.5-pro"
|
||||
```
|
||||
|
||||
Any `vendor/model` string from [openrouter.ai/models](https://openrouter.ai/models) works — the `supportedModels` list in the registry is a UI hint, not an allow-list.
|
||||
|
||||
**App attribution** (optional): pass `appName` / `appUrl` in the engine config to set the `X-OpenRouter-Title` / `HTTP-Referer` headers — useful to see your app on the OpenRouter dashboard and leaderboards:
|
||||
|
||||
```ts
|
||||
createAISDKEngine("openrouter", {
|
||||
apiKey: process.env.OPENROUTER_API_KEY,
|
||||
appName: "My App",
|
||||
appUrl: "https://myapp.example",
|
||||
});
|
||||
```
|
||||
|
||||
## Registering a Custom Engine
|
||||
|
||||
Register custom engines in a server plugin at startup. Import from the
|
||||
`@agent-native/core/agent/engine` subpath:
|
||||
|
||||
```ts
|
||||
// server/plugins/my-engine.ts
|
||||
import {
|
||||
registerAgentEngine,
|
||||
type AgentEngine,
|
||||
type EngineEvent,
|
||||
type EngineStreamOptions,
|
||||
} from "@agent-native/core/agent/engine";
|
||||
|
||||
registerAgentEngine({
|
||||
name: "my-engine",
|
||||
label: "My Custom Engine",
|
||||
description: "...",
|
||||
capabilities: {
|
||||
thinking: false,
|
||||
promptCaching: false,
|
||||
vision: false,
|
||||
computerUse: false,
|
||||
parallelToolCalls: true,
|
||||
},
|
||||
defaultModel: "my-model-v1",
|
||||
supportedModels: ["my-model-v1", "my-model-v2"],
|
||||
requiredEnvVars: ["MY_ENGINE_API_KEY"],
|
||||
create: (config): AgentEngine => ({
|
||||
name: "my-engine",
|
||||
label: "My Custom Engine",
|
||||
defaultModel: "my-model-v1",
|
||||
supportedModels: ["my-model-v1", "my-model-v2"],
|
||||
capabilities: {
|
||||
/* same shape as above */
|
||||
} as any,
|
||||
async *stream(opts: EngineStreamOptions): AsyncIterable<EngineEvent> {
|
||||
// yield text-delta / thinking-delta / tool-call / usage events
|
||||
// as they arrive, then:
|
||||
yield { type: "assistant-content", parts: /* final content parts */ [] };
|
||||
yield { type: "stop", reason: "end_turn" };
|
||||
},
|
||||
}),
|
||||
});
|
||||
```
|
||||
|
||||
### Engine stream contract
|
||||
|
||||
Every engine's `stream(opts)` MUST emit, in order:
|
||||
|
||||
1. Zero or more `text-delta`, `thinking-delta`, `tool-call`, and `usage`
|
||||
events as they arrive from the model.
|
||||
2. Exactly one `{ type: "assistant-content", parts }` event with the
|
||||
structured content for the turn. `runAgentLoop` reads this to
|
||||
reconstruct the assistant message for the next turn.
|
||||
3. Exactly one terminal `{ type: "stop", reason }` event.
|
||||
|
||||
After registering, the engine appears in `list-agent-engines` output and can
|
||||
be selected via `set-agent-engine`.
|
||||
|
||||
## Env Vars Reference
|
||||
|
||||
| Variable | Purpose |
|
||||
|---|---|
|
||||
| `ANTHROPIC_API_KEY` | Required for `anthropic` and `ai-sdk:anthropic` engines |
|
||||
| `OPENAI_API_KEY` | Required for `ai-sdk:openai` |
|
||||
| `OPENROUTER_API_KEY` | Required for `ai-sdk:openrouter` |
|
||||
| `GOOGLE_GENERATIVE_AI_API_KEY` | Required for `ai-sdk:google` |
|
||||
| `GROQ_API_KEY` | Required for `ai-sdk:groq` |
|
||||
| `MISTRAL_API_KEY` | Required for `ai-sdk:mistral` |
|
||||
| `COHERE_API_KEY` | Required for `ai-sdk:cohere` |
|
||||
| `AGENT_ENGINE` | Default engine name (overridden by settings store) |
|
||||
@@ -0,0 +1,161 @@
|
||||
---
|
||||
name: agent-native-docs
|
||||
description: >-
|
||||
How to find version-matched Agent-Native framework docs and source bundled in
|
||||
node_modules. Use before implementing or answering questions about
|
||||
@agent-native/core APIs, generated apps, workspaces, templates, or advanced
|
||||
features.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Agent-Native Docs Lookup
|
||||
|
||||
## Rule
|
||||
|
||||
Before implementing or explaining non-trivial Agent-Native behavior, read the
|
||||
version-matched docs installed with `@agent-native/core`. When examples,
|
||||
imports, or implementation details matter, inspect the packaged source corpus
|
||||
too.
|
||||
|
||||
## Why
|
||||
|
||||
Generated apps and workspaces may be on a different framework version than the
|
||||
public docs or model memory. The installed package is the source that matches
|
||||
the app in front of you. A version-matched `@agent-native/core-corpus` package
|
||||
provides first-party template source when an app needs those examples, without
|
||||
adding the corpus to every Core installation.
|
||||
|
||||
## How
|
||||
|
||||
From a generated app directory:
|
||||
|
||||
```bash
|
||||
pnpm action framework-search --pattern "defineAction"
|
||||
pnpm action framework-search \
|
||||
--pattern "defineAction" \
|
||||
--scope source \
|
||||
--path "templates/*/actions/*.ts"
|
||||
pnpm action framework-search --pattern "Agent(?:Panel|Sidebar)" --mode regex --scope source
|
||||
```
|
||||
|
||||
Use `framework-search` first when a question may cross the docs and source
|
||||
boundary. It searches version-matched framework docs, runtime-visible skills,
|
||||
readable Core or Toolkit package source, and first-party template source when
|
||||
the optional corpus is installed, in one bounded read-only call. Use
|
||||
`scope: docs` or `scope: source` to narrow it, then use the focused readers for
|
||||
the page or file you need.
|
||||
|
||||
The headless `pnpm agent` loop and built-in app agents expose read-only
|
||||
`framework-search`, `docs-search`, and `source-search` tools when Core's docs
|
||||
scripts are bundled. The default substring mode is safest for ordinary
|
||||
questions; use `glob` for wildcard paths, `sql-like` for `%` and `_` wildcards,
|
||||
and `regex` for precise structural matches. Results are bounded, so refine the
|
||||
pattern or path instead of treating a truncated result as exhaustive.
|
||||
|
||||
From a generated app directory, the lower-level readers remain available:
|
||||
|
||||
```bash
|
||||
pnpm action docs-search --query "actions"
|
||||
pnpm action docs-search --slug actions-defining
|
||||
pnpm action docs-search --list
|
||||
pnpm action source-search --query "defineAction"
|
||||
pnpm action source-search --path templates/plan/AGENTS.md
|
||||
pnpm action source-search --path templates/chat/actions/hello.ts
|
||||
pnpm action source-search --list
|
||||
```
|
||||
|
||||
If a search reports that the optional first-party template corpus is not
|
||||
installed, add it at the same version as Core:
|
||||
|
||||
```bash
|
||||
core_version=$(node -p 'require("./node_modules/@agent-native/core/package.json").version')
|
||||
pnpm add -D "@agent-native/core-corpus@$core_version"
|
||||
```
|
||||
|
||||
Use the unified tool for discovery, then the focused tools for full page or
|
||||
file reads.
|
||||
|
||||
If the action runner is unavailable, search the package directly:
|
||||
|
||||
```bash
|
||||
rg -n "actions|automations|a2a|sharing" node_modules/@agent-native/core/docs
|
||||
rg -n "defineAction|useActionQuery" node_modules/@agent-native/core-corpus/corpus
|
||||
```
|
||||
|
||||
Then read `node_modules/@agent-native/core/docs/AGENTS.md` or the matching file
|
||||
under `node_modules/@agent-native/core/docs/content/`. For template examples,
|
||||
read files under `node_modules/@agent-native/core-corpus/corpus/templates/`. The corpus
|
||||
carries templates only; for Core's own implementation read
|
||||
`node_modules/@agent-native/core/dist/` (compiled sources plus `.d.ts`).
|
||||
|
||||
Toolkit ships readable TypeScript under
|
||||
`node_modules/@agent-native/toolkit/src/`. Read
|
||||
`customizing-agent-native` before taking ownership of a shared component: inspect package
|
||||
source as a read-only reference, then configure, compose, or eject the smallest
|
||||
supported unit into app-owned source. Preserve public actions, application
|
||||
state, auth, and agent-chat runtime contracts. Never edit `node_modules` or
|
||||
deep-import its private source. Manual copying is only the fallback described by
|
||||
an unknown third-party package's add-style blueprint.
|
||||
|
||||
## Reuse Proven Patterns (rg + cp)
|
||||
|
||||
Version-matched installed source outranks web docs or memory: it is the exact
|
||||
code shipping with this app. `node_modules/@agent-native/core-corpus/corpus/templates/`
|
||||
holds source for every first-party template, not just the one this app started
|
||||
from, so a pattern from the mail template is fair game for a tasks app. Grep
|
||||
across it, then copy a whole file as a starting point instead of writing the
|
||||
pattern from scratch:
|
||||
|
||||
```bash
|
||||
# Find how other templates solved a similar problem
|
||||
rg -n "drag.*drop|reorder" node_modules/@agent-native/core-corpus/corpus/templates
|
||||
|
||||
# Grab a proven action file as a starting point, then adapt names/schema
|
||||
cp node_modules/@agent-native/core-corpus/corpus/templates/chat/actions/hello.ts \
|
||||
actions/greet.ts
|
||||
|
||||
# Read the framework's own implementation behind an API
|
||||
rg -n "defineAction" node_modules/@agent-native/core/dist/action.js
|
||||
```
|
||||
|
||||
Copying template-level app code (actions, components, skill files) is the
|
||||
expected reuse path — templates exist to be forked. This is different from
|
||||
copying `core`/`toolkit` **runtime internals**: for those, follow
|
||||
`customizing-agent-native`'s configure/compose/eject ladder instead of
|
||||
hand-duplicating framework logic.
|
||||
|
||||
## Useful Slugs
|
||||
|
||||
| Need | Slugs |
|
||||
| ------------------------------ | ----- |
|
||||
| Define and call actions | `actions-overview`, `actions-defining`, `actions-advanced` |
|
||||
| Typed client calls and data | `client-overview`, `client-entry-points`, `client-data` |
|
||||
| SQL, auth, access, sharing | `postgres`, `server-database`, `authentication`, `security`, `sharing` |
|
||||
| UI state visible to the agent | `context-awareness` |
|
||||
| Headless and chat-first apps | `pure-agent-apps`, `agent-surfaces`, `using-your-agent` |
|
||||
| Automations and schedules | `automations`, `recurring-jobs` |
|
||||
| Cross-app and external agents | `a2a-protocol`, `external-agents`, `mcp-protocol`, `mcp-apps` |
|
||||
| Skills and instructions | `skills-guide`, `writing-agent-instructions` |
|
||||
|
||||
## Don't
|
||||
|
||||
- Do not rely on memory for framework APIs when package docs are present.
|
||||
- Do not add custom REST wrappers for app data before reading
|
||||
`actions-overview` and `actions-defining`.
|
||||
- Do not add inline LLM calls before reading `using-your-agent` and
|
||||
`agent-surfaces`.
|
||||
- Do not copy framework runtime internals when a public API or narrow UI copy
|
||||
will do; read `customizing-agent-native` for the supported override ladder.
|
||||
|
||||
## Authoring visual docs blocks
|
||||
|
||||
Treat the shared `Diagram` block as a renderer, not as a reason to style every
|
||||
docs UI as a sketch. Use the hand-drawn font and Rough.js only for actual
|
||||
diagrams or wireframes that communicate structure, flow, or a design draft.
|
||||
For polished UI-like content - cards, logo walls, tables, controls, or product
|
||||
shells — set `renderMode="design"` (and usually `frame="hide"` when the block
|
||||
is the content itself). Design mode preserves normal docs typography and
|
||||
disables the Rough.js overlay. Keep `data-rough` only on elements intentionally
|
||||
sketched inside a real diagram.
|
||||
@@ -0,0 +1,314 @@
|
||||
---
|
||||
name: agent-native-toolkit
|
||||
description: >-
|
||||
Inventory and ownership rules for shared Agent-Native workspace UI. Use
|
||||
before building app chrome, settings, navigation, sharing, collaboration,
|
||||
setup, history, comments, chat rails, agent UX, or repeated workspace behavior.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Agent-Native Toolkit
|
||||
|
||||
Use this skill when deciding whether app chrome, settings, collaboration,
|
||||
sharing, navigation, organization, setup, history, comments, or agent UX should
|
||||
be built app-locally or moved into reusable framework/toolkit pieces.
|
||||
|
||||
## Core Rule
|
||||
|
||||
Apps own domain models, domain actions, and product-specific workflows. The
|
||||
framework and `@agent-native/toolkit` own repeated workspace behavior users
|
||||
expect to work the same everywhere.
|
||||
|
||||
Move behavior into shared toolkit primitives when it is:
|
||||
|
||||
- workspace-wide, such as settings, nav, search, org membership, or setup
|
||||
- agent-visible, such as context, actions, run progress, or proof-of-done
|
||||
- governed, such as secrets, permissions, sharing, audit, or billing
|
||||
- repeated by two or more apps
|
||||
- not tied to one domain model
|
||||
|
||||
Keep behavior app-local when the abstraction would hide important domain
|
||||
language or make a simple app-specific workflow harder to understand.
|
||||
|
||||
## Agent Surface Contract
|
||||
|
||||
When using the shared app shell, keep its two navigation surfaces distinct:
|
||||
|
||||
- The left rail owns domain destinations and chat history when the app has a
|
||||
full-page chat route. Do not label a domain workflow as `Chat` just because
|
||||
the app was scaffolded from the chat template.
|
||||
- Settings is not a rail item. It opens from the account menu (`OrgSwitcher`
|
||||
in the sidebar footer) and from ⌘, (Ctrl+, elsewhere), which `AppProviders`
|
||||
binds. Keep the `/settings` route; don't add a Settings entry to `items`,
|
||||
`secondaryItems`, or the footer.
|
||||
- The right `AgentSidebar` owns contextual agent work. Domain buttons that call
|
||||
`sendToAgentChat` should open it (`openSidebar: true`) so the user can see,
|
||||
steer, and review the agent without losing the page they were using.
|
||||
- Keep `/` or `/chat/*` as the full-page chat surface when the starter provides
|
||||
one. Put domain workflows on named routes and wire the shell's route checks,
|
||||
navigation labels, and handoffs to those routes together.
|
||||
- Use familiar message or neutral action icons for agent affordances. Never use
|
||||
sparkle, wand, magic, or robot icons as an AI label; the copy should carry the
|
||||
meaning.
|
||||
- Give the right rail a quiet visual boundary with a subtle surface shift,
|
||||
divider, or both. The domain page and AgentSidebar should not collapse into a
|
||||
single undifferentiated background.
|
||||
- Any button labeled as agent work must use `sendToAgentChat` with bounded
|
||||
context and `openSidebar: true`; local deterministic analysis should be
|
||||
labeled as local, preview, or analyze. For original/generated review, stack
|
||||
the source above the result by default and use side-by-side only for short,
|
||||
highly scannable content.
|
||||
- Deterministic implementation does not make an AI-shaped experience
|
||||
deterministic. If the user expects research, analysis, generation,
|
||||
recommendation, synthesis, visible progress, or steering, route the button
|
||||
to the AgentSidebar and let the agent call focused actions. Keep revisions in
|
||||
the same thread instead of adding a second freeform prompt box.
|
||||
- Standalone apps with `AgentSidebar` must use one AgentKit controller and
|
||||
transport. Core's `AssistantChat` export remains supported as an alias for
|
||||
`AgentKitAssistantChat`; use AgentKit slots and registries for custom message
|
||||
UI. Keep assistant-ui transcript/runtime imports inside the shared composer
|
||||
integration; when linked dependencies need Vite aliases, resolve one
|
||||
`@agent-native/agentkit` context and verify a real handoff.
|
||||
|
||||
Contextual agent UI is not a reason to expose every option at once. Start with
|
||||
the domain task's primary action, reveal review or configuration only when the
|
||||
current state needs it, and let the sidebar carry conversational depth.
|
||||
|
||||
When an app exposes context sources or integration shortcuts, show only
|
||||
capabilities available to that app and the current caller. Keep retrieving
|
||||
context distinct from asking the agent to invoke an integration, and recheck
|
||||
availability when the user submits. Do not infer agent-tool access from a
|
||||
connected messaging account or expose credential values. Link to shared
|
||||
Integrations settings when a required connection is missing.
|
||||
|
||||
## Visual Direction And Workspace Variety
|
||||
|
||||
Shared workspace behavior should be consistent without forcing every app into
|
||||
the same visual skin. Keep shell and component tokens semantic, then let each
|
||||
app record a visual direction in `DESIGN.md` before styling. Choose its palette
|
||||
and composition from the product context, and keep semantic states accessible.
|
||||
|
||||
Do not make warm beige plus terracotta the workspace fallback. Preserve a
|
||||
workspace-level brand when one exists; otherwise keep shared chrome neutral and
|
||||
allow app-owned accents to distinguish products while retaining accessible
|
||||
semantic states and the shared AgentSidebar contract.
|
||||
|
||||
## Discover Before Building
|
||||
|
||||
Before creating an app-local version of repeated workspace or agent UI:
|
||||
|
||||
1. Check the reusable kits below and the installed package documentation.
|
||||
2. Search installed public components and source with `docs-search` and
|
||||
`source-search`.
|
||||
3. Run `agent-native eject --list` to see the version-matched units published
|
||||
by the packages installed in this app.
|
||||
4. Read `customizing-agent-native` and configure, compose, or eject the
|
||||
smallest unit instead of recreating shared behavior from memory.
|
||||
|
||||
Use public package exports at runtime. Published source and ejection manifests
|
||||
are discovery and ownership-transfer mechanisms, not private runtime APIs.
|
||||
|
||||
## Design-System Boundary
|
||||
|
||||
For apps with a UI, keep an explicit design-system seam in
|
||||
`app/design-system.ts` using `defineDesignSystem` from
|
||||
`@agent-native/toolkit/design-system`, and supply it to `ToolkitProvider`. The
|
||||
semantic contract contains:
|
||||
|
||||
- nine leaf components: `ActionButton`, `IconButton`, `TextField`, `TextArea`,
|
||||
`Spinner`, `Skeleton`, `Status`, `Surface`, and `Avatar`
|
||||
- eight behavior components: `Tooltip`, `Menu`, `Popover`, `Dialog`, `Picker`,
|
||||
`Checkbox`, `Switch`, and `Tabs`
|
||||
|
||||
These are semantic contracts, not styling contracts. An adapter may use
|
||||
Tailwind/shadcn, MUI-style theme providers, React Aria, CSS modules, CSS-in-JS,
|
||||
or another React design system. Do not assume CVA, utility classes, or even a
|
||||
`className`; behavior adapters may supply their overlay and focus
|
||||
implementation wholesale while honoring portal, focus-restoration, keyboard,
|
||||
dismissal, ARIA, and z-index interoperability.
|
||||
|
||||
Pages, routes, and domain components import ordinary controls through the app's
|
||||
local adapter layer, usually `@/components/ui/*`. They must not import
|
||||
`@agent-native/toolkit/ui/*` directly. Toolkit feature exports are still the
|
||||
right home for shared workspace behavior; their presentation flows through the
|
||||
registered semantic components, feature controller, and product-level slots.
|
||||
|
||||
Import any design-system adapter explicitly; do not auto-detect it or load React
|
||||
components from JSON. Run a custom adapter against
|
||||
`@agent-native/toolkit/conformance` in the app's CI before adopting it.
|
||||
|
||||
## Settings Direction
|
||||
|
||||
Durable settings belong in Settings. The agent sidebar should not become a
|
||||
second settings app; it can show contextual quick controls and deep links.
|
||||
Settings has the same groups in every app, and page ids are stable URL segments
|
||||
(`/settings/<page>/<sub>`):
|
||||
|
||||
- Account: `profile`, `preferences`, `security`
|
||||
- Connections: `integrations` (`integrations/builder`), `api-keys`
|
||||
- Agent: `model`, `instructions`, `memory`, `skills`, `files`, `sub-agents`
|
||||
- Organization: `org`, `members`, `usage`, and for owners and admins `auth`,
|
||||
`apps`, `infra`, `audit`
|
||||
- The app's group: `app` (areas at `app/<id>`), `notifications`,
|
||||
`automations`, `channels` (`channels/<platform>`), `mcp`, `creative-context`
|
||||
- Footer: `labs`, `whats-new`
|
||||
|
||||
Link with `buildSettingsRoute(page, sub?, { anchor? })`; older tab and section
|
||||
ids continue to resolve through framework redirects. Account › Profile is the
|
||||
canonical profile surface (`get-user-profile`, `update-user-profile`); don't
|
||||
build an app-local profile page. Read the `toolkit-settings` documentation for
|
||||
the current route and page ids.
|
||||
|
||||
When adding a new API key, OAuth grant, provider connection, model selector, app
|
||||
preference, notification preference, or usage/billing surface, find the page
|
||||
that owns that kind of setting first: provider keys go through the one provider
|
||||
dialog on Model, other keys on API keys, channels on Channels, and app-only
|
||||
preferences in the app's group. Only add sidebar UI when it is needed in the
|
||||
moment of agent use.
|
||||
|
||||
### The app's group in Settings
|
||||
|
||||
Settings has a group named after the app.
|
||||
Core owns its pages: General, Notifications, Automations, Channels, MCP server,
|
||||
Creative context, plus Labs and What's new in the footer. A template supplies
|
||||
only its own content, through these `SettingsTabsPage` props:
|
||||
|
||||
- `generalGroups`: the app's own `SettingsGroup`s on its General page. Core puts
|
||||
Agent › Default model above them (owners and admins change it; the agent
|
||||
uses `manage-agent-engine` `set-app-default`) and This browser › Demo mode
|
||||
below. Until a template passes it, today's `general` shows there.
|
||||
- `appAreas`: `[{ id, label, content, visible?, keywords?, searchEntries? }]`,
|
||||
tabs on the General page routed `/settings/app/<id>`. Set `visible: false`
|
||||
while the lab behind an area is off. A tab with
|
||||
`settingsPlacement: "app-area"` in `extraTabs` works the same.
|
||||
- `notifications` (plus `notificationsSearchEntries`): the Notifications page
|
||||
shows only when this is passed.
|
||||
- `mcpAbout`: the MCP server page's about line, naming what an MCP host can do
|
||||
in this app.
|
||||
- Labs come from `labs`; What's new comes from `whatsNewMarkdown`, or from the
|
||||
`ChangelogSettingsCard` passed as `whatsNew`.
|
||||
- Any other `extraTabs` item becomes its own page in the app's group. To swap a
|
||||
core page for a variant, `registerSettingsPages([{ ...corePage, component }])`
|
||||
at module scope (Dispatch's Members keeps its app-role column this way). To
|
||||
add a group to one channel's page, `registerChannelSettingsExtensions`.
|
||||
|
||||
The route needs a `settings.$.tsx` splat next to `settings.tsx`, and the layout
|
||||
hides its own sidebar and header on Settings routes while the flag is on or
|
||||
loading (`isSettingsPathname`), because the shell brings its own.
|
||||
|
||||
Search entries per area: each `searchEntries` item's `hash` is the row's
|
||||
`SettingsRow` id, and a hit opens that area's tab and scrolls to the row. With
|
||||
the flag off, the same props render as today's tabs, so a migrated template
|
||||
works either way. Link with `buildSettingsRoute("app", "<area>")`, never a
|
||||
hand-written path.
|
||||
|
||||
Gate UI on a lab with `useLab(LAB_DEFINITION)` rather than `useLab(key)`: a
|
||||
definition reads as its `defaultEnabled` until the server answers, while a bare
|
||||
key reads as on.
|
||||
|
||||
## Integration Setup Preflight
|
||||
|
||||
Before building any setup, settings, credential, OAuth, or connection surface,
|
||||
search the workspace/provider connection catalog first. If the provider already
|
||||
has a reusable connection, use its catalog, app grant, and scoped credential
|
||||
resolver rather than registering a parallel secret. Only then classify fields
|
||||
that still need app-local setup by lifecycle and scope:
|
||||
|
||||
| Need | Default primitive |
|
||||
| --- | --- |
|
||||
| Deploy- or app-level configuration | Runtime configuration or deployment env vars |
|
||||
| Existing workspace/provider connection | Workspace-connection catalog/grant plus `resolveWorkspaceConnectionCredential(s)ForApp` |
|
||||
| App-local API/service key with no reusable connection | `registerRequiredSecret({ kind: "api-key" })` and the vault |
|
||||
| Authorization-code or refresh-token flow | `kind: "oauth"` with `@agent-native/core/oauth-tokens` |
|
||||
| Account, customer, or other non-secret identifiers | Scoped connection metadata or app data |
|
||||
| Provider-specific prerequisites, sequencing, or health | A thin app-local guide over the shared primitives |
|
||||
|
||||
Do not register every provider field as a generic secret, mark every field as
|
||||
required, or create a second credential-management surface. One logical
|
||||
connection should normally produce one onboarding outcome. A custom setup page
|
||||
is appropriate only when it adds domain-specific guidance or readiness checks;
|
||||
it should link to or call the shared settings, OAuth, and action surfaces rather
|
||||
than duplicating their storage or transport.
|
||||
|
||||
## Reusable Kits
|
||||
|
||||
- **Settings kit**: one searchable Settings page with Account, Connections,
|
||||
Agent, and Organization groups plus a group for the app's own settings. The
|
||||
index is built from page declarations; give every row a search entry whose
|
||||
anchor is its `SettingsRow` id so users find settings by name.
|
||||
- **Collaboration kit**: Yjs docs, presence, agent presence, live cursors,
|
||||
remote selections, recent edit highlights, real-time sync indicators, and
|
||||
undo/redo grouping.
|
||||
- **Sharing kit**: private/workspace/org/public-link access, invites, roles,
|
||||
expirations, agent-readable links, and resource registration.
|
||||
- **Navigation and command kit**: app shell, side nav, breadcrumbs, app switcher,
|
||||
command palette entries, recent resources, pinned resources, and global search.
|
||||
- **Organization kit**: folders, tags, favorites, archive, trash, ownership,
|
||||
membership, and common resource metadata.
|
||||
- **Setup and connections kit**: declarative setup requirements, model readiness,
|
||||
missing-secret states, OAuth grants, and provider connection health.
|
||||
- **Agent UX kit**: sidebar, composer, staged context, mentions, voice, human
|
||||
approval, generative UI, progress, and screen-state exposure.
|
||||
- **Custom block kit**: optional, sandboxed extensions for one-off behavior or
|
||||
views. Apps opt in; Core owns sandboxing, storage, and access checks, while
|
||||
Toolkit provides reusable adoption UI. Promote repeated or durable workflows
|
||||
to app-owned actions and UI.
|
||||
- **Chat history kit**: presentational chat lists and recent-chat rails belong
|
||||
in Toolkit; Core keeps thread persistence, agent execution, transport, and
|
||||
page-to-sidebar handoff. Apps provide routing, labels, and domain actions.
|
||||
- **Data grid kit**: provider-agnostic spreadsheet mechanics belong in
|
||||
`@agent-native/toolkit/data-grid`. Apps provide rows, typed columns, editor
|
||||
slots, selection and width state, persistence callbacks, and product-level
|
||||
row/body slots. Keep database models, access checks, grouping, drag/drop,
|
||||
and domain actions in the app adapter.
|
||||
- **Agent page kit**: the full-page Agent surface (`AgentTabsPage` from
|
||||
`@agent-native/toolkit/app/agent-page`) for agent resources, context
|
||||
snapshots, integrations, automations, settings, and MCP access. The page
|
||||
supports app-provided tabs. Use `agent-native-docs` to find current guidance
|
||||
before adding it.
|
||||
- **History and recovery kit**: audit log, activity feed, version history,
|
||||
checkpoints, undo, redo, restore, and proof-of-done.
|
||||
- **Comments and review kit**: anchored comments, pins, mentions, review
|
||||
requests, resolved threads, agent follow-up tasks, and notifications.
|
||||
- **Workflow and observability kit**: notifications, approvals, scheduled work,
|
||||
background runs, recurring jobs, traces, evals, feedback, and run timelines.
|
||||
|
||||
## Implementation Checklist
|
||||
|
||||
When adding or refactoring one of these areas:
|
||||
|
||||
1. Search app code and installed package documentation/source for an existing
|
||||
feature before building an app-local version.
|
||||
2. Configure the public feature through its data, action, controller, semantic
|
||||
component, and product-level render seams.
|
||||
3. Keep shared data provider-agnostic and scoped by auth/sharing rules.
|
||||
4. Expose the same capability to the UI and agent through actions or documented
|
||||
client helpers.
|
||||
5. Keep app-specific labels, routes, resource adapters, and settings panels in
|
||||
the app integration instead of forking shared UI for one app.
|
||||
6. Document app-specific configuration for the next contributor; use
|
||||
`agent-native-docs` when the installed package behavior is unclear.
|
||||
7. Prefer public props and slots; if they cannot express the need, use the
|
||||
smallest supported ejection unit. See `customizing-agent-native` for the
|
||||
configure → compose → eject → propose seam ladder.
|
||||
8. Keep one controller as the source of truth for the default and custom render
|
||||
paths. A custom design must not fork actions, analytics, async state, or
|
||||
accessibility behavior.
|
||||
9. If the app registers a custom adapter, verify it with the conformance kit,
|
||||
including focus, keyboard, dismissal, and portal behavior where components
|
||||
meet framework surfaces.
|
||||
|
||||
## Related Skills
|
||||
|
||||
Read these alongside this skill when the work touches the specific area:
|
||||
|
||||
- `sharing`
|
||||
- `secrets`
|
||||
- `adding-a-feature`
|
||||
- `agent-native-docs`
|
||||
|
||||
Use `agent-native-docs` to find installed-version guidance for navigation,
|
||||
screen context, collaboration, visual direction, and other capabilities not
|
||||
included in your scaffold's skill set.
|
||||
@@ -0,0 +1,271 @@
|
||||
---
|
||||
name: authentication
|
||||
description: >-
|
||||
How to wire this app's login experience through the framework's
|
||||
createAuthPlugin — branded loginHtml, public paths, and signup/logout UI.
|
||||
Read before creating or editing server/plugins/auth.ts, or before adding
|
||||
gated routes / a public marketing page.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Authentication
|
||||
|
||||
## Rule
|
||||
|
||||
If a user requests authentication or login or other similar terms, you should setup
|
||||
authentication in their app using this skill.
|
||||
|
||||
`server/plugins/auth.ts` exports `createAuthPlugin(options)` from
|
||||
`@agent-native/core/server` — that plugin is the app's auth. Do not hand-roll
|
||||
session cookies, a parallel login route, or a custom auth backend; configure
|
||||
the existing plugin instead.
|
||||
|
||||
## Choose the landing route before wiring auth
|
||||
|
||||
Before writing `loginHtml` or the sign-in journey, inspect `app/routes`, the
|
||||
app's navigation, and any existing `app.homePath` in
|
||||
`server/plugins/config.ts`. Preserve a valid existing `homePath`; otherwise
|
||||
pick the app's actual primary authenticated route (`/`, `/dashboard`,
|
||||
`/tasks`, ...) and persist it there — never assume `/home` unless that route
|
||||
really exists. `loginHtml` and the journey script below both need this value:
|
||||
a hardcoded `/` only works for apps whose real landing page is root.
|
||||
|
||||
## Branded login page
|
||||
|
||||
Pass `loginHtml: string` — a full HTML document that replaces the built-in
|
||||
login page and its framework chrome entirely, so it can carry this app's own
|
||||
layout, fonts, colors, and copy. Write it to match this app's actual look and
|
||||
feel (its palette, type, and voice) — do not ship the generic framework login
|
||||
page, and do not reuse another app's `loginHtml` verbatim without replacing
|
||||
its copy and styling first.
|
||||
|
||||
The login HTML must call the framework's own auth endpoints, so behavior
|
||||
matches the built-in page:
|
||||
|
||||
- `POST /_agent-native/auth/register { email, password, callbackURL? }` →
|
||||
`{ ok: true }` or `{ error }`. **`{ ok: true }` only means the account was
|
||||
created — register does NOT set a session cookie, so the visitor is still
|
||||
signed out at this point.**
|
||||
- `POST /_agent-native/auth/login { email, password }` → sets the session
|
||||
cookie and returns `{ ok: true }` or `{ error }`. This is the only
|
||||
endpoint that establishes a session.
|
||||
- `GET /_agent-native/google/auth-url?return=<path>` → `{ url }` to send the
|
||||
browser to for Google sign-in (only relevant when Google OAuth is
|
||||
configured)
|
||||
|
||||
**Sign-up must chain register → login before treating the user as signed
|
||||
in.** A custom `loginHtml` that posts to `/register` and redirects on that
|
||||
response's `{ ok: true }` alone creates the account but leaves the visitor
|
||||
logged out — they land back on the app, still unauthenticated, and have to
|
||||
log in separately right after signing up. The framework's own built-in login
|
||||
page (not the custom `loginHtml` you write) already does this chaining
|
||||
internally, which is why this bug only shows up once an app supplies its own
|
||||
`loginHtml`. Every sign-up handler must call login immediately after a
|
||||
successful register, with the same email/password, and only redirect once
|
||||
*that* call also returns `{ ok: true }`:
|
||||
|
||||
```js
|
||||
function submitSignup(email, password) {
|
||||
return postJson("/_agent-native/auth/register", email, password).then(
|
||||
function (data) {
|
||||
if (!(data && data.ok)) throw new Error(data && data.error);
|
||||
// Register succeeded but did not sign the visitor in — log in now.
|
||||
return postJson("/_agent-native/auth/login", email, password);
|
||||
},
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
On success there is no redirect to follow — reload the current URL (e.g.
|
||||
`location.reload()`) and it now passes the auth guard.
|
||||
|
||||
**This shortcut only works at the root path.** For any other gated route
|
||||
(e.g. `/toppings`), the client `<RequireSession>` gate does not serve
|
||||
`loginHtml` in place at that URL — it navigates the browser to
|
||||
`/sign-in?c=<opaque-continuation>` first, so `location.reload()` there just
|
||||
re-shows the login form forever instead of returning the visitor to
|
||||
`/toppings`. To resume the original page, decode that continuation with the
|
||||
framework's own helper instead of hand-rolling redirect logic:
|
||||
|
||||
```html
|
||||
<script>${signInJourneyInlineScript()}</script>
|
||||
<!-- import { signInJourneyInlineScript } from "@agent-native/core/shared" -->
|
||||
<script>
|
||||
// Second arg is the app home path — use the app's configured `app.homePath`
|
||||
// from server/plugins/config.ts (e.g. "/dashboard"), not a hardcoded "/".
|
||||
var journey = __anCreateSignInJourney("", "/dashboard");
|
||||
var resumeHref = journey.journeyForLocation(window.location).resumeHref;
|
||||
// On page load: if already authenticated, window.location.replace(resumeHref)
|
||||
// On login/signup success: window.location.replace(resumeHref) instead of reload()
|
||||
</script>
|
||||
```
|
||||
|
||||
`resumeHref` decodes the `c` continuation back to the originally-requested
|
||||
path, falling back to that configured `homePath` when there isn't one —
|
||||
hardcoding `/` here silently sends visitors to the wrong page on any app
|
||||
whose real landing route isn't root. Embed `signInJourneyInlineScript()` in
|
||||
every custom `loginHtml` that guards more than just `/`.
|
||||
|
||||
The login page must include:
|
||||
|
||||
- A **sign-in** form (email/password) posting to `/_agent-native/auth/login`.
|
||||
- A **sign-up** control — a visible "Sign up" / "Create account" affordance
|
||||
that posts to `/_agent-native/auth/register`. Never ship a login-only page
|
||||
with no way to register.
|
||||
|
||||
## Logging out
|
||||
|
||||
Once a user is signed in, the app's authenticated UI must include a **logout**
|
||||
control — do not leave users with no way to sign out. Use the framework's
|
||||
`signOut()` helper from `@agent-native/core/client` rather than posting to
|
||||
`/_agent-native/auth/logout` directly; it revokes the server session and only
|
||||
then navigates, avoiding a stale authenticated screen that renders against a
|
||||
dead cookie:
|
||||
|
||||
```ts
|
||||
import { signOut } from "@agent-native/core/client";
|
||||
|
||||
<button onClick={() => signOut()}>Log out</button>;
|
||||
```
|
||||
|
||||
## Separating a public marketing page from the private app
|
||||
|
||||
When an app needs a public landing surface in front of a gated authenticated
|
||||
app, keep the two on different routes rather than gating everything or exposing
|
||||
everything. The blank starter ships `app/routes/_index.tsx` as a placeholder
|
||||
canvas at `/`; a common split is:
|
||||
|
||||
- **Public marketing page** at `/` — listed in `workspaceAppPublicPaths` (and
|
||||
`PUBLIC_PATHS` in `app/root.tsx`, see below) so signed-out visitors can reach
|
||||
it.
|
||||
- **Private app** behind auth at a separate route (e.g. `/dashboard`), used as
|
||||
`app.homePath`.
|
||||
|
||||
For the public page, prefer the framework's ready-made shell
|
||||
`MarketingHome` from `@agent-native/toolkit/marketing` instead of hand-rolling
|
||||
a hero. It renders a branded landing shell with a hero, value props, and CTA
|
||||
buttons that can deep-link into sign-in and the app:
|
||||
|
||||
```tsx
|
||||
import { MarketingHome } from "@agent-native/toolkit/marketing";
|
||||
import { appPath } from "@agent-native/core/client/api-path";
|
||||
import { APP_TITLE } from "@/lib/app-config";
|
||||
|
||||
export default function MarketingHomeRoute() {
|
||||
return (
|
||||
<MarketingHome
|
||||
appName={APP_TITLE}
|
||||
tagline="One-line value proposition."
|
||||
description="Supporting product description."
|
||||
valueProps={["First benefit", "Second benefit", "Third benefit"]}
|
||||
primaryActionHref={appPath("/dashboard")} // the app's real homePath
|
||||
secondaryActionHref={appPath("/sign-in")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Point `primaryActionHref` at the app's actual authenticated landing route (the
|
||||
same value chosen for `app.homePath`), not a hardcoded `/home`. Pass
|
||||
`variant="auth"` with an `auth` node to compose the login form beside the
|
||||
marketing copy on a single public page. Only reach for `MarketingHome` when the
|
||||
app actually wants a public marketing surface — a purely private app needs no
|
||||
public landing page at all.
|
||||
|
||||
## Public paths
|
||||
|
||||
`workspaceAppPublicPaths: string[]` exempts page-route prefixes from the
|
||||
private-app auth gate, e.g. `["/"]` so a logged-out visitor hitting the
|
||||
marketing root gets the SPA (which renders the public landing page) instead of
|
||||
being redirected to sign-in. Every route not listed here — and every
|
||||
action/API — stays gated and requires a session. Set this explicitly for any
|
||||
route a signed-out visitor should be able to reach; use
|
||||
`workspaceAppProtectedPaths` for the inverse (an otherwise-public audience
|
||||
with specific pages, e.g. an admin screen, that must still require a session).
|
||||
|
||||
**This only configures the server.** There is a SEPARATE client-side gate in
|
||||
`app/root.tsx`: `<AppProviders queryClient={...}>` defaults its `isPublicPath`
|
||||
prop to `false`, which wraps the *entire* app in `<ClientOnly>` +
|
||||
`<RequireSession>` — every route, including ones already listed in
|
||||
`workspaceAppPublicPaths`. Setting `workspaceAppPublicPaths` alone does
|
||||
**not** make a page public; the two must be kept in sync by hand:
|
||||
|
||||
```tsx
|
||||
// app/root.tsx — must match workspaceAppPublicPaths in server/plugins/auth.ts
|
||||
const PUBLIC_PATHS = ["/", "/menu", "/order"];
|
||||
|
||||
export default function Root() {
|
||||
const location = useLocation();
|
||||
const isPublicPath = PUBLIC_PATHS.includes(location.pathname);
|
||||
return (
|
||||
<AppProviders queryClient={queryClient} isPublicPath={isPublicPath}>
|
||||
{/* ... */}
|
||||
</AppProviders>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Forgetting this makes every route require sign-in even when the server
|
||||
config says otherwise — the symptom is public marketing pages redirecting to
|
||||
login for no apparent reason. When adding or changing
|
||||
`workspaceAppPublicPaths`, always update this array in `app/root.tsx` too.
|
||||
|
||||
**Setting `isPublicPath={true}` streams real SSR markup for that route
|
||||
instead of a `<ClientOnly>` shell** (see `AppProviders`'s own doc comment).
|
||||
Most generated `root.tsx` files already mount router-dependent app-shell
|
||||
services next to `<Outlet />` — e.g. a `DbSyncSetup`-style component calling
|
||||
`useNavigationState` / `useLocation`, or anything else needing Router
|
||||
context. Those services were only ever exercised inside the `<ClientOnly>`
|
||||
branch before; once a route becomes public, they render during SSR too,
|
||||
where that context may not be established, and the whole page 500s with
|
||||
`Error: useLocation() may be used only in the context of a <Router>
|
||||
component`, repeated several times in the server log. Wrap any such service
|
||||
in `<ClientOnly>` explicitly so it keeps deferring to the client regardless
|
||||
of `isPublicPath`:
|
||||
|
||||
```tsx
|
||||
import { ClientOnly } from "@agent-native/core/client/ui";
|
||||
|
||||
<AppProviders queryClient={queryClient} isPublicPath={isPublicPath}>
|
||||
<ClientOnly>
|
||||
<DbSyncSetup />
|
||||
</ClientOnly>
|
||||
<AppLayout>
|
||||
<Outlet />
|
||||
</AppLayout>
|
||||
</AppProviders>;
|
||||
```
|
||||
|
||||
Do this once when first adding any public path, not per-route — the app
|
||||
shell services live above the routed `<Outlet />` regardless of which page
|
||||
is loading.
|
||||
|
||||
## Example
|
||||
|
||||
```ts
|
||||
import { createAuthPlugin } from "@agent-native/core/server";
|
||||
|
||||
export default createAuthPlugin({
|
||||
workspaceAppPublicPaths: ["/"],
|
||||
loginHtml: `<!doctype html>
|
||||
<html>
|
||||
<head>
|
||||
<title>Sign in — Acme</title>
|
||||
<style>/* match this app's palette, type, and voice */</style>
|
||||
</head>
|
||||
<body>
|
||||
<!-- sign-in form -> POST /_agent-native/auth/login -->
|
||||
<!-- sign-up form/toggle -> POST /_agent-native/auth/register,
|
||||
THEN POST /_agent-native/auth/login with the same credentials —
|
||||
register alone does not create a session. -->
|
||||
<script>
|
||||
// Sign-in: on { ok: true } from /login, location.reload()
|
||||
// Sign-up: on { ok: true } from /register, immediately call /login;
|
||||
// only reload once THAT also returns { ok: true }
|
||||
</script>
|
||||
</body>
|
||||
</html>`,
|
||||
});
|
||||
```
|
||||
@@ -0,0 +1,200 @@
|
||||
---
|
||||
name: build-an-app
|
||||
description: >-
|
||||
Fast end-to-end workflow for turning this starter into a working domain app
|
||||
from a short or vague request. Use when asked to build, make, create, or
|
||||
prototype an app, tool, tracker, dashboard, booking, inventory, or CRM
|
||||
system with Agent-Native. Read before the first edit.
|
||||
scope: both
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Build an App
|
||||
|
||||
Done means one useful domain workflow with a designed route, shared UI/agent
|
||||
actions, correct access, agent context, and a smoke run that proves its key
|
||||
rule. Finish a narrow slice before expanding it.
|
||||
|
||||
This skill edits source files. If this session cannot write files (a deployed
|
||||
app's runtime agent), say the change needs a code session and stop.
|
||||
|
||||
The four-area parity rule from `adding-a-feature` (UI, action, instructions,
|
||||
application state) applies to everything you add. This skill supplies the
|
||||
order and decisions; use the edit-point reference for the scaffold you have.
|
||||
|
||||
## 1. Orient
|
||||
|
||||
Read `AGENTS.md`, this skill, and only the files you will edit. Skip broad repo
|
||||
surveys, `README.md`, and `DESIGN.md`. Use the bundled docs/source commands in
|
||||
`AGENTS.md` only to answer a concrete API question; do not web-research
|
||||
framework APIs.
|
||||
|
||||
## 2. Decide
|
||||
|
||||
Choose these six things before writing code:
|
||||
|
||||
1. **Slice**: the one workflow that proves the app. For a booking app: create a
|
||||
booking, reject an overlap, cancel, weekly grid per room. Name what you are
|
||||
deferring (recurrence, notifications, roles, integrations) unless requested.
|
||||
2. **Who sees each table**: pick one row of the access table in
|
||||
`references/data-and-access.md`: private, team-visible, shared on invite, or a
|
||||
child that inherits its parent's access. Making a team resource private per
|
||||
user is the usual wrong turn. Everyone then sees an empty list, and no
|
||||
conflict check can see anyone else's rows. Give each table `owner_email`
|
||||
and/or `org_id`, directly or via `ownableColumns()`; `org_id` alone passes
|
||||
`[db-tool-scoping]`. Doctor checks the schema marker, not query authorization;
|
||||
never denylist or opt out `rooms` or `bookings`.
|
||||
3. **Invariants**: rules that must hold under concurrent requests (no overlap,
|
||||
stock never negative, unique slug). Enforce them in a write action inside a
|
||||
transaction or with a database constraint; the UI alone is insufficient.
|
||||
4. **Actions**: `list-<things>`, `create-<thing>`, a single `update-<thing>`
|
||||
patch per resource, and the domain verbs (`cancel-booking`). Fewer,
|
||||
orthogonal tools make the agent choose better.
|
||||
5. **Route**: give the domain its own route (for example, `/rooms`). Preserve
|
||||
existing routes and set `app.homePath` so sign-in lands on the domain when
|
||||
that is the requested home screen.
|
||||
6. **Agent context**: URL ids and filters (for example `roomId`, `week`) that
|
||||
belong in `navigation`.
|
||||
|
||||
## 3. Build: write everything, then verify once
|
||||
|
||||
In a generated app, read `package.json` at
|
||||
`["agent-native"].scaffold.template` and choose the matching reference:
|
||||
|
||||
- `builder-code-starter`: this starter has no Chat shell. Use `AGENTS.md`,
|
||||
`DEVELOPING.md`, and `drizzle/START_HERE.md` for edit points.
|
||||
- `default`: `references/edit-points-default.md`
|
||||
- workspace root: use `adding-workspace-apps` to create an app, then follow the
|
||||
new app's own `AGENTS.md` and scaffold reference.
|
||||
- another domain template: use its `AGENTS.md` and `adding-a-feature`; do not
|
||||
apply Chat or default shell instructions to it.
|
||||
|
||||
If metadata is absent, inspect the actual route, layout, plugin, and navigation
|
||||
files before choosing an edit point. Do not infer a shell from the app name.
|
||||
|
||||
Write the UI, actions, instructions, and state before running the verification
|
||||
steps below. Do not leave placeholder or comment-only screens.
|
||||
|
||||
`references/rooms-example.md` gives a booking slice to adapt. It was verified
|
||||
against the Chat starter; use the selected edit-point reference for the shell.
|
||||
Use `frontend-design` for a deliberate visual direction and finish the
|
||||
requested screens and interactions.
|
||||
|
||||
### Data
|
||||
|
||||
- Use PostgreSQL only, and keep migrations additive: new columns are nullable
|
||||
or have a default, and nothing is dropped or renamed. Never edit an applied
|
||||
entry; append a new named one.
|
||||
- Set `ownerEmail` from `ctx.userEmail` and `orgId` from `ctx.orgId` on inserts
|
||||
where those columns exist. Never rely on a development identity fallback.
|
||||
- Ids are text from `crypto.randomUUID()`.
|
||||
- Bound every list (a time range or `.limit()`), select only the columns it
|
||||
renders, and index the columns it filters and sorts on.
|
||||
- Store normalized UTC ISO timestamps; collect/display local times in the
|
||||
user's timezone. Validate offsets at the action boundary before parsing.
|
||||
|
||||
The access table, the concurrency pattern, and the security rules are in
|
||||
`references/data-and-access.md`.
|
||||
|
||||
### Actions
|
||||
|
||||
- `schema` is zod, with `.describe()` on every field stating its units and
|
||||
format (for example, "ISO 8601 date-time with offset").
|
||||
- Reads use `http: { method: "GET" }` and `readOnly: true`. Leave writes on the
|
||||
default POST so `useActionMutation` needs no `method`.
|
||||
- Reject with `fail(message, { errorCode, statusCode })` from
|
||||
`@agent-native/core/action`: 409 for a conflict, 404 for not found, 403 for
|
||||
forbidden. A returned `{ error }` is counted as success everywhere, and a
|
||||
bare `throw` reaches the browser as a generic 500.
|
||||
- Return plain objects that include the `id`. Keep LLM calls out of actions;
|
||||
AI-shaped work belongs in the agent chat.
|
||||
- When the request is batch-shaped ("add these 20"), write one action that
|
||||
takes an array and writes it in one transaction.
|
||||
|
||||
### UI
|
||||
|
||||
- Load and write data with `useActionQuery` and `useActionMutation` from
|
||||
`@agent-native/core/client/hooks`. No `fetch`, and no `/api/*` routes for app
|
||||
data. Those routes are only for uploads, webhooks, OAuth callbacks, and streaming.
|
||||
- While data loads, show a `Skeleton` in the shape of the final layout, not a
|
||||
spinner or "Loading…".
|
||||
- Writes should feel instant. In `onMutate`, update `["action", "<name>", params]`
|
||||
with `setQueryData`; in `onError`, roll back and show
|
||||
`toast.error(actionErrorMessage(error) ?? "<fallback>")`.
|
||||
- Import controls from `@/components/ui/*`. When one is missing (dialog,
|
||||
select, skeleton, alert-dialog), add a one-line re-export like `button.tsx`:
|
||||
`export * from "@agent-native/toolkit/ui/dialog";`.
|
||||
- Use Tabler icons only. Confirm with `AlertDialog`; never use `window.confirm`,
|
||||
`alert`, or `prompt`.
|
||||
- Don't add a page title that repeats the nav item, a subtitle under a title,
|
||||
or a stats strip. The data is the page. For visual direction, see `frontend-design`.
|
||||
- Follow the app's existing localization pattern for user-facing copy.
|
||||
- Add a pure `link` builder with `buildDeepLink()` to actions that create or
|
||||
list navigable resources; see `adding-a-feature` for the shape.
|
||||
|
||||
### Agent instructions
|
||||
|
||||
Append one section of about 1,500 characters at most to `AGENTS.md`. The
|
||||
runtime prompt cuts the file off at 6,000 characters. Cover:
|
||||
|
||||
- a one-line purpose with the routes
|
||||
- the invariants, and how to report a rejection
|
||||
- time and format conventions
|
||||
- the new `navigation` fields
|
||||
- an action table with unpadded cells
|
||||
|
||||
Keep the action table aligned with the scaffold's primary tool list when one
|
||||
exists; other actions should remain discoverable through `tool-search`. Leave
|
||||
unrelated AGENTS.md sections, README, and DESIGN.md as they are.
|
||||
|
||||
### Real-time
|
||||
|
||||
Agent writes need no wiring, because the chat run refreshes action queries
|
||||
after each tool. Add `useDbSync({ realtime: { reason } })` to a page only when
|
||||
other people change its data while it is open and the user must see the change
|
||||
before refreshing. A booking grid doesn't qualify: the server rejects bookings
|
||||
made from a stale view. See `real-time-sync`.
|
||||
|
||||
## 4. Verify, once, in this order
|
||||
|
||||
1. Start `pnpm exec agent-native dev` in the background, without `--open`, and
|
||||
wait for the ready URL. Startup regenerates `.generated/action-types.d.ts`
|
||||
and the actions registry, so a typecheck run before this is meaningless.
|
||||
On loopback, automatic dev sign-in works when the local database has no real
|
||||
users. If the sign-in page appears, use an existing local account or switch
|
||||
to a separate disposable local database; do not create accounts or set
|
||||
`AUTH_DISABLED`.
|
||||
2. Run `pnpm typecheck`, then `pnpm agent-native:doctor`. Plain `pnpm doctor`
|
||||
runs pnpm's own command and exits 0 without running Agent-Native Doctor. Fix
|
||||
every finding, then rerun only what failed.
|
||||
3. Check the agent path. Call a guarded write twice with the same input via
|
||||
`pnpm action <name> --key value`. The second call must fail with the expected
|
||||
message; read back the saved state through the matching list/get action.
|
||||
The CLI prints the failure message, not its structured `errorCode`, so also
|
||||
verify any code-specific behavior in the action contract or browser.
|
||||
4. Run one browser smoke on the domain route:
|
||||
- create a record
|
||||
- trigger the rejection: a toast appears and nothing is written
|
||||
- cancel or undo, repeat the previously rejected write, and confirm it
|
||||
succeeds
|
||||
|
||||
Inspect console and network failures. Fix errors from the new route or actions
|
||||
and identify existing scaffold messages separately. The only expected 4xx/5xx
|
||||
is the rejection being tested. Capture the finished workflow.
|
||||
5. Stop the dev server and close the tab.
|
||||
|
||||
Skip the production build, unrelated test suites, and README or DESIGN rewrites.
|
||||
To triage failures, see `references/verification.md`.
|
||||
|
||||
## 5. Report
|
||||
|
||||
State what works and the proof, what you deferred, and anything the user still
|
||||
has to do (for example, set `DATABASE_URL` before deploying). Never report a
|
||||
check you didn't run.
|
||||
|
||||
## Related
|
||||
|
||||
- `adding-a-feature`: the parity checklist for each later feature in this app.
|
||||
- `frontend-design`, `actions`, `sharing`, `real-time-sync`, and `security`:
|
||||
go deeper on one area when the references aren't enough.
|
||||
@@ -0,0 +1,91 @@
|
||||
# Data and access decisions
|
||||
|
||||
Use this when choosing who may see a row or when adding a schema/migration. A
|
||||
table's columns control framework SQL-tool scoping; app actions still need their
|
||||
own access checks for the people and records they return.
|
||||
|
||||
## Choose the row model
|
||||
|
||||
| Data | Columns | App action behavior |
|
||||
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Private to its creator (notes, drafts) | `owner_email` | Filter reads and writes by `ctx.userEmail`; set the owner on insert. |
|
||||
| Shareable resource (documents, dashboards) | `...ownableColumns()` plus `createSharesTable()` and `registerShareableResource()` | Use `accessFilter(table, shares)` for lists; use `assertAccess(type, id, role)` before reads/writes by id. Choose `private`, `org`, or `public` visibility deliberately. |
|
||||
| Team resource (rooms, products, customers) | Same shareable-resource columns | Use `visibility: "org"` when an org is active. Without an org, choose a deliberate private or no-create behavior. |
|
||||
| Child of a resource (bookings in a room, line items in an order) | `parent_id`, `owner_email`, and the parent's `org_id` when present | Check access to the parent in the action, then scope every child query by parent id and tenant. Apply child-specific rules in the write action. |
|
||||
| Organization-only rows (for example, membership records) | `org_id` only | Filter each app action by the active org; this does not support private ownership or per-user share grants. |
|
||||
| Public URL (published form or booking page) | Separate slug/token | Use a public route with its own validation and read policy; sharing visibility does not create anonymous URL access. |
|
||||
|
||||
Do not make a shared team resource private by adding only `owner_email`: that
|
||||
causes normal app actions and lists to hide coworkers' rows. Use
|
||||
`ownableColumns()` and the registered sharing helpers. Conversely, a room's
|
||||
bookings can inherit the room's access if the booking actions check the room
|
||||
before returning its rows.
|
||||
|
||||
### What agent SQL tools can see
|
||||
|
||||
`db-query`/`db-exec` create scoped views: an `owner_email` table is limited to
|
||||
the current owner. If the caller has an active org and the table also has
|
||||
`org_id`, rows are further limited to that org or a null org; without an active
|
||||
org, only the owner filter applies. An `org_id`-only table is limited to the
|
||||
current org and denied when there is no org. A table with neither column is
|
||||
denied. This is deliberately narrower than share grants, so use typed app
|
||||
actions to list team-shared records or children that inherit parent access.
|
||||
Do not add filters to raw SQL that duplicate these views.
|
||||
|
||||
The same row scoping does not replace action authorization. `accessFilter`
|
||||
resolves resource visibility/share grants; `assertAccess` checks one resource
|
||||
and role. The person who owns a row and a person with an org role are different
|
||||
access concepts.
|
||||
|
||||
## Schema and migrations
|
||||
|
||||
- PostgreSQL only. Define tables with `drizzle-orm/pg-core`; use
|
||||
`drizzle-orm` query operators. Import framework sharing helpers from
|
||||
`@agent-native/core/db/schema` only for ownable resources.
|
||||
- Chat has no database files or Drizzle migration config. Add
|
||||
`server/db/schema.ts`, `server/db/index.ts` with `createGetDb(schema)`, and
|
||||
`server/plugins/db.ts` with `runMigrations([...], { table })`. Follow the
|
||||
bundled Database docs. Other starters may document their own migration path.
|
||||
- Each migration entry needs a unique stable `{ version, name, sql }`. Never
|
||||
renumber or edit an applied entry; append a new additive migration.
|
||||
- Additive only: new columns are nullable or have a default, and nothing is
|
||||
dropped, renamed, or retyped. Keep SQL DDL aligned with the Drizzle schema.
|
||||
- Use text ids from `crypto.randomUUID()`. For sortable time text, normalize
|
||||
every input to UTC `Date#toISOString()` before storing or comparing it.
|
||||
- Use a `CHECK` or `UNIQUE` constraint for single-row rules such as valid
|
||||
status, `end > start`, or unique slugs.
|
||||
|
||||
`ownableColumns()` provides a development fallback owner value for framework
|
||||
compatibility. App actions must still set the authenticated `ownerEmail` from
|
||||
`ctx.userEmail`; never rely on that fallback to identify a real user.
|
||||
|
||||
## Invariants across rows
|
||||
|
||||
For rules such as no overlapping bookings or no overselling:
|
||||
|
||||
1. Validate and normalize input, then check the caller's access to the parent.
|
||||
2. Start `getDb().transaction(async (tx) => { ... })`.
|
||||
3. Lock the parent row with `tx.select(...).from(parent).where(...).for("update")`
|
||||
so concurrent writers for that parent serialize.
|
||||
4. Query for conflicts with `tx`; if one exists, use `fail()` with a stable
|
||||
`errorCode`, `statusCode: 409`, and a safe conflict identifier.
|
||||
5. Insert with `tx` and return the saved result. Do not open a separate query
|
||||
or call another action from inside the transaction callback.
|
||||
|
||||
The lock is effective only when every writer follows the same parent-lock
|
||||
protocol. Put the invariant in one action and use a database constraint when a
|
||||
single-row constraint can express it.
|
||||
|
||||
## Query and security defaults
|
||||
|
||||
- Give every action a zod schema. Bound every list with a time range, `.limit()`,
|
||||
or pagination; select only fields the caller needs; index hot filters/sorts.
|
||||
- Use parameterized Drizzle queries. Never concatenate user input into SQL.
|
||||
- Keep secrets in workspace connections or the vault, not source, SQL, seeds, or
|
||||
instructions. See the `secrets` skill before adding credentials.
|
||||
- Put file/image/audio/video/PDF payloads in configured blob storage and save
|
||||
only the returned URL or opaque id in SQL.
|
||||
- Add a custom `/api/*` route only for uploads, webhooks, OAuth callbacks,
|
||||
streaming, or public unauthenticated responses. Use actions for app data.
|
||||
- Keep startup limited to framework/plugin initialization and migrations;
|
||||
put imports, backfills, and provider calls behind an action or job.
|
||||
@@ -0,0 +1,23 @@
|
||||
# Default scaffold edit points
|
||||
|
||||
Use only when `package.json["agent-native"].scaffold.template` is `default`.
|
||||
This scaffold has a document/provider root and a sample `/home` route. It has
|
||||
no Chat sidebar, `Layout.tsx`, `server/plugins/agent-chat.ts`, or
|
||||
`INITIAL_TOOL_NAMES` list.
|
||||
|
||||
| File | Change |
|
||||
| ----------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `server/db/schema.ts` (new) | Define PostgreSQL tables with `drizzle-orm/pg-core`; use the shared schema helpers when access/sharing needs them |
|
||||
| `server/db/index.ts` (new) | Export `getDb = createGetDb(schema)` and register shareable resources as needed |
|
||||
| `server/plugins/db.ts` (new) | Add named, additive migrations with `runMigrations` |
|
||||
| `actions/<verb>-<noun>.ts` | One default-exported `defineAction` per file; the filename becomes the tool name |
|
||||
| `app/routes.ts` and `app/routes/<domain>.tsx` | `flatRoutes()` discovers route files; add the domain route and nested routes using the filename conventions already present |
|
||||
| `app/root.tsx` | Keep the document, providers, and `<Outlet />`; do not replace it with a domain shell |
|
||||
| `app/hooks/use-navigation-state.ts` | Extend the current path-derived navigation state only when the agent needs selected domain ids or filters beyond the current URL |
|
||||
| `server/plugins/agent-native-email-branding.ts` | Set `app.homePath` to the requested authenticated home route; the create command adds this plugin when it renames the scaffold |
|
||||
| `AGENTS.md` | Add a concise domain section with routes, invariants, state, and primary actions |
|
||||
|
||||
`app/routes/_index.tsx` is the sign-in landing route. `app/routes/home.tsx`
|
||||
is the authenticated sample page. Preserve both unless the requested workflow
|
||||
specifically replaces the home experience. The default template has no app
|
||||
navigation shell to extend; add only the navigation the product needs.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,57 @@
|
||||
# Verification: run order and triage
|
||||
|
||||
## Run order and why
|
||||
|
||||
1. **Dev server first.** Run `pnpm exec agent-native dev` in the background.
|
||||
`pnpm dev` also works but passes `--open` and launches a browser. Starting
|
||||
the server runs your migrations and regenerates `.generated/action-types.d.ts`
|
||||
and `.generated/actions-registry.ts`. Until it has run, `useActionQuery("new-action")`
|
||||
cannot type-check and the agent cannot see the new tools.
|
||||
2. **`pnpm typecheck`.** This runs React Router typegen, then `tsc --noEmit`.
|
||||
It does not regenerate action types; step 1 does that.
|
||||
3. **`pnpm agent-native:doctor`.** It scans `actions/` and `server/` for
|
||||
unscoped queries on ownable tables, credentials read from `process.env`,
|
||||
and similar mistakes. If the script is missing, run `pnpm exec agent-native doctor`.
|
||||
4. **Agent path.** Run `pnpm action <name> --key value`. When the dev server is
|
||||
running, the CLI forwards the call to it, so it shares the same database and
|
||||
dev identity. Call the guarded write twice with the same input and verify
|
||||
the second fails with the expected message; read the saved state through the
|
||||
matching list/get action. The CLI prints failure messages, not structured
|
||||
`errorCode` values, so verify code-specific behavior in the action contract
|
||||
or browser. Raw `db-query` views are scoped to the current owner or
|
||||
organization and do not include all records granted through app-level sharing.
|
||||
5. **One browser smoke** on the domain route: create, the rejected case, and
|
||||
undo or cancel. Inspect console and failed network requests. Fix errors from
|
||||
the new route or actions; identify existing scaffold messages separately.
|
||||
On loopback, automatic dev sign-in works while the database has no real
|
||||
users. If it shows a sign-in page, use an existing local account or a
|
||||
separate disposable local database; do not create accounts or set
|
||||
`AUTH_DISABLED`. Capture the finished workflow.
|
||||
6. **Clean up.** Close the tab and stop the dev server.
|
||||
|
||||
Run each check once. After a fix, rerun only the check that failed. Don't
|
||||
add a production build, new test files, or a second full pass.
|
||||
|
||||
## Triage
|
||||
|
||||
| Symptom | Usual cause | Fix |
|
||||
| ----------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `useActionQuery("x")` type error, or the action is unknown to the agent | `.generated/*` is stale | Make sure the dev server is running, save the action file, and rerun typecheck |
|
||||
| `relation "x" does not exist` | The table has no migration entry, or `server/plugins/db.ts` doesn't default-export `runMigrations(...)` | Add the entry and restart dev |
|
||||
| Migration ignored after an edit | You changed an entry that had already run | Revert the edit and append a new named entry |
|
||||
| 405 from an action | The HTTP method and the hook disagree | Reads use `http: { method: "GET" }` with `useActionQuery`; writes use the default POST with `useActionMutation` |
|
||||
| Toast says "Internal server error" | A bare `throw` | Throw with `fail(message, { statusCode })` |
|
||||
| A rejected write shows as a success | The action returned `{ error }` | Throw with `fail()` |
|
||||
| `view-screen` reports `view: "chat"` on a domain page | `viewForPath` has no case for the route | Add the case |
|
||||
| The agent asks "which one?" on a detail page | The id isn't in `navigation` | Add it in `getNavigationState` |
|
||||
| The agent doesn't reach for the new actions | They aren't in `INITIAL_TOOL_NAMES` or `AGENTS.md` | Add them to both |
|
||||
| Sign-in lands on `/home` | `homePath` is unset, or set somewhere other than a server plugin | Set it with `defineAppConfig` in `server/plugins/` and restart dev |
|
||||
| Sign-in page during the smoke | The DB has a real user, `AGENT_NATIVE_DISABLE_AUTO_DEV_ACCOUNT=1`, or the server isn't loopback development | Use an existing local account or a separate disposable local DB; verify loopback dev and clear the opt-out. Don't create accounts or set `AUTH_DISABLED` |
|
||||
| Doctor reports an unscoped query | An ownable table is read without an access helper in that statement or block | Put `accessFilter(...)` in the query's `where`, or call `assertAccess` first in the same block |
|
||||
| `Named export 'IconX' not found` | The icon name was guessed | Grep the exact name in `node_modules/@tabler/icons-react/dist/tabler-icons-react.d.ts` |
|
||||
| A `@/components/ui/<x>` import fails | The starter doesn't ship that primitive | Add `export * from "@agent-native/toolkit/ui/<x>";` |
|
||||
| The UI doesn't update after an agent write | The page uses raw `useQuery`, not the action hooks | Switch to `useActionQuery` |
|
||||
| Two quick writes both succeed despite a rule | The check runs outside a transaction or without a lock | Use the lock-then-check pattern in `data-and-access.md` |
|
||||
|
||||
If you couldn't run a step (no browser tool, port blocked), say so in the
|
||||
report. Don't claim it passed.
|
||||
@@ -0,0 +1,87 @@
|
||||
---
|
||||
name: client-side-routing
|
||||
description: >-
|
||||
How to add routes without remounting the app shell. Use when adding a new
|
||||
route, fixing agent sidebar reloads on navigation, or choosing between
|
||||
`root.tsx` layout and pathless `_app.tsx` layout patterns.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Client-Side Routing
|
||||
|
||||
## Rule
|
||||
|
||||
All templates are single-page apps using React Router. **Navigation must not remount the app shell.** The agent sidebar, document tree, and any other persistent chrome must survive route changes.
|
||||
|
||||
## Why
|
||||
|
||||
If the shell unmounts on every navigation, the agent chat reconnects/reloads, destroying in-progress work and hammering the backend.
|
||||
|
||||
## Hard Rule
|
||||
|
||||
**The app shell (AgentSidebar + any top-level navigation) must be mounted ONCE, above the `<Outlet />`.** Never wrap each page in its own `<AppLayout>` / `<Layout>`. React sees a different component at the outlet position on each nav and unmounts the entire subtree.
|
||||
|
||||
## Two Correct Patterns
|
||||
|
||||
### 1. All routes need the shell
|
||||
|
||||
Mount `<AppLayout>` in `root.tsx` around `<Outlet />`:
|
||||
|
||||
```tsx
|
||||
// app/root.tsx
|
||||
<AppLayout>
|
||||
<Outlet />
|
||||
</AppLayout>
|
||||
```
|
||||
|
||||
### 2. Mix of protected and public routes
|
||||
|
||||
Use a React Router **pathless layout route**:
|
||||
|
||||
```
|
||||
app/routes/
|
||||
_app.tsx # renders <AppLayout><Outlet /></AppLayout>
|
||||
_app._index.tsx # / → under AppLayout
|
||||
_app.settings.tsx # /settings → under AppLayout
|
||||
_app.team.tsx # /team → under AppLayout
|
||||
book.$slug.tsx # /book/:slug → no layout (public)
|
||||
f.$.tsx # /f/* → no layout (public form filler)
|
||||
```
|
||||
|
||||
The `_` prefix on `_app.tsx` makes it a **pathless** parent — it contributes the layout but no URL segment. Route files prefixed with `_app.` nest under it and share the layout instance across navigations.
|
||||
|
||||
## Anti-Pattern
|
||||
|
||||
```tsx
|
||||
// ❌ BAD — each route wraps its own Layout, causing full remount on every nav
|
||||
export default function Settings() {
|
||||
return (
|
||||
<AppLayout>
|
||||
<SettingsContent />
|
||||
</AppLayout>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
If a page needs per-route data (e.g. sidebar highlighting the active document), derive it inside the layout from `useParams()` / `useLocation()` — don't pass it as a prop through every route file.
|
||||
|
||||
## Chat-First Routes
|
||||
|
||||
If `/` is a full-page chat such as `AgentChatHome`, keep the app shell mounted
|
||||
around it when possible so `AgentSidebar` URL sync and route warmup stay active.
|
||||
If the chat route intentionally lives outside the shell, add a tiny app-owned
|
||||
prewarm for the routes agents commonly open from that chat. In local dev,
|
||||
React Router can update the address bar before a cold Vite route chunk commits,
|
||||
which makes navigation look broken even when the URL is correct.
|
||||
|
||||
## Adding a New Route
|
||||
|
||||
- **Pattern #1** (AppLayout in `root.tsx`): just render page content — nothing else.
|
||||
- **Pattern #2** (pathless `_app.tsx`): name the file `_app.<segment>.tsx` for authed routes, or bare `<segment>.tsx` for public routes.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `adding-a-feature` — The four-area checklist referencing route layout patterns
|
||||
- `context-awareness` — Navigation state written on every route change
|
||||
@@ -0,0 +1,282 @@
|
||||
---
|
||||
name: context-awareness
|
||||
description: >-
|
||||
How the agent knows what the user is looking at. Use when exposing UI state to
|
||||
the agent, implementing view-screen or navigate actions, wiring navigation
|
||||
state, or debugging agent context issues.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Context Awareness
|
||||
|
||||
## Rule
|
||||
|
||||
Apps can sync semantic navigation state when the route changes by using the
|
||||
shared route-state hook. When screen context is available, Core includes a
|
||||
`<current-screen>` snapshot in each agent turn, so the agent can get basic
|
||||
route context without first calling another tool. Apps can add concise
|
||||
visible-record details to that snapshot and expose selection in tab-scoped
|
||||
state.
|
||||
|
||||
## Why
|
||||
|
||||
Without context awareness, the agent is blind. It asks "which email?" when the user is staring at one. It cannot act on the current selection, cannot provide relevant suggestions, and cannot modify what the user sees. Context awareness is what makes the agent feel like a collaborator rather than a disconnected chatbot.
|
||||
|
||||
## The Core Patterns
|
||||
|
||||
### 1. Navigation State (`navigation` key)
|
||||
|
||||
Use the shared route-state hook to write a tab-scoped `navigation` key as the
|
||||
route changes. Include semantic screen state such as the view, open IDs, active
|
||||
tab, and focused object.
|
||||
|
||||
**UI side** — use `useAgentRouteState` in the app's route-state hook. The app
|
||||
can wrap it in an app-owned `useNavigationState` hook to map route paths to
|
||||
semantic views and consume the agent's `navigate` command.
|
||||
|
||||
```tsx
|
||||
// app/hooks/use-navigation-state.ts
|
||||
import { useAgentRouteState } from "@agent-native/core/client/navigation";
|
||||
import { TAB_ID } from "@/lib/tab-id";
|
||||
|
||||
export function useNavigationState() {
|
||||
useAgentRouteState({
|
||||
browserTabId: TAB_ID,
|
||||
requestSource: TAB_ID,
|
||||
getNavigationState: ({ pathname, searchParams }) => ({
|
||||
view:
|
||||
pathname === "/"
|
||||
? "home"
|
||||
: pathname === "/sign-in"
|
||||
? "sign-in"
|
||||
: pathname.replace(/^\/+/, ""),
|
||||
// Optional semantic alias. Raw query params are already exposed in
|
||||
// <current-url> and controllable with set-search-params.
|
||||
label: searchParams.get("label"),
|
||||
}),
|
||||
getCommandPath: (command: any) =>
|
||||
command.path ?? `/${command.view === "home" ? "home" : command.view}`,
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
The default scaffold uses `/home` for home and `/sign-in` for authentication;
|
||||
`/` redirects according to the configured home route. Map navigation to the
|
||||
app's actual routes and pass an explicit `path` for destinations that do not
|
||||
follow the `/<view>` convention.
|
||||
|
||||
`TAB_ID` comes from the framework's `getBrowserTabId()` (see the scaffolded `app/lib/tab-id.ts`; never redefine it). The server resolves tab-scoped `application_state` writes and page-local WebMCP calls (`X-Agent-Native-Browser-Tab`) against this same id, so a hand-rolled random id silently breaks selection sync for hidden and background tabs.
|
||||
|
||||
**Agent side** — read before acting:
|
||||
|
||||
```ts
|
||||
import { readAppState } from "@agent-native/core/application-state";
|
||||
|
||||
const navigation = await readAppState("navigation");
|
||||
// e.g. { view: "thread", threadId: "abc123", subject: "Re: Q3 Planning" }
|
||||
```
|
||||
|
||||
**What to include in navigation state:**
|
||||
|
||||
- `view` — the current page/section (e.g., "inbox", "form-builder", "dashboard")
|
||||
- Item IDs — the selected/open item (e.g., `threadId`, `formId`, `issueKey`)
|
||||
- Semantic aliases — label names, active tabs, focused row, or stable filter names the agent should reason about
|
||||
- Focused object IDs and active tabs that are not already represented by URL state
|
||||
|
||||
Keep text-selection ranges and excerpts in the tab-scoped `selection` key, not
|
||||
in `navigation`.
|
||||
|
||||
Raw URL query params are already synced by the framework to `__url__` and shown to the built-in agent as `<current-url>`. Keep shareable filters in URL state, then use `view-screen` to summarize important query params as `activeFilters` when helpful.
|
||||
|
||||
Keep `application_state` values small. Do not store pasted files, base64 images,
|
||||
recording chunks, screenshots, or other large blobs in navigation or app-state
|
||||
keys; upload them and store only a URL or storage handle.
|
||||
|
||||
### Selection state
|
||||
|
||||
For app-owned per-tab selection, suffix the key with `TAB_ID`; `requestSource`
|
||||
labels the write origin but does not scope the key. Keep the value to stable ids
|
||||
and a short label or excerpt, never the full document:
|
||||
|
||||
```ts
|
||||
import { writeClientAppState } from "@agent-native/core/client/hooks";
|
||||
import { TAB_ID } from "@/lib/tab-id";
|
||||
|
||||
await writeClientAppState(
|
||||
`selection:${TAB_ID}`,
|
||||
{ kind: "text", id: "artifact-123", text: "short excerpt" },
|
||||
{ requestSource: TAB_ID },
|
||||
);
|
||||
```
|
||||
|
||||
A server action can read that tab's value with
|
||||
`readAppStateForCurrentTab("selection")`. A `view-screen` result may include the
|
||||
selection and a specific next action when that helps the agent target an edit.
|
||||
|
||||
### 2. Current URL (`__url__` key)
|
||||
|
||||
`AgentPanel` automatically writes `__url__` with `{ pathname, search, hash, searchParams }`. The built-in agent sees it as a `<current-url>` block in every turn.
|
||||
|
||||
Use this for URL-reachable filters and search state. The agent can update it with the built-in `set-search-params` and `set-url-path` tools; do not duplicate the whole query string into `navigation`.
|
||||
|
||||
### Settings page (`settings-view` key)
|
||||
|
||||
The redesigned Settings shell writes tab-scoped `settings-view` = `{ page, sub, label }` (for example `{ page: "integrations", sub: "builder", label: "Connections › Integrations › Builder.io" }`) and deletes it when Settings closes. `<current-url>` shows it as a `settingsPage:` line, because a legacy or mounted pathname doesn't name the page the shell resolved. To send the user to a page, call the built-in `open-settings-page` tool with a page id (plus `sub` or `anchor`); it resolves old tab and section ids through the same redirect table as links. A template's own `navigate` action only needs a Settings branch for its app areas (`/settings/app/<area>`), built with `buildSettingsRoute`.
|
||||
|
||||
### 3. The `view-screen` Action
|
||||
|
||||
Use a `view-screen` action for a concise snapshot of visible record data the
|
||||
agent needs in addition to basic navigation. Read navigation and selection
|
||||
state, then query the relevant summaries through existing data helpers or
|
||||
Drizzle. Do not add REST wrappers just so `view-screen` can read app data.
|
||||
|
||||
```ts
|
||||
// actions/view-screen.ts
|
||||
import { defineAction } from "@agent-native/core/action";
|
||||
import {
|
||||
readAppState,
|
||||
readAppStateForCurrentTab,
|
||||
} from "@agent-native/core/application-state";
|
||||
import { z } from "zod";
|
||||
|
||||
export default defineAction({
|
||||
description: "Return a concise snapshot of the current screen.",
|
||||
schema: z.object({}),
|
||||
http: false,
|
||||
readOnly: true,
|
||||
run: async () => {
|
||||
const navigation = await readAppState("navigation");
|
||||
const screen: Record<string, unknown> = {};
|
||||
if (navigation) screen.navigation = navigation;
|
||||
|
||||
const selection = await readAppStateForCurrentTab("selection");
|
||||
if (selection) screen.selection = selection;
|
||||
|
||||
// Add concise visible-record summaries using the app's existing data helpers.
|
||||
return screen;
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Core builds the `<current-screen>` block for each agent turn by running the
|
||||
surfaced `view-screen` action. If no such action is available, it falls back to
|
||||
the current tab's `navigation` state. The scaffold action returns navigation;
|
||||
extend it with concise, relevant visible-record details when the app has them.
|
||||
The agent can use the injected snapshot directly and call `view-screen` again
|
||||
when it needs a fresh read after context has changed.
|
||||
|
||||
### 4. The `navigate` Action
|
||||
|
||||
The agent writes a one-shot `navigate` command to application-state. The UI reads it, performs the navigation, and deletes the entry.
|
||||
|
||||
**Agent side:**
|
||||
|
||||
```ts
|
||||
import { writeAppStateForCurrentTab } from "@agent-native/core/application-state";
|
||||
|
||||
// Navigate the user to a specific thread
|
||||
await writeAppStateForCurrentTab("navigate", {
|
||||
view: "inbox",
|
||||
path: "/inbox/abc123",
|
||||
threadId: "abc123",
|
||||
});
|
||||
```
|
||||
|
||||
**UI side** — use `useAgentRouteState`, shown above. It polls command keys,
|
||||
dedupes `_writeId`, deletes consumed commands, and applies app-local routing.
|
||||
|
||||
When a destination has a real URL, let the `navigate` command carry that local
|
||||
`path` (plus semantic fields when useful) and have the UI prefer `path` before
|
||||
falling back to semantic routing. Keep app navigation single-channel: do not
|
||||
also write `__set_url__` for the same navigation. `__set_url__` belongs to the
|
||||
framework URL tools (`set-url-path`, `set-search-params`) and URL-only filter
|
||||
changes. If a command can arrive while a chat stream is rendering, prefer
|
||||
`navigate(path, { replace: true, flushSync: true })` over a view-transition
|
||||
wrapper so the URL and visible route commit together.
|
||||
|
||||
Keep `path` router-local. A segment matching the app mount prefix remains part
|
||||
of the local route unless a matching `view` route or explicit `publicPath`
|
||||
identifies the mounted URL. Carry the mounted form separately in `publicPath`;
|
||||
never infer that `path` is mounted from its prefix alone.
|
||||
|
||||
## Jitter Prevention
|
||||
|
||||
Agent-side application-state writes are tagged with
|
||||
`requestSource: "agent"`. The UI uses `useDbSync({ ignoreSource: TAB_ID })` so
|
||||
it ignores its own writes while still picking up changes from agents, other
|
||||
tabs, and scripts.
|
||||
|
||||
Import `useAgentRouteState` and `useSemanticNavigationState` from
|
||||
`@agent-native/core/client/navigation`. Import
|
||||
`setClientAppState`, `writeClientAppState`, `readClientAppState`, and
|
||||
`deleteClientAppState` from `@agent-native/core/client/hooks`; avoid the
|
||||
deprecated `@agent-native/core/client` barrel. Pass `{ requestSource: TAB_ID }`
|
||||
on UI writes when pairing with `useDbSync({ ignoreSource: TAB_ID })`; pass
|
||||
`{ keepalive: true }` for short-lived writes such as selection cleanup during
|
||||
unload.
|
||||
|
||||
```ts
|
||||
// app/root.tsx
|
||||
import { TAB_ID } from "@/lib/tab-id";
|
||||
|
||||
useDbSync({
|
||||
queryClient,
|
||||
ignoreSource: TAB_ID, // ignore events from this tab's own writes
|
||||
});
|
||||
```
|
||||
|
||||
The UI sends its browser tab ID in `X-Agent-Native-Browser-Tab`; when a write
|
||||
has a `requestSource`, the client sends it in `X-Request-Source` and the server
|
||||
records it as the event origin. `useDbSync` ignores events whose origin matches
|
||||
`ignoreSource`, preventing a tab from refetching after its own state writes.
|
||||
|
||||
## Gold-Standard Example: Mail Template
|
||||
|
||||
The mail template demonstrates these patterns working together:
|
||||
|
||||
**Navigation state shape:**
|
||||
```json
|
||||
{ "view": "inbox", "threadId": "thread-123", "focusedEmailId": "msg-456", "label": "important" }
|
||||
```
|
||||
|
||||
**view-screen output:**
|
||||
- Reads navigation state
|
||||
- Reads `__url__` if URL query filters matter
|
||||
- Fetches email list matching current view/filter state
|
||||
- Fetches thread messages if a thread is open
|
||||
- Returns everything as a single JSON snapshot
|
||||
|
||||
**navigate command:**
|
||||
- `{ "view": "starred" }` — switch to starred view
|
||||
- `{ "view": "inbox", "threadId": "thread-123" }` — open a specific thread
|
||||
- For pure query-filter changes, use `set-search-params`
|
||||
|
||||
## Do
|
||||
|
||||
- Use the auto-injected `<current-screen>` block for basic context — call `view-screen` only when you need richer data
|
||||
- Include semantic route state in the `navigation` key (view, item IDs, active tab, focused row)
|
||||
- Keep shareable filters in URL query params so `<current-url>` and `set-search-params` work
|
||||
- Add concise visible-record details to `view-screen` for views where the agent needs them beyond the injected navigation context
|
||||
- Use `useAgentRouteState` or `useSemanticNavigationState` for UI-side navigation sync and command consumption
|
||||
- Use the one-shot `navigate` command pattern for app navigation; include a same-origin `path` when the target URL is known
|
||||
- Tag agent writes with `requestSource: "agent"` (the script helpers do this automatically)
|
||||
|
||||
## Don't
|
||||
|
||||
- Don't assume the user is on a specific page — use `<current-screen>` or read
|
||||
navigation state when context is missing or stale
|
||||
- Don't hardcode navigation paths in scripts — read the current state and branch
|
||||
- Don't write to the `navigation` key from the agent — it belongs to the UI. Use `navigate` instead.
|
||||
- Don't write both `navigate` and `__set_url__` for one app navigation; competing consumers can make the browser URL change before React Router commits the page.
|
||||
- Don't ignore the `<current-screen>` block — it tells you where the user is
|
||||
- Don't duplicate whole URL query strings into `navigation` when `<current-url>` already exposes them
|
||||
- Don't store fetched data in navigation state — it holds IDs and semantic UI state only. The `view-screen` script fetches the actual data.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- **adding-a-feature** — Context awareness is area 4 of the four-area checklist
|
||||
- **real-time-sync** — How `useDbSync` delivers app-state changes to the UI
|
||||
- **actions** — How to create the `view-screen` and `navigate` actions
|
||||
- **storing-data** — Application-state is one of the core SQL stores
|
||||
@@ -0,0 +1,219 @@
|
||||
---
|
||||
name: customizing-agent-native
|
||||
description: >-
|
||||
How to configure, compose, or eject Agent-Native features into app-owned
|
||||
code. Use when overriding shared components or integrations, customizing a
|
||||
template, adding UI to chat or headless apps, or inspecting package source.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Customizing Agent-Native
|
||||
|
||||
## Rule
|
||||
|
||||
Start with the app's registered design system and local UI adapters, then use
|
||||
the public feature's props, semantic components, controller, product slots,
|
||||
and callbacks. If those seams are not enough, use the eject CLI to transfer
|
||||
the smallest supported feature into the app and make that copy app-owned.
|
||||
Never edit `node_modules`, deep-import a private source file at runtime, or
|
||||
patch an `@agent-native/*` package.
|
||||
|
||||
Use this order:
|
||||
|
||||
1. Set brand tokens with the build-time theme configuration when tokens are
|
||||
enough.
|
||||
2. Register company components in `app/design-system.ts` with
|
||||
`defineDesignSystem`, then pass that definition to `ToolkitProvider`.
|
||||
3. Configure a public feature through its semantic components, headless
|
||||
controller, and product-level render slots.
|
||||
4. Compose app primitives behind the app's local UI adapter layer.
|
||||
5. Eject the smallest feature into app-owned source.
|
||||
6. Propose a new Toolkit seam when the same override is useful in two apps.
|
||||
|
||||
Ejection is for intentional product customization, not for hiding an upgrade
|
||||
failure or replacing Core runtime behavior.
|
||||
|
||||
## Use A Company Design System
|
||||
|
||||
Keep the explicit, typed registration seam in `app/design-system.ts`:
|
||||
|
||||
```tsx
|
||||
import { defineDesignSystem } from "@agent-native/toolkit/design-system";
|
||||
import {
|
||||
AcmeActionButtonAdapter,
|
||||
AcmeDialogAdapter,
|
||||
} from "./design-system/acme-adapter";
|
||||
|
||||
export const designSystem = defineDesignSystem({
|
||||
name: "Acme",
|
||||
components: {
|
||||
ActionButton: AcmeActionButtonAdapter,
|
||||
Dialog: AcmeDialogAdapter,
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
Adapters translate the semantic Toolkit contract into company component props.
|
||||
They are ordinary React components and may use MUI-style providers, React Aria,
|
||||
CSS modules, CSS-in-JS, or another styling runtime. `className` and `style` are
|
||||
optional interoperability hooks, not Tailwind or CVA requirements.
|
||||
|
||||
The contract has nine leaf components (`ActionButton`, `IconButton`,
|
||||
`TextField`, `TextArea`, `Spinner`, `Skeleton`, `Status`, `Surface`, `Avatar`)
|
||||
and eight behavior components (`Tooltip`, `Menu`, `Popover`, `Dialog`,
|
||||
`Picker`, `Checkbox`, `Switch`, `Tabs`). `Picker` covers select and combobox
|
||||
behavior, not date picking. Behavior adapters own their portal, focus,
|
||||
keyboard, dismissal, and stacking implementation while honoring the semantic
|
||||
props and `portalContainer` interop contract.
|
||||
|
||||
App product code imports standard controls from its local adapter path, usually
|
||||
`@/components/ui/*`. Do not import `@agent-native/toolkit/ui/*` directly from
|
||||
pages, routes, or domain components. That bypasses the app seam and makes a
|
||||
future design-system replacement incomplete. Toolkit feature packages remain
|
||||
valid imports; configure their presentation through the registered semantic
|
||||
components, controller, and product slots.
|
||||
|
||||
Run the published conformance kit against a complete adapter in its own CI:
|
||||
|
||||
```tsx
|
||||
import { assertDesignSystemConformance } from "@agent-native/toolkit/conformance";
|
||||
import { DESIGN_SYSTEM_CONTRACT_VERSION } from "@agent-native/toolkit/design-system";
|
||||
|
||||
await assertDesignSystemConformance({
|
||||
adapterName: "Acme",
|
||||
components,
|
||||
contractVersion: DESIGN_SYSTEM_CONTRACT_VERSION,
|
||||
});
|
||||
```
|
||||
|
||||
## Customize A Shared Feature
|
||||
|
||||
Prefer feature-level headless controllers over rebuilding individual widgets.
|
||||
One controller must power both the Toolkit default view and every custom render
|
||||
path so behavior, actions, analytics, accessibility state, and error handling
|
||||
cannot drift. Use a product-level render slot to replace the view while keeping
|
||||
that controller. Eject only when the controller and slots cannot express the
|
||||
required product behavior.
|
||||
|
||||
## Eject A Feature
|
||||
|
||||
Discover and inspect the ejection units published by installed first-party
|
||||
packages before changing source:
|
||||
|
||||
```bash
|
||||
agent-native eject --list
|
||||
agent-native eject inspect <unit>
|
||||
agent-native eject <unit> --app <app>
|
||||
agent-native eject <unit> --app <app> --apply
|
||||
```
|
||||
|
||||
The command is dry-run by default. It prints the file closure, consumer import
|
||||
rewrites, protected package contracts, and verification commands before
|
||||
writing. `--apply` copies the package-version-matched source into the app and
|
||||
rewrites only imports covered by the unit manifest.
|
||||
|
||||
If a framework feature has no ejection unit, follow its documented
|
||||
configuration, adapter, or extension seam; do not invent a manual package-copy
|
||||
recipe. For an unknown third-party package, use the emitted add-style blueprint
|
||||
as a starting point. Protected runtime behavior is never copied.
|
||||
|
||||
Applied ejections are recorded in the committed
|
||||
`agent-native.ejections.json`, including package version, manifest digest,
|
||||
target hashes, and import rewrites. Use the recorded state to review drift or
|
||||
undo an unchanged ejection:
|
||||
|
||||
```bash
|
||||
agent-native eject diff <unit> --app <app>
|
||||
agent-native eject restore <unit> --app <app>
|
||||
agent-native eject restore <unit> --app <app> --apply
|
||||
```
|
||||
|
||||
Restore is hash-gated. It refuses to remove locally edited files or reverse
|
||||
changed imports and prints their diff instead. Keep an edited ejection as
|
||||
app-owned code, or reconcile those edits before restoring it.
|
||||
|
||||
## Find The Installed Implementation
|
||||
|
||||
Use the source that matches the installed package version:
|
||||
|
||||
The template corpus is optional. If source-search reports it is unavailable,
|
||||
follow `agent-native-docs` to install the matching package before using the
|
||||
direct corpus path below.
|
||||
|
||||
```bash
|
||||
pnpm action docs-search --query "<component or feature>"
|
||||
pnpm action source-search --query "<component or symbol>"
|
||||
rg -n "<component or symbol>" node_modules/@agent-native/toolkit/src
|
||||
rg -n "<component or symbol>" node_modules/@agent-native/core-corpus/corpus
|
||||
```
|
||||
|
||||
- Toolkit publishes readable TypeScript under
|
||||
`node_modules/@agent-native/toolkit/src/` for selective UI adoption.
|
||||
- First-party template source lives under
|
||||
`node_modules/@agent-native/core-corpus/corpus/templates/`; Core's own implementation
|
||||
lives under `node_modules/@agent-native/core/dist/`.
|
||||
- Treat those trees as read-only references. Prefer `agent-native eject` so the
|
||||
package manifest selects the complete source closure and rewrites imports.
|
||||
Manual inspection is still useful for deciding whether to configure,
|
||||
compose, eject, or propose a shared seam.
|
||||
|
||||
Do not manually guess at sibling dependencies. The ejection manifest owns the
|
||||
required file closure and keeps protected contracts on public package imports.
|
||||
|
||||
## Preserve The Agent-Native Contract
|
||||
|
||||
UI ownership may change; product contracts should not:
|
||||
|
||||
- Keep app operations in `defineAction` actions and call them through
|
||||
`useActionQuery`, `useActionMutation`, or another named client helper.
|
||||
- Keep navigation, selection, and focused-object state visible through the
|
||||
existing application-state keys.
|
||||
- Keep AI work in the shared agent chat instead of adding direct LLM calls.
|
||||
- Keep auth, access checks, persistence, chat transport, and agent execution in
|
||||
Core. Do not copy those runtimes into the app.
|
||||
- Keep local adapters narrow so package upgrades still improve every surface
|
||||
the app has not intentionally taken ownership of.
|
||||
- Keep page, route, and domain code on local UI adapter imports. Never reach
|
||||
around the registered design system with direct Toolkit UI primitive imports.
|
||||
|
||||
## App Shapes
|
||||
|
||||
- **Template app:** begin with `app/design-system.ts`, its local UI adapters,
|
||||
and domain UI. Use Toolkit features for repeated workspace behavior; eject
|
||||
only the unit being customized.
|
||||
- **Chat app:** keep `AgentChatSurface`, thread state, and chat transport in
|
||||
Core. Compose or eject Toolkit presentation such as chat-history UI around it.
|
||||
- **Headless app:** stay action-first while no UI is needed. When adding a UI,
|
||||
use the Chat template as the on-ramp or add Toolkit components without
|
||||
replacing the existing actions.
|
||||
- **Workspace:** keep one-app overrides in that app. Promote a local component
|
||||
to a shared workspace package when multiple workspace apps use it.
|
||||
|
||||
## After Ejecting
|
||||
|
||||
- Commit `agent-native.ejections.json` with the app-owned files and rewrites.
|
||||
- Remove unused dependencies and imports from the ejected files.
|
||||
- Keep visible text in the app's localization catalogs.
|
||||
- Run the manifest verification commands plus the app's formatter, typecheck,
|
||||
and focused tests.
|
||||
- Re-check the installed source during future package upgrades; the app-owned
|
||||
ejection does not receive upstream fixes automatically. Use `eject diff` to
|
||||
distinguish recorded output from subsequent local edits.
|
||||
|
||||
## Don't
|
||||
|
||||
- Don't edit or import from `node_modules/@agent-native/*/src` at runtime.
|
||||
- Don't add `pnpm.overrides`, patches, or resolutions for Agent-Native packages.
|
||||
- Don't copy Core auth, DB, action, agent-loop, or transport internals.
|
||||
- Don't manually copy a package feature when no supported ejection is published;
|
||||
use its documented configuration, adapter, or extension seam.
|
||||
- Don't eject a full package when a prop, slot, wrapper, or smaller unit works.
|
||||
- Don't fork feature state into a custom view; consume the feature's controller.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `agent-native-docs` — version-matched docs, source lookup, and package upgrades
|
||||
- `agent-native-toolkit` — shared-vs-app-owned architecture boundary
|
||||
- `adding-a-feature` — UI/action/instructions/application-state parity
|
||||
@@ -0,0 +1,62 @@
|
||||
---
|
||||
name: delegate-to-agent
|
||||
description: >-
|
||||
Route user-facing AI work through the app's agent chat. Use when adding an
|
||||
AI-powered button, workflow, research task, generation flow, or follow-up.
|
||||
scope: dev
|
||||
---
|
||||
|
||||
# Delegate AI Work to Agent Chat
|
||||
|
||||
## Rule
|
||||
|
||||
Use the agent chat for work that needs AI reasoning, research, generation, or
|
||||
multi-step decisions. Keep app actions deterministic; let the agent orchestrate
|
||||
them so the user can see and steer the work.
|
||||
|
||||
## Start a visible agent turn
|
||||
|
||||
Call `sendToAgentChat()` from the UI and open the AgentSidebar for user-initiated
|
||||
work:
|
||||
|
||||
```ts
|
||||
import { sendToAgentChat } from "@agent-native/core/client/agent-chat";
|
||||
|
||||
sendToAgentChat({
|
||||
message: userRequest,
|
||||
context: JSON.stringify({ documentId }),
|
||||
submit: true,
|
||||
openSidebar: true,
|
||||
});
|
||||
```
|
||||
|
||||
Keep the user's request in `message`. Put only concise supporting context—such
|
||||
as a selected record id, current view, or bounded excerpt—in `context`. Use
|
||||
attachments or image fields for files and visuals; do not serialize full
|
||||
records or credentials into a prompt. The agent should read private or large
|
||||
data through the app's authorized actions.
|
||||
|
||||
Use `submit: true` when a clear user action already states the intent. Use
|
||||
`submit: false` to open the composer with a prefill when the user should review
|
||||
or complete the request. Do not auto-submit a generic generation prompt before
|
||||
the user has supplied the request.
|
||||
|
||||
Reserve `background: true` with `openSidebar: false` for work the product
|
||||
intentionally runs silently, such as a system-initiated task. A button that
|
||||
asks the user to do AI work should open the sidebar.
|
||||
|
||||
## Keep the boundary clear
|
||||
|
||||
- Use focused actions for provider reads, validation, deterministic
|
||||
transformations, database writes, and other explicit operations.
|
||||
- Let the agent choose and sequence those actions for AI-shaped workflows.
|
||||
- Keep a user's freeform prompt in the AgentSidebar composer. Use controls for
|
||||
structured parameters; do not add a second prompt or follow-up textbox.
|
||||
- Do not call model-provider SDKs, `completeText()`, or AI SDK generation
|
||||
functions from app UI, actions, or server helpers. Do not make an action a
|
||||
hidden second agent.
|
||||
|
||||
## Related skills
|
||||
|
||||
- `actions` — define deterministic operations shared by the UI and agent.
|
||||
- `context-awareness` — provide navigation and selected-record context.
|
||||
@@ -0,0 +1,109 @@
|
||||
---
|
||||
name: frontend-design
|
||||
description: >-
|
||||
Product-specific interface design for an Agent-Native app. Use when creating
|
||||
or changing any user-facing UI, including screenshot feedback, copy or
|
||||
density cleanup, settings, controls, or a visual redesign.
|
||||
scope: both
|
||||
---
|
||||
|
||||
# Frontend Design
|
||||
|
||||
Design around the user's task and the app's existing visual language. A
|
||||
distinctive interface comes from a clear product point of view, not extra
|
||||
decoration. Keep implementation accessible and responsive.
|
||||
|
||||
## Choose a direction
|
||||
|
||||
Before a substantial new surface or redesign, decide who is using it, what
|
||||
they came to do, and what they should see or do next. Pick a visual direction
|
||||
that fits the product's brand and domain. For routine changes, inspect and
|
||||
follow the existing components, type, color tokens, and spacing.
|
||||
|
||||
If a screen has two unrelated primary jobs, split the workflows or states.
|
||||
Do not solve an unclear structure by adding more cards, tabs, controls, or
|
||||
explanatory copy.
|
||||
|
||||
## Keep the starting view focused
|
||||
|
||||
The first view should show where the user is, the current work or state, and
|
||||
the input or decision needed now. Make one action clear. Defer rare, advanced,
|
||||
diagnostic, destructive, and historical controls to a relevant menu or
|
||||
disclosure.
|
||||
|
||||
Every visible element should orient the user, show useful content or state,
|
||||
collect required input, or enable the next action. If it has no job, remove it
|
||||
or disclose it. Density should come from useful data, not extra chrome.
|
||||
|
||||
Do not add a page title that repeats the selected navigation item, a subtitle
|
||||
or eyebrow under a title, a count strip over visible content, an About section
|
||||
in settings, or helper copy that repeats a label unless the user asks for it.
|
||||
A card, panel, tab, or settings group gets a title or a description, not both.
|
||||
Use tooltips or progressive disclosure for explanations that are not needed to
|
||||
make the current decision. User-authored descriptions are content: render them
|
||||
when present and render nothing when empty.
|
||||
|
||||
For sequential setup, show one decision at a time with clear progress and
|
||||
sensible defaults. Use the smallest surface that fits the task: an inline row
|
||||
or dialog for a small edit, a focused flow for multi-step work.
|
||||
|
||||
## Use the app's design system
|
||||
|
||||
This starter ships **no brand system** — the neutral, 0%-saturation tokens in
|
||||
`app/global.css` are a placeholder, not a design to preserve. Every app must
|
||||
look impressive on first load even when the build prompt gives no design
|
||||
direction: commit to one deliberate visual world, set a product-fitting accent
|
||||
family in the light and dark tokens, and establish a clear type hierarchy,
|
||||
spacing rhythm, and one signature detail. Do not ship the gray placeholder and
|
||||
do not average toward generic SaaS. If an app already has a real brand, preserve
|
||||
it. Keep shared behavior and semantic token names consistent; palette, density,
|
||||
composition, type contrast, and shape language are yours to define. Prefer
|
||||
semantic color tokens over raw palette colors, and avoid generic gradients,
|
||||
glass effects, decorative blobs, and hero sections without a product purpose.
|
||||
|
||||
Use the app's local UI adapter for standard controls. In an Agent-Native app,
|
||||
check the configured design system and toolkit provider before changing how
|
||||
shared controls look. Read `shadcn-ui` when implementing or composing a
|
||||
standard control; keep product-specific layout and visual decisions here.
|
||||
|
||||
Use real or generated imagery when it helps the user understand the subject.
|
||||
Do not add decorative assets solely to fill empty space.
|
||||
|
||||
## Coordinate the UI with the agent
|
||||
|
||||
Keep repeatable, direct manipulation in the domain UI and use the agent for
|
||||
work that benefits from judgment, exploration, or conversation. If the app has
|
||||
a contextual agent sidebar, reuse it for in-context help and keep the user on
|
||||
the current work surface. Do not add a second freeform prompt box. A control
|
||||
that promises agent help should hand off the relevant context; label local,
|
||||
deterministic behavior plainly.
|
||||
|
||||
## Interaction Responsiveness
|
||||
|
||||
Show feedback as soon as the user acts, aiming for 100 ms. When work cannot
|
||||
finish immediately, acknowledge it before a network round-trip and show a
|
||||
focused pending state within 400 ms. Use optimistic updates when safe, then
|
||||
confirm or roll back on failure. Keep long work visibly progressing and offer
|
||||
a way to stop when the operation supports cancellation.
|
||||
|
||||
## Make interactions clear and accessible
|
||||
|
||||
Support keyboard use, visible focus, accessible names, readable contrast, and
|
||||
clear validation and recovery. Dialog and menu controls should use the app's
|
||||
existing accessible primitives rather than hand-built click-outside behavior.
|
||||
Never use browser `alert`, `confirm`, or `prompt` dialogs.
|
||||
|
||||
Use motion to clarify a state change. Prefer short transitions on opacity or
|
||||
transform, respect reduced-motion preferences, and avoid delaying content with
|
||||
decorative entrances or long animations.
|
||||
|
||||
Fit the content to narrow screens as well as desktop. Text and controls should
|
||||
not overflow their containers; fixed-format editors, boards, and toolbars
|
||||
should keep stable dimensions.
|
||||
|
||||
## Review the result
|
||||
|
||||
Check that the main job and next action are obvious. Look at the default,
|
||||
loading, empty, error, and success states that apply, and check a narrow
|
||||
viewport. Remove anything that competes with the task without helping the user
|
||||
act or understand state.
|
||||
@@ -0,0 +1,102 @@
|
||||
# Visual Direction Reference
|
||||
|
||||
Use this reference when a new app or workspace needs a visual point of view and
|
||||
does not already have an established brand system. It adapts the useful parts
|
||||
of Impeccable's workflow: understand the product, name the surface mode, deal
|
||||
several coherent directions, commit to one, and audit the result for defaults
|
||||
that became the design by accident.
|
||||
|
||||
## The direction contract
|
||||
|
||||
Before writing UI, capture these decisions in the app's `DESIGN.md`:
|
||||
|
||||
| Decision | What to record |
|
||||
| -------------------- | ----------------------------------------------------------------- |
|
||||
| Product mode | `operate`, `read`, `persuade`, or `experience` |
|
||||
| Audience and cadence | Who uses it, how often, and under what conditions |
|
||||
| Visual world | A short name and the feeling it creates |
|
||||
| Palette family | The semantic accent family and neutral undertone |
|
||||
| Type treatment | Sans-first, editorial contrast, or display-led emphasis |
|
||||
| Composition | Focused workbench, list/detail, document, canvas, or guided steps |
|
||||
| Shape language | Quiet corners, crisp geometry, or soft utility surfaces |
|
||||
| Anti-references | Defaults this app must not drift toward |
|
||||
|
||||
`DESIGN.md` is a portable design contract, not a license to bypass the app's
|
||||
tokens or component system. If the app already has a brand system, document it
|
||||
and preserve it. If it does not, choose a direction before styling.
|
||||
|
||||
## Palette families
|
||||
|
||||
Use one family as an accent and keep the rest of the system semantic and quiet.
|
||||
These are starting points, not a fixed theme library:
|
||||
|
||||
| Family | Good fit | Typical character |
|
||||
| ---------------- | ------------------------------------------- | --------------------------------- |
|
||||
| Ink / graphite | Admin, security, sensitive review | Serious, low-noise, high contrast |
|
||||
| Cobalt / sky | Planning, collaboration, scheduling | Clear, trustworthy, alert |
|
||||
| Pine / teal | Automation, systems, finance, data | Calm, capable, grounded |
|
||||
| Indigo / violet | Slides, creative tools, research | Exploratory, focused, expressive |
|
||||
| Plum / berry | Publishing, knowledge, editorial work | Distinctive, thoughtful, human |
|
||||
| Coral / rose | Communication, people, customer workflows | Warm, direct, social |
|
||||
| Ochre / citron | Lightweight planning or energetic utilities | Optimistic, sparing, directional |
|
||||
| Paper / charcoal | Long-form reading, exports, approvals | Tactile, restrained, legible |
|
||||
|
||||
Do not make warm beige plus terracotta the universal fallback. Do not rotate
|
||||
through saturated colors mechanically. Choose the family that supports the
|
||||
workflow, then verify contrast, dark mode, focus states, destructive states,
|
||||
and the sidebar boundary.
|
||||
|
||||
## Variation without chaos
|
||||
|
||||
Vary at least two independent axes when sibling apps share a workspace:
|
||||
|
||||
- accent family or neutral undertone;
|
||||
- information density and page composition;
|
||||
- type contrast and display treatment;
|
||||
- radius and border language;
|
||||
- navigation emphasis and use of whitespace.
|
||||
|
||||
Keep shared behavior, semantic token names, accessibility, and AgentSidebar
|
||||
placement consistent. The goal is a family of products, not five unrelated
|
||||
themes and not five copies of the same starter.
|
||||
|
||||
For a batch of apps, keep a small direction ledger in the workspace
|
||||
`DESIGN.md` or the handoff. Record each app's mode, direction, and palette
|
||||
family, then choose a new family or a clearly different composition for the
|
||||
next app unless an existing brand requires reuse. Never copy a sibling's
|
||||
`global.css` palette block or treat the last app's accent as the generator
|
||||
default.
|
||||
|
||||
## Review vocabulary
|
||||
|
||||
Make one named intervention at a time so the agent can reason about the
|
||||
change:
|
||||
|
||||
- `distill` - remove copy, controls, cards, and chrome that do not serve the
|
||||
next decision;
|
||||
- `typeset` - repair hierarchy, measure, line length, and emphasis;
|
||||
- `colorize` - establish a restrained semantic palette and contrast states;
|
||||
- `layout` - repair grouping, density, alignment, and responsive composition;
|
||||
- `polish` - resolve the small visual inconsistencies after the structure is
|
||||
right;
|
||||
- `audit` - check slop, accessibility, responsive behavior, and visual drift.
|
||||
|
||||
Do not average several directions into a generic compromise. Deal two or three
|
||||
coherent options only when a new or explicitly redesigned surface has a real
|
||||
visual decision to make; for routine operate work, select one fitting direction
|
||||
and encode only the useful decision in tokens and `DESIGN.md`.
|
||||
|
||||
## Anti-slop audit
|
||||
|
||||
Before handoff, inspect the first viewport and ask:
|
||||
|
||||
- Did the app inherit the neighboring app's palette or hero layout without a
|
||||
product reason?
|
||||
- Does the first viewport show one job and one next action, rather than a
|
||||
capability catalog?
|
||||
- Are there equal-weight cards, status chips, helper paragraphs, or controls
|
||||
that should be removed or disclosed?
|
||||
- Does the typography fit the product mode instead of decorating the shell?
|
||||
- Is the AgentSidebar distinct but quiet, with the domain page still primary?
|
||||
- Are focus, loading, empty, error, dark, and narrow-width states part of the
|
||||
same design direction?
|
||||
@@ -0,0 +1,88 @@
|
||||
---
|
||||
name: inline-embeds
|
||||
description: >-
|
||||
How to render interactive previews of app screens inline in agent chat via
|
||||
sandboxed iframes. Covers the `embed` fence syntax, the `postNavigate` pop-out
|
||||
helper, and when to prefer an embed over prose / a static image.
|
||||
---
|
||||
|
||||
# Inline Embeds
|
||||
|
||||
The chat renderer lets you embed a sandboxed iframe pointing at any same-origin
|
||||
route of this app, rendered inline with your reply. Use this when a live,
|
||||
interactive preview communicates more than prose or a static screenshot — a
|
||||
chart, an email thread, a slide, a form, a ticket.
|
||||
|
||||
## The `embed` fence
|
||||
|
||||
Emit a fenced code block with the language `embed`:
|
||||
|
||||
````
|
||||
```embed
|
||||
src: /email?id=msg_123
|
||||
aspect: 4/3
|
||||
title: Re: Q4 planning
|
||||
```
|
||||
````
|
||||
|
||||
Keys:
|
||||
|
||||
| Key | Required | Notes |
|
||||
| -------- | -------- | ------------------------------------------------------------------ |
|
||||
| `src` | yes | Same-origin path beginning with `/`. Cross-origin URLs are blocked |
|
||||
| `aspect` | no | `16/9` (default), `4/3`, `3/2`, `2/1`, `21/9`, `1/1` |
|
||||
| `title` | no | Accessible label + hover tooltip |
|
||||
| `height` | no | Fixed pixel height when aspect ratio doesn't fit |
|
||||
|
||||
The rendered iframe is sandboxed (`allow-scripts allow-same-origin allow-forms
|
||||
allow-popups`) and `referrerpolicy="same-origin"`. The browser enforces that
|
||||
the iframe can't navigate the parent window.
|
||||
|
||||
## When to reach for an embed
|
||||
|
||||
- A chart or visualization that benefits from tooltips / hover.
|
||||
- A detail view the user might want to scan (email, ticket, event, slide).
|
||||
- Anything where "here's a link to it" would force an extra click.
|
||||
|
||||
**Don't** embed when plain prose, a bulleted list, or a small table is enough.
|
||||
**Don't** embed external sites — the renderer blocks cross-origin URLs.
|
||||
|
||||
## "Open in main window" button — `postNavigate`
|
||||
|
||||
Every embed route should include a small "Open" button so the user can pop the
|
||||
view out of the chat and into the full app. Import the helper from
|
||||
`@agent-native/core/client`:
|
||||
|
||||
```tsx
|
||||
import { postNavigate, isInAgentEmbed } from "@agent-native/core/client";
|
||||
|
||||
export function OpenButton({ path }: { path: string }) {
|
||||
if (!isInAgentEmbed()) return null;
|
||||
return (
|
||||
<button onClick={() => postNavigate(path)}>Open</button>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
`postNavigate` sends a `postMessage` to the parent chat window. The chat
|
||||
renderer validates the message is same-origin, same-iframe, and the path is
|
||||
relative, then updates the parent URL via `history.pushState` so react-router
|
||||
navigates without a page reload.
|
||||
|
||||
When the page is loaded directly (not in an iframe), `postNavigate` falls back
|
||||
to a same-window navigation, so the button works both ways.
|
||||
|
||||
## Adding an embed route to a template
|
||||
|
||||
1. Create a chromeless route (e.g. `app/routes/email.tsx`) that renders the
|
||||
detail view without the app shell.
|
||||
2. Mark the route path as bare in `app/components/layout/Layout.tsx` so the
|
||||
sidebar / header don't render inside the iframe.
|
||||
3. Render the existing detail component with a transparent background so it
|
||||
blends into the chat theme.
|
||||
4. Include an `<OpenButton>` that calls `postNavigate("/path/to/detail")`.
|
||||
5. Document the embed URL in this template's `AGENTS.md` so the agent knows
|
||||
what's embeddable.
|
||||
|
||||
The framework-level fence renderer and security enforcement apply
|
||||
automatically — no per-template wiring beyond the route and layout bypass.
|
||||
@@ -0,0 +1,364 @@
|
||||
---
|
||||
name: integration-webhooks
|
||||
description: >-
|
||||
Cross-platform pattern for handling messaging integration webhooks (Slack,
|
||||
Telegram, WhatsApp, email, etc.) on serverless hosts. Use when adding a new
|
||||
integration adapter, debugging dropped messages, or wiring long-running agent
|
||||
work into a webhook handler.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Integration Webhooks
|
||||
|
||||
## Rule
|
||||
|
||||
Integration webhooks (Slack, Telegram, WhatsApp, email, Google Docs, etc.) must
|
||||
**enqueue work to SQL and return 200 immediately**, then process the work in a
|
||||
**separate fresh function execution** kicked off by a self-fired HTTP POST. SQL
|
||||
is always the source of truth. Long-lived hosts use an in-process retry loop as
|
||||
a best-effort safety net; serverless deployments must use an external durable
|
||||
sweep when recovery cannot depend on a process staying alive.
|
||||
|
||||
Do not run agent loops inside the webhook handler itself. Do not rely on
|
||||
fire-and-forget `Promise`s after `return`ing from a serverless handler — they get
|
||||
killed when the function freezes.
|
||||
|
||||
## Why
|
||||
|
||||
Messaging platforms expect a 200 response within a tight window — Slack will
|
||||
retry after 3 seconds, and a retried event triggers duplicate agent runs. At the
|
||||
same time, an agent loop replying to the message can take 30–60+ seconds because
|
||||
it may make multiple LLM calls and tool calls.
|
||||
|
||||
Past attempts that don't work cross-host:
|
||||
|
||||
- **Fire-and-forget `Promise.then(...)` after returning** — Lambda/Vercel/CF
|
||||
freeze the execution context the moment the response goes out. The promise
|
||||
is silently killed, the user gets no reply, and there's no error in the
|
||||
logs.
|
||||
- **A platform background function as the queue** — host-specific execution is
|
||||
useful as a delivery mechanism, but it cannot replace the SQL row or atomic
|
||||
claim shared by every host.
|
||||
- **Cloudflare `event.waitUntil()`** — CF Workers only, not portable.
|
||||
- **Vercel Fluid / `after()`** — Vercel-only, gated behind specific runtimes.
|
||||
- **A long-lived in-process queue** — fine on a single Node box, but on
|
||||
serverless every cold start gets a fresh queue and any pending work is
|
||||
lost.
|
||||
|
||||
The only universal answer: **persist the work, then trigger a brand new
|
||||
function execution to do it.** SQL is the queue, a self-webhook is the trigger,
|
||||
and a recurring job is the safety net.
|
||||
|
||||
## The Flow
|
||||
|
||||
```
|
||||
┌──────────┐ 1. POST /integrations/:platform/webhook
|
||||
│ Platform │────────────────────────────────────────────►┌──────────────────┐
|
||||
└──────────┘ │ Webhook handler │
|
||||
│ (function exec 1)│
|
||||
└──────────────────┘
|
||||
│
|
||||
2. INSERT INTO integration_pending_tasks
|
||||
(status='pending', payload=...)
|
||||
│
|
||||
3. dispatch POST /integrations/process-task
|
||||
— portable self-fire by default
|
||||
— acknowledged background handoff when enabled
|
||||
│
|
||||
4. return 200 to platform ◄───────────┘
|
||||
|
||||
┌──────────────────┐
|
||||
5. POST arrives at processor │ Processor │
|
||||
(separate fresh function) │ (function exec 2)│
|
||||
└──────────────────┘
|
||||
│
|
||||
6. claimPendingTask(id) → status='processing'
|
||||
7. runAgentLoop(...) — full timeout budget here
|
||||
8. adapter.sendResponse(...) back to platform
|
||||
9. markTaskCompleted(id)
|
||||
|
||||
|
||||
┌──────────────────────────────────────────────┐
|
||||
│ Recovery sweep (every 60s) — safety net │
|
||||
│ Re-fires processor for tasks stuck in │
|
||||
│ 'pending' or 'processing' beyond timeout. │
|
||||
│ Caps retries at 3 then marks 'failed'. │
|
||||
└──────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The webhook handler does as little as possible. The fresh function execution
|
||||
that handles `_process-task` gets its own full timeout budget for the agent
|
||||
loop.
|
||||
|
||||
## Key Files
|
||||
|
||||
| File | Purpose |
|
||||
| ----------------------------------------------------------------------- | ---------------------------------------------------------------------- |
|
||||
| `packages/core/src/integrations/plugin.ts` | Mounts `/_agent-native/integrations/*` routes |
|
||||
| `packages/core/src/integrations/webhook-handler.ts` | Verifies signature, parses, enqueues task, fires processor |
|
||||
| `packages/core/src/integrations/pending-tasks-store.ts` | SQL queue: `insertPendingTask`, `claimPendingTask`, `markTaskCompleted`, `markTaskFailed` |
|
||||
| `packages/core/src/integrations/pending-tasks-retry-job.ts` | Recurring retry sweep (`startPendingTasksRetryJob`, `retryStuckPendingTasks`) |
|
||||
| `packages/core/src/integrations/integration-durable-dispatch.ts` | Default-off acknowledged dispatch, scoped rollout, and outcome recording |
|
||||
| `packages/core/src/integrations/types.ts` | `PlatformAdapter`, `IncomingMessage`, `OutgoingMessage` |
|
||||
| `packages/core/src/integrations/adapters/{slack,telegram,whatsapp,email,google-docs}.ts` | One adapter per platform |
|
||||
|
||||
## Routes
|
||||
|
||||
All under `/_agent-native/integrations/`:
|
||||
|
||||
| Method | Path | Purpose |
|
||||
| ------ | -------------------------- | ------------------------------------------------------------- |
|
||||
| POST | `/:platform/webhook` | Platform pings this. Verifies, enqueues, returns 200 quickly. |
|
||||
| POST | `/process-task` | Processor target. Claims a task and runs the agent loop. |
|
||||
| POST | `/retry-stuck-tasks` | Signed, bounded recovery sweep for durable schedulers. |
|
||||
| GET | `/status` | All integrations status (settings UI). |
|
||||
| GET | `/:platform/status` | One platform's status. |
|
||||
| POST | `/:platform/enable` | Enable an integration. |
|
||||
| POST | `/:platform/disable` | Disable an integration. |
|
||||
| POST | `/:platform/setup` | Platform-specific setup (e.g. Telegram webhook registration). |
|
||||
|
||||
## SQL Schema
|
||||
|
||||
The pending-task queue lives in `integration_pending_tasks`:
|
||||
|
||||
```sql
|
||||
CREATE TABLE IF NOT EXISTS integration_pending_tasks (
|
||||
id TEXT PRIMARY KEY,
|
||||
platform TEXT NOT NULL,
|
||||
external_thread_id TEXT NOT NULL,
|
||||
payload TEXT NOT NULL, -- JSON-serialized IncomingMessage
|
||||
owner_email TEXT NOT NULL,
|
||||
org_id TEXT,
|
||||
status TEXT NOT NULL, -- pending | processing | completed | failed
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
dispatch_attempts INTEGER NOT NULL DEFAULT 0,
|
||||
last_dispatch_at INTEGER,
|
||||
last_dispatch_outcome TEXT,
|
||||
dispatch_scope TEXT, -- persisted channel scope for recovery
|
||||
error_message TEXT,
|
||||
created_at INTEGER NOT NULL,
|
||||
updated_at INTEGER NOT NULL,
|
||||
completed_at INTEGER
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_pending_tasks_status_created
|
||||
ON integration_pending_tasks(status, created_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_pending_tasks_dispatch_scope
|
||||
ON integration_pending_tasks(platform, dispatch_scope);
|
||||
```
|
||||
|
||||
The store layer creates this lazily on first use via `ensureTable()` and uses
|
||||
`intType()` from `db/client.ts` so it works on both SQLite and Postgres.
|
||||
|
||||
`claimPendingTask` is the critical concurrency primitive: it atomically flips
|
||||
`pending` → `processing` and increments `attempts`, returning `null` if another
|
||||
worker beat us to it. Both the initial dispatch and every recovery sweep
|
||||
funnel through the same processor endpoint, and `claimPendingTask` is what
|
||||
prevents the same task from being processed twice.
|
||||
|
||||
### Netlify durable recovery
|
||||
|
||||
The portable self-dispatch remains the default. To emit and use Netlify's
|
||||
acknowledged background worker plus a one-minute scheduled recovery function,
|
||||
set `AGENT_INTEGRATION_DURABLE_DISPATCH=true` at build and runtime. A production
|
||||
rollout can be narrowed with the comma-separated
|
||||
`AGENT_INTEGRATION_DURABLE_DISPATCH_SCOPES` allowlist. Supported values are
|
||||
`<platform>:*`, `<platform>:<external-thread-id>`, and, for adapters that expose
|
||||
one, `<platform>:<channel-id>` (for example `slack:C123`).
|
||||
Channel-scoped handoffs persist that scope separately from the provider thread
|
||||
identity so a later bounded recovery sweep applies the same allowlist decision.
|
||||
|
||||
Workspace deploys emit this pair only for the Dispatch control-plane app, which
|
||||
owns workspace messaging integrations. Standalone templates emit their own
|
||||
pair when the same flag is enabled.
|
||||
|
||||
The background handoff waits only for Netlify's enqueue acknowledgement, not
|
||||
for the agent loop. A failed or non-2xx acknowledgement falls back to the
|
||||
portable processor. The scheduled function calls the HMAC-authenticated,
|
||||
bounded `/retry-stuck-tasks` route; its atomic compare-and-set update prevents
|
||||
overlapping sweeps from dispatching the same stale row twice.
|
||||
Rows acknowledged by the 15-minute background worker use a 16-minute stale
|
||||
cutoff, while portable synchronous dispatches retain the shorter serverless
|
||||
cutoff. Apply that lease predicate before `LIMIT` so healthy long runs cannot
|
||||
hide recoverable work. The background processor writes its lease marker in the
|
||||
same atomic update that claims the row; best-effort dispatch telemetry is not
|
||||
trusted for replay safety.
|
||||
|
||||
## Adding a New Platform Adapter
|
||||
|
||||
1. **Implement `PlatformAdapter`** in `packages/core/src/integrations/adapters/<platform>.ts`:
|
||||
|
||||
```ts
|
||||
export function myPlatformAdapter(): PlatformAdapter {
|
||||
return {
|
||||
platform: "myplatform",
|
||||
label: "MyPlatform",
|
||||
getRequiredEnvKeys: () => [
|
||||
{ name: "MYPLATFORM_TOKEN", label: "MyPlatform Bot Token", scope: "global" },
|
||||
{ name: "MYPLATFORM_SIGNING_SECRET", label: "MyPlatform Signing Secret", scope: "global" },
|
||||
],
|
||||
async handleVerification(event) {
|
||||
// Platform-specific challenge response, if any
|
||||
return { handled: false };
|
||||
},
|
||||
async verifyWebhook(event) {
|
||||
// Verify HMAC/signature with a server-side secret and constant-time comparison.
|
||||
// Never leave this as a permissive stub in production.
|
||||
return verifyMyPlatformSignature(event);
|
||||
},
|
||||
async parseIncomingMessage(event) {
|
||||
// Map raw payload → IncomingMessage, or null to ignore
|
||||
return null;
|
||||
},
|
||||
async sendResponse(message, context) {
|
||||
// POST back to the platform's API
|
||||
},
|
||||
formatAgentResponse(text) {
|
||||
return { text, platformContext: {} };
|
||||
},
|
||||
async getStatus(baseUrl) {
|
||||
return { platform: "myplatform", label: "MyPlatform", enabled: false, configured: false };
|
||||
},
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
2. **Register it** in `getDefaultAdapters()` inside `plugin.ts`. The webhook,
|
||||
queue, processor, and retry job are shared infrastructure — you do not
|
||||
write any of that per-adapter.
|
||||
|
||||
3. **Declare required env keys** so the secrets/onboarding UI surfaces them.
|
||||
See `secrets` and `onboarding` skills.
|
||||
|
||||
4. **Update the platform's webhook URL** to point at
|
||||
`${baseUrl}/_agent-native/integrations/<platform>/webhook`. For platforms
|
||||
with a registration API (Telegram), implement `POST /:platform/setup`.
|
||||
|
||||
Never hardcode bot tokens, signing secrets, verification tokens, webhook URLs,
|
||||
channel/customer identifiers, or copied platform payloads with real private data
|
||||
inside the adapter, tests, docs, prompts, or fixtures. `getRequiredEnvKeys()`
|
||||
declares credential names only. Values come from deployment configuration,
|
||||
registered secrets, OAuth, or scoped credential stores, and tests should use
|
||||
obvious fake placeholders.
|
||||
|
||||
The adapter is **only** responsible for:
|
||||
|
||||
- platform-specific verification (signatures, challenges)
|
||||
- payload → `IncomingMessage` mapping
|
||||
- agent text → platform format
|
||||
- delivering the response back to the platform
|
||||
|
||||
It does **not** know about the queue, the processor, retries, or the agent
|
||||
loop. Those are handled by the shared webhook handler.
|
||||
|
||||
### Slack non-message events
|
||||
|
||||
Slack's Events API also sends events that are not agent messages, such as
|
||||
`link_shared` for app unfurls. Do not map those into `IncomingMessage` unless
|
||||
they should actually run the agent. Handle them as short, provider-specific
|
||||
webhook work: verify the Slack signature, return `200 OK` quickly, and call the
|
||||
provider API needed for the event (`chat.unfurl` for link previews). If a single
|
||||
Slack app must handle both agent chat and app unfurls, put a dispatcher in front
|
||||
of the one Slack Events Request URL and route message events to the integration
|
||||
webhook flow while routing `link_shared` to the app-specific unfurl handler.
|
||||
|
||||
## Long-Running Agent Work
|
||||
|
||||
The processor endpoint runs in a fresh function execution with its own full
|
||||
timeout (typically 30–60s on Netlify/Vercel, longer on background-friendly
|
||||
hosts). That budget is dedicated entirely to the agent loop — there is no
|
||||
platform-side timer racing it.
|
||||
|
||||
If a single agent run might exceed the function timeout (large multi-step
|
||||
plans, deep delegation chains), the agent should:
|
||||
|
||||
1. Send an interim acknowledgement back to the platform so the user knows the
|
||||
request landed (`adapter.sendResponse({ text: "Working on it..." })`).
|
||||
2. Persist intermediate state in chat-thread data, application state, or a
|
||||
recurring job so the next invocation can pick up where this one left off.
|
||||
|
||||
The retry job will only re-fire tasks stuck in `processing` for over 5 minutes,
|
||||
so a normal long-running reply is safe.
|
||||
|
||||
## Cross-Platform Considerations
|
||||
|
||||
- **Portable correctness, optional host acceleration.** Every host uses SQL,
|
||||
HMAC-authenticated processor routes, and atomic claims. A host-specific
|
||||
background function or scheduler may provide a more reliable wake-up, but
|
||||
disabling it must preserve the portable path.
|
||||
- **No assumed runtime.** The processor endpoint is a normal H3 handler under
|
||||
`/_agent-native/`. It runs wherever the rest of the framework runs.
|
||||
- **No persistent in-memory state.** The dedup map in the webhook handler is
|
||||
best-effort only; the SQL queue is the source of truth. Any cold start
|
||||
loses the dedup map but the queue stays consistent.
|
||||
- **Postgres + SQLite both supported.** `claimPendingTask` uses `RETURNING` on
|
||||
Postgres and a re-read on SQLite. No platform-specific SQL.
|
||||
- **Self-webhook URL resolution.** The processor URL is built from
|
||||
`WEBHOOK_BASE_URL`, `APP_URL`, or `URL` env vars (with `localhost:3000` as
|
||||
the dev fallback). Templates that change their public URL must keep one of
|
||||
these set.
|
||||
|
||||
## Why Fire-and-Forget on Serverless Is Unreliable
|
||||
|
||||
The portable webhook path gives the outbound processor request a short head
|
||||
start but does not wait for the response body, so that initial dispatch is
|
||||
**not** guaranteed to complete before the function freezes. On a long-lived
|
||||
host, the in-process retry loop is a best-effort safety net. On Netlify with
|
||||
durable dispatch enabled, the initial handoff is acknowledged and the external
|
||||
scheduled function supplies the recovery wake-up for cases where:
|
||||
|
||||
- The serverless platform froze the handler before the outbound `fetch`
|
||||
flushed its bytes.
|
||||
- The processor function 502'd or cold-started slow enough to time out.
|
||||
- The processor itself was killed mid-agent-loop (function timeout, container
|
||||
shutdown, deploy mid-run).
|
||||
|
||||
Tasks stuck in `pending` for >90s or `processing` for >5min get re-fired up to
|
||||
3 times. After 3 attempts they're marked `failed` permanently so we stop
|
||||
spamming the processor.
|
||||
|
||||
**Never assume the initial dispatch succeeded.** Rely on the SQL queue, atomic
|
||||
claim, and a recovery mechanism whose lifetime is independent of the original
|
||||
request. An in-process timer alone is not that mechanism on serverless.
|
||||
|
||||
## Debugging Checklist
|
||||
|
||||
1. **Platform sent the webhook?** Check the platform's delivery logs (Slack
|
||||
admin, Telegram `getWebhookInfo`).
|
||||
2. **Webhook handler returned 200?** If not, the platform retries — look for
|
||||
duplicate task rows. Signature failures return 401.
|
||||
3. **Task in the queue?** `SELECT * FROM integration_pending_tasks WHERE
|
||||
external_thread_id = '...' ORDER BY created_at DESC LIMIT 5`.
|
||||
4. **Status?** `pending` means the processor never picked it up — check that
|
||||
`_process-task` is reachable from the box itself (the self-fetch must work
|
||||
over the public URL). `processing` for over 5 minutes means the processor
|
||||
died mid-run — a live recovery sweep will pick it up.
|
||||
5. **Failed?** Check `error_message` and `attempts`. After 3 attempts the row
|
||||
is parked at `failed` and won't be retried.
|
||||
6. **Reply not delivered?** The processor likely succeeded but
|
||||
`adapter.sendResponse` failed — check the adapter's outbound logs.
|
||||
|
||||
## Automation connectors
|
||||
|
||||
Workflow systems such as n8n and Zapier are not messaging channels. Do not add
|
||||
them as `PlatformAdapter`s or route them through `provider-api`.
|
||||
|
||||
For n8n-style workflow invocation and callbacks, use
|
||||
`@agent-native/core/automation` with static workflow IDs and allow-listed
|
||||
origins. Agents provide structured input, never a target URL or credential.
|
||||
Callbacks must verify a configured secret/signature, claim a durable event ID,
|
||||
enqueue work through the established queue, and acknowledge quickly.
|
||||
|
||||
Zapier is blueprint-only unless the app implements Zapier's explicit REST Hook
|
||||
subscribe/unsubscribe contract or configures a separate Zapier MCP connection.
|
||||
Do not imply a generic Zapier workflow-execution API exists.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `server-plugins` — How `/_agent-native/` routes get mounted
|
||||
- `recurring-jobs` — Pattern the retry job follows
|
||||
- `actions` — When to use an action vs a webhook
|
||||
- `secrets` — Registering platform tokens
|
||||
- `onboarding` — Surfacing setup steps for each platform
|
||||
- `delegate-to-agent` — How the processor invokes the agent loop
|
||||
@@ -0,0 +1,48 @@
|
||||
---
|
||||
name: internationalization
|
||||
description: >-
|
||||
How to add localized UI copy when the user explicitly requests i18n.
|
||||
Do not load or apply this skill for ordinary English UI edits in this
|
||||
starter — it ships inline English strings with no catalogs.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Internationalization
|
||||
|
||||
## Rule
|
||||
|
||||
**Opt-in only.** Do not add i18n catalogs, `LanguagePicker`, locale init scripts,
|
||||
or `AppProviders i18n={{...}}` unless the user explicitly asks for
|
||||
internationalization / localization / multiple languages.
|
||||
|
||||
This starter ships **English-only inline copy**. For normal UI text edits,
|
||||
change the string in the component and stop — do not create `app/i18n/`.
|
||||
|
||||
When the user does request i18n, then: visible UI copy belongs in the app's i18n
|
||||
catalog, not inline in components. Update the English source catalog first,
|
||||
update existing locale catalogs, and run the i18n guard.
|
||||
|
||||
## Catalogs
|
||||
|
||||
When enabling i18n, use `app/i18n/`:
|
||||
|
||||
- `en-US.ts` is the canonical source tree and fallback.
|
||||
- Other locale files keep the same non-plural keys and the same placeholders.
|
||||
- `index.ts` exports an `AgentNativeI18nCatalog` with English bundled and
|
||||
non-English catalogs loaded by dynamic import.
|
||||
|
||||
Use BCP-47 filenames from the supported set: `en-US`, `zh-CN`, `zh-TW`, `es-ES`,
|
||||
`fr-FR`, `de-DE`, `ja-JP`, `ko-KR`, `pt-BR`, `hi-IN`, `ar-SA`.
|
||||
|
||||
## Verification
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
pnpm guard:i18n-catalogs
|
||||
```
|
||||
|
||||
For broader changes, also run the affected tests and a single `pnpm typecheck`
|
||||
at the end of the batch.
|
||||
@@ -0,0 +1,337 @@
|
||||
---
|
||||
name: multi-app-workspace
|
||||
description: >-
|
||||
How to build or extend a multi-app Agent-Native workspace — the monorepo
|
||||
shape, the Dispatch control plane, the shell app that fronts every other app,
|
||||
and the shared package. Use when the user asks for a workspace, a platform, a
|
||||
suite of apps, an app launcher or shell, a second app, Dispatch, a shared
|
||||
vault, or cross-app agents. This repo is a standalone app, so read this
|
||||
before restructuring it.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Multi-App Workspaces
|
||||
|
||||
## Rule
|
||||
|
||||
Scaffold a workspace with the CLI. Never hand-build the monorepo wiring, and
|
||||
never hand-build Dispatch — it is a published template and runtime package, not
|
||||
something to recreate from parts.
|
||||
|
||||
## This repo's starting point
|
||||
|
||||
`package.json` records `agent-native.scaffold.shape: "standalone"`, there is no
|
||||
`agent-native.workspaceCore` field, and `pnpm-workspace.yaml` has no `packages:`
|
||||
key. This is a single app, not a workspace root. `add-app` will not work here
|
||||
until a workspace root exists.
|
||||
|
||||
Converting is mechanical, but **this folder must stay the root**. It is the git
|
||||
root and the container expects it as the project root, so never scaffold a new
|
||||
folder in the parent and move the repo into it. `create .` is also out — it
|
||||
aborts unless the directory is empty apart from `.git` / `README.md` /
|
||||
`.gitignore`.
|
||||
|
||||
Instead, scaffold into a staging subdirectory *inside* this repo, hoist its root
|
||||
files up, and delete it. Nothing leaves the git root.
|
||||
|
||||
```bash
|
||||
# 1. Staging scaffold. The name becomes the shared package scope
|
||||
# (@app-workspace/shared), so use the real workspace name.
|
||||
npx @agent-native/core@latest create app-workspace
|
||||
|
||||
# 2. Move this app's source under apps/<app-id>/, preserving history.
|
||||
# Include app-level AGENTS.md, CLAUDE.md, DESIGN.md, and .agents/skills.
|
||||
mkdir -p apps/<app-id>
|
||||
git mv <app files> apps/<app-id>/
|
||||
|
||||
# 3. Hoist the scaffold's root files, then drop the staging dir.
|
||||
mv app-workspace/package.json app-workspace/pnpm-workspace.yaml \
|
||||
app-workspace/agent-native.config.ts app-workspace/agent-native.json \
|
||||
app-workspace/tsconfig.base.json app-workspace/AGENTS.md \
|
||||
app-workspace/DESIGN.md app-workspace/scripts app-workspace/packages .
|
||||
mv app-workspace/apps/dispatch apps/dispatch
|
||||
rm -rf app-workspace
|
||||
```
|
||||
|
||||
That gives the root `package.json` with `workspaceCore`, `pnpm-workspace.yaml`
|
||||
with its dependency catalog, `packages/shared/`, the workspace `AGENTS.md` and
|
||||
`DESIGN.md`, and `apps/dispatch`. Point the root `.agents/skills` at the shared
|
||||
package (`ln -s ../packages/shared/.agents/skills .agents/skills`) and keep
|
||||
`.claude/skills` pointing at `.agents/skills`.
|
||||
|
||||
Leave container- and CI-required files (`netlify.toml`, workflow configs,
|
||||
`.env`) at the git root. Move framework skills into
|
||||
`packages/shared/.agents/skills/` so every app inherits them; only genuinely
|
||||
app-specific skills go under `apps/<app-id>/.agents/skills/`.
|
||||
|
||||
Step 2 skips the **workspacify** transform that `create` and `add-app` run on a
|
||||
template, so apply it by hand to the moved app. It is a short, closed list:
|
||||
|
||||
- add `"@app-workspace/shared": "workspace:*"` to `dependencies`
|
||||
- add `postgres` (core lazy-loads it when `DATABASE_URL` is Postgres)
|
||||
- resolve any `workspace:*` refs for `@agent-native/core|toolkit|dispatch` to
|
||||
real version ranges
|
||||
- delete `pnpm.onlyBuiltDependencies` — build approvals belong at the root
|
||||
- delete `learnings.defaults.md` (standalone-only)
|
||||
- replace copied framework skills under `.agents/skills/` with symlinks to the
|
||||
root `.agents/skills`; keep app-specific skills local
|
||||
- rewrite `AGENTS.md` action commands to `cd apps/<app-id> && pnpm action`
|
||||
- in `netlify.toml`, set the build to
|
||||
`APP_BASE_PATH=/<app-id> VITE_APP_BASE_PATH=/<app-id> NITRO_PRESET=netlify pnpm --filter <app-id> build`
|
||||
and point `functions` at `apps/<app-id>/.netlify/functions-internal`
|
||||
|
||||
App source itself is left untouched — the three-layer model auto-discovers the
|
||||
shared package from the root `workspaceCore` field. Then consolidate `.env` to
|
||||
the workspace root so every app shares `BETTER_AUTH_SECRET`, `DATABASE_URL`,
|
||||
and `A2A_SECRET`, and run `pnpm install` at the root.
|
||||
|
||||
If porting screens into a freshly scaffolded app is easier than moving this one,
|
||||
do that instead — it skips the transform entirely.
|
||||
|
||||
## Scaffold
|
||||
|
||||
Workspace is the **default** shape of `create`; `--standalone` is the opt-out.
|
||||
**Dispatch is always scaffolded** — the template picker hides it and the CLI
|
||||
unions it in, so `--template` only names the *additional* apps:
|
||||
|
||||
```bash
|
||||
npx @agent-native/core@latest create app-workspace --template tasks,content
|
||||
```
|
||||
|
||||
Inside an existing workspace root, `create <name>` delegates to `add-app`:
|
||||
|
||||
```bash
|
||||
npx @agent-native/core@latest add-app crm --template content
|
||||
pnpm install # at the workspace root
|
||||
pnpm dev
|
||||
```
|
||||
|
||||
Both run **workspacify** on the template. There is no separate "workspace-app"
|
||||
scaffold to maintain.
|
||||
|
||||
## Anatomy
|
||||
|
||||
```
|
||||
package.json "agent-native": { "workspaceCore": "@app-workspace/shared" }
|
||||
pnpm-workspace.yaml packages: ["packages/*", "apps/*"]
|
||||
agent-native.config.ts defineAgentNativeConfig({ translations, changelog, ... })
|
||||
.env shared ANTHROPIC_API_KEY, BETTER_AUTH_SECRET, DATABASE_URL, A2A_SECRET
|
||||
packages/shared/ the private @app-workspace/shared package
|
||||
DESIGN.md workspace brand contract + sibling direction ledger
|
||||
apps/dispatch/ control plane + shell (see below)
|
||||
apps/<domain-app>/ one directory per app
|
||||
```
|
||||
|
||||
App discovery is by directory: the **app id is the directory name** under
|
||||
`apps/`, and the display name comes from that app's `package.json`
|
||||
`displayName`. Nothing registers apps in a central list.
|
||||
|
||||
Per-app gateway config lives under `agent-native` in the app's `package.json`:
|
||||
`workspaceApp.audience` (`"internal"` default, or `"public"`),
|
||||
`workspaceApp.publicPaths`, `workspaceApp.protectedPaths`.
|
||||
|
||||
## The shell / default app
|
||||
|
||||
`agent-native dev` at the workspace root starts the gateway, not an app. The
|
||||
gateway mounts each app at `/<appId>` on one origin and lazily boots an app on
|
||||
first visit (`--eager` starts all, `--prewarm` warms in background).
|
||||
|
||||
Default app resolution, in order:
|
||||
|
||||
1. `WORKSPACE_DEFAULT_APP` env var, if it names a real app
|
||||
2. an app with id `dispatch`
|
||||
3. otherwise `apps[0]` — and `/` does **not** redirect
|
||||
|
||||
So the container experience is: name the shell app `dispatch`, and `/` redirects
|
||||
to it automatically. That is the whole mechanism — no manifest, no registry
|
||||
file.
|
||||
|
||||
Because every app shares one origin and the session cookie is scoped to `/`, a
|
||||
mounted pane inherits the ambient session. Only trusted, workspace-owner
|
||||
authored apps belong there. Read `security` before making any app publicly
|
||||
reachable or installable from outside the workspace.
|
||||
|
||||
## Dispatch
|
||||
|
||||
Dispatch is the workspace control plane: secrets vault, workspace connections,
|
||||
messaging inbox (Slack / email / Telegram / WhatsApp), cross-app A2A delegation,
|
||||
MCP gateway, approvals, agent profiles, shared resources, and the Apps rail that
|
||||
fronts the other apps.
|
||||
|
||||
Two things share the name:
|
||||
|
||||
- the **`dispatch` template** — scaffold it as `apps/dispatch`
|
||||
- **`@agent-native/dispatch`** — the published runtime package holding its
|
||||
server logic, routes, and components
|
||||
|
||||
Do not reimplement any of it. In a real workspace, the Dispatch app's route
|
||||
files are one-line re-exports:
|
||||
|
||||
```tsx
|
||||
// apps/dispatch/app/routes/$appId.tsx
|
||||
export {
|
||||
clientLoader,
|
||||
default,
|
||||
loader,
|
||||
meta,
|
||||
} from "@agent-native/dispatch/routes/pages/$appId";
|
||||
```
|
||||
|
||||
`app/routes.ts` stays on `flatRoutes()` — React Router resolves route `file`
|
||||
paths relative to the consumer's `app/`, so package-internal paths cannot be
|
||||
splatted in directly. The one-line shell file per route is the supported
|
||||
pattern.
|
||||
|
||||
To add a workspace-owned tab: write a normal local route file under
|
||||
`app/routes/`, then register the tab in `app/dispatch-extensions.tsx`. The shell
|
||||
chrome comes from `Layout` in `@agent-native/dispatch/components`.
|
||||
|
||||
If the user wants Dispatch-like behavior without Dispatch, say so plainly and
|
||||
scope it — a single app cannot get the vault, inbox, and cross-app routing for
|
||||
free.
|
||||
|
||||
### Dispatch must carry the product's brand
|
||||
|
||||
A scaffolded Dispatch ships the neutral 0%-saturation starter palette, so out of
|
||||
the box it reads as "a default Agent-Native app" rather than as the product's
|
||||
front door. That is not acceptable for the shell — it is the first screen every
|
||||
user sees and the frame around every other app.
|
||||
|
||||
Dispatch's theming is app-owned even though its routes come from the package:
|
||||
|
||||
- `apps/dispatch/app/global.css` — the token block. Replace the placeholder
|
||||
`:root` / dark values with the workspace brand for **both** modes.
|
||||
- `apps/dispatch/app/design-system.ts` — `defineDesignSystem({ name, theme,
|
||||
components })` to override component adapters.
|
||||
- `apps/dispatch/app/dispatch-extensions.tsx` — workspace-owned tabs.
|
||||
- `Layout` from `@agent-native/dispatch/components` consumes semantic tokens, so
|
||||
retheming the tokens retheme the chrome. Do not fork the Layout to restyle it.
|
||||
|
||||
Treat the shell like a designed surface: read `frontend-design` and apply the
|
||||
workspace brand to the Overview, Apps rail, and empty states before calling the
|
||||
workspace done.
|
||||
|
||||
## Shared design system and brand
|
||||
|
||||
**This does not happen automatically — assume it is broken until you wire it.**
|
||||
Every scaffolded app gets its own copy of `app/global.css` with the same
|
||||
placeholder tokens, and the shared package ships no CSS export. Left alone, apps
|
||||
drift and the workspace looks like unrelated demos.
|
||||
|
||||
The framework's default stance is deliberately anti-uniform: the scaffolded
|
||||
`DESIGN.md` tells each app to pick its own accent and warns against copying a
|
||||
sibling's palette. It carves out one exception — *"unless the workspace has an
|
||||
explicit brand system"*. When the user wants one shared look, take that
|
||||
exception explicitly and record it, rather than silently copying token blocks
|
||||
between apps.
|
||||
|
||||
Wire it once:
|
||||
|
||||
1. Put the tokens in the shared package, e.g.
|
||||
`packages/shared/src/client/brand.css`, and add an export entry to its
|
||||
`package.json`: `"./brand.css": "./src/client/brand.css"`.
|
||||
2. In every app's `app/global.css`, delete the copied `:root` token block and
|
||||
import the shared one after the framework styles:
|
||||
|
||||
```css
|
||||
@import "tailwindcss";
|
||||
@import "@agent-native/core/styles/agent-native.css";
|
||||
@import "@agent-native/toolkit/styles.css";
|
||||
@import "@app-workspace/shared/brand.css";
|
||||
|
||||
@source "./**/*.{ts,tsx}";
|
||||
@source "../../../packages/shared/src/**/*.{ts,tsx}";
|
||||
```
|
||||
|
||||
The second `@source` is required or Tailwind will not scan shared components
|
||||
and their classes get purged.
|
||||
|
||||
3. Share component-level decisions through `defineDesignSystem` exported from
|
||||
`packages/shared/src/client`, with each app's `app/design-system.ts`
|
||||
re-exporting it and layering only genuine app-local overrides.
|
||||
4. Record the brand in the root `DESIGN.md` — its "Shared product context" and
|
||||
"Sibling direction ledger" are the workspace's source of truth. Each app's
|
||||
own `DESIGN.md` then records only what it varies.
|
||||
|
||||
Apps may still differentiate with an accent or composition, but they inherit the
|
||||
shared base rather than re-deriving a direction. When adding an app to a
|
||||
workspace that already has a brand, apply steps 2–4 as part of scaffolding it —
|
||||
not as a later cleanup pass.
|
||||
|
||||
## Three layers, merged by file name
|
||||
|
||||
1. **App local** — `apps/<name>/` wins
|
||||
2. **Workspace shared** — `packages/shared/`
|
||||
3. **Framework default** — `@agent-native/core`
|
||||
|
||||
Applies to plugins, skills, actions, and `AGENTS.md`. Create the file and it
|
||||
takes over; there is no wiring step.
|
||||
|
||||
| Override | File in the app |
|
||||
| ------------------ | -------------------------------------------------- |
|
||||
| Auth plugin | `apps/<name>/server/plugins/auth.ts` |
|
||||
| Agent-chat plugin | `apps/<name>/server/plugins/agent-chat.ts` |
|
||||
| One skill | `apps/<name>/.agents/skills/<skill>/SKILL.md` |
|
||||
| One action | `apps/<name>/actions/<action>.ts` |
|
||||
| Extra instructions | `apps/<name>/AGENTS.md` (merges with workspace one) |
|
||||
|
||||
## packages/shared
|
||||
|
||||
Only for what genuinely spans apps: an auth/SSO override and agent-chat override
|
||||
exported from `src/server/index.ts`, shared React exports from
|
||||
`src/client/index.ts`, workspace `AGENTS.md`, skills under `.agents/skills/`,
|
||||
shared `actions/`, and provider connector helpers. Apps depend on it as
|
||||
`"@app-workspace/shared": "workspace:*"`.
|
||||
|
||||
Promote a component here only when more than one app uses it. Everything else
|
||||
stays app-local — framework defaults already cover the common case.
|
||||
|
||||
## Don't
|
||||
|
||||
- Don't create a second app registry, launcher, or wrapper app. The gateway plus
|
||||
Dispatch's Apps rail is the registry.
|
||||
- Don't build a new dashboard that re-implements mail, calendar, or analytics.
|
||||
Reach existing apps as A2A peers or link to them.
|
||||
- Don't copy a credential into each app's `.env`. One vault, grants and
|
||||
credential refs out — read `secrets` and `workspace-connections`.
|
||||
- Don't copy shared skill files into an app. Link or override them.
|
||||
- Don't add i18n or changelog to a new app unless asked; keep apps English-only
|
||||
by default.
|
||||
- Don't ship Dispatch on the placeholder palette. The shell is the product's
|
||||
front door.
|
||||
- Don't duplicate token blocks between apps to make them match. Put them in the
|
||||
shared package and import.
|
||||
- Don't relocate this repo to make it a workspace. The current folder is the git
|
||||
root and the container root; scaffold into a staging subdirectory and hoist.
|
||||
|
||||
## Verify
|
||||
|
||||
```bash
|
||||
pnpm install # workspace root
|
||||
pnpm dev # gateway; / should land on the default app
|
||||
pnpm -r typecheck
|
||||
pnpm agent-native:doctor # per app
|
||||
```
|
||||
|
||||
Then open the shell and at least one domain app in a browser. Confirm the brand
|
||||
is visibly applied in both light and dark mode, not just that the build passes.
|
||||
|
||||
Confirm the gateway lists every app, that `/` redirects to the shell, and that
|
||||
logging into one app carries into another before calling it done.
|
||||
|
||||
## Deeper reading
|
||||
|
||||
Version-matched docs ship in the package. From an app directory:
|
||||
|
||||
```bash
|
||||
pnpm action docs-search --slug multi-app-workspace
|
||||
pnpm action docs-search --slug dispatch
|
||||
pnpm action docs-search --slug workspace-deployment
|
||||
pnpm action docs-search --slug workspace-connections
|
||||
pnpm action docs-search --slug workspace-management
|
||||
```
|
||||
|
||||
Template source for every first-party app, including Dispatch, is readable at
|
||||
`node_modules/@agent-native/core/corpus/templates/`.
|
||||
@@ -0,0 +1,95 @@
|
||||
---
|
||||
name: notifications
|
||||
description: >-
|
||||
In-app notifications primitive with pluggable server-side channels. Use when
|
||||
the agent needs to surface progress, alerts, or completions to the user —
|
||||
both in-app (bell + toast) and out-of-band (webhook, Slack, custom).
|
||||
---
|
||||
|
||||
# Notifications
|
||||
|
||||
`notify()` is the framework's "tell the user something" primitive. Every call persists a row to the inbox (drives the bell UI) and fans out to any registered server-side channels. Channels follow the same pluggable-provider pattern as `tracking` — register at startup, `notify()` fans out, errors are isolated.
|
||||
|
||||
Use for: *agent progress milestones, automation triggers firing, background job completions, critical errors*. Don't use for chat replies — those go through the conversation.
|
||||
|
||||
## Tools
|
||||
|
||||
| Tool | Purpose |
|
||||
|---|---|
|
||||
| `notify` | Send a notification (severity + title + optional body/metadata/channels) |
|
||||
| `list-notifications` | Show recent notifications for the current user |
|
||||
|
||||
## Sending
|
||||
|
||||
```
|
||||
notify --severity info --title "Booking confirmed" --body "Jane at 3pm"
|
||||
```
|
||||
|
||||
| Severity | When |
|
||||
|---|---|
|
||||
| `info` | FYI / progress / confirmation |
|
||||
| `warning` | Something to look at soon |
|
||||
| `critical` | Needs immediate attention |
|
||||
|
||||
Optional: `--metadataJson '{"threadId":"abc"}'`, `--channels inbox,webhook` (omit to run all registered).
|
||||
|
||||
## Delivery
|
||||
|
||||
`notify()` always inserts into the `notifications` table (unless `channels` explicitly excludes `inbox`), then fans out to every registered channel in parallel (best-effort; a failing channel doesn't block others). Finally it emits `notification.sent` on the event bus so automations can chain — e.g. *"when a critical notification fires, also page on-call."*
|
||||
|
||||
## Built-in Channels
|
||||
|
||||
| Channel | How | Requires |
|
||||
|---|---|---|
|
||||
| `inbox` | INSERT → drives bell UI | (always on) |
|
||||
| `webhook` | POST JSON to `NOTIFICATIONS_WEBHOOK_URL` (+ optional `NOTIFICATIONS_WEBHOOK_AUTH`); both support `${keys.NAME}` + URL allowlists from the ad-hoc-keys system | env var set |
|
||||
|
||||
The webhook channel resolves `${keys.NAME}` server-side — the raw value never enters the agent context.
|
||||
|
||||
## Registering a Custom Channel
|
||||
|
||||
```ts
|
||||
// server/plugins/notifications-slack.ts
|
||||
import { registerNotificationChannel } from "@agent-native/core/notifications";
|
||||
|
||||
export default () => {
|
||||
registerNotificationChannel({
|
||||
name: "slack-ops",
|
||||
async deliver(input, meta) {
|
||||
await fetch(process.env.OPS_SLACK_WEBHOOK!, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ text: `*${input.severity}* — ${input.title}`, owner: meta.owner }),
|
||||
});
|
||||
},
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
Names are unique — re-registering replaces. `deliver()` must be best-effort; a thrown error is logged and ignored. Do NOT call `notify()` from inside a channel (recursion).
|
||||
|
||||
## HTTP API
|
||||
|
||||
Mounted at `/_agent-native/notifications/*` by `core-routes-plugin`, all session-scoped:
|
||||
|
||||
- `GET /notifications?unread=true&limit=50&before=<iso>`
|
||||
- `GET /notifications/count`
|
||||
- `POST /notifications/:id/read`
|
||||
- `POST /notifications/read-all`
|
||||
- `DELETE /notifications/:id`
|
||||
|
||||
## UI
|
||||
|
||||
```tsx
|
||||
import { NotificationsBell } from "@agent-native/core/client/notifications";
|
||||
|
||||
<NotificationsBell browserNotifications />
|
||||
```
|
||||
|
||||
Bell icon + unread badge + lazy-loaded dropdown. Pass `browserNotifications` to also fire system `new Notification(...)` popups for items that arrive after mount (dedups by id, renders an "Enable" prompt until permission is granted, silently no-ops on denied / unsupported). Styled with shadcn tokens — adapts to the host theme.
|
||||
|
||||
## Related
|
||||
|
||||
- `automations` — event-triggered bodies can call `notify`.
|
||||
- `secrets` — `${keys.NAME}` substitution + URL allowlists powering the webhook channel.
|
||||
- `tracking` — analytics; separate concern, don't route through notifications.
|
||||
@@ -0,0 +1,56 @@
|
||||
---
|
||||
name: onboarding
|
||||
description: >-
|
||||
How to register user-facing setup steps (API keys, OAuth, connecting
|
||||
third-party services) for the sidebar setup checklist. Use when adding a
|
||||
feature that needs initial user configuration.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Onboarding Steps
|
||||
|
||||
## Rule
|
||||
|
||||
If a feature requires user-facing setup (API keys, OAuth, connecting a third-party service), register an onboarding step so it appears in the agent sidebar's setup checklist.
|
||||
|
||||
Onboarding must point users to a secure credential path; it must never encode
|
||||
the credential value in source, docs, fixtures, prompts, or generated content.
|
||||
For API keys and service tokens, prefer `registerRequiredSecret()` from the
|
||||
`secrets` skill so the settings UI, encrypted storage, validation, and
|
||||
onboarding checklist stay in one place. For OAuth, check the scoped OAuth token
|
||||
store. Use deployment env vars only for deploy-level configuration, not
|
||||
per-user credentials.
|
||||
|
||||
## Registering a Step
|
||||
|
||||
```ts
|
||||
import { registerOnboardingStep } from "@agent-native/core/onboarding";
|
||||
import { hasOAuthTokens } from "@agent-native/core/oauth-tokens";
|
||||
|
||||
registerOnboardingStep({
|
||||
id: "gmail",
|
||||
order: 100,
|
||||
title: "Connect Gmail",
|
||||
description: "Grant read/send access.",
|
||||
methods: [
|
||||
{
|
||||
id: "oauth",
|
||||
kind: "link",
|
||||
primary: true,
|
||||
label: "Sign in with Google",
|
||||
payload: { url: "/_agent-native/google/auth-url" },
|
||||
},
|
||||
],
|
||||
isComplete: async (ctx) =>
|
||||
ctx?.userEmail ? hasOAuthTokens("google", ctx.userEmail) : false,
|
||||
});
|
||||
```
|
||||
|
||||
See `packages/core/docs/content/onboarding.md` for method kinds and built-in steps.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `adding-a-feature` — The four-area checklist; onboarding is often part of a new integration
|
||||
- `authentication` — Most onboarding steps involve OAuth or credentials
|
||||
@@ -0,0 +1,79 @@
|
||||
---
|
||||
name: performance
|
||||
description: >-
|
||||
Keep app loads and interactions responsive as data grows. Use when a page
|
||||
feels slow, jumps, or lags, or when changing a data read, list, polling path,
|
||||
startup path, or performance-sensitive UI.
|
||||
scope: dev
|
||||
---
|
||||
|
||||
# Performance
|
||||
|
||||
Find the cost that users actually wait on, then reduce it without weakening
|
||||
the result. A slow screen may be waiting on the server, moving too much data,
|
||||
serial reads, repeated computation, or browser rendering; measure before adding
|
||||
caches or extra complexity.
|
||||
|
||||
## Load only what the current view needs
|
||||
|
||||
- Shape list reads around the fields the list displays. Keep large document
|
||||
bodies, histories, rendered output, and other rarely viewed data on a detail
|
||||
or on-demand path. Return a small preview when the list needs one.
|
||||
- Paginate or window unbounded histories and activity feeds. Start with the
|
||||
recent or visible range and load more as the user asks for it.
|
||||
- Batch related reads instead of issuing one query per row. Compute counts and
|
||||
other aggregates in the database when the result can be much smaller than
|
||||
the source rows.
|
||||
- Start independent reads together. Do not make the first useful content wait
|
||||
for unrelated settings, below-the-fold panels, or secondary details.
|
||||
- Index fields used by frequent filters, joins, and sorts when the data and
|
||||
observed query cost justify it. Keep indexes aligned with real query shapes.
|
||||
|
||||
For action-backed screens, shape the action response for the screen's current
|
||||
need and keep the UI on the app's existing action and query hooks. Do not add a
|
||||
second fetch path that duplicates the same read.
|
||||
|
||||
## Keep repeated work cheap
|
||||
|
||||
- Keep list and frequently refreshed reads inexpensive. Avoid parsing,
|
||||
reformatting, or rebuilding large values on every read when the result can be
|
||||
prepared once or computed only for the view that needs it.
|
||||
- Use the app's existing live-update path when fresh data must reach an open
|
||||
screen. Poll only when needed, and keep polled reads bounded and cheap.
|
||||
- Keep large file contents and long records out of list responses. Load them
|
||||
when the user opens the relevant item rather than sending them on every list
|
||||
refresh.
|
||||
- Defer nonessential data and expensive child views until after the main
|
||||
content is usable. Window a rendered list when rendering all rows makes
|
||||
scrolling or updates slow.
|
||||
|
||||
## Protect startup and the first paint
|
||||
|
||||
- Keep migrations, backfills, data scans, aggregations, provider handshakes,
|
||||
and cache warming out of module evaluation and application startup. Hosted
|
||||
serverless instances can restart, so startup work can repeat on user
|
||||
requests. Use the app's deliberate migration, job, or on-demand path.
|
||||
- Keep optional heavy runtimes out of modules loaded by ordinary page requests.
|
||||
Load a browser, media processor, or other large dependency only in the
|
||||
feature or job that needs it, and inspect the deployed bundle when adding
|
||||
one.
|
||||
- Keep the server-rendered shell public and independent of a visitor's session.
|
||||
Resolve user-specific state after the shell loads through the app's
|
||||
authenticated client data path. Reads that must reflect a recent mutation
|
||||
should not depend on cached server-rendered loader data.
|
||||
- Give loading placeholders the final content's basic geometry. Reserve space
|
||||
for content whose size is known; avoid showing a temporary layout that shifts
|
||||
the user's reading position when data arrives.
|
||||
|
||||
## Keep interactions responsive
|
||||
|
||||
Show that an interaction registered as soon as it happens, aiming for 100 ms.
|
||||
If the work needs the network or takes longer, acknowledge it before waiting
|
||||
and show a focused pending state within 400 ms. Use an optimistic update when
|
||||
it is safe, then confirm or roll back on failure.
|
||||
|
||||
When investigating a slow experience, separate server response time, data
|
||||
transfer, serial waits, rendering, layout movement, and long interaction work.
|
||||
Use representative data and the production build when development tooling
|
||||
changes the cost. Verify that the user-visible action completed before
|
||||
comparing timings or memory.
|
||||
@@ -0,0 +1,99 @@
|
||||
---
|
||||
name: progress
|
||||
description: >-
|
||||
Report live progress from long-running agent tasks. Use when a task takes
|
||||
more than a few seconds, so the user can watch status in the runs tray
|
||||
instead of staring at a spinner.
|
||||
---
|
||||
|
||||
# Progress
|
||||
|
||||
## Overview
|
||||
|
||||
`progress_runs` is the framework's "what is the agent doing right now" primitive. The agent starts a run at the top of a long task, updates it as work proceeds, and completes it with a terminal status. The UI renders active runs in a header-bar widget with a percent bar, current step, and spinner/check/X — live visibility into work that would otherwise be opaque.
|
||||
|
||||
Separate concern from `notifications`:
|
||||
|
||||
| | Notifications | Progress |
|
||||
|---|---|---|
|
||||
| Shape | One-shot event — "X happened" | Continuous state — "X is 45% done" |
|
||||
| UI surface | Bell + toast | Runs tray with percent bar |
|
||||
| Lifecycle | Dismissable (read/unread) | Running → terminal (succeeded/failed/cancelled) |
|
||||
|
||||
Common pattern: on completion, emit a `notify()` so the user sees the outcome when they're not actively watching the tray.
|
||||
|
||||
## Tool
|
||||
|
||||
All progress operations go through a single `manage-progress` tool with an `action` parameter:
|
||||
|
||||
| Action | Purpose |
|
||||
|---|---|
|
||||
| `start` | Mark the start of a long task. Returns a runId. |
|
||||
| `update` | Update percent and/or current step. Call frequently. |
|
||||
| `complete` | Mark terminal status: `succeeded`, `failed`, `cancelled`. |
|
||||
| `list` | List recent runs (all or `--active=true`). |
|
||||
|
||||
## Canonical Flow
|
||||
|
||||
```
|
||||
manage-progress --action=start --title "Triage 128 unread emails" --step "Fetching inbox"
|
||||
→ runId=abc
|
||||
|
||||
manage-progress --action=update --runId=abc --percent=25 --step="Classifying 32/128"
|
||||
manage-progress --action=update --runId=abc --percent=75 --step="Drafting replies 97/128"
|
||||
|
||||
manage-progress --action=complete --runId=abc --status=succeeded
|
||||
notify --severity=info --title="Triage done" --body="12 archived, 6 drafts ready to review"
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Start a run for anything > ~5 seconds.** Users want feedback; a spinner with no context feels frozen.
|
||||
- **Update at natural checkpoints**, not every iteration. Every 5–10% is enough for most UIs.
|
||||
- **Always call `manage-progress --action=complete`** at the end — including the error path. An orphaned `running` row is worse than no row.
|
||||
- **Pair with `notify`** on completion. The tray tells users what's *running*; notifications tell them what *finished*.
|
||||
- **Use `metadataJson`** on `manage-progress --action=start` to pass a link back to the produced artifact (thread id, document path), so the UI can deep-link from the runs tray.
|
||||
|
||||
## Runs API
|
||||
|
||||
Mounted at `/_agent-native/runs/*` by `core-routes-plugin`. **Read-only** over HTTP — writes flow through the agent tools:
|
||||
|
||||
| Method | Route |
|
||||
|---|---|
|
||||
| `GET` | `/_agent-native/runs?active=true&limit=50` |
|
||||
| `GET` | `/_agent-native/runs/:id` |
|
||||
| `DELETE` | `/_agent-native/runs/:id` |
|
||||
|
||||
## UI Surface
|
||||
|
||||
Ships as `<RunsTray />` at `@agent-native/core/client/progress`:
|
||||
|
||||
```tsx
|
||||
import { RunsTray } from "@agent-native/core/client/progress";
|
||||
|
||||
export function HeaderBar() {
|
||||
return (
|
||||
<header className="flex items-center gap-2">
|
||||
{/* … */}
|
||||
<RunsTray />
|
||||
</header>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
Inline header widget — mount next to the notifications bell. Shows a spinner icon + count badge when runs are active; click opens a dropdown with a live percent bar per run. Hides the trigger entirely when no active runs. Polls `active=true` every `pollMs` (default 3s).
|
||||
|
||||
## Event Bus Integration
|
||||
|
||||
Two events emit on the bus so automations can react:
|
||||
|
||||
- `run.progress.started` — `{ runId, title, step? }`
|
||||
- `run.progress.updated` — `{ runId, percent, step, status }`
|
||||
|
||||
Example automation: *"when a run takes longer than 5 minutes, notify me."*
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `notifications` — fire one when a run finishes so the user sees the outcome.
|
||||
- `automations` — subscribe to `run.progress.updated` to build watchdogs on slow runs.
|
||||
- `delegate-to-agent` — if you're delegating a long task, start a run on the delegator side so the caller has visibility.
|
||||
@@ -0,0 +1,392 @@
|
||||
---
|
||||
name: real-time-collab
|
||||
description: >-
|
||||
Multi-user collaborative editing with Yjs CRDT, SSE fast-path transport, and
|
||||
granular server-side merge. Use when adding real-time collaborative editing to
|
||||
a template, debugging sync issues, or understanding how the agent and humans
|
||||
edit documents simultaneously.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Real-Time Collaboration
|
||||
|
||||
## Rule
|
||||
|
||||
Collaborative editing uses Yjs CRDT via TipTap. The agent and human users are
|
||||
equal participants — both edit the same Y.Doc and changes merge cleanly without
|
||||
conflicts. Always choose an explicit `access` mode on `createCollabPlugin`.
|
||||
|
||||
## How It Works
|
||||
|
||||
- **`Y.Doc`** stores the document as a `Y.XmlFragment` (ProseMirror node tree)
|
||||
- **TipTap's Collaboration extension** binds the editor to the Y.XmlFragment
|
||||
via `ySyncPlugin`
|
||||
- **CollaborationCaret extension** renders remote users' cursors with names and
|
||||
colors
|
||||
- **SSE fast-path** — `/_agent-native/poll-events` `EventSource` delivers collab
|
||||
events push-style; while SSE is healthy the collab poll interval relaxes to
|
||||
~12 s
|
||||
- **Polling fallback** — `/_agent-native/poll` is polled every 2 s when SSE is
|
||||
unavailable; this is the universal serverless fallback
|
||||
- **Update batching** — local Yjs updates are debounced ~80 ms and coalesced
|
||||
with `Y.mergeUpdates` before sending; flushed immediately on
|
||||
`visibilitychange` / `pagehide`
|
||||
- **SQL `_collab_docs` table** persists Yjs state as base64 (SQLite/Postgres
|
||||
compatible). Tombstone compaction fires automatically when the stored blob
|
||||
exceeds 4× the fresh encoded size.
|
||||
|
||||
## Agent + Human Editing
|
||||
|
||||
1. **Human edits** → TipTap → ySyncPlugin → Y.XmlFragment → `POST /_agent-native/collab/:docId/update`
|
||||
2. **Agent edits** → action edits canonical SQL content + bumps `updatedAt` → change-sync refetch → the open editor reconciles the new content into the live Y.Doc (see below) → poll update → all clients
|
||||
|
||||
Both produce Yjs operations that merge cleanly. Agent edits appear without
|
||||
destroying cursor position, selection, or undo history.
|
||||
|
||||
The agent does **not** push edits into Yjs in-process and does **not** call any
|
||||
localhost probe — those approaches silently no-op on serverless (the action runs
|
||||
in a different process). The peer-editor model below replaced them.
|
||||
|
||||
## Agent Edits As A Real-Time Peer Editor
|
||||
|
||||
**SQL is the durable source of truth for document body content.** The agent
|
||||
action edits the canonical content column and bumps `updatedAt`. No localhost
|
||||
calls, no in-process Yjs mutation.
|
||||
|
||||
**The open editor reconciles authoritative external content into the live
|
||||
Y.Doc.** The `updatedAt` bump flows through change-sync, which refetches the
|
||||
record. The lead client applies the new content via `setContent`, producing Yjs
|
||||
operations that merge with concurrent human edits. Every connected client
|
||||
receives the result through normal Yjs sync.
|
||||
|
||||
### The `updatedAt` gate
|
||||
|
||||
```ts
|
||||
// In the editor's reconcile effect
|
||||
if (loaded.updatedAt > lastAppliedUpdatedAt.current) {
|
||||
applyAuthoritativeContent(loaded.content); // adopt
|
||||
lastAppliedUpdatedAt.current = loaded.updatedAt;
|
||||
}
|
||||
// else: lagging poll / stale snapshot → ignore
|
||||
```
|
||||
|
||||
Without the gate, a slightly-behind poll response re-applies old content and
|
||||
the edit "reverts on next poll". A fresh mount always adopts whatever content
|
||||
it loaded.
|
||||
|
||||
### Lead-client election
|
||||
|
||||
Exactly ONE connected client applies the authoritative snapshot; the rest
|
||||
receive it through Yjs sync:
|
||||
|
||||
```ts
|
||||
import { isReconcileLeadClient } from "@agent-native/core/client/collab";
|
||||
|
||||
if (
|
||||
loaded.updatedAt > lastAppliedUpdatedAt.current &&
|
||||
isReconcileLeadClient(awareness, ydoc.clientID)
|
||||
) {
|
||||
applyAuthoritativeContent(loaded.content);
|
||||
}
|
||||
```
|
||||
|
||||
The agent's awareness entry (`AGENT_CLIENT_ID`, max int) can never be the
|
||||
lead. A sole client is always the lead. The election is deterministic with no
|
||||
coordination round-trip.
|
||||
|
||||
### v1 limitation
|
||||
|
||||
Full-content reconcile is **last-writer-wins** for the rare case where a human
|
||||
has unsaved edits in the exact region the agent simultaneously rewrites. Edits
|
||||
in **different** regions merge fine through the CRDT.
|
||||
|
||||
## Security
|
||||
|
||||
### Always choose an explicit access mode
|
||||
|
||||
Inspect the schema and sharing registration before configuring collaboration:
|
||||
|
||||
- For owned or shareable records, use `mode: "resource"` and the resource type
|
||||
registered through `registerShareableResource`.
|
||||
- For records deliberately visible to every authenticated user on the
|
||||
deployment, use `mode: "all-authenticated"`.
|
||||
- Never invent a `resourceType` merely to silence a warning. Resource mode is
|
||||
correct only when the matching ownership and sharing model exists.
|
||||
|
||||
```ts
|
||||
// server/plugins/collab.ts
|
||||
import { createCollabPlugin } from "@agent-native/core/server";
|
||||
|
||||
export default createCollabPlugin({
|
||||
table: "documents",
|
||||
contentColumn: "content",
|
||||
idColumn: "id",
|
||||
access: { mode: "resource", resourceType: "document" },
|
||||
});
|
||||
```
|
||||
|
||||
For intentionally deployment-wide authenticated collaboration:
|
||||
|
||||
```ts
|
||||
createCollabPlugin({
|
||||
table: "todos",
|
||||
contentColumn: "content",
|
||||
access: { mode: "all-authenticated" },
|
||||
});
|
||||
```
|
||||
|
||||
Omitting `access` is supported only for legacy compatibility and is deprecated.
|
||||
It behaves like `all-authenticated`, logs a warning, and is flagged by Doctor.
|
||||
Choose the mode explicitly so access intent is reviewable.
|
||||
|
||||
Non-owner sharees who have explicit access fall back to state-vector catch-up
|
||||
(safe, slightly higher latency). Awareness routes require the same viewer
|
||||
access as read routes.
|
||||
|
||||
### Payload limits
|
||||
|
||||
Write routes reject payloads exceeding `maxPayloadBytes` (default 2 MB) with
|
||||
HTTP 413. Override:
|
||||
|
||||
```ts
|
||||
createCollabPlugin({
|
||||
access: { mode: "resource", resourceType: "document" },
|
||||
maxPayloadBytes: 512 * 1024,
|
||||
});
|
||||
```
|
||||
|
||||
## Enabling Collaboration
|
||||
|
||||
### 1. Install packages
|
||||
|
||||
```bash
|
||||
pnpm add @tiptap/extension-collaboration @tiptap/extension-collaboration-caret @tiptap/y-tiptap @tiptap/core
|
||||
```
|
||||
|
||||
### 2. Add collab server plugin (with explicit access)
|
||||
|
||||
```ts
|
||||
// server/plugins/collab.ts
|
||||
import { createCollabPlugin } from "@agent-native/core/server";
|
||||
|
||||
export default createCollabPlugin({
|
||||
table: "documents",
|
||||
contentColumn: "content",
|
||||
idColumn: "id",
|
||||
access: { mode: "resource", resourceType: "document" },
|
||||
});
|
||||
```
|
||||
|
||||
### 3. Use the client hook
|
||||
|
||||
```ts
|
||||
import { useCollaborativeDoc, emailToColor, emailToName } from "@agent-native/core/client/collab";
|
||||
|
||||
const { ydoc, awareness, activeUsers, agentActive, agentPresent } =
|
||||
useCollaborativeDoc({
|
||||
docId: documentId,
|
||||
requestSource: TAB_ID,
|
||||
user: {
|
||||
name: emailToName(session.email),
|
||||
email: session.email,
|
||||
color: emailToColor(session.email),
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
### 4. Add TipTap extensions
|
||||
|
||||
```ts
|
||||
import { Collaboration } from "@tiptap/extension-collaboration";
|
||||
import { CollaborationCaret } from "@tiptap/extension-collaboration-caret";
|
||||
|
||||
const editor = useEditor({
|
||||
extensions: [
|
||||
StarterKit.configure({ history: false }), // Yjs handles undo
|
||||
Collaboration.configure({ document: ydoc }),
|
||||
CollaborationCaret.configure({
|
||||
provider: { awareness },
|
||||
user: { name: session.email, color: "#6366f1" },
|
||||
}),
|
||||
],
|
||||
// Do NOT pass content — Yjs owns it
|
||||
});
|
||||
```
|
||||
|
||||
### 5. Add to vite.config.ts optimizeDeps
|
||||
|
||||
```ts
|
||||
optimizeDeps: {
|
||||
include: [
|
||||
"yjs",
|
||||
"y-protocols/awareness",
|
||||
"@tiptap/core",
|
||||
"@tiptap/extension-collaboration",
|
||||
"@tiptap/extension-collaboration-caret",
|
||||
"@tiptap/y-tiptap",
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
## Collab Routes (auto-mounted)
|
||||
|
||||
| Route | Purpose |
|
||||
| ----- | ------- |
|
||||
| `GET /_agent-native/collab/:docId/state` | Fetch full Y.Doc state (accepts `?stateVector=` for diff) |
|
||||
| `POST /_agent-native/collab/:docId/update` | Apply client Yjs update |
|
||||
| `POST /_agent-native/collab/:docId/text` | Apply full text (diff-based) |
|
||||
| `POST /_agent-native/collab/:docId/search-replace` | Surgical find/replace in Y.XmlFragment |
|
||||
| `POST /_agent-native/collab/:docId/json` | Apply full JSON diff to Y.Map/Y.Array |
|
||||
| `GET /_agent-native/collab/:docId/json` | Read current JSON state |
|
||||
| `POST /_agent-native/collab/:docId/patch` | Surgical JSON patch ops |
|
||||
| `POST /_agent-native/collab/:docId/awareness` | Sync cursor/presence state |
|
||||
| `GET /_agent-native/collab/:docId/users` | List active users |
|
||||
|
||||
## Granular Server-Side Merge Pattern
|
||||
|
||||
For structured documents (slides, forms, design files) where body collab would
|
||||
cause LWW conflicts at the container level, use **granular server-side merge**:
|
||||
define an action with targeted per-item operations.
|
||||
|
||||
**When to use granular merge vs body collab:**
|
||||
|
||||
| Scenario | Recommended approach |
|
||||
| -------- | -------------------- |
|
||||
| Free-form rich text, cursor-level CRDT matters | Body collab (Y.XmlFragment + TipTap) |
|
||||
| Structured items (slides, fields) where different users edit different items | Granular server-side merge (action with patch ops) |
|
||||
|
||||
Example operation shape for slides:
|
||||
|
||||
```ts
|
||||
type PatchDeckOp =
|
||||
| { type: "patch"; slideId: string; fields: Partial<SlideFields> }
|
||||
| { type: "add"; position: number; slide: SlideData }
|
||||
| { type: "delete"; slideId: string }
|
||||
| { type: "reorder"; slideId: string; newIndex: number };
|
||||
```
|
||||
|
||||
Concurrent edits to different slides both succeed at the action level; there
|
||||
is no whole-deck LWW. Forms use the same shape with field-level ops.
|
||||
|
||||
## Agent Presence & Lingering Edit Highlights
|
||||
|
||||
The agent is a *visible* collaborator, not a silent content-swapper. Core
|
||||
handles most of this automatically:
|
||||
|
||||
- **Auto-presence on agent writes** — any `applyText` / `searchAndReplace` /
|
||||
`applyJson` / `applyPatchOps` call with `requestSource: "agent"` publishes
|
||||
an agent awareness entry plus a `recentEdits` attribution describing what
|
||||
changed. Actions that route writes through the collab layer get full
|
||||
presence UX with zero extra wiring.
|
||||
- **Linger** — `agentLeaveDocument` (and the auto-presence path) keeps the
|
||||
agent's awareness entry alive for ~6s (`AGENT_PRESENCE_LINGER_MS`) after the
|
||||
last edit so viewers see who just changed what. Pass `{ lingerMs: 0 }` to
|
||||
clear immediately. On serverless the linger degrades to the 30s awareness
|
||||
expiry.
|
||||
- **`agentTouchDocument(docId, { edit, metadata })`** — refcount-neutral
|
||||
presence + attribution for actions that write SQL directly (no collab doc).
|
||||
`edit.descriptor` is one of `{kind:"text",quote}`, `{kind:"selector",selector}`,
|
||||
`{kind:"paths",paths}`, `{kind:"doc"}`.
|
||||
- **Durable across instances** — awareness is mirrored to the additive
|
||||
`_collab_awareness` table, so presence written by an action in one
|
||||
serverless invocation is visible to clients polling any other instance.
|
||||
|
||||
Client rendering:
|
||||
|
||||
```tsx
|
||||
import {
|
||||
usePresence, useRecentEdits, RecentEditHighlights,
|
||||
PresenceBar, LiveCursorOverlay, RemoteSelectionRings,
|
||||
} from "@agent-native/core/client/collab";
|
||||
|
||||
const { others, setPresence } = usePresence(awareness, ydoc?.clientID);
|
||||
const recentEdits = useRecentEdits(others); // non-expired, ~6s TTL
|
||||
|
||||
<RecentEditHighlights
|
||||
edits={recentEdits}
|
||||
containerRef={containerRef}
|
||||
resolveRect={(edit) => /* map descriptor → DOMRect, or null */ null}
|
||||
/>
|
||||
```
|
||||
|
||||
Humans get the same treatment: call `publishRecentEdit(awareness, { descriptor })`
|
||||
from local mutation paths so peers see lingering highlights for human edits
|
||||
too. `CollabUser.avatarUrl` puts faces on avatars, cursors, and edit tags.
|
||||
|
||||
## Per-User Undo (never revert someone else's work)
|
||||
|
||||
Undo must only reverse the local user's edits — and must never restore a
|
||||
whole-document snapshot (that clobbers concurrent edits by peers/the agent).
|
||||
Core ships two primitives:
|
||||
|
||||
**Yjs surfaces — `useCollabUndo`** (wraps `Y.UndoManager` lifecycle):
|
||||
|
||||
```ts
|
||||
import { useCollabUndo } from "@agent-native/core/client/collab";
|
||||
|
||||
const { undo, redo, canUndo, canRedo, transactLocal, localOrigin } =
|
||||
useCollabUndo({
|
||||
ydoc,
|
||||
scope: (doc) => doc.getText("content"),
|
||||
captureTimeout: 500,
|
||||
enableKeyboardShortcuts: true, // Mod+Z / Shift+Mod+Z / Mod+Y
|
||||
});
|
||||
|
||||
// Tag every local mutation so it is captured:
|
||||
transactLocal(() => { /* mutate shared types */ });
|
||||
```
|
||||
|
||||
Remote (`"remote"`) and agent (`"agent"`/`"server"`) origins are never
|
||||
captured. The manager is recreated/destroyed automatically when `ydoc`
|
||||
changes. (TipTap's Collaboration extension already provides this behavior
|
||||
for its own editor content.)
|
||||
|
||||
**Op-based surfaces (slides/forms) — `useLocalOpUndo`**: record inverse
|
||||
granular ops for each local mutation; undo replays the inverse ops through
|
||||
your normal granular mutation path:
|
||||
|
||||
```ts
|
||||
const { push, undo, redo, canUndo, canRedo } = useLocalOpUndo({
|
||||
apply: (ops) => applyGranularOps(ops), // your patch path
|
||||
});
|
||||
|
||||
push({
|
||||
undo: [{ type: "patch", slideId, fields: prevFields }],
|
||||
redo: [{ type: "patch", slideId, fields: nextFields }],
|
||||
coalesceKey: `${slideId}:content`, // merge rapid bursts into one step
|
||||
});
|
||||
```
|
||||
|
||||
Entries whose target no longer exists should fail soft (skip), never reset
|
||||
the whole history — external/agent edits must not wipe the user's undo stack.
|
||||
|
||||
## Common Pitfalls
|
||||
|
||||
- **Missing `access`** — Legacy omission behaves like `all-authenticated`, logs
|
||||
a startup warning, and is flagged by Doctor. Choose `resource` for records
|
||||
backed by ownership/sharing, or explicit `all-authenticated` for intentionally
|
||||
deployment-wide records. Never invent a resource type to silence the warning.
|
||||
- **Don't pass `content` as a TipTap prop** when Collaboration is enabled —
|
||||
Yjs owns the content. Seed via `editor.commands.setContent()` only when the
|
||||
Y.XmlFragment is empty.
|
||||
- **Don't call `editor.setContent()` ad hoc for agent edits** — the only
|
||||
sanctioned `setContent` is gated by `updatedAt` and guarded by
|
||||
`isReconcileLeadClient`. Calling it from elsewhere duplicates content across
|
||||
the CRDT or re-applies stale snapshots.
|
||||
- **Add packages to `optimizeDeps`** — Vite won't pre-bundle Yjs correctly
|
||||
otherwise, causing runtime errors in dev.
|
||||
- **One `Y.Doc` per document** — Don't create multiple Y.Doc instances for the
|
||||
same document ID. `useCollaborativeDoc` caches by ID.
|
||||
- **Destroy Y.UndoManager on doc change** — Stale managers hold Y.Doc
|
||||
references and grow unboundedly. Recreate on `docId` change.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- `real-time-sync` — The change-sync system that delivers the `updatedAt` bump
|
||||
driving editor reconciliation; also `useReconciledState` for non-Yjs surfaces
|
||||
- `storing-data` — The `_collab_docs` table and SQL canonical content
|
||||
- `security` — `registerShareableResource`, `resolveAccess`, `assertAccess`
|
||||
- `self-modifying-code` — Agent edits to collaborative documents edit canonical
|
||||
SQL content, not raw Yjs
|
||||
@@ -0,0 +1,146 @@
|
||||
---
|
||||
name: real-time-sync
|
||||
description: >-
|
||||
Decide whether a page needs external changes before refresh, then use the
|
||||
opt-in shared SSE and polling transport safely.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Real-Time Sync
|
||||
|
||||
## Decision rule
|
||||
|
||||
Opt in only when both are true:
|
||||
|
||||
1. The data can change without the current user acting.
|
||||
2. The user needs to see that change before refreshing or navigating.
|
||||
|
||||
A local agent edit does not meet this rule. The chat run stream already
|
||||
invalidates action queries and source counters after each side-effecting tool
|
||||
and again at run end, without opening a background poll.
|
||||
|
||||
### Opt in
|
||||
|
||||
- **Slides deck editor:** another collaborator can edit the open deck.
|
||||
- **Mail inbox:** new mail can arrive while the inbox is open.
|
||||
- **A watched job:** a background job changes progress while the user watches it.
|
||||
- **Cross-tab state:** state must converge across this user's open tabs without a
|
||||
new action.
|
||||
|
||||
### Keep it off
|
||||
|
||||
- Public, anonymous, marketing, docs, and SSR pages.
|
||||
- Settings, forms, and read-mostly lists or dashboards. Refresh them on focus or
|
||||
navigation instead.
|
||||
- Single-user agent edits. The chat run stream handles those.
|
||||
- Pages where an update is useful eventually but not before the next refresh.
|
||||
|
||||
## Cost and behavior
|
||||
|
||||
`useDbSync()` has no background transport unless the page opts in with a
|
||||
non-empty reason. One transport is shared per tab. A visible opted-in tab polls
|
||||
at 1 minute, then 2, then 5 minutes while idle; user activity or a local
|
||||
mutation resets that sequence. Hidden tabs pause by default. During an active
|
||||
agent run, opted-in sync can poll at its configured `interval`; local tool
|
||||
completion and run-end invalidation do not depend on that poll.
|
||||
|
||||
On a long-lived host, same-process changes stream over
|
||||
`/_agent-native/events`; polling is the cross-process fallback. On a production
|
||||
serverless host, the local events endpoint refuses the long-lived stream and
|
||||
`/_agent-native/poll` carries remote changes. The paid Hosted Realtime Sync
|
||||
Gateway is not required for this pattern.
|
||||
|
||||
While a collab doc shows another person present, the transport polls every
|
||||
2.5 s instead (`acquireCollabPollBoost()`, held by the collab client, not by
|
||||
pages). It is a no-op whenever a stream is connected, lapses after 3 minutes
|
||||
without input or remote events, and never applies to lone tabs.
|
||||
|
||||
## Use the hook
|
||||
|
||||
Declare the reason beside the route gate so reviewers can see why the page pays
|
||||
for remote sync:
|
||||
|
||||
```tsx
|
||||
useDbSync({
|
||||
queryClient,
|
||||
realtime: isPrivateDeckEditorPath(location.pathname)
|
||||
? { reason: "other collaborators can edit this deck while it is open" }
|
||||
: undefined,
|
||||
pauseWhenHidden: true,
|
||||
});
|
||||
```
|
||||
|
||||
The reason is required by the TypeScript API. Opt in only for a named private
|
||||
or authenticated route; public, documentation, and SSR pages should not start a
|
||||
background transport.
|
||||
|
||||
An opted-in page only hears about an action when its change event reaches the
|
||||
current user. By default an `action` event reaches the actor alone, so a
|
||||
collaborator's comment, save, or agent edit never arrives. Declare
|
||||
`changeResource: (input, result) => ({ resourceType, resourceId })` on the
|
||||
mutating action and the event also reaches everyone who can read that resource.
|
||||
Name it from `input` when the call carries the resource id (Content's
|
||||
`documentChangeResource`, Slides' comment actions) and from `result` when the
|
||||
call is keyed by a child id (Design's `designChangeResource` for
|
||||
`delete-file`); return `null` for a call that changed nothing. Do not publish a
|
||||
parallel per-template event for the same purpose.
|
||||
|
||||
Do not start `subscribeSyncEvents()` or an `EventSource` in a feature to bypass
|
||||
the decision. `subscribeSyncEvents()` is a lower-level transport subscription
|
||||
used by the existing Yjs collaboration client and narrow framework plumbing.
|
||||
Keep Yjs collaborative editing on its existing channel.
|
||||
|
||||
## Query freshness
|
||||
|
||||
Prefer `useActionQuery()` for action-backed data. Mutating actions refresh local
|
||||
action observers; the chat run stream also invalidates them for agent tool
|
||||
side effects. Raw queries should include the relevant source counters:
|
||||
|
||||
```tsx
|
||||
const versions = useChangeVersions(["dashboards", "action"]);
|
||||
useQuery({
|
||||
queryKey: ["dashboard", id, versions],
|
||||
queryFn: () => fetchDashboard(id),
|
||||
placeholderData: (previous) => previous,
|
||||
});
|
||||
```
|
||||
|
||||
That covers local chat-run edits. Remote edits reach the counter through
|
||||
`useDbSync()` only on an opted-in page. Use `useReconciledState` when a form or
|
||||
inline editor copies a query value into local state so incoming data does not
|
||||
replace active typing.
|
||||
|
||||
URL commands (`__set_url__`, `set-url`, and `set-search-params`) and
|
||||
`refresh-screen` also flow through local chat events. The sidebar listens for
|
||||
screen refresh only while its panel is open or a chat run is active; public docs
|
||||
can disable that boundary with `screenRefreshEnabled={false}`.
|
||||
|
||||
## Source counters
|
||||
|
||||
On local tool completion, `useDbSync()` advances the action counter and any
|
||||
other raw-query source counters currently observed by the page. Generic tool
|
||||
completion events do not identify their data domain, so keep raw-query source
|
||||
lists narrow. Remote sync events advance their specific source counters.
|
||||
|
||||
| Source | Changed by |
|
||||
| --- | --- |
|
||||
| `action` | A successful mutating action or local chat-run side-effect completion |
|
||||
| `app-state` | Writes to `application_state`, including URL commands |
|
||||
| `settings` | Writes to `settings` |
|
||||
| `dashboards`, `analyses`, `extensions` | Domain-specific mutations that emit those sources |
|
||||
| `collab` | Yjs collaborative document updates |
|
||||
| `screen-refresh` | The explicit `refresh-screen` agent tool |
|
||||
|
||||
Use `useChangeVersions()` when one query depends on more than one source.
|
||||
|
||||
## Avoid
|
||||
|
||||
- Do not create manual polling loops or a second `EventSource`.
|
||||
- Do not enable background sync for a whole app root when only one private
|
||||
route needs remote updates.
|
||||
- Do not assume a successful local action is a reason for a background
|
||||
subscriber; use local mutation invalidation and the chat run stream.
|
||||
- Do not blanket-invalidate template queries when a source-versioned query or
|
||||
action-backed query can target the refreshed data.
|
||||
@@ -0,0 +1,72 @@
|
||||
---
|
||||
name: reliable-mutations
|
||||
description: >-
|
||||
How the agent must perform writes so they actually persist under the hosted
|
||||
foreground run budget and long-running background handoffs. Use whenever you
|
||||
create, update, delete, or batch-write app data — especially "do this for many
|
||||
items" loops, or any task where the user expects N things to end up saved.
|
||||
scope: dev
|
||||
---
|
||||
|
||||
# Reliable Mutations
|
||||
|
||||
## Rule
|
||||
|
||||
Make a change in **one atomic call** when the action supports it, then **verify
|
||||
the persisted end state and report concrete proof** (counts/ids). Never drive a
|
||||
multi-step change by looping many small writes, and never report success from a
|
||||
tool ✓ alone.
|
||||
|
||||
## Why
|
||||
|
||||
Hosted foreground agent runs have a short soft budget so they can hand off
|
||||
cleanly under synchronous serverless walls. Durable background runs get a much
|
||||
longer budget, but they still should not rely on loops of many small writes:
|
||||
continuations can retry the same intent and leave partial state if each item is
|
||||
committed separately. One atomic call commits or fails as a unit; verification
|
||||
turns a hopeful ✓ into a fact.
|
||||
|
||||
## How
|
||||
|
||||
1. **Prefer a single atomic call.** If an action accepts the whole set (add
|
||||
many, set all, bulk update), pass the full batch in one call so it commits
|
||||
atomically. Check the action surface for a batch/plural form before reaching
|
||||
for a loop.
|
||||
2. **Do not loop many small writes under any run budget.** A sequence of N
|
||||
per-item writes can still leave partial or no state when a foreground run
|
||||
hands off, a background run continues, or an upstream provider fails. If no
|
||||
batch action exists, that is a gap in the action layer — add or extend an
|
||||
action that accepts the batch (see the `actions` skill) rather than papering
|
||||
over it with a loop.
|
||||
3. **Verify the end state after writing.** Re-read the data (a list/read action,
|
||||
a count query) and confirm the result matches intent — the right number of
|
||||
rows, the expected ids/fields. Do this before you tell the user it worked,
|
||||
and include the relevant verification expectation in the app's `AGENTS.md`.
|
||||
4. **Report proof-of-done, not vibes.** State concrete evidence: "saved 12 of 12
|
||||
panels (ids …)" or "updated 5 rows". Do not infer success from the presence
|
||||
of a tool ✓ on an individual call.
|
||||
5. **On a time-budget cutoff, fail loud.** If the turn is cut before the change
|
||||
is fully committed and verified, say so explicitly and report what *did*
|
||||
persist (M of N) and what remains. Never round a partial or unverified write
|
||||
up to "done".
|
||||
|
||||
## Don't
|
||||
|
||||
- Don't loop `for each item: write(item)` for a large set in a single hosted
|
||||
turn.
|
||||
- Don't claim completion because every tool call returned ✓ — a ✓ on an aborted
|
||||
chunk does not mean the row was committed.
|
||||
- Don't silently shrink the scope ("I added a few of them") and present it as the
|
||||
finished task.
|
||||
- Don't try to "fix" this by asking for a longer run timeout — the budget is
|
||||
correct; restructure the write instead.
|
||||
|
||||
## Related
|
||||
|
||||
- `actions` — define or extend a batch/atomic action when only per-item writes
|
||||
exist.
|
||||
- `storing-data` — where app data lives and how reads/writes are scoped.
|
||||
- `performance` — avoid query waterfalls when verifying end state.
|
||||
- Design doc: `packages/core/docs/design/durable-agent-runs.md` — the real
|
||||
ceiling fix (checkpointed and durable runs); this skill is the agent-facing
|
||||
mitigation that reduces how often the ceiling is hit.
|
||||
@@ -0,0 +1,82 @@
|
||||
---
|
||||
name: secrets
|
||||
description: >-
|
||||
Connect external services and keep app credentials scoped. Use before adding
|
||||
an API key, OAuth connection, provider setup, or server-side request that
|
||||
needs a user's or workspace's credential.
|
||||
scope: dev
|
||||
---
|
||||
|
||||
# Secrets
|
||||
|
||||
## Rule
|
||||
|
||||
Credentials belong to the user, organization, workspace, or deployment that
|
||||
owns them. Reuse the strongest shared connection or credential flow available;
|
||||
never copy a value into app code or client-visible state.
|
||||
|
||||
## Choose the credential source
|
||||
|
||||
1. Check the workspace connection catalog first. If the provider is already
|
||||
connected, request the app grant and resolve its vault-backed credential
|
||||
reference through the workspace-connection API.
|
||||
2. For OAuth, use the shared authorization and token flow. Do not store access
|
||||
or refresh tokens as ordinary settings or API-key values.
|
||||
3. If the app truly needs its own API key, register it with the shared secrets
|
||||
surface. Do not build a parallel key form or storage table.
|
||||
4. Use deployment configuration only for a secret owned by the deployed app,
|
||||
such as a webhook verification secret. LLM inference keys are an app-owned
|
||||
exception: self-hosted apps may use provider keys from deployment env as a
|
||||
shared fallback, while scoped user or organization keys take precedence.
|
||||
Hosted-workspace deployments backed by a shared database must not share
|
||||
those env keys across apps or tenants. This exception does not authorize
|
||||
using env credentials to access user-owned provider data.
|
||||
|
||||
## Register an app-local API key
|
||||
|
||||
Register the key once so Settings can manage it and the app can describe why it
|
||||
is needed. Supported scopes are `user`, `org`, and `workspace`; choose the
|
||||
narrowest scope that matches who owns the credential and how the app resolves
|
||||
it. Put the registration in a server module imported by a loaded server plugin.
|
||||
|
||||
```ts
|
||||
import { registerRequiredSecret } from "@agent-native/core/secrets";
|
||||
|
||||
registerRequiredSecret({
|
||||
key: "EXAMPLE_SERVICE_API_KEY",
|
||||
label: "Example service API key",
|
||||
description: "Connects this app to the example service.",
|
||||
docsUrl: "https://example.com/api-keys",
|
||||
scope: "user",
|
||||
kind: "api-key",
|
||||
required: true,
|
||||
});
|
||||
```
|
||||
|
||||
Use `kind: "oauth"` for an OAuth-backed connection and set `oauthProvider` and
|
||||
`oauthConnectUrl` for the shared Connect flow. Set `required` only when the app
|
||||
cannot perform its primary workflow without that connection. A validator may
|
||||
check a key before save; never log or include the value in a validation error.
|
||||
|
||||
## Resolve credentials on the server
|
||||
|
||||
Resolve credentials only inside server-side actions or server helpers, using
|
||||
the request's user and organization context. Keep a missing key separate from
|
||||
a failed credential-store lookup: ask the user to connect the provider only
|
||||
when the credential is absent; make a store failure retryable.
|
||||
|
||||
For an app-local key, use `resolveSecretDetailed()` from
|
||||
`@agent-native/core/server` in the request context. Check `lookupFailed` before
|
||||
checking `value`; do not turn a failed lookup into a setup prompt.
|
||||
|
||||
Never read a user's or workspace's API key from `process.env`, or add a raw
|
||||
environment fallback to a scoped lookup. Do not put credentials in action
|
||||
arguments or results, agent messages or hidden context, application state,
|
||||
browser storage, client bundles, logs, or error text. Send them only in the
|
||||
provider request that needs them, and redact provider responses before
|
||||
returning an error.
|
||||
|
||||
## Related skills
|
||||
|
||||
- `security` — protect access to app data and external requests.
|
||||
- `actions` — expose server-side operations to both the agent and UI.
|
||||
@@ -0,0 +1,80 @@
|
||||
---
|
||||
name: security
|
||||
description: >-
|
||||
Secure app data, actions, routes, and external input. Use when changing
|
||||
authentication, authorization, database access, uploads, untrusted content,
|
||||
or server-side requests to user-provided URLs.
|
||||
scope: dev
|
||||
---
|
||||
|
||||
# Security
|
||||
|
||||
## Rule
|
||||
|
||||
Treat each action, route, query, and external request as a trust boundary.
|
||||
Validate inputs, check the caller's authority for every row, and fail closed
|
||||
when access cannot be established.
|
||||
|
||||
## Validate input and queries
|
||||
|
||||
- Define action inputs with a Zod `schema`; validate data from forms, URLs,
|
||||
providers, and files before using it.
|
||||
- Build database queries with Drizzle. For raw SQL, bind values as parameters;
|
||||
never concatenate user input into SQL text.
|
||||
- Keep large uploads and file contents in file storage. Store only their
|
||||
returned ids or URLs in SQL.
|
||||
|
||||
## Authorize rows and actions
|
||||
|
||||
Choose a table's access model when designing its data:
|
||||
|
||||
| Data | Access model |
|
||||
| --- | --- |
|
||||
| Private user rows | Store `owner_email` and filter every read and write by the current caller. |
|
||||
| Organization-wide catalog | Store `org_id` and scope action queries to the active org; gate restricted mutations by org or app role. |
|
||||
| Team-shared or individually shareable resources | Use `ownableColumns()`, register the resource type, and check access with the sharing helpers. |
|
||||
| Child rows | Check access to the parent before reading or changing children; add any child-specific rules in the action. |
|
||||
|
||||
Do not make a team-wide catalog private by adding a per-user owner filter. For
|
||||
an organization-owned catalog, `org_id` without `owner_email` is valid: scoped
|
||||
database tools expose only the active organization's rows, while app actions
|
||||
still need their own org filter and authorization. For resources users can
|
||||
share, use these helpers:
|
||||
|
||||
- Add `accessFilter(table, sharesTable)` to list and read-many queries.
|
||||
- Use `resolveAccess(type, id)` for an optional read by id, or
|
||||
`assertAccess(type, id, role)` before a read or write that requires access.
|
||||
- Use an action's `authorize` gate for role-wide restrictions. It decides who
|
||||
may call the operation; it does not replace row-level access checks.
|
||||
|
||||
Prefer actions for normal app data. A custom HTTP route is appropriate for
|
||||
protocols such as uploads, streaming, webhooks, OAuth callbacks, or public
|
||||
unauthenticated resources. An authenticated custom route must establish the
|
||||
session/request context and apply the same row-level access checks as an action.
|
||||
|
||||
## Handle untrusted content and URLs
|
||||
|
||||
- React escapes rendered text. Do not pass untrusted content to
|
||||
`dangerouslySetInnerHTML`, `innerHTML`, `eval`, or `document.write`.
|
||||
- Use `ssrfSafeFetch` from `@agent-native/core/extensions/url-safety` for
|
||||
server-side requests to user- or agent-controlled URLs. It checks private
|
||||
network destinations and redirects.
|
||||
- Treat provider error bodies and uploaded files as untrusted input. Return a
|
||||
useful, bounded error to the user without exposing internal details.
|
||||
|
||||
## Protect credentials and consequential actions
|
||||
|
||||
Never put credential values in source, prompts, action arguments or results,
|
||||
application state, client bundles, logs, or error messages. Use the shared
|
||||
credential flow in the `secrets` skill.
|
||||
|
||||
For a genuinely high-consequence outward action, such as sending a message,
|
||||
charging a payment method, or publishing publicly, use `needsApproval` to ask
|
||||
the user to approve that call. Approval does not grant access: keep the normal
|
||||
`authorize` and row-level checks as well.
|
||||
|
||||
## Related skills
|
||||
|
||||
- `actions` — define validated operations shared by the agent and UI.
|
||||
- `secrets` — connect external services and resolve credentials safely.
|
||||
- `sharing` — configure access to shareable resources.
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: shadcn-ui
|
||||
description: >-
|
||||
Using the app's local UI adapter and Toolkit or shadcn primitives. Use when
|
||||
choosing or composing standard controls, implementing dialogs, menus, or
|
||||
forms, or changing component variants and theme tokens.
|
||||
scope: dev
|
||||
---
|
||||
|
||||
# shadcn/ui and Local UI Adapters
|
||||
|
||||
Use the components already provided by the app. Read the app's design-system
|
||||
configuration, Toolkit provider, and local UI components before adding or
|
||||
changing a control. Their exports, variants, and props are the contract; do
|
||||
not guess from upstream examples.
|
||||
|
||||
## Keep imports behind the local adapter
|
||||
|
||||
Product pages and domain components should import standard controls through the
|
||||
app's configured local UI alias. In the Chat starter, that is
|
||||
`@/components/ui/*`; its `app/components/ui/button.tsx` is a one-line
|
||||
re-export of `@agent-native/toolkit/ui/button`. Follow an adjacent local shim
|
||||
when the app needs another Toolkit primitive that is already exported there.
|
||||
|
||||
Use the app's configured design system and provider mapping for controls passed
|
||||
to shared Toolkit surfaces. For shared Toolkit feature presentation, use the
|
||||
semantic components exposed by `@agent-native/toolkit/design-system`; keep the
|
||||
feature behavior in its existing controller and customize only its supported
|
||||
presentation seam.
|
||||
|
||||
## Compose existing controls
|
||||
|
||||
- Prefer a primitive's built-in variant and size. Put page layout on a parent
|
||||
instead of overriding shared component appearance for one screen.
|
||||
- Use the app's semantic theme tokens for reusable UI, such as
|
||||
`bg-background`, `text-muted-foreground`, `border-border`, and `bg-primary`.
|
||||
Keep theme values in the app's existing CSS theme file.
|
||||
- Use the control that matches the choice: `Switch` for a binary setting,
|
||||
`Checkbox` for independent multi-select, `RadioGroup` for one choice from a
|
||||
short set, and `Select` or the app's combobox for a longer predefined list.
|
||||
- Compose cards and form fields from the primitives already available. Avoid
|
||||
adding explanatory copy that repeats a visible title or label; see
|
||||
`frontend-design` for the app's surface-density rules.
|
||||
- Put selectable items inside their menu or list group primitives. Keep tab
|
||||
triggers inside the tab list. Supply an accessible title to dialog, sheet,
|
||||
drawer, and alert-dialog content.
|
||||
- Match the trigger API to the actual local component. Toolkit wrappers may
|
||||
expose a different API from the upstream primitive; inspect its props before
|
||||
using options such as `asChild` or `render`.
|
||||
|
||||
## Keep controls operable
|
||||
|
||||
Use the app's existing field components and validation pattern. Associate
|
||||
errors with their inputs and expose invalid state to assistive technology.
|
||||
Icon-only actions need an accessible name and a usable focus target. Use the
|
||||
icon package already installed by the app.
|
||||
|
||||
Do not recreate menus, popovers, dialogs, or confirmations with absolute
|
||||
positioning and custom click-outside handlers. Never use browser `alert`,
|
||||
`confirm`, or `prompt`; use the app's dialog primitives. Keep overlay focus,
|
||||
keyboard, dismissal, and stacking behavior from the existing primitive.
|
||||
|
||||
For small visual refinements, use layout classes and semantic tokens. Avoid raw
|
||||
palette overrides, arbitrary one-off values, and manual overlay `z-index` unless
|
||||
you are fixing a reproduced bug. Use `gap-*` for layout spacing and the app's
|
||||
class-merging helper when it has one.
|
||||
|
||||
## Related skill
|
||||
|
||||
- **frontend-design** — Product UX, density, visual direction, and responsive
|
||||
behavior.
|
||||
@@ -0,0 +1,289 @@
|
||||
---
|
||||
name: sharing
|
||||
description: >-
|
||||
Framework-level sharing and privacy for user-authored resources
|
||||
(dashboards, documents, forms, decks, etc.). Use when making a resource
|
||||
table ownable, wiring list/read/update access checks, or dropping the
|
||||
standard share dialog into a template.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Sharing — Private by Default, Explicit Share
|
||||
|
||||
## Rule
|
||||
|
||||
Any resource a user **creates** (dashboards, documents, forms, decks, compositions, booking links, issues, analyses) is **private to the creator** by default and visible to others only when they have been **explicitly shared** with or when the creator changes visibility to `org` or `public`.
|
||||
|
||||
This is the framework-level primitive. Every ownable resource gets it for free — same API, same UI, same skill.
|
||||
|
||||
Workspace apps are the intentional organization-scoped exception: their default
|
||||
visibility is `org`, configurable by an organization owner/admin. The creator is
|
||||
stored as the app owner, and the creator or an organization owner/admin can
|
||||
change the app's visibility or manage its share grants.
|
||||
|
||||
## Concepts
|
||||
|
||||
### Three visibility levels
|
||||
|
||||
- **`private`** — owner + explicit share grants only. Default.
|
||||
- **`org`** — owner + explicit grants + anyone in the same org (read-only).
|
||||
- **`public`** — owner + explicit grants + **anyone with the link** (read-only). Public docs do NOT appear in other users' list/sidebar/search results — `accessFilter` omits them by default. They're reachable by id (`resolveAccess` admits them) so direct links and SSR routes like `/p/:id` keep working. If a list endpoint legitimately needs cross-user public discovery (a template gallery, etc.), pass `accessFilter(table, shares, ctx, minRole, { includePublic: true })`.
|
||||
|
||||
Visibility is coarse. Explicit share grants are fine-grained (per user, reusable
|
||||
organization group, or per org).
|
||||
|
||||
### Roles on a share grant
|
||||
|
||||
- **`viewer`** — read only.
|
||||
- **`commenter`** — read + add comments, but cannot edit the resource or manage shares.
|
||||
- **`editor`** — read + write.
|
||||
- **`admin`** — read + write + manage shares. Does NOT replace the single `owner_email` on the resource.
|
||||
|
||||
Share roles apply to one resource; organization roles apply to a team; app
|
||||
roles apply within one app. These are separate permissions. For role setup,
|
||||
use `agent-native-docs` to find the current organization and app-role guide.
|
||||
|
||||
Before adding an admin gate, identify which role system protects that operation
|
||||
and use its existing role descriptor and permission checks. Do not replace role
|
||||
checks with an email comparison or a custom `isAdmin` column.
|
||||
|
||||
### Anonymous public URLs stay separate
|
||||
|
||||
Form "publish" slugs, booking-link slugs, any feature that exposes a URL to unauthenticated users — these are a different axis and are NOT controlled by the sharing system. Keep them alongside it.
|
||||
|
||||
## Make a resource ownable
|
||||
|
||||
In your template's `server/db/schema.ts`:
|
||||
|
||||
```ts
|
||||
import { sql } from "drizzle-orm";
|
||||
import { pgTable, text } from "drizzle-orm/pg-core";
|
||||
import {
|
||||
createSharesTable,
|
||||
ownableColumns,
|
||||
} from "@agent-native/core/db/schema";
|
||||
|
||||
export const decks = pgTable("decks", {
|
||||
id: text("id").primaryKey(),
|
||||
title: text("title").notNull(),
|
||||
data: text("data").notNull(),
|
||||
createdAt: text("created_at").notNull().default(sql`now()`),
|
||||
updatedAt: text("updated_at").notNull().default(sql`now()`),
|
||||
...ownableColumns(), // adds owner_email, org_id, visibility
|
||||
});
|
||||
|
||||
export const deckShares = createSharesTable("deck_shares");
|
||||
```
|
||||
|
||||
Then register it **in `server/db/index.ts`** (not the schema file — keeps the schema file free of the `getDb` closure and avoids circular imports):
|
||||
|
||||
```ts
|
||||
// server/db/index.ts
|
||||
import * as schema from "./schema.js";
|
||||
import { createGetDb } from "@agent-native/core/db";
|
||||
import { registerShareableResource } from "@agent-native/core/sharing";
|
||||
|
||||
export const getDb = createGetDb(schema);
|
||||
export { schema };
|
||||
|
||||
registerShareableResource({
|
||||
type: "deck",
|
||||
resourceTable: schema.decks,
|
||||
sharesTable: schema.deckShares,
|
||||
displayName: "Deck",
|
||||
titleColumn: "title",
|
||||
getResourcePath: (deck) => `/deck/${deck.id}`,
|
||||
getDb,
|
||||
});
|
||||
```
|
||||
|
||||
The `type` string is the stable id the UI and actions use. `getDb` is required — the framework-level share actions use it to reach your template's DB.
|
||||
|
||||
### Restricting public visibility and cross-org user shares
|
||||
|
||||
Some resources should NOT be reachable by an arbitrary authenticated user even with the link, and should NOT be shareable to an email outside the org. Two optional registration flags lock these axes down:
|
||||
|
||||
```ts
|
||||
registerShareableResource({
|
||||
type: "extension",
|
||||
// ...
|
||||
allowPublic: false, // hides "Public" in the share dialog and rejects it server-side
|
||||
requireOrgMemberForUserShares: true, // user shares must target an org member or pending invitee
|
||||
supportsGroupShares: true, // enable reusable organization groups for this resource
|
||||
});
|
||||
```
|
||||
|
||||
- **`allowPublic: false`** — `set-resource-visibility('public')` throws `ForbiddenError`, `accessFilter` / `resolveAccess` treat any stored `'public'` row as private (defense in depth against bad data), and the share popover hides the "Public" option. `list-resource-shares` returns `policy.allowPublic: false` so the UI follows the server.
|
||||
- **`requireOrgMemberForUserShares: true`** — `share-resource` looks up `principalId` in `org_members` and `org_invitations` (pending) for the resource's `orgId` and rejects user shares to anyone else. The same flag also pins `principalType: "org"` shares to the resource's own org — sharing to a *different* org would let that org's members run code in the viewer's auth context (same threat model as a public extension). (The flag name is kept for backward compatibility; treat it as "lock both user and org shares to the resource's org".)
|
||||
|
||||
Use both for resources that execute code or expose privileged data with the *viewer's* credentials. A public or cross-org-shared resource with that access could let an unrelated user act with the viewer's credentials.
|
||||
|
||||
Defaults match historical behaviour: `allowPublic: true`, `requireOrgMemberForUserShares: false`. Resources that don't set the flags work as before.
|
||||
|
||||
### Reusable organization groups
|
||||
|
||||
The workspace organization model stores reusable groups in
|
||||
`workspace_user_groups`. Organization owners/admins manage the groups and their
|
||||
members through the existing group actions. Set `supportsGroupShares: true` on a
|
||||
resource registration to enable `principalType: "group"` in the generic share
|
||||
actions and the shared popover's autocomplete. Group ids are always checked
|
||||
against the resource's organization, and membership is evaluated at access time
|
||||
so group changes apply to existing shares.
|
||||
|
||||
Workspace apps opt into this flag and use the organization default visibility
|
||||
setting. The app creator is the durable `owner_email`, while organization
|
||||
owners/admins receive admin access through the registration's
|
||||
`canManageAccess` callback. For these registrations, a direct resource-level
|
||||
`admin` share does not override that manager policy; it grants the editor role
|
||||
for access checks, while only the creator and callback-approved managers can
|
||||
change visibility or manage share grants.
|
||||
|
||||
## Filter list/read queries
|
||||
|
||||
```ts
|
||||
import { accessFilter } from "@agent-native/core/sharing";
|
||||
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(schema.decks)
|
||||
.where(accessFilter(schema.decks, schema.deckShares));
|
||||
```
|
||||
|
||||
`accessFilter` admits rows the current user owns, has been shared on, or that the user can reach via `org` visibility. `public` rows are NOT admitted by default — see the visibility section above for why and how to opt in.
|
||||
|
||||
## Guard write actions
|
||||
|
||||
```ts
|
||||
import { assertAccess } from "@agent-native/core/sharing";
|
||||
|
||||
export default defineAction({
|
||||
schema: z.object({ id: z.string(), title: z.string() }),
|
||||
run: async (args) => {
|
||||
await assertAccess("deck", args.id, "editor");
|
||||
// ...proceed
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
For delete actions use `"admin"` (or fold in `"owner"` to require the real owner).
|
||||
|
||||
`authorize` is a different axis, not an alternative: it gates whether the caller may run the operation at all, while `assertAccess` scopes which row they may touch. A write action restricted to some teammates needs both — `authorize: appAccess.requireAny(...)` on the action, `assertAccess` inside `run`.
|
||||
|
||||
## Create actions must set owner
|
||||
|
||||
When inserting a new row, fill `ownerEmail` and `orgId` from the request context:
|
||||
|
||||
```ts
|
||||
import { fail } from "@agent-native/core/action";
|
||||
import {
|
||||
getRequestUserEmail,
|
||||
getRequestOrgId,
|
||||
} from "@agent-native/core/server/request-context";
|
||||
|
||||
const ownerEmail = getRequestUserEmail();
|
||||
// Never fall back to a shared sentinel owner; require an authenticated session.
|
||||
if (!ownerEmail) fail("Not authenticated", { statusCode: 401 });
|
||||
|
||||
await db.insert(schema.decks).values({
|
||||
id: crypto.randomUUID(),
|
||||
title,
|
||||
data,
|
||||
ownerEmail,
|
||||
orgId: getRequestOrgId(),
|
||||
// visibility defaults to 'private'
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
## Drop in the share UI
|
||||
|
||||
```tsx
|
||||
import { ShareButton } from "@agent-native/toolkit/app/sharing";
|
||||
|
||||
// In the resource's header/toolbar:
|
||||
<ShareButton
|
||||
resourceType="deck"
|
||||
resourceId={deck.id}
|
||||
resourceTitle={deck.title}
|
||||
/>;
|
||||
```
|
||||
|
||||
For list views, show `<VisibilityBadge visibility={row.visibility} />` next to each resource.
|
||||
|
||||
## Standard share surface
|
||||
|
||||
All app share popovers should use the same compact surface contract:
|
||||
|
||||
- Use the text-only `ShareTrigger` from `@agent-native/toolkit/sharing`.
|
||||
- Render ordinary links with `ShareCopyRow`, which exposes a Copy action without
|
||||
printing the raw URL.
|
||||
- Keep general access and individual people access in the standard Core sharing
|
||||
flow. The people flow supports email invites, roles, notifications, and
|
||||
removal through the shared share actions.
|
||||
- Add `ShareAgentsSection` only when the resource has a real agent-readable
|
||||
link or prompt. Keep it collapsed by default and supply domain-specific
|
||||
content through the shared section shell.
|
||||
- When `supportsGroupShares` is enabled, keep the existing people input as the
|
||||
only entry point and include organization groups in its autocomplete. Do not
|
||||
add a separate group-management surface to each resource.
|
||||
- App-specific tabs or controls may remain when they represent a real domain
|
||||
action (for example, an embed-code editor), but they should retain the same
|
||||
trigger, copy-row, access, and spacing language.
|
||||
|
||||
`ShareDisclosureSection` is the toolkit-owned shell for optional expandable
|
||||
share details; use its `ShareAgentsSection` or `SharePeopleSection` wrappers
|
||||
instead of creating another collapsible share panel in a template.
|
||||
|
||||
## Actions available everywhere
|
||||
|
||||
The framework auto-mounts these actions in every template — no per-template boilerplate:
|
||||
|
||||
| Action | Args | Purpose |
|
||||
| -------------------------- | ------------------------------------------------------------------------------ | ----------------------------------------- |
|
||||
| `share-resource` | `resourceType, resourceId, principalType, principalId, role, notify?, resourceUrl?, message?` | Grant a user, group, or org access. `notify` defaults to true for individual user shares; `resourceUrl` can provide the direct app link and `message` an optional short note for the notification email. |
|
||||
| `unshare-resource` | `resourceType, resourceId, principalType, principalId` | Revoke access. |
|
||||
| `list-resource-shares` | `resourceType, resourceId` | Current visibility + all share grants. |
|
||||
| `set-resource-visibility` | `resourceType, resourceId, visibility` | Change to `private` / `org` / `public`. |
|
||||
|
||||
Both the agent and the UI use these same actions. The agent calls them as tools;
|
||||
UI code should use `ShareButton` / `ShareDialog` or the action client hooks
|
||||
instead of hand-writing route calls.
|
||||
|
||||
To re-skin the share notification email for the whole app, register
|
||||
`overrideTransactionalEmail("core.resource-shared", render)` from a server
|
||||
plugin. Do not fork `share-resource` or add another per-resource hook: the
|
||||
registration's `getBrandName` / `getLogoUrl` / `getSender` / `getHeroHtml` /
|
||||
`getShareEmailExtras` hooks still feed the default template and the override's
|
||||
props. See
|
||||
`/docs/deployment#email-templates`.
|
||||
|
||||
## Migration pattern for existing tables
|
||||
|
||||
When retrofitting an existing resource table:
|
||||
|
||||
1. Add `owner_email`, `org_id`, `visibility` columns (defaults `'local@localhost'`, `NULL`, `'private'`).
|
||||
2. Backfill `owner_email` from any prior creator trail; otherwise leave the default.
|
||||
3. Add the companion `{type}_shares` table.
|
||||
4. Register via `registerShareableResource`.
|
||||
5. Update list/read actions to use `accessFilter`.
|
||||
6. Update update/delete actions to `assertAccess` with the correct role.
|
||||
7. Add `<ShareButton>` to the resource header.
|
||||
8. Add `getResourcePath` in the registration so agent-triggered shares can email a direct link even when no UI supplied `resourceUrl`.
|
||||
|
||||
## Templates that opt out
|
||||
|
||||
Sharing doesn't apply to:
|
||||
|
||||
- **Personal-data apps** (mail) — user-scoped by design.
|
||||
- **External source-of-truth data** — apply the access policy enforced by the upstream system.
|
||||
- **Demo/boilerplate** (starter) — no resources.
|
||||
|
||||
For these, add a short note to the template's `AGENTS.md` explaining why.
|
||||
|
||||
## Debugging
|
||||
|
||||
- `ForbiddenError` from an action means the current user isn't owner / hasn't been shared / can't meet the role bar.
|
||||
- If the agent can't see a resource it just created, check that the insert actually set `owner_email` from the request context.
|
||||
- If a share doesn't take effect in the UI, confirm the template's `list-*` action uses `accessFilter` — the share rows are there but nothing is reading them yet.
|
||||
@@ -0,0 +1,223 @@
|
||||
---
|
||||
name: storing-data
|
||||
description: >-
|
||||
How to store application data in agent-native apps. All data lives in SQL.
|
||||
Use when adding data models, deciding where to store data, or reading/writing
|
||||
application data.
|
||||
scope: dev
|
||||
metadata:
|
||||
internal: true
|
||||
---
|
||||
|
||||
# Storing Data — SQL is the Source of Truth
|
||||
|
||||
## Rule
|
||||
|
||||
All application data lives in **SQL** (local PGlite, hosted Postgres in production). The agent and UI share the same database. SQL stores structured records, metadata, references, and searchable text — not large raw file payloads. Do not store durable app data in the filesystem unless the app is explicitly running a Local File Mode artifact flow described below.
|
||||
|
||||
Large binary or file-like payloads (images, video/audio, PDFs, ZIPs, screenshots, session replay chunks, thumbnails, generated assets, `data:` URLs, and base64 file bodies) must go through configured file/blob storage such as `uploadFile()` or `putPrivateBlob()`. Persist only the returned URL, asset id, or opaque blob handle in SQL. If storage is unavailable in hosted or persistent-database mode, fail closed with setup guidance instead of falling back to base64 in `application_state`, `settings`, `resources`, or app tables.
|
||||
|
||||
**Uploaded files an action opens later** (chat attachments, import controls, chunked commits) are one core `AttachmentRef`: mint with `mintAttachmentRef`, open with `resolveAttachment` and `unwrapAttachment` from `@agent-native/core/private-blob`. Never write a template descriptor, never branch on error text, and never truncate a ref (`ATTACHMENT_REF_MAX_CHARS` is the floor for any prompt or field that carries one). Each failure is typed: `notFound`, `forbiddenScope`, `expired` and `malformed` are definitive and stop the turn; only `storageUnavailable` is retryable, and the same ref works once storage is back, so never ask the user to attach the file again for it.
|
||||
|
||||
**Local File Mode exception:** some artifact apps (Content, Plans, Slides, Dashboards, Designs, etc.) can intentionally use repo files as the source of truth for the artifact itself. This must be explicit via `agent-native.json`, `AGENT_NATIVE_MODE=local-files`, or an app-owned local-file action helper. In that mode, the UI and agent still go through app actions, but those actions read/write scoped files through `@agent-native/core/local-artifacts` instead of SQL rows. App state, auth, settings, credentials, collaboration metadata, and hosted database mode remain SQL. File-to-database or file-to-provider synchronization is an explicit sync step, not an implicit side effect of editing.
|
||||
|
||||
When you add a data model, a list, or a read path, also follow the `performance` skill: project only the columns a list renders, index the columns hot queries filter/sort on, and avoid query waterfalls — so apps stay fast as data grows.
|
||||
|
||||
## How It Works
|
||||
|
||||
Agent-Native apps use Drizzle ORM over PostgreSQL. Local development uses PGlite at `data/pglite`; production and shared preview deploys need a persistent hosted PostgreSQL `DATABASE_URL`.
|
||||
|
||||
For app code, use Drizzle's schema/query DSL by default. Raw SQL is an escape hatch for additive migrations, health checks, or one-off maintenance, not the normal way to build features.
|
||||
|
||||
### Schema and migration ownership
|
||||
|
||||
Define PostgreSQL tables with Drizzle's `drizzle-orm/pg-core` exports and use
|
||||
`drizzle-orm` for query operators. Import only framework-owned sharing helpers,
|
||||
such as `ownableColumns()` and `createSharesTable()`, from
|
||||
`@agent-native/core/db/schema`. Do not import table builders through the core
|
||||
helper module.
|
||||
|
||||
When the project contains `drizzle.config.ts` and `drizzle/START_HERE.md`, that managed Drizzle scaffold is the only app migration path. Define app tables in `drizzle/schema.ts`, run `pnpm db:generate`, and apply them with `pnpm db:migrate`. `scripts/migrate-production.ts` applies the framework tables and leaves app tables to `db:migrate` (it skips `server/plugins/db.ts` when `drizzle.config.ts` exists): do not create a parallel `runMigrations([...])` list in `server/plugins/db.ts` or import an app migration runner into the release script.
|
||||
|
||||
In projects without that managed scaffold, every entry added to a framework `runMigrations([...])` list (`@agent-native/core/db`) needs a unique, stable `name` alongside its `version`; append changes instead of renumbering, reusing, or editing an applied entry.
|
||||
|
||||
Why: version numbers alone are not a safe identity. Two branches that each independently extend the same migration list can ship different DDL under the same version numbers — whichever branch deploys first "claims" those version numbers in the bookkeeping table, and the other branch's DDL is silently treated as already applied even though it never ran. A `name:` slug is tracked independently of version numbers, so it applies exactly once per database regardless of what any other branch already recorded.
|
||||
|
||||
Existing unnamed migrations don't need to be renamed retroactively (the two gating strategies coexist), but any new entry should always carry a name.
|
||||
|
||||
Every migration must be additive and backward compatible with code that may
|
||||
still be running. A new `ADD COLUMN ... NOT NULL` with no `DEFAULT` breaks on
|
||||
existing rows and inserts from older code. Make it nullable, give it a safe
|
||||
`DEFAULT`, or use a self-filling type (`SERIAL`, `GENERATED ... AS IDENTITY`);
|
||||
backfill separately when it needs a real value.
|
||||
|
||||
### Core SQL Stores (created by the framework, available in all templates)
|
||||
|
||||
| Store | Purpose | Access |
|
||||
| ------------------- | ---------------------------------------------------- | ------------------------------------------ |
|
||||
| `application_state` | Ephemeral UI state (compose windows, navigation) | `readAppState()` / `writeAppState()` |
|
||||
| `settings` | Persistent KV config (preferences, app settings) | `getSetting()` / `putSetting()` |
|
||||
| `oauth_tokens` | OAuth credentials | `@agent-native/core/oauth-tokens` |
|
||||
| `sessions` | Auth sessions | `@agent-native/core/server` |
|
||||
|
||||
### Domain Data (per-template)
|
||||
|
||||
In a managed Drizzle scaffold, define the PostgreSQL schema in
|
||||
`drizzle/schema.ts` and get `getDb()` and `schema` from `server/db.ts` (see
|
||||
`drizzle/START_HERE.md`). Otherwise, define it in `server/db/schema.ts`;
|
||||
`getDb()` comes from the local `server/db/index.ts`. All queries are async.
|
||||
|
||||
```ts
|
||||
import { eq, sql } from "drizzle-orm";
|
||||
import { boolean, pgTable, text } from "drizzle-orm/pg-core";
|
||||
|
||||
export const tasks = pgTable("tasks", {
|
||||
id: text("id").primaryKey(),
|
||||
title: text("title").notNull(),
|
||||
completed: boolean("completed").notNull().default(false),
|
||||
createdAt: text("created_at").notNull().default(sql`now()`),
|
||||
});
|
||||
|
||||
const rows = await db.select().from(tasks).where(eq(tasks.id, taskId));
|
||||
```
|
||||
|
||||
Use `drizzle-orm/pg-core` so app schemas state their PostgreSQL types directly.
|
||||
|
||||
#### Identity-shaped columns need a policy
|
||||
|
||||
Member offboarding and email changes refuse to run while any column named
|
||||
`email`, `*_email`, `*scope_id`, `created_by`, `updated_by`, `invited_by`,
|
||||
`owner`, `principal_id`, `session_id`, or `user_id` has no policy.
|
||||
`createSharesTable()` tables are handled for you, and undeclared `owner_email`
|
||||
columns transfer to the successor, which is right only for owned content.
|
||||
Declare every other one, including columns that are not member identities, from
|
||||
the app's database plugin graph (Clips does it in `server/db/index.ts`):
|
||||
|
||||
```ts
|
||||
import { registerIdentityColumns } from "@agent-native/core/org";
|
||||
|
||||
registerIdentityColumns([
|
||||
// Access grant: follows an email change, ends with the membership.
|
||||
{ table: "space_members", column: "email", emailChange: "rekey", offboard: "delete", orgScope: { column: "space_id", references: { table: "spaces", column: "id", orgColumn: "org_id" } }, reason: "Space membership grants access." },
|
||||
// Someone else's address: never rewritten.
|
||||
{ table: "meeting_participants", column: "email", emailChange: "retain", offboard: "retain", reason: "Attendee address from the calendar provider." },
|
||||
// A credential in an owner_email table: never handed to the successor.
|
||||
{ table: "api_keys", column: "owner_email", emailChange: "rekey", offboard: "revoke", reason: "Bearer keys act as their owner." },
|
||||
]);
|
||||
```
|
||||
|
||||
Choose `delete` for grants, credentials, and pending tokens, or `revoke` (sets
|
||||
`revoked_at`) when a reader treats a missing row as "not revoked"; `retain` for
|
||||
attribution, history, and third-party addresses; `transfer` only for owned
|
||||
data. Declare `owner_email` tables that hold credentials or grants, or
|
||||
offboarding hands them to the successor. A table without `org_id` needs
|
||||
`orgScope` or an organization-scoped removal leaves its rows alone.
|
||||
|
||||
| Template | Tables |
|
||||
| ------------ | --------------------------------------------- |
|
||||
| **Mail** | emails, labels |
|
||||
| **Calendar** | booking links and bookings; events stay in Google Calendar |
|
||||
| **Forms** | forms, responses |
|
||||
| **Content** | documents in SQL; connected local-folder sources sync separately |
|
||||
| **Slides** | decks (JSON stored in SQL) |
|
||||
| **Clips** | recording metadata in SQL; video and image files use blob storage |
|
||||
|
||||
### Agent Access
|
||||
|
||||
The agent uses app-specific actions to read/write the database. Core DB scripts are for inspection and maintenance, not for implementing normal product behavior:
|
||||
|
||||
- `pnpm action db-schema` — Show all tables, columns, types
|
||||
- `pnpm action db-query --sql "SELECT * FROM forms"` — Run SELECT queries
|
||||
- `pnpm action db-exec --sql "UPDATE ..."` — Last-resort ad-hoc maintenance for short columns, multi-column writes, or computed updates when no domain action exists. For several related writes, prefer `--statements '[{"sql":"...","args":[...]}]'` so they run sequentially in one transaction. Schema changes are blocked; use a reviewed additive migration instead.
|
||||
- `pnpm action db-patch --table <t> --column <c> --where "<clause>" --find "<old>" --replace "<new>"` — **Surgical search/replace on a large text column.** Sends the diff instead of re-transmitting the whole value, so it's dramatically more token-efficient than `db-exec UPDATE` when editing multi-kilobyte documents, slide HTML, dashboard/form JSON, etc. Targets exactly one row per call — narrow `--where` by primary key. Supports `--edits '[{find,replace},...]'` for batch edits and `--all` to replace every occurrence.
|
||||
- App-specific actions for domain operations — **always prefer these over raw SQL when one exists.** They encode business rules, power the client action hooks, and for editor-backed tables (documents, slides) also push live Yjs updates to open collaborative editors. `db-patch` is the generic fallback for tables without a dedicated edit action.
|
||||
|
||||
**For one-off maintenance, how to choose between `db-exec UPDATE` and `db-patch`:**
|
||||
|
||||
| Scenario | Use |
|
||||
| -------------------------------------------------------------- | ------------ |
|
||||
| `SET status = 'published'` on one row | `db-exec` |
|
||||
| `SET calories = calories + 50` | `db-exec` |
|
||||
| Updating several columns at once | `db-exec` |
|
||||
| Inserting/updating several rows as one logical operation | `db-exec --statements` |
|
||||
| Fixing a typo in a 50KB markdown document's `content` column | `db-patch` |
|
||||
| Changing a single key in a dashboard's JSON blob | `db-patch` |
|
||||
| Tweaking one paragraph of slide HTML stored in `decks.data` | `db-patch` |
|
||||
| Any edit where you'd otherwise re-send thousands of characters | `db-patch` |
|
||||
|
||||
All of these honor the per-user / per-org data scoping — you can't read or write rows outside the current user's data, regardless of which tool you choose.
|
||||
|
||||
### Frontend Access
|
||||
|
||||
The frontend calls actions using React Query hooks from the client API. The framework owns the HTTP transport behind these hooks, so components should not call action routes with raw `fetch`.
|
||||
|
||||
```ts
|
||||
import { useActionQuery, useActionMutation } from "@agent-native/core/client/hooks";
|
||||
|
||||
// Read data
|
||||
const { data } = useActionQuery("list-meals", { date: "2025-01-01" });
|
||||
|
||||
// Write data
|
||||
const { mutate } = useActionMutation("log-meal");
|
||||
```
|
||||
|
||||
Actions are the **preferred way** for the frontend to access data. You rarely need custom `/api/` routes — only for file uploads, streaming, webhooks, or OAuth callbacks.
|
||||
|
||||
### Production / Cloud Deployment
|
||||
|
||||
Local PGlite works out of the box for development. To deploy to production or any environment where data must survive restarts:
|
||||
|
||||
1. Set `DATABASE_URL` to a persistent hosted PostgreSQL database.
|
||||
2. Keep schema and queries PostgreSQL-compatible.
|
||||
|
||||
|
||||
|
||||
### Real-time Sync
|
||||
|
||||
Polling streams database changes to the UI. When the agent writes to the database via scripts, the UI updates automatically via `useDbSync()` which invalidates React Query caches.
|
||||
|
||||
## Do
|
||||
|
||||
- Use Drizzle ORM for structured domain data (forms, bookings, documents)
|
||||
- Use Drizzle query builder methods (`select`, `insert`, `update`, `delete`) and standard operators from `drizzle-orm` (`eq`, `and`, `or`, `inArray`, `desc`, etc.) for app reads/writes
|
||||
- Use `drizzle-orm/pg-core` for PostgreSQL table and column builders; use `@agent-native/core/db/schema` for framework-owned sharing helpers only
|
||||
- Use the `settings` store for app configuration and user preferences
|
||||
- Use `application-state` for ephemeral UI state that the agent and UI share
|
||||
- Use `oauth-tokens` for OAuth credentials
|
||||
- Use `uploadFile()` or `putPrivateBlob()` for large files/blob data and store only URLs, ids, or handles in SQL
|
||||
- Use core DB scripts (`db-schema`, `db-query`, `db-exec`, `db-patch`) for ad-hoc database operations
|
||||
- Use `db-exec --statements` instead of several separate `db-exec` calls for related writes; it is faster and rolls back the whole batch if one statement fails
|
||||
- Reach for `db-patch` instead of `db-exec UPDATE` whenever you're making a small change to a large text/JSON column — it's much cheaper on tokens
|
||||
|
||||
## Don't
|
||||
|
||||
- Don't store structured app data as JSON files
|
||||
- Don't store app state in localStorage, sessionStorage, or cookies (except for UI-only preferences like sidebar width)
|
||||
- Don't keep state only in memory (server variables, global stores)
|
||||
- Don't use Redis or any external state store for app data
|
||||
- Don't store large files, base64 blobs, `data:` URLs, screenshots, videos, audio, PDFs, ZIPs, or session replay chunks directly in SQL rows, `application_state`, `settings`, or `resources`
|
||||
- Don't implement product features with raw SQL or `getDbExec()` when Drizzle can express the query
|
||||
- Write advanced SQL for PostgreSQL
|
||||
- Don't interpolate user input directly into SQL queries — use Drizzle ORM's query builder
|
||||
|
||||
## Security
|
||||
|
||||
- **SQL injection** — Use Drizzle ORM's query builder, never raw string interpolation for SQL queries
|
||||
- **Validate before writing** — Check data shape before writing, especially for user-submitted data
|
||||
|
||||
## Application State and Context Awareness
|
||||
|
||||
When storing app-state, include **navigation state** — the agent needs to know what the user is looking at. The `application_state` table holds ephemeral UI state that both the agent and UI share. Key patterns:
|
||||
|
||||
- **`navigation` key** — the UI writes current view and selection on route changes; state may be scoped to the current browser tab.
|
||||
- **`navigate` command** — write it with `writeAppStateForCurrentTab("navigate", value)` so the command reaches the current tab; the UI processes and deletes it.
|
||||
- **Domain-specific keys** (e.g., `compose-{id}`) — bidirectional state for features like email drafts.
|
||||
|
||||
When adding a new data model or feature, also consider what navigation and selection state needs to be exposed via application-state. See the **context-awareness** skill for the full pattern.
|
||||
|
||||
## Related Skills
|
||||
|
||||
- **context-awareness** — How to expose navigation and selection state via application-state
|
||||
- **real-time-sync** — Set up polling so the UI updates when the database changes
|
||||
- **actions** — Create actions with `defineAction` to query the database
|
||||
- **build-an-app** — Apply the data model to a complete app feature
|
||||
@@ -0,0 +1 @@
|
||||
../.agents/skills
|
||||
@@ -0,0 +1,8 @@
|
||||
# Custom health check message
|
||||
PING_MESSAGE=pong
|
||||
|
||||
# Skip login/signup (local dev / preview only)
|
||||
# Auth is enabled when AUTH_DISABLED is unset. Standalone production deploys
|
||||
# need a stable BETTER_AUTH_SECRET; BETTER_AUTH_URL is inferred automatically.
|
||||
# BETTER_AUTH_SECRET=
|
||||
# AUTH_DISABLED=true
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
.react-router/
|
||||
.generated/
|
||||
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
node_modules
|
||||
build/
|
||||
dist
|
||||
dist-ssr
|
||||
.output/
|
||||
.netlify/
|
||||
.deploy-tmp/
|
||||
*.local
|
||||
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
.tmp/
|
||||
|
||||
**/data/
|
||||
data/pglite/
|
||||
data/uploads/
|
||||
data/settings.json
|
||||
data/.sessions.json
|
||||
|
||||
learnings.md
|
||||
|
||||
.vercel/
|
||||
.agent-native/
|
||||
data/*.lock
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"mcpServers": {
|
||||
"shadcn": {
|
||||
"command": "npx",
|
||||
"args": ["shadcn@latest", "mcp"]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"tabWidth": 2,
|
||||
"useTabs": false,
|
||||
"printWidth": 80,
|
||||
"trailingComma": "all",
|
||||
"proseWrap": "preserve",
|
||||
"sortImports": true
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
# App — Agent Guide
|
||||
|
||||
This starter ships as a blank Agent-Native app canvas — that describes its
|
||||
initial state, not necessarily its current one. See `DEVELOPING.md` before
|
||||
making any source code change.
|
||||
|
||||
## Skills
|
||||
|
||||
Search with `rg --hidden --follow`; read the exact linked guide before deeper work. `.agents/skills/build-an-app/SKILL.md` — start here for vague requests to create a domain app. `.agents/skills/adding-a-feature/SKILL.md` — cross-area feature checklist. Data/integrations: `.agents/skills/actions/SKILL.md`, `.agents/skills/storing-data/SKILL.md`, `.agents/skills/security/SKILL.md`, `.agents/skills/secrets/SKILL.md`, `.agents/skills/sharing/SKILL.md`. UI: `.agents/skills/frontend-design/SKILL.md`, `.agents/skills/shadcn-ui/SKILL.md`, `.agents/skills/client-side-routing/SKILL.md`. Agent context/workflows: `.agents/skills/context-awareness/SKILL.md`, `.agents/skills/real-time-sync/SKILL.md`, `.agents/skills/reliable-mutations/SKILL.md`, `.agents/skills/performance/SKILL.md`, `.agents/skills/delegate-to-agent/SKILL.md`. Framework: `.agents/skills/agent-native-docs/SKILL.md`, `.agents/skills/agent-native-toolkit/SKILL.md`, `.agents/skills/customizing-agent-native/SKILL.md`.
|
||||
|
||||
Use local docs only (no web research): `pnpm action docs-search --query "<topic>"`, `pnpm action docs-search --slug "<slug>"`, `pnpm action docs-search --list`, `pnpm action source-search --query "<pattern>"`, `pnpm action source-search --path <path>`, or `pnpm action source-search --list`. For external-agent integrations, read `pnpm action docs-search --slug "external-agents"`.
|
||||
|
||||
This repo is a single standalone app (`agent-native.scaffold.shape:
|
||||
"standalone"`), not a workspace root. If the user asks for a workspace, a
|
||||
platform or suite of apps, a second app, an app shell or launcher, or Dispatch,
|
||||
read the `multi-app-workspace` skill before touching the repo layout.
|
||||
|
||||
## Core rules
|
||||
|
||||
- UI feedback: target 100 ms, never exceed 400 ms; acknowledge before network work.
|
||||
- Normal app data must flow through actions. Keep actions deterministic and focused; use agent chat/AgentSidebar for AI work and follow-ups in the same thread. Keep structured state in SQL and large files in configured storage; persist references only.
|
||||
- For external integrations, inspect the workspace/provider connection catalog first; reuse its scoped resolver. Never hardcode credentials, webhook URLs, or private/customer data.
|
||||
- Never fabricate. Report failures and recover; verify writes by reading the row or screen. Navigation is in `<current-screen>`; use `view-screen` for fresh visible-record details.
|
||||
|
||||
For custom branding, keep `server/plugins/agent-native-email-branding.ts` aligned: `app.name` appears in transactional email and optional `app.logoUrl` must be an absolute HTTPS URL.
|
||||
|
||||
## Application state
|
||||
|
||||
- `navigation` describes the view and selected ids. The default home view is
|
||||
`home` at `/` (blank app canvas). No agent rail or chat is mounted by
|
||||
default; add one only when the user asks.
|
||||
- Use `navigate` when supported and `view-screen` for a fresh read of visible details; basic navigation is already in `<current-screen>`.
|
||||
|
||||
## Building a domain app
|
||||
|
||||
Choose the primary workflow and route before editing. Build on the blank canvas in `app/routes/_index.tsx` or add domain routes under `app/routes/`. This starter has no Chat route, sidebar, header, or agent rail; add only the navigation the product needs. Set `app.homePath` in the existing `defineAppConfig` in `server/plugins/config.ts` as `DEVELOPING.md` describes.
|
||||
|
||||
Use `adding-a-feature` for functional parity and `frontend-design` for a user-facing screen. Keep feature guidance here and update `README.md` as `DEVELOPING.md` describes. After all edits, run one typecheck, one doctor check, and one browser smoke of the primary workflow and its authenticated landing. Skip production build and extra test suites.
|
||||
|
||||
Before building common workspace or agent UI, read `agent-native-toolkit`; for supported customization, read `customizing-agent-native`.
|
||||
|
||||
- Guarded verification: run `pnpm agent-native:doctor`; fix findings before done.
|
||||
|
||||
- แผนผังการทำงาน (Frontend / Backend / Data): `docs/architecture.html` — เอกสารประกอบ เปิดด้วยเบราว์เซอร์ ไม่ถูก build เข้าแอป; อัปเดตเมื่อโครง route/API/data เปลี่ยน
|
||||
- คู่มือใช้งานหลังบ้าน (ภาษาไทย ทีละงาน): `docs/admin-guide.md` · API reference: `docs/api.md`
|
||||
- เมื่อเพิ่ม/เปลี่ยนฟิลด์ใน `Cinema`, หมวดหมู่, หรือ flow ของหลังบ้าน → อัปเดต `DESIGN.md` + `docs/architecture.html` + `docs/admin-guide.md` พร้อมกัน (ห้ามปล่อยเอกสารตกรุ่น)
|
||||
- ห้ามเขียนทับ `data/content/content.json` ด้วย seed: `readContent()` โยน error เมื่อไฟล์เสีย และสำรอง `.output/content.json.bakN` ก่อนแก้ด้วยสคริปต์
|
||||
@@ -0,0 +1,5 @@
|
||||
# App — Agent Guide
|
||||
|
||||
The agent guide for this app lives in [AGENTS.md](AGENTS.md) — the single source
|
||||
of truth for the framework contract, skills, application state, data, and
|
||||
verification rules. This file is only a pointer; read AGENTS.md.
|
||||
@@ -0,0 +1,31 @@
|
||||
# Project decisions
|
||||
|
||||
<!-- Written by Builder.io from the answers given before the first build. Question catalog 2026-09-30.1. -->
|
||||
|
||||
The user made these choices before any code existed. Treat them as
|
||||
requirements for the initial build rather than suggestions. They can be
|
||||
changed later in chat.
|
||||
|
||||
## How will your users interact with your app?
|
||||
|
||||
<!-- interaction-model = ui-only -->
|
||||
|
||||
- **Answer:** UI only, no agent
|
||||
- **Chosen by:** the user
|
||||
- **What this means:** Build a visual interface without an end-user AI agent experience.
|
||||
|
||||
## Will users need to login to use your app?
|
||||
|
||||
<!-- authentication = not-required -->
|
||||
|
||||
- **Answer:** No
|
||||
- **Chosen by:** the user
|
||||
- **What this means:** Allow users to use the app without signing in.
|
||||
|
||||
## What style should we start with?
|
||||
|
||||
<!-- visual-style = playful-friendly -->
|
||||
|
||||
- **Answer:** Playful/Friendly
|
||||
- **Chosen by:** the user
|
||||
- **What this means:** Use a playful, friendly visual style.
|
||||
@@ -0,0 +1,209 @@
|
||||
# Visual Design Contract
|
||||
|
||||
`AGENTS.md` is the canonical statement of the blank-canvas rule — check
|
||||
`app/routes/_index.tsx` and `app/global.css`, preserve any real UI/brand
|
||||
already there, and only treat the canvas as blank when those files still show
|
||||
the starter's placeholder. This file does not restate that rule; it records
|
||||
**this app's** visual direction. The fields below are the source of truth for
|
||||
that direction: once filled in, read and preserve them on every build; while
|
||||
they are still empty, the first substantial UI pass fills them in.
|
||||
|
||||
## Non-negotiable: impress by default
|
||||
|
||||
When this app is still a blank canvas, every app generated from this template
|
||||
must look **spectacular on first load**, even when the build prompt gives no
|
||||
design direction. "Looks like a clean, intentional product" is the floor, not
|
||||
the goal. When no direction is supplied, you still commit to one — do not
|
||||
default to safe gray SaaS:
|
||||
|
||||
- Commit to one concrete visual world (see the `frontend-design` skill and its
|
||||
`references/visual-direction.md`). Do not ship the neutral placeholder theme.
|
||||
- Choose a product-fitting accent family and set it in the `app/global.css`
|
||||
tokens for **both** light and dark. Never leave the 0%-saturation default as
|
||||
the shipped palette.
|
||||
- Establish a clear type hierarchy, a consistent spacing rhythm, and one
|
||||
signature detail (a considered empty state, a distinctive header, a crafted
|
||||
primary action) that makes the surface feel designed for its domain.
|
||||
- Get focus, hover, empty, loading, and dark-mode states right — that polish is
|
||||
the difference between an AI demo and a product.
|
||||
|
||||
Pick a direction and execute it fully; never average toward generic SaaS. Once
|
||||
a direction is established and recorded below, preserve and extend it rather
|
||||
than starting over unless otherwise directed to.
|
||||
|
||||
## Fill in before building the first surface
|
||||
|
||||
Once the fields below are filled in, they describe this app's established
|
||||
visual direction — read and preserve them on every subsequent build; do not
|
||||
re-derive a new direction. The first UI pass must fill these fields in as
|
||||
part of that build, not leave them as an empty template.
|
||||
|
||||
- Product mode: `experience`
|
||||
- Audience and cadence: Thai moviegoers browsing independent cinemas; occasional discovery.
|
||||
- Visual world (name + the feeling it creates): Dim indie screening room — friendly, warm, a little playful (pixel-style logo, rounded chips and cards).
|
||||
- Palette family + neutral undertone: Cinema crimson (#8F0808 / #A92626 / #D47272) on near-black neutrals (#0D0D0D, #1B1B1B, #242424) with a slight warm cast.
|
||||
- Type treatment: Inter + Noto Sans Thai; Jersey 15 pixel face for the AlterFlixHub wordmark only. เนื้อความยาว (บทความ/ย่อหน้าอ่านต่อเนื่อง เช่นหน้า /about) ใช้ `font-content` = IBM Plex Sans Thai Looped (มีหัว, 400/500) — หัวข้อและ UI ยังเป็น Inter + Noto Sans Thai ตามเดิม
|
||||
- Composition: Full-bleed hero with crimson glow, centered glass search box, 4-column card grid at 1224px max.
|
||||
- Shape language: Soft radii (8px controls, 18px pills, 16-20px cards), frosted-glass panels.
|
||||
- Anti-references (defaults this app must not drift toward): Gray SaaS dashboards, light themes, neon gradients, heavy chrome.
|
||||
|
||||
## โลโก้ (ห้ามเปลี่ยนแปลง — ห้ามตีความใหม่)
|
||||
|
||||
สเปกนี้เป็นข้อบังคับ ใช้กับทุกหน้าและทุกภาษาที่รองรับ:
|
||||
|
||||
| หัวข้อ | ค่าที่กำหนด |
|
||||
|---|---|
|
||||
| คำ | `AlterFlixHub` — ตัวสะกด/ตัวพิมพ์นี้เท่านั้น (ไม่ ALL CAPS, ไม่เว้นวรรค, ไม่แปล) |
|
||||
| ฟอนต์ | `Jersey 15` **เท่านั้น** ห้ามใช้ Inter หรือฟอนต์อื่นแทน |
|
||||
| น้ำหนัก/สไตล์ | ตามฟอนต์ดั้งเดิม — ห้ามใส่ bold/italic/uppercase/letter-spacing/เงา/ไล่สี |
|
||||
| สี | `#8F0808` เท่านั้น (ทุกสถานะ รวม hover/active) |
|
||||
| ขนาด header (navbar) | `text-4xl` = **36px** |
|
||||
| ขนาด footer | `text-2xl` = **24px** |
|
||||
| ตำแหน่ง | header: element แรก ชิดซ้ายสุด และคลิกกลับหน้าแรกได้ · footer: ซ้ายสุดของแถว |
|
||||
|
||||
- ไม่อนุญาตให้เพิ่มขนาดที่สาม หรือเปลี่ยนสี/ฟอนต์แม้ในสถานะ hover/active
|
||||
- ใช้ `Logo` เป็นข้อความแทนช่องรูปที่ยังไม่มีในแกลเลอรีหน้าโรงหนัง (`Gallery`) — ช่องหลัก `size="md"` (36px), ช่องย่อย `size="sm"` (24px) เท่านั้น; ข้อความ alt ยังใช้ `gallery.main/second/third` เพื่อการเข้าถึง
|
||||
- การเปลี่ยนใด ๆ ต้องได้อนุมัติจากเจ้าของโปรเจกต์ก่อน แล้วอัปเดตพร้อมกันทั้งตารางนี้, `LOGO_SPEC` (`app/lib/design-tokens.ts`) และ `app/components/site/Logo.spec.ts`
|
||||
- ตัวบังคับเชิงโค้ด: `Logo` อ่านค่าจาก `LOGO_SPEC` ผ่าน `logoClasses()` — ถ้ามีคนแก้สเปก เทสต์ `Logo.spec.ts` จะพังทันที
|
||||
|
||||
## Layout contract (บังคับ)
|
||||
|
||||
- หน้าเว็บจบที่ footer เสมอ: `SiteShell` เป็น `flex flex-col min-h-dvh` + เนื้อหาอยู่ใน `flex-1` (block ไม่ใช่ flex-col เพื่อไม่ให้ `main` ที่มี `mx-auto` หดเป็น max-content)
|
||||
- ของตกแต่งพื้นหลัง (รูปฮีโร่, gradient, glow) ต้องอยู่ใน `BackdropFrame` = `absolute inset-0 overflow-hidden` เสมอ — ถ้าปล่อยเป็น absolute ลอย ๆ ที่ใช้ `top-[…px]`/`bottom` ค่าเยอะ ๆ จะยืด `scrollHeight` ให้ยาวเกินเนื้อหา ทำให้มีพื้นที่ว่างเลื่อนได้ใต้ footer
|
||||
- แสงที่ต้องอยู่ช่วงล่างของหน้าให้ยึด `bottom-*` ไม่ใช่ `top-[px]` ตายตัว เพราะความสูงหน้าเปลี่ยนตามจำนวนการ์ดที่แสดง
|
||||
|
||||
## Agent-Native is structural, not visual
|
||||
|
||||
This shell already meets the Agent-Native contract: data in SQL, actions as the
|
||||
single source of truth, application state for navigation/selection, and
|
||||
real-time sync. **Chat and the agent rail are opt-in, not default.** Build the
|
||||
product UI first. Add an `AgentSidebar`, a full-page chat route, or
|
||||
`sendToAgentChat` handoffs only when the user asks for agent interaction — and
|
||||
when you do, follow `agent-native-toolkit` and `frontend-design` → Agent
|
||||
Surface And Page Boundaries so the surfaces are wired correctly.
|
||||
|
||||
## Guardrails
|
||||
|
||||
- Keep semantic token names and shared component seams intact; express the
|
||||
direction through token _values_, type, spacing, and composition — not by
|
||||
forking the design system.
|
||||
- Density comes from data, not prose. Subtract explanatory chrome; never
|
||||
subtract the visual craft that makes the app impressive.
|
||||
- Compare against real products in the chosen mode, not against the starter.
|
||||
|
||||
## Code map
|
||||
|
||||
Single source of truth per concern — do not duplicate these:
|
||||
|
||||
- `app/lib/cinemas.ts` — ข้อมูลโรงหนัง + ฟังก์ชันกรอง/ค้นหา (`filterCinemas`, `findCinemaBySlug`, `formatDistance`)
|
||||
- `app/lib/design-tokens.ts` — ค่าสีจาก Figma สำหรับ inline style (Tailwind class ยังเป็น literal เสมอ)
|
||||
- `app/lib/i18n/` — `messages.ts` (ข้อความ TH/EN ทั้งหมด คีย์หมวดหมู่/tag/ชำระเงิน/สิ่งอำนวยความสะดวก), `index.tsx` (`LocaleProvider`, `useI18n`, cookie `locale`)
|
||||
- ข้อความทุกคำใน UI ต้องมาจาก `messages` ไม่ hardcode ใน component · หมวดหมู่และ tag เก็บคีย์เป็นภาษาไทยเสมอ (ใช้กรองข้อมูล) แล้วแปลด้วย `messages.categories` / `messages.tags`
|
||||
- ข้อความอังกฤษของเนื้อหาโรงหนังเป็นฟิลด์เสริม `location_label_en` / `description_en` / `address_lines_en` / `value_en` — ไม่กรอกก็ fallback ไทย · ชื่อไทยใช้ `name_th` (+ helper `cinemaName(cinema, locale)`), ไม่กรอกก็แสดงชื่ออังกฤษ
|
||||
- `<title>` ของหน้ารายละเอียดสร้างจาก loader ของ route เอง (`meta({ loaderData })` — เวอร์ชันนี้ส่ง `loaderData` ไม่ใช่ `data`)
|
||||
- `<head>` (title/description) ไม่เปลี่ยนตามภาษา; ภาษาเริ่มต้นเลือกตามลำดับ **?lang= → localStorage → cookie → ไทย** (`resolveInitialLocale`) — ตั้งใจไม่ใช้ `navigator.language` เพราะเว็บไทย-first
|
||||
- สลับภาษาได้ 2 ทาง: ปุ่ม **TH / EN** ที่ header (ไม่มีเมนู ไม่มีจุดคลิกพลาด) หรือลิงก์ `?lang=en` ที่บังคับภาษาและ SSR ใส่ `<html lang>` ถูกต้อง
|
||||
- การเลือกถูกเก็บทั้ง cookie และ localStorage (รองรับเบราว์เซอร์ที่บล็อกคุกกี้) และซิงก์ข้ามแท็บผ่าน `storage` event
|
||||
- `app/components/site/` — โครงร่วม: `SiteShell` (flex column + `min-h-screen`, เนื้อหา `flex-1` เพื่อดัน footer ไปท้ายจอ), `SiteHeader`, `SiteFooter` (ความกว้างเนื้อหา cap ที่ 1016px เท่าคอลัมน์ฮีโร่ ไม่ยืดตามกริดการ์ด), `Logo`, `CinemaCard`, `CinemaGrid` + `CategoryFilter`
|
||||
- `app/components/home/` — ส่วนของหน้าแรก (`HeroSection`)
|
||||
- `app/components/cinema/` — ส่วนของหน้ารายละเอียด (`Gallery`, `CinemaSummary`, `TransportList`, `ContactPanel`, `FacilitiesSection`, `LocationPanel`, `CinemaNotFound`)
|
||||
- `app/routes/about.tsx` — หน้า "เกี่ยวกับเรา" (route `/about`, เมนูอยู่ทั้ง header และ footer, ใช้ `<Link>` ของ react-router จึงสลับหน้าแบบ SPA ไม่โหลดเอกสารใหม่) · เนื้อความเป็น `font-content` (มีหัว) ขนาด 17-18px `leading-[1.95]`, นำ 19-21px, หัวข้อยังเป็น Inter ตามเดิม
|
||||
- `docs/architecture.html` — แผนผังการทำงาน Frontend / Backend / Data (เอกสารประกอบ ไม่ถูก build เข้าแอป) เปิดด้วยเบราว์เซอร์ได้ตรง ๆ
|
||||
- `app/routes/_index.tsx` (หน้าแรก) และ `app/routes/cinema.$slug.tsx` (รายละเอียด) — ประกอบ component + จัดการ state ของ route เท่านั้น ข้อมูลมาจาก `useContent()`
|
||||
- `app/routes/admin_.login.tsx` (หน้า login) และ `app/routes/admin.tsx` (แดชบอร์ด **5 แท็บ**: โรงหนัง / หน้าเกี่ยวกับเรา / คำศัพท์หลายภาษา / Footer-ไอคอน / สถิติการค้นหา) — ใช้ `admin_.login` เพื่อให้เป็น route พี่น้องของ `/admin` (ถ้าตั้งชื่อ `admin.login` จะกลายเป็น route ลูกที่ไม่มี `<Outlet/>` แล้วหน้าว่าง)
|
||||
- ฟอร์มโรงหนังแบ่งเป็น **หมวดพับได้** (`app/components/admin/AdminSection.tsx` ใช้ `<details>/<summary>` เนทีฟ) เปิดไว้เฉพาะ "ข้อมูลหลัก" — เพิ่มหมวดใหม่ให้ใช้คอมโพเนนต์นี้เสมอ อย่าเรียงช่องยาวรวดเดียว
|
||||
- ช่อง slug (`SlugInput.tsx`): ดึงจากชื่ออังกฤษอัตโนมัติ (`suggestSlug`) จนกว่าจะแก้เอง · กันค่าว่าง/ซ้ำ · เตือนว่าลิงก์เดิมจะใช้ไม่ได้
|
||||
|
||||
## หลังบ้าน (admin)
|
||||
|
||||
- ข้อมูลที่แก้ได้เก็บที่ `data/content/content.json` (สร้างจาก seed อัตโนมัติครั้งแรก) — หน้าเว็บอ่านผ่าน `readContent()` ใน loader ของ `app/root.tsx` แล้วกระจายด้วย `ContentProvider`
|
||||
- API: `POST /api/admin/login` · `POST /api/admin/logout` · `GET /api/admin/session` · `GET|PUT /api/admin/content` · `POST /api/admin/cinemas/import` (วาง JSON ทับตาม slug)
|
||||
- ล็อกอินเริ่มต้น: ผู้ใช้ `it is me` / รหัส `it is me&it is me` — เปลี่ยนได้ด้วย env `ADMIN_USERNAME`, `ADMIN_PASSWORD`, `ADMIN_SESSION_SECRET`; session เป็น cookie HttpOnly ที่เซ็น HMAC (8 ชั่วโมง)
|
||||
- คำศัพท์ในหลังบ้านคือ dot path ของข้อความในหน้าเว็บ (`hero.subtitle`) ต่อภาษา — ค่าว่างแปลว่าใช้ค่าเดิมจาก `messages.ts`
|
||||
- Footer เก็บเป็นรายการ `{icon_name, label, href}` — ไอคอนที่เลือกได้อยู่ใน `app/components/site/footer-icons.ts`
|
||||
- หน้า "เกี่ยวกับเรา" แก้ได้ที่แท็บ `หน้าเกี่ยวกับเรา` (`app/components/admin/AboutEditor.tsx`) — เก็บเป็น `about: { th, en }` ใน `content.json` แต่ละภาษามี `title`, `lead`, `sections[]`, `contactHeading`, `contactNote`
|
||||
- ฟิลด์ที่เว้นว่างจะถูกเติมด้วยค่าเริ่มต้นจาก `MESSAGES[locale].about` ตอน sanitize (`sanitizeAbout`) — ไฟล์เก่าที่ไม่มีคีย์ `about` จึงยังใช้งานได้
|
||||
- `app/routes/about.tsx` อ่านจาก `useContent().about[locale]` เท่านั้น ไม่ผูกกับข้อความใน `messages.ts` อีก
|
||||
- ตัวแก้ไขมีแท็บภาษา + ตัวอย่างหน้าเว็บสด และปุ่ม "คืนค่าตั้งต้น" ต่อภาษา
|
||||
- ลำดับโรงหนังในหลังบ้าน (`app/components/admin/CinemaList.tsx`) — ลำดับในอาร์เรย์ `cinemas` = ลำดับที่หน้าเว็บแสดง
|
||||
- โหมด **ลำดับที่จัดไว้** (ค่าเริ่มต้น): ลากวางสลับที่ได้ หรือกด ↑ ↓ ทีละขั้น (คีย์บอร์ดใช้ได้) · เมื่อลำดับต่างจากที่บันทึกจะมีปุ่ม **บันทึกลำดับใหม่** (`PUT /api/admin/content` ส่งเฉพาะ `cinemas`) หรือจะกด **บันทึกทั้งหมด** ในฟอร์มก็ได้
|
||||
- โหมด **ก-ฮ**: เรียงชื่อไทยด้วย `Intl.Collator("th")` — เป็นเพียงมุมมอง ลากสลับไม่ได้จนกว่าจะกด **ใช้ลำดับ ก-ฮ นี้**
|
||||
- ฟังก์ชันบริสุทธิ์ที่ใช้ซ้ำได้: `sortCinemasByName` · `moveCinema` · `shiftCinema` · `hasSameOrder`
|
||||
- ช่องกรอกหลายค่าในหลังบ้าน (`app/components/admin/CommaListInput.tsx`) — หมวด/ชำระเงินแก้เป็น `CommaListInput`
|
||||
- เก็บข้อความดิบใน `draft` ระหว่างพิมพ์ จึงพิมพ์ `,` คั่นได้จริง (ถ้าผูก array เข้า `value` ตรง ๆ ตัวคั่นจะถูกตัดทิ้งทุกคีย์)
|
||||
- ตอนออกจากช่อง (blur) ค่อย normalize เป็น `", "` · รับ `,` และ `、` เป็นตัวคั่นด้วย · `parseCommaList` ใช้ซ้ำได้
|
||||
- สิ่งอำนวยความสะดวก **ผูกกับโรงหนังแต่ละโรง** (ไม่มีแท็บส่วนกลางแล้ว) — `cinema.facilities` = หัวข้อที่มีจริง, `cinema.facility_details[key] = { label?, sub_th?, sub_en? }` = ข้อความเฉพาะโรง
|
||||
- ในฟอร์มโรงหนัง: ชิปเลือกหัวข้อ → ด้านล่างมีช่อง "ชื่อหัวข้อ" (ช่องเดียว ใช้ทั้ง TH/EN)
|
||||
- ช่องคำอธิบาย TH/EN แสดงเฉพาะ slug `house-cinema-samyan` (ข้อมูลครบแล้ว) — โรงอื่นไม่ต้องกรอก
|
||||
- หน้าเว็บแสดงคำอธิบายเฉพาะที่มีค่าใน `facility_details` (ไม่กรอก = ไม่แสดงบรรทัดคำอธิบาย) · ไม่เลือกหัวข้อเลย → "ไม่มีข้อมูล"
|
||||
- ฟังก์ชันที่เกี่ยวข้อง: `cinemaFacilities()` (เรียงตาม `FACILITY_KEYS`) · UI หลังบ้าน `app/components/admin/CinemaFacilitiesEditor.tsx`
|
||||
- ที่ตั้ง (`app/lib/map-embed.ts`) — ลำดับ: `map_url` (Google Maps) → `coordinates` (0,0 ถือว่าไม่กรอก) → "ไม่มีข้อมูล"; iframe ใช้ `maps.google.com/maps?q=…&output=embed` (ไม่ต้องมี API key)
|
||||
- การเดินทาง (`app/components/admin/TransportEditor.tsx`) — แก้ `transport[]` (icon/TH/EN) ต่อโรง; แถวที่ยังไม่กรอกจะไม่แสดงบนหน้าเว็บ
|
||||
- ช่องทางติดต่อ (`app/components/admin/ContactsEditor.tsx`) — แก้ `contacts[]` = `{ label, value, href }` ต่อโรง (ป้ายชื่อมี datalist แนะนำ Website/Facebook/Call ฯลฯ) · หัวข้อการ์ดใช้ `contact_heading` ต่อโรง ไม่กรอก = `detail.contactTitle`
|
||||
|
||||
## กติกาข้อมูล (บังคับ — กันข้อมูลหาย)
|
||||
|
||||
- `readContent()` เขียน seed **เฉพาะกรณีไฟล์ไม่มี (`ENOENT`)** เท่านั้น — ถ้าไฟล์ parse/sanitize ไม่ผ่านให้ **โยน error** ห้ามเขียนทับด้วย seed (เคสจริง: เคยทำให้ข้อมูล 20 โรงหายระหว่างแก้โค้ด)
|
||||
- ก่อนแก้ `data/content/content.json` ด้วยสคริปต์ ให้ `cp` สำรองไว้ที่ `.output/content.json.bakN` ทุกครั้ง
|
||||
- ฟิลด์ใหม่ใน `Cinema` ต้องมีค่าเริ่มต้นที่ปลอดภัยเมื่อข้อมูลเก่าไม่มีฟิลด์นั้น (เช่น `facilities` → `[]`, `facility_details` → `{}`) และต้องผ่าน `sanitizeCinemas()`
|
||||
- โรงที่ `hidden: true` ต้องถูกกรองด้วย `publiclyVisible()` ก่อนแสดง/จัดอันดับ
|
||||
|
||||
## หมวดหมู่ (categories)
|
||||
|
||||
- ลำดับ/รายการทั้งหมดอยู่ใน `CINEMA_CATEGORIES` (`app/lib/cinemas.ts`) — แถบกรองหน้าแรกและชิปในหลังบ้านอ่านจากที่เดียวกัน
|
||||
- ชื่อที่แสดงมาจาก `messages.categories` + `messages.tags` (TH/EN) และ override ได้ผ่าน `site.terms` (`categories.<คีย์>`)
|
||||
- เพิ่มหมวดใหม่ = แก้ 3 ที่พร้อมกัน: `CINEMA_CATEGORIES` → `categories` (TH/EN) → เพิ่ม term ใน `content.json` (ถ้าต้องการให้แก้คำแปลในหลังบ้านได้)
|
||||
- หมวดที่เพิ่มล่าสุด: `กลุ่มคนฉายหนัง` (Film collectives) · `หนังไทย` (Thai films)
|
||||
- `ทั้งหมด` ใช้เป็น "ไม่กรอง" และไม่ถูกเสนอในชิปของหลังบ้าน (`ASSIGNABLE_CATEGORIES` ตัดออกให้)
|
||||
|
||||
## คอมโพเนนต์หลังบ้าน (`app/components/admin/`)
|
||||
|
||||
| ไฟล์ | ใช้ทำอะไร |
|
||||
|---|---|
|
||||
| `AdminSection.tsx` | การ์ดหมวดพับได้ (details/summary + badge + description) |
|
||||
| `CinemaList.tsx` | รายชื่อโรง: เรียง ก-ฮ (`Intl.Collator("th")`) + ลากวาง/↑↓ สลับตำแหน่ง |
|
||||
| `ChipPicker.tsx` | ชิปเลือกหลายค่า (หมวด/สิ่งอำนวยความสะดวก) + `toggleValue()` |
|
||||
| `CommaListInput.tsx` | ช่องหลายค่าคั่น `,` (เก็บ draft กันตัวคั่นถูกกลืน) + `parseCommaList()` |
|
||||
| `SlugInput.tsx` | slug: `normalizeSlug()` · `suggestSlug()` · `slugProblem()` |
|
||||
| `PhotosEditor.tsx` | รูปโรงหนัง (`photos[]`) — รูปแรกเป็นปกการ์ดหน้าแรก |
|
||||
| `TransportEditor.tsx` | วิธีเดินทาง (`transport[]`) |
|
||||
| `ContactsEditor.tsx` | ช่องทางติดต่อ (`contacts[]`) |
|
||||
| `CinemaFacilitiesEditor.tsx` | ข้อความสิ่งอำนวยความสะดวกต่อโรง (`facility_details`) |
|
||||
| `AboutEditor.tsx` | เนื้อหาหน้า "เกี่ยวกับเรา" |
|
||||
|
||||
## รูปภาพ
|
||||
|
||||
- `cinema.photos[0]` = **รูปปกการ์ดหน้าแรก** (`CinemaCard`) — ไม่มีรูป = ใช้ gradient 4 แบบ (`CARD_GRADIENTS`)
|
||||
- หน้า detail ใช้ `Gallery`: มีไม่ครบ 3 รูป ช่องที่ว่างแสดง **โลโก้ AlterFlixHub** (ดูหัวข้อโลโก้)
|
||||
- รูปในเครื่องวางที่ `public/images/…` แล้วใส่ path `/images/…` (ไฟล์ `hero.png` ใช้เป็นพื้นหลังฮีโร่หน้าแรก)
|
||||
|
||||
## ลำดับการ์ดหน้าแรก (สลับทุกวัน)
|
||||
|
||||
- `app/lib/daily-order.ts` — `dailyOrder(items, idOf, key)` คำนวณลำดับจาก "วันที่" ล้วน ๆ (ไม่เก็บ state)
|
||||
- เงื่อนไขบังคับ: **โรงหนึ่งต้องไม่ได้อยู่ตำแหน่งการ์ดเดิม 2 วันติดกัน**
|
||||
- permutation ฐาน = seeded shuffle (Fisher–Yates + mulberry32) จากลำดับที่แอดมินจัดไว้ → คงที่ทุกวัน
|
||||
- หมุน (rotate) ด้วย offset รายวันในช่วง `1..n-1` และ offset วันติดกันไม่เท่ากัน → ทุกโรงเลื่อนตำแหน่งแน่นอน
|
||||
- n = 2 สลับวันละครั้ง · รายการ < 2 คงเดิม
|
||||
- ทุกคนเห็นลำดับเดียวกันในวันเดียวกัน (คีย์วันที่แบบ UTC จาก loader → ไม่มี hydration mismatch)
|
||||
- ลำดับนี้ทำงาน **ก่อน** ตัวกรองหมวด/คำค้น — ผลกรองจึงสลับตามไปด้วย; ถ้าผู้ใช้กด "ใกล้ฉัน" การเรียงตามระยะทางยังชนะเสมอ
|
||||
- ตรวจด้วยสเปก `app/lib/daily-order.spec.ts` (n = 2..40 × 10 วัน, ไม่มีตำแหน่งซ้ำวันติดกัน)
|
||||
|
||||
## สถิติการค้นหา (privacy-first, แนว Umami)
|
||||
- เก็บ event แบบ append-only ที่ `data/analytics/events.jsonl` (หมุนไฟล์เมื่อเกิน 8 MB, เก็บล่าสุด 50k event)
|
||||
- ตัวรับ event: `POST /api/analytics/collect` (สาธารณะ) — ไม่ใช้คุกกี้ ไม่เก็บ IP/User-Agent ดิบ ระบุผู้เข้าชมด้วย `sha256(เกลือรายวัน | ip | ua)` 16 ตัวอักษร
|
||||
- ชนิด event: `search` (query/category/result_count) · `cinema_select` (slug/source/position) · `cinema_view` · `near_me`
|
||||
- ฝั่งเว็บเรียกผ่าน `trackEvent()` (`app/lib/analytics-client.ts`) — กลืน error, กัน event ซ้ำใน 1.5 วินาที, ค้นหาจะถูกบันทึกหลังผู้ใช้หยุดพิมพ์ 900 ms และต้องมี ≥ 2 ตัวอักษร
|
||||
- สรุปผล: `summarize(events, days)` (`app/lib/analytics.server.ts`) → คำค้นยอดนิยม, คำค้นที่ไม่พบผล, CTR, ผลลัพธ์เฉลี่ย, หมวดที่ถูกใช้, โรงหนังที่ถูกเปิด/คลิก, การค้นหารายวัน
|
||||
- ดูได้ที่หลังบ้าน แท็บ **สถิติการค้นหา** (`GET /api/admin/analytics?days=1|7|30|90`, ต้องล็อกอิน)
|
||||
- ตั้ง `ANALYTICS_SALT` ใน env เพื่อไม่ให้ hash ผู้เข้าชมคาดเดาได้ข้าม deployment
|
||||
|
||||
## หมวด "ยอดนิยม" (จากสถิติ ไม่ใช่ป้ายมือ)
|
||||
|
||||
- `app/lib/popularity.server.ts` — `computePopularity()` อ่าน `events.jsonl` แล้วให้สถานะ + อันดับ (memo 5 นาที)
|
||||
- **เงื่อนไขเปิดใช้: ต้องมีประวัติข้อมูล ≥ 180 วัน (6 เดือน)** — `ready=false` จนกว่าจะครบ เพื่อไม่ให้ฐานผู้ชมเล็ก ๆ ครองอันดับ
|
||||
- ระหว่างยังไม่ครบ: หมวด "ยอดนิยม" ใช้ `tags` ที่ตั้งไว้ (พฤติกรรมเดิม) **โดยไม่แสดงข้อความแจ้งบนหน้าเว็บ** — สถานะ/วันเหลือดูได้จาก `computePopularity()` หรือหลังบ้านเท่านั้น (ผู้ใช้สั่งลบข้อความออกจากหน้าแรก)
|
||||
- คะแนนเมื่อพร้อมใช้: `cinema_view` = 1 · `cinema_select` = 1.5 (เจตนาชัดกว่า) × decay ครึ่งชีวิต 30 วัน · นับเฉพาะ 90 วันล่าสุด · เอา top 8
|
||||
- โรงที่ถูกซ่อน (`hidden`) ไม่ถูกจัดอันดับ/แสดง
|
||||
- ค่าคงที่: `POPULARITY_MIN_HISTORY_DAYS` · `POPULARITY_WINDOW_DAYS` · `POPULARITY_TOP_N`
|
||||
|
||||
เพิ่มหน้าใหม่: ใส่ component ที่ `app/components/<domain>/` แล้วให้ route เป็นตัวประกอบเท่านั้น
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
# app — Development Guide
|
||||
|
||||
This guide is for development-mode agents editing this app's source code. For app operations and tools, see AGENTS.md.
|
||||
|
||||
## Tech Stack
|
||||
|
||||
- **Framework:** @agent-native/core + React Router v8 (framework mode)
|
||||
- **Frontend:** React 19, Vite, TailwindCSS, shadcn/ui
|
||||
- **Routing:** File-based via `flatRoutes()` — SSR shell + client rendering
|
||||
- **Backend:** Nitro (via @agent-native/core) — file-based API routing, server plugins, deploy-anywhere presets
|
||||
- **State:** SQL-backed (SSE for real-time updates)
|
||||
|
||||
## Commands
|
||||
|
||||
- **Dev:** `pnpm dev` (Vite dev server with both React Router + Nitro plugins)
|
||||
- **Build:** `pnpm build` (React Router build — client + SSR + Nitro server)
|
||||
- **Start:** `node .output/server/index.mjs` (production)
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
app/ # React frontend
|
||||
root.tsx # HTML shell + global providers
|
||||
entry.client.tsx # Client hydration entry
|
||||
routes.ts # Route config — flatRoutes()
|
||||
routes/ # File-based page routes (auto-discovered)
|
||||
_index.tsx # / (chat page)
|
||||
components/ # UI components
|
||||
hooks/ # React hooks
|
||||
lib/ # Utilities (cn, etc)
|
||||
|
||||
server/ # Nitro API server
|
||||
routes/
|
||||
api/ # Route-only endpoints (uploads, webhooks, OAuth, streaming)
|
||||
[...page].get.ts # SSR catch-all (delegates to React Router)
|
||||
plugins/ # Server plugins (startup logic)
|
||||
lib/ # Shared server modules
|
||||
|
||||
shared/ # Isomorphic code (imported by both client & server)
|
||||
|
||||
actions/ # Shared app operations (defineAction; UI uses action hooks)
|
||||
run.ts # Script dispatcher
|
||||
*.ts # Individual actions (pnpm action <name>)
|
||||
|
||||
data/pglite/ # Local PGlite data directory
|
||||
|
||||
react-router.config.ts # React Router framework config
|
||||
.agents/skills/ # Agent skills — detailed guidance for each rule
|
||||
```
|
||||
|
||||
## Framework Basics
|
||||
|
||||
**SSR-first framework, CSR-by-default content:** This app uses React Router v8 framework mode with `ssr: true`. But virtually every route renders only an SSR shell (loading spinner + meta tags). Normal app data fetching happens on the client via action hooks. Server-side data fetching is the exception — only used for public pages that need SEO/OG tags.
|
||||
|
||||
## Chat-First Shape
|
||||
|
||||
Agent-Native is the application framework and execution platform. AgentKit is
|
||||
its agent interaction and experience layer. Toolkit supplies the semantic
|
||||
composer, design-system primitives, and workspace UI used around the
|
||||
conversation.
|
||||
|
||||
The `/` route is the app's primary AgentKit surface. Its default integration is:
|
||||
|
||||
- `createAgentNativeAgentKitTransport()` from
|
||||
`@agent-native/toolkit/app/chat/agentkit-chat` for the production Agent-Native
|
||||
runtime.
|
||||
- `CoreAgentKitRoot` from `@agent-native/toolkit/app/chat/agentkit-chat` for one
|
||||
managed controller, thread context, and the default action-widget renderer.
|
||||
- `AgentKitChat` for the reference transcript, composer, queue, approvals,
|
||||
activities, and suggestions.
|
||||
- `CoreComposerRuntimeProvider` for Agent-Native composer capabilities.
|
||||
|
||||
The surrounding Core app shell owns the full-height canvas, global navigation,
|
||||
durable thread routing, and route-level chrome. `AgentKitChat` owns the
|
||||
conversation column. Pass route controls through its `toolbar` prop. Use
|
||||
`slots` and `registry` on `AgentKitRoot` for presentation overrides without
|
||||
forking conversation state.
|
||||
|
||||
Action UI is opt-in on each action through `chatUI.renderer`. `CoreAgentKitRoot`
|
||||
provides Core's `AgentKitActionWidget` in `slots.widget`; it resolves the
|
||||
declared React renderer from the stored tool input and result, then keeps the
|
||||
widget with its assistant message after activity rollup and thread reload. App
|
||||
renderers can register with `registerActionChatRenderer()` from
|
||||
`@agent-native/toolkit/app/chat/agentkit-chat` using the same renderer id declared by
|
||||
the action. Built-in Core renderers need no app registration.
|
||||
|
||||
This template is also the canonical AgentKit reference surface. Develop and
|
||||
verify shared chat UX here first, then use domain apps such as Dispatch as
|
||||
consumer smoke tests. Queue behavior can be exercised by submitting follow-ups
|
||||
while a run is active. The shared composer remains mounted throughout these
|
||||
states. The route does not provide fallback suggestions: contextual next
|
||||
actions appear only when the agent injects them through AgentKit's structured
|
||||
`suggestions` input.
|
||||
|
||||
For a headless app that later needs UI, this template is the intended landing
|
||||
zone: bring the existing actions over, keep their names stable, and let the chat
|
||||
call them before adding extra screens. For a custom agent backend, keep the app
|
||||
shell and implement `AgentTransport`, or adapt an existing Core
|
||||
`AgentChatRuntime` with `createAgentKitProtocolAdapter()` from
|
||||
`@agent-native/core/client/agent-chat`.
|
||||
|
||||
### Package and scaffold path
|
||||
|
||||
The Chat template depends on `@agent-native/core`,
|
||||
`@agent-native/agentkit`, and `@agent-native/toolkit` through workspace
|
||||
specifiers in this repository. The CLI resolves them for the generated shape:
|
||||
|
||||
- A normal standalone scaffold receives published package ranges.
|
||||
- A local framework-development scaffold packages the local Core, AgentKit,
|
||||
and Toolkit implementations. Missing compiled package exports are built
|
||||
before the tarballs are created.
|
||||
- A workspacified Chat app inherits a concrete package version already pinned
|
||||
by the workspace root. Otherwise it uses the compatible range supplied by
|
||||
the running CLI.
|
||||
|
||||
Do not replace these dependencies with direct `dist` paths or deep source
|
||||
imports. Install the generated manifest as written.
|
||||
|
||||
### Migrate an older Core chat surface
|
||||
|
||||
Core's `AssistantChat` remains supported as the AgentKit-backed surface, as do
|
||||
`AgentPanel`, `AgentSidebar`, `AgentChatSurface`, `AgentChatHome`, and
|
||||
`MultiTabAssistantChat`. Apps that only mount these components do not need to
|
||||
replace their chat UI.
|
||||
|
||||
If your app used the removed `AssistantChat.createAdapter`, adapter helpers, or
|
||||
assistant-ui transcript/runtime APIs, follow the version-matched guide at
|
||||
`node_modules/@agent-native/core/docs/migrations/agentkit-chat.md`. It maps each
|
||||
removed API to `runtime`, `createTransport`, AgentKit slots, or a custom
|
||||
`AgentTransport`. Keep one conversation controller and stream owner.
|
||||
|
||||
Widgets invoke stable action ids through the transport. Map them to the same
|
||||
`defineAction` surface used by the app and agent. Smart objects and client
|
||||
effects request host navigation or context changes. They do not bypass action
|
||||
validation, application-state helpers, request context, or ownable-data access
|
||||
checks.
|
||||
|
||||
## Adding a Page
|
||||
|
||||
Create a file in `app/routes/`. The filename determines the URL path:
|
||||
|
||||
```
|
||||
app/routes/_index.tsx → /
|
||||
app/routes/settings.tsx → /settings
|
||||
app/routes/inbox.tsx → /inbox
|
||||
app/routes/inbox.$threadId.tsx → /inbox/:threadId
|
||||
app/routes/$id.tsx → /:id (dynamic param)
|
||||
```
|
||||
|
||||
Each route file exports a default component, optional `meta()`, and optional `HydrateFallback()`:
|
||||
|
||||
```tsx
|
||||
import MyPage from "@/pages/MyPage";
|
||||
|
||||
export function meta() {
|
||||
return [{ title: "My Page" }];
|
||||
}
|
||||
|
||||
export function HydrateFallback() {
|
||||
return (
|
||||
<div className="flex items-center justify-center h-screen">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-foreground" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function MyPageRoute() {
|
||||
return <MyPage />;
|
||||
}
|
||||
```
|
||||
|
||||
**Do NOT fetch data server-side** in route loaders unless the page genuinely needs SEO/OG content. The standard pattern is: SSR renders the shell, client hydrates, and React reads/writes normal app data through actions with `useActionQuery` / `useActionMutation`.
|
||||
|
||||
## Adding App Data
|
||||
|
||||
Normal app data starts as an action, not a custom route. Add `actions/<verb>-<resource>.ts` with `defineAction`, mark reads with `http: { method: "GET" }`, and call reads/writes from React with `useActionQuery` / `useActionMutation` from `@agent-native/core/client`. This keeps the UI and agent on one contract and lets mutating actions refresh action-backed queries automatically.
|
||||
|
||||
## Adding a Route-Only Endpoint
|
||||
|
||||
Use `server/routes/api/` only for protocols that cannot be modeled as JSON actions: multipart uploads, streaming/SSE/WebSocket, webhooks, OAuth callbacks/redirects, public SEO/OG endpoints, or binary/static asset serving. Do not add `/api/*` routes for normal CRUD, data queries, or pass-through wrappers around actions; the action endpoint already exists at `/_agent-native/actions/:name`.
|
||||
|
||||
Each route-only endpoint still exports a default `defineEventHandler`, but keep shared app logic in actions or server libraries so agent and UI behavior do not fork.
|
||||
|
||||
## Adding a Server Plugin
|
||||
|
||||
Startup logic (auth, SSE, etc.) lives in `server/plugins/`. Use `defineNitroPlugin` from core:
|
||||
|
||||
```ts
|
||||
import { defineNitroPlugin } from "@agent-native/core";
|
||||
|
||||
export default defineNitroPlugin(async (nitroApp) => {
|
||||
// Runs once at server startup
|
||||
});
|
||||
```
|
||||
|
||||
## Key Imports from `@agent-native/core`
|
||||
|
||||
| Import | Purpose |
|
||||
| -------------------------------------------- | -------------------------------------------------------------------------- |
|
||||
| `defineNitroPlugin` | Define a server plugin (re-exported from Nitro) |
|
||||
| `createDefaultSSEHandler` | Create SSE endpoint for DB change events (server) |
|
||||
| `readAppState`, `writeAppState` | Read/write application state (from `@agent-native/core/application-state`) |
|
||||
| `readSetting`, `writeSetting` | Read/write settings (from `@agent-native/core/settings`) |
|
||||
| `defineEventHandler`, `readBody`, `getQuery` | H3 route handler utilities (re-exported) |
|
||||
| `sendToAgentChat` | Send messages to agent from UI (client-side) |
|
||||
| `agentChat` | Send messages to agent from scripts (server-side) |
|
||||
|
||||
## Adding an Action
|
||||
|
||||
Create `actions/<verb>-<resource>.ts` with `defineAction`. Run with `pnpm action <name> --id value`; React callers should use `useActionQuery` for GET actions and `useActionMutation` for mutating actions, not a matching `/api/*` wrapper.
|
||||
|
||||
**Sending to agent chat from UI:**
|
||||
|
||||
```ts
|
||||
import { sendToAgentChat } from "@agent-native/core/client";
|
||||
sendToAgentChat({
|
||||
message: "Generate something",
|
||||
context: "...",
|
||||
submit: true,
|
||||
});
|
||||
```
|
||||
|
||||
**Sending to agent chat from scripts:**
|
||||
|
||||
```ts
|
||||
import { agentChat } from "@agent-native/core";
|
||||
agentChat.submit("Generate something");
|
||||
```
|
||||
|
||||
## Database & Environment Variables
|
||||
|
||||
Local development uses PGlite at `data/pglite`. For production and shared environments, set `DATABASE_URL` to a persistent hosted PostgreSQL database.
|
||||
|
||||
Real credential values belong only in local `.env` files, deployment configuration, or registered secrets/settings UI. Never commit, document, log, return, paste, or include real keys, tokens, webhook URLs, signing secrets, or private data in examples; use empty values or obvious placeholders.
|
||||
|
||||
When adding app data, define tables with Drizzle's `drizzle-orm/pg-core`
|
||||
exports and use Drizzle's query builder for reads/writes. Import framework
|
||||
sharing helpers such as `ownableColumns()` and `createSharesTable()` from
|
||||
`@agent-native/core/db/schema`. Keep SQL PostgreSQL-compatible and reserve raw
|
||||
SQL for additive migrations, health checks, or carefully scoped maintenance.
|
||||
|
||||
| Variable | Required | Description |
|
||||
| --------------- | ---------------------------- | ----------------------------------------------------------------------------- |
|
||||
| `DATABASE_URL` | Production yes, local dev no | PostgreSQL or PGlite database URL (local dev default: `pglite:./data/pglite`) |
|
||||
| `AUTH_DISABLED` | Optional | Set to `true` or `1` to skip login/signup (local dev/preview only) |
|
||||
|
||||
## Extensions (Framework Feature)
|
||||
|
||||
The framework provides **Extensions** — mini sandboxed Alpine.js apps that run inside iframes. Extensions let users (or the agent) create interactive widgets, dashboards, and utilities without modifying the app's source code. They appear in the sidebar under an "Extensions" section. (Distinct from LLM tools — the function-calling primitives the agent invokes.)
|
||||
|
||||
- **Creating extensions**: Via the sidebar "+" button, agent chat, or `POST /_agent-native/extensions`
|
||||
- **API calls**: Extensions use `extensionFetch()` (legacy alias `toolFetch`) which proxies requests through the server with `${keys.NAME}` secret injection
|
||||
- **Styling**: Extensions inherit the main app's Tailwind v4 theme automatically
|
||||
- **Sharing**: Private by default, shareable with org or specific users (same model as other ownable resources)
|
||||
- **Security**: Iframe sandbox + CSP + SSRF protection on the proxy
|
||||
|
||||
See the `extensions` skill in `.agents/skills/extensions/SKILL.md` for full implementation details.
|
||||
|
||||
## Preserve existing work
|
||||
|
||||
This starter ships as a blank Agent-Native app canvas — that describes its
|
||||
initial state, not necessarily its current one. Before assuming no UI or
|
||||
brand exists, check `app/routes/_index.tsx` and `app/global.css`: if they
|
||||
already contain real content, that content is the current product and its
|
||||
established brand. Build additively, preserve existing tokens/routes/palette,
|
||||
and do not re-derive a new visual direction or overwrite shipped UI unless
|
||||
the user explicitly asks for a redesign. Only treat the canvas as blank when
|
||||
the files actually show the starter's placeholder content.
|
||||
|
||||
If `DECISIONS.md` exists at the repo root, read it before starting work — it
|
||||
holds pre-build choices as current requirements. If the user changes one
|
||||
later in chat, update `DECISIONS.md` to match.
|
||||
|
||||
`README.md` starts as a generic "My App" placeholder. Once the app has real
|
||||
features, rewrite its title and opening paragraph to name the app and say what
|
||||
it does, and keep the run instructions accurate when you change scripts or
|
||||
required env vars.
|
||||
|
||||
**Do not add internationalization or changelog support unless the user
|
||||
explicitly asks for them.** This starter ships English-only UI copy inline —
|
||||
no `app/i18n/`, LanguagePicker, `CHANGELOG.md`, or What's New surfaces. If the
|
||||
user requests i18n or changelogs, load the matching skill and add only what
|
||||
they asked for.
|
||||
|
||||
## Data & actions (read these first)
|
||||
|
||||
Add persistence or auth **only when data must survive reload or be shared
|
||||
between users**. A pure UI, copy, or layout change needs no schema, action, or
|
||||
auth — build it directly and do **not** read the `security` or `storing-data`
|
||||
skills for UI-only work. Only when you actually add an action, route, or schema
|
||||
that handles user input or persistence, read `security` and `storing-data`
|
||||
first.
|
||||
|
||||
### Choose the post-auth landing route from the app
|
||||
|
||||
Before enabling authentication, inspect `app/routes`, the app's navigation,
|
||||
and any existing `app.homePath` in `server/plugins/config.ts`. Preserve an
|
||||
existing `homePath` when it still points to a valid route. Otherwise choose
|
||||
the actual primary authenticated landing page from the product already built,
|
||||
such as `/`, `/dashboard`, or `/tasks`. Never assume `/home` unless that
|
||||
route really exists.
|
||||
|
||||
The starter ships `homePath: "/"` only so sign-in lands on the blank canvas.
|
||||
Once `/` is a public page and the signed-in app lives elsewhere, replace it
|
||||
with that route.
|
||||
|
||||
Do not choose an auth route, API route, public-only marketing page, wildcard
|
||||
route, or parameterized route that cannot open without an id. If multiple
|
||||
authenticated landing routes are equally plausible and the product intent is
|
||||
unclear, ask the user instead of inventing one.
|
||||
|
||||
Write the selected route to the existing `defineAppConfig` object in
|
||||
`server/plugins/config.ts` while preserving its `plugins.disabled` settings:
|
||||
|
||||
```ts
|
||||
export default defineAppConfig({
|
||||
app: { homePath: "/dashboard" },
|
||||
plugins: {
|
||||
disabled: ["integrations", "observational-memory", "sentry", "terminal"],
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
After enabling or changing auth, verify both signup and login land on an
|
||||
existing page rather than a 404.
|
||||
|
||||
When adding SQL-backed features, do **not** start with `find` / `cat` over
|
||||
`node_modules`. Read these two files first:
|
||||
|
||||
1. `drizzle/START_HERE.md` — table map, migrate commands, path map
|
||||
2. `drizzle/crud-action-example.ts` — copy-paste list/create/update/delete
|
||||
|
||||
Then use `getDb` / `schema` from `server/db.ts`. After a batch of related
|
||||
schema/action edits: one smoke test, one `pnpm typecheck` (see Verification).
|
||||
|
||||
- Guarded verification: run `pnpm agent-native:doctor`; fix findings before done.
|
||||
|
||||
## Verification
|
||||
|
||||
Run checks **once at the end of a batch of related edits**, not after every
|
||||
file, action, or small UI tweak. Dev already runs route/action typegen while
|
||||
`pnpm dev` is up — do not treat that as a reason to also run full typecheck
|
||||
after each write.
|
||||
|
||||
| Change shape | Verify with |
|
||||
| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
|
||||
| UI / copy / layout only | Formatter if the app has one; preview if something looks wrong. Skip full typecheck unless the edit touched types or imports. |
|
||||
| New/changed actions, schema, server, or shared types | One `pnpm typecheck` (and lint if the app has it) after the batch. |
|
||||
| New DB-backed CRUD | One smoke path only (e.g. create + list via `pnpm action …` or a single HTTP call). Do **not** CLI-test every action method. |
|
||||
|
||||
Do not re-run typecheck to "confirm" after a clean pass. If typecheck fails on
|
||||
unrelated pre-existing errors, fix or note them — do not thrash with repeated
|
||||
full runs and greps.
|
||||
|
||||
## Configuration is code, not env vars
|
||||
|
||||
Configure framework behavior in `agent-native.config.ts` via
|
||||
`defineAgentNativeConfig({ ... })`. App metadata consumed by `getAppConfig()`,
|
||||
including `app.homePath`, belongs in the existing `defineAppConfig` object in
|
||||
`server/plugins/config.ts`. Do **not** reach for `process.env` to drive app
|
||||
behavior, feature flags, or framework options. Environment variables are only
|
||||
for deploy-level secrets and host settings (see `secrets`); never add a
|
||||
`process.env` fallback to configure a feature.
|
||||
@@ -0,0 +1,77 @@
|
||||
# AlterFlixHub
|
||||
|
||||
ไดเรกทอรีโรงหนังอิสระ/อาร์ตเฮาส์และกลุ่มคนฉายหนังในประเทศไทย — ค้นหาโรงตามชื่อ/จังหวัด/หมวดหมู่ ดูรายละเอียดการเดินทาง ที่ตั้ง และช่องทางติดต่อของแต่ละโรง พร้อมหลังบ้านสำหรับแก้ข้อมูลได้เองโดยไม่ต้องแตะโค้ด
|
||||
|
||||
Stack: **React Router 8 (SSR) + Vite 8 + Tailwind 4 + TypeScript** บน Agent-Native runtime (Node/h3) · ข้อมูลเก็บเป็นไฟล์ JSON ใน `data/` · สถิติแบบ privacy-first (ไม่มีคุกกี้ ไม่เก็บ IP)
|
||||
|
||||
## เริ่มใช้งาน
|
||||
|
||||
```bash
|
||||
cp .env.example .env # ครั้งแรกเท่านั้น
|
||||
pnpm install
|
||||
pnpm dev # http://localhost:8080
|
||||
```
|
||||
|
||||
| คำสั่ง | ทำอะไร |
|
||||
|---|---|
|
||||
| `pnpm typecheck` | ตรวจ TypeScript ทั้งโปรเจกต์ |
|
||||
| `pnpm test` | รันสเปกทั้งหมด (vitest) |
|
||||
| `pnpm build` / `pnpm start` | build / รันโปรดักชัน |
|
||||
| `pnpm agent-native:doctor` | ตรวจสุขภาพโปรเจกต์ตามกฎของ framework |
|
||||
|
||||
## หน้าเว็บ
|
||||
|
||||
| Route | หน้า |
|
||||
|---|---|
|
||||
| `/` | หน้าแรก — ฮีโร่ค้นหา, แถบหมวด, กริดการ์ดโรงหนัง (รูปปกจาก `photos[0]` · **ลำดับการ์ดสลับเองทุกวัน** ไม่ให้ซ้ำตำแหน่งเดิม 2 วันติดกัน) |
|
||||
| `/cinema/<slug>` | รายละเอียดโรง — แกลเลอรี, สรุป, การเดินทาง, สิ่งอำนวยความสะดวก, ที่ตั้ง (แผนที่), ติดต่อ/ชำระเงิน |
|
||||
| `/about` | เกี่ยวกับเรา (เนื้อหาจากหลังบ้าน) |
|
||||
| `/admin` | หลังบ้าน (5 แท็บ) — ดู [docs/admin-guide.md](docs/admin-guide.md) |
|
||||
|
||||
รองรับ **ไทย/อังกฤษ** สลับที่ header หรือ `?lang=en` (จำค่าไว้ใน cookie + localStorage)
|
||||
|
||||
## หลังบ้าน
|
||||
|
||||
`http://localhost:8080/admin` — ล็อกอินด้วย `ADMIN_USERNAME` / `ADMIN_PASSWORD` (ค่าเริ่มต้น `it is me` / `it is me&it is me`)
|
||||
|
||||
แก้ได้: โรงหนัง (ชื่อ/slug/หมวด/สิ่งอำนวยความสะดวก/การเดินทาง/ติดต่อ/รูปภาพ/ที่ตั้ง/คำอธิบาย) · หน้าเกี่ยวกับเรา · คำศัพท์ทุกคำในหน้าเว็บ · Footer · ดูสถิติการค้นหา
|
||||
|
||||
คู่มือทีละงาน: **[docs/admin-guide.md](docs/admin-guide.md)**
|
||||
|
||||
## โครงสร้าง
|
||||
|
||||
```
|
||||
app/
|
||||
routes/ _index (หน้าแรก) · cinema.$slug · about · admin / admin_.login
|
||||
components/
|
||||
site/ SiteShell · SiteHeader/Footer · Logo · CinemaCard · CinemaGrid
|
||||
cinema/ Gallery · CinemaSummary · TransportList · FacilitiesSection · LocationPanel · ContactPanel
|
||||
admin/ AdminSection · CinemaList · ChipPicker · CommaListInput · SlugInput · PhotosEditor ·
|
||||
TransportEditor · ContactsEditor · CinemaFacilitiesEditor · AboutEditor
|
||||
lib/ cinemas · content.server · map-embed · popularity.server · analytics.* · i18n/ · geo
|
||||
server/
|
||||
routes/api/ admin/* (login, content, import, analytics) · analytics/collect
|
||||
data/
|
||||
content/content.json แหล่งข้อมูลจริงของโรงหนัง/คำศัพท์/about (แก้ผ่านหลังบ้าน)
|
||||
analytics/events.jsonl สถิติแบบ append-only
|
||||
docs/
|
||||
admin-guide.md คู่มือใช้งานหลังบ้าน (ภาษาไทย)
|
||||
api.md API reference
|
||||
architecture.html แผนผังการทำงาน Frontend/Backend/Data (เปิดด้วยเบราว์เซอร์)
|
||||
DESIGN.md สัญญาการออกแบบ (บังคับ) — สี ฟอนต์ โลโก้ layout กติกาข้อมูล
|
||||
AGENTS.md กฎสำหรับ agent/AI ที่แก้โค้ดโปรเจกต์นี้
|
||||
```
|
||||
|
||||
## ข้อมูลและสถิติ
|
||||
|
||||
- โรงหนัง/คำศัพท์/หน้าเกี่ยวกับเรา เก็บที่ `data/content/content.json` (หลังบ้านเขียนแบบ atomic)
|
||||
- สถิติเก็บที่ `data/analytics/events.jsonl` — event: `search`, `cinema_select`, `cinema_view`, `near_me`; ไม่ใช้คุกกี้ ไม่เก็บ IP/UA ดิบ
|
||||
- หมวด "ยอดนิยม" จะเริ่มจัดอันดับจากสถิติจริงเมื่อข้อมูลครบ **6 เดือน** ก่อนหน้านั้นใช้ป้ายที่ตั้งมือ
|
||||
- ตั้ง `ANALYTICS_SALT` ใน `.env` ก่อน deploy จริง
|
||||
|
||||
## เอกสารอื่น
|
||||
|
||||
- [DESIGN.md](DESIGN.md) — สัญญาการออกแบบ: พาเลตต์ ฟอนต์ โลโก้ layout ฟิลด์ข้อมูล และกติกากันข้อมูลหาย
|
||||
- [docs/api.md](docs/api.md) — endpoint ทั้งหมด (method/path/auth/body)
|
||||
- [docs/architecture.html](docs/architecture.html) — แผนผังการทำงาน
|
||||
- [DEVELOPING.md](DEVELOPING.md) — คู่มือ framework ของ starter (ไม่ใช่ของเฉพาะโปรเจกต์นี้)
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import action from "./hello";
|
||||
|
||||
describe("hello", () => {
|
||||
it("defaults name to world when omitted", async () => {
|
||||
const result = await action.run({});
|
||||
|
||||
expect(result).toEqual({ message: "Hello, world!" });
|
||||
});
|
||||
|
||||
it("greets the provided name", async () => {
|
||||
const result = await action.run({ name: "Steve" });
|
||||
|
||||
expect(result).toEqual({ message: "Hello, Steve!" });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,14 @@
|
||||
import { defineAction } from "@agent-native/core/action";
|
||||
import { z } from "zod";
|
||||
|
||||
export default defineAction({
|
||||
description: "Return a friendly greeting.",
|
||||
mcpTool: true,
|
||||
schema: z.object({
|
||||
name: z.string().default("world").describe("Name to greet"),
|
||||
}),
|
||||
http: { method: "GET" },
|
||||
run: async ({ name }) => {
|
||||
return { message: `Hello, ${name}!` };
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* Navigate the UI to a view.
|
||||
*
|
||||
* Writes a navigate command to application state which the UI reads and auto-deletes.
|
||||
*
|
||||
* Usage:
|
||||
* pnpm action navigate --view=home
|
||||
* pnpm action navigate --path=/some/route
|
||||
*
|
||||
* Options:
|
||||
* --view View name to navigate to
|
||||
* --path URL path to navigate to
|
||||
*/
|
||||
|
||||
import { defineAction, fail } from "@agent-native/core/action";
|
||||
import { writeAppStateForCurrentTab } from "@agent-native/core/application-state";
|
||||
import { z } from "zod";
|
||||
|
||||
export default defineAction({
|
||||
description:
|
||||
"Navigate the UI to a specific view or path. Writes a navigate command to application state which the UI reads and auto-deletes. The default product surface is the home canvas at /; agent chat stays in the right rail.",
|
||||
schema: z.object({
|
||||
view: z.string().optional().describe("View name to navigate to"),
|
||||
path: z.string().optional().describe("URL path to navigate to"),
|
||||
}),
|
||||
http: false,
|
||||
run: async (args) => {
|
||||
if (!args.view && !args.path) {
|
||||
fail("At least --view or --path is required.", {
|
||||
errorCode: "navigate_target_required",
|
||||
});
|
||||
}
|
||||
const nav: Record<string, string> = {};
|
||||
if (args.view) nav.view = args.view;
|
||||
if (args.path) nav.path = args.path;
|
||||
nav._writeId = `${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||||
await writeAppStateForCurrentTab("navigate", nav);
|
||||
return `Navigating to ${args.view || args.path}`;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,35 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const executeRequest = vi.fn();
|
||||
|
||||
vi.mock("@agent-native/core/provider-api", () => ({
|
||||
createProviderApiRuntime: () => ({ executeRequest }),
|
||||
}));
|
||||
|
||||
const { default: action, requiresProviderApiApproval } =
|
||||
await import("./provider-api-request");
|
||||
|
||||
describe("provider-api-request", () => {
|
||||
beforeEach(() => {
|
||||
executeRequest.mockReset();
|
||||
});
|
||||
|
||||
it("routes Slack reads through the shared provider runtime", async () => {
|
||||
executeRequest.mockResolvedValue({ ok: true, team: "Example" });
|
||||
|
||||
await expect(
|
||||
action.run({ provider: "slack", method: "GET", path: "/auth.test" }),
|
||||
).resolves.toEqual({ ok: true, team: "Example" });
|
||||
expect(executeRequest).toHaveBeenCalledWith({
|
||||
provider: "slack",
|
||||
method: "GET",
|
||||
path: "/auth.test",
|
||||
});
|
||||
});
|
||||
|
||||
it("requires approval for provider writes", () => {
|
||||
expect(requiresProviderApiApproval({ method: "GET" })).toBe(false);
|
||||
expect(requiresProviderApiApproval({ method: "HEAD" })).toBe(false);
|
||||
expect(requiresProviderApiApproval({ method: "POST" })).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,48 @@
|
||||
import { createProviderApiRuntime } from "@agent-native/core/provider-api";
|
||||
import { createProviderApiRequestAction } from "@agent-native/core/provider-api/actions/provider-api";
|
||||
import { z } from "zod";
|
||||
|
||||
const runtime = createProviderApiRuntime({
|
||||
appId: "chat",
|
||||
providerIds: ["slack"],
|
||||
});
|
||||
|
||||
const schema = z.object({
|
||||
provider: z.literal("slack").default("slack"),
|
||||
method: z
|
||||
.enum(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"])
|
||||
.default("GET"),
|
||||
path: z.string().min(1).describe("Slack Web API path, such as /auth.test."),
|
||||
query: z.unknown().optional().describe("Optional query parameters."),
|
||||
headers: z
|
||||
.record(z.string(), z.unknown())
|
||||
.optional()
|
||||
.describe("Optional non-authentication headers."),
|
||||
body: z.unknown().optional().describe("Optional request body."),
|
||||
connectionId: z
|
||||
.string()
|
||||
.trim()
|
||||
.min(1)
|
||||
.optional()
|
||||
.describe("Optional workspace connection to use."),
|
||||
timeoutMs: z.coerce.number().int().min(1_000).max(120_000).optional(),
|
||||
maxBytes: z.coerce
|
||||
.number()
|
||||
.int()
|
||||
.min(1_000)
|
||||
.max(4 * 1024 * 1024)
|
||||
.optional(),
|
||||
});
|
||||
|
||||
export function requiresProviderApiApproval(args: { method: string }): boolean {
|
||||
return args.method !== "GET" && args.method !== "HEAD";
|
||||
}
|
||||
|
||||
export default createProviderApiRequestAction(runtime, {
|
||||
appId: "chat",
|
||||
schema,
|
||||
http: false,
|
||||
needsApproval: requiresProviderApiApproval,
|
||||
description:
|
||||
"Call Slack's authenticated Web API through the user's workspace connection. Use this when the conversation needs a concrete Slack read or write. If Slack is not connected, the runtime pauses the run and surfaces the standard contextual connection card; do not replace that request with prose or ask for credentials in chat.",
|
||||
});
|
||||
@@ -0,0 +1,2 @@
|
||||
import { runScript } from "@agent-native/core/scripts";
|
||||
void runScript();
|
||||
@@ -0,0 +1,36 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
readAppState: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@agent-native/core/application-state", () => ({
|
||||
readAppState: mocks.readAppState,
|
||||
}));
|
||||
|
||||
import action from "./view-screen";
|
||||
|
||||
describe("view-screen", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it("returns the current navigation state when present", async () => {
|
||||
mocks.readAppState.mockResolvedValue({ view: "chat", threadId: "t1" });
|
||||
|
||||
const result = await action.run({});
|
||||
|
||||
expect(mocks.readAppState).toHaveBeenCalledWith("navigation");
|
||||
expect(result).toEqual({
|
||||
navigation: { view: "chat", threadId: "t1" },
|
||||
});
|
||||
});
|
||||
|
||||
it("returns a fallback message when there is no navigation state", async () => {
|
||||
mocks.readAppState.mockResolvedValue(null);
|
||||
|
||||
const result = await action.run({});
|
||||
|
||||
expect(result).toBe("No application state found. Is the app running?");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
/**
|
||||
* See what the user is currently looking at on screen.
|
||||
*
|
||||
* Reads and returns the current navigation state from application state.
|
||||
*
|
||||
* Usage:
|
||||
* pnpm action view-screen
|
||||
*/
|
||||
|
||||
import { defineAction } from "@agent-native/core/action";
|
||||
import { readAppState } from "@agent-native/core/application-state";
|
||||
import { z } from "zod";
|
||||
|
||||
export default defineAction({
|
||||
description:
|
||||
"See what the user is currently looking at on screen. Returns the current navigation state for the app canvas plus agent rail. Always call this first before taking any action.",
|
||||
schema: z.object({}),
|
||||
http: false,
|
||||
readOnly: true,
|
||||
run: async () => {
|
||||
const navigation = await readAppState("navigation");
|
||||
|
||||
const screen: Record<string, unknown> = {};
|
||||
if (navigation) screen.navigation = navigation;
|
||||
|
||||
if (Object.keys(screen).length === 0) {
|
||||
return "No application state found. Is the app running?";
|
||||
}
|
||||
return screen;
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { defineAgentNativeConfig } from "@agent-native/core/config";
|
||||
|
||||
export default defineAgentNativeConfig({
|
||||
changelog: { enabled: false },
|
||||
harness: true,
|
||||
onboarding: { firstRun: "off" },
|
||||
});
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"version": 1,
|
||||
"onboarding": {
|
||||
"firstRun": "off"
|
||||
},
|
||||
"doctor": {
|
||||
"failOnBuild": false
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { useState } from "react";
|
||||
|
||||
import type { AboutContent, AboutSection } from "@/lib/content-types";
|
||||
import type { Locale } from "@/lib/i18n/messages";
|
||||
|
||||
const inputClass =
|
||||
"w-full rounded-lg border border-[#303030] bg-[#141414] px-3 py-2 text-sm text-white outline-none transition focus:border-[#A92626] focus-visible:ring-2 focus-visible:ring-[#A92626]/40";
|
||||
const labelClass = "flex flex-col gap-1.5 text-xs text-[#999]";
|
||||
const buttonClass =
|
||||
"min-h-11 rounded-lg border border-[#303030] px-3 text-sm transition hover:border-[#A92626] hover:text-[#D47272] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#A92626]";
|
||||
const primaryButtonClass =
|
||||
"min-h-11 rounded-lg bg-[#8F0808] px-4 text-sm font-medium transition hover:bg-[#a30a0a] focus-visible:outline focus-visible:outline-2 focus-visible:outline-[#D47272]";
|
||||
|
||||
const LOCALE_TABS: Array<{ code: Locale; label: string }> = [
|
||||
{ code: "th", label: "ไทย" },
|
||||
{ code: "en", label: "English" },
|
||||
];
|
||||
|
||||
type AboutEditorProps = {
|
||||
value: Record<Locale, AboutContent>;
|
||||
defaults: Record<Locale, AboutContent>;
|
||||
onChange: (next: Record<Locale, AboutContent>) => void;
|
||||
onSave: () => void;
|
||||
saving: boolean;
|
||||
};
|
||||
|
||||
/**
|
||||
* ตัวแก้ไขหน้า "เกี่ยวกับเรา" — แยกแท็บตามภาษา มีตัวอย่างหน้าเว็บให้ดูสด ๆ
|
||||
* ฟิลด์ที่เว้นว่างจะถูกเซิร์ฟเวอร์คืนเป็นข้อความตั้งต้นให้อัตโนมัติ (sanitizeAbout)
|
||||
*/
|
||||
export function AboutEditor({
|
||||
value,
|
||||
defaults,
|
||||
onChange,
|
||||
onSave,
|
||||
saving,
|
||||
}: AboutEditorProps) {
|
||||
const [locale, setLocale] = useState<Locale>("th");
|
||||
const current = value[locale];
|
||||
|
||||
function patch(next: Partial<AboutContent>) {
|
||||
onChange({ ...value, [locale]: { ...current, ...next } });
|
||||
}
|
||||
|
||||
function patchSection(index: number, next: Partial<AboutSection>) {
|
||||
patch({
|
||||
sections: current.sections.map((section, i) =>
|
||||
i === index ? { ...section, ...next } : section,
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
function moveSection(index: number, direction: -1 | 1) {
|
||||
const target = index + direction;
|
||||
if (target < 0 || target >= current.sections.length) return;
|
||||
const sections = [...current.sections];
|
||||
const [moved] = sections.splice(index, 1);
|
||||
sections.splice(target, 0, moved);
|
||||
patch({ sections });
|
||||
}
|
||||
|
||||
function addSection() {
|
||||
patch({
|
||||
sections: [
|
||||
...current.sections,
|
||||
{ heading: `หัวข้อที่ ${current.sections.length + 1}`, body: "" },
|
||||
],
|
||||
});
|
||||
}
|
||||
|
||||
function removeSection(index: number) {
|
||||
patch({ sections: current.sections.filter((_, i) => i !== index) });
|
||||
}
|
||||
|
||||
function restoreDefaults() {
|
||||
onChange({ ...value, [locale]: defaults[locale] });
|
||||
}
|
||||
|
||||
const titleMissing = current.title.trim() === "";
|
||||
const leadTooLong = current.lead.length > 400;
|
||||
|
||||
return (
|
||||
<div className="px-6 py-5">
|
||||
<div className="mb-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div
|
||||
role="tablist"
|
||||
aria-label="ภาษา"
|
||||
className="flex items-center gap-1 rounded-lg border border-[#242424] bg-[#141414] p-1"
|
||||
>
|
||||
{LOCALE_TABS.map((tab) => (
|
||||
<button
|
||||
key={tab.code}
|
||||
type="button"
|
||||
role="tab"
|
||||
aria-selected={locale === tab.code}
|
||||
onClick={() => setLocale(tab.code)}
|
||||
className={`min-h-9 rounded-md px-4 text-sm transition ${
|
||||
locale === tab.code
|
||||
? "bg-[#242424] font-semibold text-[#D47272]"
|
||||
: "text-[#999] hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{tab.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2">
|
||||
<button type="button" className={buttonClass} onClick={restoreDefaults}>
|
||||
คืนค่าตั้งต้น ({locale.toUpperCase()})
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={primaryButtonClass}
|
||||
onClick={onSave}
|
||||
disabled={saving}
|
||||
>
|
||||
{saving ? "กำลังบันทึก…" : "บันทึกหน้าเกี่ยวกับเรา"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_360px]">
|
||||
<div className="flex flex-col gap-4">
|
||||
<label className={labelClass}>
|
||||
หัวข้อหลัก (H1)
|
||||
<input
|
||||
className={inputClass}
|
||||
value={current.title}
|
||||
onChange={(event) => patch({ title: event.target.value })}
|
||||
aria-describedby="about-title-help"
|
||||
aria-invalid={titleMissing}
|
||||
/>
|
||||
<span
|
||||
id="about-title-help"
|
||||
className={titleMissing ? "text-[#D47272]" : "text-[#8A8A8A]"}
|
||||
>
|
||||
{titleMissing
|
||||
? "ต้องมีหัวข้อ — ถ้าเว้นว่าง ระบบจะใช้ข้อความตั้งต้น"
|
||||
: `แสดงบนสุดของหน้า · ${current.title.length}/80 ตัวอักษร`}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<label className={labelClass}>
|
||||
ย่อหน้าแนะนำ (ใต้หัวข้อ)
|
||||
<textarea
|
||||
className={`${inputClass} min-h-24 leading-[1.7]`}
|
||||
value={current.lead}
|
||||
onChange={(event) => patch({ lead: event.target.value })}
|
||||
aria-describedby="about-lead-help"
|
||||
aria-invalid={leadTooLong}
|
||||
/>
|
||||
<span
|
||||
id="about-lead-help"
|
||||
className={leadTooLong ? "text-[#D47272]" : "text-[#8A8A8A]"}
|
||||
>
|
||||
{leadTooLong
|
||||
? "ยาวเกิน 400 ตัวอักษร — บนมือถือจะอ่านยาก"
|
||||
: `${current.lead.length}/400 ตัวอักษร`}
|
||||
</span>
|
||||
</label>
|
||||
|
||||
<fieldset className="flex flex-col gap-3">
|
||||
<legend className="mb-1 text-xs text-[#999]">
|
||||
ส่วนย่อย ({current.sections.length} ส่วน)
|
||||
</legend>
|
||||
|
||||
{current.sections.map((section, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="rounded-xl border border-[#242424] bg-[#141414] p-4"
|
||||
>
|
||||
<div className="mb-2 flex items-center justify-between gap-2">
|
||||
<span className="text-xs text-[#8A8A8A]">ส่วนที่ {index + 1}</span>
|
||||
<div className="flex items-center gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className="size-8 rounded-md text-[#999] transition hover:bg-[#242424] hover:text-white disabled:opacity-40"
|
||||
onClick={() => moveSection(index, -1)}
|
||||
disabled={index === 0}
|
||||
aria-label={`เลื่อนส่วนที่ ${index + 1} ขึ้น`}
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="size-8 rounded-md text-[#999] transition hover:bg-[#242424] hover:text-white disabled:opacity-40"
|
||||
onClick={() => moveSection(index, 1)}
|
||||
disabled={index === current.sections.length - 1}
|
||||
aria-label={`เลื่อนส่วนที่ ${index + 1} ลง`}
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="min-h-8 rounded-md px-2 text-xs text-[#D47272] transition hover:bg-[#242424]"
|
||||
onClick={() => removeSection(index)}
|
||||
>
|
||||
ลบ
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<label className={labelClass}>
|
||||
หัวข้อย่อย
|
||||
<input
|
||||
className={inputClass}
|
||||
value={section.heading}
|
||||
onChange={(event) =>
|
||||
patchSection(index, { heading: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className={`${labelClass} mt-2`}>
|
||||
เนื้อหา
|
||||
<textarea
|
||||
className={`${inputClass} min-h-24 leading-[1.75]`}
|
||||
value={section.body}
|
||||
onChange={(event) =>
|
||||
patchSection(index, { body: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`${buttonClass} self-start`}
|
||||
onClick={addSection}
|
||||
>
|
||||
+ เพิ่มส่วน
|
||||
</button>
|
||||
</fieldset>
|
||||
|
||||
<div className="rounded-xl border border-[#A92626]/40 bg-[#141414] p-4">
|
||||
<p className="mb-3 text-xs text-[#999]">กล่องติดต่อ (ท้ายหน้า)</p>
|
||||
<label className={labelClass}>
|
||||
หัวข้อ
|
||||
<input
|
||||
className={inputClass}
|
||||
value={current.contactHeading}
|
||||
onChange={(event) =>
|
||||
patch({ contactHeading: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className={`${labelClass} mt-2`}>
|
||||
ข้อความ
|
||||
<textarea
|
||||
className={`${inputClass} min-h-20 leading-[1.75]`}
|
||||
value={current.contactNote}
|
||||
onChange={(event) => patch({ contactNote: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<aside className="lg:sticky lg:top-24 lg:self-start">
|
||||
<p className="mb-2 text-xs text-[#8A8A8A]">ตัวอย่างหน้าเว็บ (สด)</p>
|
||||
<div className="rounded-xl border border-[#242424] bg-[#0D0D0D] p-4">
|
||||
<h3 className="text-xl font-bold leading-[1.3]">
|
||||
{current.title || "—"}
|
||||
</h3>
|
||||
<p className="mt-2 text-sm leading-[1.7] text-[#B3B3B3]">
|
||||
{current.lead || "—"}
|
||||
</p>
|
||||
<div className="mt-3 flex flex-col gap-2">
|
||||
{current.sections.map((section, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="rounded-lg border border-[#242424] bg-[#141414] p-3"
|
||||
>
|
||||
<p className="text-sm font-semibold">{section.heading}</p>
|
||||
<p className="mt-1 text-xs leading-[1.7] text-[#B3B3B3]">
|
||||
{section.body}
|
||||
</p>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<div className="mt-3 rounded-lg border border-[#A92626]/50 bg-gradient-to-b from-[#8F0808]/20 to-transparent p-3">
|
||||
<p className="text-sm font-semibold">{current.contactHeading}</p>
|
||||
<p className="mt-1 text-xs leading-[1.7] text-[#B3B3B3]">
|
||||
{current.contactNote}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<a
|
||||
href={`/about?lang=${locale}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="mt-3 inline-flex min-h-11 items-center text-xs text-[#D47272] underline-offset-4 hover:underline"
|
||||
>
|
||||
เปิดหน้า /about?lang={locale} ↗
|
||||
</a>
|
||||
</aside>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
import { IconChevronRight } from "@tabler/icons-react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
/**
|
||||
* หมวดการ์ดแบบพับได้ของหลังบ้าน (ใช้ <details> เนทีฟ — คีย์บอร์ดและ screen reader ทำงานได้เอง)
|
||||
* ค่าเริ่มต้น = พับเก็บ เพื่อไม่ให้หน้าแอดมินยืดยาว
|
||||
*/
|
||||
type Props = {
|
||||
title: string;
|
||||
description?: string;
|
||||
/** ข้อความสั้น ๆ เช่นจำนวนรายการ */
|
||||
badge?: string;
|
||||
defaultOpen?: boolean;
|
||||
children: ReactNode;
|
||||
};
|
||||
|
||||
export function AdminSection({
|
||||
title,
|
||||
description,
|
||||
badge,
|
||||
defaultOpen = false,
|
||||
children,
|
||||
}: Props) {
|
||||
return (
|
||||
<details
|
||||
open={defaultOpen}
|
||||
className="group overflow-hidden rounded-xl border border-[#242424] bg-[#111111]"
|
||||
>
|
||||
<summary className="flex cursor-pointer list-none items-center justify-between gap-3 px-4 py-3 transition hover:bg-[#171717] focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-[-2px] focus-visible:outline-[#A92626] [&::-webkit-details-marker]:hidden">
|
||||
<span className="flex min-w-0 items-center gap-2">
|
||||
<IconChevronRight
|
||||
size={16}
|
||||
className="shrink-0 text-[#8F8F8F] transition-transform group-open:rotate-90"
|
||||
/>
|
||||
<span className="truncate text-sm font-medium">{title}</span>
|
||||
{badge ? (
|
||||
<span className="shrink-0 rounded-full bg-[#242424] px-2 py-0.5 text-[11px] text-[#B3B3B3]">
|
||||
{badge}
|
||||
</span>
|
||||
) : null}
|
||||
</span>
|
||||
{description ? (
|
||||
<span className="hidden shrink-0 text-[11px] text-[#777] sm:block">
|
||||
{description}
|
||||
</span>
|
||||
) : null}
|
||||
</summary>
|
||||
<div className="border-t border-[#242424] px-4 py-4">{children}</div>
|
||||
</details>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
type ChipOption = {
|
||||
value: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
type ChipPickerProps = {
|
||||
options: ChipOption[];
|
||||
selected: string[];
|
||||
onToggle: (value: string) => void;
|
||||
/** ข้อความเมื่อยังไม่ได้เลือกอะไร */
|
||||
emptyHint?: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* ปุ่มเลือกหลายค่าแบบชิป สำหรับหลังบ้าน (หมวดหมู่ / สิ่งอำนวยความสะดวก)
|
||||
* ค่าที่เลือกจะถูกเก็บตามลำดับ options เสมอ เพื่อให้ข้อมูลในไฟล์นิ่ง
|
||||
*/
|
||||
export function ChipPicker({
|
||||
options,
|
||||
selected,
|
||||
onToggle,
|
||||
emptyHint,
|
||||
}: ChipPickerProps) {
|
||||
const chosen = new Set(selected);
|
||||
const known = new Set(options.map((option) => option.value));
|
||||
const extras = selected.filter((value) => !known.has(value));
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{options.map((option) => {
|
||||
const active = chosen.has(option.value);
|
||||
return (
|
||||
<button
|
||||
key={option.value}
|
||||
type="button"
|
||||
aria-pressed={active}
|
||||
onClick={() => onToggle(option.value)}
|
||||
className={`rounded-full border px-3 py-1 text-xs transition ${
|
||||
active
|
||||
? "border-[#A92626] bg-[rgba(143,8,8,0.18)] text-[#D47272]"
|
||||
: "border-[#303030] text-[#999] hover:border-[#A92626] hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{option.label}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
{extras.map((value) => (
|
||||
<button
|
||||
key={value}
|
||||
type="button"
|
||||
aria-pressed
|
||||
onClick={() => onToggle(value)}
|
||||
className="rounded-full border border-[#A92626] bg-[rgba(143,8,8,0.18)] px-3 py-1 text-xs text-[#D47272] transition hover:border-[#D47272]"
|
||||
>
|
||||
{value}
|
||||
</button>
|
||||
))}
|
||||
{options.length === 0 && extras.length === 0 && emptyHint ? (
|
||||
<span className="text-xs text-[#777]">{emptyHint}</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* สลับค่าหนึ่งตัวในลิสต์ แล้วเรียงตามลำดับ options (ค่าที่ไม่รู้จักต่อท้าย)
|
||||
*/
|
||||
export function toggleValue(
|
||||
selected: string[],
|
||||
value: string,
|
||||
order: string[],
|
||||
): string[] {
|
||||
const next = selected.includes(value)
|
||||
? selected.filter((item) => item !== value)
|
||||
: [...selected, value];
|
||||
const rank = (item: string) => {
|
||||
const index = order.indexOf(item);
|
||||
return index < 0 ? order.length + 1 : index;
|
||||
};
|
||||
return [...next].sort((a, b) => rank(a) - rank(b));
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { Cinema } from "@/lib/cinemas";
|
||||
import { DEFAULT_LOCALE, MESSAGES, type FacilityKey } from "@/lib/i18n/messages";
|
||||
|
||||
/**
|
||||
* แก้ข้อความสิ่งอำนวยความสะดวก "ของโรงนี้" (ผูกกับโรง ไม่ใช่ส่วนกลาง)
|
||||
*
|
||||
* - ชื่อหัวข้อ: ช่องเดียว (ใช้ทั้ง TH/EN) — ว่าง = ใช้ค่าเริ่มต้นจาก messages.ts
|
||||
* - คำอธิบาย TH/EN: แสดงเฉพาะโรงที่ต้องการ (hasDescriptions) เช่น เฮ้าส์ สามย่าน
|
||||
* ที่มีข้อมูลครบแล้ว โรงอื่นไม่ต้องกรอก
|
||||
*/
|
||||
|
||||
export type FacilityDetail = {
|
||||
label?: string;
|
||||
sub_th?: string;
|
||||
sub_en?: string;
|
||||
};
|
||||
|
||||
const ADMIN_MESSAGES = MESSAGES[DEFAULT_LOCALE];
|
||||
|
||||
type Props = {
|
||||
facilities: FacilityKey[];
|
||||
details: NonNullable<Cinema["facility_details"]>;
|
||||
hasDescriptions: boolean;
|
||||
onChange: (next: NonNullable<Cinema["facility_details"]>) => void;
|
||||
inputClass: string;
|
||||
labelClass: string;
|
||||
};
|
||||
|
||||
export function CinemaFacilitiesEditor({
|
||||
facilities,
|
||||
details,
|
||||
hasDescriptions,
|
||||
onChange,
|
||||
inputClass,
|
||||
labelClass,
|
||||
}: Props) {
|
||||
if (facilities.length === 0) {
|
||||
return (
|
||||
<span className="text-[11px] text-[#777]">
|
||||
เลือกหัวข้อด้านบนก่อน แล้วค่อยใส่ชื่อที่ต้องการ
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function update(key: FacilityKey, patch: FacilityDetail) {
|
||||
const current = details[key] ?? {};
|
||||
const next: FacilityDetail = { ...current, ...patch };
|
||||
const cleaned: FacilityDetail = {};
|
||||
if (next.label?.trim()) cleaned.label = next.label;
|
||||
if (next.sub_th?.trim()) cleaned.sub_th = next.sub_th;
|
||||
if (next.sub_en?.trim()) cleaned.sub_en = next.sub_en;
|
||||
onChange({ ...details, [key]: cleaned });
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
{facilities.map((key) => {
|
||||
const fallback = ADMIN_MESSAGES.facilities[key];
|
||||
const detail = details[key] ?? {};
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className="grid gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-2"
|
||||
>
|
||||
<label className={labelClass}>
|
||||
ชื่อหัวข้อ
|
||||
<input
|
||||
className={inputClass}
|
||||
value={detail.label ?? ""}
|
||||
placeholder={fallback.title}
|
||||
onChange={(event) => update(key, { label: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
{hasDescriptions ? (
|
||||
<>
|
||||
<label className={labelClass}>
|
||||
คำอธิบาย (TH)
|
||||
<input
|
||||
className={inputClass}
|
||||
value={detail.sub_th ?? ""}
|
||||
placeholder={fallback.sub}
|
||||
onChange={(event) =>
|
||||
update(key, { sub_th: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<label className={labelClass}>
|
||||
คำอธิบาย (EN)
|
||||
<input
|
||||
className={inputClass}
|
||||
value={detail.sub_en ?? ""}
|
||||
placeholder={MESSAGES.en.facilities[key].sub}
|
||||
onChange={(event) =>
|
||||
update(key, { sub_en: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import {
|
||||
IconArrowDown,
|
||||
IconArrowUp,
|
||||
IconGripVertical,
|
||||
IconSortAscendingLetters,
|
||||
} from "@tabler/icons-react";
|
||||
import { useMemo, useState } from "react";
|
||||
|
||||
import type { Cinema } from "@/lib/cinemas";
|
||||
|
||||
/**
|
||||
* รายชื่อโรงหนังในหลังบ้าน — เรียง ก-ฮ และสลับตำแหน่งได้
|
||||
*
|
||||
* - โหมด "ลำดับที่จัดไว้": ลากวางสลับที่ หรือกด ↑ ↓ (ใช้เมาส์/คีย์บอร์ดได้ทั้งคู่)
|
||||
* ลำดับที่ได้คือลำดับเดียวกับที่หน้าเว็บแสดง (อาร์เรย์ cinemas ใน content.json)
|
||||
* - โหมด "ก-ฮ": เรียงตามชื่อไทยด้วย Intl.Collator("th") — ยังไม่บันทึกจนกว่าจะกด "ใช้ลำดับนี้"
|
||||
* (กันเข้าใจผิดว่าลากในโหมดเรียงได้)
|
||||
*/
|
||||
|
||||
const thaiCollator = new Intl.Collator("th", {
|
||||
sensitivity: "base",
|
||||
numeric: true,
|
||||
});
|
||||
|
||||
function sortKey(cinema: Cinema): string {
|
||||
return (cinema.name_th?.trim() || cinema.name || "").trim();
|
||||
}
|
||||
|
||||
/** เรียงชื่อโรงหนังภาษาไทยตามพจนานุกรม ก-ฮ */
|
||||
export function sortCinemasByName(cinemas: Cinema[]): Cinema[] {
|
||||
return [...cinemas].sort((a, b) => thaiCollator.compare(sortKey(a), sortKey(b)));
|
||||
}
|
||||
|
||||
/** เทียบว่าสองลิสต์มี slug เรียงเหมือนกันหรือยัง */
|
||||
export function hasSameOrder(a: Cinema[], b: Cinema[]): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
return a.every((cinema, index) => cinema.slug === b[index]?.slug);
|
||||
}
|
||||
|
||||
/** ย้ายโรงหนังจากตำแหน่งหนึ่งไปแทรกก่อน/หลังอีกตัว */
|
||||
export function moveCinema(
|
||||
cinemas: Cinema[],
|
||||
fromSlug: string,
|
||||
toSlug: string,
|
||||
position: "before" | "after" = "before",
|
||||
): Cinema[] {
|
||||
if (fromSlug === toSlug) return cinemas;
|
||||
const from = cinemas.findIndex((item) => item.slug === fromSlug);
|
||||
const target = cinemas.findIndex((item) => item.slug === toSlug);
|
||||
if (from < 0 || target < 0) return cinemas;
|
||||
|
||||
const next = [...cinemas];
|
||||
const [moved] = next.splice(from, 1);
|
||||
const insertAt = next.findIndex((item) => item.slug === toSlug);
|
||||
if (insertAt < 0) return cinemas;
|
||||
next.splice(position === "after" ? insertAt + 1 : insertAt, 0, moved);
|
||||
return next;
|
||||
}
|
||||
|
||||
/** เลื่อนขึ้น/ลงทีละหนึ่งตำแหน่ง (สำหรับปุ่มลูกศร) */
|
||||
export function shiftCinema(cinemas: Cinema[], slug: string, delta: number): Cinema[] {
|
||||
const from = cinemas.findIndex((item) => item.slug === slug);
|
||||
const to = from + delta;
|
||||
if (from < 0 || to < 0 || to >= cinemas.length) return cinemas;
|
||||
const next = [...cinemas];
|
||||
const [moved] = next.splice(from, 1);
|
||||
next.splice(to, 0, moved);
|
||||
return next;
|
||||
}
|
||||
|
||||
type SortMode = "manual" | "thai";
|
||||
|
||||
type CinemaListProps = {
|
||||
cinemas: Cinema[];
|
||||
selected: string | null;
|
||||
/** ลำดับในหน้าเว็บยังไม่ตรงกับที่บันทึกไว้หรือไม่ */
|
||||
dirty: boolean;
|
||||
saving: boolean;
|
||||
onSelect: (slug: string) => void;
|
||||
onReorder: (next: Cinema[]) => void;
|
||||
onSaveOrder: () => void;
|
||||
};
|
||||
|
||||
const modeButtonClass = (active: boolean) =>
|
||||
`flex-1 rounded-md px-2 py-1 text-[11px] transition ${
|
||||
active ? "bg-[#242424] text-[#D47272]" : "text-[#999] hover:text-white"
|
||||
}`;
|
||||
|
||||
const arrowButtonClass =
|
||||
"flex size-6 items-center justify-center rounded text-[#777] transition hover:bg-[#242424] hover:text-white disabled:pointer-events-none disabled:opacity-30";
|
||||
|
||||
export function CinemaList({
|
||||
cinemas,
|
||||
selected,
|
||||
dirty,
|
||||
saving,
|
||||
onSelect,
|
||||
onReorder,
|
||||
onSaveOrder,
|
||||
}: CinemaListProps) {
|
||||
const [mode, setMode] = useState<SortMode>("manual");
|
||||
const [dragSlug, setDragSlug] = useState<string | null>(null);
|
||||
const [overSlug, setOverSlug] = useState<string | null>(null);
|
||||
|
||||
const visible = useMemo(
|
||||
() => (mode === "thai" ? sortCinemasByName(cinemas) : cinemas),
|
||||
[cinemas, mode],
|
||||
);
|
||||
|
||||
function handleDrop(event: React.DragEvent<HTMLLIElement>, toSlug: string) {
|
||||
event.preventDefault();
|
||||
const fromSlug = dragSlug ?? event.dataTransfer.getData("text/plain");
|
||||
setOverSlug(null);
|
||||
setDragSlug(null);
|
||||
if (!fromSlug || fromSlug === toSlug) return;
|
||||
onReorder(moveCinema(cinemas, fromSlug, toSlug));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-2 flex flex-col gap-2">
|
||||
<div className="flex items-center gap-1 rounded-lg border border-[#303030] p-1">
|
||||
<button
|
||||
type="button"
|
||||
className={modeButtonClass(mode === "manual")}
|
||||
aria-pressed={mode === "manual"}
|
||||
onClick={() => setMode("manual")}
|
||||
>
|
||||
ลำดับที่จัดไว้
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={modeButtonClass(mode === "thai")}
|
||||
aria-pressed={mode === "thai"}
|
||||
onClick={() => setMode("thai")}
|
||||
>
|
||||
<span className="inline-flex items-center justify-center gap-1">
|
||||
<IconSortAscendingLetters size={13} /> ก-ฮ
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{mode === "thai" ? (
|
||||
<div className="rounded-lg border border-[#303030] bg-[#141414] p-2 text-[11px] leading-[1.7] text-[#999]">
|
||||
เรียงตามชื่อไทย ก-ฮ · โหมดนี้ลากสลับไม่ได้
|
||||
<button
|
||||
type="button"
|
||||
className="mt-1 block w-full rounded-md border border-[#303030] px-2 py-1 text-[11px] text-[#D47272] transition hover:border-[#A92626]"
|
||||
onClick={() => {
|
||||
onReorder(sortCinemasByName(cinemas));
|
||||
setMode("manual");
|
||||
}}
|
||||
>
|
||||
ใช้ลำดับ ก-ฮ นี้ (แล้วกดบันทึก)
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<p className="px-1 text-[11px] leading-[1.6] text-[#777]">
|
||||
ลากชื่อเพื่อสลับตำแหน่ง หรือกด ↑ ↓ ทีละขั้น
|
||||
</p>
|
||||
)}
|
||||
|
||||
{dirty ? (
|
||||
<button
|
||||
type="button"
|
||||
disabled={saving}
|
||||
className="rounded-lg bg-[#8F0808] px-3 py-1.5 text-[11px] font-medium transition hover:bg-[#a30a0a] disabled:opacity-60"
|
||||
onClick={onSaveOrder}
|
||||
>
|
||||
{saving ? "กำลังบันทึก…" : "บันทึกลำดับใหม่"}
|
||||
</button>
|
||||
) : null}
|
||||
|
||||
<ul className="flex max-h-[62vh] flex-col gap-1 overflow-y-auto pr-1">
|
||||
{visible.map((item, index) => {
|
||||
const isSelected = item.slug === selected;
|
||||
const isDragging = dragSlug === item.slug;
|
||||
const isOver = overSlug === item.slug && dragSlug !== item.slug;
|
||||
return (
|
||||
<li
|
||||
key={item.slug}
|
||||
draggable={mode === "manual"}
|
||||
onDragStart={(event) => {
|
||||
setDragSlug(item.slug);
|
||||
event.dataTransfer.effectAllowed = "move";
|
||||
event.dataTransfer.setData("text/plain", item.slug);
|
||||
}}
|
||||
onDragOver={(event) => {
|
||||
if (mode !== "manual") return;
|
||||
event.preventDefault();
|
||||
event.dataTransfer.dropEffect = "move";
|
||||
setOverSlug(item.slug);
|
||||
}}
|
||||
onDragLeave={() => {
|
||||
setOverSlug((current) => (current === item.slug ? null : current));
|
||||
}}
|
||||
onDrop={(event) => handleDrop(event, item.slug)}
|
||||
onDragEnd={() => {
|
||||
setDragSlug(null);
|
||||
setOverSlug(null);
|
||||
}}
|
||||
className={`group flex items-center gap-1 rounded-lg pr-1 transition ${
|
||||
isSelected ? "bg-[#242424]" : "hover:bg-[#1B1B1B]"
|
||||
} ${isDragging ? "opacity-40" : ""} ${
|
||||
isOver ? "outline outline-2 outline-offset-[-2px] outline-[#A92626]" : ""
|
||||
} ${mode === "manual" ? "cursor-grab active:cursor-grabbing" : ""}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`pl-1 ${
|
||||
mode === "manual" ? "text-[#555] group-hover:text-[#999]" : "text-transparent"
|
||||
}`}
|
||||
>
|
||||
<IconGripVertical size={14} />
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onSelect(item.slug)}
|
||||
className={`min-w-0 flex-1 py-2 text-left text-sm transition ${
|
||||
isSelected ? "text-[#D47272]" : "text-[#B3B3B3] hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<span className="block truncate">{item.name_th || item.name}</span>
|
||||
<span className="block truncate text-[10px] text-[#777]">{item.slug}</span>
|
||||
</button>
|
||||
{mode === "manual" ? (
|
||||
<span className="flex flex-col">
|
||||
<button
|
||||
type="button"
|
||||
className={arrowButtonClass}
|
||||
aria-label={`เลื่อน ${item.name_th || item.name} ขึ้น`}
|
||||
disabled={index === 0}
|
||||
onClick={() => onReorder(shiftCinema(cinemas, item.slug, -1))}
|
||||
>
|
||||
<IconArrowUp size={13} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={arrowButtonClass}
|
||||
aria-label={`เลื่อน ${item.name_th || item.name} ลง`}
|
||||
disabled={index === visible.length - 1}
|
||||
onClick={() => onReorder(shiftCinema(cinemas, item.slug, 1))}
|
||||
>
|
||||
<IconArrowDown size={13} />
|
||||
</button>
|
||||
</span>
|
||||
) : null}
|
||||
</li>
|
||||
);
|
||||
})}
|
||||
</ul>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
/**
|
||||
* ช่องกรอกหลายค่า คั่นด้วย "," (เช่น หมวด, ช่องทางชำระเงิน)
|
||||
*
|
||||
* ทำไมต้องมี draft: ถ้าผูก value เข้ากับ array ตรง ๆ แล้ว split/join ทุกคีย์
|
||||
* ตัว "," ที่เพิ่งพิมพ์จะถูกตัดทิ้งทันที ( join(", ") ไม่มีตัวคั่นให้ค่าว่าง )
|
||||
* ทำให้พิมพ์คั่นค่าไม่ได้เลย — draft เก็บข้อความดิบระหว่างพิมพ์ แล้วค่อย
|
||||
* normalize เป็น ", " เมื่อออกจากช่อง
|
||||
*/
|
||||
|
||||
/** แปลงข้อความ → รายการ (รับ , , 、 และขึ้นบรรทัดใหม่เป็นตัวคั่นด้วย) */
|
||||
export function parseCommaList(value: string): string[] {
|
||||
return value
|
||||
.replace(/[,、]/g, ",")
|
||||
.split(/[,\n]/)
|
||||
.map((item) => item.trim())
|
||||
.filter((item) => item !== "");
|
||||
}
|
||||
|
||||
export function formatList(value: string[]): string {
|
||||
return value.join(", ");
|
||||
}
|
||||
|
||||
type CommaListInputProps = {
|
||||
value: string[];
|
||||
onChangeValue: (next: string[]) => void;
|
||||
className?: string;
|
||||
placeholder?: string;
|
||||
id?: string;
|
||||
};
|
||||
|
||||
export function CommaListInput({
|
||||
value,
|
||||
onChangeValue,
|
||||
className,
|
||||
placeholder,
|
||||
id,
|
||||
}: CommaListInputProps) {
|
||||
const canonical = formatList(value);
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
|
||||
// ค่าถูกเปลี่ยนจากที่อื่น (เช่น เปลี่ยนโรง / ใช้ JSON / คืนค่า) → ทิ้ง draft
|
||||
useEffect(() => {
|
||||
if (draft === null) return;
|
||||
if (formatList(parseCommaList(draft)) !== canonical) setDraft(null);
|
||||
}, [canonical, draft]);
|
||||
|
||||
return (
|
||||
<input
|
||||
id={id}
|
||||
className={className}
|
||||
placeholder={placeholder}
|
||||
value={draft ?? canonical}
|
||||
spellCheck={false}
|
||||
onChange={(event) => {
|
||||
const text = event.target.value;
|
||||
setDraft(text);
|
||||
onChangeValue(parseCommaList(text));
|
||||
}}
|
||||
onBlur={() => setDraft(null)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
|
||||
import type { ContactChannel } from "@/lib/cinemas";
|
||||
|
||||
/**
|
||||
* แก้ช่องทางติดต่อของการ์ด "สอบถามข้อมูลและจองตั๋ว" ต่อโรง
|
||||
* แต่ละแถว = label / ค่าที่แสดง / ลิงก์ (ถ้าไม่มีลิงก์ หน้าเว็บแสดงเป็นข้อความธรรมดา)
|
||||
*/
|
||||
|
||||
const SUGGESTED_LABELS = [
|
||||
"Website",
|
||||
"Facebook",
|
||||
"Instagram",
|
||||
"Line",
|
||||
"Call",
|
||||
"อีเมล",
|
||||
"จองตั๋ว",
|
||||
];
|
||||
|
||||
const smallButtonClass =
|
||||
"flex min-h-9 items-center gap-1 rounded-lg border border-[#303030] px-2 text-xs text-[#999] transition hover:border-[#A92626] hover:text-[#D47272]";
|
||||
|
||||
type Props = {
|
||||
contacts: ContactChannel[];
|
||||
onChange: (next: ContactChannel[]) => void;
|
||||
inputClass: string;
|
||||
labelClass: string;
|
||||
};
|
||||
|
||||
export function ContactsEditor({ contacts, onChange, inputClass, labelClass }: Props) {
|
||||
function updateAt(index: number, patch: Partial<ContactChannel>) {
|
||||
onChange(
|
||||
contacts.map((item, i) => (i === index ? { ...item, ...patch } : item)),
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-[#999]">ช่องทางติดต่อ / จองตั๋ว</span>
|
||||
|
||||
{contacts.length === 0 ? (
|
||||
<span className="text-[11px] text-[#777]">
|
||||
ยังไม่มีช่องทางติดต่อ — หน้าเว็บจะขึ้น “ยังไม่ระบุช่องทางติดต่อ”
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{contacts.map((contact, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="grid gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-[130px_minmax(0,1fr)_minmax(0,1fr)_auto]"
|
||||
>
|
||||
<label className={labelClass}>
|
||||
ป้ายชื่อ
|
||||
<input
|
||||
className={inputClass}
|
||||
value={contact.label}
|
||||
placeholder="Website"
|
||||
list="contact-label-options"
|
||||
onChange={(event) => updateAt(index, { label: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className={labelClass}>
|
||||
ข้อความที่แสดง
|
||||
<input
|
||||
className={inputClass}
|
||||
value={contact.value}
|
||||
placeholder="www.housesamyan.com"
|
||||
onChange={(event) => updateAt(index, { value: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className={labelClass}>
|
||||
ลิงก์ (ไม่บังคับ)
|
||||
<input
|
||||
className={inputClass}
|
||||
value={contact.href ?? ""}
|
||||
placeholder="https://… หรือ tel:+66…"
|
||||
onChange={(event) =>
|
||||
updateAt(index, {
|
||||
href: event.target.value.trim() === "" ? null : event.target.value,
|
||||
})
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<button
|
||||
type="button"
|
||||
className={smallButtonClass}
|
||||
aria-label={`ลบช่องทางที่ ${index + 1}`}
|
||||
onClick={() => onChange(contacts.filter((_, i) => i !== index))}
|
||||
>
|
||||
<IconTrash size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<datalist id="contact-label-options">
|
||||
{SUGGESTED_LABELS.map((label) => (
|
||||
<option key={label} value={label} />
|
||||
))}
|
||||
</datalist>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`${smallButtonClass} w-fit`}
|
||||
onClick={() => onChange([...contacts, { label: "", value: "", href: null }])}
|
||||
>
|
||||
<IconPlus size={14} />
|
||||
เพิ่มช่องทางติดต่อ
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
|
||||
/**
|
||||
* แก้รายการรูปโรงหนัง (อาร์เรย์ `photos`) — ใส่เป็น URL หรือ path ในโปรเจกต์
|
||||
* รูปแรกใช้เป็นภาพหลักของแกลเลอรี · ลากสลับลำดับไม่ได้ ใช้ปุ่ม ↑/↓ แทน
|
||||
*/
|
||||
type Props = {
|
||||
photos: string[];
|
||||
onChange: (next: string[]) => void;
|
||||
inputClass: string;
|
||||
labelClass: string;
|
||||
};
|
||||
|
||||
const smallButtonClass =
|
||||
"flex min-h-9 items-center gap-1 rounded-lg border border-[#303030] px-2 text-xs text-[#999] transition hover:border-[#A92626] hover:text-[#D47272]";
|
||||
|
||||
export function PhotosEditor({ photos, onChange, inputClass, labelClass }: Props) {
|
||||
function updateAt(index: number, value: string) {
|
||||
onChange(photos.map((item, i) => (i === index ? value : item)));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-[#999]">รูปภาพโรงหนัง</span>
|
||||
|
||||
{photos.length === 0 ? (
|
||||
<span className="text-[11px] text-[#777]">
|
||||
ยังไม่มีรูป — หน้าเว็บจะแสดงช่องแทน (ภาพที่ 1/2/3)
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{photos.map((photo, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="grid items-center gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-[64px_minmax(0,1fr)_auto_auto]"
|
||||
>
|
||||
<div className="size-16 overflow-hidden rounded-md border border-[#303030] bg-[#141414]">
|
||||
{photo ? (
|
||||
// eslint-disable-next-line jsx-a11y/alt-text
|
||||
<img
|
||||
src={photo}
|
||||
alt=""
|
||||
className="size-full object-cover"
|
||||
loading="lazy"
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<label className={labelClass}>
|
||||
{index === 0 ? "รูปหลัก (URL หรือ /images/...)" : `รูปที่ ${index + 1}`}
|
||||
<input
|
||||
className={inputClass}
|
||||
value={photo}
|
||||
placeholder="/images/hero.png หรือ https://…/photo.jpg"
|
||||
onChange={(event) => updateAt(index, event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex gap-1">
|
||||
<button
|
||||
type="button"
|
||||
className={smallButtonClass}
|
||||
aria-label={`เลื่อนรูปที่ ${index + 1} ขึ้น`}
|
||||
disabled={index === 0}
|
||||
onClick={() => {
|
||||
const next = [...photos];
|
||||
[next[index - 1], next[index]] = [next[index], next[index - 1]];
|
||||
onChange(next);
|
||||
}}
|
||||
>
|
||||
↑
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className={smallButtonClass}
|
||||
aria-label={`เลื่อนรูปที่ ${index + 1} ลง`}
|
||||
disabled={index === photos.length - 1}
|
||||
onClick={() => {
|
||||
const next = [...photos];
|
||||
[next[index + 1], next[index]] = [next[index], next[index + 1]];
|
||||
onChange(next);
|
||||
}}
|
||||
>
|
||||
↓
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
className={smallButtonClass}
|
||||
aria-label={`ลบรูปที่ ${index + 1}`}
|
||||
onClick={() => onChange(photos.filter((_, i) => i !== index))}
|
||||
>
|
||||
<IconTrash size={14} />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`${smallButtonClass} w-fit`}
|
||||
onClick={() => onChange([...photos, ""])}
|
||||
>
|
||||
<IconPlus size={14} />
|
||||
เพิ่มรูป
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
|
||||
/**
|
||||
* ช่องแก้ slug (ใช้ใน URL) ของโรงหนัง
|
||||
*
|
||||
* ทำไมของเดิม "แก้ไม่ได้": อินพุตผูกกับ `cinema.slug` ตรง ๆ และแปลงค่าทุกคีย์
|
||||
* (`replace(/[^a-z0-9-]/g, "-")`) — พอพิมพ์ตัวอักษรไทย/เว้นวรรค มันกลายเป็น "-"
|
||||
* ทันที และถ้าลบจนว่าง ค่าก็ว่างทันที ทำให้ดูเหมือนพิมพ์อะไรไม่ได้เลย
|
||||
*
|
||||
* ที่นี่เก็บ "ข้อความดิบ" ระหว่างพิมพ์ (draft) แล้วค่อยจัดรูปตอนออกจากช่อง (blur)
|
||||
* slug ว่างหรือซ้ำกับโรงอื่นจะไม่ถูกบันทึก — คืนค่าเดิมให้
|
||||
*/
|
||||
|
||||
const SLUG_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
|
||||
|
||||
/** จัดรูป slug: ตัวเล็ก, ช่องว่าง/ขีดซ้ำ → ขีดเดียว, ตัดอักขระที่ไม่ใช่ a-z0-9- */
|
||||
export function normalizeSlug(value: string): string {
|
||||
return value
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[\s_]+/g, "-")
|
||||
.replace(/[^a-z0-9-]/g, "")
|
||||
.replace(/-{2,}/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* แนะนำ slug จากชื่อโรงหนังภาษาอังกฤษ
|
||||
* "HOUSE CINEMA SAMYAN" → "house-cinema-samyan" · "." และอักขระอื่นถูกตัดให้เอง
|
||||
*/
|
||||
export function suggestSlug(name: string): string {
|
||||
return normalizeSlug(
|
||||
name
|
||||
.normalize("NFKD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.replace(/&/g, " and ")
|
||||
.replace(/['’]/g, ""),
|
||||
);
|
||||
}
|
||||
|
||||
/** เหตุผลที่ slug ใช้ไม่ได้ (null = ใช้ได้) */
|
||||
export function slugProblem(
|
||||
slug: string,
|
||||
options: { others: string[]; self?: string },
|
||||
): string | null {
|
||||
if (slug === "") return "slug ว่างไม่ได้";
|
||||
if (!SLUG_PATTERN.test(slug)) return "ใช้ได้เฉพาะ a-z, 0-9 และ - (ห้ามขีดติดกัน/หัวท้าย)";
|
||||
if (options.others.some((other) => other === slug && other !== options.self)) {
|
||||
return "slug นี้มีโรงอื่นใช้อยู่";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
type SlugInputProps = {
|
||||
value: string;
|
||||
/** slug ของโรงอื่นทั้งหมด ใช้ตรวจซ้ำ */
|
||||
others: string[];
|
||||
onChange: (slug: string) => void;
|
||||
className?: string;
|
||||
};
|
||||
|
||||
export function SlugInput({ value, others, onChange, className }: SlugInputProps) {
|
||||
const [draft, setDraft] = useState<string | null>(null);
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const lastValue = useRef(value);
|
||||
|
||||
// ค่าถูกเปลี่ยนจากภายนอก (สลับโรง / ใช้ JSON / คืนค่า) → ทิ้ง draft
|
||||
// เทียบกับค่าก่อนหน้า ไม่ใช่เทียบกับ draft เพราะระหว่างพิมพ์ value ยังไม่เปลี่ยน
|
||||
useEffect(() => {
|
||||
if (lastValue.current === value) return;
|
||||
lastValue.current = value;
|
||||
setDraft(null);
|
||||
}, [value]);
|
||||
|
||||
const shown = draft ?? value;
|
||||
const preview = normalizeSlug(shown);
|
||||
const problem = slugProblem(preview, { others, self: value });
|
||||
const dirty = preview !== value;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1">
|
||||
<input
|
||||
className={className}
|
||||
value={shown}
|
||||
spellCheck={false}
|
||||
placeholder="house-cinema-samyan"
|
||||
onChange={(event) => {
|
||||
setDraft(event.target.value);
|
||||
setNotice(null);
|
||||
}}
|
||||
onBlur={() => {
|
||||
const next = normalizeSlug(draft ?? value);
|
||||
if (next !== "" && slugProblem(next, { others, self: value }) === null) {
|
||||
if (next !== value) {
|
||||
onChange(next);
|
||||
setNotice("เปลี่ยน slug แล้ว — ลิงก์เดิมของโรงนี้จะใช้ไม่ได้ (ต้องกดบันทึก)");
|
||||
}
|
||||
} else if (next !== value) {
|
||||
setNotice("slug ไม่ถูกบันทึก (ว่าง/ซ้ำ/รูปแบบไม่ถูก) — คงค่าเดิมไว้");
|
||||
}
|
||||
setDraft(null);
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className="flex flex-wrap items-center gap-2 text-[11px]">
|
||||
<code className="text-[#777]">/cinema/{preview || "…"}</code>
|
||||
{problem && dirty ? (
|
||||
<span className="text-[#D47272]">{problem}</span>
|
||||
) : null}
|
||||
{!problem && dirty ? (
|
||||
<span className="text-[#B3B3B3]">กด Tab/คลิกออกเพื่อยืนยัน slug ใหม่</span>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{notice ? (
|
||||
<span className="text-[11px] text-[#D47272]">{notice}</span>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import { IconPlus, IconTrash } from "@tabler/icons-react";
|
||||
|
||||
import type { TransportMode } from "@/lib/cinemas";
|
||||
import { DEFAULT_LOCALE, MESSAGES } from "@/lib/i18n/messages";
|
||||
|
||||
/**
|
||||
* แก้ไขข้อมูลการเดินทางของโรงหนัง (รถยนต์ส่วนตัว / รถไฟฟ้า / รถประจำทาง)
|
||||
* เรียงตามลำดับในอาร์เรย์ transport ของ content.json
|
||||
*/
|
||||
|
||||
const ADMIN_MESSAGES = MESSAGES[DEFAULT_LOCALE];
|
||||
const ICON_OPTIONS: Array<TransportMode["icon_name"]> = [
|
||||
"private_car",
|
||||
"metro",
|
||||
"bus",
|
||||
];
|
||||
|
||||
type TransportEditorProps = {
|
||||
value: TransportMode[];
|
||||
onChange: (next: TransportMode[]) => void;
|
||||
inputClass: string;
|
||||
labelClass: string;
|
||||
};
|
||||
|
||||
const smallButtonClass =
|
||||
"flex min-h-9 items-center gap-1 rounded-lg border border-[#303030] px-2 text-xs text-[#999] transition hover:border-[#A92626] hover:text-[#D47272]";
|
||||
|
||||
export function TransportEditor({
|
||||
value,
|
||||
onChange,
|
||||
inputClass,
|
||||
labelClass,
|
||||
}: TransportEditorProps) {
|
||||
function updateAt(index: number, patch: Partial<TransportMode>) {
|
||||
onChange(value.map((item, i) => (i === index ? { ...item, ...patch } : item)));
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-xs text-[#999]">การเดินทาง</span>
|
||||
|
||||
{value.length === 0 ? (
|
||||
<span className="text-[11px] text-[#777]">
|
||||
ยังไม่มีข้อมูล — หน้าเว็บจะซ่อนบล็อกการเดินทาง
|
||||
</span>
|
||||
) : null}
|
||||
|
||||
{value.map((route, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="grid gap-2 rounded-lg border border-[#242424] p-2 sm:grid-cols-[130px_minmax(0,1fr)_minmax(0,1fr)_auto]"
|
||||
>
|
||||
<label className={labelClass}>
|
||||
วิธีเดินทาง
|
||||
<select
|
||||
className={inputClass}
|
||||
value={route.icon_name}
|
||||
onChange={(event) =>
|
||||
updateAt(index, {
|
||||
icon_name: event.target.value as TransportMode["icon_name"],
|
||||
})
|
||||
}
|
||||
>
|
||||
{ICON_OPTIONS.map((icon) => (
|
||||
<option key={icon} value={icon}>
|
||||
{ADMIN_MESSAGES.transport[icon]}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</label>
|
||||
<label className={labelClass}>
|
||||
รายละเอียด (TH)
|
||||
<input
|
||||
className={inputClass}
|
||||
value={route.value}
|
||||
placeholder="MRT สถานีสามย่าน"
|
||||
onChange={(event) => updateAt(index, { value: event.target.value })}
|
||||
/>
|
||||
</label>
|
||||
<label className={labelClass}>
|
||||
รายละเอียด (EN)
|
||||
<input
|
||||
className={inputClass}
|
||||
value={route.value_en ?? ""}
|
||||
placeholder="MRT Sam Yan station"
|
||||
onChange={(event) =>
|
||||
updateAt(index, { value_en: event.target.value })
|
||||
}
|
||||
/>
|
||||
</label>
|
||||
<div className="flex items-end">
|
||||
<button
|
||||
type="button"
|
||||
className={smallButtonClass}
|
||||
aria-label={`ลบวิธีเดินทางลำดับที่ ${index + 1}`}
|
||||
onClick={() => onChange(value.filter((_, i) => i !== index))}
|
||||
>
|
||||
<IconTrash size={14} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
|
||||
<button
|
||||
type="button"
|
||||
className={`${smallButtonClass} w-fit`}
|
||||
onClick={() =>
|
||||
onChange([...value, { icon_name: "bus", value: "", value_en: "" }])
|
||||
}
|
||||
>
|
||||
<IconPlus size={14} />
|
||||
เพิ่มวิธีเดินทาง
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseCommaList, formatList } from "@/components/admin/CommaListInput";
|
||||
import { normalizeSlug, slugProblem, suggestSlug } from "@/components/admin/SlugInput";
|
||||
|
||||
/**
|
||||
* สเปกของตัวช่วยในหลังบ้าน — กันบั๊กที่เคยเจอจริง
|
||||
* 1) ช่องคั่นด้วย "," ที่กลืนตัวคั่นระหว่างพิมพ์
|
||||
* 2) slug ที่พิมพ์ไทย/เว้นวรรคแล้วหาย
|
||||
*/
|
||||
|
||||
describe("parseCommaList", () => {
|
||||
it("แยกด้วย , และตัดช่องว่างหัวท้าย", () => {
|
||||
expect(parseCommaList("อาร์ตเฮาส์, สารคดี")).toEqual(["อาร์ตเฮาส์", "สารคดี"]);
|
||||
});
|
||||
|
||||
it("ทิ้งค่าว่าง และรับตัวคั่นเต็มความกว้าง/ขึ้นบรรทัดใหม่", () => {
|
||||
expect(parseCommaList("เงินสด, , โอน")).toEqual(["เงินสด", "โอน"]);
|
||||
expect(parseCommaList("เงินสด,โอน")).toEqual(["เงินสด", "โอน"]);
|
||||
expect(parseCommaList("ก\nข")).toEqual(["ก", "ข"]);
|
||||
});
|
||||
|
||||
it("ค่าว่างได้อาร์เรย์ว่าง", () => {
|
||||
expect(parseCommaList(" ")).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatList", () => {
|
||||
it("ต่อด้วย ', ' เสมอ", () => {
|
||||
expect(formatList(["a", "b"])).toBe("a, b");
|
||||
expect(formatList([])).toBe("");
|
||||
});
|
||||
});
|
||||
|
||||
describe("normalizeSlug", () => {
|
||||
it("ตัวเล็ก + ช่องว่างเป็นขีด", () => {
|
||||
expect(normalizeSlug("Mecani Cinema")).toBe("mecani-cinema");
|
||||
});
|
||||
|
||||
it("ตัดอักขระที่ไม่ใช่ a-z0-9- และยุบขีดซ้ำ", () => {
|
||||
expect(normalizeSlug(" HOUSE & Co. ")).toBe("house-co");
|
||||
expect(normalizeSlug("a__b")).toBe("a-b");
|
||||
expect(normalizeSlug("--a--b--")).toBe("a-b");
|
||||
});
|
||||
|
||||
it("ภาษาไทยล้วนได้ค่าว่าง (ไม่ยอมให้บันทึก พร้อมเหตุผล)", () => {
|
||||
expect(normalizeSlug("เมคานี ใหม่")).toBe("");
|
||||
expect(slugProblem("", { others: [] })).toBe("slug ว่างไม่ได้");
|
||||
});
|
||||
});
|
||||
|
||||
describe("suggestSlug", () => {
|
||||
it("แปลงชื่ออังกฤษเป็น slug", () => {
|
||||
expect(suggestSlug("HOUSE CINEMA SAMYAN")).toBe("house-cinema-samyan");
|
||||
expect(suggestSlug("MECANI")).toBe("mecani");
|
||||
});
|
||||
|
||||
it("& กลายเป็น 'and' และตัด apostrophe", () => {
|
||||
expect(suggestSlug("Doc Club & Friends")).toBe("doc-club-and-friends");
|
||||
expect(suggestSlug("O'Brien Cinema")).toBe("obrien-cinema");
|
||||
});
|
||||
|
||||
it("ตัดเสียง accent", () => {
|
||||
expect(suggestSlug("Café Lumière")).toBe("cafe-lumiere");
|
||||
});
|
||||
});
|
||||
|
||||
describe("slugProblem", () => {
|
||||
it("ซ้ำกับโรงอื่น = ใช้ไม่ได้", () => {
|
||||
expect(
|
||||
slugProblem("mecani", { others: ["mecani", "loprama"], self: "loprama" }),
|
||||
).toBe("slug นี้มีโรงอื่นใช้อยู่");
|
||||
});
|
||||
|
||||
it("ซ้ำกับตัวเอง = ผ่าน (ตอนแก้ฟิลด์อื่น)", () => {
|
||||
expect(slugProblem("mecani", { others: ["mecani"], self: "mecani" })).toBeNull();
|
||||
});
|
||||
|
||||
it("รูปแบบผิด เช่นขีดหัว/ท้าย = ใช้ไม่ได้", () => {
|
||||
expect(slugProblem("-mecani", { others: [] })).toContain("a-z");
|
||||
expect(slugProblem("mecani--x", { others: [] })).toContain("a-z");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { Link } from "react-router";
|
||||
|
||||
import { SiteShell } from "@/components/site/SiteShell";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
|
||||
/** หน้า fallback เมื่อ slug ไม่ตรงกับโรงหนังที่มีอยู่ */
|
||||
export function CinemaNotFound() {
|
||||
const { messages } = useI18n();
|
||||
|
||||
return (
|
||||
<SiteShell variant="detail">
|
||||
<main className="relative z-10 mx-auto flex max-w-[1440px] flex-col items-center gap-6 px-5 py-32 text-center md:px-[108px]">
|
||||
<h1 className="text-3xl font-bold">{messages.notFound.title}</h1>
|
||||
<p className="text-[#B3B3B3]">{messages.notFound.text}</p>
|
||||
<Link
|
||||
to="/"
|
||||
className="rounded-lg px-6 py-2 font-medium"
|
||||
style={{ background: COLORS.brand }}
|
||||
>
|
||||
{messages.notFound.cta}
|
||||
</Link>
|
||||
</main>
|
||||
</SiteShell>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { IconMap, IconMapPin } from "@tabler/icons-react";
|
||||
|
||||
import {
|
||||
cinemaDescription,
|
||||
cinemaLocationLabel,
|
||||
cinemaName,
|
||||
type Cinema,
|
||||
} from "@/lib/cinemas";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
|
||||
/** หัวโรงหนัง: ป้ายประเภท + ชื่อ + ที่ตั้ง + ปุ่มแผนที่ + คำอธิบาย */
|
||||
export function CinemaSummary({ cinema }: { cinema: Cinema }) {
|
||||
const { locale, messages } = useI18n();
|
||||
const locationLabel = cinemaLocationLabel(cinema, locale);
|
||||
const description = cinemaDescription(cinema, locale);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-6">
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{cinema.tags.map((tag) => (
|
||||
<span
|
||||
key={tag}
|
||||
className="rounded-[18px] border border-[#A92626] px-4 py-2 text-sm text-[#D47272]"
|
||||
style={{ background: COLORS.pillGradient }}
|
||||
>
|
||||
{messages.tags[tag] ?? tag}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
<h1 className="text-[40px] font-bold leading-[1.3]">
|
||||
{cinemaName(cinema, locale)}
|
||||
</h1>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-between gap-4">
|
||||
<div className="flex items-center gap-2 text-lg">
|
||||
<IconMapPin size={24} className="shrink-0" />
|
||||
{locationLabel || messages.card.locationFallback}
|
||||
</div>
|
||||
{cinema.map_url ? (
|
||||
<a
|
||||
href={cinema.map_url}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex w-[200px] items-center justify-center gap-2 rounded-lg border border-white px-4 py-2 text-lg font-medium"
|
||||
>
|
||||
{messages.detail.openMap}
|
||||
<IconMap size={24} />
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{description ? (
|
||||
<p className="text-xl leading-[1.3]">{description}</p>
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { IconCircleCheck, IconExternalLink } from "@tabler/icons-react";
|
||||
|
||||
import type { Cinema, ContactChannel } from "@/lib/cinemas";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { translate } from "@/lib/i18n/messages";
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
|
||||
function isExternal(href: string | null): boolean {
|
||||
return href !== null && href.startsWith("http");
|
||||
}
|
||||
|
||||
function ContactRow({ channel }: { channel: ContactChannel }) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-[#999]">{channel.label}</span>
|
||||
<a
|
||||
href={channel.href ?? undefined}
|
||||
target={isExternal(channel.href) ? "_blank" : undefined}
|
||||
rel="noreferrer"
|
||||
className="flex items-center justify-between"
|
||||
>
|
||||
<span>{channel.value}</span>
|
||||
<IconExternalLink size={16} />
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** กล่องติดต่อ/จองตั๋ว — แต่ละส่วนซ่อนได้ถ้ายังไม่มีข้อมูล */
|
||||
export function ContactPanel({ cinema }: { cinema: Cinema }) {
|
||||
const { messages } = useI18n();
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="flex flex-col justify-between gap-6 rounded-xl p-6"
|
||||
style={{ border: `1px solid ${COLORS.border}` }}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
<h2 className="text-2xl font-semibold leading-[1.3]">
|
||||
{(cinema.contact_heading?.trim() || messages.detail.contactTitle)}
|
||||
</h2>
|
||||
|
||||
{cinema.contacts.length === 0 ? (
|
||||
<p className="text-sm text-[#999]">{messages.detail.contactsFallback}</p>
|
||||
) : (
|
||||
cinema.contacts.map((channel) => (
|
||||
<ContactRow key={channel.label} channel={channel} />
|
||||
))
|
||||
)}
|
||||
|
||||
<div className="flex flex-col gap-3">
|
||||
<span className="text-sm text-[#999]">
|
||||
{messages.detail.paymentMethods}
|
||||
</span>
|
||||
{cinema.payments.length === 0 ? (
|
||||
<span className="text-sm text-[#999]">
|
||||
{messages.detail.paymentsFallback}
|
||||
</span>
|
||||
) : (
|
||||
<div className="flex flex-wrap items-center gap-6">
|
||||
{cinema.payments.map((payment) => (
|
||||
<span key={payment} className="flex items-center gap-1 text-sm">
|
||||
<IconCircleCheck size={16} />
|
||||
{translate(messages.payments, payment)}
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import {
|
||||
IconBook,
|
||||
IconBriefcase,
|
||||
IconCoffee,
|
||||
IconPlant2,
|
||||
IconShoppingBag,
|
||||
IconSofa,
|
||||
IconTicket,
|
||||
IconToolsKitchen2,
|
||||
type Icon as TablerIcon,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { LocationPanel } from "@/components/cinema/LocationPanel";
|
||||
import { cinemaFacilities, type Cinema } from "@/lib/cinemas";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import type { FacilityKey } from "@/lib/i18n/messages";
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
|
||||
const FACILITY_ICONS: Record<FacilityKey, TablerIcon> = {
|
||||
seating: IconSofa,
|
||||
ticket: IconTicket,
|
||||
restaurant: IconToolsKitchen2,
|
||||
cafe: IconCoffee,
|
||||
garden: IconPlant2,
|
||||
bookstore: IconBook,
|
||||
colearning: IconBriefcase,
|
||||
other: IconShoppingBag,
|
||||
};
|
||||
|
||||
/** สิ่งอำนวยความสะดวก (ซ้าย) + ที่ตั้ง (ขวา) ตาม layout ใน Figma */
|
||||
export function FacilitiesSection({ cinema }: { cinema: Cinema }) {
|
||||
const { locale, messages } = useI18n();
|
||||
const facilities = cinemaFacilities(cinema);
|
||||
|
||||
return (
|
||||
<section className="grid gap-10 lg:grid-cols-[minmax(0,749px)_minmax(0,384px)] lg:justify-between">
|
||||
<div className="flex flex-col gap-8">
|
||||
<h2 className="text-2xl font-semibold leading-[1.3]">
|
||||
{messages.detail.facilities}
|
||||
</h2>
|
||||
{facilities.length > 0 ? (
|
||||
<div className="grid grid-cols-2 gap-x-4 gap-y-10 sm:grid-cols-4">
|
||||
{facilities.map((key) => {
|
||||
const Icon = FACILITY_ICONS[key];
|
||||
const base = messages.facilities[key];
|
||||
const custom = cinema.facility_details?.[key];
|
||||
const title = custom?.label?.trim() || base.title;
|
||||
// คำอธิบายแสดงเฉพาะที่กรอกไว้รายโรง (ค่าเริ่มต้นใช้เป็น placeholder ในหลังบ้าน)
|
||||
const sub =
|
||||
(locale === "en" ? custom?.sub_en : custom?.sub_th)?.trim() ?? "";
|
||||
return (
|
||||
<div key={key} className="flex flex-col items-center gap-3">
|
||||
<div
|
||||
className="flex size-[72px] items-center justify-center rounded-full"
|
||||
style={{ background: COLORS.glowSoft }}
|
||||
>
|
||||
<Icon size={40} stroke={1.5} />
|
||||
</div>
|
||||
<div className="text-center">
|
||||
<div className="font-medium">{title}</div>
|
||||
{sub ? (
|
||||
<div className="mt-1 text-sm text-[#B3B3B3]">{sub}</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
) : (
|
||||
<p className="text-sm text-[#777]">{messages.detail.noData}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<LocationPanel cinema={cinema} />
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { IconChevronLeft, IconChevronRight } from "@tabler/icons-react";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { Logo } from "@/components/site/Logo";
|
||||
import { splitGallery } from "@/lib/gallery";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
type GalleryProps = {
|
||||
photos: string[];
|
||||
cinemaName: string;
|
||||
};
|
||||
|
||||
type GallerySlotProps = {
|
||||
photo: string | null;
|
||||
alt: string;
|
||||
/** เนื้อหาที่แสดงเมื่อยังไม่มีรูป — ใช้โลโก้ AlterFlixHub แทนข้อความ */
|
||||
placeholder: ReactNode;
|
||||
className: string;
|
||||
};
|
||||
|
||||
function GallerySlot({ photo, alt, placeholder, className }: GallerySlotProps) {
|
||||
if (!photo) {
|
||||
return (
|
||||
<div
|
||||
className={`flex items-center justify-center bg-[#242424] text-sm text-[#999] ${className}`}
|
||||
>
|
||||
{placeholder}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<img
|
||||
src={photo}
|
||||
alt={alt}
|
||||
className={`bg-[#242424] object-cover ${className}`}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** แกลเลอรีภาพโรงหนัง — ป้าย "+N" คำนวณจากจำนวนรูปจริงในข้อมูล */
|
||||
export function Gallery({ photos, cinemaName }: GalleryProps) {
|
||||
const { messages } = useI18n();
|
||||
const { main, thumbs, remaining } = splitGallery(photos);
|
||||
const [firstThumb = null, secondThumb = null] = thumbs;
|
||||
|
||||
return (
|
||||
<section className="grid gap-6 lg:grid-cols-[minmax(0,807px)_minmax(0,387px)]">
|
||||
<div className="relative overflow-hidden rounded-xl">
|
||||
<GallerySlot
|
||||
photo={main}
|
||||
alt={`${messages.gallery.main} — ${cinemaName}`}
|
||||
placeholder={<Logo size="md" />}
|
||||
className="aspect-[269/202] w-full lg:aspect-auto lg:h-[606px]"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={messages.gallery.previous}
|
||||
className="absolute left-6 top-1/2 flex size-10 -translate-y-1/2 items-center justify-center rounded-full bg-black/50"
|
||||
>
|
||||
<IconChevronLeft size={24} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={messages.gallery.next}
|
||||
className="absolute right-6 top-1/2 flex size-10 -translate-y-1/2 items-center justify-center rounded-full bg-black/50"
|
||||
>
|
||||
<IconChevronRight size={24} />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-2 gap-6 lg:grid-cols-1 lg:grid-rows-2">
|
||||
<div className="overflow-hidden rounded-xl">
|
||||
<GallerySlot
|
||||
photo={firstThumb}
|
||||
alt={`${messages.gallery.second} — ${cinemaName}`}
|
||||
placeholder={<Logo size="sm" />}
|
||||
className="aspect-[387/290] w-full"
|
||||
/>
|
||||
</div>
|
||||
<div className="relative overflow-hidden rounded-xl">
|
||||
<GallerySlot
|
||||
photo={secondThumb}
|
||||
alt={`${messages.gallery.third} — ${cinemaName}`}
|
||||
placeholder={<Logo size="sm" />}
|
||||
className="aspect-[387/290] w-full"
|
||||
/>
|
||||
{remaining > 0 ? (
|
||||
<div className="absolute bottom-2.5 right-2.5 flex size-[60px] items-center justify-center rounded-lg bg-black/80 text-lg font-medium">
|
||||
{messages.gallery.more(remaining)}
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { IconMap } from "@tabler/icons-react";
|
||||
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
import { cinemaAddressLines, cinemaName, type Cinema } from "@/lib/cinemas";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { mapEmbedUrl, mapOpenUrl } from "@/lib/map-embed";
|
||||
|
||||
/**
|
||||
* การ์ดที่ตั้ง + แผนที่
|
||||
* แผนที่ดึงจากลิงก์ Google Maps ของโรง ถ้าไม่มีจึงใช้พิกัดที่กรอกในหลังบ้าน
|
||||
* ถ้าไม่มีทั้งสองอย่างแสดง "ไม่มีข้อมูล"
|
||||
*/
|
||||
export function LocationPanel({ cinema }: { cinema: Cinema }) {
|
||||
const { locale, messages } = useI18n();
|
||||
const addressLines = cinemaAddressLines(cinema, locale);
|
||||
const embedUrl = mapEmbedUrl(cinema, locale);
|
||||
const openUrl = mapOpenUrl(cinema);
|
||||
|
||||
return (
|
||||
<aside
|
||||
className="flex flex-col gap-6 self-start rounded-xl p-6"
|
||||
style={{ border: `1px solid ${COLORS.border}` }}
|
||||
>
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-between gap-3">
|
||||
<h2 className="text-2xl font-semibold leading-[1.3]">
|
||||
{messages.detail.location}
|
||||
</h2>
|
||||
{openUrl ? (
|
||||
<a
|
||||
href={openUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="inline-flex items-center gap-1 text-sm text-[#D47272] transition hover:text-white"
|
||||
>
|
||||
<IconMap size={16} />
|
||||
{messages.detail.openMap}
|
||||
</a>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
{embedUrl ? (
|
||||
<div
|
||||
className="relative h-[183px] overflow-hidden rounded-xl"
|
||||
style={{
|
||||
border: `1px solid ${COLORS.border}`,
|
||||
background: COLORS.surfaceMuted,
|
||||
}}
|
||||
>
|
||||
{/* ลายตารางใต้แผนที่ — กันช่องว่างขาวตอน iframe ยังโหลดไม่เสร็จ */}
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-0"
|
||||
style={{
|
||||
backgroundImage:
|
||||
"linear-gradient(rgba(255,255,255,0.05) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.05) 1px, transparent 1px)",
|
||||
backgroundSize: "24px 24px",
|
||||
}}
|
||||
/>
|
||||
<iframe
|
||||
title={`${messages.detail.location} — ${cinemaName(cinema, locale)}`}
|
||||
src={embedUrl}
|
||||
loading="lazy"
|
||||
referrerPolicy="no-referrer-when-downgrade"
|
||||
allowFullScreen
|
||||
className="relative size-full border-0"
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className="flex h-[183px] items-center justify-center rounded-xl text-sm text-[#777]"
|
||||
style={{
|
||||
border: `1px dashed ${COLORS.border}`,
|
||||
background: COLORS.surfaceMuted,
|
||||
}}
|
||||
>
|
||||
{messages.detail.noData}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<p className="text-sm leading-[1.3] text-[#999]">
|
||||
{addressLines.length > 0
|
||||
? addressLines.map((line) => (
|
||||
<span key={line} className="block">
|
||||
{line}
|
||||
</span>
|
||||
))
|
||||
: messages.detail.addressFallback}
|
||||
</p>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import {
|
||||
IconBus,
|
||||
IconCar,
|
||||
IconTrain,
|
||||
type Icon as TablerIcon,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { transportValue, type TransportMode } from "@/lib/cinemas";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
|
||||
const TRANSPORT_ICONS: Record<TransportMode["icon_name"], TablerIcon> = {
|
||||
private_car: IconCar,
|
||||
metro: IconTrain,
|
||||
bus: IconBus,
|
||||
};
|
||||
|
||||
/** วิธีเดินทางมาถึงโรงหนัง — ซ่อนทั้งบล็อกถ้ายังไม่มีข้อมูล */
|
||||
export function TransportList({ transport }: { transport: TransportMode[] }) {
|
||||
const { locale, messages } = useI18n();
|
||||
// แถวที่ยังไม่ได้กรอกรายละเอียด (เพิ่มจากหลังบ้านแล้วเว้นว่าง) ไม่ต้องแสดง
|
||||
const routes = transport.filter((route) => route.value.trim() !== "");
|
||||
|
||||
if (routes.length === 0) return null;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{routes.map((route, index) => {
|
||||
const Icon = TRANSPORT_ICONS[route.icon_name];
|
||||
const isLast = index === routes.length - 1;
|
||||
return (
|
||||
<div
|
||||
key={`${route.icon_name}-${index}`}
|
||||
className="flex flex-col justify-between gap-1 py-2.5 sm:min-h-10 sm:flex-row sm:gap-4"
|
||||
style={{
|
||||
borderBottom: isLast ? undefined : `1px solid ${COLORS.border}`,
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center gap-2 font-medium">
|
||||
<Icon size={20} />
|
||||
{messages.transport[route.icon_name]}
|
||||
</div>
|
||||
<div className="sm:text-right">{transportValue(route, locale)}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { IconCircleCheck, IconMapPin, IconSearch } from "@tabler/icons-react";
|
||||
|
||||
import type { NearMeStatus } from "@/hooks/use-near-me";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
type HeroSectionProps = {
|
||||
query: string;
|
||||
onQueryChange: (query: string) => void;
|
||||
nearMeStatus: NearMeStatus;
|
||||
onRequestLocation: () => void;
|
||||
};
|
||||
|
||||
/** ข้อความสถานะของปุ่ม "ใกล้ฉัน" — แสดงเฉพาะตอนกำลังหา/ผิดพลาด/พร้อมใช้ */
|
||||
function statusMessage(status: NearMeStatus, messages: ReturnType<typeof useI18n>["messages"]) {
|
||||
switch (status) {
|
||||
case "locating":
|
||||
return messages.search.locating;
|
||||
case "denied":
|
||||
return messages.search.denied;
|
||||
case "unsupported":
|
||||
return messages.search.unsupported;
|
||||
case "error":
|
||||
return messages.search.error;
|
||||
case "ready":
|
||||
return messages.search.sortedByDistance;
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** ฮีโร่หน้าแรก: หัวข้อ + ช่องค้นหา (ค้นทันทีขณะพิมพ์) + ปุ่มหาตำแหน่ง */
|
||||
export function HeroSection({
|
||||
query,
|
||||
onQueryChange,
|
||||
nearMeStatus,
|
||||
onRequestLocation,
|
||||
}: HeroSectionProps) {
|
||||
const { messages } = useI18n();
|
||||
const status = statusMessage(nearMeStatus, messages);
|
||||
const isReady = nearMeStatus === "ready";
|
||||
|
||||
return (
|
||||
<section className="mx-auto flex max-w-[1016px] flex-col items-center gap-10 pt-24 md:pt-[167px]">
|
||||
<div className="flex max-w-[745px] flex-col items-center gap-4 text-center">
|
||||
<h1 className="text-4xl font-bold leading-[1.3] md:text-[56px]">
|
||||
{messages.hero.titlePrefix}
|
||||
<span className="text-[#A92626]">{messages.hero.titleHighlight}</span>
|
||||
{messages.hero.titleSuffix}
|
||||
</h1>
|
||||
<p className="text-base md:text-xl">{messages.hero.subtitle}</p>
|
||||
</div>
|
||||
|
||||
<div className="w-full rounded-2xl border border-[#303030] bg-[#1B1B1B]/80 px-4 py-6 backdrop-blur-[32px] md:px-10">
|
||||
<div className="flex h-14 items-center gap-3 rounded-lg border border-[#1B1B1B] bg-[#1F1F1F] px-5">
|
||||
<IconSearch size={16} className="shrink-0 text-[#999]" />
|
||||
<input
|
||||
value={query}
|
||||
onChange={(event) => onQueryChange(event.target.value)}
|
||||
placeholder={messages.search.placeholder}
|
||||
aria-label={messages.search.placeholder}
|
||||
className="min-w-0 flex-1 bg-transparent text-sm text-white outline-none placeholder:text-[#454545]"
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRequestLocation}
|
||||
disabled={nearMeStatus === "locating"}
|
||||
aria-label={messages.search.nearMe}
|
||||
className={`hidden items-center gap-2 border-l border-[#999] px-4 text-sm transition disabled:opacity-60 sm:flex ${
|
||||
isReady ? "text-[#D47272]" : "text-[#999] hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{isReady ? <IconCircleCheck size={16} /> : <IconMapPin size={16} />}
|
||||
{messages.search.nearMe}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
className="h-8 rounded-lg border border-[#8F0808] bg-[#8F0808] px-6 text-sm font-medium transition hover:bg-[#a30a0a]"
|
||||
>
|
||||
{messages.search.submit}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{status ? (
|
||||
<p
|
||||
role="status"
|
||||
aria-live="polite"
|
||||
className={`px-1 pt-3 text-xs ${
|
||||
nearMeStatus === "ready" ? "text-[#B3B3B3]" : "text-[#D47272]"
|
||||
}`}
|
||||
>
|
||||
{status}
|
||||
</p>
|
||||
) : null}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { HeaderActionsProvider } from "@agent-native/toolkit/app-shell";
|
||||
|
||||
interface LayoutProps {
|
||||
children: React.ReactNode;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean Agent-Native app shell: a single full-height canvas with no chat or
|
||||
* agent UI mounted by default. The app already satisfies the Agent-Native
|
||||
* contract (data in SQL, actions as the source of truth, application state for
|
||||
* navigation, real-time sync) — the agent rail and chat are opt-in surfaces.
|
||||
*
|
||||
* To add the persistent agent rail when the user asks for it, wrap {children}
|
||||
* in `AgentSidebar` from "@agent-native/core/client/agent-chat"
|
||||
* (position="right", a stable storageKey, browserTabId={TAB_ID} from
|
||||
* "@/lib/tab-id"). See the `agent-native-toolkit` skill for the full pattern.
|
||||
*/
|
||||
export function Layout({ children }: LayoutProps) {
|
||||
return (
|
||||
<HeaderActionsProvider>
|
||||
<div className="flex h-screen w-full flex-col overflow-hidden bg-background text-foreground">
|
||||
<main className="agent-native-app-main min-w-0 flex-1 overflow-y-auto overscroll-contain">
|
||||
{children}
|
||||
</main>
|
||||
</div>
|
||||
</HeaderActionsProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import {
|
||||
IconArrowRight,
|
||||
IconBuildingCommunity,
|
||||
IconMapPin,
|
||||
} from "@tabler/icons-react";
|
||||
import { Link } from "react-router";
|
||||
|
||||
import {
|
||||
CARD_GRADIENTS,
|
||||
cinemaCategoryLabel,
|
||||
cinemaLocationLabel,
|
||||
cinemaName,
|
||||
type Cinema,
|
||||
} from "@/lib/cinemas";
|
||||
import { formatDistance } from "@/lib/geo";
|
||||
import { trackEvent } from "@/lib/analytics-client";
|
||||
import { useNearMe } from "@/hooks/use-near-me";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
type CinemaCardProps = {
|
||||
cinema: Cinema;
|
||||
/** ลำดับการ์ด ใช้เลือก gradient ให้สลับสีสม่ำเสมอ */
|
||||
index?: number;
|
||||
/** ที่มาของการ์ด ใช้บันทึกสถิติการคลิก */
|
||||
source?: string;
|
||||
/** คำค้นปัจจุบัน (แนบไปกับการคลิกเพื่อวัด CTR ของคำค้น) */
|
||||
searchQuery?: string;
|
||||
};
|
||||
|
||||
export function CinemaCard({
|
||||
cinema,
|
||||
index = 0,
|
||||
source = "list",
|
||||
searchQuery,
|
||||
}: CinemaCardProps) {
|
||||
const { locale, messages } = useI18n();
|
||||
const { distances } = useNearMe();
|
||||
const gradient = CARD_GRADIENTS[index % CARD_GRADIENTS.length];
|
||||
// รูปแรก = ปกการ์ด (ถ้าไม่มีรูป ใช้ gradient เดิมเป็นพื้นหลัง)
|
||||
const cover = cinema.photos.find((photo) => photo.trim() !== "");
|
||||
const distanceLabel = formatDistance(
|
||||
distances[cinema.slug],
|
||||
messages.card.distanceFallback,
|
||||
);
|
||||
|
||||
return (
|
||||
<article
|
||||
className={`relative flex aspect-[3/4] flex-col justify-end overflow-hidden rounded-[20px] bg-gradient-to-br p-2 lg:aspect-auto lg:h-[308px] ${gradient}`}
|
||||
>
|
||||
{cover ? (
|
||||
<>
|
||||
<img
|
||||
src={cover}
|
||||
alt=""
|
||||
aria-hidden="true"
|
||||
loading="lazy"
|
||||
className="absolute inset-0 size-full object-cover"
|
||||
/>
|
||||
{/* ไล่เงาเพื่อให้ตัวอักษรบนการ์ดอ่านได้ */}
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="absolute inset-0 bg-gradient-to-t from-[#0D0D0D]/95 via-[#0D0D0D]/35 to-transparent"
|
||||
/>
|
||||
</>
|
||||
) : null}
|
||||
|
||||
<div className="relative flex flex-col gap-1.5 rounded-2xl border border-white/10 bg-[#1B1B1B]/80 p-3 backdrop-blur-xl">
|
||||
<span className="text-[10px] text-[#B3B3B3]">{distanceLabel}</span>
|
||||
<h3 className="text-sm font-semibold">{cinemaName(cinema, locale)}</h3>
|
||||
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
|
||||
<IconMapPin size={12} />
|
||||
{cinemaLocationLabel(cinema, locale) || messages.card.locationFallback}
|
||||
</p>
|
||||
<p className="flex items-center gap-1.5 text-xs text-[#B3B3B3]">
|
||||
<IconBuildingCommunity size={12} />
|
||||
{cinemaCategoryLabel(cinema, messages) ||
|
||||
messages.card.categoryFallback}
|
||||
</p>
|
||||
<Link
|
||||
to={`/cinema/${cinema.slug}`}
|
||||
onClick={() =>
|
||||
trackEvent({
|
||||
type: "cinema_select",
|
||||
slug: cinema.slug,
|
||||
source,
|
||||
query: searchQuery,
|
||||
position: index + 1,
|
||||
locale,
|
||||
})
|
||||
}
|
||||
className="mt-3 flex items-center justify-end gap-2 text-xs font-medium"
|
||||
>
|
||||
{messages.card.seeDetail} <IconArrowRight size={12} />
|
||||
</Link>
|
||||
</div>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { CinemaCard } from "@/components/site/CinemaCard";
|
||||
import type { Cinema, CinemaCategory } from "@/lib/cinemas";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
/** กริดการ์ดโรงหนัง — ใช้ทั้งหน้าแรกและส่วน "โรงหนังอิสระอื่นๆ" */
|
||||
export function CinemaGrid({
|
||||
cinemas,
|
||||
source = "list",
|
||||
searchQuery,
|
||||
}: {
|
||||
cinemas: Cinema[];
|
||||
source?: string;
|
||||
searchQuery?: string;
|
||||
}) {
|
||||
return (
|
||||
<div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-4">
|
||||
{cinemas.map((cinema, index) => (
|
||||
<CinemaCard
|
||||
key={cinema.slug}
|
||||
cinema={cinema}
|
||||
index={index}
|
||||
source={source}
|
||||
searchQuery={searchQuery}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type CategoryFilterProps = {
|
||||
/** เก็บคีย์หมวดเป็นภาษาไทยเสมอ เพื่อใช้กรองข้อมูลได้ทุกภาษา */
|
||||
active: CinemaCategory;
|
||||
categories: readonly CinemaCategory[];
|
||||
onChange: (category: CinemaCategory) => void;
|
||||
};
|
||||
|
||||
export function CategoryFilter({
|
||||
active,
|
||||
categories,
|
||||
onChange,
|
||||
}: CategoryFilterProps) {
|
||||
const { messages } = useI18n();
|
||||
|
||||
return (
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{categories.map((category) => {
|
||||
const isActive = category === active;
|
||||
return (
|
||||
<button
|
||||
key={category}
|
||||
type="button"
|
||||
onClick={() => onChange(category)}
|
||||
aria-pressed={isActive}
|
||||
className={
|
||||
isActive
|
||||
? "rounded-[18px] border border-[#A92626] bg-gradient-to-b from-[#8F0808]/30 to-[#1B1B1B]/0 px-4 py-2 text-sm text-[#D47272]"
|
||||
: "rounded-[18px] border border-[#303030] bg-[#242424] px-4 py-2 text-sm text-[#B3B3B3] transition hover:border-[#A92626]/60"
|
||||
}
|
||||
>
|
||||
{messages.categories[category]}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
import { LOCALE_OPTIONS } from "@/lib/i18n/messages";
|
||||
import { COLORS } from "@/lib/design-tokens";
|
||||
|
||||
/** ธงชาติไทยย่อส่วน */
|
||||
function FlagTh() {
|
||||
return (
|
||||
<span
|
||||
className="block h-4 w-[21px] shrink-0 rounded-[1px]"
|
||||
style={{ background: COLORS.flagGradient }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** ธงสหราชอาณาจักรย่อส่วน */
|
||||
function FlagEn() {
|
||||
return (
|
||||
<span
|
||||
className="relative block h-4 w-[21px] shrink-0 overflow-hidden rounded-[1px]"
|
||||
style={{ background: "#012169" }}
|
||||
>
|
||||
<span
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
"linear-gradient(45deg, transparent 44%, #F4F5F8 44% 56%, transparent 56%), linear-gradient(-45deg, transparent 44%, #F4F5F8 44% 56%, transparent 56%)",
|
||||
}}
|
||||
/>
|
||||
<span
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
"linear-gradient(90deg, transparent 40%, #F4F5F8 40% 60%, transparent 60%), linear-gradient(0deg, transparent 33%, #F4F5F8 33% 67%, transparent 67%)",
|
||||
}}
|
||||
/>
|
||||
<span
|
||||
className="absolute inset-0"
|
||||
style={{
|
||||
background:
|
||||
"linear-gradient(90deg, transparent 44%, #C8102E 44% 56%, transparent 56%), linear-gradient(0deg, transparent 40%, #C8102E 40% 60%, transparent 60%)",
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
const FLAGS = { th: FlagTh, en: FlagEn } as const;
|
||||
|
||||
/**
|
||||
* สลับภาษาเป็นปุ่มสองปุ่ม (TH / EN) — ไม่มีเมนูให้เปิด/ปิด
|
||||
* จึงไม่มีปัญหาคลิกพลาดหรือเมนูถูกบัง และกดครั้งเดียวเปลี่ยนทันที
|
||||
*/
|
||||
export function LocaleSwitcher() {
|
||||
const { locale, setLocale } = useI18n();
|
||||
|
||||
return (
|
||||
<div role="group" aria-label="ภาษา" className="flex items-center gap-1">
|
||||
{LOCALE_OPTIONS.map((option) => {
|
||||
const Flag = FLAGS[option.locale];
|
||||
const isActive = option.locale === locale;
|
||||
return (
|
||||
<button
|
||||
key={option.locale}
|
||||
type="button"
|
||||
lang={option.locale}
|
||||
onClick={() => setLocale(option.locale)}
|
||||
aria-pressed={isActive}
|
||||
title={option.name}
|
||||
className={`flex items-center gap-1.5 rounded-lg px-1.5 py-1 text-sm transition sm:gap-2 sm:px-2 ${
|
||||
isActive
|
||||
? "bg-[#242424] font-semibold text-[#D47272]"
|
||||
: "text-[#B3B3B3] hover:text-white"
|
||||
}`}
|
||||
>
|
||||
<span className="hidden sm:block">
|
||||
<Flag />
|
||||
</span>
|
||||
<span className="text-base font-medium leading-none sm:text-lg">
|
||||
{option.code}
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { LOGO_SPEC } from "@/lib/design-tokens";
|
||||
import { logoClasses } from "@/components/site/Logo";
|
||||
|
||||
/**
|
||||
* กันการเผลอเปลี่ยนโลโก้: สเปกใน DESIGN.md ถูกตรึงไว้ที่นี่
|
||||
* ถ้าเทสต์นี้พัง แปลว่ามีคนแก้สเปกโลโก้ — ต้องขออนุมัติก่อน
|
||||
*/
|
||||
describe("โลโก้ AlterFlixHub (สเปกที่ห้ามเปลี่ยน)", () => {
|
||||
it("ใช้คำว่า AlterFlixHub เท่านั้น", () => {
|
||||
expect(LOGO_SPEC.wordmark).toBe("AlterFlixHub");
|
||||
});
|
||||
|
||||
it("ฟอนต์ต้องเป็น Jersey 15", () => {
|
||||
expect(LOGO_SPEC.fontFamily).toContain("Jersey 15");
|
||||
expect(logoClasses("md")).toContain("font-['Jersey_15']");
|
||||
expect(logoClasses("sm")).toContain("font-['Jersey_15']");
|
||||
});
|
||||
|
||||
it("สีต้องเป็นแดงแบรนด์ #8F0808", () => {
|
||||
expect(LOGO_SPEC.color).toBe("#8F0808");
|
||||
});
|
||||
|
||||
it("header 36px (md) และ footer 24px (sm) เท่านั้น", () => {
|
||||
expect(LOGO_SPEC.sizes.md).toBe("text-4xl");
|
||||
expect(LOGO_SPEC.sizes.sm).toBe("text-2xl");
|
||||
expect(logoClasses("md")).toContain("text-4xl");
|
||||
expect(logoClasses("sm")).toContain("text-2xl");
|
||||
});
|
||||
|
||||
it("ไม่มีตัวเลือกขนาดอื่นนอกเหนือจาก sm/md", () => {
|
||||
expect(Object.keys(LOGO_SPEC.sizes).sort()).toEqual(["md", "sm"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
import { LOGO_SPEC, type LogoSize } from "@/lib/design-tokens";
|
||||
|
||||
type LogoProps = {
|
||||
className?: string;
|
||||
/** sm = footer (24px) · md = header (36px) */
|
||||
size?: LogoSize;
|
||||
};
|
||||
|
||||
/**
|
||||
* โลโก้ AlterFlixHub — ตาม DESIGN.md หัวข้อ "โลโก้ (ห้ามเปลี่ยนแปลง)"
|
||||
* ฟอนต์ Jersey 15 สี #8F0808 และมีสองขนาดเท่านั้น (sm/md)
|
||||
*/
|
||||
export function logoClasses(size: LogoSize = "md"): string {
|
||||
return `font-['Jersey_15'] leading-none ${LOGO_SPEC.sizes[size]}`;
|
||||
}
|
||||
|
||||
export function Logo({ className = "", size = "md" }: LogoProps) {
|
||||
return (
|
||||
<span
|
||||
className={`${logoClasses(size)} ${className}`}
|
||||
style={{ fontFamily: LOGO_SPEC.fontFamily, color: LOGO_SPEC.color }}
|
||||
>
|
||||
{LOGO_SPEC.wordmark}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import { Link } from "react-router";
|
||||
|
||||
import { Logo } from "@/components/site/Logo";
|
||||
import { footerIcon } from "@/components/site/footer-icons";
|
||||
import { useContent } from "@/lib/content-context";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* Footer ใช้คอนเทนเนอร์เดียวกับ <main> ของทุกหน้า (max-w-[1440px] + px เดียวกัน)
|
||||
* ขอบซ้าย/ขวาจึงตรงกับกริดการ์ดโรงหนังเป๊ะ ไม่ว่าหน้าจะแสดงการ์ดกี่ใบ
|
||||
*/
|
||||
export function SiteFooter() {
|
||||
const { site } = useContent();
|
||||
const { messages } = useI18n();
|
||||
|
||||
return (
|
||||
<footer className="relative z-10 mx-auto w-full max-w-[1440px] px-5 pb-6 md:px-[108px]">
|
||||
<div className="flex flex-col items-center gap-3 border-t border-white/10 pt-4 sm:flex-row sm:justify-between">
|
||||
<div className="flex items-center gap-4">
|
||||
<Logo size="sm" />
|
||||
<nav aria-label="เมนูล่าง" className="flex items-center gap-3 text-xs">
|
||||
<Link
|
||||
to="/about"
|
||||
className="text-[#B3B3B3] transition hover:text-white"
|
||||
>
|
||||
{messages.nav.about}
|
||||
</Link>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-wrap items-center justify-center gap-1.5">
|
||||
{site.footer.map((item) => {
|
||||
const Icon = footerIcon(item.icon_name);
|
||||
const isExternal = item.href.startsWith("http");
|
||||
return (
|
||||
<a
|
||||
key={item.id}
|
||||
href={item.href || "#"}
|
||||
aria-label={item.label}
|
||||
title={item.label}
|
||||
target={isExternal ? "_blank" : undefined}
|
||||
rel={isExternal ? "noreferrer" : undefined}
|
||||
className="flex size-8 items-center justify-center rounded-full bg-white/90 text-[#0D0D0D] transition hover:bg-white"
|
||||
>
|
||||
<Icon size={18} />
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
<p className="text-xs text-[#999]">Copyright © AlterFlixHub</p>
|
||||
</div>
|
||||
</footer>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { Link, useLocation } from "react-router";
|
||||
|
||||
import { Logo } from "@/components/site/Logo";
|
||||
import { LocaleSwitcher } from "@/components/site/LocaleSwitcher";
|
||||
import { useI18n } from "@/lib/i18n";
|
||||
|
||||
/**
|
||||
* Header: โลโก้ชิดซ้าย · ด้านขวาเป็น [เกี่ยวกับเรา] + [ปุ่มภาษา TH/EN]
|
||||
* ไม่มีเมนู "หน้าแรก" — กลับหน้าแรกได้ด้วยการกดโลโก้
|
||||
*/
|
||||
export function SiteHeader() {
|
||||
const { messages } = useI18n();
|
||||
const { pathname } = useLocation();
|
||||
const isAbout = pathname.startsWith("/about");
|
||||
|
||||
return (
|
||||
<header className="relative z-10 mx-auto flex h-[68px] w-full max-w-[1440px] items-center justify-between gap-4 px-5 md:px-[108px]">
|
||||
<Link to="/" aria-label={`AlterFlixHub — ${messages.nav.home}`} className="shrink-0">
|
||||
<Logo />
|
||||
</Link>
|
||||
|
||||
<div className="flex items-center gap-1.5 sm:gap-2">
|
||||
<Link
|
||||
to="/about"
|
||||
aria-current={isAbout ? "page" : undefined}
|
||||
className={`rounded-lg border px-2 py-1 text-xs transition sm:px-3 sm:py-1.5 sm:text-sm ${
|
||||
isAbout
|
||||
? "border-[#A92626] bg-[#8F0808]/20 text-white"
|
||||
: "border-[#303030] text-[#B3B3B3] hover:border-[#A92626]/60 hover:text-white"
|
||||
}`}
|
||||
>
|
||||
{messages.nav.about}
|
||||
</Link>
|
||||
|
||||
<LocaleSwitcher />
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { SiteFooter } from "@/components/site/SiteFooter";
|
||||
import { SiteHeader } from "@/components/site/SiteHeader";
|
||||
|
||||
type ShellVariant = "home" | "detail";
|
||||
|
||||
const HERO_IMAGE = "/images/hero.png";
|
||||
|
||||
/**
|
||||
* กรอบของตกแต่งพื้นหลัง
|
||||
* ต้องมี overflow-hidden ไม่งั้น glow ที่วางด้วย top/bottom แบบ px
|
||||
* จะยืด scrollHeight ของหน้าให้ยาวเกินเนื้อหา → เกิดพื้นที่ว่างใต้ footer
|
||||
*/
|
||||
function BackdropFrame({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none absolute inset-0 overflow-hidden"
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** พื้นหลังหน้าแรก: รูปฮีโร่ + ไล่สีลงพื้นหลัง + แสงแดงสองจุด */
|
||||
function HomeBackdrop() {
|
||||
return (
|
||||
<BackdropFrame>
|
||||
<img
|
||||
src={HERO_IMAGE}
|
||||
alt=""
|
||||
className="pointer-events-none absolute inset-x-0 top-0 h-[553px] w-full object-cover"
|
||||
/>
|
||||
<div className="pointer-events-none absolute inset-x-0 top-0 h-[553px] bg-gradient-to-b from-transparent via-[#0D0D0D]/60 to-[#0D0D0D]" />
|
||||
<div className="pointer-events-none absolute left-1/2 top-0 size-[382px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-[#8F0808] blur-[237px]" />
|
||||
{/* จุดล่างยึดกับขอบล่างของหน้า (เดิมใช้ top-[1620px] ตายตัว จึงล้นเลย footer เมื่อแสดงโรงหนังแบบย่อ) */}
|
||||
<div className="pointer-events-none absolute bottom-[-140px] left-1/2 size-[382px] -translate-x-1/2 rounded-full bg-[#4C0404]/70 blur-[237px]" />
|
||||
</BackdropFrame>
|
||||
);
|
||||
}
|
||||
|
||||
/** พื้นหลังหน้ารายละเอียด: แสงแดงจุดเดียวตามระยะใน Figma */
|
||||
function DetailBackdrop() {
|
||||
return (
|
||||
<BackdropFrame>
|
||||
<div className="pointer-events-none absolute left-1/2 top-[649px] size-[382px] -translate-x-1/2 rounded-full bg-[#4C0404] opacity-[0.66] blur-[237px]" />
|
||||
</BackdropFrame>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* โครงหน้าเว็บที่ทุก route ใช้ร่วมกัน (พื้นหลัง + header + footer)
|
||||
* variant เลือกชุดพื้นหลัง ไม่ใช่ layout — เนื้อหายังคงอยู่ใน route
|
||||
*/
|
||||
export function SiteShell({
|
||||
variant,
|
||||
children,
|
||||
}: {
|
||||
variant: ShellVariant;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
return (
|
||||
<div className="relative flex min-h-dvh w-full flex-col overflow-x-hidden bg-[#0D0D0D] text-white">
|
||||
{variant === "home" ? <HomeBackdrop /> : <DetailBackdrop />}
|
||||
<SiteHeader />
|
||||
{/* flex-1 ดัน footer ไปท้ายจอเมื่อเนื้อหาสั้น — เป็น block ธรรมดา
|
||||
(ไม่ใช้ flex-col เพื่อไม่ให้ main ที่มี mx-auto หดเหลือ max-content จนล้นจอมือถือ) */}
|
||||
<div className="flex-1">{children}</div>
|
||||
<SiteFooter />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import {
|
||||
IconBrandFacebook,
|
||||
IconBrandInstagram,
|
||||
IconBrandLinkedin,
|
||||
IconBrandTelegram,
|
||||
IconBrandTiktok,
|
||||
IconBrandX,
|
||||
IconBrandYoutube,
|
||||
IconLink,
|
||||
IconMail,
|
||||
IconPhone,
|
||||
type Icon as TablerIcon,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
/** ไอคอนที่เลือกใช้ได้ใน footer — เพิ่มชื่อใหม่ได้โดยเติมใน map นี้ */
|
||||
export const FOOTER_ICONS: Record<string, TablerIcon> = {
|
||||
IconBrandFacebook,
|
||||
IconBrandInstagram,
|
||||
IconBrandLinkedin,
|
||||
IconBrandYoutube,
|
||||
IconBrandTelegram,
|
||||
IconBrandTiktok,
|
||||
IconBrandX,
|
||||
IconMail,
|
||||
IconPhone,
|
||||
IconLink,
|
||||
};
|
||||
|
||||
export const FOOTER_ICON_NAMES = Object.keys(FOOTER_ICONS);
|
||||
|
||||
export function footerIcon(name: string): TablerIcon {
|
||||
return FOOTER_ICONS[name] ?? IconLink;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from "@agent-native/toolkit/ui/button";
|
||||
@@ -0,0 +1,20 @@
|
||||
import {
|
||||
ToolkitProvider,
|
||||
type ToolkitComponents,
|
||||
} from "@agent-native/toolkit/provider";
|
||||
import type { ReactNode } from "react";
|
||||
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { designSystem } from "@/design-system";
|
||||
|
||||
const components: ToolkitComponents = {
|
||||
Button: Button as ToolkitComponents["Button"],
|
||||
};
|
||||
|
||||
export function AppToolkitProvider({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<ToolkitProvider components={components} designSystem={designSystem}>
|
||||
{children}
|
||||
</ToolkitProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
import { defineDesignSystem } from "@agent-native/toolkit/design-system";
|
||||
|
||||
export const designSystem = defineDesignSystem({});
|
||||
@@ -0,0 +1,10 @@
|
||||
import { configureClientRouterBasename } from "@agent-native/core/client/api-path";
|
||||
import { installRouteChunkRecovery } from "@agent-native/core/client/route-chunk-recovery";
|
||||
import { hydrateRoot } from "react-dom/client";
|
||||
import { HydratedRouter } from "react-router/dom";
|
||||
|
||||
installRouteChunkRecovery();
|
||||
|
||||
configureClientRouterBasename();
|
||||
|
||||
hydrateRoot(document, <HydratedRouter />);
|
||||
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
createDocumentRequestHandler,
|
||||
streamTimeout,
|
||||
} from "@agent-native/core/server/entry-server";
|
||||
import { ServerRouter } from "react-router";
|
||||
|
||||
const handleDocumentRequest = createDocumentRequestHandler(ServerRouter);
|
||||
|
||||
export { streamTimeout };
|
||||
export default handleDocumentRequest;
|
||||
+263
@@ -0,0 +1,263 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Jersey+15&family=Noto+Sans+Thai:wght@400;500;600;700&display=swap");
|
||||
@import "@fontsource-variable/inter";
|
||||
@import "@fontsource/ibm-plex-sans-thai-looped/400.css";
|
||||
@import "@fontsource/ibm-plex-sans-thai-looped/500.css";
|
||||
|
||||
@import "tailwindcss";
|
||||
@import "@agent-native/toolkit/styles.css";
|
||||
|
||||
@source "./**/*.{ts,tsx}";
|
||||
|
||||
/* ฟอนต์เนื้อหายาว (มีหัว) — หัวข้อและ UI ยังใช้ Inter + Noto Sans Thai ตาม DESIGN.md */
|
||||
@theme {
|
||||
--font-content: "IBM Plex Sans Thai Looped", "Noto Sans Thai", sans-serif;
|
||||
}
|
||||
|
||||
:root {
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 0 0% 10%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 0 0% 10%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 0 0% 10%;
|
||||
--primary: 0 0% 15%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 0 0% 95%;
|
||||
--secondary-foreground: 0 0% 15%;
|
||||
--muted: 0 0% 95%;
|
||||
--muted-foreground: 0 0% 45%;
|
||||
--accent: 0 0% 95%;
|
||||
--accent-foreground: 0 0% 15%;
|
||||
--destructive: 0 91% 71%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 90%;
|
||||
--input: 0 0% 90%;
|
||||
--ring: 0 0% 40%;
|
||||
--radius: 0.5rem;
|
||||
--sidebar-background: 0 0% 97%;
|
||||
--sidebar-foreground: 0 0% 45%;
|
||||
--sidebar-primary: 0 0% 15%;
|
||||
--sidebar-primary-foreground: 0 0% 100%;
|
||||
--sidebar-accent: 0 0% 95%;
|
||||
--sidebar-accent-foreground: 0 0% 15%;
|
||||
--sidebar-border: 0 0% 90%;
|
||||
--sidebar-ring: 0 0% 40%;
|
||||
--chat-sidebar-width: 17.25rem;
|
||||
--chat-sidebar-content-inset: 0.5rem;
|
||||
--chat-sidebar-row-padding: 0.75rem;
|
||||
--chat-sidebar-title-fade: 1.25rem;
|
||||
}
|
||||
|
||||
.chat-layout-shell {
|
||||
--agent-layout-left-drawer-expanded-width: var(--chat-sidebar-width);
|
||||
--agent-native-lower-surface: var(--agent-kit-nav-surface);
|
||||
}
|
||||
|
||||
.agentkit-chat-empty-copy {
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.agentkit-chat-empty-copy h1 {
|
||||
margin: 0;
|
||||
color: hsl(var(--foreground));
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.agent-kit-chat-footer-stack {
|
||||
inline-size: min(100%, 47rem);
|
||||
margin-inline: auto;
|
||||
pointer-events: auto;
|
||||
}
|
||||
|
||||
.agent-kit-chat-footer-stack > .agentkit-composer-stack {
|
||||
inline-size: 100%;
|
||||
}
|
||||
|
||||
.agent-kit-chat-guided-question {
|
||||
max-block-size: min(32rem, 58dvh);
|
||||
overflow: auto;
|
||||
margin-block-end: 0.5rem;
|
||||
border: 1px solid var(--agentkit-border);
|
||||
border-radius: var(--agentkit-radius);
|
||||
background: var(--agentkit-surface);
|
||||
box-shadow: var(--agentkit-elevation);
|
||||
}
|
||||
|
||||
.chat-sidebar-history .an-chat-history__list {
|
||||
padding-top: 0;
|
||||
}
|
||||
|
||||
.chat-sidebar-history .an-chat-history__section-label {
|
||||
padding: 8px
|
||||
calc(var(--chat-sidebar-content-inset) + var(--chat-sidebar-row-padding))
|
||||
5px;
|
||||
color: hsl(var(--sidebar-foreground) / 0.66);
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0;
|
||||
text-transform: none;
|
||||
}
|
||||
|
||||
.chat-sidebar-history.an-chat-history--rail .an-chat-history-row {
|
||||
margin-inline: var(--chat-sidebar-content-inset);
|
||||
border-radius: calc(var(--radius) + 2px);
|
||||
}
|
||||
|
||||
.chat-sidebar-history.an-chat-history--rail .an-chat-history-row__button {
|
||||
min-height: 34px;
|
||||
padding-block: 7px;
|
||||
padding-inline: var(--chat-sidebar-row-padding);
|
||||
color: hsl(var(--sidebar-foreground));
|
||||
}
|
||||
|
||||
.chat-sidebar-history.an-chat-history--rail
|
||||
.an-chat-history-row--has-menu
|
||||
.an-chat-history-row__button {
|
||||
padding-inline-end: calc(var(--chat-sidebar-row-padding) + 1.5rem);
|
||||
}
|
||||
|
||||
.chat-sidebar-history .an-chat-history-row__title {
|
||||
flex: 1 1 auto;
|
||||
color: hsl(var(--sidebar-accent-foreground));
|
||||
font-size: 13px;
|
||||
font-weight: 400;
|
||||
text-overflow: clip;
|
||||
}
|
||||
|
||||
.chat-sidebar-thread-title-shell {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.chat-sidebar-thread-title {
|
||||
display: block;
|
||||
flex: 1 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.chat-sidebar-thread-running {
|
||||
color: hsl(var(--sidebar-foreground) / 0.72);
|
||||
}
|
||||
|
||||
.chat-sidebar-thread-title[data-overflow="true"] {
|
||||
mask-image: linear-gradient(
|
||||
to right,
|
||||
hsl(var(--foreground)) 0,
|
||||
hsl(var(--foreground)) calc(100% - var(--chat-sidebar-title-fade)),
|
||||
hsl(var(--foreground) / 0) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.chat-sidebar-thread-title__content {
|
||||
display: block;
|
||||
width: max-content;
|
||||
transform: translateX(0);
|
||||
}
|
||||
|
||||
.an-chat-history-row:hover
|
||||
.chat-sidebar-thread-title[data-overflow="true"]
|
||||
.chat-sidebar-thread-title__content {
|
||||
animation: chat-sidebar-title-reveal
|
||||
var(--chat-sidebar-title-duration, 1800ms) ease-in-out 350ms;
|
||||
}
|
||||
|
||||
.chat-sidebar-thread-details {
|
||||
border-color: hsl(var(--sidebar-border));
|
||||
}
|
||||
|
||||
.chat-sidebar-history.an-chat-history--rail
|
||||
.an-chat-history-row__menu-trigger--pinned {
|
||||
pointer-events: none;
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.chat-sidebar-history.an-chat-history--rail
|
||||
.an-chat-history-row:hover
|
||||
.an-chat-history-row__menu-trigger--pinned,
|
||||
.chat-sidebar-history.an-chat-history--rail
|
||||
.an-chat-history-row:focus-within
|
||||
.an-chat-history-row__menu-trigger--pinned,
|
||||
.chat-sidebar-history.an-chat-history--rail
|
||||
.an-chat-history-row__menu-trigger--pinned[aria-expanded="true"] {
|
||||
pointer-events: auto;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
@keyframes chat-sidebar-title-reveal {
|
||||
to {
|
||||
transform: translateX(calc(-1 * var(--chat-sidebar-title-shift, 0px)));
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.an-chat-history-row:hover .chat-sidebar-thread-title__content {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.chat-sidebar-history.an-chat-history--rail
|
||||
.an-chat-history-row--active
|
||||
.an-chat-history-row__button {
|
||||
background: hsl(var(--sidebar-accent));
|
||||
color: hsl(var(--sidebar-accent-foreground));
|
||||
}
|
||||
|
||||
.dark {
|
||||
--background: 0 0% 13%;
|
||||
--foreground: 0 0% 90%;
|
||||
--card: 0 0% 16.47%;
|
||||
--card-foreground: 0 0% 90%;
|
||||
--popover: 0 0% 15%;
|
||||
--popover-foreground: 0 0% 90%;
|
||||
--primary: 0 0% 75%;
|
||||
--primary-foreground: 0 0% 10%;
|
||||
--secondary: 0 0% 18%;
|
||||
--secondary-foreground: 0 0% 90%;
|
||||
--muted: 0 0% 16%;
|
||||
--muted-foreground: 0 0% 60%;
|
||||
--accent: 0 0% 18%;
|
||||
--accent-foreground: 0 0% 90%;
|
||||
--destructive: 0 84% 60%;
|
||||
--destructive-foreground: 0 0% 98%;
|
||||
--border: 0 0% 24%;
|
||||
--input: 0 0% 24%;
|
||||
--ring: 0 0% 60%;
|
||||
--radius: 0.5rem;
|
||||
--sidebar-background: 0 0% 10%;
|
||||
--sidebar-foreground: 0 0% 60%;
|
||||
--sidebar-primary: 0 0% 75%;
|
||||
--sidebar-primary-foreground: 0 0% 10%;
|
||||
--sidebar-accent: 0 0% 16%;
|
||||
--sidebar-accent-foreground: 0 0% 90%;
|
||||
--sidebar-border: 0 0% 20%;
|
||||
--sidebar-ring: 0 0% 60%;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
body {
|
||||
@apply bg-background text-foreground;
|
||||
font-family: "Inter Variable", "Inter", "Noto Sans Thai", sans-serif;
|
||||
font-feature-settings: "cv02", "cv03", "cv04", "cv11";
|
||||
}
|
||||
}
|
||||
|
||||
::-webkit-scrollbar {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
}
|
||||
::-webkit-scrollbar-track {
|
||||
background: transparent;
|
||||
}
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: hsl(var(--muted-foreground) / 0.22);
|
||||
border-radius: 3px;
|
||||
}
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: hsl(var(--muted-foreground) / 0.34);
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import {
|
||||
appBasePath,
|
||||
appPathFromLocalRoute,
|
||||
} from "@agent-native/core/client/api-path";
|
||||
import { useAgentRouteState } from "@agent-native/core/client/navigation";
|
||||
|
||||
import { TAB_ID } from "@/lib/tab-id";
|
||||
|
||||
export interface NavigationState {
|
||||
view?: string;
|
||||
path?: string;
|
||||
publicPath?: string;
|
||||
}
|
||||
|
||||
export function useNavigationState() {
|
||||
useAgentRouteState<NavigationState>({
|
||||
browserTabId: TAB_ID,
|
||||
requestSource: TAB_ID,
|
||||
getNavigationState: ({ pathname }) => ({
|
||||
view: viewForPath(pathname),
|
||||
path: pathname,
|
||||
publicPath: appPathFromLocalRoute(pathname),
|
||||
}),
|
||||
getCommandPath: commandPathForNavigation,
|
||||
});
|
||||
}
|
||||
|
||||
export function commandPathForNavigation(command: NavigationState): string {
|
||||
const fallbackPath = pathForView(command?.view);
|
||||
const path = typeof command?.path === "string" ? command.path : "";
|
||||
if (!path) return fallbackPath;
|
||||
|
||||
const basePath = appBasePath();
|
||||
if (!basePath) return path;
|
||||
|
||||
const suffixIndex = path.search(/[?#]/);
|
||||
const pathname = suffixIndex === -1 ? path : path.slice(0, suffixIndex);
|
||||
const suffix = suffixIndex === -1 ? "" : path.slice(suffixIndex);
|
||||
const publicPath =
|
||||
typeof command?.publicPath === "string" ? command.publicPath : "";
|
||||
const publicPathSuffixIndex = publicPath.search(/[?#]/);
|
||||
const declaredPublicPath =
|
||||
publicPathSuffixIndex === -1
|
||||
? publicPath
|
||||
: publicPath.slice(0, publicPathSuffixIndex);
|
||||
const publicViewPath = appPathFromLocalRoute(pathForView(command?.view));
|
||||
if (
|
||||
matchesPathPrefix(pathname, basePath) &&
|
||||
(matchesPathPrefix(pathname, publicViewPath) ||
|
||||
(declaredPublicPath && declaredPublicPath === pathname))
|
||||
) {
|
||||
return `${pathname.slice(basePath.length) || "/"}${suffix}`;
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
function matchesPathPrefix(pathname: string, prefix: string): boolean {
|
||||
return pathname === prefix || pathname.startsWith(`${prefix}/`);
|
||||
}
|
||||
|
||||
function viewForPath(pathname: string): string {
|
||||
if (pathname === "/") return "home";
|
||||
return "home";
|
||||
}
|
||||
|
||||
function pathForView(view?: string): string {
|
||||
switch (view) {
|
||||
case "home":
|
||||
return "/";
|
||||
default:
|
||||
return "/";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
type ReactNode,
|
||||
} from "react";
|
||||
|
||||
import { CINEMAS, type Cinema } from "@/lib/cinemas";
|
||||
import {
|
||||
fetchRoadDistances,
|
||||
straightLineDistance,
|
||||
type Coordinates,
|
||||
type DistanceResult,
|
||||
} from "@/lib/geo";
|
||||
|
||||
export type NearMeStatus =
|
||||
| "idle"
|
||||
| "locating"
|
||||
| "ready"
|
||||
| "denied"
|
||||
| "unsupported"
|
||||
| "error";
|
||||
|
||||
export type NearMeContextValue = {
|
||||
status: NearMeStatus;
|
||||
coords: Coordinates | null;
|
||||
/** ระยะทางต่อ slug — มีค่าเฉพาะหลังขอตำแหน่งสำเร็จ */
|
||||
distances: Record<string, DistanceResult | undefined>;
|
||||
requestLocation: () => void;
|
||||
};
|
||||
|
||||
const GEOLOCATION_TIMEOUT_MS = 10000;
|
||||
|
||||
const NearMeContext = createContext<NearMeContextValue | null>(null);
|
||||
|
||||
/** คำนวณระยะทางเส้นตรงให้ทุกโรง (ใช้เมื่อ OSRM เรียกไม่สำเร็จ) */
|
||||
function straightLineDistances(cinemas: Cinema[], origin: Coordinates) {
|
||||
const result: Record<string, DistanceResult | undefined> = {};
|
||||
for (const cinema of cinemas) {
|
||||
if (!cinema.coordinates) continue;
|
||||
result[cinema.slug] = straightLineDistance(origin, cinema.coordinates);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* แชร์ตำแหน่งอุปกรณ์และระยะทางถึงแต่ละโรงให้ทุกหน้า
|
||||
* ขอตำแหน่งเฉพาะเมื่อผู้ใช้กด "ใกล้ฉัน" เท่านั้น (ไม่ขออัตโนมัติ)
|
||||
* รายการโรงหนังมาจากเนื้อหาที่โหลดใน root loader (แก้จากหลังบ้านได้)
|
||||
*/
|
||||
export function NearMeProvider({
|
||||
cinemas,
|
||||
children,
|
||||
}: {
|
||||
cinemas: Cinema[];
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [status, setStatus] = useState<NearMeStatus>("idle");
|
||||
const [coords, setCoords] = useState<Coordinates | null>(null);
|
||||
const [distances, setDistances] = useState<
|
||||
Record<string, DistanceResult | undefined>
|
||||
>({});
|
||||
|
||||
const loadDistances = useCallback(
|
||||
async (origin: Coordinates) => {
|
||||
const targets = cinemas.filter((cinema) => cinema.coordinates !== null);
|
||||
try {
|
||||
const road = await fetchRoadDistances(
|
||||
origin,
|
||||
targets.map((cinema) => cinema.coordinates as Coordinates),
|
||||
);
|
||||
const next: Record<string, DistanceResult | undefined> = {};
|
||||
targets.forEach((cinema, index) => {
|
||||
const destination = cinema.coordinates as Coordinates;
|
||||
next[cinema.slug] =
|
||||
road[index] ?? straightLineDistance(origin, destination);
|
||||
});
|
||||
setDistances(next);
|
||||
} catch {
|
||||
setDistances(straightLineDistances(cinemas, origin));
|
||||
}
|
||||
setStatus("ready");
|
||||
},
|
||||
[cinemas],
|
||||
);
|
||||
|
||||
const requestLocation = useCallback(() => {
|
||||
if (typeof navigator === "undefined" || !navigator.geolocation) {
|
||||
setStatus("unsupported");
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("locating");
|
||||
navigator.geolocation.getCurrentPosition(
|
||||
(position) => {
|
||||
const origin: Coordinates = {
|
||||
latitude: position.coords.latitude,
|
||||
longitude: position.coords.longitude,
|
||||
};
|
||||
setCoords(origin);
|
||||
void loadDistances(origin);
|
||||
},
|
||||
(error) => {
|
||||
setStatus(error.code === error.PERMISSION_DENIED ? "denied" : "error");
|
||||
},
|
||||
{ timeout: GEOLOCATION_TIMEOUT_MS, maximumAge: 60000 },
|
||||
);
|
||||
}, [loadDistances]);
|
||||
|
||||
const value = useMemo<NearMeContextValue>(
|
||||
() => ({ status, coords, distances, requestLocation }),
|
||||
[status, coords, distances, requestLocation],
|
||||
);
|
||||
|
||||
return <NearMeContext.Provider value={value}>{children}</NearMeContext.Provider>;
|
||||
}
|
||||
|
||||
export function useNearMe(): NearMeContextValue {
|
||||
const value = useContext(NearMeContext);
|
||||
if (!value) throw new Error("useNearMe ต้องถูกใช้ภายใน <NearMeProvider>");
|
||||
return value;
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { createHmac } from "node:crypto";
|
||||
|
||||
import { createError, deleteCookie, getCookie, setCookie, type H3Event } from "h3";
|
||||
|
||||
export const ADMIN_COOKIE = "afx_admin";
|
||||
const SESSION_TTL_SECONDS = 60 * 60 * 8;
|
||||
|
||||
const DEFAULT_USERNAME = "it is me";
|
||||
const DEFAULT_PASSWORD = "it is me&it is me";
|
||||
|
||||
function secret(): string {
|
||||
return process.env.ADMIN_SESSION_SECRET ?? "alterflixhub-local-admin-secret";
|
||||
}
|
||||
|
||||
export function adminCredentials() {
|
||||
return {
|
||||
username: process.env.ADMIN_USERNAME ?? DEFAULT_USERNAME,
|
||||
password: process.env.ADMIN_PASSWORD ?? DEFAULT_PASSWORD,
|
||||
};
|
||||
}
|
||||
|
||||
export function isValidCredentials(username: string, password: string): boolean {
|
||||
const expected = adminCredentials();
|
||||
const given = createHmac("sha256", secret())
|
||||
.update(`${username}\u0000${password}`)
|
||||
.digest("hex");
|
||||
const wanted = createHmac("sha256", secret())
|
||||
.update(`${expected.username}\u0000${expected.password}`)
|
||||
.digest("hex");
|
||||
return given === wanted;
|
||||
}
|
||||
|
||||
function sign(payload: string): string {
|
||||
return createHmac("sha256", secret()).update(payload).digest("hex");
|
||||
}
|
||||
|
||||
function createToken(): string {
|
||||
const expiresAt = String(Date.now() + SESSION_TTL_SECONDS * 1000);
|
||||
return `${expiresAt}.${sign(expiresAt)}`;
|
||||
}
|
||||
|
||||
function isTokenValid(token: string | undefined): boolean {
|
||||
if (!token) return false;
|
||||
const [expiresAt, signature] = token.split(".");
|
||||
if (!expiresAt || !signature) return false;
|
||||
if (Number(expiresAt) < Date.now()) return false;
|
||||
return sign(expiresAt) === signature;
|
||||
}
|
||||
|
||||
export function createAdminSession(event: H3Event): void {
|
||||
setCookie(event, ADMIN_COOKIE, createToken(), {
|
||||
httpOnly: true,
|
||||
sameSite: "lax",
|
||||
path: "/",
|
||||
maxAge: SESSION_TTL_SECONDS,
|
||||
});
|
||||
}
|
||||
|
||||
export function clearAdminSession(event: H3Event): void {
|
||||
deleteCookie(event, ADMIN_COOKIE, { path: "/" });
|
||||
}
|
||||
|
||||
export function isAdmin(event: H3Event): boolean {
|
||||
return isTokenValid(getCookie(event, ADMIN_COOKIE));
|
||||
}
|
||||
|
||||
/** ใช้ใน API route ที่ต้องล็อกอินก่อน */
|
||||
export function requireAdmin(event: H3Event): void {
|
||||
if (!isAdmin(event)) {
|
||||
throw createError({ statusCode: 401, statusMessage: "ต้องเข้าสู่ระบบก่อน" });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type { AnalyticsEventType } from "@/lib/analytics-types";
|
||||
|
||||
export type TrackInput = {
|
||||
type: AnalyticsEventType;
|
||||
query?: string;
|
||||
category?: string;
|
||||
result_count?: number;
|
||||
slug?: string;
|
||||
source?: string;
|
||||
position?: number;
|
||||
locale?: string;
|
||||
};
|
||||
|
||||
const DEDUPE_WINDOW_MS = 1500;
|
||||
const recent = new Map<string, number>();
|
||||
|
||||
/**
|
||||
* ส่ง event สถิติไปที่ /api/analytics/collect
|
||||
* - กลืน error ทั้งหมด (สถิติต้องไม่ทำให้หน้าเว็บพัง)
|
||||
* - กัน event ซ้ำใน 1.5 วินาที (เช่น effect ยิงซ้ำตอน re-render)
|
||||
*/
|
||||
export function trackEvent(input: TrackInput): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
const key = JSON.stringify(input);
|
||||
const now = Date.now();
|
||||
const last = recent.get(key);
|
||||
if (last !== undefined && now - last < DEDUPE_WINDOW_MS) return;
|
||||
recent.set(key, now);
|
||||
|
||||
try {
|
||||
void fetch("/api/analytics/collect", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ events: [input] }),
|
||||
keepalive: true,
|
||||
}).catch(() => undefined);
|
||||
} catch {
|
||||
// ไม่ทำอะไร — ปล่อยให้หน้าเว็บทำงานต่อ
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
/**
|
||||
* สถิติแบบ privacy-first (แนวเดียวกับ Umami): ไม่ใช้คุกกี้ ไม่เก็บ IP/UA ดิบ
|
||||
* เก็บเป็น event ต่อบรรทัด (JSONL) แล้วสรุปผลฝั่งเซิร์ฟเวอร์
|
||||
*/
|
||||
|
||||
export type AnalyticsEventType = "search" | "cinema_select" | "cinema_view" | "near_me";
|
||||
|
||||
export type AnalyticsEvent = {
|
||||
type: AnalyticsEventType;
|
||||
/** เวลาที่เกิดเหตุ (ISO) — เซิร์ฟเวอร์เป็นผู้กำหนด */
|
||||
at: string;
|
||||
/** รหัสผู้เข้าชมแบบไม่ระบุตัวตน (sha256 ของ ip+ua+เกลือรายวัน) */
|
||||
visitor: string;
|
||||
locale: string;
|
||||
/** คำค้น (เฉพาะ type=search) */
|
||||
query?: string;
|
||||
category?: string;
|
||||
result_count?: number;
|
||||
slug?: string;
|
||||
/** ที่มาของการคลิก: search | category | near_me | other_cinemas */
|
||||
source?: string;
|
||||
position?: number;
|
||||
};
|
||||
|
||||
export type SearchQueryStat = {
|
||||
query: string;
|
||||
count: number;
|
||||
zero_result_count: number;
|
||||
click_count: number;
|
||||
};
|
||||
|
||||
export type CinemaStat = {
|
||||
slug: string;
|
||||
views: number;
|
||||
selects: number;
|
||||
};
|
||||
|
||||
export type AnalyticsSummary = {
|
||||
range_days: number;
|
||||
total_searches: number;
|
||||
unique_visitors: number;
|
||||
zero_result_searches: number;
|
||||
near_me_uses: number;
|
||||
average_results: number;
|
||||
click_through_rate: number;
|
||||
top_queries: SearchQueryStat[];
|
||||
zero_result_queries: SearchQueryStat[];
|
||||
top_categories: Array<{ category: string; count: number }>;
|
||||
top_cinemas: CinemaStat[];
|
||||
daily_searches: Array<{ date: string; count: number }>;
|
||||
/** คำค้นล่าสุด เพื่อดูพฤติกรรมสด ๆ ในหลังบ้าน */
|
||||
recent_searches: Array<{ at: string; query: string; result_count: number }>;
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
import { appendFile, mkdir, readFile, rename, stat } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
|
||||
import type {
|
||||
AnalyticsEvent,
|
||||
AnalyticsSummary,
|
||||
CinemaStat,
|
||||
SearchQueryStat,
|
||||
} from "@/lib/analytics-types";
|
||||
|
||||
const ANALYTICS_DIR = path.join(process.cwd(), "data", "analytics");
|
||||
const EVENTS_FILE = path.join(ANALYTICS_DIR, "events.jsonl");
|
||||
/** เก็บสูงสุดเท่านี้แล้วหมุนไฟล์ เพื่อไม่ให้อ่านช้าเมื่อนานวัน */
|
||||
const MAX_EVENTS = 50_000;
|
||||
|
||||
function normalizeQuery(query: string): string {
|
||||
return query.trim().toLowerCase().replace(/\s+/g, " ");
|
||||
}
|
||||
|
||||
export async function appendEvent(event: AnalyticsEvent): Promise<void> {
|
||||
await mkdir(ANALYTICS_DIR, { recursive: true });
|
||||
await appendFile(EVENTS_FILE, `${JSON.stringify(event)}\n`, "utf8");
|
||||
await rotateIfNeeded();
|
||||
}
|
||||
|
||||
async function rotateIfNeeded(): Promise<void> {
|
||||
try {
|
||||
const info = await stat(EVENTS_FILE);
|
||||
if (info.size < 8 * 1024 * 1024) return;
|
||||
await rename(EVENTS_FILE, `${EVENTS_FILE}.${Date.now()}.bak`);
|
||||
} catch {
|
||||
// ไฟล์ยังไม่เกิด — ไม่ต้องหมุน
|
||||
}
|
||||
}
|
||||
|
||||
export async function readEvents(): Promise<AnalyticsEvent[]> {
|
||||
try {
|
||||
const raw = await readFile(EVENTS_FILE, "utf8");
|
||||
return raw
|
||||
.split("\n")
|
||||
.filter((line) => line.trim() !== "")
|
||||
.flatMap((line) => {
|
||||
try {
|
||||
return [JSON.parse(line) as AnalyticsEvent];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
})
|
||||
.slice(-MAX_EVENTS);
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
function percentage(part: number, whole: number): number {
|
||||
if (whole === 0) return 0;
|
||||
return Math.round((part / whole) * 1000) / 10;
|
||||
}
|
||||
|
||||
/** สรุปสถิติการค้นหา/การเลือกโรงหนังในช่วง N วันล่าสุด */
|
||||
export function summarize(
|
||||
events: AnalyticsEvent[],
|
||||
rangeDays: number,
|
||||
now = Date.now(),
|
||||
): AnalyticsSummary {
|
||||
const since = now - rangeDays * 24 * 60 * 60 * 1000;
|
||||
const inRange = events.filter((event) => {
|
||||
const time = Date.parse(event.at);
|
||||
return Number.isFinite(time) && time >= since;
|
||||
});
|
||||
|
||||
const searches = inRange.filter((event) => event.type === "search");
|
||||
const selects = inRange.filter((event) => event.type === "cinema_select");
|
||||
const visitors = new Set(inRange.map((event) => event.visitor));
|
||||
|
||||
const queryMap = new Map<string, SearchQueryStat>();
|
||||
const categoryMap = new Map<string, number>();
|
||||
const dailyMap = new Map<string, number>();
|
||||
const cinemaMap = new Map<string, CinemaStat>();
|
||||
|
||||
let resultTotal = 0;
|
||||
let zeroResults = 0;
|
||||
|
||||
for (const event of searches) {
|
||||
const query = normalizeQuery(event.query ?? "");
|
||||
if (query === "") continue;
|
||||
const stat = queryMap.get(query) ?? {
|
||||
query,
|
||||
count: 0,
|
||||
zero_result_count: 0,
|
||||
click_count: 0,
|
||||
};
|
||||
stat.count += 1;
|
||||
if ((event.result_count ?? 0) === 0) stat.zero_result_count += 1;
|
||||
queryMap.set(query, stat);
|
||||
|
||||
resultTotal += event.result_count ?? 0;
|
||||
if ((event.result_count ?? 0) === 0) zeroResults += 1;
|
||||
|
||||
const category = event.category ?? "ทั้งหมด";
|
||||
categoryMap.set(category, (categoryMap.get(category) ?? 0) + 1);
|
||||
|
||||
const date = event.at.slice(0, 10);
|
||||
dailyMap.set(date, (dailyMap.get(date) ?? 0) + 1);
|
||||
}
|
||||
|
||||
for (const event of selects) {
|
||||
const slug = event.slug ?? "";
|
||||
if (slug === "") continue;
|
||||
const stat = cinemaMap.get(slug) ?? { slug, views: 0, selects: 0 };
|
||||
stat.selects += 1;
|
||||
cinemaMap.set(slug, stat);
|
||||
// นับคลิกให้คำค้นที่ผู้ใช้ค้นล่าสุด (ถ้ามี source=search)
|
||||
if (event.source === "search" && event.query) {
|
||||
const query = normalizeQuery(event.query);
|
||||
const queryStat = queryMap.get(query);
|
||||
if (queryStat) queryStat.click_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
for (const event of inRange) {
|
||||
if (event.type !== "cinema_view" || !event.slug) continue;
|
||||
const stat = cinemaMap.get(event.slug) ?? {
|
||||
slug: event.slug,
|
||||
views: 0,
|
||||
selects: 0,
|
||||
};
|
||||
stat.views += 1;
|
||||
cinemaMap.set(event.slug, stat);
|
||||
}
|
||||
|
||||
const allQueries = Array.from(queryMap.values()).sort(
|
||||
(first, second) => second.count - first.count,
|
||||
);
|
||||
|
||||
return {
|
||||
range_days: rangeDays,
|
||||
total_searches: searches.length,
|
||||
unique_visitors: visitors.size,
|
||||
zero_result_searches: zeroResults,
|
||||
near_me_uses: inRange.filter((event) => event.type === "near_me").length,
|
||||
average_results:
|
||||
searches.length === 0 ? 0 : Math.round((resultTotal / searches.length) * 10) / 10,
|
||||
click_through_rate: percentage(selects.length, searches.length),
|
||||
top_queries: allQueries.slice(0, 20),
|
||||
zero_result_queries: allQueries
|
||||
.filter((stat) => stat.zero_result_count > 0)
|
||||
.sort((first, second) => second.zero_result_count - first.zero_result_count)
|
||||
.slice(0, 10),
|
||||
top_categories: Array.from(categoryMap.entries())
|
||||
.map(([category, count]) => ({ category, count }))
|
||||
.sort((first, second) => second.count - first.count)
|
||||
.slice(0, 10),
|
||||
top_cinemas: Array.from(cinemaMap.values())
|
||||
.sort(
|
||||
(first, second) =>
|
||||
second.selects + second.views - (first.selects + first.views),
|
||||
)
|
||||
.slice(0, 10),
|
||||
daily_searches: Array.from(dailyMap.entries())
|
||||
.map(([date, count]) => ({ date, count }))
|
||||
.sort((first, second) => first.date.localeCompare(second.date)),
|
||||
recent_searches: [...searches]
|
||||
.sort((first, second) => second.at.localeCompare(first.at))
|
||||
.slice(0, 15)
|
||||
.map((event) => ({
|
||||
at: event.at,
|
||||
query: normalizeQuery(event.query ?? ""),
|
||||
result_count: event.result_count ?? 0,
|
||||
}))
|
||||
.filter((row) => row.query !== ""),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { summarize } from "./analytics.server";
|
||||
import type { AnalyticsEvent } from "./analytics-types";
|
||||
|
||||
const NOW = Date.parse("2026-10-29T10:00:00.000Z");
|
||||
|
||||
function event(partial: Partial<AnalyticsEvent>): AnalyticsEvent {
|
||||
return {
|
||||
type: "search",
|
||||
at: "2026-10-29T09:00:00.000Z",
|
||||
visitor: "v1",
|
||||
locale: "th",
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
describe("summarize", () => {
|
||||
const events: AnalyticsEvent[] = [
|
||||
event({ query: "House Samyan", result_count: 1 }),
|
||||
event({ query: "house samyan", result_count: 1 }),
|
||||
event({ query: "ไม่มีโรงนี้", result_count: 0, visitor: "v2" }),
|
||||
event({ query: "อาร์ตเฮาส์", category: "อาร์ตเฮาส์", result_count: 2 }),
|
||||
event({ type: "cinema_select", slug: "house-cinema-samyan", source: "search", query: "house samyan" }),
|
||||
event({ type: "cinema_view", slug: "house-cinema-samyan" }),
|
||||
event({ type: "near_me", result_count: 6 }),
|
||||
// เก่าเกินช่วง 7 วัน — ต้องไม่ถูกนับ
|
||||
event({ query: "เก่ามาก", at: "2026-10-01T09:00:00.000Z" }),
|
||||
];
|
||||
|
||||
const summary = summarize(events, 7, NOW);
|
||||
|
||||
it("นับเฉพาะ event ในช่วงเวลา", () => {
|
||||
expect(summary.total_searches).toBe(4);
|
||||
});
|
||||
|
||||
it("นับผู้เข้าชมไม่ซ้ำจาก hash", () => {
|
||||
expect(summary.unique_visitors).toBe(2);
|
||||
});
|
||||
|
||||
it("รวมคำค้นที่ต่างแค่ช่องว่าง/ตัวพิมพ์ และนับครั้งที่ค้นไม่พบ", () => {
|
||||
const house = summary.top_queries.find((row) => row.query === "house samyan");
|
||||
expect(house?.count).toBe(2);
|
||||
expect(summary.top_queries.find((row) => row.query === "ไม่มีโรงนี้")?.zero_result_count).toBe(1);
|
||||
expect(summary.zero_result_searches).toBe(1);
|
||||
});
|
||||
|
||||
it("นับคลิกต่อคำค้นและการเปิดดูโรงหนัง", () => {
|
||||
const house = summary.top_queries.find((row) => row.query === "house samyan");
|
||||
expect(house?.click_count).toBe(1);
|
||||
const cinema = summary.top_cinemas.find((row) => row.slug === "house-cinema-samyan");
|
||||
expect(cinema).toEqual({ slug: "house-cinema-samyan", views: 1, selects: 1 });
|
||||
});
|
||||
|
||||
it("สรุปจำนวนครั้งที่ใช้ ใกล้ฉัน และ CTR", () => {
|
||||
expect(summary.near_me_uses).toBe(1);
|
||||
expect(summary.click_through_rate).toBe(25);
|
||||
});
|
||||
|
||||
it("ผลลัพธ์เฉลี่ยต่อการค้นหา", () => {
|
||||
expect(summary.average_results).toBe(1);
|
||||
});
|
||||
|
||||
it("คำค้นล่าสุดเรียงจากใหม่ไปเก่าและตัด event นอกช่วงออก", () => {
|
||||
expect(summary.recent_searches.length).toBeGreaterThan(0);
|
||||
const times = summary.recent_searches.map((row) => row.at);
|
||||
expect([...times].sort((a, b) => b.localeCompare(a))).toEqual(times);
|
||||
expect(summary.recent_searches.some((row) => row.query === "เก่ามาก")).toBe(false);
|
||||
});
|
||||
});
|
||||
Loaded 100 of 188 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user