Compare commits

..
17 Commits
Author SHA1 Message Date
ZacharyZhang-NYandClaude Opus 5.5 e374bc1e8e Release: drop an empty CSC_LINK so the keychain identity signs the macOS build
Build Release Installers / Release for the tag (push) Successful in 11s
Build Release Installers / Windows installer (NSIS x64) (push) Successful in 1m19s
Build Release Installers / Linux packages (AppImage + deb x64) (push) Successful in 2m16s
CI / Typecheck, lint, tests, e2e (push) Successful in 3m25s
Build Release Installers / macOS installers (dmg + zip, x64 + arm64) (push) Successful in 7m22s
electron-builder read the empty secret as a certificate path and failed with "not a file". Also keeps lighting.ts types module-private.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 21:31:36 -04:00
ZacharyZhang-NYandClaude Opus 5.5 eca8693ac3 Release: build macOS installers on the login-session signing runner
Build Release Installers / macOS installers (dmg + zip, x64 + arm64) (push) Failing after 26s
Build Release Installers / Release for the tag (push) Successful in 11s
Build Release Installers / Windows installer (NSIS x64) (push) Successful in 1m14s
CI / Typecheck, lint, tests, e2e (push) Successful in 3m36s
Build Release Installers / Linux packages (AppImage + deb x64) (push) Successful in 1m56s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 21:27:22 -04:00
ZacharyZhang-NYandClaude Opus 5.5 7b07bcea02 Release: fail the macOS job when notarization secrets are set but the Developer ID identity is unreachable
CI / Typecheck, lint, tests, e2e (push) Successful in 3m37s
v1.5.1 shipped ad-hoc macOS installers with only a warning: the runner ran as a system LaunchDaemon, outside the login keychain's session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 21:24:50 -04:00
ZacharyZhang-NYandClaude Opus 5.5 245ff66336 1.5.1: refined office, chat in the app language, current OpenAI models, own connector keys
Build Release Installers / Release for the tag (push) Successful in 16s
Build Release Installers / Windows installer (NSIS x64) (push) Successful in 1m48s
CI / Typecheck, lint, tests, e2e (push) Successful in 3m52s
Build Release Installers / Linux packages (AppImage + deb x64) (push) Successful in 2m21s
Build Release Installers / macOS installers (dmg + zip, x64 + arm64) (push) Successful in 7m15s
- Home: the goal title box is two line boxes tall (2.8em), so a third line no longer peeks out.
- Chat messages, reply fallbacks and assignment DMs follow the app display language; tasks and documents keep the working language.
- OpenAI and GPT-account model lists match OpenAI's current line-up; default gpt-6.1-sol.
- Onboarding connectors step takes the operator's Composio and logo.dev keys, then lists the toolkits the Composio project enables; without a key Connectors leaves the sidebar.
- Google Antigravity removed end to end (migration 111), with the remote-revocation path only it used.
- Office: 2x pixel people with outlines, rim light, walk, typing and blink; dithered real-clock lighting; detailed furniture and floors.
- Per-agent model picker lists the provider's whole model list, live when connected.
- Chat wake context breaks same-millisecond ties by insertion order; the mid-run inbox dedupes by message id.
- The stored "clock" theme reads back instead of falling to "system".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 21:12:19 -04:00
ZacharyZhang-NYandClaude Opus 5.5 48dfddffef Linux packages: set the project homepage the deb format requires
Build Release Installers / Release for the tag (push) Successful in 10s
Build Release Installers / Linux packages (AppImage + deb x64) (push) Successful in 2m0s
CI / Typecheck, lint, tests, e2e (push) Successful in 3m6s
Build Release Installers / Windows installer (NSIS x64) (push) Successful in 1m5s
Build Release Installers / macOS installers (dmg + zip, x64 + arm64) (push) Successful in 10m33s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:54:20 -04:00
ZacharyZhang-NYandClaude Opus 5.5 8299346fbd CI on Gitea: cap test workers so a shared runner does not time out; tag pushes build and attach Windows, Linux and macOS installers to the Gitea release; version 1.5.0
CI / Typecheck, lint, tests, e2e (push) Successful in 3m29s
Build Release Installers / Release for the tag (push) Successful in 11s
Build Release Installers / Linux packages (AppImage + deb x64) (push) Failing after 37s
Build Release Installers / Windows installer (NSIS x64) (push) Successful in 55s
Build Release Installers / macOS installers (dmg + zip, x64 + arm64) (push) Successful in 6m53s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 16:33:46 -04:00
ZacharyZhang-NY 15a93165e0 docs: add AGit pull request instructions
CI / Typecheck, lint, tests, e2e (push) Failing after 5m34s
2026-10-09 19:46:34 +00:00
ZacharyZhang-NYandClaude Opus 5.5 05ad409624 S3.10: office card shows the person's pixel portrait; provider policy explanations move into column tooltips
CI / Typecheck, lint, tests, e2e (push) Failing after 6m37s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 14:03:19 -04:00
ZacharyZhang-NYandClaude Opus 5.5 e5a4e87300 S3.9: the org chart draws everyone as their office pixel person, with one shared CEO rule
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:56:49 -04:00
ZacharyZhang-NYandClaude Opus 5.5 ccd698602e S3.8: office people show real agent state: running, queued, cooling down, blocked or idle, from sessions, task holds and pending approvals
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:51:04 -04:00
ZacharyZhang-NYandClaude Opus 5.5 202418f81c S3.7: isometric office assets: animated monitors, coffee machine with steam, toilets, sinks, real-time wall clock, decorative window weather; explanatory on-screen notes and the hint bubble removed
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:34:12 -04:00
ZacharyZhang-NYandClaude Opus 5.5 23c7d55b1d S3.6: isometric 2.5D office engine: projection, depth-sorted blocks and people, half-resolution pixel rendering, day-part and season palette
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 13:03:04 -04:00
ZacharyZhang-NYandClaude Opus 5.5 5dfc2a6dc6 S3.5: every page on the pixel grid: tokenised type, square corners, pixel charts with HTML axis labels
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:45:15 -04:00
ZacharyZhang-NYandClaude Opus 5.5 c97adc14cb S3.4: pixel shell, navigation and global search
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:29:12 -04:00
ZacharyZhang-NYandClaude Opus 5.5 08ff96eec8 S3.3: pixel components: name-plate dialog titles, sunken fields, raised tabs, notched badges, XP bars, inventory slots, guide hint bubbles, game-over errors with Continue
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:23:17 -04:00
ZacharyZhang-NYandClaude Opus 5.5 a6036308b7 S3.2: hand-placed 12x12 pixel icon set replaces lucide and reicon
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:13:33 -04:00
ZacharyZhang-NYandClaude Opus 5.5 86dbb4efa1 S3.1: pixel design language: palette with day-part and season rotation, Fusion Pixel font on whole screen pixels, dither ground, 9-slice dialogs, pixel buttons, menu arrow
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 12:07:31 -04:00
185 changed files with 3788 additions and 2347 deletions

No files matched your search

+68 -51
View File
@@ -1,28 +1,38 @@
name: Build Release Installers
# Builds Windows and macOS installers when a release is published and
# attaches them to it. macOS builds are signed and notarized only when the
# runner has the Developer ID identity and the APPLE_API_ISSUER and
# APPLE_API_KEY_P8 secrets are set; otherwise they are ad-hoc signed.
# A pushed v* tag builds Windows, Linux and macOS installers on the Gitea
# runners and attaches them to the tag's release. The tag must equal
# "v" + package.json version. macOS builds are signed and notarized when the
# APPLE_API_* secrets are set (the Developer ID identity must then be reachable,
# or the job fails); without those secrets they are ad-hoc signed.
on:
release:
types: [published]
workflow_dispatch:
inputs:
tag:
description: "Release tag to attach installers to (back-fill)"
required: true
push:
tags: ["v*"]
permissions:
contents: write
env:
COREPACK_ENABLE_DOWNLOAD_PROMPT: "0"
GITEA_TOKEN: ${{ secrets.GITHUB_TOKEN }}
jobs:
release:
name: Release for the tag
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
package-manager-cache: false
- name: Check version and create the release
run: node scripts/gitea-release.mjs create
windows:
name: Windows installer (NSIS x64)
needs: release
runs-on: windows-latest
steps:
- uses: actions/checkout@v5
@@ -31,28 +41,18 @@ jobs:
node-version: 24
package-manager-cache: false
- name: Enable pnpm via corepack
run: |
corepack enable pnpm
pnpm --version
run: corepack enable pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build installer
run: pnpm run package:win
- name: List artifacts
run: Get-ChildItem release
- name: Upload installer to release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ github.event.release.tag_name || inputs.tag }}
run: |
$exts = @('.exe', '.dmg', '.zip', '.AppImage', '.deb')
$files = Get-ChildItem release -File | Where-Object { $exts -contains $_.Extension }
if (-not $files) { throw "no uploadable artifacts found in release/" }
gh release upload $env:TAG @($files.FullName) --clobber
- name: Upload installer
run: node scripts/gitea-release.mjs upload release
macos:
name: macOS installers (dmg + zip, x64 + arm64)
runs-on: macos-latest
linux:
name: Linux packages (AppImage + deb x64)
needs: release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
@@ -60,33 +60,62 @@ jobs:
node-version: 24
package-manager-cache: false
- name: Enable pnpm via corepack
run: |
corepack enable pnpm
pnpm --version
run: corepack enable pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Build packages
run: pnpm run package:linux
- name: Upload packages
run: node scripts/gitea-release.mjs upload release
macos:
name: macOS installers (dmg + zip, x64 + arm64)
needs: release
# Runs in the login session, where the Developer ID identity lives.
runs-on: macos-signing
steps:
- uses: actions/checkout@v5
- uses: actions/setup-node@v5
with:
node-version: 24
package-manager-cache: false
- name: Enable pnpm via corepack
run: corepack enable pnpm
- name: Install dependencies
run: pnpm install --frozen-lockfile
- name: Detect signing capability
id: signing
env:
CSC_LINK: ${{ secrets.CSC_LINK }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
run: |
if security find-identity -v -p codesigning | grep -q "Developer ID Application: Yang Zhang (9PDD8M2SMS)" && [ -n "$APPLE_API_ISSUER" ] && [ -n "$APPLE_API_KEY_P8" ]; then
echo "signed=true" >> "$GITHUB_OUTPUT"
echo "Developer ID identity and notarization credentials found: building signed + notarized installers."
else
if [ -z "$APPLE_API_ISSUER" ] || [ -z "$APPLE_API_KEY_ID" ] || [ -z "$APPLE_API_KEY_P8" ]; then
echo "signed=false" >> "$GITHUB_OUTPUT"
echo "::warning::Building ad-hoc-signed, un-notarized macOS installers."
echo "::warning::No notarization secrets: building ad-hoc-signed, un-notarized macOS installers."
elif [ -n "$CSC_LINK" ] || security find-identity -v -p codesigning | grep -q "Developer ID Application: Yang Zhang (9PDD8M2SMS)"; then
echo "signed=true" >> "$GITHUB_OUTPUT"
echo "Developer ID certificate and notarization credentials found: building signed + notarized installers."
else
security find-identity -v -p codesigning
echo "::error::Notarization secrets are set but this runner cannot reach the Developer ID identity; run the runner in the login session or set CSC_LINK."
exit 1
fi
- name: Build installers (signed + notarized)
if: steps.signing.outputs.signed == 'true'
env:
CSC_LINK: ${{ secrets.CSC_LINK }}
CSC_KEY_PASSWORD: ${{ secrets.CSC_KEY_PASSWORD }}
APPLE_API_KEY: ${{ runner.temp }}/apple-api-key.p8
APPLE_API_KEY_ID: ZDCSZ5IE7071
APPLE_API_KEY_ID: ${{ secrets.APPLE_API_KEY_ID }}
APPLE_API_ISSUER: ${{ secrets.APPLE_API_ISSUER }}
APPLE_API_KEY_P8: ${{ secrets.APPLE_API_KEY_P8 }}
run: |
# An empty CSC_LINK reads as a certificate path; the keychain signs instead.
[ -n "$CSC_LINK" ] || unset CSC_LINK CSC_KEY_PASSWORD
printf '%s' "$APPLE_API_KEY_P8" > "$APPLE_API_KEY"
trap 'rm -f "$APPLE_API_KEY"' EXIT
pnpm build
pnpm exec electron-builder --mac --x64 --arm64 --publish never -c.forceCodeSigning=true
- name: Build installers (ad-hoc fallback)
@@ -94,17 +123,5 @@ jobs:
run: |
pnpm build
pnpm exec electron-builder --mac --x64 --arm64 --publish never --config electron-builder.unsigned.yml
- name: List artifacts
run: ls -la release
- name: Upload installers to release
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ github.event.release.tag_name || inputs.tag }}
run: |
shopt -s nullglob
files=(release/*.dmg release/*.zip)
if [ ${#files[@]} -eq 0 ]; then
echo "no uploadable artifacts found in release/" >&2
exit 1
fi
gh release upload "$TAG" "${files[@]}" --clobber
- name: Upload installers
run: node scripts/gitea-release.mjs upload release
+15
View File
@@ -0,0 +1,15 @@
# Contributing
## Opening a pull request on git.zacharyzhang.com
Forking is disabled on this server. Open pull requests with AGit instead:
1. Register an account at https://git.zacharyzhang.com
2. Clone, commit your changes, then push to a `refs/for/<target-branch>` ref:
```bash
git clone https://git.zacharyzhang.com/ZacharyZhang-NY/AgentCompany.git
git push origin HEAD:refs/for/main -o topic=<short-name> -o title="<PR title>" -o description="<PR body>"
```
3. To update the pull request, push again with the same `topic`.
-1
View File
@@ -21,7 +21,6 @@ The app ships with no keys. Add your own in **Settings > Integrations**:
|---|---|---|
| Composio API key | Connectors page and agent connector tools | platform.composio.dev |
| logo.dev publishable key | Connector logos | logo.dev |
| Google Antigravity OAuth client secret | Google Antigravity sign-in | Google |
Model provider keys and sign-ins live in **Settings > Providers**. All keys are encrypted with the OS keychain.
+2 -3
View File
@@ -1,9 +1,10 @@
{
"name": "agentcompany-new",
"version": "1.4.1",
"version": "1.5.1",
"private": true,
"type": "module",
"description": "Enterprise Electron control plane for AI agent companies.",
"homepage": "https://git.zacharyzhang.com/ZacharyZhang-NY/AgentCompany",
"author": {
"name": "AgentCompany",
"email": "dev@agentcompany.ai"
@@ -31,11 +32,9 @@
"postinstall": "node scripts/ensure-electron.cjs"
},
"dependencies": {
"lucide-react": "0.468.0",
"react": "19.2.4",
"react-dom": "19.2.4",
"react-markdown": "10.1.0",
"reicon-react": "^1.1.2",
"remark-gfm": "4.0.1",
"zod": "4.3.6"
},
-24
View File
@@ -14,9 +14,6 @@ importers:
.:
dependencies:
lucide-react:
specifier: 0.468.0
version: 0.468.0(react@19.2.4)
react:
specifier: 19.2.4
version: 19.2.4
@@ -26,9 +23,6 @@ importers:
react-markdown:
specifier: 10.1.0
version: 10.1.0(@types/react@19.2.2)(react@19.2.4)
reicon-react:
specifier: ^1.1.2
version: 1.1.2(react@19.2.4)
remark-gfm:
specifier: 4.0.1
version: 4.0.1
@@ -1950,11 +1944,6 @@ packages:
resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==}
engines: {node: '>=10'}
lucide-react@0.468.0:
resolution: {integrity: sha512-6koYRhnM2N0GGZIdXzSeiNwguv1gt/FAjZOiPl76roBi3xKEXa4WmfpxgQwTTL4KipXjefrnf3oV4IsYhi4JFA==}
peerDependencies:
react: ^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0-rc
magic-string@0.30.21:
resolution: {integrity: sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==}
@@ -2426,11 +2415,6 @@ packages:
resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==}
engines: {node: '>= 6'}
reicon-react@1.1.2:
resolution: {integrity: sha512-dbp1CPEPKFjWfG41lGRMWi74YKfKJlb2JcB/TRBAUQF6jalZYW1dRZisRPCpze5TfQwRBD30p40qnoY+oYi7MQ==}
peerDependencies:
react: '>=16.8.0'
remark-gfm@4.0.1:
resolution: {integrity: sha512-1quofZ2RQ9EWdeN34S79+KExV1764+wCUGop5CPL1WGdD0ocPpu91lzPGbwWMECpEpd42kJGQwzRfyov9j4yNg==}
@@ -4908,10 +4892,6 @@ snapshots:
dependencies:
yallist: 4.0.0
lucide-react@0.468.0(react@19.2.4):
dependencies:
react: 19.2.4
magic-string@0.30.21:
dependencies:
'@jridgewell/sourcemap-codec': 1.5.5
@@ -5623,10 +5603,6 @@ snapshots:
string_decoder: 1.1.1
util-deprecate: 1.0.2
reicon-react@1.1.2(react@19.2.4):
dependencies:
react: 19.2.4
remark-gfm@4.0.1:
dependencies:
'@types/mdast': 4.0.4
+53
View File
@@ -0,0 +1,53 @@
// Gitea release for the pushed tag: `create` checks the tag against package.json and opens the release; `upload` attaches installers.
import { openAsBlob } from "node:fs";
import { readdir, readFile } from "node:fs/promises";
import { basename, join } from "node:path";
const INSTALLER = /\.(exe|dmg|zip|AppImage|deb)$/;
function env(name) {
const value = process.env[name];
if (!value) throw new Error(`${name} is not set.`);
return value;
}
const api = `${env("GITHUB_SERVER_URL")}/api/v1/repos/${env("GITHUB_REPOSITORY")}`;
const tag = env("GITHUB_REF_NAME");
const headers = { Authorization: `token ${env("GITEA_TOKEN")}` };
async function call(method, path, body) {
const response = await fetch(`${api}${path}`, { method, headers: body instanceof FormData ? headers : { ...headers, "Content-Type": "application/json" }, body: body instanceof FormData ? body : body && JSON.stringify(body) });
if (!response.ok) throw new Error(`${method} ${path} failed: ${response.status} ${await response.text()}`);
return response.status === 204 ? null : response.json();
}
async function create() {
const { version } = JSON.parse(await readFile("package.json", "utf8"));
if (tag !== `v${version}`) throw new Error(`Tag ${tag} does not match package.json version ${version}; bump the version before tagging.`);
const existing = await fetch(`${api}/releases/tags/${tag}`, { headers });
if (existing.ok) return console.log(`Release ${tag} already exists.`);
if (existing.status !== 404) throw new Error(`Looking up release ${tag} failed: ${existing.status} ${await existing.text()}`);
await call("POST", "/releases", { tag_name: tag, name: `AgentCompany ${version}`, draft: false, prerelease: false });
console.log(`Created release ${tag}.`);
}
async function upload(dir) {
const files = (await readdir(dir)).filter((name) => INSTALLER.test(name)).map((name) => join(dir, name));
if (files.length === 0) throw new Error(`No installers found in ${dir}.`);
const release = await call("GET", `/releases/tags/${tag}`);
for (const file of files) {
const name = basename(file);
// A re-run replaces the asset instead of failing on the duplicate name.
const old = release.assets.find((asset) => asset.name === name);
if (old) await call("DELETE", `/releases/${release.id}/assets/${old.id}`);
const form = new FormData();
form.append("attachment", await openAsBlob(file), name);
await call("POST", `/releases/${release.id}/assets?name=${encodeURIComponent(name)}`, form);
console.log(`Uploaded ${name}.`);
}
}
const [command, dir] = process.argv.slice(2);
if (command === "create") await create();
else if (command === "upload") await upload(dir ?? "release");
else throw new Error(`Unknown command ${command}; use create or upload.`);
+1 -1
View File
@@ -21,7 +21,7 @@ export const organizationContracts = {
goalTitle: z.string(), goalDescription: z.string(), providerKey: z.string(), providerSecret: z.string(), providerModel: z.string(),
}) satisfies z.ZodType<C.BootstrapOnboardingInput>,
setActiveOrganization: z.strictObject({ orgId: id }) satisfies z.ZodType<C.SetActiveOrganizationInput>,
setUiPreferences: z.strictObject({ theme: z.enum(["system", "light", "dark"]).optional(), language: z.enum(["en", "zh"]).optional() }) satisfies z.ZodType<C.SetUiPreferencesInput>,
setUiPreferences: z.strictObject({ theme: z.enum(["system", "light", "dark", "clock"]).optional(), language: z.enum(["en", "zh"]).optional() }) satisfies z.ZodType<C.SetUiPreferencesInput>,
deleteOrganization: z.strictObject({ orgId: id }) satisfies z.ZodType<C.DeleteOrganizationInput>,
createOrganization: z.strictObject({
organizationName: z.string(), description: z.string().optional(), mission: z.string(), goal: z.string(), employeeName: z.string(),
+2 -12
View File
@@ -65,7 +65,7 @@ export function registerIpcHandlers(deps: IpcDeps): void {
const chat = new ChatService(deps.connection.db);
const providers = new ProviderService(deps.connection.db);
const integrationKeys = new IntegrationKeyStore(deps.connection.db);
const providerOAuth = new ProviderOAuthService(integrationKeys);
const providerOAuth = new ProviderOAuthService();
const skills = new SkillService(deps.connection.db, deps.artifactRoot);
const announceChange = coalesce(() => {
try {
@@ -261,17 +261,7 @@ export function registerIpcHandlers(deps: IpcDeps): void {
}
});
handle("setProviderModel", (input) => mutate(() => setProviderModel(deps.connection.db, input)));
handle("revokeProviderCredential", async (input) => {
try {
await providers.revokeCredential(input);
notifyDataChanged();
return ok(snapshot.load());
} catch (error) {
// The local disconnect has happened even when the provider refused the revocation.
notifyDataChanged();
return fail("provider_revoke_failed", error instanceof Error ? error.message : String(error));
}
});
handle("revokeProviderCredential", (input) => mutate(() => providers.revokeCredential(input)));
handle("updateProviderPolicy", (input) => mutate(() => providers.updatePolicy(input)));
handle("setProviderPrices", (input) => mutate(() => providers.setPrices(input)));
handle("setGoalAuditor", (input) => mutate(() => setGoalAuditor(deps.connection.db, input)));
@@ -0,0 +1,13 @@
// Google Antigravity is no longer offered; its rows, secrets and key go.
export const dropGoogleAntigravitySchema = `
update agents set model_provider_id = null, model_id = null
where model_provider_id in (select id from providers where provider_key = 'google-antigravity');
update organizations set audit_provider_id = null
where audit_provider_id in (select id from providers where provider_key = 'google-antigravity');
delete from providers where provider_key = 'google-antigravity';
update credentials set ciphertext = x'' where provider_key = 'google-antigravity';
delete from integration_keys where name = 'google_antigravity_client_secret';
update app_state
set onboarding_draft_json = json_set(onboarding_draft_json, '$.step', 'provider', '$.providerKey', 'openai', '$.providerModel', 'gpt-6.1-sol', '$.providerBaseUrl', '')
where json_extract(onboarding_draft_json, '$.providerKey') = 'google-antigravity';
`;
+2
View File
@@ -109,6 +109,7 @@ import { searchPendingSchema } from "./migrations/107-search-pending";
import { dropAutomationRulesSchema } from "./migrations/108-drop-automation-rules";
import { dropMeetingsSchema } from "./migrations/109-drop-meetings";
import { dropSprintsSchema } from "./migrations/110-drop-sprints";
import { dropGoogleAntigravitySchema } from "./migrations/111-drop-google-antigravity";
interface Migration {
version: number;
@@ -227,6 +228,7 @@ const MIGRATIONS: Migration[] = [
{ version: 108, name: "drop_automation_rules", sql: dropAutomationRulesSchema },
{ version: 109, name: "drop_meetings", sql: dropMeetingsSchema },
{ version: 110, name: "drop_sprints", sql: dropSprintsSchema },
{ version: 111, name: "drop_google_antigravity", sql: dropGoogleAntigravitySchema },
];
const SCHEMA_VERSION = MIGRATIONS[MIGRATIONS.length - 1].version;
+2 -7
View File
@@ -1,7 +1,6 @@
import { app } from "electron";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import type { DatabaseSync } from "node:sqlite";
import { DatabaseConnection } from "./database/connection";
import { appPageUrl, createMainWindow } from "./app/create-window";
import { registerIpcHandlers } from "./app/ipc-handlers";
@@ -13,6 +12,7 @@ import { recoverInterruptedWork } from "./app/startup-recovery";
import { startTaskQueueWorker } from "./app/task-queue-worker";
import { confirmDiscardOnClose } from "./app/unsaved-guard";
import { stopAllRunsAndWait } from "./services/run-control";
import { appLanguage } from "./services/work-language";
const QUIT_GRACE_MS = 10_000;
@@ -28,7 +28,7 @@ if (!app.requestSingleInstanceLock()) {
// strings, date formatting) is only settable pre-ready, and it follows the
// stored language preference instead of the OS locale.
const connection = new DatabaseConnection(join(profileDir, "agentcompany.db"));
const language = storedLanguage(connection.db);
const language = appLanguage(connection.db);
app.commandLine.appendSwitch("lang", language === "zh" ? "zh-CN" : "en-US");
app.whenReady().then(() => {
@@ -98,11 +98,6 @@ if (!app.requestSingleInstanceLock()) {
});
}
function storedLanguage(db: DatabaseSync): string {
const row = db.prepare("select language from app_state where id = 1").get() as { language: string } | undefined;
return row?.language ?? "en";
}
/**
* The bundled skill catalogue: the repo folder during development, the
* extraResources copy in a packaged build, or an explicit override for
+5 -1
View File
@@ -18,6 +18,7 @@ import { sendMessageTool } from "./agent-send-message";
import { withSavepoint } from "../database/connection";
import { optionalEnum, optionalString, optionalStringArray, optionalText, requireString } from "./agent-tool-args";
import { CEO_FIRST_HIRES } from "./org-building";
import { appLanguage } from "./work-language";
import type { JsonRecord } from "./provider-http";
import type { ToolCall, ToolDefinition } from "./provider-tool-turn";
@@ -435,8 +436,11 @@ function postAssignmentMessage(
{ type: "agent", id: ctx.agent.id },
{ type: "agent", id: input.assignee.id },
);
const mention = `@${canonicalMentionHandle(input.assignee.name)}`;
const body = [
`@${canonicalMentionHandle(input.assignee.name)} take task_id=${input.taskId}: ${input.title}.`,
appLanguage(deps.db) === "zh"
? `${mention} 请接手 task_id=${input.taskId}:${input.title}。`
: `${mention} take task_id=${input.taskId}: ${input.title}.`,
input.description,
].join(" ");
const messageId = deps.chat.sendMessage({
+1 -1
View File
@@ -10,7 +10,7 @@ export function setAutonomousPaused(db: DatabaseSync, paused: boolean): void {
}
/** The app-wide theme and language, kept for every company. */
export function updateUiPreferences(db: DatabaseSync, input: { theme?: "system" | "light" | "dark"; language?: "en" | "zh" }): void {
export function updateUiPreferences(db: DatabaseSync, input: { theme?: "system" | "light" | "dark" | "clock"; language?: "en" | "zh" }): void {
const current = db.prepare("select theme, language from app_state where id = 1")
.get() as { theme: string; language: string } | undefined;
const theme = input.theme ?? current?.theme ?? "system";
+18 -14
View File
@@ -30,16 +30,18 @@ export function loadChatWakeContext(db: DatabaseSync, orgId: string, agentId: st
const thread = db.prepare("select space_id from chat_threads where id = ? and org_id = ?")
.get(scope.sourceThreadId, orgId) as { space_id: string } | undefined;
if (!thread) throw new Error(`Chat wake thread ${scope.sourceThreadId} no longer exists.`);
const lastReplyAt = (db.prepare(`
select coalesce(max(created_at), '') as at from chat_messages
const lastReply = db.prepare(`
select created_at as at, rowid as seq from chat_messages
where thread_id = ? and org_id = ? and sender_type = 'agent' and sender_id = ? and deleted_at is null
`).get(scope.sourceThreadId, orgId, agentId) as { at: string }).at;
const isFresh = `not (m.sender_type = 'agent' and m.sender_id = ?) and (m.created_at > ? or coalesce(m.edited_at, '') > ?)`;
order by created_at desc, rowid desc limit 1
`).get(scope.sourceThreadId, orgId, agentId) as { at: string; seq: number } | undefined;
const at = lastReply?.at ?? "";
const isFresh = `not (m.sender_type = 'agent' and m.sender_id = ?) and ((m.created_at, m.rowid) > (?, ?) or coalesce(m.edited_at, '') >= ?)`;
const inThread = "m.thread_id = ? and m.org_id = ? and m.deleted_at is null";
const args = [scope.sourceThreadId, orgId, agentId, lastReplyAt, lastReplyAt];
const fresh = db.prepare(`${MESSAGE_SELECT} where ${inThread} and ${isFresh} order by m.created_at asc`)
const args = [scope.sourceThreadId, orgId, agentId, at, lastReply?.seq ?? 0, at];
const fresh = db.prepare(`${MESSAGE_SELECT} where ${inThread} and ${isFresh} order by m.created_at asc, m.rowid asc`)
.all(...args) as unknown as ThreadMessageRow[];
const history = (db.prepare(`${MESSAGE_SELECT} where ${inThread} and not (${isFresh}) order by m.created_at desc limit ?`)
const history = (db.prepare(`${MESSAGE_SELECT} where ${inThread} and not (${isFresh}) order by m.created_at desc, m.rowid desc limit ?`)
.all(...args, HISTORY_LIMIT) as unknown as ThreadMessageRow[]).reverse();
const historyTotal = (db.prepare(`select count(*) as n from chat_messages m where ${inThread} and not (${isFresh})`)
.get(...args) as { n: number }).n;
@@ -98,24 +100,26 @@ function utcMinute(iso: string): string {
return `${iso.slice(0, 10)} ${iso.slice(11, 16)} UTC`;
}
/** Polls the threads this run is part of for messages from others. */
/** Polls the threads this run is part of for messages from others that it has not seen; ids, not timestamps, mark what was seen. */
export function createRunMessagePoller(
db: DatabaseSync,
input: { orgId: string; agentId: string; sourceThreadId: string | null; runStartedAt: string; onInjected: (entries: ReadEntry[]) => void },
): () => string | null {
let watermark = input.runStartedAt;
const since = db.prepare("select id from chat_messages where org_id = ? and created_at >= ?");
const seen = new Set((since.all(input.orgId, input.runStartedAt) as Array<{ id: string }>).map((row) => row.id));
return () => {
const rows = db.prepare(`${MESSAGE_SELECT}
where m.org_id = ? and m.created_at > ? and m.deleted_at is null
const rows = (db.prepare(`${MESSAGE_SELECT}
where m.org_id = ? and m.created_at >= ? and m.deleted_at is null
and not (m.sender_type = 'agent' and m.sender_id = ?)
and (m.thread_id = ? or m.thread_id in (
select own.thread_id from chat_messages own
where own.org_id = ? and own.sender_type = 'agent' and own.sender_id = ? and own.created_at >= ?
))
order by m.created_at asc
`).all(input.orgId, watermark, input.agentId, input.sourceThreadId, input.orgId, input.agentId, input.runStartedAt) as unknown as ThreadMessageRow[];
order by m.created_at asc, m.rowid asc
`).all(input.orgId, input.runStartedAt, input.agentId, input.sourceThreadId, input.orgId, input.agentId, input.runStartedAt) as unknown as ThreadMessageRow[])
.filter((row) => !seen.has(row.id));
for (const row of rows) seen.add(row.id);
if (rows.length === 0) return null;
watermark = rows[rows.length - 1].created_at;
input.onInjected(rows.map(readEntry));
console.info(`[run-inbox] agent ${input.agentId}: ${rows.length} new message(s) injected mid-run`);
return ["Messages that arrived while you were working (they may change what you should do):", ...rows.map((m) => formatMessage(db, m))].join("\n");
@@ -1,154 +0,0 @@
/**
* Google Antigravity (Gemini 3 / Claude / GPT-OSS via Google Cloud) —
* authorization-code + PKCE flow with project discovery.
*
* Ported from the reference implementation in @mariozechner/pi-ai.
*/
import { startOAuthCallbackServer } from "./oauth-callback-server";
import { generatePkce } from "./pkce";
import type { OAuthCredentials, OAuthFlow, OAuthLoginCallbacks } from "./oauth-types";
import { httpFailure } from "../provider-http";
import { oauthFetch } from "./oauth-fetch";
const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com";
const CALLBACK_PORT = 51121;
const CALLBACK_PATH = "/oauth-callback";
const REDIRECT_URI = `http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`;
const SCOPES = [
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile",
"https://www.googleapis.com/auth/cclog",
"https://www.googleapis.com/auth/experimentsandconfigs",
];
const AUTH_URL = "https://accounts.google.com/o/oauth2/v2/auth";
const TOKEN_URL = "https://oauth2.googleapis.com/token";
const CODE_ASSIST_ENDPOINTS = ["https://cloudcode-pa.googleapis.com", "https://daily-cloudcode-pa.sandbox.googleapis.com"];
export function requireAntigravityClientSecret(secret: string | null | undefined): string {
if (!secret) throw new Error("Google Antigravity sign-in needs its OAuth client secret. Add it in Settings > Integrations.");
return secret;
}
function buildAuthorizeUrl(challenge: string, state: string): string {
const params = new URLSearchParams({
client_id: CLIENT_ID,
response_type: "code",
redirect_uri: REDIRECT_URI,
scope: SCOPES.join(" "),
code_challenge: challenge,
code_challenge_method: "S256",
state,
access_type: "offline",
prompt: "consent",
});
return `${AUTH_URL}?${params.toString()}`;
}
async function exchangeCode(code: string, verifier: string, clientSecret: string, cancel?: AbortSignal): Promise<{ access: string; refresh: string; expires: number }> {
const { response, text } = await oauthFetch(TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: CLIENT_ID,
client_secret: clientSecret,
code,
grant_type: "authorization_code",
redirect_uri: REDIRECT_URI,
code_verifier: verifier,
}),
}, cancel);
if (!response.ok) throw new Error(`Token exchange failed: ${response.status} ${text}`);
const json = JSON.parse(text) as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown };
if (typeof json.access_token !== "string" || typeof json.refresh_token !== "string" || typeof json.expires_in !== "number") {
throw new Error("Token response was missing required fields.");
}
return { access: json.access_token, refresh: json.refresh_token, expires: Date.now() + json.expires_in * 1000 - 5 * 60 * 1000 };
}
/** Extract a Code Assist project id from a loadCodeAssist response (unit-tested). */
export function readProjectId(payload: Record<string, unknown>): string | null {
const project = payload.cloudaicompanionProject;
if (typeof project === "string" && project) return project;
if (project && typeof project === "object" && "id" in project) {
const id = (project as { id?: unknown }).id;
if (typeof id === "string" && id) return id;
}
return null;
}
async function discoverProject(accessToken: string, cancel?: AbortSignal): Promise<string> {
const headers = {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
"User-Agent": "google-api-nodejs-client/9.15.1",
};
for (const endpoint of CODE_ASSIST_ENDPOINTS) {
try {
const { response, text } = await oauthFetch(`${endpoint}/v1internal:loadCodeAssist`, {
method: "POST",
headers,
body: JSON.stringify({ metadata: { ideType: "IDE_UNSPECIFIED", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" } }),
}, cancel);
if (response.ok) {
const projectId = readProjectId(JSON.parse(text) as Record<string, unknown>);
if (projectId) return projectId;
}
} catch (error) {
// A cancelled sign-in ends here; any other failure moves on to the next endpoint.
if (cancel?.aborted) throw error;
}
}
throw new Error("Antigravity project discovery failed.");
}
/** Revokes the sign-in at Google; revoking the refresh token also ends its access tokens. */
export async function revokeAntigravity(refreshToken: string): Promise<void> {
const { response, text } = await oauthFetch("https://oauth2.googleapis.com/revoke", {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({ token: refreshToken }),
});
if (!response.ok) throw httpFailure(`Google revocation failed: ${response.status} ${text}`, response, text);
}
/** Refresh an expired Antigravity access token, retaining the project id. */
export async function refreshAntigravity(refreshToken: string, projectId: string, clientSecret: string): Promise<OAuthCredentials> {
const { response, text } = await oauthFetch(TOKEN_URL, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
client_id: CLIENT_ID,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: "refresh_token",
}),
});
if (!response.ok) throw httpFailure(`Antigravity token refresh failed: ${response.status} ${text}`, response, text);
const json = JSON.parse(text) as { access_token?: unknown; refresh_token?: unknown; expires_in?: unknown };
if (typeof json.access_token !== "string" || typeof json.expires_in !== "number") {
throw new Error("Antigravity token refresh response was missing required fields.");
}
const refresh = typeof json.refresh_token === "string" && json.refresh_token ? json.refresh_token : refreshToken;
return { access: json.access_token, refresh, expires: Date.now() + json.expires_in * 1000 - 5 * 60 * 1000, projectId };
}
export const antigravityFlow: OAuthFlow = {
providerKey: "google-antigravity",
async login(callbacks: OAuthLoginCallbacks): Promise<OAuthCredentials> {
const clientSecret = requireAntigravityClientSecret(callbacks.clientSecret);
const { verifier, challenge } = generatePkce();
const server = await startOAuthCallbackServer({ port: CALLBACK_PORT, path: CALLBACK_PATH, signal: callbacks.signal });
try {
callbacks.onAuth({ url: buildAuthorizeUrl(challenge, verifier), userCode: null });
const result = await server.waitForCode();
if (result.state !== verifier) throw new Error("OAuth state mismatch.");
const tokens = await exchangeCode(result.code, verifier, clientSecret, callbacks.signal);
callbacks.onProgress?.("Resolving project");
const projectId = await discoverProject(tokens.access, callbacks.signal);
return { access: tokens.access, refresh: tokens.refresh, expires: tokens.expires, projectId };
} finally {
server.close();
}
},
};
-2
View File
@@ -1,6 +1,5 @@
import { githubCopilotFlow } from "./github-copilot-flow";
import { openaiCodexFlow } from "./openai-codex-flow";
import { antigravityFlow } from "./google-antigravity-flow";
import { anthropicClaudeFlow } from "./anthropic-claude-flow";
import { kimiCodeFlow } from "./kimi-code-flow";
import type { OAuthFlow } from "./oauth-types";
@@ -9,7 +8,6 @@ import type { OAuthFlow } from "./oauth-types";
const OAUTH_FLOWS: Record<string, OAuthFlow> = {
"github-copilot": githubCopilotFlow,
"gpt-account": openaiCodexFlow,
"google-antigravity": antigravityFlow,
"claude-pro": anthropicClaudeFlow,
"kimi-code": kimiCodeFlow,
};
-2
View File
@@ -21,8 +21,6 @@ export interface OAuthLoginCallbacks {
signal?: AbortSignal;
/** GitHub Enterprise domain for Copilot; null/empty means github.com. */
enterpriseDomain?: string | null;
/** Client secret for flows that need one. */
clientSecret?: string | null;
}
export interface OAuthFlow {
+1 -3
View File
@@ -6,14 +6,12 @@ export interface StoredOAuth {
refresh: string;
expires: number;
accountId?: string;
projectId?: string;
enterpriseUrl?: string | null;
}
/** Extras a provider's turns cannot run without, with the words used when one is missing. */
const REQUIRED_EXTRAS: Record<string, { field: "accountId" | "projectId"; label: string }> = {
const REQUIRED_EXTRAS: Record<string, { field: "accountId"; label: string }> = {
"gpt-account": { field: "accountId", label: "ChatGPT account id" },
"google-antigravity": { field: "projectId", label: "Google Cloud project id" },
};
/** The one check of a stored sign-in, used both when it is saved and when a run uses it. */
+1 -1
View File
@@ -67,7 +67,7 @@ export class OrganizationService {
setAutonomousPaused(this.db, paused);
}
updateUiPreferences(input: { theme?: "system" | "light" | "dark"; language?: "en" | "zh" }): void {
updateUiPreferences(input: { theme?: "system" | "light" | "dark" | "clock"; language?: "en" | "zh" }): void {
updateUiPreferences(this.db, input);
}
@@ -3,7 +3,7 @@ import type { ProviderModelEntry } from "../../shared/provider-models";
import type { ProviderObservedRateLimitState } from "../../shared/provider-runtime-domain";
import type { ProviderAuthProfile } from "./provider-auth-profiles";
import type { ProviderBackgroundCreateResult, ProviderBackgroundRetrieveResult } from "./provider-background";
import type { ProviderAuthorizeHandler, ProviderRefreshHandler, ProviderRevokeHandler } from "./provider-auth-lifecycle";
import type { ProviderAuthorizeHandler, ProviderRefreshHandler } from "./provider-auth-lifecycle";
import type { ProviderCancelResult, ProviderStreamResult } from "./provider-streaming";
export interface ProviderExecutionInput {
@@ -50,7 +50,6 @@ export interface ProviderAdapter {
authType: ProviderAuthType;
authorize: ProviderAuthorizeHandler;
refresh: ProviderRefreshHandler;
revoke: ProviderRevokeHandler;
parseAuthProfile(secret: string): ProviderAuthProfile;
listModels(ctx: ProviderContext): Promise<ProviderModelEntry[]>;
getRateLimitState(ctx: ProviderContext): Promise<ProviderRateLimitState | null>;
+1 -23
View File
@@ -9,16 +9,10 @@ import {
parseOpenAiCompatProfile,
parseVertexProfile,
requireAccessTokenProfile,
requireAccountTokenProfile,
requireAnthropicCompatProfile,
requireApiKeyProfile,
requireAzureProfile,
requireBedrockProfile,
requireOpenAiCompatProfile,
requireVertexProfile,
} from "./provider-auth-profiles";
import { backgroundUnsupported, retrieveUnsupported } from "./provider-background";
import { authorizeWithParser, refreshUnsupported, revokeLocalProfile } from "./provider-auth-lifecycle";
import { authorizeWithParser, refreshUnsupported } from "./provider-auth-lifecycle";
import { getJson, postEventStream, postJson, WHOLE_RESPONSE_WAIT, type JsonRecord } from "./provider-http";
import { OUTPUT_RESERVE_TOKENS } from "./context-budget";
import { chatMaxTokensField } from "./provider-tool-turns/chat-format";
@@ -26,8 +20,6 @@ import { fetchAnthropicModels, fetchOpenAiModels } from "./provider-models-fetch
import { KIMI_CODE_BASE_URL } from "./oauth/kimi-code-flow";
import { FINISHED_STOP_REASONS, incompleteTurn, requireFinished } from "./provider-tool-turn";
import { incompleteReason } from "./provider-tool-turns/responses-format";
import { revokeAntigravity } from "./oauth/google-antigravity-flow";
import { parseStoredOAuth } from "./oauth/stored-oauth";
const ANTHROPIC_VERSION = "2023-06-01";
const CLAUDE_PRO_BETA = "claude-code-20250219,oauth-2025-04-20,fine-grained-tool-streaming-2025-05-14";
@@ -55,7 +47,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.API_KEY,
authorize: authorizeWithParser(parseApiKey),
refresh: refreshUnsupported("OpenAI API key"),
revoke: revokeLocalProfile((profile) => { requireApiKeyProfile(profile, "OpenAI"); }),
parseAuthProfile: parseApiKey,
listModels: (ctx) => fetchOpenAiModels("https://api.openai.com/v1/models", {
authorization: `Bearer ${requireApiKeyProfile(ctx.authProfile, "OpenAI").apiKey}`,
@@ -138,7 +129,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.API_KEY,
authorize: authorizeWithParser(parseApiKey),
refresh: refreshUnsupported("Anthropic API key"),
revoke: revokeLocalProfile((profile) => { requireApiKeyProfile(profile, "Anthropic"); }),
parseAuthProfile: parseApiKey,
listModels: (ctx) => fetchAnthropicModels("https://api.anthropic.com/v1/models", {
"x-api-key": requireApiKeyProfile(ctx.authProfile, "Anthropic").apiKey,
@@ -224,10 +214,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
healthUrl: "https://api.moonshot.cn/v1/models",
}),
"github-copilot": browserTokenAdapter("github-copilot", PROVIDER_AUTH_TYPE.OAUTH_PKCE),
"google-antigravity": {
...browserTokenAdapter("google-antigravity", PROVIDER_AUTH_TYPE.OAUTH_PKCE),
revoke: async (input) => revokeAntigravity(parseStoredOAuth("google-antigravity", input.secret).refresh),
},
"gpt-account": browserTokenAdapter("gpt-account", PROVIDER_AUTH_TYPE.ACCOUNT_SUBSCRIPTION),
"claude-pro": {
...browserTokenAdapter("claude-pro", PROVIDER_AUTH_TYPE.OAUTH_PKCE),
@@ -248,7 +234,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.CLOUD,
authorize: authorizeWithParser(parseAzureProfile),
refresh: refreshUnsupported("Azure OpenAI cloud credential"),
revoke: revokeLocalProfile((profile) => { requireAzureProfile(profile); }),
parseAuthProfile: parseAzureProfile,
listModels: () => listStaticModels("azure-openai"),
getRateLimitState: providerRateLimitUnknown,
@@ -262,7 +247,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.CLOUD,
authorize: authorizeWithParser(parseBedrockProfile),
refresh: refreshUnsupported("AWS Bedrock cloud credential"),
revoke: revokeLocalProfile((profile) => { requireBedrockProfile(profile); }),
parseAuthProfile: parseBedrockProfile,
listModels: () => listStaticModels("aws-bedrock"),
getRateLimitState: providerRateLimitUnknown,
@@ -276,7 +260,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.CLOUD,
authorize: authorizeWithParser(parseVertexProfile),
refresh: refreshUnsupported("Vertex AI cloud credential"),
revoke: revokeLocalProfile((profile) => { requireVertexProfile(profile); }),
parseAuthProfile: parseVertexProfile,
listModels: () => listStaticModels("vertex-ai"),
getRateLimitState: providerRateLimitUnknown,
@@ -290,7 +273,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.CLOUD,
authorize: authorizeWithParser(parseOpenAiCompatProfile),
refresh: refreshUnsupported("Custom OpenAI-compatible endpoint"),
revoke: revokeLocalProfile((profile) => { requireOpenAiCompatProfile(profile); }),
parseAuthProfile: parseOpenAiCompatProfile,
listModels: () => listStaticModels("custom-openai"),
getRateLimitState: providerRateLimitUnknown,
@@ -304,7 +286,6 @@ export const providerAdapters: ProviderAdapterRegistry = {
authType: PROVIDER_AUTH_TYPE.CLOUD,
authorize: authorizeWithParser(parseAnthropicCompatProfile),
refresh: refreshUnsupported("Custom Anthropic-compatible endpoint"),
revoke: revokeLocalProfile((profile) => { requireAnthropicCompatProfile(profile); }),
parseAuthProfile: parseAnthropicCompatProfile,
listModels: () => listStaticModels("custom-anthropic"),
getRateLimitState: providerRateLimitUnknown,
@@ -363,7 +344,6 @@ function openAiCompatibleAdapter({
authType: PROVIDER_AUTH_TYPE.API_KEY,
authorize: authorizeWithParser(parseApiKey),
refresh: refreshUnsupported(`${label} API key`),
revoke: revokeLocalProfile((profile) => { requireApiKeyProfile(profile, label); }),
parseAuthProfile: parseApiKey,
listModels: (ctx) => fetchOpenAiModels(healthUrl, {
authorization: `Bearer ${requireApiKeyProfile(ctx.authProfile, label).apiKey}`,
@@ -413,13 +393,11 @@ function responseMessages(instructions: string | null, prompt: string): Array<{
function browserTokenAdapter(providerKey: string, authType: ProviderAuthType): ProviderAdapter {
const parseAuthProfile = oauthProfileParser(providerKey, authType === PROVIDER_AUTH_TYPE.ACCOUNT_SUBSCRIPTION ? "account_token" : "access_token");
const assertProfile = authType === PROVIDER_AUTH_TYPE.ACCOUNT_SUBSCRIPTION ? requireAccountTokenProfile : requireAccessTokenProfile;
return {
providerKey,
authType,
authorize: authorizeWithParser(parseAuthProfile),
refresh: refreshUnsupported(`${providerKey} token`),
revoke: revokeLocalProfile((profile) => { assertProfile(profile); }),
parseAuthProfile,
listModels: () => listStaticModels(providerKey),
getRateLimitState: providerRateLimitUnknown,
@@ -18,15 +18,8 @@ export interface ProviderRefreshResult {
refreshedAt: string;
}
export interface ProviderRevokeInput {
authProfile: ProviderAuthProfile;
/** The stored credential, for providers that revoke with the refresh token. */
secret: string;
}
export type ProviderAuthorizeHandler = (input: ProviderAuthorizeInput) => Promise<ProviderAuthorizeResult>;
export type ProviderRefreshHandler = (input: ProviderRefreshInput) => Promise<ProviderRefreshResult>;
export type ProviderRevokeHandler = (input: ProviderRevokeInput) => Promise<void>;
export function authorizeWithParser(parseAuthProfile: (secret: string) => ProviderAuthProfile): ProviderAuthorizeHandler {
return async (input) => ({ authProfile: parseAuthProfile(input.secret) });
@@ -37,9 +30,3 @@ export function refreshUnsupported(label: string): ProviderRefreshHandler {
throw new Error(`${label} does not support token refresh.`);
};
}
export function revokeLocalProfile(assertProfile: (profile: ProviderAuthProfile) => void): ProviderRevokeHandler {
return async (input) => {
assertProfile(input.authProfile);
};
}
@@ -82,11 +82,6 @@ export function requireAccessTokenProfile(profile: ProviderAuthProfile): Extract
return profile;
}
export function requireAccountTokenProfile(profile: ProviderAuthProfile): Extract<ProviderAuthProfile, { type: "account_token" }> {
if (profile.type !== "account_token") throw new Error("Account token profile is required.");
return profile;
}
export function requireAzureProfile(profile: ProviderAuthProfile): Extract<ProviderAuthProfile, { type: "azure_openai" }> {
if (profile.type !== "azure_openai") throw new Error("Azure OpenAI profile is required.");
return profile;
@@ -1,5 +1,4 @@
import { getOAuthFlow } from "./oauth/oauth-flows";
import type { IntegrationKeyStore } from "./integration-key-store";
export interface ProviderOAuthHooks {
onAuth: (info: { url: string; userCode: string | null }) => void;
@@ -15,8 +14,6 @@ export interface ProviderOAuthHooks {
export class ProviderOAuthService {
private readonly controllers = new Map<string, AbortController>();
constructor(private readonly keys: IntegrationKeyStore) {}
async run(input: { providerKey: string; enterpriseDomain?: string | null }, hooks: ProviderOAuthHooks): Promise<string> {
const flow = getOAuthFlow(input.providerKey);
if (this.controllers.has(input.providerKey)) {
@@ -30,7 +27,6 @@ export class ProviderOAuthService {
onProgress: hooks.onProgress,
signal: controller.signal,
enterpriseDomain: input.enterpriseDomain ?? null,
clientSecret: input.providerKey === "google-antigravity" ? this.keys.read("google_antigravity_client_secret") : null,
});
return JSON.stringify(credentials);
} finally {
@@ -1,4 +1,3 @@
import type { IntegrationKeyStore } from "./integration-key-store";
import type { DatabaseSync } from "node:sqlite";
import type { CancelProviderResponseInput, CreateProviderResponseInput, StreamProviderResponseInput } from "../../shared/commands";
import { FEATURE_FLAG_KEY, PROVIDER_AUTH_TYPE, PROVIDER_DATA_POLICY, PROVIDER_EXECUTION_MODE, PROVIDER_REQUEST_STATE, type ProviderExecutionMode } from "../../shared/domain";
@@ -41,7 +40,6 @@ export interface ProviderResponseRunnerDeps {
adapters: ProviderAdapterRegistry;
audit: AuditService;
authBroker: AuthBrokerService;
integrationKeys: IntegrationKeyStore;
operations: OperationsService;
rateLimitRegistry: ProviderRateLimitRegistry;
responseObserver: ProviderResponseObserver;
@@ -122,7 +120,7 @@ export class ProviderResponseRunner {
const provider = loadConfiguredProvider(this.deps.db, input.orgId, input.providerId);
const workspaceId = this.normalizeWorkspaceId(input.orgId, input.workspaceId ?? null);
if (!supportsToolTurn(provider.provider_key)) {
throw new Error("Agent execution is not available for this provider; assign the agent an OpenAI, Anthropic, xAI, Groq, Mistral, Cerebras, OpenRouter, GPT account, GitHub Copilot, Google Antigravity, or Claude Pro provider.");
throw new Error("Agent execution is not available for this provider; assign the agent an OpenAI, Anthropic, xAI, Groq, Mistral, Cerebras, OpenRouter, GPT account, GitHub Copilot, or Claude Pro provider.");
}
// A call made for a run works for its agent: the agent's model, its budget, its attribution.
const taskRunId = currentRunId();
@@ -198,7 +196,7 @@ export class ProviderResponseRunner {
});
const startedAt = Date.now();
try {
const credential = await resolveTurnCredential({ authBroker: this.deps.authBroker, integrationKeys: this.deps.integrationKeys, orgId, provider: owner });
const credential = await resolveTurnCredential({ authBroker: this.deps.authBroker, orgId, provider: owner });
const result = await turn({ credential, model, instructions: request.instructions, messages: request.messages, tools: request.tools });
recordObservedRateLimit(this.deps.rateLimitRegistry, orgId, owner, model, result.rateLimitState ?? null);
// Tool calls are output the model wrote, as much as its text.
+17 -36
View File
@@ -68,7 +68,6 @@ export class ProviderService {
adapters,
audit: this.audit,
authBroker: this.authBroker,
integrationKeys: this.integrationKeys,
operations: this.operations,
rateLimitRegistry: this.rateLimitRegistry,
responseObserver: this.responseObserver,
@@ -136,40 +135,27 @@ export class ProviderService {
return providerEndpoint(this.db, this.authBroker, orgId, providerId);
}
/** Revokes at the provider where it can, then always disconnects and erases the credential here; a remote failure is reported, not hidden. */
async revokeCredential(input: RevokeProviderCredentialInput): Promise<void> {
/** Disconnects the provider and erases its credential on this computer. */
revokeCredential(input: RevokeProviderCredentialInput): void {
const provider = this.db.prepare(`
select id, provider_key, auth_type, label, credential_id
select provider_key, label, credential_id
from providers
where id = ? and org_id = ?
`).get(input.providerId, input.orgId) as { id: string; provider_key: string; auth_type: ProviderAuthType; label: string; credential_id: string | null } | undefined;
`).get(input.providerId, input.orgId) as { provider_key: string; label: string; credential_id: string | null } | undefined;
if (!provider) throw new Error("Provider was not found.");
if (!provider.credential_id) throw new Error(`${provider.label} is not connected.`);
const credentialId = provider.credential_id;
const entry = requireCatalogEntry(provider.provider_key);
let remoteError: string | null = null;
if (entry.revokesRemotely) {
try {
const adapter = requireAdapter(this.adapters, provider.provider_key, provider.auth_type);
const secret = this.authBroker.loadProviderSecret({ orgId: input.orgId, providerId: provider.id, providerKey: provider.provider_key, credentialId });
await adapter.revoke({ authProfile: adapter.parseAuthProfile(secret), secret });
} catch (error) {
remoteError = error instanceof Error ? error.message : String(error);
}
if (!this.authBroker.revokeProviderProfile({ orgId: input.orgId, providerId: input.providerId, providerKey: provider.provider_key, credentialId })) {
throw new Error(`${provider.label} has no active sign-in to disconnect.`);
}
// The credential read at the start is the one disconnected; a connection made while Google answered stays.
const disconnected = this.authBroker.revokeProviderProfile({ orgId: input.orgId, providerId: input.providerId, providerKey: provider.provider_key, credentialId });
if (disconnected) {
this.db.prepare(`
update providers
set credential_id = null, enabled = 0, auth_state = ?, health_state = ?, last_error = null, last_checked_at = null
where id = ? and org_id = ? and credential_id = ?
`).run(AUTH_STATE_REVOKED, HEALTH_STATE_UNCHECKED, input.providerId, input.orgId, credentialId);
// Sessions mid-turn on this provider stop now instead of finishing on a revoked account.
const running = this.db.prepare("select id from task_runs where provider_id = ? and state = 'running'").all(input.providerId) as Array<{ id: string }>;
for (const run of running) stopRun(run.id, `${provider.label} was disconnected.`);
}
const remote = !entry.revokesRemotely ? "not_supported" : remoteError ? "failed" : "revoked";
this.db.prepare(`
update providers
set credential_id = null, enabled = 0, auth_state = ?, health_state = ?, last_error = null, last_checked_at = null
where id = ? and org_id = ? and credential_id = ?
`).run(AUTH_STATE_REVOKED, HEALTH_STATE_UNCHECKED, input.providerId, input.orgId, credentialId);
// Sessions mid-turn on this provider stop now instead of finishing on a revoked account.
const running = this.db.prepare("select id from task_runs where provider_id = ? and state = 'running'").all(input.providerId) as Array<{ id: string }>;
for (const run of running) stopRun(run.id, `${provider.label} was disconnected.`);
this.audit.record({
orgId: input.orgId,
entityType: "provider",
@@ -177,14 +163,9 @@ export class ProviderService {
actorType: "system",
actorId: null,
action: "credential_revoked",
payload: { providerKey: provider.provider_key, remote, remoteError, replacedMeanwhile: !disconnected },
payload: { providerKey: provider.provider_key },
});
console.info(`[providers] ${provider.provider_key} disconnected; remote revocation ${remote}`);
const problems = [
...(disconnected ? [] : [`${provider.label} was reconnected while it was being disconnected; the old sign-in is erased and the new connection stays.`]),
...(remoteError ? [`${disconnected ? "Disconnected on this computer, but " : "The old sign-in was not confirmed revoked: "}${provider.label} did not confirm revoking the sign-in (${remoteError}); revoke it in your account.`] : []),
];
if (problems.length > 0) throw new Error(problems.join(" "));
console.info(`[providers] ${provider.provider_key} disconnected`);
}
/**
@@ -204,7 +185,7 @@ export class ProviderService {
const provider = loadConfiguredProvider(this.db, input.orgId, input.providerId);
const adapter = requireAdapter(this.adapters, provider.provider_key, provider.auth_type);
// Renew an expired sign-in the way a run does, so the list and the runs agree on whether the account works.
await resolveTurnCredential({ authBroker: this.authBroker, integrationKeys: this.integrationKeys, orgId: input.orgId, provider });
await resolveTurnCredential({ authBroker: this.authBroker, orgId: input.orgId, provider });
const credential = loadCredential(this.authBroker, input.orgId, provider);
const authProfile = adapter.parseAuthProfile(credential.secret);
return adapter.listModels({ authProfile, model: provider.model });
@@ -3,7 +3,7 @@
* pass the key straight through; OAuth/subscription providers parse the stored
* credential JSON, refresh the access token when it has expired (persisting the
* rotated token), and hand the turn a usable access token plus the extras
* (accountId / projectId / enterpriseUrl) its backend needs.
* (accountId / enterpriseUrl) its backend needs.
*/
import { PROVIDER_AUTH_TYPE } from "../../../shared/domain";
import type { AuthBrokerService } from "../auth-broker-service";
@@ -26,21 +26,17 @@ import type { TurnCredential } from "../provider-tool-turn";
import type { OAuthCredentials } from "../oauth/oauth-types";
import { refreshCodex } from "../oauth/openai-codex-flow";
import { refreshClaudePro } from "../oauth/anthropic-claude-flow";
import { refreshAntigravity, requireAntigravityClientSecret } from "../oauth/google-antigravity-flow";
import type { IntegrationKeyStore } from "../integration-key-store";
import { refreshGitHubCopilotToken } from "../oauth/github-copilot-flow";
import { refreshKimiCode } from "../oauth/kimi-code-flow";
import { parseStoredOAuth, type StoredOAuth } from "../oauth/stored-oauth";
import { untilStopped } from "../run-control";
function refreshOAuth(providerKey: string, creds: StoredOAuth, keys: IntegrationKeyStore): Promise<OAuthCredentials> {
function refreshOAuth(providerKey: string, creds: StoredOAuth): Promise<OAuthCredentials> {
switch (providerKey) {
case "gpt-account":
return refreshCodex(creds.refresh);
case "claude-pro":
return refreshClaudePro(creds.refresh);
case "google-antigravity":
return refreshAntigravity(creds.refresh, requireProjectId(creds), requireAntigravityClientSecret(keys.read("google_antigravity_client_secret")));
case "github-copilot":
return refreshGitHubCopilotToken(creds.refresh, creds.enterpriseUrl ?? undefined);
case "kimi-code":
@@ -82,14 +78,12 @@ function toTurnCredential(creds: StoredOAuth | OAuthCredentials): TurnCredential
return {
accessToken: creds.access,
accountId: typeof creds.accountId === "string" ? creds.accountId : undefined,
projectId: typeof creds.projectId === "string" ? creds.projectId : undefined,
enterpriseUrl: typeof enterpriseUrl === "string" ? enterpriseUrl : enterpriseUrl === null ? null : undefined,
};
}
export async function resolveTurnCredential(deps: {
authBroker: AuthBrokerService;
integrationKeys: IntegrationKeyStore;
orgId: string;
provider: ProviderRow;
}): Promise<TurnCredential> {
@@ -109,13 +103,13 @@ export async function resolveTurnCredential(deps: {
/** Refreshes in flight, by stored credential: a rotating provider honours a refresh token once, so callers at once share one. */
const refreshing = new Map<string, Promise<OAuthCredentials>>();
function refreshOnce(deps: { authBroker: AuthBrokerService; integrationKeys: IntegrationKeyStore; orgId: string; provider: ProviderRow }, creds: StoredOAuth): Promise<OAuthCredentials> {
function refreshOnce(deps: { authBroker: AuthBrokerService; orgId: string; provider: ProviderRow }, creds: StoredOAuth): Promise<OAuthCredentials> {
const credentialId = deps.provider.credential_id;
if (!credentialId) throw new Error("Provider credential id is missing; reconnect the provider.");
const running = refreshing.get(credentialId);
if (running) return running;
console.info(`[credentials] refreshing the ${deps.provider.provider_key} sign-in`);
const refresh = refreshOAuth(deps.provider.provider_key, creds, deps.integrationKeys)
const refresh = refreshOAuth(deps.provider.provider_key, creds)
.then((refreshed) => {
deps.authBroker.updateProviderSecret({ orgId: deps.orgId, providerKey: deps.provider.provider_key, credentialId, secret: JSON.stringify(refreshed) });
return refreshed;
@@ -124,8 +118,3 @@ function refreshOnce(deps: { authBroker: AuthBrokerService; integrationKeys: Int
refreshing.set(credentialId, refresh);
return refresh;
}
function requireProjectId(creds: StoredOAuth): string {
if (!creds.projectId) throw new Error("The Google Antigravity sign-in is missing its Google Cloud project id; sign in again.");
return creds.projectId;
}
@@ -1,37 +1,21 @@
/**
* Google Cloud Code Assist (Gemini) encoding for the Antigravity backend.
* Ported from Pi's google-shared `convertMessages` / `convertTools` and the
* Antigravity request wrapper in google-gemini-cli.
*/
/** Gemini generateContent encoding for Vertex AI. */
import { OUTPUT_RESERVE_TOKENS } from "../context-budget";
import { isRecord, ProviderHttpError, readProviderErrorCode, type JsonRecord, type ProviderEventStreamMessage } from "../provider-http";
import { FINISHED_STOP_REASONS, replayIn, requireFinished, toolCallFromObject, type AgentTurnMessage, type AgentTurnResult, type AssistantReplay, type ToolCall, type ToolDefinition } from "../provider-tool-turn";
import { isRecord, type JsonRecord } from "../provider-http";
import { FINISHED_STOP_REASONS, replayIn, requireFinished, toolCallFromObject, type AgentTurnMessage, type AssistantReplay, type ToolCall, type ToolDefinition } from "../provider-tool-turn";
const ANTIGRAVITY_SYSTEM_INSTRUCTION =
"You are Antigravity, a powerful agentic AI coding assistant designed by the Google Deepmind team working on Advanced Agentic Coding." +
"You are pair programming with a USER to solve their coding task. The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question." +
"**Absolute paths only**" +
"**Proactiveness**";
function usesToolCallId(model: string): boolean {
return model.startsWith("claude-") || model.startsWith("gpt-oss-");
}
function geminiToolDefs(model: string, tools: ToolDefinition[]): unknown[] {
const useParameters = model.startsWith("claude-");
function geminiToolDefs(tools: ToolDefinition[]): unknown[] {
return [
{
functionDeclarations: tools.map((tool) => ({
name: tool.name,
description: tool.description,
...(useParameters ? { parameters: tool.parameters } : { parametersJsonSchema: tool.parameters }),
parametersJsonSchema: tool.parameters,
})),
},
];
}
function toGeminiContents(model: string, messages: AgentTurnMessage[]): JsonRecord[] {
const withId = usesToolCallId(model);
function toGeminiContents(messages: AgentTurnMessage[]): JsonRecord[] {
const contents: JsonRecord[] = [];
for (const message of messages) {
if (message.role === "user") {
@@ -45,12 +29,12 @@ function toGeminiContents(model: string, messages: AgentTurnMessage[]): JsonReco
const parts: unknown[] = [];
if (message.text) parts.push({ text: message.text });
for (const call of message.toolCalls) {
parts.push({ functionCall: { name: call.name, args: call.arguments, ...(withId ? { id: call.id } : {}) } });
parts.push({ functionCall: { name: call.name, args: call.arguments } });
}
if (parts.length > 0) contents.push({ role: "model", parts });
} else {
const responses: unknown[] = message.results.map((result) => ({
functionResponse: { name: result.toolName, response: { output: result.output }, ...(withId ? { id: result.toolCallId } : {}) },
functionResponse: { name: result.toolName, response: { output: result.output } },
}));
if (message.followUp) responses.push({ text: message.followUp });
const last = contents[contents.length - 1];
@@ -64,45 +48,16 @@ function toGeminiContents(model: string, messages: AgentTurnMessage[]): JsonReco
return contents;
}
/** The full Antigravity request envelope ({project, model, request, ...}). */
export function antigravityRequestBody(input: {
model: string;
projectId: string;
instructions: string | null;
messages: AgentTurnMessage[];
tools: ToolDefinition[];
requestId: string;
}): JsonRecord {
const request: JsonRecord = {
contents: toGeminiContents(input.model, input.messages),
generationConfig: { maxOutputTokens: OUTPUT_RESERVE_TOKENS },
systemInstruction: {
role: "user",
parts: [
{ text: ANTIGRAVITY_SYSTEM_INSTRUCTION },
{ text: `Please ignore following [ignore]${ANTIGRAVITY_SYSTEM_INSTRUCTION}[/ignore]` },
...(input.instructions ? [{ text: input.instructions }] : []),
],
},
};
if (input.tools.length > 0) {
request.tools = geminiToolDefs(input.model, input.tools);
request.toolConfig = { functionCallingConfig: { mode: "AUTO" } };
}
return { project: input.projectId, model: input.model, request, requestType: "agent", userAgent: "antigravity", requestId: input.requestId };
}
/** The Vertex AI generateContent body (Gemini, no Antigravity wrapper). */
/** The Vertex AI generateContent body. */
export function vertexRequestBody(input: {
model: string;
instructions: string | null;
messages: AgentTurnMessage[];
tools: ToolDefinition[];
}): JsonRecord {
const body: JsonRecord = { contents: toGeminiContents(input.model, input.messages), generationConfig: { maxOutputTokens: OUTPUT_RESERVE_TOKENS } };
const body: JsonRecord = { contents: toGeminiContents(input.messages), generationConfig: { maxOutputTokens: OUTPUT_RESERVE_TOKENS } };
if (input.instructions) body.systemInstruction = { parts: [{ text: input.instructions }] };
if (input.tools.length > 0) {
body.tools = geminiToolDefs(input.model, input.tools);
body.tools = geminiToolDefs(input.tools);
body.toolConfig = { functionCallingConfig: { mode: "AUTO" } };
}
return body;
@@ -135,40 +90,3 @@ export function parseGeminiResponse(data: JsonRecord): { text: string; toolCalls
const result = partsToResult(parts);
return { text: result.text.join("").trim(), toolCalls: result.toolCalls, replay: { format: "gemini", content: parts } };
}
export async function accumulateGeminiStream(messages: AsyncIterable<ProviderEventStreamMessage>): Promise<AgentTurnResult> {
const raw: string[] = [];
const textParts: string[] = [];
const toolCalls: ToolCall[] = [];
const replayParts: unknown[] = [];
let finishReason: unknown = null;
let counter = 0;
for await (const message of messages) {
raw.push(message.rawData);
if (isRecord(message.data.error)) {
const error = message.data.error;
throw new ProviderHttpError(typeof error.message === "string" ? error.message : "Antigravity stream failed.", null, typeof error.code === "number" ? error.code : null, false, readProviderErrorCode({ error }));
}
const response = isRecord(message.data.response) ? message.data.response : null;
if (!response) continue;
const candidates = Array.isArray(response.candidates) ? response.candidates : [];
if (isRecord(candidates[0]) && typeof candidates[0].finishReason === "string") finishReason = candidates[0].finishReason;
const content = candidates.length > 0 && isRecord(candidates[0]) && isRecord(candidates[0].content) ? candidates[0].content : null;
const parts = content && Array.isArray(content.parts) ? content.parts : [];
for (const part of parts) {
if (!isRecord(part)) continue;
replayParts.push(part);
if (typeof part.text === "string" && part.thought !== true) {
textParts.push(part.text);
} else if (isRecord(part.functionCall)) {
const fc = part.functionCall;
const name = typeof fc.name === "string" ? fc.name : "";
if (!name) continue;
const id = typeof fc.id === "string" && fc.id ? fc.id : `${name}_${(counter += 1)}`;
toolCalls.push(toolCallFromObject(id, name, fc.args));
}
}
}
requireFinished(finishReason, FINISHED_STOP_REASONS.gemini);
return { text: textParts.join("").trim(), toolCalls, rawResponseJson: JSON.stringify(raw), ...(replayParts.length > 0 ? { replay: { format: "gemini", content: replayParts } } : {}) };
}
@@ -2,7 +2,6 @@ import type { ToolTurnFn } from "../provider-tool-turn";
import {
makeChatCompletionsTurn,
runAnthropicTurn,
runAntigravityTurn,
runAzureTurn,
runBedrockTurn,
runClaudeProTurn,
@@ -28,7 +27,6 @@ const TURNS: Record<string, ToolTurnFn> = {
"kimi-cn": makeChatCompletionsTurn("kimi-cn", "https://api.moonshot.cn/v1/chat/completions", "Kimi CN"),
"gpt-account": runCodexTurn,
"github-copilot": runCopilotTurn,
"google-antigravity": runAntigravityTurn,
"claude-pro": runClaudeProTurn,
"kimi-code": runKimiCodeTurn,
"custom-openai": runCustomOpenAiTurn,
+2 -25
View File
@@ -9,7 +9,7 @@ import type { AgentTurnMessage, AgentTurnResult, ProviderToolTurnInput, TurnCred
import { accumulateResponsesStream, parseResponsesOutput, responsesToolDefs, toResponsesInput } from "./responses-format";
import { anthropicToolDefs, parseAnthropicContent, toAnthropicMessages } from "./anthropic-format";
import { accumulateChatStream, chatMaxTokensField, chatToolDefs, parseChatChoice, toChatMessages } from "./chat-format";
import { accumulateGeminiStream, antigravityRequestBody, parseGeminiResponse, vertexRequestBody } from "./gemini-format";
import { parseGeminiResponse, vertexRequestBody } from "./gemini-format";
import { bedrockToolConfig, parseBedrockOutput, toBedrockMessages } from "./bedrock-format";
import { signAwsRequest } from "./aws-sigv4";
import { getGcpAccessToken } from "./gcp-auth";
@@ -17,8 +17,6 @@ import { COPILOT_HEADERS, copilotBaseUrl } from "../oauth/github-copilot-flow";
import { KIMI_CODE_BASE_URL } from "../oauth/kimi-code-flow";
import { OUTPUT_RESERVE_TOKENS } from "../context-budget";
const ANTIGRAVITY_VERSION = "1.21.9";
const ANTIGRAVITY_ENDPOINT = "https://cloudcode-pa.googleapis.com";
const CODEX_BASE_URL = "https://chatgpt.com/backend-api";
function requireApiKey(credential: TurnCredential, label: string): string {
@@ -211,27 +209,6 @@ export async function runCustomAnthropicTurn(input: ProviderToolTurnInput): Prom
return { ...parsed, rawResponseJson: JSON.stringify(response.data), rateLimitState: response.rateLimitState };
}
// ---- Google Antigravity (OAuth, Gemini Code Assist, SSE) ----
export async function runAntigravityTurn(input: ProviderToolTurnInput): Promise<AgentTurnResult> {
const access = requireAccessToken(input.credential, "Google Antigravity");
if (!input.credential.projectId) throw new Error("Antigravity credential is missing its project id.");
const requestId = `agent-${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
const body = antigravityRequestBody({
model: input.model,
projectId: input.credential.projectId,
instructions: input.instructions,
messages: input.messages,
tools: input.tools,
requestId,
});
const response = await postEventStream(`${ANTIGRAVITY_ENDPOINT}/v1internal:streamGenerateContent?alt=sse`, {
Authorization: `Bearer ${access}`,
"User-Agent": `antigravity/${ANTIGRAVITY_VERSION} darwin/arm64`,
}, body);
return { ...(await accumulateGeminiStream(response.messages)), rateLimitState: response.rateLimitState };
}
// ---- Azure OpenAI (Chat Completions at the resource deployment) ----
export async function runAzureTurn(input: ProviderToolTurnInput): Promise<AgentTurnResult> {
@@ -283,7 +260,7 @@ export async function runVertexTurn(input: ProviderToolTurnInput): Promise<Agent
const { projectId, region, serviceAccountJson } = input.credential;
if (!projectId || !region || !serviceAccountJson) throw new Error("Vertex AI credential is incomplete.");
const token = await getGcpAccessToken(serviceAccountJson);
const body = vertexRequestBody({ model: input.model, instructions: input.instructions, messages: input.messages, tools: input.tools });
const body = vertexRequestBody({ instructions: input.instructions, messages: input.messages, tools: input.tools });
const url = `https://${region}-aiplatform.googleapis.com/v1/projects/${projectId}/locations/${region}/publishers/google/models/${input.model}:generateContent`;
const response = await postJson(url, { authorization: `Bearer ${token}` }, body, WHOLE_RESPONSE_WAIT);
const parsed = parseGeminiResponse(response.data);
+6 -3
View File
@@ -2,7 +2,9 @@ import { currentDataVersion } from "./data-version";
import { loadViewState } from "./view-state";
import { loadOnboardingDraft } from "./onboarding-progress";
import type { DatabaseSync, StatementSync, SQLInputValue } from "node:sqlite";
import type { AppSnapshot } from "../../shared/domain";
import type { AppSnapshot, UiTheme } from "../../shared/domain";
const UI_THEMES: UiTheme[] = ["system", "light", "dark", "clock"];
import { PROVIDER_CATALOG } from "../../shared/provider-catalog";
import { IntegrationKeyStore } from "./integration-key-store";
import { currentProviderUsageWindow } from "../../shared/provider-runtime-domain";
@@ -173,9 +175,10 @@ export class SnapshotService {
private resolveUiPreferences(): AppSnapshot["uiPreferences"] {
const row = this.db.prepare("select theme, language from app_state where id = 1")
.get() as { theme: string; language: string } | undefined;
const theme = row?.theme === "light" || row?.theme === "dark" ? row.theme : "system";
const theme = row?.theme ?? "system";
if (!UI_THEMES.includes(theme as UiTheme)) throw new Error(`Stored theme "${theme}" is not a known theme.`);
const language = row?.language === "zh" ? "zh" : "en";
return { theme, language };
return { theme: theme as UiTheme, language };
}
}
+5 -4
View File
@@ -1,4 +1,4 @@
import { taskWorkLanguage } from "./work-language";
import { appLanguage, taskWorkLanguage } from "./work-language";
import { closeChatWakeTask } from "./chat-wake-close";
import type { DatabaseSync } from "node:sqlite";
import type { RunTaskInput } from "../../shared/commands";
@@ -187,7 +187,9 @@ export class TaskExecutionService {
.run(effectiveModel(agent.model_id, provider.model), provider.credential_id, runId);
}
const runModel = pinned ?? effectiveModel(agent.model_id, provider.model);
skillRuntimeSnapshot = this.resolveSkillRuntimeSnapshot(orgId, agent.id, runId, skillBudgetTokens(provider.context_window_tokens), `${task.title}\n${task.description}`, { providerKey: provider.provider_key, model: runModel }, task.writing_mode === WRITING_MODE.CONVERSATIONAL, taskWorkLanguage(this.db, orgId, task.id));
const language = taskWorkLanguage(this.db, orgId, task.id);
const chatLanguage = appLanguage(this.db);
skillRuntimeSnapshot = this.resolveSkillRuntimeSnapshot(orgId, agent.id, runId, skillBudgetTokens(provider.context_window_tokens), `${task.title}\n${task.description}`, { providerKey: provider.provider_key, model: runModel }, task.writing_mode === WRITING_MODE.CONVERSATIONAL, task.origin === "chat_wake" ? chatLanguage : language);
// Watermark for reply delivery and mid-run message polling.
const runStartedAt = new Date().toISOString();
const chatContext = loadChatWakeContext(this.db, orgId, agent.id, isolation.secretScopeJson);
@@ -208,7 +210,6 @@ export class TaskExecutionService {
const connectorNames = new ConnectorGrantsService(this.db)
.toolkitsForAgent(orgId, agent.id)
.map(connectorDisplayName);
const language = taskWorkLanguage(this.db, orgId, task.id);
// Baseline taken before any await, so a goal closed while tools load still reaches the session.
const goalChanges = createGoalChangePoller(this.db, task.goal_id);
const externalTools = loadComposioTools(this.db, this.providers.integrationKeys, orgId, agent.id);
@@ -222,7 +223,7 @@ export class TaskExecutionService {
orgId,
providerId: provider.id,
workspaceId: task.workspace_id,
instructions: buildAgentInstructions({ agent, companyName: this.orgName(orgId), isCeo, hasReports, connectorNames, language }),
instructions: buildAgentInstructions({ agent, companyName: this.orgName(orgId), isCeo, hasReports, connectorNames, language, chatLanguage }),
initialUserTurn: buildTaskPrompt({
task,
agent,
+7 -2
View File
@@ -97,6 +97,8 @@ export interface AgentInstructionContext {
connectorNames: string[];
/** The task's working language (its own, else the company's). */
language: "en" | "zh";
/** The app's display language: every chat message uses it. */
chatLanguage: "en" | "zh";
}
/**
@@ -113,8 +115,11 @@ export function buildAgentInstructions(input: AgentInstructionContext): string {
"Work like a sharp person: take in what is actually in front of you, decide the smallest real next step, do it, then tell whoever needs to know. Do not narrate busywork.",
`Your tools are how you act: hire_agent builds your team, create_task delegates and assigns work by name (set requires_filesystem for engineering work that must change code or run commands), update_task_status tracks it, list_files and read_file explore the company workspace, write_deliverable produces real files, run_command builds and tests for real on filesystem tasks, create_document writes company documents (PRDs, specs, memos, reports) and list_documents, read_document, update_document find and revise them, search_knowledge and record_knowledge read and grow what the company has learned, read_messages catches you up on what teammates said, and send_message is how you talk to everyone. web_search and fetch_url reach the live web — look up APIs, docs, and facts instead of guessing them.`,
input.language === "zh"
? "公司的工作语言是简体中文:你写的每一条消息、任务标题与描述、文档和交付物都用中文表达(代码、命令、API 名称等技术标识保持原样)。工具名称和工具参数的字段名仍按定义使用英文。"
: "The working language is English: write every message, task title and description, document and deliverable in English (code, commands and API names stay as they are), even when the material you read is in another language.",
? "公司的工作语言是简体中文:任务标题与描述、文档和交付物都用中文表达(代码、命令、API 名称等技术标识保持原样)。工具名称和工具参数的字段名仍按定义使用英文。"
: "The working language is English: write every task title and description, document and deliverable in English (code, commands and API names stay as they are), even when the material you read is in another language.",
input.chatLanguage === "zh"
? "聊天语言是简体中文:你发出的每一条聊天消息(send_message、回复、交接说明)都用中文,即使对方或任务材料用的是其他语言。"
: "The chat language is English: write every chat message you send (send_message, replies, handoff notes) in English, even when the other person or the task material uses another language.",
capabilityBriefing(input),
"Talk like a person on a team, not a status bot: address teammates by @name, say what you genuinely think, ask when you are unsure, and reply when someone asks you something. Before starting work, check your messages with read_messages to see if anyone needs you. Post where the work lives — 'engineering', 'product', or otherwise 'general' — and keep a back-and-forth in one thread by passing the thread_id a previous send_message returned. Hand work to a teammate with /handoff @Name and the file_id write_deliverable gives you.",
].join("\n");
+6
View File
@@ -11,3 +11,9 @@ export function taskWorkLanguage(db: DatabaseSync, orgId: string, taskId: string
if (!row) throw new Error("Task was not found.");
return row.language;
}
/** The app's display language; agents chat in it. */
export function appLanguage(db: DatabaseSync): WorkLanguage {
const row = db.prepare("select language from app_state where id = 1").get() as { language: WorkLanguage } | undefined;
return row?.language ?? "en";
}
+8 -15
View File
@@ -1,3 +1,5 @@
import { usePaletteClock } from "../shared/palette-clock";
import { usePixelScale } from "../shared/pixel-scale";
import { Modal } from "../shared/Modal";
import { StaleBanner } from "./StaleBanner";
import { oneOf, readViewState, seedViewState, writeViewState } from "../shared/view-state";
@@ -8,9 +10,9 @@ import { hasPageUnsaved } from "../shared/unsaved";
import { ErrorBoundary } from "../shared/ErrorBoundary";
import { StartupScreen } from "./StartupScreen";
import type { Focus } from "../pages/types";
import { useEffect, useMemo, useState } from "react";
import { useMemo, useState } from "react";
import { Shell } from "../shared/Shell";
import { ROUTE_IDS, type RouteId } from "../shared/routes";
import { connectorsEnabled, ROUTE_IDS, type RouteId } from "../shared/routes";
import { AvatarDirectoryContext, type AvatarLook } from "../shared/ui";
import { Onboarding } from "./Onboarding";
import { useSnapshot } from "./useSnapshot";
@@ -67,25 +69,16 @@ export function App() {
}, [snapshot?.agents, snapshot?.employees, snapshot?.activeOrgId]);
const [creatingOrg, setCreatingOrg] = useState(false);
const theme = snapshot?.uiPreferences.theme ?? "system";
useEffect(() => {
const media = window.matchMedia("(prefers-color-scheme: dark)");
const apply = () => {
const resolved = theme === "system" ? (media.matches ? "dark" : "light") : theme;
document.documentElement.dataset.theme = resolved;
};
apply();
if (theme !== "system") return;
media.addEventListener("change", apply);
return () => media.removeEventListener("change", apply);
}, [theme]);
usePaletteClock(snapshot?.uiPreferences.theme ?? "system");
usePixelScale();
if (!snapshot) {
// A failed manual retry is already recorded in syncFailure, which the screen shows.
return <StartupScreen failure={syncFailure} onRetry={() => void actions.reload().catch(() => undefined)} />;
}
seedViewState(snapshot.viewState);
const route = routeChoice ?? readViewState("route", isRoute) ?? "home";
const chosenRoute = routeChoice ?? readViewState("route", isRoute) ?? "home";
const route = chosenRoute === "connectors" && !connectorsEnabled(snapshot) ? "home" : chosenRoute;
// A company exists from Launch on, but its setup is unfinished until the connectors step is done; that is stored, so a restart resumes it.
const unfinished = snapshot.organizations.find((organization) => organization.setupCompletedAt === null) ?? null;
if (snapshot.organizations.length === 0 || creatingOrg || unfinished) {
+1 -1
View File
@@ -8,7 +8,7 @@ const RISK_NAMES = { low: () => t("Low"), medium: () => t("Medium"), high: () =>
export function AutonomySummary({ mode }: { mode: "ai_ceo" | "ai_cofounder" }) {
const gated = { level: RISK_NAMES[COMPANY_PRESETS.taskRiskCeiling](), amount: dollars(COMPANY_PRESETS.hireReviewAboveCents) };
return (
<section aria-label={t("What this mode allows")} style={{ fontSize: 13, color: "var(--text-2)", lineHeight: 1.6 }}>
<section aria-label={t("What this mode allows")} style={{ fontSize: "var(--fs-body)", color: "var(--text-2)", lineHeight: 1.6 }}>
<ul style={{ margin: 0, paddingLeft: 18 }}>
<li>{mode === "ai_ceo"
? t("Approved without you: tasks above {level} risk, tasks that run commands in a workspace, and hires over {amount} a month.", gated)
+29 -21
View File
@@ -168,15 +168,15 @@ export function Onboarding({
<div>
<div className="row" style={{ gap: 8 }}>
<div className="brand-mark">A</div>
<div style={{ fontWeight: 540 }}>AgentCompany</div>
<div>AgentCompany</div>
{cancel && step !== "connectors" && (
<button type="button" className="button ghost" style={{ marginLeft: "auto" }} onClick={cancel}>
{t("Cancel")}
</button>
)}
</div>
<h1 className="page-h1" style={{ fontSize: 24, marginTop: 32, letterSpacing: "-0.02em" }}>{t("Start your AI company.")}</h1>
<p className="page-sub" style={{ maxWidth: 460, fontSize: 14, lineHeight: 1.55 }}>
<h1 className="page-h1" style={{ fontSize: "var(--fs-display)", marginTop: 32 }}>{t("Start your AI company.")}</h1>
<p className="page-sub" style={{ maxWidth: 460, fontSize: "var(--fs-body)", lineHeight: 1.55 }}>
{t("Stand up the workspace, bind the provider, and queue the first operating loop.")}
</p>
<div className="onboarding-steps">
@@ -188,20 +188,35 @@ export function Onboarding({
<div className="card" style={{ maxWidth: 460 }}>
<div className="card-label" style={{ marginBottom: 10 }}>{t("Runtime selected")}</div>
<div className="row" style={{ gap: 10 }}>
<Icon name="bot" size={18} />
<strong style={{ fontSize: 14 }}>{selectedProvider.label}</strong>
<Icon name="bot" />
<strong style={{ fontSize: "var(--fs-body)" }}>{selectedProvider.label}</strong>
{draft.providerModel && <Pill tone="violet">{draft.providerModel}</Pill>}
</div>
<div style={{ marginTop: 10, fontSize: 12, color: "var(--text-3)" }}>
<div style={{ marginTop: 10, fontSize: "var(--fs-body)", color: "var(--text-3)" }}>
{t("We never embed the key in the build. Credentials encrypt locally via OS-protected storage.")}
</div>
</div>
</section>
{step === "connectors" ? (
<div className="onboarding-panel">
<div key={step} className="step-view">
{bootstrappedOrgId && (
<ConnectorsStep
orgId={bootstrappedOrgId}
snapshot={snapshot}
actions={actions}
onFinish={() => finishSetup(bootstrappedOrgId)}
/>
)}
</div>
{error && <div style={{ color: "var(--red)", marginTop: 16, fontSize: "var(--fs-body)" }}>{error}</div>}
</div>
) : (
<form className="onboarding-panel" onSubmit={submit} noValidate>
<div key={step} className="step-view">
{restored && step !== "connectors" && (
<p role="status" style={{ fontSize: 13, color: "var(--text-2)", margin: "0 0 12px" }}>
{restored && (
<p role="status" style={{ fontSize: "var(--fs-body)", color: "var(--text-2)", margin: "0 0 12px" }}>
{t("Your progress was restored. Keys are never saved before launch, so enter yours again.")}
</p>
)}
@@ -240,17 +255,10 @@ export function Onboarding({
onBack={back("mode")}
/>
)}
{step === "connectors" && bootstrappedOrgId && (
<ConnectorsStep
orgId={bootstrappedOrgId}
snapshot={snapshot}
actions={actions}
onFinish={() => finishSetup(bootstrappedOrgId)}
/>
)}
</div>
{error && <div style={{ color: "var(--red)", marginTop: 16, fontSize: 14 }}>{error}</div>}
{error && <div style={{ color: "var(--red)", marginTop: 16, fontSize: "var(--fs-body)" }}>{error}</div>}
</form>
)}
</main>
</div>
);
@@ -284,10 +292,10 @@ function WelcomeStep({
/>
</div>
<RestartForLanguage language={language} />
<p style={{ color: "var(--text-2)", fontSize: 14, lineHeight: 1.55 }}>
<p style={{ color: "var(--text-2)", fontSize: "var(--fs-body)", lineHeight: 1.55 }}>
{t("AgentCompany sets up your operating loop in six steps. Bring an API key, pick a runtime for the founding CEO, and we'll wire up the first goal, project, and task.")}
</p>
<ul style={{ paddingLeft: 20, color: "var(--text-2)", lineHeight: 1.8, margin: 0, fontSize: 14 }}>
<ul style={{ paddingLeft: 20, color: "var(--text-2)", lineHeight: 1.8, margin: 0, fontSize: "var(--fs-body)" }}>
<li>{t("Connect one model provider (OpenAI, Anthropic, xAI, or Groq).")}</li>
<li>{t("Name the company and the human board chair.")}</li>
<li>{t("Pick execution mode and bind the workspace path.")}</li>
@@ -321,7 +329,7 @@ function CompanyStep({ draft, onChange, onBack, onNext }: StepProps) {
<Field label={t("Workspace path (optional)")}>
<div className="row" style={{ gap: 6 }}>
<input className="input" value={draft.workspacePath} onChange={(event) => onChange({ workspacePath: event.target.value })} />
<Button tone="ghost" onClick={chooseWorkspace}><Icon name="folder" size={16} /> {t("Choose")}</Button>
<Button tone="ghost" onClick={chooseWorkspace}><Icon name="folder" /> {t("Choose")}</Button>
</div>
</Field>
<Actions onBack={onBack} onNext={onNext} />
@@ -333,7 +341,7 @@ function ModeStep({ draft, onChange, onBack, onNext }: StepProps) {
return (
<div className="form-grid">
<h2 className="page-h1">{t("Mode")}</h2>
<p style={{ color: "var(--text-3)", fontSize: 14 }}>{t("How autonomous should the CEO be?")}</p>
<p style={{ color: "var(--text-3)", fontSize: "var(--fs-body)" }}>{t("How autonomous should the CEO be?")}</p>
<ModeCard
title={t("AI CEO")}
description={t("Runs on its own: approves its risky work and large hires, and writes deliverables without review.")}
@@ -6,14 +6,16 @@ import type { AppSnapshot } from "../../../shared/domain";
import { Button } from "../shared/ui";
import { ToolkitCatalog } from "../pages/connectors/ToolkitCatalog";
import { useConnectorCatalog } from "../pages/connectors/useConnectorCatalog";
import { IntegrationKeyRow } from "../pages/settings/IntegrationKeysPanel";
import { connectorsEnabled } from "../shared/routes";
import { DEFAULT_CONNECTOR_ACCOUNT_LABEL } from "../../../shared/commands";
import type { SnapshotActions } from "./useSnapshot";
import { t } from "../i18n/i18n";
/**
* The post-launch onboarding step: the company exists, so connections can be
* made against it. Connecting is optional — Finish enters the app either way
* and the Connectors page carries the same catalog.
* The post-launch onboarding step: the operator saves their own Composio and
* logo.dev keys, then connects the toolkits their Composio project enables.
* Skipping leaves Connectors out of the app until a Composio key is saved.
*/
export function ConnectorsStep({
orgId,
@@ -26,6 +28,21 @@ export function ConnectorsStep({
actions: SnapshotActions;
onFinish: () => void;
}) {
const enabled = connectorsEnabled(snapshot);
const composioSavedAt = snapshot.integrationKeys.find((key) => key.name === "composio")?.updatedAt;
return (
<div className="form-grid">
<h2 className="page-h1">{t("Connectors")}</h2>
{snapshot.integrationKeys.map((status) => <IntegrationKeyRow key={status.name} status={status} actions={actions} />)}
{enabled && <ConnectorChoices key={composioSavedAt} orgId={orgId} snapshot={snapshot} actions={actions} />}
<div className="modal-actions" style={{ marginTop: 4 }}>
<Button tone="primary" onClick={onFinish}>{enabled ? t("Finish") : t("Skip")}</Button>
</div>
</div>
);
}
function ConnectorChoices({ orgId, snapshot, actions }: { orgId: string; snapshot: AppSnapshot; actions: SnapshotActions }) {
const { catalog, busySlug, connectError, signIn, accountSync, syncAccounts, stopWaiting, checkAgain, connect, retry } = useConnectorCatalog(orgId, actions);
const connectedSlugs = useMemo(
() =>
@@ -38,8 +55,7 @@ export function ConnectorsStep({
);
return (
<div className="form-grid">
<h2 className="page-h1">{t("Connectors")}</h2>
<>
{catalog.phase === "error" && <ErrorText message={catalog.message} action={{ label: t("Retry"), onClick: retry }} />}
{catalog.phase === "ready" && (
<div style={{ maxHeight: 420, overflowY: "auto", paddingRight: 4 }}>
@@ -54,9 +70,6 @@ export function ConnectorsStep({
{signIn && <SignInStatus signIn={signIn} onStop={stopWaiting} onCheckAgain={checkAgain} />}
<AccountSyncNote sync={accountSync} onRetry={syncAccounts} />
{connectError && <ErrorText message={connectError} />}
<div className="modal-actions" style={{ marginTop: 4 }}>
<Button tone="primary" onClick={onFinish}>{t("Finish")}</Button>
</div>
</div>
</>
);
}
@@ -25,7 +25,7 @@ export function ProviderStep({
return (
<div className="form-grid">
<h2 className="page-h1">{t("Provider")}</h2>
<p style={{ color: "var(--text-3)", fontSize: 14 }}>
<p style={{ color: "var(--text-3)", fontSize: "var(--fs-body)" }}>
{t("Pick the runtime for the founding CEO. You can attach more providers in Settings later.")}
</p>
<div className="option-grid">
@@ -112,7 +112,7 @@ function ProviderCredentialFields({
return (
<div className="provider-inline-form">
{selected.credentialHelp && (
<div style={{ fontSize: 13, color: "var(--text-3)", lineHeight: 1.5 }}>{selected.credentialHelp}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", lineHeight: 1.5 }}>{selected.credentialHelp}</div>
)}
{isOAuthLike ? (
<ProviderOAuthConnect
@@ -160,7 +160,7 @@ function ProviderCredentialFields({
{loading ? t("Getting models...") : fetched ? t("Reload models") : t("Get models")}
</Button>
)}
{loadError && <div style={{ color: "var(--red)", fontSize: 12 }}>{loadError}</div>}
{loadError && <div style={{ color: "var(--red)", fontSize: "var(--fs-body)" }}>{loadError}</div>}
{(hasCredential || isCustom) && (
<Field label={t("Model")}>
{fetched || showCuratedList ? (
+1 -1
View File
@@ -9,7 +9,7 @@ export function StaleBanner({ failure, syncedAt, onRetry }: { failure: SyncFailu
// Outside the app root, so it stays usable while a dialog makes the app inert.
return createPortal(
<div role="alert" className="card" style={{ position: "fixed", top: 8, left: "50%", transform: "translateX(-50%)", zIndex: 900, display: "flex", gap: 10, alignItems: "center", padding: "8px 12px", borderColor: "var(--amber, var(--red))", maxWidth: "min(720px, calc(100vw - 32px))" }}>
<div style={{ fontSize: 13, minWidth: 0 }}>
<div style={{ fontSize: "var(--fs-body)", minWidth: 0 }}>
<strong>{t("Not up to date.")}</strong>{" "}
{syncedAt ? t("Showing data from {time}.", { time: formatTime(syncedAt) }) : null}{" "}
<span style={{ color: "var(--text-2)", wordBreak: "break-word" }}>{t("Updating failed: {reason} (attempt {count}).", { reason: failure.message, count: failure.attempts })}</span>
+7 -7
View File
@@ -1,4 +1,4 @@
import { Button } from "../shared/ui";
import { GameOver } from "../shared/GameOver";
import { t } from "../i18n/i18n";
import type { SyncFailure } from "./useSnapshot";
@@ -7,12 +7,12 @@ export function StartupScreen({ failure, onRetry }: { failure: SyncFailure | nul
return (
<div className="app-shell" style={{ display: "grid", placeItems: "center", padding: 24 }}>
{failure ? (
<div role="alert" style={{ maxWidth: 480, display: "grid", gap: 12, textAlign: "center" }}>
<strong>{t("AgentCompany could not load its data.")}</strong>
<div className="mono" style={{ fontSize: 12, color: "var(--text-2)", wordBreak: "break-word" }}>{failure.message}</div>
<div style={{ fontSize: 13, color: "var(--text-3)" }}>{t("Retrying every few seconds (attempt {count}).", { count: failure.attempts })}</div>
<div><Button onClick={onRetry}>{t("Retry now")}</Button></div>
</div>
<GameOver
title={t("AgentCompany could not load its data.")}
error={failure.message}
note={t("Retrying every few seconds (attempt {count}); Continue tries now.", { count: failure.attempts })}
onContinue={onRetry}
/>
) : (
<div role="status" style={{ color: "var(--text-3)" }}>{t("Starting AgentCompany…")}</div>
)}
@@ -13,8 +13,7 @@ curl -o <provider-key>.png "https://img.logo.dev/<domain>?token=<publishable-tok
Domain per file: openai.com, anthropic.com, claude.ai (claude-pro), grok.com
(xai), groq.com, mistral.ai, cerebras.ai, openrouter.ai, moonshot.ai (kimi;
also used for kimi-code — kimi.com is not in logo.dev's index), moonshot.cn
(kimi-cn), github.com (github-copilot), antigravity.google
(google-antigravity), chatgpt.com (gpt-account), azure.microsoft.com
(kimi-cn), github.com (github-copilot), chatgpt.com (gpt-account), azure.microsoft.com
(azure-openai), aws.amazon.com (aws-bedrock), cloud.google.com (vertex-ai).
The custom-openai / custom-anthropic endpoints carry no official brand and
render as letter tiles.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.2 KiB

Binary file not shown.
@@ -0,0 +1,96 @@
Fusion Pixel Font
https://github.com/TakWolf/fusion-pixel-font
Copyright (c) 2022, TakWolf (https://takwolf.com).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,96 @@
Ark Pixel Font
https://github.com/TakWolf/ark-pixel-font
Copyright (c) 2021, TakWolf (https://takwolf.com).
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,108 @@
[Cubic 11]
These fonts are free software.
Unlimited permission is granted to use, copy, and distribute them, with or without modification, either commercially or noncommercially.
THESE FONTS ARE PROVIDED "AS IS" WITHOUT WARRANTY.
此字型是免費的。
無論您是否進行對本字型進行商業或非商業性修改,均可無限制地使用,複製和分發它們。
本字型的衍生品之授權必須與此字型相同,且不作任何擔保。
[JF Dot M+H 12]
Copyright(c) 2005 M+ FONTS PROJECT
[M+ BITMAP FONTS]
Copyright (C) 2002-2004 COZ
These fonts are free software.
Unlimited permission is granted to use, copy, and distribute it, with or without modification, either commercially and noncommercially.
THESE FONTS ARE PROVIDED "AS IS" WITHOUT WARRANTY.
これらのフォントはフリー(自由な)ソフトウエアです。
あらゆる改変の有無に関わらず、また商業的な利用であっても、自由にご利用、複製、再配布することができますが、全て無保証とさせていただきます。
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -0,0 +1,93 @@
Copyright (c) 2019–2025 Lee Minseo (quiple@quiple.dev)
This font software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
https://openfontlicense.org
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION & CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.
+2 -2
View File
@@ -20,8 +20,8 @@ const APPROVAL_KINDS: Record<string, string> = {
};
export const approvalKindLabel = (kind: string) => labelOf("approval kind", APPROVAL_KINDS, kind);
const OFFICE_ACTIVITIES: Record<string, string> = { active: t("Active"), thinking: t("Thinking"), busy: t("Busy"), idle: t("Idle") };
export const officeActivityLabel = (activity: string) => labelOf("office activity", OFFICE_ACTIVITIES, activity);
const OFFICE_STATES: Record<string, string> = { running: t("Running"), queued: t("Queued"), cooldown: t("Cooling down"), blocked: t("Blocked"), idle: t("Idle") };
export const officeStateLabel = (state: string) => labelOf("office state", OFFICE_STATES, state);
const APPROVAL_STATES: Record<string, string> = { pending: t("Pending"), approved: t("Approved"), declined: t("Declined"), superseded: t("Superseded") };
export const approvalStateLabel = (state: string) => labelOf("approval state", APPROVAL_STATES, state);
+12 -14
View File
@@ -134,7 +134,6 @@ export const zh: Record<string, string> = {
"Resume": "恢复",
"Missing this run": "本次运行缺少的能力",
"Disconnect": "断开连接",
"Revokes the sign-in at {provider} and erases it from this computer.": "在 {provider} 撤销登录授权,并从本机删除。",
"Erases the key from this computer. {provider} keeps accepting it until you revoke it in your account.": "仅从本机删除密钥。在你于 {provider} 账号中撤销之前,该密钥仍然有效。",
"API key (if the server asks for one)": "API 密钥(服务需要时填写)",
"Checking...": "检查中...",
@@ -212,8 +211,6 @@ export const zh: Record<string, string> = {
"Powers the Connectors page and agent connector tools. Create one at platform.composio.dev.": "用于连接器页面和 Agent 的连接器工具。在 platform.composio.dev 创建。",
"logo.dev publishable key": "logo.dev 公开密钥",
"Shows brand logos for connectors. Create one at logo.dev.": "为连接器显示品牌图标。在 logo.dev 创建。",
"Google Antigravity OAuth client secret": "Google Antigravity OAuth 客户端密钥",
"Needed to sign in to and refresh the Google Antigravity provider.": "登录和续期 Google Antigravity 时需要。",
"Saved": "已保存",
"Not set": "未设置",
"Replace key": "替换密钥",
@@ -256,12 +253,13 @@ export const zh: Record<string, string> = {
"Base URL is required.": "请填写基础 URL。",
"Billing": "用量账单",
"Blocked": "受阻",
"Cooling down": "冷却中",
"Waiting for your approval.": "正在等待你的审批。",
"Board": "看板",
"Browse": "浏览",
"Budget": "预算",
"Budget cap": "预算上限",
"Budget utilization": "预算使用率",
"Busy": "忙碌",
"By agent": "按智能体",
"CEO": "CEO",
"CEO OFFICE": "CEO 办公室",
@@ -343,7 +341,6 @@ export const zh: Record<string, string> = {
"That file could not be read as an image.": "无法将该文件读取为图片。",
"Conversation messages": "会话消息",
"Office tools": "办公室工具",
"Agents with work stay at their desks. Only idle agents walk to coffee, snacks or the meeting table.": "有工作的智能体会一直待在工位;只有空闲的智能体才会去咖啡机、零食区或会议桌。",
"Avatar": "头像",
"Avatar emoji": "头像表情",
"Avatar color": "头像颜色",
@@ -365,6 +362,7 @@ export const zh: Record<string, string> = {
"Filter risk": "筛选风险",
"Filter tasks": "筛选任务",
"Finish": "完成",
"Skip": "跳过",
"Foreground": "前台",
"General": "通用",
"Get models": "获取模型",
@@ -580,7 +578,6 @@ export const zh: Record<string, string> = {
"Team": "团队",
"Tests": "测试",
"Theme": "主题",
"Thinking": "思考中",
"Progress": "进度",
"Title": "标题",
"Today": "今天",
@@ -601,6 +598,14 @@ export const zh: Record<string, string> = {
"Version (semver)": "版本(semver)",
"Visibility": "可见性",
"Needs you": "需要你处理",
"Goal progress": "目标进度",
"Budget allocated": "已分配预算",
"Budget compared with the largest agent budget": "与最高智能体预算相比",
"GAME OVER": "游戏结束",
"The rest of the app still works; Continue tries this page again.": "应用其他部分仍可使用;点“继续”会重新打开此页。",
"Continue reloads the window; your data is kept.": "点“继续”会重新加载窗口;数据会保留。",
"Retrying every few seconds (attempt {count}); Continue tries now.": "每隔几秒自动重试(第 {count} 次);点“继续”立即重试。",
"Follow the clock": "跟随时间(夜间变暗)",
"Next in line": "下一项工作",
"Stopped: {reason}": "已停下:{reason}",
"{n} more after these": "之后还有 {n} 项",
@@ -701,8 +706,6 @@ export const zh: Record<string, string> = {
"Waiting for the {name} sign-in in your browser (check {check} of {checks}).": "正在等待你在浏览器中完成 {name} 登录(第 {check}/{checks} 次检查)。",
"Stop waiting": "停止等待",
"People to mention": "可提及的人",
"Only a task runs: an agent picks it up and does the work. Goals and projects group tasks; documents and knowledge are what agents read and write along the way.": "只有任务会被执行:智能体接手任务并完成工作。目标和项目用来归组任务;文档和知识是智能体在工作中读写的内容。",
"Agents read and write these while working on tasks. Nothing here starts work; a task does.": "智能体在执行任务时读写这些内容。这里的内容不会自行启动工作,只有任务会。",
"{title}: use the arrow keys to read each value": "{title}:用方向键逐项读取数值",
"{rate}% of judged work accepted": "已评判的工作中 {rate}% 被接受",
"No work judged yet": "还没有评判过的工作",
@@ -719,7 +722,7 @@ export const zh: Record<string, string> = {
"Copy failed": "复制失败",
"Checking account status with Composio…": "正在向 Composio 核对账号状态…",
"Account status checked with Composio at {time}.": "已于 {time} 向 Composio 核对账号状态。",
"Account status could not be checked with Composio: {reason}. The statuses below may be out of date.": "无法向 Composio 核对账号状态:{reason}。下方状态可能已过时。",
"Account status could not be checked with Composio, so the statuses below may be out of date. Reason: {reason}": "无法向 Composio 核对账号状态,下方状态可能已过时。原因:{reason}",
"{name} ({label}) is connected.": "{name}({label})已连接。",
"{name} ({label}) is still not connected. If you finished signing in, check again; otherwise connect again.": "{name}({label})仍未连接。如果已经完成登录,请再次检查;否则请重新连接。",
"Check again": "再次检查",
@@ -741,12 +744,7 @@ export const zh: Record<string, string> = {
"Stay": "留下",
"This page could not be shown.": "此页面无法显示。",
"AgentCompany hit an error it could not recover from here.": "AgentCompany 遇到了无法在此恢复的错误。",
"The rest of the app still works; go to another page or try this one again.": "应用的其他部分仍可使用;可以前往其他页面,或重试此页面。",
"Reloading the window starts it again; your data is kept.": "重新加载窗口即可重新开始;你的数据会保留。",
"Try again": "重试",
"Reload": "重新加载",
"AgentCompany could not load its data.": "AgentCompany 无法加载数据。",
"Retrying every few seconds (attempt {count}).": "每隔几秒重试一次(第 {count} 次)。",
"Retry now": "立即重试",
"Starting AgentCompany…": "正在启动 AgentCompany…",
"Direct: only its members take part, and every message wakes the other members. As the board, you can read it even when you are not a member.": "私聊:只有成员参与,每条消息都会唤醒其他成员。作为董事会,即使你不是成员也能阅读。",
+1
View File
@@ -7,6 +7,7 @@ import "./styles/fonts.css";
import "./styles.css";
import "./styles/components.css";
import "./overlays.css";
import "./styles/pixel.css";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
+4 -9
View File
@@ -12,10 +12,6 @@
width: min(520px, 100%);
max-height: min(760px, 100%);
overflow: auto;
border: 1px solid var(--border);
border-radius: var(--r-xl);
background: var(--panel);
box-shadow: 0 20px 60px rgba(24, 24, 24, 0.18);
padding: var(--sp-5);
animation: overlay-enter var(--motion-base) var(--ease-out-expo);
}
@@ -27,7 +23,8 @@
from { opacity: 0; transform: translateY(8px) scale(0.98); }
to { opacity: 1; transform: none; }
}
.modal-title { margin: 0 0 var(--sp-4); font-size: var(--fs-title); font-weight: 600; letter-spacing: -0.01em; }
/* Dialog name plate, as a speaker's name above an RPG text box. */
.modal-title { display: inline-block; margin: 0 0 var(--sp-4); padding: 2px 10px; font-size: var(--fs-title); background: var(--btn-primary-bg); color: var(--btn-primary-fg); box-shadow: 2px 2px 0 0 var(--border-strong); }
.modal-actions { display: flex; justify-content: flex-end; gap: var(--sp-2); margin-top: var(--sp-5); }
.onboarding-window {
@@ -107,7 +104,7 @@
.option-card:hover { border-color: var(--border-strong); box-shadow: var(--shadow-sm); }
.option-card:active { transform: scale(0.99); }
.option-card.active { border-color: var(--text-1); box-shadow: inset 0 0 0 1px var(--text-1); }
.option-card .opt-title { font-size: var(--fs-body); font-weight: 540; }
.option-card .opt-title { font-size: var(--fs-body); }
.option-card .opt-sub { font-size: var(--fs-caption); color: var(--text-3); margin-top: var(--sp-1); }
.provider-inline-form {
display: grid;
@@ -145,8 +142,6 @@
.menu-label {
padding: var(--sp-2) var(--sp-2) var(--sp-1);
font-size: var(--fs-caption);
font-weight: 540;
letter-spacing: 0.01em;
color: var(--text-3);
}
.menu-row {
@@ -164,7 +159,7 @@
transition: background var(--motion-fast) var(--ease-out), color var(--motion-fast) var(--ease-out);
}
.menu-row:hover { background: var(--hover); color: var(--text-1); }
.menu-row.active { background: var(--panel-3); color: var(--text-1); font-weight: 540; }
.menu-row.active { background: var(--panel-3); color: var(--text-1); }
.menu-row.danger { color: var(--red); }
.menu-row.danger:hover { background: rgba(210, 59, 59, 0.1); color: var(--red); }
.menu-row .menu-check { margin-left: auto; color: var(--accent); display: inline-flex; }
+14 -15
View File
@@ -158,7 +158,7 @@ export function ApprovalsPage({ snapshot, actions, navigate, focus }: PageProps)
{decided.length > 0 && (
<>
<div className="section-label" style={{ margin: "32px 0 10px" }}>{t("Recently decided")}</div>
{driftError && <div style={{ color: "var(--red)", fontSize: 13, marginBottom: 8 }}>{t("Could not check approved content: {message}", { message: driftError })}</div>}
{driftError && <div style={{ color: "var(--red)", fontSize: "var(--fs-body)", marginBottom: 8 }}>{t("Could not check approved content: {message}", { message: driftError })}</div>}
<div className="card" style={{ padding: 0, overflow: "hidden" }}>
{shownDecided.map((approval, index) => (
<DecidedRow
@@ -176,7 +176,7 @@ export function ApprovalsPage({ snapshot, actions, navigate, focus }: PageProps)
</div>
{decided.length > decidedLimit && (
<div className="row" style={{ justifyContent: "center", marginTop: 12, gap: 10 }}>
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{t("Showing {shown} of {total}", { shown: Math.min(decidedLimit, decided.length), total: decided.length })}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("Showing {shown} of {total}", { shown: Math.min(decidedLimit, decided.length), total: decided.length })}</span>
<Button size="small" onClick={() => setDecidedLimit((limit) => limit + DECIDED_PAGE)}>{t("Show earlier decisions")}</Button>
</div>
)}
@@ -232,7 +232,7 @@ function StatTile({ label, value, tone }: { label: string; value: string; tone?:
<div className="card-label" style={{ marginBottom: 6 }}>{label}</div>
<div
className="num"
style={{ fontSize: 18, fontWeight: 600, color: tone === "amber" ? "var(--amber)" : "var(--text-1)", letterSpacing: "-0.02em" }}
style={{ fontSize: "var(--fs-display)", color: tone === "amber" ? "var(--amber)" : "var(--text-1)" }}
>
{value}
</div>
@@ -266,7 +266,6 @@ function ApprovalRow({
<div
style={{
border: "1px solid var(--border)",
borderRadius: 12,
background: "var(--panel)",
padding: 18,
marginBottom: 10,
@@ -276,20 +275,20 @@ function ApprovalRow({
alignItems: "flex-start",
}}
>
<div style={{ width: 3, alignSelf: "stretch", background: tone.color, borderRadius: 2 }} />
<div style={{ width: 3, alignSelf: "stretch", background: tone.color }} />
<div style={{ minWidth: 0 }}>
<div className="row" style={{ marginBottom: 4 }}>
<span style={{ fontSize: 12, color: tone.color, fontWeight: 540, letterSpacing: "0.02em" }}>{tone.label}</span>
<span style={{ fontSize: "var(--fs-body)", color: tone.color }}>{tone.label}</span>
<span style={{ color: "var(--text-4)" }}>·</span>
<Pill>{approvalKindLabel(approval.kind)}</Pill>
</div>
<div style={{ fontSize: 15, fontWeight: 540, letterSpacing: "-0.01em", marginBottom: 4 }}>{approval.title}</div>
<div style={{ fontSize: 14, color: "var(--text-2)", lineHeight: 1.5, marginBottom: 12, whiteSpace: "pre-wrap" }}>
<div style={{ fontSize: "var(--fs-body)", marginBottom: 4 }}>{approval.title}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-2)", lineHeight: 1.5, marginBottom: 12, whiteSpace: "pre-wrap" }}>
{approval.details}
</div>
<div className="row" style={{ gap: 8 }}>
<Avatar name={requester} size="sm" bot={isBot} />
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{t("Requested by {requester}", { requester })} · {formatRelative(approval.createdAt)}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("Requested by {requester}", { requester })} · {formatRelative(approval.createdAt)}</span>
</div>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 6, alignItems: "flex-end" }}>
@@ -336,27 +335,27 @@ function DecidedRow({
style={{
gap: 12,
padding: "12px 18px",
fontSize: 14,
fontSize: "var(--fs-body)",
borderBottom: last ? "none" : "1px solid var(--border-soft)",
background: focused ? "var(--accent-soft)" : undefined,
}}
>
<Icon name={approved ? "check" : "x"} size={14} color={approved ? "var(--green)" : superseded ? "var(--text-3)" : "var(--red)"} />
<Icon name={approved ? "check" : "x"} color={approved ? "var(--green)" : superseded ? "var(--text-3)" : "var(--red)"} />
<button
type="button"
className="link-button"
aria-label={t("View record of {title}", { title: approval.title })}
onClick={onView}
style={{ flex: 1, fontWeight: 480, color: "var(--text-1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", textAlign: "left" }}
style={{ flex: 1, color: "var(--text-1)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", textAlign: "left" }}
>
{approval.title}
</button>
{approval.sourceEntityType === "task" && approval.sourceEntityId && (
<button type="button" className="link-button" style={{ fontSize: 12 }} onClick={() => onOpenTask(approval.sourceEntityId!)}>{t("Open task")}</button>
<button type="button" className="link-button" style={{ fontSize: "var(--fs-body)" }} onClick={() => onOpenTask(approval.sourceEntityId!)}>{t("Open task")}</button>
)}
{drift && <Pill tone="amber">{drift === "changed" ? t("Changed since approval") : t("Removed since approval")}</Pill>}
<Avatar name={requester} size="sm" bot />
<div style={{ fontSize: 12, color: "var(--text-3)", width: 180, textAlign: "right", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", width: 180, textAlign: "right", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
{decidedLabel} · {formatRelative(approval.decidedAt ?? approval.createdAt)}{superseded ? "" : ` · ${decider.split(" ")[0]}`}
</div>
</div>
@@ -412,7 +411,7 @@ function BatchSummary({ total, result, onDismiss }: { total: number; result: Bat
return (
<div role="status" className="card" style={{ padding: 14, marginBottom: 16 }}>
<div className="row" style={{ gap: 8 }}>
<span style={{ fontWeight: 600 }}>{t("Approved {n} of {total}.", { n: result.approved.length, total })}</span>
<span>{t("Approved {n} of {total}.", { n: result.approved.length, total })}</span>
<span style={{ marginLeft: "auto" }}><Button size="small" tone="ghost" onClick={onDismiss}>{t("Dismiss")}</Button></span>
</div>
{result.failed.map((failure) => (
+1 -1
View File
@@ -46,7 +46,7 @@ export function ConnectorsPage({ snapshot, actions }: PageProps) {
return (
<div style={{ maxWidth: 1060 }}>
<h2 style={{ margin: "0 0 18px", fontSize: 16, fontWeight: 600 }}>{t("Connectors")}</h2>
<h2 style={{ margin: "0 0 18px", fontSize: "var(--fs-body)" }}>{t("Connectors")}</h2>
{connectError && <ErrorText message={connectError} />}
+4 -4
View File
@@ -90,7 +90,7 @@ export function FilesPage({ snapshot, actions, focus }: PageProps) {
]}
/>
<Button tone="primary" onClick={upload}>
<Icon name="upload" size={16} /> {t("Upload")}
<Icon name="upload" /> {t("Upload")}
</Button>
</TopbarActions>
<h1 className="page-h1">{t("Files")}</h1>
@@ -119,7 +119,7 @@ export function FilesPage({ snapshot, actions, focus }: PageProps) {
<div className="row" style={{ marginBottom: 10 }}>
<div className="section-label">{labelFor(section)}</div>
<div style={{ marginLeft: "auto", fontSize: 12, color: "var(--text-3)" }}>{t("Modified")} ↓</div>
<div style={{ marginLeft: "auto", fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("Modified")} ↓</div>
</div>
{view === "list" ? (
@@ -163,7 +163,7 @@ function FilesFilter({
<Popover
trigger={({ toggle }) => (
<button type="button" className="button ghost" aria-label={t("Filter files")} onClick={toggle}>
<Icon name="filter" size={16} color={scan !== "all" ? "var(--accent)" : "currentColor"} />
<Icon name="filter" color={scan !== "all" ? "var(--accent)" : "currentColor"} />
</button>
)}
>
@@ -173,7 +173,7 @@ function FilesFilter({
{options.map((option) => (
<MenuRow key={option.id} active={scan === option.id} onClick={() => onScan(option.id)}>
{option.label}
{scan === option.id && <span className="menu-check"><Icon name="check" size={16} /></span>}
{scan === option.id && <span className="menu-check"><Icon name="check" /></span>}
</MenuRow>
))}
</>
+24 -27
View File
@@ -1,3 +1,4 @@
import { XpBar } from "../shared/XpBar";
import { runTriggerLabel } from "../i18n/labels";
import { goalProgress, type GoalPace } from "./home/goal-progress";
import { nextUp } from "./home/next-up";
@@ -57,7 +58,7 @@ export function HomePage({ snapshot, actions, navigate }: PageProps) {
return (
<div className="page-wide" style={{ maxWidth: 1240 }}>
<TopbarActions>
<Button tone="primary" onClick={() => setNewTaskOpen(true)}><Icon name="plus" size={16} /> {t("New task")}</Button>
<Button tone="primary" onClick={() => setNewTaskOpen(true)}><Icon name="plus" /> {t("New task")}</Button>
</TopbarActions>
<h1 className="page-h1">{greeting}, {firstName}</h1>
<p className="page-sub">{renderSummary(needsYou.length, agents.length)}</p>
@@ -114,17 +115,15 @@ function GoalCard({
return (
<section className="card">
<div className="card-label" style={{ marginBottom: 12 }}>{t("Quarter goal")}</div>
<div style={{ fontSize: 16, fontWeight: 540, lineHeight: 1.4, letterSpacing: "-0.01em", display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", minHeight: 44 }}>
<div style={{ fontSize: "var(--fs-body)", lineHeight: 1.4, display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden", minHeight: "2.8em" }}>
{goal ? goal.title : t("Set the first goal for {organizationName}.", { organizationName })}
</div>
<div className="row" style={{ alignItems: "baseline", gap: 8, marginTop: 16 }}>
<span className="num" style={{ fontSize: 18, fontWeight: 600 }}>{progress ? `${percent}%` : "—"}</span>
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{progress?.pace ? statusLabel(progress.pace) : t("no target date")}</span>
<span className="num" style={{ fontSize: "var(--fs-display)" }}>{progress ? `${percent}%` : "—"}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{progress?.pace ? statusLabel(progress.pace) : t("no target date")}</span>
{goal && <TargetDate goal={goal} actions={actions} />}
</div>
<div style={{ marginTop: 12, height: 4, background: "var(--panel-3)", borderRadius: 999, overflow: "hidden" }}>
<div style={{ width: `${percent}%`, height: "100%", background: "var(--text-1)", transition: "width var(--motion-slow) var(--ease-out)" }} />
</div>
<div style={{ marginTop: 12 }}><XpBar percent={percent} label={t("Goal progress")} /></div>
{goal?.status === "active" && goal.stalledReason && (
<div className="row" style={{ marginTop: 12, gap: 8, alignItems: "center" }}>
<span className="form-error" role="status" style={{ flex: 1, marginTop: 0 }}>{goal.stalledReason}</span>
@@ -153,23 +152,21 @@ function SpendCard({
<section className="card">
<div className="card-label" style={{ marginBottom: 12 }}>{t("Monthly budget")}</div>
<div className="row" style={{ alignItems: "baseline", gap: 6 }}>
<span className="num" style={{ fontSize: 18, fontWeight: 600 }}>{money(totalBudgetCents)}</span>
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{capCents > 0 ? `/ ${money(capCents)}` : t("allocated")}</span>
</div>
<div style={{ marginTop: 12, height: 4, background: "var(--panel-3)", borderRadius: 999, overflow: "hidden" }}>
<div style={{ width: `${fillPct}%`, height: "100%", background: "var(--text-1)" }} />
<span className="num" style={{ fontSize: "var(--fs-display)" }}>{money(totalBudgetCents)}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{capCents > 0 ? `/ ${money(capCents)}` : t("allocated")}</span>
</div>
<div style={{ marginTop: 12 }}><XpBar percent={fillPct} label={t("Budget allocated")} /></div>
<div style={{ marginTop: 12, display: "flex", flexDirection: "column", gap: 8 }}>
{connected.slice(0, 3).map((provider) => {
const allocatedCents = agents.filter((agent) => agent.modelProviderId === provider.id).reduce((sum, agent) => sum + agent.budgetCents, 0);
return (
<div key={provider.id} className="row" style={{ fontSize: 14 }}>
<div key={provider.id} className="row" style={{ fontSize: "var(--fs-body)" }}>
<span style={{ color: "var(--text-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{provider.label}</span>
<span className="num mono" style={{ marginLeft: "auto", color: "var(--text-1)", fontWeight: 500 }}>{money(allocatedCents)}</span>
<span className="num mono" style={{ marginLeft: "auto", color: "var(--text-1)" }}>{money(allocatedCents)}</span>
</div>
);
})}
{connected.length === 0 && <span style={{ fontSize: 14, color: "var(--text-3)" }}>{t("No providers connected")}</span>}
{connected.length === 0 && <span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("No providers connected")}</span>}
</div>
</section>
);
@@ -191,7 +188,7 @@ function RunActivityCard({
<section className="card">
<div className="row" style={{ marginBottom: 12 }}>
<span className="card-label">{t("Agent runs")}</span>
<button type="button" className="link-button" style={{ marginLeft: "auto", fontSize: 12 }} onClick={onViewAll}>{t("All runs")} →</button>
<button type="button" className="link-button" style={{ marginLeft: "auto", fontSize: "var(--fs-body)" }} onClick={onViewAll}>{t("All runs")} →</button>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
{recent.map((run) => {
@@ -201,15 +198,15 @@ function RunActivityCard({
<div key={run.id} className="row" style={{ gap: 10 }}>
{agent && <Avatar name={agent.name} size="sm" bot />}
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{task?.title ?? run.taskId}</div>
<div style={{ fontSize: 12, color: "var(--text-3)" }}>{agent?.name ?? t("Agent")} · {runTriggerLabel(run.trigger)}</div>
<div style={{ fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{task?.title ?? run.taskId}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{agent?.name ?? t("Agent")} · {runTriggerLabel(run.trigger)}</div>
</div>
<Pill tone={runStateTone(run.state)}>{runStateLabel(run.state)}</Pill>
<span className="mono" style={{ fontSize: 12, color: "var(--text-3)", flexShrink: 0 }}>{formatRelative(run.createdAt)}</span>
<span className="mono" style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", flexShrink: 0 }}>{formatRelative(run.createdAt)}</span>
</div>
);
})}
{recent.length === 0 && <div style={{ fontSize: 14, color: "var(--text-3)" }}>{t("No runs yet")}</div>}
{recent.length === 0 && <div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("No runs yet")}</div>}
</div>
</section>
);
@@ -233,7 +230,7 @@ function RecentMessagesCard({
<section className="card">
<div className="row" style={{ marginBottom: 12 }}>
<span className="card-label">{t("Recent messages")}</span>
<button type="button" className="link-button" style={{ marginLeft: "auto", fontSize: 12 }} onClick={onViewAll}>{t("Open chat")} →</button>
<button type="button" className="link-button" style={{ marginLeft: "auto", fontSize: "var(--fs-body)" }} onClick={onViewAll}>{t("Open chat")} →</button>
</div>
<div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
{recent.map((msg) => {
@@ -247,16 +244,16 @@ function RecentMessagesCard({
<Avatar name={name} size="sm" bot={msg.senderType === "agent"} />
<div style={{ flex: 1, minWidth: 0 }}>
<div className="row" style={{ gap: 6 }}>
<span style={{ fontSize: 14, fontWeight: 540 }}>{name}</span>
{space && <span style={{ fontSize: 12, color: "var(--text-3)" }}>#{space.name}</span>}
<span className="mono" style={{ marginLeft: "auto", fontSize: 12, color: "var(--text-3)", flexShrink: 0 }}>{formatTime(msg.createdAt)}</span>
<span style={{ fontSize: "var(--fs-body)" }}>{name}</span>
{space && <span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>#{space.name}</span>}
<span className="mono" style={{ marginLeft: "auto", fontSize: "var(--fs-body)", color: "var(--text-3)", flexShrink: 0 }}>{formatTime(msg.createdAt)}</span>
</div>
<div style={{ fontSize: 14, color: "var(--text-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", lineHeight: 1.4 }}>{preview}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", lineHeight: 1.4 }}>{preview}</div>
</div>
</div>
);
})}
{recent.length === 0 && <div style={{ fontSize: 14, color: "var(--text-3)" }}>{t("No messages yet")}</div>}
{recent.length === 0 && <div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("No messages yet")}</div>}
</div>
</section>
);
@@ -316,7 +313,7 @@ function TargetDate({ goal, actions }: { goal: GoalRecord; actions: PageProps["a
};
return (
<span style={{ marginLeft: "auto", display: "inline-flex", alignItems: "center", gap: 6 }}>
<input className="input" type="date" aria-label={t("Target date")} value={value} onChange={(event) => change(event.target.value)} style={{ height: 26, padding: "0 6px", fontSize: 12 }} />
<input className="input" type="date" aria-label={t("Target date")} value={value} onChange={(event) => change(event.target.value)} style={{ height: 26, padding: "0 6px", fontSize: "var(--fs-body)" }} />
{error && <span className="form-error" role="alert">{error}</span>}
</span>
);
+1 -2
View File
@@ -30,7 +30,7 @@ export function LibraryPage({ snapshot, actions, focus }: PageProps) {
return (
<div className="split-main">
<aside className="secondary-pane">
<div style={{ fontSize: 14, fontWeight: 600, padding: "4px 8px 14px" }}>{t("Library")}</div>
<div style={{ fontSize: "var(--fs-body)", padding: "4px 8px 14px" }}>{t("Library")}</div>
<div className="nav" style={{ gap: 1 }}>
{TABS.map((item) => (
<button
@@ -49,7 +49,6 @@ export function LibraryPage({ snapshot, actions, focus }: PageProps) {
<div className="content">
<div className="page">
<h1 className="page-h1">{tab === "documents" ? t("Documents") : t("Knowledge")}</h1>
<p className="page-sub">{t("Agents read and write these while working on tasks. Nothing here starts work; a task does.")}</p>
{tab === "documents"
? <DocumentsPanel focusId={focus?.kind === "document" ? focus.id : null} orgId={orgId} employeeId={employee.id} documents={documents} tasks={tasks} actions={actions} />
: <KnowledgePanel focusId={focus?.kind === "knowledge" ? focus.id : null} orgId={orgId} employeeId={employee.id} entries={entries} scopes={scopes} actions={actions} />}
+55 -43
View File
@@ -5,9 +5,14 @@ import { activeOrgId, requireActiveEmployee } from "./types";
import { hashString, renderOffice, type RenderPerson } from "./office/office-renderer";
import { OfficeSimulation, cameraFor, type MoveInput } from "./office/simulation";
import { AgentDetailCard } from "./office/AgentDetailCard";
import { officeActivityLabel } from "../i18n/labels";
import { officeStateLabel } from "../i18n/labels";
import { cardPositionFor, CARD_FALLBACK_H } from "./office/agent-card-position";
import type { AgentActivity, Camera, OfficeAgentInput, Vec } from "./office/office-types";
import { artScale, isoFrame, isoPixelSize, pickAt, toIso, type IsoFrame } from "./office/iso";
import { dayPart, season } from "../shared/palette-clock";
import { pixelScale } from "../shared/pixel-scale";
import type { Camera, OfficeAgentInput } from "./office/office-types";
import { officeStatus } from "./office/agent-state";
import { ceoIdOf, officeRoster } from "./office/roster";
import { t } from "../i18n/i18n";
const FPS_INTERVAL = 1000 / 24;
@@ -29,6 +34,8 @@ export function OfficePage({ snapshot }: PageProps) {
const canvasRef = useRef<HTMLCanvasElement>(null);
const keysRef = useRef<MoveInput>({ up: false, down: false, left: false, right: false });
const cameraRef = useRef<Camera>({ x: 0, y: 0 });
/** How the last frame mapped plan to screen, for turning clicks into picks. */
const viewRef = useRef<{ frame: IsoFrame; pixel: number } | null>(null);
const selectedIdRef = useRef<string | null>(null);
const cardBoxRef = useRef<HTMLDivElement>(null);
const [selectedId, setSelectedId] = useState<string | null>(null);
@@ -36,10 +43,9 @@ export function OfficePage({ snapshot }: PageProps) {
if (simRef.current === null) simRef.current = new OfficeSimulation();
const inputs = useMemo<OfficeAgentInput[]>(() => {
const orgAgents = snapshot.agents
.filter((agent) => agent.orgId === orgId && agent.lifecycle === "active")
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
const orgTasks = snapshot.tasks.filter((task) => task.orgId === orgId && isBusinessTask(task));
const orgAgents = officeRoster(snapshot.agents.filter((agent) => agent.orgId === orgId));
const allTasks = snapshot.tasks.filter((task) => task.orgId === orgId);
const orgTasks = allTasks.filter(isBusinessTask);
return orgAgents.map((agent) => ({
id: agent.id,
name: agent.name,
@@ -47,10 +53,10 @@ export function OfficePage({ snapshot }: PageProps) {
title: agent.title,
department: agent.department,
roleLevel: agent.roleLevel,
activity: resolveActivity(snapshot.chatPresence, snapshot.taskRuns, agent.id),
status: officeStatus(agent.id, { runs: snapshot.taskRuns, tasks: allTasks, approvals: snapshot.approvals }),
taskTitle: orgTasks.find((task) => task.assigneeAgentId === agent.id && task.status === "in_progress")?.title ?? null,
}));
}, [snapshot.agents, snapshot.tasks, snapshot.chatPresence, snapshot.taskRuns, orgId]);
}, [snapshot.agents, snapshot.tasks, snapshot.approvals, snapshot.taskRuns, orgId]);
useEffect(() => {
simRef.current!.sync(inputs);
@@ -112,6 +118,8 @@ export function OfficePage({ snapshot }: PageProps) {
let running = true;
let raf = 0;
let lastFrame = 0;
const scene = document.createElement("canvas");
const lightMap = document.createElement("canvas");
const tick = (now: number) => {
if (!running) return;
@@ -134,13 +142,16 @@ export function OfficePage({ snapshot }: PageProps) {
const sim = simRef.current!;
sim.step(elapsed, keysRef.current);
const focus = sim.player ? { x: sim.player.x, y: sim.player.y } : { x: sim.plan.world.w / 2, y: viewH / 2 };
const camera = cameraFor(sim.plan.world, viewW, viewH, focus);
const frame = isoFrame(sim.plan.world);
const pixel = isoPixelSize(dpr);
const focus = sim.player ? { x: sim.player.x, y: sim.player.y } : { x: sim.plan.world.w / 2, y: sim.plan.world.h / 2 };
const camera = cameraFor(frame.size, viewW / pixel, viewH / pixel, toIso(frame, focus));
cameraRef.current = camera;
viewRef.current = { frame, pixel };
const people: RenderPerson[] = sim.agents.map((agent) => ({
id: agent.input.id,
name: agent.input.name,
activity: agent.input.activity,
state: agent.input.status.state,
x: agent.x,
y: agent.y,
desk: agent.isCeo ? sim.plan.ceoDesk : sim.plan.desks[agent.deskIndex!].bounds,
@@ -156,7 +167,7 @@ export function OfficePage({ snapshot }: PageProps) {
people.push({
id: `board:${sim.player.employeeId}`,
name: sim.player.name,
activity: "idle",
state: "idle",
x: sim.player.x,
y: sim.player.y,
desk: null,
@@ -169,7 +180,23 @@ export function OfficePage({ snapshot }: PageProps) {
carrying: null,
});
}
renderOffice(ctx, viewW, viewH, sim.plan, camera, people, now, new Date(), selectedIdRef.current);
const clock = new Date();
renderOffice(ctx, scene, lightMap, {
frame,
plan: sim.plan,
camera,
pixel,
art: artScale(dpr),
fontScale: pixelScale(dpr),
viewW,
viewH,
people,
timeMs: now,
clock,
dayPart: dayPart(clock),
season: season(clock),
selectedId: selectedIdRef.current,
});
// The detail card rides beside its agent, even while they walk.
const cardBox = cardBoxRef.current;
@@ -178,7 +205,8 @@ export function OfficePage({ snapshot }: PageProps) {
: null;
if (cardBox && selected) {
const cardH = cardBox.offsetHeight || CARD_FALLBACK_H;
const position = cardPositionFor({ x: selected.x, y: selected.y }, camera, viewW, viewH, cardH);
const feet = toIso(frame, selected);
const position = cardPositionFor({ x: (feet.x - camera.x) * pixel, y: (feet.y - camera.y) * pixel }, { x: 0, y: 0 }, viewW, viewH, cardH);
cardBox.style.transform = `translate(${position.left}px, ${position.top}px)`;
cardBox.style.visibility = "visible";
}
@@ -191,28 +219,26 @@ export function OfficePage({ snapshot }: PageProps) {
};
}, []);
const worldPointFrom = (event: MouseEvent<HTMLCanvasElement>): Vec | null => {
/** The agent drawn under the pointer, picked in the same iso pixels the frame was drawn in. */
const agentAt = (event: MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
if (!canvas) return null;
const view = viewRef.current;
if (!canvas || !view) return null;
const bounds = canvas.getBoundingClientRect();
return {
x: event.clientX - bounds.left + cameraRef.current.x,
y: event.clientY - bounds.top + cameraRef.current.y,
const point = {
x: (event.clientX - bounds.left) / view.pixel + Math.round(cameraRef.current.x),
y: (event.clientY - bounds.top) / view.pixel + Math.round(cameraRef.current.y),
};
return pickAt(view.frame, simRef.current!.agents, point);
};
const onCanvasClick = (event: MouseEvent<HTMLCanvasElement>) => {
const point = worldPointFrom(event);
if (!point) return;
const hit = simRef.current!.hitTest(point);
const hit = agentAt(event);
setSelectedId(hit ? hit.input.id : null);
};
const onCanvasMouseMove = (event: MouseEvent<HTMLCanvasElement>) => {
const canvas = canvasRef.current;
const point = worldPointFrom(event);
if (!canvas || !point) return;
canvas.style.cursor = simRef.current!.hitTest(point) ? "pointer" : "default";
event.currentTarget.style.cursor = agentAt(event) ? "pointer" : "default";
};
return (
@@ -227,7 +253,7 @@ export function OfficePage({ snapshot }: PageProps) {
/>
{selectedAgent && (
<div ref={cardBoxRef} style={{ position: "absolute", left: 0, top: 0, willChange: "transform", visibility: "hidden" }}>
<AgentDetailCard agent={selectedAgent} onClose={() => setSelectedId(null)} />
<AgentDetailCard agent={selectedAgent} isCeo={selectedAgent.id === ceoIdOf(inputs)} onClose={() => setSelectedId(null)} />
</div>
)}
<div className="office-toolbar" role="toolbar" aria-label={t("Office tools")}>
@@ -236,26 +262,12 @@ export function OfficePage({ snapshot }: PageProps) {
aria-label={t("Show a person")}
value={selectedId ?? ""}
onChange={(event) => setSelectedId(event.target.value || null)}
style={{ width: 200, height: 30 }}
style={{ width: 200 }}
>
<option value="">{t("Show a person…")}</option>
{inputs.map((input) => <option key={input.id} value={input.id}>{t("{name}, {activity}", { name: input.name, activity: officeActivityLabel(input.activity) })}</option>)}
{inputs.map((input) => <option key={input.id} value={input.id}>{t("{name}, {activity}", { name: input.name, activity: officeStateLabel(input.status.state) })}</option>)}
</select>
<span className="office-legend">{t("Agents with work stay at their desks. Only idle agents walk to coffee, snacks or the meeting table.")}</span>
</div>
</div>
);
}
function resolveActivity(
presence: Array<{ principalType: string; principalId: string; status: string }>,
runs: Array<{ agentId: string | null; state: string }>,
agentId: string,
): AgentActivity {
if (runs.some((run) => run.agentId === agentId && run.state === "running")) return "active";
const record = presence.find((row) => row.principalType === "agent" && row.principalId === agentId);
if (record?.status === "thinking") return "thinking";
if (record?.status === "waiting_approval" || record?.status === "busy") return "busy";
if (record?.status === "active" || record?.status === "online") return "active";
return "idle";
}
+19 -20
View File
@@ -90,8 +90,8 @@ export function RunsPage({ snapshot, actions, navigate, focus }: PageProps) {
<div className="split-main">
<aside className="secondary-pane" style={{ width: 340 }}>
<div style={{ padding: "12px 12px 8px" }}>
<div style={{ fontSize: 14, fontWeight: 600, marginBottom: 8 }}>{t("Runs")}</div>
<div className="row" style={{ gap: 8, marginBottom: 8, fontSize: 12, color: "var(--text-3)" }}>
<div style={{ fontSize: "var(--fs-body)", marginBottom: 8 }}>{t("Runs")}</div>
<div className="row" style={{ gap: 8, marginBottom: 8, fontSize: "var(--fs-body)", color: "var(--text-3)" }}>
<span>{t("{n} queued", { n: queued })}</span><span>·</span><span>{t("{n} running", { n: running })}</span><span>·</span><span>{t("{n} failed", { n: failed })}</span>
</div>
<input
@@ -118,10 +118,10 @@ export function RunsPage({ snapshot, actions, navigate, focus }: PageProps) {
onClick={() => setSelectedId(run.id)}
>
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<div style={{ fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{task?.title ?? run.taskId}
</div>
<div style={{ fontSize: 12, color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{agent?.name ?? t("Agent")} · {runTriggerLabel(run.trigger)}
</div>
</div>
@@ -129,11 +129,11 @@ export function RunsPage({ snapshot, actions, navigate, focus }: PageProps) {
</button>
);
})}
{filtered.length === 0 && <div style={{ padding: 16, fontSize: 14, color: "var(--text-3)" }}>{t("No runs")}</div>}
{filtered.length === 0 && <div style={{ padding: 16, fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("No runs")}</div>}
{historyError && <div className="form-error" role="alert" style={{ padding: "0 16px" }}>{historyError}</div>}
<div style={{ padding: 12, display: "flex", justifyContent: "center" }}>
{olderDone
? <span style={{ fontSize: 12, color: "var(--text-3)" }}>{t("These are all the runs.")}</span>
? <span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("These are all the runs.")}</span>
: <Button size="small" onClick={loadOlder}>{t("Show older runs")}</Button>}
</div>
</div>
@@ -142,7 +142,7 @@ export function RunsPage({ snapshot, actions, navigate, focus }: PageProps) {
{selected ? (
<RunDetail key={selected.id} run={selected} tasks={tasks} agents={agents} providers={providers} actions={actions} onOpenTask={(taskId) => navigate("work", { kind: "task", id: taskId })} />
) : (
<div style={{ display: "grid", placeItems: "center", height: "100%", color: "var(--text-3)", fontSize: 14 }}>
<div style={{ display: "grid", placeItems: "center", height: "100%", color: "var(--text-3)", fontSize: "var(--fs-body)" }}>
{t("Select a run")}
</div>
)}
@@ -190,10 +190,10 @@ function RunDetail({ run, tasks, agents, providers, actions, onOpenTask }: {
<div className="row" style={{ gap: 10, marginBottom: 16 }}>
{agent && <Avatar name={agent.name} size="sm" bot />}
<div>
<button type="button" className="link-button" style={{ fontSize: 16, fontWeight: 600 }} aria-label={t("Open task {title}", { title: task?.title ?? run.taskId })} onClick={() => onOpenTask(run.taskId)}>
<button type="button" className="link-button" style={{ fontSize: "var(--fs-body)" }} aria-label={t("Open task {title}", { title: task?.title ?? run.taskId })} onClick={() => onOpenTask(run.taskId)}>
{task?.title ?? run.taskId}
</button>
<div style={{ fontSize: 12, color: "var(--text-3)" }}>{run.id}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{run.id}</div>
</div>
<Pill tone={runTone(run.state)}>{runLabel(run.state)}</Pill>
{run.state === "running" && <Button size="small" onClick={stop} disabled={busy}>{t("Stop")}</Button>}
@@ -201,13 +201,13 @@ function RunDetail({ run, tasks, agents, providers, actions, onOpenTask }: {
{run.state === "failed" && <Button size="small" onClick={again} disabled={busy}>{busy ? t("Running…") : t("Retry")}</Button>}
{(run.state === "stopped" || run.state === "superseded") && <Button size="small" onClick={again} disabled={busy}>{busy ? t("Running…") : t("Resume")}</Button>}
</div>
{run.state === "queued" && <div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 8 }}>{t("A cancelled session can start again on the next heartbeat; block the task to keep it stopped.")}</div>}
{run.state === "queued" && <div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", marginBottom: 8 }}>{t("A cancelled session can start again on the next heartbeat; block the task to keep it stopped.")}</div>}
{(run.state === "failed" || run.state === "stopped" || run.state === "superseded") && (
<div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 8 }}>{t("A new session on the task picks up from what earlier sessions did and where they stopped.")}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", marginBottom: 8 }}>{t("A new session on the task picks up from what earlier sessions did and where they stopped.")}</div>
)}
{controlError && <div className="form-error" role="alert">{controlError}</div>}
<div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "8px 16px", fontSize: 14, marginBottom: 20 }}>
<div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "8px 16px", fontSize: "var(--fs-body)", marginBottom: 20 }}>
<MetaLabel>{t("Agent")}</MetaLabel><div>{agent?.name ?? "—"} ({agent?.role ?? "—"})</div>
<MetaLabel>{t("Provider")}</MetaLabel><div>{provider?.label ?? "—"}</div>
<MetaLabel>{t("Model")}</MetaLabel><div>{run.runModel ?? t("Chosen when the session starts")}</div>
@@ -216,7 +216,7 @@ function RunDetail({ run, tasks, agents, providers, actions, onOpenTask }: {
{run.startedAt && (<><MetaLabel>{t("Started")}</MetaLabel><div>{formatRelative(run.startedAt)}</div></>)}
{run.completedAt && (<><MetaLabel>{t("Completed")}</MetaLabel><div>{formatRelative(run.completedAt)}</div></>)}
{durationMs !== null && (<><MetaLabel>{t("Duration")}</MetaLabel><div>{formatDuration(durationMs)}</div></>)}
<MetaLabel>{t("Context")}</MetaLabel><div className="mono" style={{ fontSize: 12, overflow: "hidden", textOverflow: "ellipsis" }}>{run.executionContextId}</div>
<MetaLabel>{t("Context")}</MetaLabel><div className="mono" style={{ fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis" }}>{run.executionContextId}</div>
</div>
<RunRequestList loaded={loadedRequests} />
@@ -224,28 +224,28 @@ function RunDetail({ run, tasks, agents, providers, actions, onOpenTask }: {
{run.state === "superseded" && run.errorMessage && (
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<div className="section-label" style={{ marginBottom: 8 }}>{t("Why it did not run")}</div>
<div style={{ fontSize: 14, color: "var(--text-1)", whiteSpace: "pre-wrap", lineHeight: 1.5 }}>{run.errorMessage}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-1)", whiteSpace: "pre-wrap", lineHeight: 1.5 }}>{run.errorMessage}</div>
</div>
)}
{run.state === "failed" && run.errorMessage && (
<div className="card" style={{ padding: 16, marginBottom: 16, borderColor: "var(--red)" }}>
<div className="section-label" style={{ color: "var(--red)", marginBottom: 8 }}>{t("Error")}</div>
<div style={{ fontSize: 14, color: "var(--text-1)", whiteSpace: "pre-wrap", lineHeight: 1.5 }}>{run.errorMessage}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-1)", whiteSpace: "pre-wrap", lineHeight: 1.5 }}>{run.errorMessage}</div>
</div>
)}
{run.capabilityWarnings && (
<div className="card" style={{ padding: 16, marginBottom: 16, borderColor: "var(--amber)" }}>
<div className="section-label" style={{ color: "var(--amber)", marginBottom: 8 }}>{t("Missing this run")}</div>
<div style={{ fontSize: 14, color: "var(--text-1)", whiteSpace: "pre-wrap", lineHeight: 1.5 }}>{run.capabilityWarnings}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-1)", whiteSpace: "pre-wrap", lineHeight: 1.5 }}>{run.capabilityWarnings}</div>
</div>
)}
{request && (
<div className="card" style={{ padding: 16, marginBottom: 16 }}>
<div className="section-label" style={{ marginBottom: 8 }}>{t("Provider request")}</div>
<div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "8px 16px", fontSize: 14 }}>
<MetaLabel>{t("Request ID")}</MetaLabel><div className="mono" style={{ fontSize: 12, overflow: "hidden", textOverflow: "ellipsis" }}>{request.id}</div>
<div style={{ display: "grid", gridTemplateColumns: "120px 1fr", gap: "8px 16px", fontSize: "var(--fs-body)" }}>
<MetaLabel>{t("Request ID")}</MetaLabel><div className="mono" style={{ fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis" }}>{request.id}</div>
<MetaLabel>{t("Model")}</MetaLabel><div>{request.model}</div>
<MetaLabel>{t("State")}</MetaLabel><div>{requestStateLabel(request.state)}</div>
<MetaLabel>{t("Input chars")}</MetaLabel><div className="num">{request.inputCharCount.toLocaleString()}</div>
@@ -257,7 +257,7 @@ function RunDetail({ run, tasks, agents, providers, actions, onOpenTask }: {
<div style={{ marginTop: 12 }}>
<div className="section-label" style={{ marginBottom: 6 }}>{t("Response")}</div>
<div style={{
fontSize: 12,
fontSize: "var(--fs-body)",
color: "var(--text-2)",
whiteSpace: "pre-wrap",
lineHeight: 1.5,
@@ -265,7 +265,6 @@ function RunDetail({ run, tasks, agents, providers, actions, onOpenTask }: {
overflow: "auto",
padding: 10,
background: "var(--panel-3)",
borderRadius: 8,
fontFamily: "var(--font-mono)",
}}>
{request.responseText}
+1 -1
View File
@@ -46,7 +46,7 @@ export function SettingsPage({ snapshot, actions, focus }: PageProps) {
return (
<div className="split-main">
<aside className="secondary-pane">
<div style={{ fontSize: 14, fontWeight: 600, padding: "4px 8px 14px" }}>{t("Settings")}</div>
<div style={{ fontSize: "var(--fs-body)", padding: "4px 8px 14px" }}>{t("Settings")}</div>
<div className="pane-scroll">
<NavGroup items={TABS} active={tab} onChange={(next) => requestLeave(() => setTab(next))} />
</div>
+28 -34
View File
@@ -1,3 +1,4 @@
import { XpBar } from "../shared/XpBar";
import { useRevealObject } from "../shared/reveal";
import { oneOf, usePersistentState } from "../shared/view-state";
import { agentModel } from "../../../shared/agent-model";
@@ -7,6 +8,7 @@ import { AvatarField } from "../shared/AvatarField";
import { TopbarActions } from "../shared/TopbarActions";
import { Dialog } from "../shared/Dialog";
import { OrgChartTree } from "./team/OrgChartTree";
import { AgentModelField } from "./team/AgentModelField";
import type { AgentRecord, EmployeeRecord, ProviderCatalogEntry, ProviderRecord } from "../../../shared/domain";
import type { PageProps } from "./types";
import { activeOrgId, money } from "./types";
@@ -105,9 +107,9 @@ export function TeamPage({ snapshot, actions, focus }: PageProps) {
<div className="page">
<TopbarActions>
<Button tone="ghost" onClick={() => cycleFilter(filter, setFilter)} title={t("Filter")}>
<Icon name="filter" size={16} /> {filterLabel(filter)}
<Icon name="filter" /> {filterLabel(filter)}
</Button>
<Button tone="primary" onClick={openHireDialog}><Icon name="plus" size={16} /> {t("Hire")}</Button>
<Button tone="primary" onClick={openHireDialog}><Icon name="plus" /> {t("Hire")}</Button>
</TopbarActions>
<h1 className="page-h1">{t("Team")}</h1>
<p className="page-sub">
@@ -150,11 +152,13 @@ export function TeamPage({ snapshot, actions, focus }: PageProps) {
{providers.map((provider) => <option key={provider.id} value={provider.id}>{provider.label}</option>)}
</select>
</Field>
<Field label={t("Model")}>
<input className="input" name="modelId" list="hire-model-suggestions" value={hireModelId} disabled={!hireProviderId} placeholder={providers.find((provider) => provider.id === hireProviderId)?.model ?? ""} onChange={(event) => setHireModelId(event.currentTarget.value)} />
</Field>
<ModelSuggestions id="hire-model-suggestions" providerId={hireProviderId} providers={providers} catalog={snapshot.providerCatalog} />
<p style={{ fontSize: 12, color: "var(--text-3)", margin: 0 }}>{t("Leave the model blank to use the provider's default. A changed model applies from the agent's next session.")}</p>
<AgentModelField
provider={providers.find((provider) => provider.id === hireProviderId) ?? null}
entry={catalogEntry(snapshot.providerCatalog, providers, hireProviderId)}
value={hireModelId}
onChange={setHireModelId}
/>
<p style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", margin: 0 }}>{t("Leave the model blank to use the provider's default. A changed model applies from the agent's next session.")}</p>
<Field label={t("Manager")}>
<select className="input" name="managerAgentId" defaultValue="">
<option value="">{t("None")}</option>
@@ -180,13 +184,13 @@ export function TeamPage({ snapshot, actions, focus }: PageProps) {
<Field label={t("Department")}><input className="input" name="department" defaultValue={editingAgent.department} required /></Field>
<Field label={t("Monthly budget")}><input className="input" name="budget" type="number" min="0" step="1" defaultValue={editingAgent.budgetCents / 100} /></Field>
<EditModelFields agent={editingAgent} providers={providers} catalog={snapshot.providerCatalog} />
<p style={{ fontSize: 12, color: "var(--text-3)", margin: 0 }}>{t("Leave the model blank to use the provider's default. A changed model applies from the agent's next session.")}</p>
<p style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", margin: 0 }}>{t("Leave the model blank to use the provider's default. A changed model applies from the agent's next session.")}</p>
<Field label={t("Seniority")}>
{/* The CEO's rank carries company-wide powers, so it is shown, never picked. */}
{editingAgent.roleLevel === "c_suite" ? (
<>
<input type="hidden" name="roleLevel" value="c_suite" />
<div style={{ fontSize: 13, color: "var(--text-2)" }}>{t("CEO: hires officers, grants connectors and skills, and closes goals. This rank cannot be changed.")}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-2)" }}>{t("CEO: hires officers, grants connectors and skills, and closes goals. This rank cannot be changed.")}</div>
</>
) : (
<select className="input" name="roleLevel" defaultValue={editingAgent.roleLevel}>
@@ -259,7 +263,6 @@ function buildRoster(
return rows;
}
/** The placeholder names the default of the provider picked now, which is the model a blank field will follow. */
function EditModelFields({ agent, providers, catalog }: { agent: AgentRecord; providers: ProviderRecord[]; catalog: ProviderCatalogEntry[] }) {
const [providerId, setProviderId] = useState(agent.modelProviderId ?? "");
const [modelId, setModelId] = useState(agent.modelId ?? "");
@@ -271,23 +274,20 @@ function EditModelFields({ agent, providers, catalog }: { agent: AgentRecord; pr
{providers.map((provider) => <option key={provider.id} value={provider.id}>{provider.label}</option>)}
</select>
</Field>
<Field label={t("Model")}>
<input className="input" name="modelId" value={modelId} onChange={(event) => setModelId(event.currentTarget.value)} disabled={!providerId} placeholder={providers.find((provider) => provider.id === providerId)?.model ?? ""} list="edit-model-suggestions" />
</Field>
<ModelSuggestions id="edit-model-suggestions" providerId={providerId} providers={providers} catalog={catalog} />
<AgentModelField
provider={providers.find((provider) => provider.id === providerId) ?? null}
entry={catalogEntry(catalog, providers, providerId)}
value={modelId}
onChange={setModelId}
/>
</>
);
}
/** Suggests only the picked provider's models; a model from another provider would mean nothing here. */
function ModelSuggestions({ id, providerId, providers, catalog }: { id: string; providerId: string; providers: ProviderRecord[]; catalog: ProviderCatalogEntry[] }) {
/** The catalog entry of the provider picked now. */
function catalogEntry(catalog: ProviderCatalogEntry[], providers: ProviderRecord[], providerId: string): ProviderCatalogEntry | null {
const providerKey = providers.find((provider) => provider.id === providerId)?.providerKey;
const models = catalog.find((entry) => entry.key === providerKey)?.models ?? [];
return (
<datalist id={id}>
{models.map((model) => <option key={model.id} value={model.id}>{model.name}</option>)}
</datalist>
);
return catalog.find((entry) => entry.key === providerKey) ?? null;
}
function RosterRow({ row, last, onEdit }: { row: RosterEntry; last: boolean; onEdit: (() => void) | null }) {
@@ -300,8 +300,8 @@ function RosterRow({ row, last, onEdit }: { row: RosterEntry; last: boolean; onE
<div className="row" style={{ gap: 10, minWidth: 0 }}>
<Avatar name={row.name} size="sm" bot={!row.human} />
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.name}</div>
<div style={{ fontSize: 12, color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.role}</div>
<div style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.name}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.role}</div>
</div>
</div>
<div style={{ color: "var(--text-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{row.dept}</div>
@@ -309,7 +309,7 @@ function RosterRow({ row, last, onEdit }: { row: RosterEntry; last: boolean; onE
style={{
color: "var(--text-2)",
fontFamily: row.human ? "inherit" : "var(--font-mono)",
fontSize: row.human ? 13 : 12,
fontSize: "var(--fs-body)",
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
@@ -322,16 +322,10 @@ function RosterRow({ row, last, onEdit }: { row: RosterEntry; last: boolean; onE
<span style={{ color: "var(--text-4)" }}>—</span>
) : (
<div className="row" style={{ gap: 8 }}>
<div style={{ flex: 1, height: 3, background: "var(--panel-3)", borderRadius: 2, overflow: "hidden", maxWidth: 100 }}>
<div
style={{
width: `${row.budgetCapCents && row.budgetCapCents > 0 ? Math.min(100, Math.round((row.budgetCents / row.budgetCapCents) * 100)) : 0}%`,
height: "100%",
background: "var(--text-2)",
}}
/>
<div style={{ flex: 1, maxWidth: 100 }}>
<XpBar percent={row.budgetCapCents && row.budgetCapCents > 0 ? (row.budgetCents / row.budgetCapCents) * 100 : 0} label={t("Budget compared with the largest agent budget")} />
</div>
<span className="num mono" style={{ fontSize: 12, color: "var(--text-3)" }}>{money(row.budgetCents)}</span>
<span className="num mono" style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{money(row.budgetCents)}</span>
</div>
)}
</div>
+13 -17
View File
@@ -108,12 +108,11 @@ export function WorkPage({ snapshot, actions, navigate, focus }: PageProps) {
onPriority={setPriorityFilter}
onAssignee={setAssigneeFilter}
/>
<Button tone="ghost" onClick={() => setNewGoalOpen(true)}><Icon name="plus" size={16} /> {t("Goal")}</Button>
<Button tone="ghost" onClick={() => setNewProjectOpen(true)}><Icon name="plus" size={16} /> {t("Project")}</Button>
<Button tone="primary" onClick={() => setNewTaskOpen(true)}><Icon name="plus" size={16} /> {t("New task")}</Button>
<Button tone="ghost" onClick={() => setNewGoalOpen(true)}><Icon name="plus" /> {t("Goal")}</Button>
<Button tone="ghost" onClick={() => setNewProjectOpen(true)}><Icon name="plus" /> {t("Project")}</Button>
<Button tone="primary" onClick={() => setNewTaskOpen(true)}><Icon name="plus" /> {t("New task")}</Button>
</TopbarActions>
<h1 className="page-h1">{t("Work")}</h1>
<p className="page-sub">{t("Only a task runs: an agent picks it up and does the work. Goals and projects group tasks; documents and knowledge are what agents read and write along the way.")}</p>
{scope && (
<div className="row" style={{ gap: 8, marginBottom: 8 }}>
<Pill>
@@ -121,7 +120,7 @@ export function WorkPage({ snapshot, actions, navigate, focus }: PageProps) {
? t("Goal: {title}", { title: goals.find((goal) => goal.id === scope.id)?.title ?? scope.id })
: t("Project: {name}", { name: projects.find((project) => project.id === scope.id)?.name ?? scope.id })}
</Pill>
<button type="button" className="link-button" style={{ fontSize: 12 }} onClick={() => setScope(null)}>{t("Show all work")}</button>
<button type="button" className="link-button" style={{ fontSize: "var(--fs-body)" }} onClick={() => setScope(null)}>{t("Show all work")}</button>
</div>
)}
<p className="page-sub">
@@ -227,7 +226,7 @@ function WorkFilter({
<Popover
trigger={({ toggle }) => (
<button type="button" className="button ghost" aria-label={t("Filter tasks")} onClick={toggle}>
<Icon name="filter" size={16} color={active ? "var(--accent)" : "currentColor"} />
<Icon name="filter" color={active ? "var(--accent)" : "currentColor"} />
</button>
)}
>
@@ -237,19 +236,19 @@ function WorkFilter({
{priorities.map((option) => (
<MenuRow key={option.id} active={priority === option.id} onClick={() => onPriority(option.id)}>
{option.label}
{priority === option.id && <span className="menu-check"><Icon name="check" size={16} /></span>}
{priority === option.id && <span className="menu-check"><Icon name="check" /></span>}
</MenuRow>
))}
<MenuDivider />
<MenuLabel>{t("Assignee")}</MenuLabel>
<MenuRow active={assignee === "all"} onClick={() => onAssignee("all")}>
{t("All assignees")}
{assignee === "all" && <span className="menu-check"><Icon name="check" size={16} /></span>}
{assignee === "all" && <span className="menu-check"><Icon name="check" /></span>}
</MenuRow>
{agents.map((agent) => (
<MenuRow key={agent.id} active={assignee === agent.id} onClick={() => onAssignee(agent.id)}>
{agent.name}
{assignee === agent.id && <span className="menu-check"><Icon name="check" size={16} /></span>}
{assignee === agent.id && <span className="menu-check"><Icon name="check" /></span>}
</MenuRow>
))}
</>
@@ -286,9 +285,9 @@ function BoardView({
return (
<div key={column.id} style={{ display: "flex", flexDirection: "column", minWidth: 0, minHeight: 0 }}>
<div className="row" style={{ padding: "4px 6px 8px", flexShrink: 0 }}>
<span style={{ width: 8, height: 8, borderRadius: 2, background: column.tone, flexShrink: 0 }} />
<span style={{ fontSize: 12, fontWeight: 540 }}>{column.label}</span>
<span className="num" style={{ fontSize: 12, color: "var(--text-3)" }}>{columnTasks.length}</span>
<span style={{ width: 8, height: 8, background: column.tone, flexShrink: 0 }} />
<span style={{ fontSize: "var(--fs-body)" }}>{column.label}</span>
<span className="num" style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{columnTasks.length}</span>
<IconButton icon="plus" label={t("Add task")} onClick={onCreate} />
</div>
<div style={{ flex: 1, minHeight: 0, overflowY: "auto", display: "flex", flexDirection: "column", gap: 8, paddingBottom: 24 }}>
@@ -341,7 +340,6 @@ function TaskCard({
style={{
background: "var(--panel)",
border: "1px solid var(--border)",
borderRadius: 10,
padding: 12,
display: "flex",
flexDirection: "column",
@@ -351,15 +349,13 @@ function TaskCard({
}}
>
<div style={{ display: "flex", alignItems: "flex-start", gap: 6 }}>
{task.priority === "high" && <span style={{ width: 3, height: 14, background: "var(--red)", borderRadius: 2, marginTop: 2, flexShrink: 0 }} />}
{task.priority === "high" && <span style={{ width: 3, height: 14, background: "var(--red)", marginTop: 2, flexShrink: 0 }} />}
<div
style={{
flex: 1,
minWidth: 0,
fontSize: 14,
fontWeight: 480,
fontSize: "var(--fs-body)",
lineHeight: 1.35,
letterSpacing: "-0.005em",
color: task.status === "done" ? "var(--text-3)" : "var(--text-1)",
display: "-webkit-box",
WebkitLineClamp: 3,
@@ -45,14 +45,14 @@ export function ApprovalDetailDialog({
<IconButton icon="x" label={t("Close")} onClick={onClose} />
</div>
<div className="row" style={{ flexWrap: "wrap", gap: 6, marginBottom: 14 }}>
<span style={{ fontSize: 12, color: tone.color, fontWeight: 540, letterSpacing: "0.02em" }}>{tone.label}</span>
<span style={{ fontSize: "var(--fs-body)", color: tone.color }}>{tone.label}</span>
<span style={{ color: "var(--text-4)" }}>·</span>
<Pill>{approvalKindLabel(approval.kind)}</Pill>
</div>
<p style={{ margin: "0 0 16px", color: "var(--text-2)", fontSize: 14, lineHeight: 1.55, whiteSpace: "pre-wrap" }}>
<p style={{ margin: "0 0 16px", color: "var(--text-2)", fontSize: "var(--fs-body)", lineHeight: 1.55, whiteSpace: "pre-wrap" }}>
{approval.details}
</p>
<div style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: "10px 14px", fontSize: 12 }}>
<div style={{ display: "grid", gridTemplateColumns: "100px 1fr", gap: "10px 14px", fontSize: "var(--fs-body)" }}>
<span style={{ color: "var(--text-3)" }}>{t("Requested by")}</span>
<span>{requester}</span>
{approval.sourceEntityType && (
@@ -117,8 +117,8 @@ export function ApprovalRecordDialog({ approval, requester, decider, drift, onCl
<Pill>{approvalKindLabel(approval.kind)}</Pill>
{drift && <Pill tone="amber">{drift === "changed" ? t("Changed since approval") : t("Removed since approval")}</Pill>}
</div>
<p style={{ margin: "0 0 16px", color: "var(--text-2)", fontSize: 14, lineHeight: 1.55, whiteSpace: "pre-wrap" }}>{approval.details}</p>
<div style={{ display: "grid", gridTemplateColumns: "110px 1fr", gap: "10px 14px", fontSize: 12 }}>
<p style={{ margin: "0 0 16px", color: "var(--text-2)", fontSize: "var(--fs-body)", lineHeight: 1.55, whiteSpace: "pre-wrap" }}>{approval.details}</p>
<div style={{ display: "grid", gridTemplateColumns: "110px 1fr", gap: "10px 14px", fontSize: "var(--fs-body)" }}>
<span style={{ color: "var(--text-3)" }}>{t("Requested by")}</span>
<span>{requester} · {formatRelative(approval.createdAt)}</span>
<span style={{ color: "var(--text-3)" }}>{t("Decided by")}</span>
+5 -5
View File
@@ -80,7 +80,7 @@ export function ChatComposer({
return (
<form onSubmit={onSubmit} onInput={() => { if (spaceId && ref.current) noteTyping(spaceId, ref.current.value); }} data-space-id={spaceId ?? undefined} style={{ padding: 14, paddingTop: 4, flexShrink: 0 }}>
<div style={{ border: "1px solid var(--border-strong)", borderRadius: 12, background: "var(--panel)", padding: "10px 12px" }}>
<div style={{ border: "1px solid var(--border-strong)", background: "var(--panel)", padding: "10px 12px" }}>
<MentionTextarea
name="message"
defaultValue={draft.body}
@@ -97,7 +97,7 @@ export function ChatComposer({
<IconButton icon="sparkle" label={t("Commands")} onClick={() => setSlashOpen((open) => !open)} disabled={locked} />
{attachments.map((attachment) => (
<span key={attachment.id} className="pill" style={{ maxWidth: 220 }}>
<Icon name="file" size={14} />
<Icon name="file" />
<span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{attachment.name}</span>
<button
type="button"
@@ -106,13 +106,13 @@ export function ChatComposer({
onClick={() => onAttachmentRemove(attachment.id)}
style={{ display: "inline-flex", border: 0, background: "transparent", padding: 0, color: "var(--text-3)", cursor: "pointer" }}
>
<Icon name="x" size={14} />
<Icon name="x" />
</button>
</span>
))}
<div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 6 }}>
<span className="mono" style={{ fontSize: 12, color: "var(--text-3)" }}>{shortcutLabel("Enter")}</span>
<Button tone="primary" size="small" type="submit" disabled={locked}><Icon name="send" size={12} /> {t("Send")}</Button>
<span className="mono" style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{shortcutLabel("Enter")}</span>
<Button tone="primary" size="small" type="submit" disabled={locked}><Icon name="send" /> {t("Send")}</Button>
</div>
</div>
{send.error && <div className="form-error" role="alert">{t("Not sent: {reason}", { reason: send.error })}</div>}
@@ -239,7 +239,7 @@ export function ChatConversation({
</div>
{!atBottom && (
<button type="button" className="jump-latest" onClick={() => jumpToLatest("smooth")}>
<span aria-hidden style={{ fontSize: 13, lineHeight: 1 }}>↓</span>
<span aria-hidden style={{ fontSize: "var(--fs-body)", lineHeight: 1 }}>↓</span>
{t("Jump to latest")}
</button>
)}
@@ -297,11 +297,11 @@ function ConversationHeader({
};
return (
<header className="row" style={{ height: 52, padding: "0 24px", borderBottom: "1px solid var(--border-soft)", flexShrink: 0 }}>
<Icon name={space.visibility === "restricted" ? "lock" : "hash"} size={15} color="var(--text-3)" />
<span style={{ fontSize: 14, fontWeight: 600 }}>{space.name}</span>
<Icon name={space.visibility === "restricted" ? "lock" : "hash"} color="var(--text-3)" />
<span style={{ fontSize: "var(--fs-body)" }}>{space.name}</span>
<span
style={{
fontSize: 12,
fontSize: "var(--fs-body)",
color: "var(--text-3)",
borderLeft: "1px solid var(--border)",
paddingLeft: 10,
@@ -341,20 +341,20 @@ function MembersButton({ space, members }: { space: ChatSpaceRecord; members: Sp
trigger={({ toggle }) => (
<button type="button" onClick={toggle} aria-label={t("Members ({count})", { count: String(members.length) })} style={{ display: "flex", alignItems: "center", gap: 6, border: 0, background: "transparent", cursor: "pointer", padding: 0 }}>
<AvatarStack names={members.slice(0, 5).map((member) => member.name)} />
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{members.length}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{members.length}</span>
</button>
)}
>
{() => (
// A large roster scrolls inside the window instead of running past it.
<div className="members-roster" style={{ padding: 12, width: 320, maxHeight: "min(480px, calc(100vh - 120px))", overflowY: "auto", display: "flex", flexDirection: "column", gap: 10 }}>
<div style={{ fontSize: 12, color: "var(--text-3)" }}>{spaceReaders(space)}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{spaceReaders(space)}</div>
{members.map((member) => (
<div key={member.id} className="row" style={{ gap: 8, alignItems: "flex-start" }}>
<Avatar name={member.name} size="sm" bot={member.bot} />
<div style={{ minWidth: 0 }}>
<div style={{ fontSize: 13, fontWeight: 540 }}>{member.name}</div>
<div style={{ fontSize: 12, color: "var(--text-3)" }}>{member.duty}</div>
<div style={{ fontSize: "var(--fs-body)" }}>{member.name}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{member.duty}</div>
</div>
</div>
))}
+16 -20
View File
@@ -84,14 +84,14 @@ export function ChatMessageRow({
<Avatar name={name} bot={bot} />
<div style={{ flex: 1, minWidth: 0 }}>
<div className="row" style={{ alignItems: "baseline", gap: 8, marginBottom: 2 }}>
<span style={{ fontSize: 14, fontWeight: 540 }}>{name}</span>
<span className="mono" style={{ fontSize: 12, color: "var(--text-3)" }}>{formatTime(message.createdAt)}</span>
{message.editedAt && !deleted && <span style={{ fontSize: 12, color: "var(--text-3)" }}>{t("(edited)")}</span>}
<span style={{ fontSize: "var(--fs-body)" }}>{name}</span>
<span className="mono" style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{formatTime(message.createdAt)}</span>
{message.editedAt && !deleted && <span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("(edited)")}</span>}
{!editing && (canModify || (onOpenThread && !deleted)) && (
<span style={{ marginLeft: "auto", display: "flex", gap: 2 }}>
{onOpenThread && !deleted && <IconButton icon="chat" label={t("Reply in thread")} size={16} onClick={onOpenThread} />}
{canModify && <IconButton icon="edit" label={t("Edit message")} size={16} onClick={() => setEditing(true)} />}
{canModify && <IconButton icon="x" label={t("Delete message")} size={16} onClick={onDelete} />}
{onOpenThread && !deleted && <IconButton icon="chat" label={t("Reply in thread")} onClick={onOpenThread} />}
{canModify && <IconButton icon="edit" label={t("Edit message")} onClick={() => setEditing(true)} />}
{canModify && <IconButton icon="x" label={t("Delete message")} onClick={onDelete} />}
</span>
)}
</div>
@@ -102,7 +102,7 @@ export function ChatMessageRow({
? t("Replying in thread: {snippet}", { snippet: thread.replyTo.snippet })
: t("Replying to {name}: {snippet}", { name: thread.replyTo.name, snippet: thread.replyTo.snippet })}
onClick={onOpenThread}
style={{ display: "block", maxWidth: "100%", margin: "0 0 4px", padding: 0, border: 0, background: "transparent", color: "var(--text-3)", fontSize: 12, textAlign: "left", cursor: "pointer", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
style={{ display: "block", maxWidth: "100%", margin: "0 0 4px", padding: 0, border: 0, background: "transparent", color: "var(--text-3)", fontSize: "var(--fs-body)", textAlign: "left", cursor: "pointer", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}
>
↳ {thread.replyTo.name === null ? thread.replyTo.snippet : `${thread.replyTo.name}: ${thread.replyTo.snippet}`}
</button>
@@ -113,7 +113,7 @@ export function ChatMessageRow({
</div>
)}
{deleted ? (
<div style={{ fontSize: 14, color: "var(--text-3)", fontStyle: "italic" }}>{t("Message deleted")}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", fontStyle: "italic" }}>{t("Message deleted")}</div>
) : editing ? (
<form onSubmit={submitEdit} onInput={() => setChanged(true)}>
<textarea
@@ -132,7 +132,7 @@ export function ChatMessageRow({
</div>
</form>
) : (
<div style={{ fontSize: 14, color: "var(--text-1)", lineHeight: 1.5, wordBreak: "break-word" }}>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-1)", lineHeight: 1.5, wordBreak: "break-word" }}>
{renderBody(message.bodyMd, messageMentions, context)}
</div>
)}
@@ -146,17 +146,17 @@ export function ChatMessageRow({
</div>
)}
{thread && thread.replyCount > 0 && (
<button type="button" onClick={onOpenThread} style={{ marginTop: 4, padding: 0, border: 0, background: "transparent", color: "var(--accent)", fontSize: 12, cursor: "pointer" }}>
<button type="button" onClick={onOpenThread} style={{ marginTop: 4, padding: 0, border: 0, background: "transparent", color: "var(--accent)", fontSize: "var(--fs-body)", cursor: "pointer" }}>
{thread.replyCount === 1 ? t("1 reply") : t("{count} replies", { count: String(thread.replyCount) })}
</button>
)}
{replyStatuses.filter((status) => status.state !== "replied").map((status) => (
<div key={`${status.agentId}-${status.state}`} role="status" style={{ fontSize: 12, color: status.state === "failed" || status.state === "expired" ? "var(--red)" : "var(--text-3)", marginTop: 4 }}>
<div key={`${status.agentId}-${status.state}`} role="status" style={{ fontSize: "var(--fs-body)", color: status.state === "failed" || status.state === "expired" ? "var(--red)" : "var(--text-3)", marginTop: 4 }}>
{replyStatusText(status, context)}
</div>
))}
{readers.length > 0 && (
<div style={{ fontSize: 12, color: "var(--text-3)", marginTop: 4 }}>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", marginTop: 4 }}>
{t("Read by {names}", { names: readers.join(", ") })}
</div>
)}
@@ -200,8 +200,6 @@ function renderBody(body: string, mentions: ChatMentionRecord[], context: Messag
background: failed ? "rgba(255,100,80,0.1)" : "var(--accent-soft)",
color: failed ? "var(--text-3)" : "var(--accent)",
padding: "1px 5px",
borderRadius: 4,
fontWeight: 500,
textDecoration: failed ? "line-through" : undefined,
}}
>
@@ -235,7 +233,6 @@ function AttachmentCard({ file, handoff = false, onOpen }: { file: FileObjectRec
style={{
maxWidth: 360,
border: "1px solid var(--border)",
borderRadius: 10,
padding: 10,
display: "flex",
alignItems: "center",
@@ -247,25 +244,24 @@ function AttachmentCard({ file, handoff = false, onOpen }: { file: FileObjectRec
style={{
width: 32,
height: 32,
borderRadius: 6,
background: "var(--panel-3)",
color: "var(--text-2)",
display: "grid",
placeItems: "center",
}}
>
<Icon name={file.kind === "folder" ? "folder" : "file"} size={16} />
<Icon name={file.kind === "folder" ? "folder" : "file"} />
</div>
<div style={{ flex: 1, minWidth: 0 }}>
<div className="row" style={{ gap: 6, minWidth: 0 }}>
<span style={{ fontSize: 12, fontWeight: 540, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.name}</span>
<span style={{ fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.name}</span>
{handoff && (
<span className="pill violet" style={{ flexShrink: 0 }}>
<Icon name="bot" size={10} /> {t("AI → AI")}
<Icon name="bot" /> {t("AI → AI")}
</span>
)}
</div>
<div style={{ fontSize: 12, color: "var(--text-3)" }}>{fileKindLabel(file.kind)}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{fileKindLabel(file.kind)}</div>
</div>
{canOpen && <IconButton icon="arrowUpRight" label={t("Open {name}", { name: file.name })} onClick={onOpen ?? undefined} />}
</div>
+4 -6
View File
@@ -84,7 +84,7 @@ export function ChatSidebar({
return (
<aside className="secondary-pane" style={{ width: paneWidth, position: "relative" }}>
<div className="row" style={{ padding: "4px 8px 12px" }}>
<div style={{ fontSize: 14, fontWeight: 600 }}>{t("Messages")}</div>
<div style={{ fontSize: "var(--fs-body)" }}>{t("Messages")}</div>
<IconButton icon="plus" label={t("New space")} onClick={onCreateSpace} />
</div>
<div className="pane-scroll">
@@ -147,7 +147,6 @@ function ConversationRow({
style={{
width: 22,
height: 22,
borderRadius: 6,
background: "var(--panel-3)",
display: "inline-flex",
alignItems: "center",
@@ -156,14 +155,13 @@ function ConversationRow({
marginTop: 2,
}}
>
<Icon name={conversation.space.visibility === "restricted" ? "lock" : "hash"} size={13} color="var(--text-3)" />
<Icon name={conversation.space.visibility === "restricted" ? "lock" : "hash"} color="var(--text-3)" />
</span>
)}
<span style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", gap: 1 }}>
<span className="row" style={{ gap: 8 }}>
<span
style={{
fontWeight: conversation.unread > 0 ? 600 : 520,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
@@ -174,14 +172,14 @@ function ConversationRow({
{conversation.title}
</span>
{conversation.isCeo && <span className="convo-ceo-badge">{t("CEO")}</span>}
<span style={{ fontSize: 11, color: "var(--text-3)", flexShrink: 0 }}>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", flexShrink: 0 }}>
{conversation.preview ? formatRelative(conversation.lastActivityAt) : ""}
</span>
</span>
<span className="row" style={{ gap: 8 }}>
<span
style={{
fontSize: 12,
fontSize: "var(--fs-body)",
color: "var(--text-3)",
overflow: "hidden",
textOverflow: "ellipsis",
+7 -7
View File
@@ -97,7 +97,7 @@ export function ChatTimeline({
</div>,
);
} else {
elements.push(<div key="history-start" style={{ textAlign: "center", fontSize: 12, color: "var(--text-3)", marginBottom: 16 }}>{t("This is the start of the conversation.")}</div>);
elements.push(<div key="history-start" style={{ textAlign: "center", fontSize: "var(--fs-body)", color: "var(--text-3)", marginBottom: 16 }}>{t("This is the start of the conversation.")}</div>);
}
let lastDay = "";
for (const message of visible) {
@@ -138,7 +138,7 @@ function DayDivider({ label }: { label: string }) {
return (
<div className="row" style={{ gap: 12, margin: "8px 0 16px" }}>
<div style={{ flex: 1, height: 1, background: "var(--border-soft)" }} />
<div style={{ fontSize: 12, color: "var(--text-3)", fontWeight: 540 }}>{label}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{label}</div>
<div style={{ flex: 1, height: 1, background: "var(--border-soft)" }} />
</div>
);
@@ -146,14 +146,14 @@ function DayDivider({ label }: { label: string }) {
function ApprovalInline({ approval, onApprove, onDecline }: { approval: ApprovalRecord; onApprove: () => void; onDecline: () => void }) {
return (
<div style={{ margin: "14px 0 18px 44px", maxWidth: 480, border: "1px solid var(--border-strong)", borderRadius: 12, background: "var(--panel)", padding: 14 }}>
<div style={{ margin: "14px 0 18px 44px", maxWidth: 480, border: "1px solid var(--border-strong)", background: "var(--panel)", padding: 14 }}>
<div className="row" style={{ marginBottom: 8 }}>
<Icon name="approve" size={14} color="var(--amber)" />
<span style={{ fontSize: 12, color: "var(--amber)", fontWeight: 540 }}>{t("Approval needed")}</span>
<Icon name="approve" color="var(--amber)" />
<span style={{ fontSize: "var(--fs-body)", color: "var(--amber)" }}>{t("Approval needed")}</span>
<Pill tone={approval.risk === "high" ? "red" : approval.risk === "medium" ? "amber" : undefined}>{riskLabel(approval.risk)}</Pill>
</div>
<div style={{ fontSize: 14, fontWeight: 540, marginBottom: 4 }}>{approval.title}</div>
<div style={{ fontSize: 12, color: "var(--text-3)", marginBottom: 12, lineHeight: 1.5 }}>{approval.details}</div>
<div style={{ fontSize: "var(--fs-body)", marginBottom: 4 }}>{approval.title}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", marginBottom: 12, lineHeight: 1.5 }}>{approval.details}</div>
<div className="row" style={{ gap: 6 }}>
<Button tone="primary" size="small" onClick={onApprove}>{t("Approve")}</Button>
<Button size="small" onClick={onDecline}>{t("Decline")}</Button>
@@ -125,7 +125,6 @@ export function MentionTextarea({
marginBottom: 4,
background: "var(--panel)",
border: "1px solid var(--border)",
borderRadius: 10,
boxShadow: "0 4px 16px rgba(0,0,0,0.12)",
maxHeight: 200,
overflow: "auto",
@@ -149,13 +148,13 @@ export function MentionTextarea({
border: 0,
background: i === index ? "var(--accent-soft)" : "transparent",
cursor: "pointer",
fontSize: 14,
fontSize: "var(--fs-body)",
color: "var(--text-1)",
textAlign: "left",
}}
>
<Avatar name={c.displayName} size="sm" bot={c.bot} />
<span style={{ fontWeight: 500 }}>{c.label}</span>
<span>{c.label}</span>
</button>
))}
</div>
@@ -175,7 +174,7 @@ export function MentionTextarea({
border: 0,
resize: "none",
outline: "none",
fontSize: 14,
fontSize: "var(--fs-body)",
color: "var(--text-1)",
background: "transparent",
padding: 0,
@@ -7,7 +7,7 @@ import { t } from "../../i18n/i18n";
export type SpaceType = "company" | "division" | "department" | "project" | "pod" | "ad_hoc" | "direct";
export type Visibility = "workspace" | "restricted";
const hint = { fontSize: 12, color: "var(--text-3)", margin: 0, lineHeight: 1.5 } as const;
const hint = { fontSize: "var(--fs-body)", color: "var(--text-3)", margin: 0, lineHeight: 1.5 } as const;
/** Each choice says what it changes: who is a member, who can read it, and which agents a message wakes. */
export function NewSpaceDialog({ open, employee, employees, agents, onClose, onSubmit }: {
+1 -1
View File
@@ -74,7 +74,7 @@ export function ThreadPanel({
return (
<aside role="complementary" aria-label={t("Thread")} style={{ width: 360, flexShrink: 0, display: "flex", flexDirection: "column", borderLeft: "1px solid var(--border-soft)", background: "var(--panel)" }}>
<header className="row" style={{ height: 52, padding: "0 16px", borderBottom: "1px solid var(--border-soft)", flexShrink: 0 }}>
<span style={{ fontSize: 14, fontWeight: 600 }}>{t("Thread")}</span>
<span style={{ fontSize: "var(--fs-body)" }}>{t("Thread")}</span>
<span style={{ marginLeft: "auto" }}><IconButton icon="x" label={t("Close thread")} onClick={onClose} /></span>
</header>
<div style={{ flex: 1, overflow: "auto", padding: "16px 16px 8px" }}>
@@ -7,14 +7,14 @@ import type { AccountSync } from "./useConnectorCatalog";
export function AccountSyncNote({ sync, onRetry }: { sync: AccountSync; onRetry: () => void }) {
if (sync.phase === "failed") {
return (
<div role="alert" className="row" style={{ gap: 10, fontSize: 13, marginBottom: 14, color: "var(--red)" }}>
<span style={{ flex: 1, minWidth: 0, wordBreak: "break-word" }}>{t("Account status could not be checked with Composio: {reason}. The statuses below may be out of date.", { reason: sync.message })}</span>
<div role="alert" className="row" style={{ gap: 10, fontSize: "var(--fs-body)", marginBottom: 14, color: "var(--red)" }}>
<span style={{ flex: 1, minWidth: 0, wordBreak: "break-word" }}>{t("Account status could not be checked with Composio, so the statuses below may be out of date. Reason: {reason}", { reason: sync.message })}</span>
<Button size="small" onClick={onRetry}>{t("Retry")}</Button>
</div>
);
}
return (
<div role="status" style={{ fontSize: 12, marginBottom: 14, color: "var(--text-3)" }}>
<div role="status" style={{ fontSize: "var(--fs-body)", marginBottom: 14, color: "var(--text-3)" }}>
{sync.phase === "syncing" ? t("Checking account status with Composio…") : t("Account status checked with Composio at {time}.", { time: formatTime(sync.at) })}
</div>
);
@@ -68,7 +68,7 @@ export function ConnectedList({
const grantable = agents.filter((agent) => agent.roleLevel !== "c_suite" && !grants.some((grant) => grant.agentId === agent.id && grant.toolkitSlug === account.toolkitSlug));
const busy = busySlug !== null;
return (
<div key={account.id} style={{ border: "1px solid var(--border)", borderRadius: 12, padding: 14, background: "var(--panel)" }}>
<div key={account.id} style={{ border: "1px solid var(--border)", padding: 14, background: "var(--panel)" }}>
<div className="row" style={{ gap: 10 }}>
<ToolkitTile
name={account.toolkitName}
@@ -76,8 +76,8 @@ export function ConnectedList({
logoUrl={logoBySlug.get(account.toolkitSlug) ?? null}
size={30}
/>
<span style={{ fontWeight: 600, fontSize: 13.5 }}>{account.toolkitName}</span>
<span style={{ color: "var(--text-2)", fontSize: 12.5 }}>{account.label}</span>
<span style={{ fontSize: "var(--fs-body)" }}>{account.toolkitName}</span>
<span style={{ color: "var(--text-2)", fontSize: "var(--fs-body)" }}>{account.label}</span>
<Pill tone={STATUS_TONE[account.status]} dot>{account.status.charAt(0) + account.status.slice(1).toLowerCase()}</Pill>
{account.pendingAccountId && <Pill tone="amber" dot>{t("Reconnect waiting for authorization")}</Pill>}
<span className="row" style={{ gap: 6, marginLeft: "auto" }}>
@@ -96,7 +96,7 @@ export function ConnectedList({
{holders.map((holder) => (
<span key={holder.agentId} className="row" style={{ gap: 2 }}>
<Pill>{holder.text}</Pill>
<IconButton icon="x" size={12} label={t("Revoke {name}", { name: holder.text })} disabled={busy} onClick={() => onRevoke(holder.agentId, account.toolkitSlug)} />
<IconButton icon="x" label={t("Revoke {name}", { name: holder.text })} disabled={busy} onClick={() => onRevoke(holder.agentId, account.toolkitSlug)} />
</span>
))}
{account.status === "ACTIVE" && grantable.length > 0 && (
@@ -7,7 +7,7 @@ export function SignInStatus({ signIn, onStop, onCheckAgain }: { signIn: SignIn;
const name = signIn.slug;
const failed = signIn.phase === "failed" || signIn.phase === "timed_out";
return (
<div role={failed ? "alert" : "status"} className="row" style={{ gap: 10, fontSize: 13, marginBottom: 14, color: failed ? "var(--red)" : "var(--text-2)" }}>
<div role={failed ? "alert" : "status"} className="row" style={{ gap: 10, fontSize: "var(--fs-body)", marginBottom: 14, color: failed ? "var(--red)" : "var(--text-2)" }}>
<span style={{ flex: 1, minWidth: 0 }}>
{signIn.phase === "waiting" && t("Waiting for the {name} sign-in in your browser (check {check} of {checks}).", { name, check: signIn.check, checks: signIn.checks })}
{signIn.phase === "connected" && t("{name} ({label}) is connected.", { name, label: signIn.label })}
@@ -20,7 +20,7 @@ export function ToolkitTile({ name, slug, logoUrl, size = 34 }: { name: string;
alt=""
width={size}
height={size}
style={{ width: size, height: size, borderRadius: 9, objectFit: "cover", flexShrink: 0 }}
style={{ width: size, height: size, objectFit: "cover", flexShrink: 0 }}
/>
);
}
@@ -29,14 +29,12 @@ export function ToolkitTile({ name, slug, logoUrl, size = 34 }: { name: string;
style={{
width: size,
height: size,
borderRadius: 9,
background: tileColor(slug),
color: "#fff",
display: "inline-flex",
alignItems: "center",
justifyContent: "center",
fontSize: size * 0.44,
fontWeight: 600,
fontSize: "var(--fs-body)",
flexShrink: 0,
}}
>
@@ -67,14 +65,14 @@ export function ToolkitCatalog({
<section>
<div className="row" style={{ marginBottom: 12, gap: 10 }}>
<div className="section-label" style={{ flex: 1 }}>{t("Catalog")}</div>
<div className="row" style={{ gap: 6, background: "var(--panel-2)", borderRadius: 8, padding: "5px 10px", width: 240 }}>
<Icon name="search" size={13} color="var(--text-3)" />
<div className="row" style={{ gap: 6, background: "var(--panel-2)", padding: "5px 10px", width: 240 }}>
<Icon name="search" color="var(--text-3)" />
<input
aria-label={t("Search connectors")}
value={query}
onChange={(event) => setQuery(event.target.value)}
placeholder={t("Search connectors")}
style={{ border: 0, outline: 0, background: "transparent", fontSize: 13, flex: 1, minWidth: 0, color: "var(--text-1)" }}
style={{ border: 0, outline: 0, background: "transparent", fontSize: "var(--fs-body)", flex: 1, minWidth: 0, color: "var(--text-1)" }}
/>
</div>
</div>
@@ -86,7 +84,6 @@ export function ToolkitCatalog({
key={entry.slug}
style={{
border: "1px solid var(--border)",
borderRadius: 12,
padding: 12,
background: "var(--panel)",
display: "flex",
@@ -95,7 +92,7 @@ export function ToolkitCatalog({
}}
>
<ToolkitTile name={entry.name} slug={entry.slug} logoUrl={entry.logoUrl} />
<span style={{ fontWeight: 600, fontSize: 13.5, flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<span style={{ fontSize: "var(--fs-body)", flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{entry.name}
</span>
{connected ? (
+2 -5
View File
@@ -9,7 +9,7 @@ export function FileIcon({ kind, big = false }: { kind: string; big?: boolean })
if (kind === "folder") {
return (
<div style={{ width: big ? 28 : 22, height: big ? 28 : 22, display: "grid", placeItems: "center", color: "var(--text-3)" }}>
<Icon name="folder" size={big ? 22 : 17} />
<Icon name="folder" />
</div>
);
}
@@ -20,14 +20,11 @@ export function FileIcon({ kind, big = false }: { kind: string; big?: boolean })
style={{
width: big ? 28 : 22,
height: big ? 28 : 22,
borderRadius: big ? 6 : 4,
background: `${map.color}14`,
color: map.color,
display: "grid",
placeItems: "center",
fontSize: big ? 9 : 8,
fontWeight: 700,
letterSpacing: 0.5,
fontSize: "var(--fs-body)",
}}
>
{label}
+8 -18
View File
@@ -26,7 +26,7 @@ export function FilesGrid({
onTogglePin: (file: FileObjectRecord) => void;
}) {
return (
<div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(220px, 1fr))", gap: 12 }}>
<div className="inventory">
{files.map((file) => (
<PinnedCard
key={file.id}
@@ -58,22 +58,12 @@ export function PinnedCard({
return (
<div
data-object-id={file.id}
className={canOpen ? "clickable-card" : ""}
className={`inventory-slot ${canOpen ? "clickable-card" : ""}`.trim()}
role={canOpen ? "button" : undefined}
tabIndex={canOpen ? 0 : undefined}
onClick={canOpen ? onOpen : undefined}
onKeyDown={canOpen ? (event) => { if (event.key === "Enter") onOpen(); } : undefined}
style={{
border: "1px solid var(--border)",
borderRadius: 10,
background: "var(--panel)",
padding: 14,
display: "flex",
flexDirection: "column",
gap: 10,
minWidth: 0,
cursor: canOpen ? "pointer" : "default",
}}
style={{ cursor: canOpen ? "pointer" : "default" }}
>
<div className="row" style={{ gap: 10 }}>
<FileIcon kind={file.kind} big />
@@ -83,23 +73,23 @@ export function PinnedCard({
onClick={(event) => { event.stopPropagation(); onUnpin(); }}
style={{ marginLeft: "auto", padding: 4, border: 0, background: "transparent", color: file.pinned ? "var(--accent)" : "var(--text-4)", cursor: "pointer" }}
>
<Icon name="pin" size={14} />
<Icon name="pin" />
</button>
</div>
<div style={{ fontSize: 14, fontWeight: 540, letterSpacing: "-0.005em", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<div style={{ fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{file.name}
</div>
<div className="mono" style={{ color: "var(--text-3)", fontSize: 10, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<div className="mono" style={{ color: "var(--text-3)", fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
sha:{shortChecksum(file.sha256)} · obj:{shortObjectRef(file.storagePath)}
</div>
<div className="row" style={{ gap: 6 }}>
<ScanPill file={file} />
<span className="mono" style={{ color: "var(--text-3)", fontSize: 12 }}>{grantCount}</span>
<span className="mono" style={{ color: "var(--text-3)", fontSize: "var(--fs-body)" }}>{grantCount}</span>
</div>
<ScanLabelStrip file={file} />
<div className="row" style={{ gap: 8, marginTop: "auto", minWidth: 0 }}>
<Avatar name={ownerName} size="sm" bot={isAgentOwner(file)} />
<span style={{ fontSize: 12, color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
{formatRelative(file.updatedAt ?? file.createdAt)} · {ownerName.split(" ")[0]}
</span>
</div>
+5 -5
View File
@@ -77,23 +77,23 @@ function FileRow({
<div className="row" style={{ gap: 10, minWidth: 0 }}>
<FileIcon kind={file.kind} />
<div style={{ display: "grid", gap: 3, minWidth: 0 }}>
<span style={{ fontWeight: 480, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.name}</span>
<span className="mono" style={{ color: "var(--text-3)", fontSize: 10, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
<span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{file.name}</span>
<span className="mono" style={{ color: "var(--text-3)", fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>
sha:{shortChecksum(file.sha256)} · obj:{shortObjectRef(file.storagePath)}
</span>
</div>
{file.pinned && <Pill tone="violet" dot>{t("Pinned")}</Pill>}
</div>
<div className="num mono" style={{ color: "var(--text-3)", fontSize: 12 }}>{formatBytes(file.sizeBytes)}</div>
<div className="num mono" style={{ color: "var(--text-3)", fontSize: "var(--fs-body)" }}>{formatBytes(file.sizeBytes)}</div>
<div className="row" style={{ gap: 8, minWidth: 0 }}>
<Avatar name={owner} size="sm" bot={isAgentOwner(file)} />
<span style={{ color: "var(--text-2)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{owner}</span>
</div>
<div className="row" style={{ gap: 6, minWidth: 0 }}>
<ScanPill file={file} />
<span className="mono" style={{ color: "var(--text-3)", fontSize: 12 }}>{grantCount}</span>
<span className="mono" style={{ color: "var(--text-3)", fontSize: "var(--fs-body)" }}>{grantCount}</span>
</div>
<div style={{ color: "var(--text-3)", fontSize: 12 }}>{formatRelative(file.updatedAt ?? file.createdAt)}</div>
<div style={{ color: "var(--text-3)", fontSize: "var(--fs-body)" }}>{formatRelative(file.updatedAt ?? file.createdAt)}</div>
<div style={{ textAlign: "right" }} onClick={(event) => event.stopPropagation()}>
<Popover trigger={({ toggle }) => <IconButton icon="more" label={t("Actions for {name}", { name: file.name })} onClick={toggle} />}>
{(close) => (
+3 -2
View File
@@ -1,4 +1,5 @@
import { Icon } from "../../shared/ui";
import type { IconName } from "../../shared/Icon";
import type { AgentRecord, FileObjectRecord } from "../../../../shared/domain";
import { isRecent, type Section } from "./file-helpers";
import { t } from "../../i18n/i18n";
@@ -84,7 +85,7 @@ function TreeItem({
active,
onClick,
}: {
icon: string;
icon: IconName;
label: string;
count: number;
active: boolean;
@@ -92,7 +93,7 @@ function TreeItem({
}) {
return (
<button type="button" aria-current={active ? "true" : undefined} className={`nav-item ${active ? "active" : ""}`.trim()} onClick={onClick}>
<span className="icon-box"><Icon name={icon} size={18} /></span>
<span className="icon-box"><Icon name={icon} /></span>
<span>{label}</span>
<span className="nav-badge num">{count}</span>
</button>
+47 -34
View File
@@ -4,7 +4,8 @@ import { useState, type ReactNode, type KeyboardEvent } from "react";
import type { AgentRecord, TaskRecord } from "../../../../shared/domain";
import { t } from "../../i18n/i18n";
const CHART_H = 116;
/** Plot height; axis labels sit below it as HTML text. */
const PLOT_H = 100;
const CHART_W = 260;
const BAR_GAP = 4;
@@ -30,7 +31,7 @@ function ChartCard({ title, readout, values, point, onPoint, children }: {
};
return (
<section className="card metric-card" aria-label={title}>
<div className="row" style={{ marginBottom: 12, gap: 8 }}>
<div style={{ display: "grid", gap: 4, marginBottom: 12 }}>
<span className="card-label">{title}</span>
<span className="metric-readout num" aria-live="polite">{readout}</span>
</div>
@@ -60,28 +61,27 @@ export function AgentWorkloadChart({ agents, tasks }: { agents: AgentRecord[]; t
return (
<ChartCard title={t("Agent workload")} readout={readout} values={data.map((d) => `${d.label}: ${d.count}`)} point={hover} onPoint={setHover}>
<svg viewBox={`0 0 ${CHART_W} ${CHART_H}`} style={{ width: "100%", height: CHART_H }}>
<svg viewBox={`0 0 ${CHART_W} ${PLOT_H}`} preserveAspectRatio="none" shapeRendering="crispEdges" style={{ width: "100%", height: PLOT_H }}>
{data.map((d, i) => {
const h = (d.count / max) * (CHART_H - 22);
const h = (d.count / max) * (PLOT_H - 6);
const x = i * (barW + BAR_GAP);
return (
<g key={d.key} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<rect x={x} y={0} width={barW} height={CHART_H - 16} fill="transparent" />
<rect x={x} y={0} width={barW} height={PLOT_H} fill="transparent" />
<rect
x={x}
y={CHART_H - h - 16}
y={PLOT_H - h}
width={barW}
height={Math.max(2, h)}
rx={4}
fill="var(--accent)"
opacity={hover === null || hover === i ? 0.85 : 0.32}
style={{ transition: "opacity var(--motion-fast) var(--ease-out)" }}
/>
<text x={x + barW / 2} y={CHART_H - 2} textAnchor="middle" fontSize="9" fill="var(--text-3)">{d.label}</text>
</g>
);
})}
</svg>
<ChartAxis labels={data.map((d) => d.label)} />
</ChartCard>
);
}
@@ -96,28 +96,27 @@ export function RunActivityChart({ days }: { days: UsageDays }) {
return (
<ChartCard title={t("Run activity")} readout={readout} values={buckets.map((b) => `${b.label}: ${b.count}`)} point={hover} onPoint={setHover}>
<svg viewBox={`0 0 ${CHART_W} ${CHART_H}`} style={{ width: "100%", height: CHART_H }}>
<svg viewBox={`0 0 ${CHART_W} ${PLOT_H}`} preserveAspectRatio="none" shapeRendering="crispEdges" style={{ width: "100%", height: PLOT_H }}>
{buckets.map((b, i) => {
const h = (b.count / max) * (CHART_H - 24);
const h = (b.count / max) * (PLOT_H - 6);
const x = i * (barW + BAR_GAP);
return (
<g key={`${b.label}-${i}`} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<rect x={x} y={0} width={barW} height={CHART_H - 16} fill="transparent" />
<rect x={x} y={0} width={barW} height={PLOT_H} fill="transparent" />
<rect
x={x}
y={CHART_H - h - 16}
y={PLOT_H - h}
width={barW}
height={Math.max(2, h)}
rx={4}
fill="var(--text-1)"
opacity={hover === null || hover === i ? 0.82 : 0.28}
style={{ transition: "opacity var(--motion-fast) var(--ease-out)" }}
/>
<text x={x + barW / 2} y={CHART_H - 2} textAnchor="middle" fontSize="9" fill="var(--text-3)">{b.label}</text>
</g>
);
})}
</svg>
<ChartAxis labels={buckets.map((b) => b.label)} />
</ChartCard>
);
}
@@ -139,16 +138,18 @@ export function AcceptanceChart({ days }: { days: UsageDays }) {
readout={t("{accepted} done · {returned} sent back · sessions: {ok} ended, {failed} failed", { accepted, returned, ok: completed, failed })}
values={[judged > 0 ? t("{rate}% of judged work accepted", { rate }) : t("No work judged yet")]}
>
<svg viewBox="0 0 100 100" style={{ width: 96, height: 96, margin: "4px auto", display: "block" }}>
<circle cx="50" cy="50" r="42" fill="none" stroke="var(--panel-3)" strokeWidth="8" />
<circle
cx="50" cy="50" r="42" fill="none" stroke="var(--green)" strokeWidth="8"
strokeDasharray={circumference} strokeDashoffset={offset}
strokeLinecap="round" transform="rotate(-90 50 50)"
style={{ transition: "stroke-dashoffset var(--motion-slow) var(--ease-out)" }}
/>
<text x="50" y="50" textAnchor="middle" dominantBaseline="central" fontSize="20" fontWeight="600" fill="var(--text-1)">{judged > 0 ? `${rate}%` : "—"}</text>
</svg>
<div style={{ position: "relative", width: 96, height: 96, margin: "4px auto" }}>
<svg viewBox="0 0 100 100" shapeRendering="crispEdges" style={{ width: 96, height: 96, display: "block" }}>
<circle cx="50" cy="50" r="42" fill="none" stroke="var(--panel-3)" strokeWidth="8" />
<circle
cx="50" cy="50" r="42" fill="none" stroke="var(--green)" strokeWidth="8"
strokeDasharray={circumference} strokeDashoffset={offset}
transform="rotate(-90 50 50)"
style={{ transition: "stroke-dashoffset var(--motion-slow) var(--ease-out)" }}
/>
</svg>
<span className="num" style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", fontSize: "var(--fs-display)" }}>{judged > 0 ? `${rate}%` : "—"}</span>
</div>
</ChartCard>
);
}
@@ -161,7 +162,7 @@ export function CostTrendChart({ days }: { days: UsageDays }) {
const max = Math.max(1, ...tokenBuckets.map((b) => b.tokens));
const coords = tokenBuckets.map((b, i) => ({
x: (i / 6) * (CHART_W - 10) + 5,
y: CHART_H - 20 - (b.tokens / max) * (CHART_H - 30),
y: PLOT_H - 4 - (b.tokens / max) * (PLOT_H - 8),
b,
}));
const points = coords.map((c) => `${c.x},${c.y}`).join(" ");
@@ -175,20 +176,32 @@ export function CostTrendChart({ days }: { days: UsageDays }) {
return (
<ChartCard title={t("Token usage")} readout={readout} values={tokenBuckets.map((b) => `${b.label}: ${compact(b.tokens)}`)} point={hover} onPoint={setHover}>
<svg viewBox={`0 0 ${CHART_W} ${CHART_H}`} style={{ width: "100%", height: CHART_H }}>
<polyline points={points} fill="none" stroke="var(--accent)" strokeWidth="2" strokeLinejoin="round" strokeLinecap="round" />
{coords.map((c, i) => (
<g key={`${c.b.label}-${i}`} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<circle cx={c.x} cy={c.y} r="9" fill="transparent" />
<circle cx={c.x} cy={c.y} r={hover === i ? 4 : 3} fill="var(--accent)" style={{ transition: "r var(--motion-fast) var(--ease-out)" }} />
<text x={c.x} y={CHART_H - 2} textAnchor="middle" fontSize="9" fill="var(--text-3)">{c.b.label}</text>
</g>
))}
<svg viewBox={`0 0 ${CHART_W} ${PLOT_H}`} shapeRendering="crispEdges" style={{ width: "100%", height: PLOT_H }}>
<polyline points={points} fill="none" stroke="var(--accent)" strokeWidth="2" />
{coords.map((c, i) => {
const side = hover === i ? 8 : 6;
return (
<g key={`${c.b.label}-${i}`} onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}>
<rect x={c.x - 9} y={c.y - 9} width={18} height={18} fill="transparent" />
<rect x={c.x - side / 2} y={c.y - side / 2} width={side} height={side} fill="var(--accent)" />
</g>
);
})}
</svg>
<ChartAxis labels={tokenBuckets.map((b) => b.label)} />
</ChartCard>
);
}
/** Axis labels as pixel text, one evenly spaced cell per datum under the plot. */
function ChartAxis({ labels }: { labels: string[] }) {
return (
<div aria-hidden="true" style={{ display: "flex", marginTop: 2, fontSize: "var(--fs-caption)", color: "var(--text-3)" }}>
{labels.map((label, index) => <span key={index} style={{ flex: 1, textAlign: "center", overflow: "hidden", whiteSpace: "nowrap" }}>{label}</span>)}
</div>
);
}
function compact(count: number): string {
if (count >= 1_000_000) return `${(count / 1_000_000).toFixed(1)}M`;
if (count >= 1000) return `${(count / 1000).toFixed(count >= 10000 ? 0 : 1)}k`;
+5 -5
View File
@@ -5,8 +5,8 @@ import { Button, Icon, Pill } from "../../shared/ui";
import type { NextUpItem } from "./next-up";
const SHOWN = 3;
const TITLE = { fontSize: 14, fontWeight: 500, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } as const;
const META = { fontSize: 12, color: "var(--text-3)", margin: "2px 0 8px" } as const;
const TITLE = { fontSize: "var(--fs-body)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" } as const;
const META = { fontSize: "var(--fs-body)", color: "var(--text-3)", margin: "2px 0 8px" } as const;
/** Home's one place for what to look at next: decisions and stopped work in priority order, or else the next task in line. */
export function NextUpCard({
@@ -35,8 +35,8 @@ export function NextUpCard({
</div>
{needsYou.length === 0 ? (
<>
<div className="row" style={{ gap: 8, color: "var(--text-3)", fontSize: 14, marginBottom: 12 }}>
<Icon name="check" size={16} /><span>{t("You're all caught up")}</span>
<div className="row" style={{ gap: 8, color: "var(--text-3)", fontSize: "var(--fs-body)", marginBottom: 12 }}>
<Icon name="check" /><span>{t("You're all caught up")}</span>
</div>
{next?.kind === "next" && (
<div>
@@ -68,7 +68,7 @@ export function NextUpCard({
<Button size="small" onClick={() => onOpenTask(item.task.id)}>{t("Open")}</Button>
</li>
) : null)}
{more > 0 && <li style={{ fontSize: 12, color: "var(--text-3)" }}>{t("{n} more after these", { n: more })}</li>}
{more > 0 && <li style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("{n} more after these", { n: more })}</li>}
</ol>
)}
</section>
@@ -97,14 +97,14 @@ export function DocumentsPanel({
style={{ display: "grid", justifyItems: "start", gap: 2 }}
>
<span>{doc.title}</span>
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{doc.docType} · v{doc.version} · {formatTime(doc.updatedAt)}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{doc.docType} · v{doc.version} · {formatTime(doc.updatedAt)}</span>
</button>
))}
</div>
{selected && (
<article aria-label={selected.title} style={{ minWidth: 0 }}>
<div className="row" style={{ gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
<h2 style={{ margin: 0, fontSize: 18 }}>{shown?.title ?? selected.title}</h2>
<h2 style={{ margin: 0, fontSize: "var(--fs-display)" }}>{shown?.title ?? selected.title}</h2>
<Pill>{selected.docType}</Pill>
<Pill tone={selected.status === "approved" ? "green" : undefined}>{documentStatusLabel(shown?.status ?? selected.status)}</Pill>
</div>
@@ -131,7 +131,7 @@ export function KnowledgePanel({
style={{ display: "grid", justifyItems: "start", gap: 2 }}
>
<span>{entry.topic}</span>
<span style={{ fontSize: 12, color: "var(--text-3)" }}>{entry.category} · {entry.scopeType} · {entry.importance}</span>
<span style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{entry.category} · {entry.scopeType} · {entry.importance}</span>
</button>
))}
</div>
@@ -139,7 +139,7 @@ export function KnowledgePanel({
{selected && (
<article aria-label={selected.topic} style={{ minWidth: 0 }}>
<div className="row" style={{ gap: 8, marginBottom: 8, flexWrap: "wrap" }}>
<h2 style={{ margin: 0, fontSize: 18 }}>{selected.topic}</h2>
<h2 style={{ margin: 0, fontSize: "var(--fs-display)" }}>{selected.topic}</h2>
<Pill>{selected.category}</Pill>
<Pill>{selected.scopeType}</Pill>
<Pill tone={entryState(selected, now) === "active" ? "green" : "amber"}>{entryState(selected, now)}</Pill>
@@ -155,7 +155,7 @@ export function KnowledgePanel({
<ol style={{ display: "grid", gap: 10, paddingLeft: 18 }}>
{revisions.map((revision) => (
<li key={revision.revision}>
<div style={{ fontSize: 12, color: "var(--text-3)" }}>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>
r{revision.revision} · {formatTime(revision.createdAt)} · {revision.changedByType} · {revision.reason}
</div>
<div style={{ whiteSpace: "pre-wrap" }}>{revision.content}</div>
@@ -1,13 +1,16 @@
import { Avatar, Icon, IconButton, Pill } from "../../shared/ui";
import { officeActivityLabel, roleLevelLabel } from "../../i18n/labels";
import { Icon, IconButton, Pill } from "../../shared/ui";
import { officeStateLabel, roleLevelLabel } from "../../i18n/labels";
import { t } from "../../i18n/i18n";
import type { AgentActivity, OfficeAgentInput } from "./office-types";
import { TaskHoldNotice } from "../work/TaskHoldNotice";
import type { OfficeAgentInput } from "./office-types";
import { PixelAvatar } from "./PixelAvatar";
import type { OfficeState } from "./agent-state";
const ACTIVITY_TONE: Record<AgentActivity, "green" | "violet" | "amber" | undefined> = {
active: "green",
thinking: "violet",
busy: "amber",
const STATE_TONE: Record<OfficeState, "green" | "amber" | "red" | undefined> = {
running: "green",
queued: undefined,
cooldown: "amber",
blocked: "red",
idle: undefined,
};
@@ -15,7 +18,7 @@ const ACTIVITY_TONE: Record<AgentActivity, "green" | "violet" | "amber" | undefi
* Floating profile card for the agent selected on the office floor. The page
* owns its placement (it follows the sprite); the card only sizes itself.
*/
export function AgentDetailCard({ agent, onClose }: { agent: OfficeAgentInput; onClose: () => void }) {
export function AgentDetailCard({ agent, isCeo, onClose }: { agent: OfficeAgentInput; isCeo: boolean; onClose: () => void }) {
return (
<div
role="dialog"
@@ -24,30 +27,30 @@ export function AgentDetailCard({ agent, onClose }: { agent: OfficeAgentInput; o
width: 264,
background: "var(--panel)",
border: "1px solid var(--border-strong)",
borderRadius: 12,
boxShadow: "0 12px 32px rgba(16,16,24,0.18)",
padding: 14,
}}
>
<div className="row" style={{ gap: 10, alignItems: "flex-start" }}>
<Avatar name={agent.name} size="lg" bot />
<PixelAvatar id={agent.id} isCeo={isCeo} />
<div style={{ flex: 1, minWidth: 0 }}>
<div style={{ fontSize: 14, fontWeight: 600, lineHeight: 1.3, wordBreak: "break-word" }}>{agent.name}</div>
<div style={{ fontSize: 12, color: "var(--text-2)", marginTop: 1, wordBreak: "break-word" }}>{agent.title}</div>
<div style={{ fontSize: "var(--fs-body)", lineHeight: 1.3, wordBreak: "break-word" }}>{agent.name}</div>
<div style={{ fontSize: "var(--fs-body)", color: "var(--text-2)", marginTop: 1, wordBreak: "break-word" }}>{agent.title}</div>
</div>
<IconButton icon="x" label={t("Close agent details")} onClick={onClose} />
</div>
<div className="row" style={{ gap: 6, marginTop: 10, flexWrap: "wrap" }}>
<Pill>{agent.department}</Pill>
<Pill>{roleLevelLabel(agent.roleLevel)}</Pill>
<Pill tone={ACTIVITY_TONE[agent.activity]} dot>{officeActivityLabel(agent.activity)}</Pill>
<Pill tone={STATE_TONE[agent.status.state]} dot>{officeStateLabel(agent.status.state)}</Pill>
</div>
{agent.status.hold && <div style={{ marginTop: 10 }}><TaskHoldNotice hold={agent.status.hold} /></div>}
{agent.taskTitle && (
<div className="row" style={{ gap: 7, marginTop: 12, alignItems: "flex-start" }}>
<Icon name="work" size={13} color="var(--text-3)" />
<Icon name="work" color="var(--text-3)" />
<span
style={{
fontSize: 12,
fontSize: "var(--fs-body)",
color: "var(--text-2)",
lineHeight: 1.45,
display: "-webkit-box",
@@ -0,0 +1,24 @@
import { useEffect, useRef } from "react";
import { appearanceFor, drawPerson } from "./sprites";
const W = 24;
const H = 24;
/** Each sprite pixel shows as a 2×2 block. */
const ZOOM = 2;
/** The person as the office draws them, from the shoulders up, so a face on the org chart is the same face at the desk. */
export function PixelAvatar({ id, isCeo }: { id: string; isCeo: boolean }) {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const canvas = ref.current!;
const scale = ZOOM * Math.max(1, Math.ceil(window.devicePixelRatio));
canvas.width = W * scale;
canvas.height = H * scale;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("The avatar canvas has no 2D context.");
ctx.imageSmoothingEnabled = false;
ctx.setTransform(scale, 0, 0, scale, 0, 0);
drawPerson(ctx, W / 2, H + 10, appearanceFor(id, isCeo), { facing: "south", walkPhase: 0, working: false, carrying: null, timeMs: 0, animSeed: 0 }, isCeo);
}, [id, isCeo]);
return <canvas ref={ref} className="pixel-avatar" data-person={id} aria-hidden="true" style={{ width: W * ZOOM, height: H * ZOOM }} />;
}
@@ -0,0 +1,33 @@
import type { TaskHold } from "../../../../shared/domain";
import { t } from "../../i18n/i18n";
/** What an agent in the office is doing, from real records: a running session, work held for the operator or a provider cooldown, a queued session, or nothing. */
export type OfficeState = "running" | "blocked" | "cooldown" | "queued" | "idle";
export interface OfficeStatus {
state: OfficeState;
/** What holds a blocked or cooling-down agent. */
hold: TaskHold | null;
}
interface Inputs {
runs: Array<{ agentId: string | null; state: string }>;
tasks: Array<{ id: string; assigneeAgentId: string | null; status: string; hold: TaskHold | null }>;
approvals: Array<{ sourceEntityType: string | null; sourceEntityId: string | null; state: string }>;
}
/** The one state an agent shows: running beats blocked, which beats a cooldown, which beats a queued session. */
export function officeStatus(agentId: string, inputs: Inputs): OfficeStatus {
const runs = inputs.runs.filter((run) => run.agentId === agentId);
if (runs.some((run) => run.state === "running")) return { state: "running", hold: null };
const open = inputs.tasks.filter((task) => task.assigneeAgentId === agentId && task.status !== "done");
const holds = open.filter((task) => task.hold !== null).map((task) => task.hold!);
const operator = holds.find((hold) => hold.waitingOn === "operator");
if (operator) return { state: "blocked", hold: operator };
const awaitingApproval = inputs.approvals.some((approval) => approval.state === "pending" && approval.sourceEntityType === "task" && open.some((task) => task.id === approval.sourceEntityId));
if (awaitingApproval) return { state: "blocked", hold: { reason: t("Waiting for your approval."), waitingOn: "operator", resumesAt: null } };
const provider = holds.find((hold) => hold.waitingOn === "provider");
if (provider) return { state: "cooldown", hold: provider };
if (runs.some((run) => run.state === "queued")) return { state: "queued", hold: null };
return { state: "idle", hold: null };
}
+101
View File
@@ -0,0 +1,101 @@
import type { Rect, Vec } from "./office-types";
// 2:1 isometric projection of the plan; the simulation stays in plan units, depth grows with x + y.
const K = 0.5;
/** Head room above the plan's north edge for the back wall and signs. */
export const SKY_MARGIN = 64;
/** Height of the back (north and west) walls, in iso pixels. */
export const BACK_WALL_H = 48;
export interface IsoFrame {
originX: number;
size: { w: number; h: number };
}
export function isoFrame(world: { w: number; h: number }): IsoFrame {
return { originX: world.h * K, size: { w: (world.w + world.h) * K, h: ((world.w + world.h) * K) / 2 + SKY_MARGIN } };
}
export function toIso(frame: IsoFrame, p: Vec, z = 0): Vec {
return { x: frame.originX + (p.x - p.y) * K, y: SKY_MARGIN + ((p.x + p.y) * K) / 2 - z };
}
/** The ground-plane point under an iso pixel. */
export function fromIso(frame: IsoFrame, s: Vec): Vec {
const difference = (s.x - frame.originX) / K;
const sum = ((s.y - SKY_MARGIN) * 2) / K;
return { x: (sum + difference) / 2, y: (sum - difference) / 2 };
}
export function depthOf(p: Vec): number {
return p.x + p.y;
}
/** Draws plan-space art (rects in plan units) flat onto the iso ground. */
export function setGroundTransform(ctx: CanvasRenderingContext2D, frame: IsoFrame): void {
ctx.transform(K, K / 2, -K, K / 2, frame.originX, SKY_MARGIN);
}
/** Draws face-space art onto a south-facing face at plan y = `planeY` whose top is at height `topZ`: x runs along the face, y down from its top. */
export function setSouthFaceTransform(ctx: CanvasRenderingContext2D, frame: IsoFrame, planeY: number, topZ: number): void {
ctx.transform(K, K / 2, 0, 1, frame.originX - planeY * K, SKY_MARGIN + (planeY * K) / 2 - topZ);
}
export interface BoxColors {
top: string;
south: string;
east: string;
}
/** An extruded block over a plan footprint, from `z` up `height` iso pixels; its top and two camera-facing sides. */
export function drawBox(ctx: CanvasRenderingContext2D, frame: IsoFrame, foot: Rect, z: number, height: number, colors: BoxColors): void {
const x0 = foot.x;
const y0 = foot.y;
const x1 = foot.x + foot.w;
const y1 = foot.y + foot.h;
const top = z + height;
polygon(ctx, colors.south, [toIso(frame, { x: x0, y: y1 }, z), toIso(frame, { x: x1, y: y1 }, z), toIso(frame, { x: x1, y: y1 }, top), toIso(frame, { x: x0, y: y1 }, top)]);
polygon(ctx, colors.east, [toIso(frame, { x: x1, y: y1 }, z), toIso(frame, { x: x1, y: y0 }, z), toIso(frame, { x: x1, y: y0 }, top), toIso(frame, { x: x1, y: y1 }, top)]);
polygon(ctx, colors.top, [toIso(frame, { x: x0, y: y0 }, top), toIso(frame, { x: x1, y: y0 }, top), toIso(frame, { x: x1, y: y1 }, top), toIso(frame, { x: x0, y: y1 }, top)]);
if (height <= 0) return;
const rim = toIso(frame, { x: x1, y: y1 }, top);
polygon(ctx, "rgba(255,255,255,0.2)", [toIso(frame, { x: x0, y: y1 }, top), rim, { x: rim.x, y: rim.y + 0.5 }, toIso(frame, { x: x0, y: y1 }, top - 0.5)]);
polygon(ctx, "rgba(255,255,255,0.14)", [rim, toIso(frame, { x: x1, y: y0 }, top), toIso(frame, { x: x1, y: y0 }, top - 0.5), { x: rim.x, y: rim.y + 0.5 }]);
const base = toIso(frame, { x: x1, y: y1 }, z);
polygon(ctx, "rgba(255,255,255,0.1)", [{ x: rim.x - 0.5, y: rim.y }, rim, base, { x: base.x - 0.5, y: base.y }]);
}
function polygon(ctx: CanvasRenderingContext2D, color: string, points: Vec[]): void {
const art = Math.max(1, Math.round(ctx.getTransform().a));
const snap = (value: number) => Math.round(value * art) / art;
ctx.fillStyle = color;
ctx.beginPath();
ctx.moveTo(snap(points[0]!.x), snap(points[0]!.y));
for (const point of points.slice(1)) ctx.lineTo(snap(point.x), snap(point.y));
ctx.closePath();
ctx.fill();
}
/** Sprite box around a person's feet in iso pixels, matching how sprites are drawn. */
const SPRITE = { halfW: 10, above: 40, below: 4 };
/** The person whose drawn sprite covers an iso point, frontmost first; at equal depth the later one, as it is drawn on top. */
export function pickAt<T extends Vec>(frame: IsoFrame, people: T[], point: Vec): T | null {
let hit: T | null = null;
for (const person of people) {
const feet = toIso(frame, person);
const inside = Math.abs(point.x - feet.x) <= SPRITE.halfW && point.y >= feet.y - SPRITE.above && point.y <= feet.y + SPRITE.below;
if (inside && (hit === null || depthOf(person) >= depthOf(hit))) hit = person;
}
return hit;
}
/** Screen size of one iso pixel in CSS px: two CSS px rounded to whole device pixels. */
export function isoPixelSize(devicePixelRatio: number): number {
return Math.max(1, Math.round(2 * devicePixelRatio)) / devicePixelRatio;
}
/** Scene pixels per iso pixel: two when an iso pixel spans an even number of device pixels, so detail stays on whole device pixels. */
export function artScale(devicePixelRatio: number): number {
return Math.max(1, Math.round(2 * devicePixelRatio)) % 2 === 0 ? 2 : 1;
}
+141
View File
@@ -0,0 +1,141 @@
import type { OfficeState } from "./agent-state";
import type { Camera, FloorPlan, Rect, Vec } from "./office-types";
import type { DayPart } from "../../shared/palette-clock";
import { BACK_WALL_H, toIso, type IsoFrame } from "./iso";
import { WALL } from "./floor-plan";
interface Light {
at: Vec;
z: number;
/** Reach in iso pixels. */
radius: number;
rgb: string;
strength: number;
}
const AMBIENT: Record<DayPart, string> = { day: "rgb(236,232,224)", dawn: "rgb(214,190,196)", dusk: "rgb(222,184,150)", night: "rgb(58,68,112)" };
const LAMPS_ON: Record<DayPart, number> = { day: 0.18, dawn: 0.6, dusk: 0.8, night: 1 };
const SCREEN_RGB: Record<OfficeState, string> = { running: "88,230,170", queued: "160,170,200", cooldown: "240,170,70", blocked: "240,80,80", idle: "110,130,170" };
const WARM = "255,206,140";
const BAYER = [0, 8, 2, 10, 12, 4, 14, 6, 3, 11, 1, 9, 15, 7, 13, 5];
const LEVELS = 12;
/** Every lamp and screen in the office: monitors glow in their agent's state colour, rooms and the open floor have warm lamps. */
export function sceneLights(plan: FloorPlan, screens: Map<Rect, OfficeState>): Light[] {
const lights: Light[] = [];
for (const [desk, state] of screens) {
lights.push({ at: { x: desk.x + desk.w / 2, y: desk.y + 14 }, z: 20, radius: 26, rgb: SCREEN_RGB[state], strength: state === "idle" ? 0.35 : 0.8 });
}
for (const desk of plan.desks) lights.push({ at: { x: desk.bounds.x + desk.bounds.w / 2, y: desk.bounds.y + 60 }, z: 0, radius: 58, rgb: WARM, strength: 0.7 });
for (const room of plan.rooms) {
const b = room.bounds;
const rgb = room.kind === "restroom" ? "205,228,255" : WARM;
lights.push({ at: { x: b.x + b.w / 2, y: b.y + b.h / 2 }, z: 0, radius: Math.max(b.w, b.h) * 0.42, rgb, strength: 0.85 });
}
for (let x = 120; x < plan.world.w; x += 220) lights.push({ at: { x, y: 320 }, z: 0, radius: 64, rgb: WARM, strength: 0.75 });
return lights;
}
/** Sunlit floor under each window, longer and slanted toward evening or morning; none at night. */
export function sunPatches(windows: Rect[], clock: Date): Vec[][] {
const hour = clock.getHours() + clock.getMinutes() / 60;
if (hour < 6.5 || hour > 18.5) return [];
const reach = 1.1 + Math.abs(hour - 12.5) * 0.35;
const slant = (12.5 - hour) * 0.18;
return windows.map((glass) => {
const low = (BACK_WALL_H - glass.y - glass.h) * reach;
const high = (BACK_WALL_H - glass.y) * reach;
return [
{ x: glass.x + slant * low, y: WALL + low },
{ x: glass.x + glass.w + slant * low, y: WALL + low },
{ x: glass.x + glass.w + slant * high, y: WALL + high },
{ x: glass.x + slant * high, y: WALL + high },
];
});
}
/** Bands a light map into a few levels with a 4×4 ordered dither, so light falls off in pixels, not gradients. */
export function ditherLevels(data: Uint8ClampedArray, width: number): void {
for (let i = 0; i < data.length; i += 4) {
const pixel = i / 4;
const threshold = BAYER[((Math.floor(pixel / width) & 3) << 2) | (pixel % width & 3)]! / 16 - 0.5;
for (let c = 0; c < 3; c++) {
const level = Math.round((data[i + c]! / 255) * LEVELS + threshold);
data[i + c] = (Math.max(0, Math.min(LEVELS, level)) / LEVELS) * 255;
}
}
}
interface LightingInput {
frame: IsoFrame;
camera: Camera;
/** Scene pixels per iso pixel. */
art: number;
dayPart: DayPart;
lights: Light[];
patches: Vec[][];
timeMs: number;
}
/** Multiplies the finished scene by a light map drawn at iso resolution: ambient for the hour, lamps and screens added, sun through the windows. */
export function applyLighting(scene: CanvasRenderingContext2D, map: HTMLCanvasElement, input: LightingInput): void {
const w = Math.ceil(scene.canvas.width / input.art);
const h = Math.ceil(scene.canvas.height / input.art);
if (map.width !== w || map.height !== h) {
map.width = w;
map.height = h;
}
const ctx = map.getContext("2d", { willReadFrequently: true });
if (!ctx) throw new Error("The light map canvas has no 2D context.");
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = AMBIENT[input.dayPart];
ctx.fillRect(0, 0, w, h);
ctx.globalCompositeOperation = "lighter";
const lamps = LAMPS_ON[input.dayPart];
const view = (p: Vec, z = 0) => {
const iso = toIso(input.frame, p, z);
return { x: iso.x - input.camera.x, y: iso.y - input.camera.y };
};
for (const light of input.lights) {
const at = view(light.at, light.z);
if (at.x < -light.radius || at.y < -light.radius || at.x > w + light.radius || at.y > h + light.radius) continue;
const glow = ctx.createRadialGradient(at.x, at.y, 0, at.x, at.y, light.radius);
glow.addColorStop(0, `rgba(${light.rgb},${0.55 * light.strength * lamps})`);
glow.addColorStop(1, `rgba(${light.rgb},0)`);
ctx.fillStyle = glow;
ctx.fillRect(at.x - light.radius, at.y - light.radius, light.radius * 2, light.radius * 2);
}
ctx.fillStyle = input.dayPart === "day" ? "rgba(255,240,205,0.16)" : "rgba(255,196,140,0.12)";
for (const patch of input.patches) {
ctx.beginPath();
patch.map((p) => view(p)).forEach((p, index) => (index === 0 ? ctx.moveTo(p.x, p.y) : ctx.lineTo(p.x, p.y)));
ctx.closePath();
ctx.fill();
}
const image = ctx.getImageData(0, 0, w, h);
ditherLevels(image.data, w);
ctx.putImageData(image, 0, 0);
scene.save();
scene.setTransform(input.art, 0, 0, input.art, 0, 0);
scene.imageSmoothingEnabled = false;
scene.globalCompositeOperation = "multiply";
scene.drawImage(map, 0, 0);
scene.globalCompositeOperation = "source-over";
drawDust(scene, input, view);
scene.restore();
}
/** Dust motes drifting up through the sunlit patches. */
function drawDust(scene: CanvasRenderingContext2D, input: LightingInput, view: (p: Vec, z?: number) => Vec): void {
scene.fillStyle = "rgba(255,246,220,0.75)";
input.patches.forEach((patch, index) => {
const centre = { x: (patch[0]!.x + patch[2]!.x) / 2, y: (patch[0]!.y + patch[2]!.y) / 2 };
for (let mote = 0; mote < 5; mote++) {
const seed = index * 7 + mote * 13;
const rise = ((input.timeMs / 90 + seed * 11) % 40);
const drift = Math.sin(input.timeMs / 1400 + seed) * 6;
const at = view({ x: centre.x + ((seed * 37) % 50) - 25 + drift, y: centre.y + ((seed * 17) % 30) - 15 }, rise);
scene.fillRect(Math.round(at.x * 2) / 2, Math.round(at.y * 2) / 2, 0.5, 0.5);
}
});
}
+148 -88
View File
@@ -1,12 +1,16 @@
import type { AgentActivity, Camera, FloorPlan, Rect } from "./office-types";
import { deskScreenRect, drawWorld } from "./scene-renderer";
import { skyScene } from "./sky";
import type { Camera, FloorPlan, Rect } from "./office-types";
import type { OfficeState } from "./agent-state";
import { drawBackWalls, drawContactShadows, drawGround, sceneDrawables, windowRects, type Drawable } from "./scene-renderer";
import { depthOf, toIso, type IsoFrame } from "./iso";
import { applyLighting, sceneLights, sunPatches } from "./lighting";
import { skyScene, weatherFor } from "./sky";
import { drawPerson, type Carrying, type Facing, type SpriteAppearance } from "./sprites";
import type { DayPart, Season } from "../../shared/palette-clock";
export interface RenderPerson {
id: string;
name: string;
activity: AgentActivity;
state: OfficeState;
x: number;
y: number;
desk: Rect | null;
@@ -19,10 +23,34 @@ export interface RenderPerson {
carrying: Carrying;
}
const ACTIVITY_DOT: Partial<Record<AgentActivity, string>> = {
active: "#34d399",
thinking: "#818cf8",
busy: "#f59e0b",
/** One frame's inputs: the scene in iso pixels, and how those pixels land on the screen. */
export interface OfficeFrame {
frame: IsoFrame;
plan: FloorPlan;
/** Camera top-left, in iso pixels. */
camera: Camera;
/** CSS px per iso pixel. */
pixel: number;
/** Scene pixels per iso pixel (artScale). */
art: number;
/** CSS px per pixel-font pixel, for the crisp text drawn over the scene. */
fontScale: number;
viewW: number;
viewH: number;
people: RenderPerson[];
timeMs: number;
clock: Date;
dayPart: DayPart;
season: Season;
selectedId: string | null;
}
/** Marker over the head: green running, grey queued, amber cooling down, red blocked; none when idle. */
const STATE_MARK: Partial<Record<OfficeState, string>> = {
running: "#34d399",
queued: "#9aa3b2",
cooldown: "#f59e0b",
blocked: "#ef4444",
};
export function hashString(value: string): number {
@@ -31,94 +59,126 @@ export function hashString(value: string): number {
return Math.abs(hash);
}
/**
* Composes one frame: static world under the camera transform, then desks'
* activity glow, then people (painter's order by y) with full-name labels.
*/
export function renderOffice(
ctx: CanvasRenderingContext2D,
viewW: number,
viewH: number,
plan: FloorPlan,
camera: Camera,
people: RenderPerson[],
timeMs: number,
clock: Date,
selectedId: string | null,
): void {
ctx.fillStyle = "#14161c";
ctx.fillRect(0, 0, viewW, viewH);
ctx.save();
ctx.translate(-camera.x, -camera.y);
drawWorld(ctx, plan, { x: camera.x, y: camera.y, w: viewW, h: viewH }, skyScene(clock));
for (const person of people) {
if (!person.desk) continue;
if (person.activity !== "active" && person.activity !== "thinking") continue;
const screen = deskScreenRect(person.desk);
ctx.fillStyle = "#1c3a2c";
ctx.fillRect(screen.x, screen.y, screen.w, screen.h);
ctx.fillStyle = "#37d38a";
const lines = 3 + (hashString(person.id) % 3);
for (let i = 0; i < lines; i++) {
const width = 6 + ((hashString(person.id) >> (i * 3)) % 14);
ctx.fillRect(screen.x + 3, screen.y + 3 + i * 3, width, 1);
}
/** Draws the scene at art resolution on `scene`, depth-sorted and lit for the hour, then scales it up unsmoothed onto `ctx` and writes labels in the pixel font. */
export function renderOffice(ctx: CanvasRenderingContext2D, scene: HTMLCanvasElement, lightMap: HTMLCanvasElement, input: OfficeFrame): void {
const sceneW = Math.ceil((input.viewW / input.pixel) * input.art);
const sceneH = Math.ceil((input.viewH / input.pixel) * input.art);
if (scene.width !== sceneW || scene.height !== sceneH) {
scene.width = sceneW;
scene.height = sceneH;
}
const sctx = scene.getContext("2d");
if (!sctx) throw new Error("The office scene canvas has no 2D context.");
sctx.setTransform(1, 0, 0, 1, 0, 0);
sctx.imageSmoothingEnabled = false;
sctx.fillStyle = "#14161c";
sctx.fillRect(0, 0, sceneW, sceneH);
const camera = snappedCamera(input);
sctx.setTransform(input.art, 0, 0, input.art, -camera.x * input.art, -camera.y * input.art);
const ordered = [...people].sort((a, b) => a.y - b.y);
for (const person of ordered) {
if (person.id === selectedId) {
ctx.strokeStyle = "rgba(94,106,210,0.9)";
ctx.lineWidth = 2;
ctx.beginPath();
ctx.ellipse(Math.round(person.x), Math.round(person.y) + 2, 13, 6, 0, 0, Math.PI * 2);
ctx.stroke();
}
const working = (person.activity === "active" || person.activity === "thinking") && person.walkPhase === 0;
drawPerson(ctx, person.x, person.y, person.appearance, {
facing: person.facing,
walkPhase: person.walkPhase,
working,
carrying: person.carrying,
timeMs,
animSeed: person.animSeed,
}, person.isCeo);
const dot = ACTIVITY_DOT[person.activity];
if (dot) {
ctx.fillStyle = dot;
ctx.beginPath();
ctx.arc(Math.round(person.x) + 10, Math.round(person.y) - 36, 3, 0, Math.PI * 2);
ctx.fill();
}
}
for (const person of ordered) drawNameLabel(ctx, person);
drawGround(sctx, input.frame, input.plan);
drawBackWalls(sctx, input.frame, input.plan, { sky: skyScene(input.clock), weather: weatherFor(input.clock), clock: input.clock, timeMs: input.timeMs });
const screens = new Map(input.people.filter((person) => person.desk).map((person) => [person.desk!, person.state]));
const scenery = sceneDrawables(input.frame, input.plan, input.season, screens, input.timeMs);
drawContactShadows(sctx, input.frame, scenery);
const items: Drawable[] = [...scenery, ...input.people.map((person) => personDrawable(input, person))];
items.sort((a, b) => a.depth - b.depth);
for (const item of items) item.draw(sctx);
ctx.restore();
applyLighting(sctx, lightMap, {
frame: input.frame,
camera,
art: input.art,
dayPart: input.dayPart,
lights: sceneLights(input.plan, screens),
patches: sunPatches(input.plan.rooms.flatMap(windowRects), input.clock),
timeMs: input.timeMs,
});
ctx.imageSmoothingEnabled = false;
ctx.drawImage(scene, 0, 0, (sceneW * input.pixel) / input.art, (sceneH * input.pixel) / input.art);
drawLabels(ctx, input, camera);
}
function drawNameLabel(ctx: CanvasRenderingContext2D, person: RenderPerson): void {
ctx.font = "600 9px -apple-system, 'Segoe UI', sans-serif";
const width = Math.ceil(ctx.measureText(person.name).width) + 10;
const x = Math.round(person.x - width / 2);
const y = Math.round(person.y + 7);
ctx.fillStyle = person.isPlayer ? "rgba(94,106,210,0.92)" : "rgba(22,22,28,0.78)";
drawRoundedRect(ctx, x, y, width, 13, 4);
ctx.fillStyle = "#f2f2f5";
/** The camera on the scene's pixel grid, so the scene and the labels over it move together. */
function snappedCamera(input: OfficeFrame): Camera {
return { x: Math.round(input.camera.x * input.art) / input.art, y: Math.round(input.camera.y * input.art) / input.art };
}
function personDrawable(input: OfficeFrame, person: RenderPerson): Drawable {
return {
// Just in front of anything sharing the same footprint centre.
depth: depthOf(person) + 0.5,
draw: (ctx) => {
const feet = toIso(input.frame, person);
if (person.id === input.selectedId) drawSelection(ctx, feet.x, feet.y, input.timeMs);
const working = person.state === "running" && person.walkPhase === 0;
drawPerson(ctx, feet.x, feet.y, person.appearance, {
facing: person.facing,
walkPhase: person.walkPhase,
working,
carrying: person.carrying,
timeMs: input.timeMs,
animSeed: person.animSeed,
}, person.isCeo);
const gem = STATE_MARK[person.state];
if (gem) drawStateGem(ctx, feet.x, feet.y - 38 + Math.round(Math.sin(input.timeMs / 420 + person.animSeed) * 2) / 2, gem);
},
};
}
/** A small faceted gem floating over the head, in the state's colour. */
function drawStateGem(ctx: CanvasRenderingContext2D, x: number, y: number, color: string): void {
const cx = Math.round(x * 2) / 2;
const rows = [0.5, 1.5, 2.5, 2.5, 1.5, 1, 0.5];
ctx.fillStyle = "rgba(20,18,24,0.85)";
rows.forEach((half, row) => ctx.fillRect(cx - half - 0.5, y + row * 0.5 - 0.5, half * 2 + 1, 1));
ctx.fillStyle = color;
rows.forEach((half, row) => ctx.fillRect(cx - half, y + row * 0.5, half * 2, 0.5));
ctx.fillStyle = "rgba(255,255,255,0.7)";
ctx.fillRect(cx - 1, y + 1, 0.5, 0.5);
ctx.fillRect(cx - 0.5, y + 0.5, 0.5, 0.5);
}
/** A pixel ring around the selected person's feet, breathing in and out. */
function drawSelection(ctx: CanvasRenderingContext2D, x: number, y: number, timeMs: number): void {
const grow = Math.round((Math.sin(timeMs / 260) + 1) * 0.5) * 0.5;
const cx = Math.round(x * 2) / 2;
const cy = Math.round(y * 2) / 2;
const rx = 9 + grow;
ctx.fillStyle = "rgba(124,138,240,0.95)";
for (let step = 0; step < 48; step++) {
const angle = (step / 48) * 2 * Math.PI;
ctx.fillRect(Math.round((cx + Math.cos(angle) * rx) * 2) / 2, Math.round((cy + Math.sin(angle) * rx * 0.5) * 2) / 2, 0.5, 0.5);
}
}
/** Names under people and room signs over doors, in the pixel font at screen resolution so they stay crisp. */
function drawLabels(ctx: CanvasRenderingContext2D, input: OfficeFrame, camera: Camera): void {
const size = 12 * input.fontScale;
ctx.font = `${size}px "Fusion Pixel"`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(person.name, person.x, y + 7);
ctx.textBaseline = "top";
const screen = (x: number, y: number, z = 0) => {
const iso = toIso(input.frame, { x, y }, z);
return { x: Math.round((iso.x - camera.x) * input.pixel), y: Math.round((iso.y - camera.y) * input.pixel) };
};
for (const room of input.plan.rooms) {
const at = screen(room.doorCx, room.bounds.y + room.bounds.h, 22);
plate(ctx, room.label, at.x, at.y - size, size, "rgba(47,42,37,0.9)");
}
for (const person of [...input.people].sort((a, b) => depthOf(a) - depthOf(b))) {
const at = screen(person.x, person.y);
plate(ctx, person.name, at.x, at.y + 6 * input.pixel, size, person.isPlayer ? "rgba(94,106,210,0.92)" : "rgba(22,22,28,0.78)");
}
ctx.textAlign = "start";
ctx.textBaseline = "alphabetic";
}
function drawRoundedRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number): void {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.fill();
function plate(ctx: CanvasRenderingContext2D, text: string, cx: number, top: number, size: number, background: string): void {
const width = Math.ceil(ctx.measureText(text).width) + size;
ctx.fillStyle = background;
ctx.fillRect(Math.round(cx - width / 2), top, width, Math.round(size * 1.5));
ctx.fillStyle = "#f2f2f5";
ctx.fillText(text, cx, top + Math.round(size * 0.25));
}
@@ -1,3 +1,4 @@
import type { OfficeStatus } from "./agent-state";
export interface Vec {
x: number;
y: number;
@@ -61,8 +62,6 @@ export interface FloorPlan {
entrance: Vec;
}
export type AgentActivity = "active" | "thinking" | "busy" | "idle";
/** Snapshot-derived facts the office simulation needs about one agent. */
export interface OfficeAgentInput {
id: string;
@@ -71,7 +70,7 @@ export interface OfficeAgentInput {
title: string;
department: string;
roleLevel: string;
activity: AgentActivity;
status: OfficeStatus;
taskTitle: string | null;
}
+311
View File
@@ -0,0 +1,311 @@
import { finishSprite, mix, PixelGrid, tone } from "./pixel-grid";
import type { Carrying, Facing, SpriteAppearance } from "./sprites";
/** Sprite canvas in art pixels (two per iso pixel); the feet rest on ANCHOR. */
export const ART_W = 40;
export const ART_H = 80;
export const ANCHOR = { x: 20, y: 74 };
/** One drawn pose: walk step 0-3 (-1 standing), typing hands 0/1 (-1 not typing), eyes shut mid-blink. */
export interface PersonFrame {
facing: Facing;
step: number;
typing: number;
blink: boolean;
carrying: Carrying;
}
const EYE = "#2a2430";
const WHITE = "#fbfaf6";
const SHIRT_WHITE = "#ecebe6";
const BELT = "#2b2a30";
const BUCKLE = "#c9b27a";
const MOUTH = "#9c4d48";
const BLUSH = "#e88a8a";
const BLAZER = "#37415c";
const BLAZER_CEO = "#262c3d";
export function personArt(look: SpriteAppearance, frame: PersonFrame, isCeo: boolean): PixelGrid {
const grid = new PixelGrid(ART_W, ART_H);
const side = frame.facing === "east" || frame.facing === "west";
const lift = frame.step === 1 || frame.step === 3 ? -1 : 0;
if (side) drawSide(grid, look, frame, isCeo, lift);
else drawFrontOrBack(grid, look, frame, isCeo, lift, frame.facing === "south");
finishSprite(grid);
return frame.facing === "west" ? grid.mirrored() : grid;
}
function jacketOf(look: SpriteAppearance, isCeo: boolean): string {
return look.outfit === "blazer" ? (isCeo ? BLAZER_CEO : BLAZER) : look.shirt;
}
function drawFrontOrBack(g: PixelGrid, look: SpriteAppearance, frame: PersonFrame, isCeo: boolean, lift: number, front: boolean): void {
const leftUp = frame.step === 0 ? 2 : 0;
const rightUp = frame.step === 2 ? 2 : 0;
legs(g, look, 12, 53, 7, leftUp, front);
legs(g, look, 21, 53, 7, rightUp, front);
g.rect(19, 53, 2, 4, look.pants);
const y = lift;
const body = jacketOf(look, isCeo);
g.rect(11, 33 + y, 18, 18, body);
g.clear(11, 33 + y);
g.clear(28, 33 + y);
g.rect(11, 51 + y, 18, 2, BELT);
if (front) g.rect(19, 51 + y, 2, 2, BUCKLE);
const swing = frame.step < 0 ? 0 : frame.step === 0 ? 1 : frame.step === 2 ? -1 : 0;
if (frame.typing >= 0) typingArms(g, look, body, y, frame.typing);
else {
arm(g, look, body, 8, 34 + y + swing);
arm(g, look, body, 29, 34 + y - swing);
}
if (front) frontOutfit(g, look, body, y);
else backOutfit(g, look, body, y);
g.rect(17, 31 + y, 6, 2, tone(look.skin, 0.84));
head(g, look, frame, y, front);
if (frame.carrying && frame.typing < 0) carried(g, frame.carrying, 31, 44 + y - swing);
}
function legs(g: PixelGrid, look: SpriteAppearance, x: number, top: number, w: number, up: number, front: boolean): void {
g.rect(x, top, w, 17 - up, look.pants);
g.rect(x, top + 6, 1, 8 - up, tone(look.pants, 0.85));
const shoeY = 70 - up;
g.rect(x - 1, shoeY, w + 1, 3, look.shoes);
g.rect(x - 1, shoeY + 3, w + 1, 1, tone(look.shoes, 0.6));
if (front) g.rect(x, shoeY, 2, 1, tone(look.shoes, 1.4));
}
function arm(g: PixelGrid, look: SpriteAppearance, body: string, x: number, top: number): void {
const sleeve = look.outfit === "tee" ? 6 : 14;
g.rect(x, top, 3, sleeve, body);
g.rect(x, top + sleeve, 3, 15 - sleeve, look.skin);
if (look.outfit === "blazer") g.rect(x, top + 13, 3, 1, SHIRT_WHITE);
if (look.outfit === "hoodie") g.rect(x, top + 13, 3, 1, tone(body, 0.78));
g.rect(x, top + 15, 3, 3, look.skin);
g.px(x + 1, top + 17, tone(look.skin, 0.82));
}
function typingArms(g: PixelGrid, look: SpriteAppearance, body: string, y: number, beat: number): void {
for (const [x, inward, offset] of [[8, 1, beat], [29, -1, 1 - beat]] as const) {
g.rect(x, 34 + y, 3, 9, body);
g.rect(x + inward * 2, 41 + y - offset, 3, 4, body);
g.rect(x + inward * 3, 44 + y - offset, 3, 2, look.skin);
}
}
function frontOutfit(g: PixelGrid, look: SpriteAppearance, body: string, y: number): void {
if (look.outfit === "tee") {
g.rect(18, 33 + y, 4, 1, look.skin);
g.rect(19, 34 + y, 2, 1, look.skin);
g.rect(22, 38 + y, 3, 2, look.accent);
g.rect(11, 50 + y, 18, 1, tone(body, 0.85));
return;
}
if (look.outfit === "hoodie") {
g.rect(13, 33 + y, 14, 2, tone(body, 0.78));
g.rect(17, 35 + y, 1, 5, WHITE);
g.rect(22, 35 + y, 1, 5, WHITE);
g.rect(14, 43 + y, 12, 6, tone(body, 0.88));
g.rect(14, 43 + y, 12, 1, tone(body, 0.74));
return;
}
for (let row = 0; row < 12; row++) {
const half = Math.max(1, 3 - Math.floor(row / 3));
g.rect(20 - half, 33 + y + row, half * 2, 1, SHIRT_WHITE);
g.px(19 - half, 33 + y + row, tone(body, 0.72));
g.px(20 + half, 33 + y + row, tone(body, 0.72));
}
g.rect(19, 34 + y, 2, 1, tone(look.accent, 0.8));
g.rect(19, 35 + y, 2, 9, look.accent);
g.px(19, 44 + y, tone(look.accent, 0.8));
g.px(21, 47 + y, "#d8d0b8");
g.px(21, 49 + y, "#d8d0b8");
g.rect(24, 37 + y, 2, 1, look.accent);
}
function backOutfit(g: PixelGrid, look: SpriteAppearance, body: string, y: number): void {
if (look.outfit === "hoodie") g.rect(14, 33 + y, 12, 5, tone(body, 0.82));
if (look.outfit === "blazer") g.rect(19, 44 + y, 1, 7, tone(body, 0.7));
if (look.outfit === "tee") g.rect(11, 50 + y, 18, 1, tone(body, 0.85));
}
function head(g: PixelGrid, look: SpriteAppearance, frame: PersonFrame, y: number, front: boolean): void {
const top = 12 + y;
g.rect(11, top, 18, 19, look.skin);
for (const [x, dy] of [[11, 0], [12, 0], [11, 1], [28, 0], [27, 0], [28, 1], [11, 18], [28, 18]] as const) g.clear(x, top + dy);
g.rect(10, top + 8, 1, 4, tone(look.skin, 0.9));
g.rect(29, top + 8, 1, 4, tone(look.skin, 0.9));
if (front) {
face(g, look, frame.blink, top);
frontHair(g, look, top);
} else backHair(g, look, top);
}
function face(g: PixelGrid, look: SpriteAppearance, blink: boolean, top: number): void {
const brow = tone(look.hair, 0.8);
g.rect(13, top + 6, 3, 1, brow);
g.rect(24, top + 6, 3, 1, brow);
if (look.glasses) {
const lens = mix(look.skin, "#9fd0f0", 0.35);
for (const x of [13, 23]) {
g.rect(x, top + 7, 4, 5, "#1c1c22");
g.rect(x + 1, top + 8, 2, 3, lens);
}
g.rect(17, top + 8, 6, 1, "#1c1c22");
}
for (const x of [14, 24]) {
if (blink) g.rect(x, top + 10, 2, 1, EYE);
else {
g.rect(x, top + 8, 2, 3, EYE);
g.px(x + 1, top + 8, WHITE);
}
}
g.px(20, top + 12, tone(look.skin, 0.8));
g.rect(18, top + 15, 4, 1, MOUTH);
g.px(17, top + 14, mix(look.skin, MOUTH, 0.5));
g.px(22, top + 14, mix(look.skin, MOUTH, 0.5));
const blush = mix(look.skin, BLUSH, 0.45);
g.rect(13, top + 13, 2, 1, blush);
g.rect(25, top + 13, 2, 1, blush);
}
function cap(g: PixelGrid, look: SpriteAppearance, top: number, rows: number): void {
g.rect(12, top - 2, 16, 1, look.hair);
g.rect(11, top - 1, 18, rows + 1, look.hair);
g.rect(14, top - 1, 4, 1, tone(look.hair, 1.4));
}
function frontHair(g: PixelGrid, look: SpriteAppearance, top: number): void {
const hair = look.hair;
switch (look.hairStyle) {
case "bald":
g.rect(15, top + 1, 3, 1, tone(look.skin, 1.12));
return;
case "buzz":
g.rect(12, top - 1, 16, 3, hair);
g.rect(11, top + 2, 1, 4, hair);
g.rect(28, top + 2, 1, 4, hair);
return;
case "short":
cap(g, look, top, 4);
g.rect(12, top + 4, 7, 1, hair);
g.rect(11, top + 4, 2, 5, hair);
g.rect(27, top + 4, 2, 5, hair);
return;
case "bob":
cap(g, look, top, 5);
g.rect(9, top + 2, 4, 14, hair);
g.rect(27, top + 2, 4, 14, hair);
g.rect(13, top + 5, 14, 1, tone(hair, 0.85));
return;
case "long":
cap(g, look, top, 4);
g.rect(9, top + 2, 4, 25, hair);
g.rect(27, top + 2, 4, 25, hair);
g.rect(13, top + 4, 8, 1, hair);
g.rect(10, top + 8, 1, 14, tone(hair, 1.25));
return;
case "ponytail":
cap(g, look, top, 4);
g.rect(21, top + 4, 6, 1, hair);
g.rect(29, top + 2, 3, 12, hair);
g.rect(29, top + 2, 3, 1, tone(look.accent, 0.9));
return;
case "curly":
cap(g, look, top - 1, 5);
for (let x = 10; x <= 29; x += 2) g.rect(x, top - 4 + (x % 4 === 0 ? 0 : 1), 2, 2, hair);
for (let row = 2; row < 12; row += 2) {
g.rect(9 + (row % 4 === 0 ? 0 : 1), top + row, 3, 2, hair);
g.rect(28 - (row % 4 === 0 ? 0 : 1), top + row, 3, 2, hair);
}
g.rect(13, top + 4, 14, 1, tone(hair, 0.85));
return;
}
}
function backHair(g: PixelGrid, look: SpriteAppearance, top: number): void {
const hair = look.hair;
if (look.hairStyle === "bald") return;
const depth = { buzz: 10, short: 14, bob: 18, long: 18, ponytail: 15, curly: 15 }[look.hairStyle];
g.rect(12, top - 2, 16, 1, hair);
g.rect(11, top - 1, 18, depth, hair);
g.rect(14, top, 5, 1, tone(hair, 1.4));
if (look.hairStyle === "long") g.rect(10, top + 14, 20, 12, hair);
if (look.hairStyle === "bob") g.rect(10, top + 12, 20, 4, hair);
if (look.hairStyle === "ponytail") {
g.rect(18, top + 13, 4, 1, look.accent);
g.rect(18, top + 14, 4, 11, hair);
g.rect(19, top + 25, 2, 2, hair);
}
if (look.hairStyle === "curly") for (let x = 11; x <= 28; x += 3) g.rect(x, top + 14, 2, 2, hair);
}
function drawSide(g: PixelGrid, look: SpriteAppearance, frame: PersonFrame, isCeo: boolean, lift: number): void {
const stride = frame.step === 0 ? 3 : frame.step === 2 ? -3 : 0;
sideLeg(g, look, 15 - stride, 0.82);
sideLeg(g, look, 20 + stride, 1);
const y = lift;
const body = jacketOf(look, isCeo);
g.rect(13, 33 + y, 14, 18, body);
g.clear(13, 33 + y);
g.clear(26, 33 + y);
g.rect(13, 51 + y, 14, 2, BELT);
if (look.outfit === "hoodie") g.rect(13, 33 + y, 5, 6, tone(body, 0.8));
if (look.outfit === "blazer") {
g.rect(24, 33 + y, 3, 9, SHIRT_WHITE);
g.rect(25, 35 + y, 2, 8, look.accent);
}
if (look.outfit === "tee") g.rect(22, 38 + y, 3, 2, look.accent);
const swing = frame.typing >= 0 ? 4 : -stride;
arm(g, look, body, 18 + Math.round(swing / 2), 34 + y);
g.rect(17, 31 + y, 5, 2, tone(look.skin, 0.84));
sideHead(g, look, frame.blink, 12 + y);
if (frame.carrying && frame.typing < 0) carried(g, frame.carrying, 22 + Math.round(swing / 2), 46 + y);
}
function sideLeg(g: PixelGrid, look: SpriteAppearance, x: number, shade: number): void {
g.rect(x, 53, 5, 17, tone(look.pants, shade));
g.rect(x, 70, 7, 3, tone(look.shoes, shade));
g.rect(x, 73, 7, 1, tone(look.shoes, 0.6 * shade));
}
function sideHead(g: PixelGrid, look: SpriteAppearance, blink: boolean, top: number): void {
g.rect(12, top, 16, 19, look.skin);
for (const [x, dy] of [[12, 0], [13, 0], [12, 1], [27, 0], [26, 0], [27, 1], [12, 18], [27, 18]] as const) g.clear(x, top + dy);
g.rect(28, top + 10, 1, 3, look.skin);
g.rect(17, top + 8, 2, 4, tone(look.skin, 0.86));
g.rect(21, top + 6, 4, 1, tone(look.hair, 0.8));
if (blink) g.rect(22, top + 10, 2, 1, EYE);
else {
g.rect(22, top + 8, 2, 3, EYE);
g.px(23, top + 8, WHITE);
}
if (look.glasses) {
g.rect(21, top + 7, 4, 1, "#1c1c22");
g.rect(21, top + 11, 4, 1, "#1c1c22");
g.rect(16, top + 8, 5, 1, "#1c1c22");
}
g.rect(24, top + 15, 3, 1, MOUTH);
g.rect(24, top + 13, 2, 1, mix(look.skin, BLUSH, 0.45));
if (look.hairStyle === "bald") return;
const hair = look.hair;
const back = { buzz: 8, short: 12, bob: 16, long: 16, ponytail: 12, curly: 14 }[look.hairStyle];
g.rect(13, top - 2, 13, 1, hair);
g.rect(12, top - 1, 15, look.hairStyle === "buzz" ? 3 : 5, hair);
g.rect(11, top, 7, back, hair);
g.rect(15, top - 1, 5, 1, tone(hair, 1.4));
if (look.hairStyle === "long") g.rect(10, top + 12, 8, 14, hair);
if (look.hairStyle === "bob") g.rect(25, top + 4, 2, 2, hair);
if (look.hairStyle === "ponytail") g.rect(8, top + 4, 4, 12, hair);
if (look.hairStyle === "curly") for (let row = 0; row < 14; row += 3) g.rect(10, top + row, 2, 2, hair);
}
function carried(g: PixelGrid, item: NonNullable<Carrying>, x: number, y: number): void {
if (item === "coffee") {
g.rect(x, y, 4, 5, WHITE);
g.rect(x, y, 4, 1, "#6b4a2f");
g.px(x + 4, y + 2, WHITE);
return;
}
g.rect(x, y + 1, 5, 4, "#c9553e");
g.rect(x + 1, y + 2, 3, 2, "#e8b84a");
}
@@ -0,0 +1,96 @@
/** An RGBA pixel buffer drawn without anti-aliasing, so procedural art stays exact. */
export class PixelGrid {
readonly data: Uint8ClampedArray<ArrayBuffer>;
constructor(readonly w: number, readonly h: number) {
this.data = new Uint8ClampedArray(new ArrayBuffer(w * h * 4));
}
rect(x: number, y: number, w: number, h: number, color: string): void {
const [r, g, b] = rgb(color);
for (let py = Math.max(0, y); py < Math.min(this.h, y + h); py++) {
for (let px = Math.max(0, x); px < Math.min(this.w, x + w); px++) this.set(px, py, r, g, b, 255);
}
}
px(x: number, y: number, color: string): void {
this.rect(x, y, 1, 1, color);
}
clear(x: number, y: number): void {
if (x >= 0 && y >= 0 && x < this.w && y < this.h) this.data[(y * this.w + x) * 4 + 3] = 0;
}
alpha(x: number, y: number): number {
return x < 0 || y < 0 || x >= this.w || y >= this.h ? 0 : this.data[(y * this.w + x) * 4 + 3]!;
}
mirrored(): PixelGrid {
const out = new PixelGrid(this.w, this.h);
for (let y = 0; y < this.h; y++) {
for (let x = 0; x < this.w; x++) {
const from = (y * this.w + x) * 4;
out.data.set(this.data.subarray(from, from + 4), (y * this.w + (this.w - 1 - x)) * 4);
}
}
return out;
}
private set(x: number, y: number, r: number, g: number, b: number, a: number): void {
const at = (y * this.w + x) * 4;
this.data[at] = r;
this.data[at + 1] = g;
this.data[at + 2] = b;
this.data[at + 3] = a;
}
}
const NEIGHBOURS = [[1, 0], [0, 1], [-1, 0], [0, -1]] as const;
/** Light from the top left: rim-lit upper-left edges, shaded lower-right edges, then a selective outline in a dark tone of the colour it borders. */
export function finishSprite(grid: PixelGrid): void {
const source = grid.data.slice();
const opaque = (x: number, y: number) => x >= 0 && y >= 0 && x < grid.w && y < grid.h && source[(y * grid.w + x) * 4 + 3]! > 0;
for (let y = 0; y < grid.h; y++) {
for (let x = 0; x < grid.w; x++) {
const at = (y * grid.w + x) * 4;
if (opaque(x, y)) {
const factor = !opaque(x - 1, y) || !opaque(x, y - 1) ? 1.14 : !opaque(x + 1, y) || !opaque(x, y + 1) ? 0.84 : 1;
for (let c = 0; c < 3; c++) grid.data[at + c] = source[at + c]! * factor;
continue;
}
for (const [dx, dy] of NEIGHBOURS) {
if (!opaque(x + dx, y + dy)) continue;
const from = ((y + dy) * grid.w + x + dx) * 4;
for (let c = 0; c < 3; c++) grid.data[at + c] = source[from + c]! * 0.32;
grid.data[at + 3] = 255;
break;
}
}
}
}
/** Mixes two colours; `amount` 0 keeps the first. */
export function mix(a: string, b: string, amount: number): string {
const [ar, ag, ab] = rgb(a);
const [br, bg, bb] = rgb(b);
const channel = (from: number, to: number) => Math.round(from + (to - from) * amount);
return hex(channel(ar, br), channel(ag, bg), channel(ab, bb));
}
/** Scales a colour's channels; below 1 darkens. */
export function tone(color: string, factor: number): string {
const [r, g, b] = rgb(color);
const channel = (value: number) => Math.max(0, Math.min(255, Math.round(value * factor)));
return hex(channel(r), channel(g), channel(b));
}
function rgb(color: string): [number, number, number] {
if (!/^#[0-9a-f]{6}$/i.test(color)) throw new Error(`Sprite colours are #rrggbb, not "${color}".`);
const value = Number.parseInt(color.slice(1), 16);
return [(value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff];
}
function hex(r: number, g: number, b: number): string {
return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, "0")}`;
}
+101
View File
@@ -0,0 +1,101 @@
import type { OfficeState } from "./agent-state";
import type { Rect } from "./office-types";
import { drawBox, setSouthFaceTransform, toIso, type IsoFrame } from "./iso";
/** Hand angles in radians, clockwise from twelve, for a local time. */
export function clockHands(date: Date): { hour: number; minute: number } {
const minutes = date.getMinutes();
return {
hour: (((date.getHours() % 12) + minutes / 60) / 12) * 2 * Math.PI,
minute: (minutes / 60) * 2 * Math.PI,
};
}
/** A 16-pixel wall clock in wall-face coordinates (x along the wall, y down), showing the real time. */
export function drawWallClock(ctx: CanvasRenderingContext2D, x: number, y: number, date: Date): void {
ctx.fillStyle = "#3f3831";
ctx.fillRect(x + 2, y, 12, 16);
ctx.fillRect(x, y + 2, 16, 12);
ctx.fillStyle = "#f2efe8";
ctx.fillRect(x + 2, y + 2, 12, 12);
ctx.fillStyle = "#8a8378";
for (const [tx, ty] of [[7, 2], [12, 7], [7, 12], [2, 7]] as const) ctx.fillRect(x + tx, y + ty, 2, 1);
const hands = clockHands(date);
hand(ctx, x + 8, y + 8, hands.minute, 5, "#2b2622");
hand(ctx, x + 8, y + 8, hands.hour, 3, "#b3543f");
}
function hand(ctx: CanvasRenderingContext2D, cx: number, cy: number, angle: number, length: number, color: string): void {
ctx.fillStyle = color;
for (let step = 0; step <= length; step++) {
ctx.fillRect(Math.round(cx + Math.sin(angle) * step - 0.5), Math.round(cy - Math.cos(angle) * step - 0.5), 1, 1);
}
}
/** A desk monitor's screen on its south face: scrolling code while running, a progress dot for queued, an amber sweep for a cooldown, a blinking red mark when blocked, a standby light when idle. */
export function drawMonitorScreen(ctx: CanvasRenderingContext2D, frame: IsoFrame, monitor: Rect, z: number, height: number, state: OfficeState, timeMs: number, seed: number): void {
ctx.save();
setSouthFaceTransform(ctx, frame, monitor.y + monitor.h, z + height);
const glass = { x: monitor.x + 2, y: 2, w: monitor.w - 4, h: height - 4 };
ctx.fillStyle = state === "running" ? "#0f2a1c" : state === "blocked" ? "#2a1012" : "#20242c";
ctx.fillRect(glass.x, glass.y, glass.w, glass.h);
if (state === "running") {
const scroll = Math.floor(timeMs / 350);
ctx.fillStyle = "#37d38a";
for (let row = 0; row < 4; row++) {
const width = 4 + ((seed * 7 + (scroll + row) * 13) % (glass.w - 6));
ctx.fillRect(glass.x + 1 + (row % 2) * 2, glass.y + 1 + row * 2, width, 1);
}
if (Math.floor(timeMs / 500) % 2 === 0) ctx.fillRect(glass.x + glass.w - 3, glass.y + glass.h - 2, 2, 1);
} else if (state === "queued") {
ctx.fillStyle = "#9aa3b2";
for (let dot = 0; dot <= Math.floor(timeMs / 400) % 3; dot++) ctx.fillRect(glass.x + 2 + dot * 3, glass.y + glass.h / 2, 2, 1);
} else if (state === "cooldown") {
ctx.fillStyle = "#e0a23a";
ctx.fillRect(glass.x + 1, glass.y + glass.h / 2, Math.max(1, (glass.w - 2) * (1 - ((timeMs / 4000) % 1))), 1);
} else if (state === "blocked") {
if (Math.floor(timeMs / 500) % 2 === 0) {
ctx.fillStyle = "#ef4444";
const cx = Math.round(glass.x + glass.w / 2);
ctx.fillRect(cx, glass.y + 1, 1, glass.h - 4);
ctx.fillRect(cx, glass.y + glass.h - 2, 1, 1);
}
} else {
ctx.fillStyle = "#e0a23a";
ctx.fillRect(glass.x + glass.w - 2, glass.y + glass.h - 1, 1, 1);
}
ctx.restore();
}
/** The snack bar's coffee machine: body, cap, a lit button and a cup, with steam curling up from the cup. */
export function drawCoffeeMachine(ctx: CanvasRenderingContext2D, frame: IsoFrame, foot: Rect, z: number, timeMs: number): void {
drawBox(ctx, frame, foot, z, 14, { top: "#454b52", south: "#2e3238", east: "#23262b" });
drawBox(ctx, frame, { x: foot.x + 1, y: foot.y + 1, w: foot.w - 2, h: 5 }, z + 14, 3, { top: "#5a616a", south: "#3c4249", east: "#30353b" });
ctx.save();
setSouthFaceTransform(ctx, frame, foot.y + foot.h, z + 14);
ctx.fillStyle = Math.floor(timeMs / 700) % 2 === 0 ? "#e2553b" : "#8f3426";
ctx.fillRect(foot.x + 2, 2, 2, 2);
ctx.fillStyle = "#d8d3c8";
ctx.fillRect(foot.x + foot.w / 2 - 2, 9, 4, 4);
ctx.restore();
const cup = toIso(frame, { x: foot.x + foot.w / 2, y: foot.y + foot.h }, z + 6);
for (let puff = 0; puff < 3; puff++) {
const rise = ((timeMs / 120 + puff * 5) % 15);
ctx.fillStyle = `rgba(242,242,245,${0.75 * (1 - rise / 15)})`;
ctx.fillRect(Math.round(cup.x + Math.sin((rise + puff) / 2) * 1.5), Math.round(cup.y - 4 - rise), 1, 1);
}
}
/** A toilet against the back wall: tank and bowl in porcelain white, the bowl's opening shaded. */
export function drawToilet(ctx: CanvasRenderingContext2D, frame: IsoFrame, cx: number, backY: number): void {
const porcelain = { top: "#f4f6f8", south: "#d9dee4", east: "#c3c9d0" };
drawBox(ctx, frame, { x: cx - 6, y: backY, w: 12, h: 5 }, 0, 16, porcelain);
drawBox(ctx, frame, { x: cx - 5, y: backY + 5, w: 10, h: 11 }, 0, 8, porcelain);
drawBox(ctx, frame, { x: cx - 3, y: backY + 7, w: 6, h: 7 }, 8, 0, { top: "#9fb2c4", south: "#9fb2c4", east: "#9fb2c4" });
}
/** A wash basin set into a counter top at height `z`: a pale rim around a shaded bowl. */
export function drawBasin(ctx: CanvasRenderingContext2D, frame: IsoFrame, basin: Rect, z: number): void {
drawBox(ctx, frame, basin, z, 0, { top: "#e4ebf2", south: "#e4ebf2", east: "#e4ebf2" });
drawBox(ctx, frame, { x: basin.x + 4, y: basin.y + 3, w: basin.w - 8, h: basin.h - 6 }, z, 0, { top: "#8fa3b7", south: "#8fa3b7", east: "#8fa3b7" });
}
+11
View File
@@ -0,0 +1,11 @@
/** Agents who come to the office, in hire order: the office and the org chart read the same list. */
export function officeRoster<T extends { id: string; lifecycle: string; createdAt: string }>(agents: T[]): T[] {
return agents
.filter((agent) => agent.lifecycle === "active")
.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
}
/** The first c-suite agent on the roster holds the CEO office and wears the CEO's look. */
export function ceoIdOf(roster: Array<{ id: string; roleLevel: string }>): string | null {
return roster.find((agent) => agent.roleLevel === "c_suite")?.id ?? null;
}
+294 -302
View File
@@ -1,24 +1,33 @@
import type { OfficeState } from "./agent-state";
import type { FloorPlan, Rect, RoomSpec } from "./office-types";
import { WALL } from "./floor-plan";
import { drawWindowSky, type SkyScene } from "./sky";
import { drawWeather, drawWindowSky, type SkyScene, type Weather } from "./sky";
import { BACK_WALL_H, depthOf, drawBox, setGroundTransform, setSouthFaceTransform, type BoxColors, type IsoFrame } from "./iso";
import { drawBasin, drawCoffeeMachine, drawMonitorScreen, drawToilet, drawWallClock } from "./props";
import type { Season } from "../../shared/palette-clock";
/**
* Draws the static office world in a 3/4 top-down pixel style: wood floor,
* room interiors, wall faces with windows, furniture, and door signage.
* Everything here is a pure function of the floor plan and the visible rect.
*/
/** One thing in the scene that people can stand in front of or behind; drawn in depth order with them. */
export interface Drawable {
depth: number;
draw: (ctx: CanvasRenderingContext2D) => void;
}
/** Height of the visible north-wall face inside each room. */
export const WALL_FACE_H = 48;
/** A piece of the scene and the plan footprint it sorts by; grounded pieces cast a contact shadow. */
export interface SceneDrawable extends Drawable {
foot: Rect;
grounded: boolean;
}
/** Interior walls are cut away to this height so rooms stay visible. */
const INNER_WALL_H = 14;
/** Longest side of a block that sorts as one piece. */
const PIECE = 32;
const PALETTE = {
wood: "#b08a62",
woodSeam: "#9c7852",
corridor: "#a8815c",
wallFill: "#4c4239",
wallEdge: "#3b332c",
wallFace: "#6b5f52",
wallFaceShadow: "#5d5246",
wall: "#6b5f52",
wallTop: "#4c4239",
baseboard: "#4f463c",
ceoCarpet: "#5c6a94",
ceoCarpetEdge: "#505d85",
@@ -28,50 +37,56 @@ const PALETTE = {
snackTileB: "#cbb891",
restTileA: "#adbfd2",
restTileB: "#9db0c5",
deskWood: "#8a6d4c",
deskWoodDark: "#75593b",
deskLeg: "#5f4832",
screenOff: "#20242c",
monitorShell: "#4b5058",
desk: "#8a6d4c",
deskExec: "#6a5238",
monitor: "#4b5058",
chair: "#3d4148",
chairDark: "#33373d",
frame: "#3f3831",
signPlate: "#2f2a25",
signText: "#d8cfc2",
panelSeam: "#5d5246",
} as const;
export function drawWorld(ctx: CanvasRenderingContext2D, plan: FloorPlan, view: Rect, sky: SkyScene): void {
drawFloor(ctx, plan, view);
for (const room of plan.rooms) drawRoomFloor(ctx, room);
drawStructure(ctx, plan, sky);
for (const room of plan.rooms) drawRoomFurniture(ctx, plan, room);
drawCorridorPlants(ctx, plan);
for (const desk of plan.desks) {
if (rectsTouch(view, expand(desk.bounds, 40))) drawDesk(ctx, desk.bounds, false);
}
for (const room of plan.rooms) drawDoorSign(ctx, room);
drawEntrance(ctx, plan);
const PLANKS = ["#b08a62", "#b8936a", "#a9845c", "#b48e65"];
const LEAVES: Record<Season, { leaf: string; light: string }> = {
spring: { leaf: "#5f9a52", light: "#e9a3c2" },
summer: { leaf: "#3f7f3a", light: "#6fb25c" },
autumn: { leaf: "#b5652a", light: "#e0a23a" },
winter: { leaf: "#5a7466", light: "#e8eef2" },
};
/** Top, south and east faces of a block from one base colour: lit from above, the east side darkest. */
export function faces(hex: string): BoxColors {
return { top: hex, south: shade(hex, 0.82), east: shade(hex, 0.66) };
}
/** The monitor screen glass for a desk; the activity glow overlay reuses it. */
export function deskScreenRect(desk: Rect): Rect {
return { x: desk.x + desk.w / 2 - 13, y: desk.y - 15, w: 26, h: 15 };
}
function drawFloor(ctx: CanvasRenderingContext2D, plan: FloorPlan, view: Rect): void {
/** Floor, rugs and tiles, flat on the ground plane. */
export function drawGround(ctx: CanvasRenderingContext2D, frame: IsoFrame, plan: FloorPlan): void {
ctx.save();
setGroundTransform(ctx, frame);
const { w, h } = plan.world;
ctx.fillStyle = PALETTE.wood;
ctx.fillRect(0, 0, w, h);
ctx.fillStyle = PALETTE.woodSeam;
const top = Math.max(0, Math.floor(view.y / 16) * 16);
const bottom = Math.min(h, view.y + view.h);
for (let y = top; y < bottom; y += 16) {
ctx.beginPath();
ctx.rect(0, 0, w, h);
ctx.clip();
for (let y = 0; y < h; y += 16) {
for (let x = (y / 16) % 2 === 0 ? -48 : 0; x < w; x += 96) {
const grain = (Math.imul(x + 977, 31) ^ Math.imul(y + 131, 17)) >>> 0;
ctx.fillStyle = PLANKS[grain % PLANKS.length]!;
ctx.fillRect(x, y, 96, 16);
ctx.fillStyle = PALETTE.woodSeam;
ctx.fillRect(x + 8 + (grain % 40), y + 4 + (grain % 3) * 3, 22 + (grain % 17), 1);
ctx.fillRect(x + 50 + (grain % 23), y + 10 - (grain % 2) * 4, 14, 1);
ctx.fillRect(x, y, 1, 16);
}
ctx.fillStyle = PALETTE.woodSeam;
ctx.fillRect(0, y, w, 1);
const offset = (y / 16) % 2 === 0 ? 0 : 48;
for (let x = offset; x < w; x += 96) ctx.fillRect(x, y, 1, 16);
}
ctx.fillStyle = PALETTE.corridor;
ctx.fillRect(WALL, 288, plan.world.w - 2 * WALL, 64);
ctx.fillRect(WALL, 288, w - 2 * WALL, 64);
ctx.fillStyle = "#93704f";
ctx.fillRect(WALL, 292, w - 2 * WALL, 1);
ctx.fillRect(WALL, 347, w - 2 * WALL, 1);
for (const room of plan.rooms) drawRoomFloor(ctx, room);
ctx.restore();
}
function drawRoomFloor(ctx: CanvasRenderingContext2D, room: RoomSpec): void {
@@ -82,293 +97,270 @@ function drawRoomFloor(ctx: CanvasRenderingContext2D, room: RoomSpec): void {
ctx.strokeStyle = room.kind === "ceo" ? PALETTE.ceoCarpetEdge : PALETTE.meetingCarpetEdge;
ctx.lineWidth = 2;
ctx.strokeRect(b.x + 6, b.y + 6, b.w - 12, b.h - 12);
ctx.fillStyle = room.kind === "ceo" ? "#66749e" : "#769a82";
for (let ty = b.y + 16; ty < b.y + b.h - 12; ty += 12) {
for (let tx = b.x + 16 + (((ty - b.y) / 12) % 2) * 6; tx < b.x + b.w - 12; tx += 12) ctx.fillRect(tx, ty, 2, 2);
}
return;
}
const [tileA, tileB] = room.kind === "snack"
? [PALETTE.snackTileA, PALETTE.snackTileB]
: [PALETTE.restTileA, PALETTE.restTileB];
const [tileA, tileB] = room.kind === "snack" ? [PALETTE.snackTileA, PALETTE.snackTileB] : [PALETTE.restTileA, PALETTE.restTileB];
for (let ty = 0; ty < b.h; ty += 16) {
for (let tx = 0; tx < b.w; tx += 16) {
ctx.fillStyle = ((tx + ty) / 16) % 2 === 0 ? tileA : tileB;
ctx.fillRect(b.x + tx, b.y + ty, Math.min(16, b.w - tx), Math.min(16, b.h - ty));
}
}
ctx.fillStyle = "rgba(255,255,255,0.28)";
for (let ty = 0; ty < b.h; ty += 16) ctx.fillRect(b.x, b.y + ty, b.w, 1);
for (let tx = 0; tx < b.w; tx += 16) ctx.fillRect(b.x + tx, b.y, 1, b.h);
}
function drawStructure(ctx: CanvasRenderingContext2D, plan: FloorPlan, sky: SkyScene): void {
/** Soft shadows on the floor where furniture and walls meet it, cast toward the south-east. */
export function drawContactShadows(ctx: CanvasRenderingContext2D, frame: IsoFrame, items: SceneDrawable[]): void {
ctx.save();
setGroundTransform(ctx, frame);
ctx.fillStyle = "rgba(28,18,10,0.2)";
for (const item of items) if (item.grounded) ctx.fillRect(item.foot.x + 1, item.foot.y + 1, item.foot.w + 3, item.foot.h + 3);
ctx.restore();
}
/** What the back walls show: the sky and weather outside, and the time for the wall clock. */
export interface Outside {
sky: SkyScene;
weather: Weather;
clock: Date;
timeMs: number;
}
/** The tall north and west walls, which everything stands in front of, with panels, windows, a clock and wall art on the north face. */
export function drawBackWalls(ctx: CanvasRenderingContext2D, frame: IsoFrame, plan: FloorPlan, outside: Outside): void {
const { w, h } = plan.world;
ctx.fillStyle = PALETTE.wallFill;
ctx.fillRect(0, 0, w, WALL);
ctx.fillRect(0, h - WALL, w, WALL);
ctx.fillRect(0, WALL, WALL, 280);
ctx.fillRect(0, 344, WALL, h - 344 - WALL);
ctx.fillRect(w - WALL, WALL, WALL, h - 2 * WALL);
for (const room of plan.rooms) {
const b = room.bounds;
ctx.fillStyle = PALETTE.wallFace;
ctx.fillRect(b.x, b.y, b.w, WALL_FACE_H);
ctx.fillStyle = PALETTE.wallFaceShadow;
ctx.fillRect(b.x, b.y + WALL_FACE_H - 6, b.w, 6);
ctx.fillStyle = PALETTE.baseboard;
ctx.fillRect(b.x, b.y + WALL_FACE_H, b.w, 2);
drawRoomWindows(ctx, room, sky);
}
ctx.fillStyle = PALETTE.wallFill;
ctx.fillRect(304, WALL, WALL, 272);
ctx.fillRect(624, WALL, WALL, 272);
ctx.fillRect(896, WALL, WALL, 272);
for (const room of plan.rooms) drawSouthWall(ctx, room);
ctx.fillStyle = PALETTE.wallEdge;
const wall = faces(PALETTE.wall);
drawBox(ctx, frame, { x: 0, y: WALL, w: WALL, h: 280 }, 0, BACK_WALL_H, wall);
drawBox(ctx, frame, { x: 0, y: 344, w: WALL, h: h - 344 - WALL }, 0, BACK_WALL_H, wall);
drawBox(ctx, frame, { x: 0, y: 0, w, h: WALL }, 0, BACK_WALL_H, { ...wall, top: PALETTE.wallTop });
ctx.save();
setSouthFaceTransform(ctx, frame, WALL, BACK_WALL_H);
ctx.fillStyle = PALETTE.wallTop;
ctx.fillRect(0, 0, w, 2);
}
function drawSouthWall(ctx: CanvasRenderingContext2D, room: RoomSpec): void {
const b = room.bounds;
const y = b.y + b.h;
const gapL = room.doorCx - 24;
const gapR = room.doorCx + 24;
ctx.fillStyle = PALETTE.wallFill;
ctx.fillRect(b.x - WALL, y, gapL - b.x + WALL, WALL);
ctx.fillRect(gapR, y, b.x + b.w - gapR + WALL, WALL);
ctx.fillStyle = PALETTE.wallEdge;
ctx.fillRect(b.x - WALL, y + WALL - 2, gapL - b.x + WALL, 2);
ctx.fillRect(gapR, y + WALL - 2, b.x + b.w - gapR + WALL, 2);
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(gapL - 3, y, 3, WALL);
ctx.fillRect(gapR, y, 3, WALL);
}
function drawRoomWindows(ctx: CanvasRenderingContext2D, room: RoomSpec, sky: SkyScene): void {
const rects = windowRects(room);
for (let i = 0; i < rects.length; i++) {
drawWindowFrame(ctx, rects[i], sky, Math.round(room.bounds.x) + i * 53);
ctx.fillStyle = PALETTE.panelSeam;
for (let x = 32; x < w; x += 32) ctx.fillRect(x, 2, 1, BACK_WALL_H - 5);
ctx.fillStyle = "#62574b";
ctx.fillRect(0, BACK_WALL_H - 14, w, 11);
ctx.fillStyle = "#857766";
ctx.fillRect(0, BACK_WALL_H - 15, w, 1);
ctx.fillStyle = PALETTE.baseboard;
ctx.fillRect(0, BACK_WALL_H - 3, w, 3);
for (const room of plan.rooms) {
windowRects(room).forEach((rect, index) => {
const seed = Math.round(room.bounds.x) + index * 53;
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(rect.x - 2, rect.y - 2, rect.w + 4, rect.h + 4);
drawWindowSky(ctx, rect, outside.sky, seed);
drawWeather(ctx, rect, outside.weather, outside.timeMs, seed);
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(rect.x + rect.w / 2 - 1, rect.y, 2, rect.h);
ctx.fillStyle = "#9c8f7c";
ctx.fillRect(rect.x - 3, rect.y + rect.h + 2, rect.w + 6, 1);
ctx.fillStyle = "#b9a98f";
ctx.fillRect(rect.x - 7, rect.y - 3, 5, rect.h + 6);
ctx.fillRect(rect.x + rect.w + 2, rect.y - 3, 5, rect.h + 6);
ctx.fillStyle = "#a39278";
ctx.fillRect(rect.x - 5, rect.y - 3, 1, rect.h + 6);
ctx.fillRect(rect.x + rect.w + 4, rect.y - 3, 1, rect.h + 6);
});
}
drawWallArt(ctx);
drawWallClock(ctx, 664, 10, outside.clock);
ctx.restore();
}
/** Window glass rects on each room's north wall face (world coordinates). */
/** Window glass on each room's stretch of the north wall face: x along the wall, y down from its top. */
export function windowRects(room: RoomSpec): Rect[] {
const b = room.bounds;
const y = b.y + 8;
const h = WALL_FACE_H - 20;
if (room.kind === "restroom") {
return [{ x: b.x + b.w - 190, y: y + 6, w: 44, h: h - 10 }];
if (room.kind === "restroom") return [{ x: b.x + b.w - 190, y: 12, w: 44, h: 18 }];
if (room.kind === "snack") return [{ x: b.x + 104, y: 8, w: 72, h: 24 }];
return [{ x: b.x + 28, y: 8, w: 72, h: 24 }, { x: b.x + b.w - 100, y: 8, w: 72, h: 24 }];
}
function drawWallArt(ctx: CanvasRenderingContext2D): void {
// CEO office wall screen and meeting-room whiteboard, between their windows.
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(143, 8, 34, 22);
ctx.fillStyle = "#7f96b8";
ctx.fillRect(145, 10, 30, 18);
ctx.fillStyle = "#f2efe8";
ctx.fillRect(424, 6, 96, 28);
ctx.fillStyle = "#b3543f";
ctx.fillRect(432, 12, 26, 3);
ctx.fillStyle = "#4f7fae";
ctx.fillRect(432, 19, 40, 3);
ctx.fillStyle = "#6d9c6b";
ctx.fillRect(432, 26, 33, 3);
// Restroom mirror over the sinks.
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(934, 8, 84, 22);
ctx.fillStyle = "#b9d3e6";
ctx.fillRect(936, 10, 80, 18);
ctx.fillStyle = "#e3f0f8";
ctx.fillRect(944, 12, 2, 12);
ctx.fillRect(948, 12, 1, 8);
}
/** A block sorted by its footprint centre; one resting on `support` touches exactly one piece of it (overhanging its outer edge is fine) and sorts just after that piece. */
export function blockDrawable(frame: IsoFrame, foot: Rect, height: number, colors: BoxColors, z = 0, support?: Rect): SceneDrawable {
return { foot, grounded: z === 0 && !support, depth: support ? restingDepth(foot, support) : centerDepth(foot), draw: (ctx) => drawBox(ctx, frame, foot, z, height, colors) };
}
function restingDepth(foot: Rect, support: Rect): number {
const under = split(support).filter((piece) => overlaps(piece, foot));
if (under.length !== 1) throw new Error("A resting block must touch exactly one piece of its support.");
return centerDepth(under[0]!) + 0.25;
}
function centerDepth(rect: Rect): number {
return depthOf({ x: rect.x + rect.w / 2, y: rect.y + rect.h / 2 });
}
/** Interior walls, furniture and desks as blocks, each sorted by depth against the people; `screens` gives each desk's screen its agent's state, and `timeMs` animates screens and steam. */
export function sceneDrawables(frame: IsoFrame, plan: FloorPlan, season: Season, screens: Map<Rect, OfficeState>, timeMs: number): SceneDrawable[] {
const items: SceneDrawable[] = [];
// Long blocks go in pieces so each sorts against nearby people on its own.
const block = (foot: Rect, height: number, colors: BoxColors, z = 0, support?: Rect) => {
for (const piece of support ? [foot] : split(foot)) items.push(blockDrawable(frame, piece, height, colors, z, support));
};
for (const wall of innerWalls(plan)) block(wall, INNER_WALL_H, faces(PALETTE.wall));
const leaves = LEAVES[season];
const plant = (cx: number, cy: number) => {
const pot = { x: cx - 6, y: cy - 6, w: 12, h: 12 };
block(pot, 8, faces("#8a5a3b"));
block({ x: cx - 8, y: cy - 8, w: 16, h: 16 }, 12, faces(leaves.leaf), 8, pot);
block({ x: cx - 4, y: cy - 4, w: 8, h: 8 }, 6, faces(leaves.light), 20, pot);
};
// CEO office: rug, executive desk, sofa, plant.
block({ x: 32, y: 96, w: 24, h: 72 }, 10, faces("#7a4a41"));
plant(280, 40);
deskBlocks(plan.ceoDesk, true, screens.get(plan.ceoDesk) ?? "idle", timeMs).forEach((item) => items.push(item(frame)));
// Meeting room: table and chairs.
block({ x: 392, y: 120, w: 160, h: 64 }, 12, faces("#75593b"));
for (let i = 0; i < 3; i++) {
block({ x: 414 + i * 52, y: 100, w: 14, h: 12 }, 8, faces(PALETTE.chair));
block({ x: 414 + i * 52, y: 192, w: 14, h: 12 }, 8, faces(PALETTE.chair));
}
if (room.kind === "snack") {
return [{ x: b.x + 24, y, w: 72, h }];
// Snack bar: counter, fridge, coffee machine, table and stools.
const counter = { x: 656, y: 40, w: 224, h: 28 };
block(counter, 16, faces("#8f8578"));
block({ x: 700, y: 20, w: 24, h: 20 }, 22, faces("#d5dade"));
const machine = { x: 726, y: 44, w: 14, h: 14 };
items.push({ foot: machine, grounded: false, depth: restingDepth(machine, counter), draw: (ctx) => drawCoffeeMachine(ctx, frame, machine, 16, timeMs) });
block({ x: 792, y: 46, w: 12, h: 10 }, 8, faces("#c9a86a"), 16, counter);
block({ x: 826, y: 46, w: 12, h: 10 }, 10, faces("#b3543f"), 16, counter);
block({ x: 748, y: 170, w: 40, h: 40 }, 12, faces("#94897b"));
block({ x: 728, y: 182, w: 12, h: 12 }, 7, faces("#6d5334"));
block({ x: 796, y: 182, w: 12, h: 12 }, 7, faces("#6d5334"));
// Restroom: three open stalls with toilets between partitions, and a sink counter.
for (let i = 0; i < 3; i++) {
const cx = 1084 + i * 40;
const toilet = { x: cx - 6, y: WALL + 2, w: 12, h: 16 };
items.push({ foot: toilet, grounded: true, depth: centerDepth(toilet), draw: (ctx) => drawToilet(ctx, frame, cx, WALL + 2) });
}
const w = 72;
for (let i = 0; i <= 3; i++) block({ x: 1063 + i * 40, y: WALL, w: 2, h: 48 }, INNER_WALL_H, faces("#7d8a99"));
const sinks = { x: 928, y: 32, w: 96, h: 32 };
block(sinks, 14, { top: "#c6d2de", south: "#a7b4c2", east: "#909eae" });
for (let i = 0; i < 2; i++) {
const basin = { x: sinks.x + 2 + i * 64, y: sinks.y + 8, w: 28, h: 16 };
items.push({ foot: basin, grounded: false, depth: restingDepth(basin, sinks), draw: (ctx) => drawBasin(ctx, frame, basin, 14) });
}
for (const [cx, cy] of [[312, 300], [632, 300], [904, 300]] as const) plant(cx, cy);
for (const desk of plan.desks) deskBlocks(desk.bounds, false, screens.get(desk.bounds) ?? "idle", timeMs).forEach((item) => items.push(item(frame)));
return items;
}
/** A desk with its monitor, keyboard and clutter, and the office chair in front of it, each a separate block so a seated person sorts between them. */
function deskBlocks(desk: Rect, executive: boolean, screen: OfficeState, timeMs: number): Array<(frame: IsoFrame) => SceneDrawable> {
const monitor = deskMonitor(desk);
const middle = desk.x + Math.floor(desk.w / 2 / PIECE) * PIECE;
const seed = Math.round(desk.x + desk.y);
const on = (foot: Rect, height: number, colors: BoxColors, z = 14) => (frame: IsoFrame) => blockDrawable(frame, foot, height, colors, z, desk);
const parts: Array<(frame: IsoFrame) => SceneDrawable> = [
...split(desk).map((piece) => (frame: IsoFrame) => blockDrawable(frame, piece, 14, faces(executive ? PALETTE.deskExec : PALETTE.desk))),
on({ x: monitor.x + 11, y: monitor.y + 1, w: 4, h: 4 }, 2, faces("#3a3e45")),
(frame) => {
const shell = blockDrawable(frame, monitor, 12, { top: PALETTE.monitor, south: PALETTE.monitor, east: shade(PALETTE.monitor, 0.7) }, 16, desk);
return { foot: monitor, grounded: false, depth: shell.depth, draw: (ctx) => {
shell.draw(ctx);
drawMonitorScreen(ctx, frame, monitor, 16, 12, screen, timeMs, seed);
} };
},
on({ x: middle + 5, y: desk.y + 16, w: 20, h: 6 }, 1, { top: "#d9dce0", south: "#b8bcc2", east: "#a6abb2" }),
on({ x: middle + 27, y: desk.y + 18, w: 3, h: 4 }, 1, faces("#cfd3d8")),
...chairBlocks(desk.x + desk.w / 2, desk.y + desk.h + 6),
];
if (seed % 2 === 0) parts.push(on({ x: desk.x + 10, y: desk.y + 10, w: 5, h: 5 }, 5, { top: "#6b4a2f", south: "#e8e3d8", east: "#cfc9bc" }));
if (seed % 3 === 0) parts.push(on({ x: desk.x + desk.w - 14, y: desk.y + 8, w: 10, h: 12 }, 2, faces("#f4f1ea")));
if (seed % 3 === 1) {
parts.push(on({ x: desk.x + desk.w - 13, y: desk.y + 6, w: 8, h: 8 }, 4, faces("#c9693f")));
parts.push(on({ x: desk.x + desk.w - 14, y: desk.y + 5, w: 10, h: 10 }, 6, faces("#4f8a45"), 18));
}
if (executive) {
parts.push(on({ x: desk.x + 8, y: desk.y + 6, w: 6, h: 6 }, 1, faces("#b89448")));
parts.push(on({ x: desk.x + 10, y: desk.y + 8, w: 2, h: 2 }, 10, faces("#b89448"), 15));
parts.push(on({ x: desk.x + 7, y: desk.y + 5, w: 8, h: 8 }, 4, faces("#2f5d4a"), 25));
}
return parts;
}
/** An office chair: five-star base, gas lift, cushioned seat, and a backrest on the desk side that the sitter covers. */
function chairBlocks(cx: number, y: number): Array<(frame: IsoFrame) => SceneDrawable> {
return [
{ x: b.x + 28, y, w, h },
{ x: b.x + b.w - 28 - w, y, w, h },
(frame) => blockDrawable(frame, { x: cx - 7, y: y + 1, w: 14, h: 10 }, 2, faces("#2d3036")),
(frame) => blockDrawable(frame, { x: cx - 1, y: y + 5, w: 2, h: 2 }, 5, faces("#5d6168"), 2),
(frame) => blockDrawable(frame, { x: cx - 8, y, w: 16, h: 11 }, 3, faces("#4a5060"), 7),
(frame) => blockDrawable(frame, { x: cx - 8, y, w: 16, h: 3 }, 11, faces(PALETTE.chair), 8),
];
}
function drawWindowFrame(ctx: CanvasRenderingContext2D, rect: Rect, sky: SkyScene, seed: number): void {
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(rect.x - 3, rect.y - 3, rect.w + 6, rect.h + 6);
drawWindowSky(ctx, rect, sky, seed);
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(rect.x + rect.w / 2 - 1, rect.y, 2, rect.h);
/** Footprint of a desk's monitor, at the back of the desktop with its screen facing south, inside the desk piece that holds the desk's centre. */
function deskMonitor(desk: Rect): Rect {
const piece = Math.floor(desk.w / 2 / PIECE) * PIECE;
return { x: desk.x + piece + 3, y: desk.y + 4, w: 26, h: 6 };
}
function drawRoomFurniture(ctx: CanvasRenderingContext2D, plan: FloorPlan, room: RoomSpec): void {
if (room.kind === "ceo") drawCeoFurniture(ctx, plan);
if (room.kind === "meeting") drawMeetingFurniture(ctx);
if (room.kind === "snack") drawSnackFurniture(ctx);
if (room.kind === "restroom") drawRestroomFurniture(ctx);
}
function drawCeoFurniture(ctx: CanvasRenderingContext2D, plan: FloorPlan): void {
const desk = plan.ceoDesk;
ctx.fillStyle = "#414b6e";
ctx.fillRect(desk.x - 16, desk.y - 8, desk.w + 32, desk.h + 40);
drawDesk(ctx, desk, true);
drawSofa(ctx, 32, 96);
drawPlant(ctx, 280, 48);
// Wall screen centered in the gap between the two windows (116..204).
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(143, 24, 34, 22);
ctx.fillStyle = "#7f96b8";
ctx.fillRect(145, 26, 30, 18);
ctx.fillStyle = "#5c7a9c";
ctx.fillRect(145, 36, 30, 8);
}
function drawMeetingFurniture(ctx: CanvasRenderingContext2D): void {
const table: Rect = { x: 392, y: 120, w: 160, h: 64 };
ctx.fillStyle = PALETTE.deskWoodDark;
ctx.fillRect(table.x, table.y, table.w, table.h);
ctx.fillStyle = PALETTE.deskWood;
ctx.fillRect(table.x + 3, table.y + 3, table.w - 6, table.h - 9);
for (let i = 0; i < 3; i++) {
drawChair(ctx, table.x + 22 + i * 52, table.y - 16);
drawChair(ctx, table.x + 22 + i * 52, table.y + table.h + 4);
/** Partitions, room fronts (with door gaps) and the low outer east and south walls. */
function innerWalls(plan: FloorPlan): Rect[] {
const { w, h } = plan.world;
const walls: Rect[] = [
{ x: 304, y: WALL, w: WALL, h: 272 },
{ x: 624, y: WALL, w: WALL, h: 272 },
{ x: 896, y: WALL, w: WALL, h: 272 },
{ x: w - WALL, y: WALL, w: WALL, h: h - 2 * WALL },
{ x: 0, y: h - WALL, w, h: WALL },
];
for (const room of plan.rooms) {
const b = room.bounds;
const y = b.y + b.h;
walls.push({ x: b.x - WALL, y, w: room.doorCx - 24 - b.x + WALL, h: WALL });
walls.push({ x: room.doorCx + 24, y, w: b.x + b.w - room.doorCx - 24 + WALL, h: WALL });
}
// Whiteboard centered in the gap between the two windows (420..524).
ctx.fillStyle = "#f2efe8";
ctx.fillRect(424, 22, 96, 30);
ctx.fillStyle = PALETTE.frame;
ctx.strokeStyle = PALETTE.frame;
ctx.lineWidth = 2;
ctx.strokeRect(424, 22, 96, 30);
ctx.fillStyle = "#b3543f";
ctx.fillRect(432, 30, 26, 3);
ctx.fillStyle = "#4f7fae";
ctx.fillRect(432, 38, 40, 3);
ctx.fillStyle = "#6d9c6b";
ctx.fillRect(432, 44, 33, 3);
return walls;
}
function drawSnackFurniture(ctx: CanvasRenderingContext2D): void {
ctx.fillStyle = "#8f8578";
ctx.fillRect(656, 40, 224, 28);
ctx.fillStyle = "#a99e8f";
ctx.fillRect(656, 40, 224, 8);
ctx.fillStyle = "#d5dade";
ctx.fillRect(660, 8, 30, 48);
ctx.fillStyle = "#b9c0c6";
ctx.fillRect(660, 30, 30, 3);
ctx.fillRect(682, 14, 4, 12);
drawCoffeeMachine(ctx, 694, 26);
ctx.fillStyle = "#c9a86a";
ctx.fillRect(806, 30, 14, 12);
ctx.fillStyle = "#b3543f";
ctx.fillRect(826, 28, 12, 14);
ctx.fillStyle = "#6d9c6b";
ctx.fillRect(844, 30, 12, 12);
ctx.fillStyle = "#94897b";
ctx.fillRect(748, 170, 40, 40);
ctx.fillStyle = "#a89d8e";
ctx.fillRect(751, 173, 34, 34);
drawStool(ctx, 738, 184);
drawStool(ctx, 792, 184);
}
function drawCoffeeMachine(ctx: CanvasRenderingContext2D, x: number, y: number): void {
ctx.fillStyle = "#2e3238";
ctx.fillRect(x, y, 22, 30);
ctx.fillStyle = "#454b52";
ctx.fillRect(x + 2, y + 2, 18, 8);
ctx.fillStyle = "#c9553e";
ctx.fillRect(x + 8, y + 12, 6, 4);
ctx.fillStyle = "#d8d3c8";
ctx.fillRect(x + 7, y + 20, 8, 7);
}
function drawRestroomFurniture(ctx: CanvasRenderingContext2D): void {
for (let i = 0; i < 3; i++) {
const x = 1064 + i * 40;
ctx.fillStyle = "#7d8a99";
ctx.fillRect(x, 16, 40, 72);
ctx.fillStyle = "#8f9dad";
ctx.fillRect(x + 4, 28, 32, 58);
ctx.fillStyle = "#6c7887";
ctx.fillRect(x + 30, 54, 4, 8);
function split(block: Rect): Rect[] {
const pieces: Rect[] = [];
for (let dy = 0; dy < block.h; dy += PIECE) {
for (let dx = 0; dx < block.w; dx += PIECE) {
pieces.push({ x: block.x + dx, y: block.y + dy, w: Math.min(PIECE, block.w - dx), h: Math.min(PIECE, block.h - dy) });
}
}
ctx.fillStyle = "#c6d2de";
ctx.fillRect(928, 32, 96, 32);
ctx.fillStyle = "#e4ebf2";
for (let i = 0; i < 2; i++) ctx.fillRect(940 + i * 44, 38, 28, 14);
ctx.fillStyle = "#aab8c6";
ctx.fillRect(936, 18, 80, 10);
return pieces;
}
function drawCorridorPlants(ctx: CanvasRenderingContext2D, plan: FloorPlan): void {
void plan;
drawPlant(ctx, 312, 300);
drawPlant(ctx, 632, 300);
drawPlant(ctx, 904, 300);
}
function drawPlant(ctx: CanvasRenderingContext2D, cx: number, cy: number): void {
ctx.fillStyle = "#8a5a3b";
ctx.fillRect(cx - 7, cy, 14, 10);
ctx.fillStyle = "#4e7a46";
ctx.fillRect(cx - 9, cy - 12, 18, 12);
ctx.fillStyle = "#659a58";
ctx.fillRect(cx - 5, cy - 18, 10, 8);
}
function drawSofa(ctx: CanvasRenderingContext2D, x: number, y: number): void {
ctx.fillStyle = "#7a4a41";
ctx.fillRect(x, y, 24, 72);
ctx.fillStyle = "#94594e";
ctx.fillRect(x + 8, y + 4, 16, 64);
}
function drawChair(ctx: CanvasRenderingContext2D, x: number, y: number): void {
ctx.fillStyle = PALETTE.chairDark;
ctx.fillRect(x, y, 16, 12);
ctx.fillStyle = PALETTE.chair;
ctx.fillRect(x + 2, y + 2, 12, 8);
}
function drawStool(ctx: CanvasRenderingContext2D, x: number, y: number): void {
ctx.fillStyle = "#6d5334";
ctx.fillRect(x, y, 10, 10);
}
function drawDesk(ctx: CanvasRenderingContext2D, desk: Rect, executive: boolean): void {
ctx.fillStyle = PALETTE.deskLeg;
ctx.fillRect(desk.x + 4, desk.y + desk.h - 6, 5, 10);
ctx.fillRect(desk.x + desk.w - 9, desk.y + desk.h - 6, 5, 10);
ctx.fillStyle = executive ? "#5f4a33" : PALETTE.deskWoodDark;
ctx.fillRect(desk.x, desk.y, desk.w, desk.h);
ctx.fillStyle = executive ? "#75593b" : PALETTE.deskWood;
ctx.fillRect(desk.x + 2, desk.y + 2, desk.w - 4, desk.h - 7);
const screen = deskScreenRect(desk);
ctx.fillStyle = PALETTE.monitorShell;
ctx.fillRect(screen.x - 2, screen.y - 2, screen.w + 4, screen.h + 4);
ctx.fillStyle = PALETTE.screenOff;
ctx.fillRect(screen.x, screen.y, screen.w, screen.h);
ctx.fillStyle = PALETTE.monitorShell;
ctx.fillRect(screen.x + screen.w / 2 - 3, screen.y + screen.h + 2, 6, 3);
if (executive) {
ctx.fillStyle = "#d8d3c8";
ctx.fillRect(desk.x + desk.w - 22, desk.y + 8, 12, 8);
ctx.fillStyle = "#4e7a46";
ctx.fillRect(desk.x + 8, desk.y + 6, 8, 10);
}
ctx.fillStyle = "#23262b";
ctx.fillRect(desk.x + desk.w / 2 - 8, desk.y + desk.h - 12, 16, 5);
drawChair(ctx, desk.x + desk.w / 2 - 8, desk.y + desk.h + 4);
}
function drawDoorSign(ctx: CanvasRenderingContext2D, room: RoomSpec): void {
const label = room.label;
ctx.font = "bold 8px monospace";
const width = ctx.measureText(label).width + 10;
const x = room.doorCx - width / 2;
const y = room.bounds.y + room.bounds.h - 13;
ctx.fillStyle = PALETTE.signPlate;
ctx.fillRect(x, y, width, 12);
ctx.fillStyle = PALETTE.signText;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillText(label, room.doorCx, y + 7);
ctx.textAlign = "start";
ctx.textBaseline = "alphabetic";
}
function drawEntrance(ctx: CanvasRenderingContext2D, plan: FloorPlan): void {
void plan;
ctx.fillStyle = PALETTE.frame;
ctx.fillRect(0, 292, 4, 56);
ctx.fillStyle = "#7fb3d9";
ctx.fillRect(4, 296, 4, 48);
ctx.fillStyle = "#8d6a45";
ctx.fillRect(20, 300, 26, 40);
ctx.fillStyle = "#9c7852";
ctx.fillRect(22, 302, 22, 36);
}
function rectsTouch(a: Rect, b: Rect): boolean {
function overlaps(a: Rect, b: Rect): boolean {
return a.x < b.x + b.w && a.x + a.w > b.x && a.y < b.y + b.h && a.y + a.h > b.y;
}
function expand(rect: Rect, margin: number): Rect {
return { x: rect.x - margin, y: rect.y - margin, w: rect.w + margin * 2, h: rect.h + margin * 2 };
function shade(hex: string, factor: number): string {
const value = Number.parseInt(hex.slice(1), 16);
const channel = (shift: number) => Math.round(((value >> shift) & 0xff) * factor);
return `rgb(${channel(16)}, ${channel(8)}, ${channel(0)})`;
}
+5 -20
View File
@@ -1,6 +1,7 @@
import { buildFloorPlan, findPath } from "./floor-plan";
import type { AmenitySpot, Camera, FloorPlan, OfficeAgentInput, Rect, Vec } from "./office-types";
import { appearanceFor, type Carrying, type Facing, type SpriteAppearance } from "./sprites";
import { ceoIdOf } from "./roster";
export type AgentBehavior =
| { kind: "seated" }
@@ -116,7 +117,7 @@ export class OfficeSimulation {
switch (agent.behavior.kind) {
case "seated": {
agent.settledMs += dt;
if (agent.input.activity === "idle" && agent.settledMs >= SETTLE_MS && this.random() < dt / MEAN_TRIP_INTERVAL_MS) {
if (agent.input.status.state === "idle" && agent.settledMs >= SETTLE_MS && this.random() < dt / MEAN_TRIP_INTERVAL_MS) {
agent.settledMs = 0;
this.startTrip(agent);
}
@@ -160,7 +161,7 @@ export class OfficeSimulation {
conveneMeeting(): number {
const spots = this.plan.amenities.filter((spot) => spot.kind === "meeting");
const candidates = this.agents.filter(
(agent) => agent.input.activity === "idle" && agent.behavior.kind === "seated" && agent.settledMs >= SETTLE_MS,
(agent) => agent.input.status.state === "idle" && agent.behavior.kind === "seated" && agent.settledMs >= SETTLE_MS,
);
if (candidates.length < 2 || spots.length < 2) return 0;
const size = Math.min(spots.length, candidates.length, 2 + Math.floor(this.random() * 3));
@@ -244,22 +245,6 @@ export class OfficeSimulation {
agent.behavior = { kind: "seated" };
}
/**
* Returns the agent whose drawn body contains the world point, preferring
* the visually frontmost (largest y). Tests against the same positions the
* renderer draws, so clicks always match what is on screen.
*/
hitTest(point: Vec): AgentSim | null {
let hit: AgentSim | null = null;
for (const agent of this.agents) {
const inBody =
point.x >= agent.x - 10 && point.x <= agent.x + 10 &&
point.y >= agent.y - 36 && point.y <= agent.y + 4;
if (inBody && (hit === null || agent.y > hit.y)) hit = agent;
}
return hit;
}
private stepPlayer(player: PlayerSim, dt: number, input: MoveInput): void {
let dx = (input.right ? 1 : 0) - (input.left ? 1 : 0);
let dy = (input.down ? 1 : 0) - (input.up ? 1 : 0);
@@ -294,7 +279,7 @@ export class OfficeSimulation {
* else takes open-floor desks in order.
*/
sync(inputs: OfficeAgentInput[]): void {
const ceoId = inputs.find((input) => input.roleLevel === "c_suite")?.id ?? null;
const ceoId = ceoIdOf(inputs);
const openCount = inputs.filter((input) => input.id !== ceoId).length;
const planRebuilt = openCount !== this.openDeskDemand;
if (planRebuilt) {
@@ -325,7 +310,7 @@ export class OfficeSimulation {
settledMs: prev?.settledMs ?? 0,
};
const onBreak = agent.behavior.kind === "dwelling" || (agent.behavior.kind === "walking" && agent.behavior.destination === "amenity");
const workStarted = input.activity !== "idle" && onBreak;
const workStarted = input.status.state !== "idle" && onBreak;
if (workStarted || (planRebuilt && prev && (agent.x !== seat.x || agent.y !== seat.y))) {
this.sendHome(agent);
}
+29
View File
@@ -1,4 +1,5 @@
import type { Rect } from "./office-types";
import { season } from "../../shared/palette-clock";
/**
* The world outside the office windows, driven by real local time: night
@@ -155,6 +156,34 @@ function drawSkyline(ctx: CanvasRenderingContext2D, glass: Rect, scene: SkyScene
}
}
export type Weather = "clear" | "rain" | "snow" | "leaves";
/** Decoration for the view outside, from the season and a per-day roll; never a forecast. */
export function weatherFor(date: Date): Weather {
const dayKey = date.getFullYear() * 400 + date.getMonth() * 32 + date.getDate();
const roll = Math.abs(Math.imul(dayKey ^ 0x5bd1e995, 2654435761) >> 7) % 100;
switch (season(date)) {
case "winter": return roll < 60 ? "snow" : "clear";
case "spring": return roll < 40 ? "rain" : "clear";
case "summer": return roll < 15 ? "rain" : "clear";
case "autumn": return roll < 45 ? "leaves" : roll < 65 ? "rain" : "clear";
}
}
/** Falling rain, snow or leaves inside a window, moving with time; each pane gets its own scatter. */
export function drawWeather(ctx: CanvasRenderingContext2D, glass: Rect, weather: Weather, timeMs: number, seed: number): void {
if (weather === "clear") return;
const style = { rain: { color: "rgba(200,220,255,0.75)", w: 1, h: 3, speed: 0.06, drift: 0.01 }, snow: { color: "#f4f6fb", w: 1, h: 1, speed: 0.008, drift: 0.004 }, leaves: { color: "#d9822b", w: 2, h: 1, speed: 0.012, drift: 0.01 } }[weather];
ctx.fillStyle = style.color;
const count = Math.max(3, Math.floor(glass.w / 6));
for (let i = 0; i < count; i++) {
const offset = (seed * 37 + i * 53) % 1000;
const fall = (offset + timeMs * style.speed) % glass.h;
const sway = (offset * 7 + timeMs * style.drift) % glass.w;
ctx.fillRect(Math.floor(glass.x + sway), Math.floor(glass.y + fall), style.w, Math.min(style.h, glass.y + glass.h - Math.floor(glass.y + fall)));
}
}
function rgb(r: number, g: number, b: number): Rgb {
return { r, g, b };
}
+57 -199
View File
@@ -1,9 +1,9 @@
/**
* Deterministic pixel people. Every agent gets a stable appearance derived
* from identity (skin tone, hair style and color, outfit, glasses), drawn
* procedurally with facing-aware variants and a two-frame walk cycle, so no
* two colleagues read as clones and nobody ships binary sprite sheets.
* from identity; poses are drawn at twice the scene's pixel density by
* person-art.ts, finished with rim light and a selective outline, and cached.
*/
import { ANCHOR, ART_H, ART_W, personArt, type PersonFrame } from "./person-art";
export type Facing = "north" | "south" | "east" | "west";
export type HairStyle = "buzz" | "short" | "bob" | "long" | "ponytail" | "curly" | "bald";
@@ -18,13 +18,15 @@ export interface SpriteAppearance {
shirt: string;
accent: string;
glasses: boolean;
pants: string;
shoes: string;
}
export interface PersonPose {
facing: Facing;
/** Radians accumulated while walking; 0 means standing still. */
walkPhase: number;
/** Seated work bob (used at desks). */
/** Typing at a desk. */
working: boolean;
carrying: Carrying;
timeMs: number;
@@ -39,10 +41,8 @@ const SHIRT_COLORS = [
"#4fb8b8", "#d97b5b", "#7ba95a", "#c4566f", "#6a7dd9",
];
const ACCENT_COLORS = ["#e5c65a", "#d95b5b", "#5bd9c0", "#c9c9d4", "#8ad95b"];
const BLAZER = "#37415c";
const BLAZER_CEO = "#2c3448";
const PANTS = "#3a3f47";
const SHOES = "#26292e";
const PANTS_COLORS = ["#3a3f47", "#2f4a6b", "#6b5a45", "#4a4a52", "#2b2d33"];
const SHOE_COLORS = ["#26292e", "#5a3a26", "#e8e6e0", "#26292e"];
export function hashIdentity(value: string): number {
let hash = 2166136261;
@@ -67,10 +67,50 @@ export function appearanceFor(id: string, isCeo: boolean): SpriteAppearance {
shirt: pick(SHIRT_COLORS, hash, 13),
accent: pick(ACCENT_COLORS, hash, 17),
glasses: (hash >>> 5) % 100 < 28,
pants: isCeo ? "#22252c" : pick(PANTS_COLORS, hash, 19),
shoes: isCeo ? "#1b1c20" : pick(SHOE_COLORS, hash, 23),
};
}
/** Draws a person anchored at foot-center (x, y). Total height ~34px. */
/** The pose frame a moment shows: four walk steps, two typing beats, a blink every few seconds. */
export function frameFor(pose: PersonPose): PersonFrame {
const turn = 2 * Math.PI;
const step = pose.walkPhase === 0 ? -1 : Math.floor(((((pose.walkPhase % turn) + turn) % turn) / turn) * 4);
const blinkEvery = 3200 + (pose.animSeed % 7) * 300;
return {
facing: pose.facing,
step,
typing: pose.working ? Math.floor(pose.timeMs / 180 + pose.animSeed) % 2 : -1,
blink: (pose.timeMs + pose.animSeed * 97) % blinkEvery < 120,
carrying: pose.carrying,
};
}
/** Most recently drawn pose canvases; the least recent go first past the cap. */
const cache = new Map<string, HTMLCanvasElement>();
const CACHE_CAP = 2048;
function spriteFor(appearance: SpriteAppearance, frame: PersonFrame, isCeo: boolean): HTMLCanvasElement {
const key = `${JSON.stringify(appearance)}|${isCeo}|${frame.facing}|${frame.step}|${frame.typing}|${frame.blink}|${frame.carrying}`;
const cached = cache.get(key);
if (cached) {
cache.delete(key);
cache.set(key, cached);
return cached;
}
const grid = personArt(appearance, frame, isCeo);
const canvas = document.createElement("canvas");
canvas.width = ART_W;
canvas.height = ART_H;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("A sprite canvas has no 2D context.");
ctx.putImageData(new ImageData(grid.data, ART_W, ART_H), 0, 0);
cache.set(key, canvas);
if (cache.size > CACHE_CAP) cache.delete(cache.keys().next().value!);
return canvas;
}
/** Draws a person standing at foot-centre (x, y) in scene pixels; the sprite is half its art size there. */
export function drawPerson(
ctx: CanvasRenderingContext2D,
x: number,
@@ -79,194 +119,12 @@ export function drawPerson(
pose: PersonPose,
isCeo: boolean,
): void {
const px = Math.round(x);
const walking = pose.walkPhase !== 0;
const stride = walking ? Math.sin(pose.walkPhase) * 2.5 : 0;
const bob = pose.working
? Math.sin(pose.timeMs * 0.003 + pose.animSeed) * 1.2
: walking ? Math.abs(Math.sin(pose.walkPhase)) * -1 : 0;
const py = Math.round(y + bob);
ctx.fillStyle = "rgba(24,18,12,0.28)";
ctx.fillRect(px - 8, Math.round(y) + 1, 16, 4);
drawLegs(ctx, px, py, stride);
drawTorso(ctx, px, py, appearance, pose, isCeo);
drawHead(ctx, px, py, appearance, pose.facing);
if (pose.carrying) drawCarriedItem(ctx, px, py, pose.carrying, pose.facing);
}
function drawLegs(ctx: CanvasRenderingContext2D, x: number, y: number, stride: number): void {
const left = Math.round(stride);
const right = Math.round(-stride);
ctx.fillStyle = PANTS;
ctx.fillRect(x - 5, y - 8 + Math.max(0, -left), 4, 8 - Math.abs(Math.min(left, 0)));
ctx.fillRect(x + 1, y - 8 + Math.max(0, -right), 4, 8 - Math.abs(Math.min(right, 0)));
ctx.fillStyle = SHOES;
ctx.fillRect(x - 6, y - 2 + (left > 0 ? -left : 0), 5, 3);
ctx.fillRect(x + 1, y - 2 + (right > 0 ? -right : 0), 5, 3);
}
function drawTorso(
ctx: CanvasRenderingContext2D,
x: number,
y: number,
appearance: SpriteAppearance,
pose: PersonPose,
isCeo: boolean,
): void {
const top = y - 20;
if (appearance.outfit === "blazer") {
ctx.fillStyle = isCeo ? BLAZER_CEO : BLAZER;
ctx.fillRect(x - 8, top, 16, 12);
if (pose.facing !== "north") {
ctx.fillStyle = "#e8e6df";
ctx.fillRect(x - 2, top, 4, 7);
ctx.fillStyle = appearance.accent;
ctx.fillRect(x - 1, top + 1, 2, 6);
}
ctx.fillStyle = isCeo ? BLAZER_CEO : BLAZER;
ctx.fillRect(x - 10, top + 1, 2, 9);
ctx.fillRect(x + 8, top + 1, 2, 9);
ctx.fillStyle = appearance.skin;
ctx.fillRect(x - 10, top + 10, 2, 2);
ctx.fillRect(x + 8, top + 10, 2, 2);
return;
}
if (appearance.outfit === "hoodie") {
ctx.fillStyle = appearance.shirt;
ctx.fillRect(x - 8, top, 16, 12);
ctx.fillRect(x - 10, top + 1, 2, 9);
ctx.fillRect(x + 8, top + 1, 2, 9);
ctx.fillStyle = shade(appearance.shirt);
ctx.fillRect(x - 8, top, 16, 3);
if (pose.facing !== "north") ctx.fillRect(x - 4, top + 7, 8, 4);
ctx.fillStyle = appearance.skin;
ctx.fillRect(x - 10, top + 10, 2, 2);
ctx.fillRect(x + 8, top + 10, 2, 2);
return;
}
ctx.fillStyle = appearance.shirt;
ctx.fillRect(x - 8, top, 16, 12);
ctx.fillRect(x - 10, top + 1, 2, 4);
ctx.fillRect(x + 8, top + 1, 2, 4);
ctx.fillStyle = appearance.skin;
ctx.fillRect(x - 10, top + 5, 2, 7);
ctx.fillRect(x + 8, top + 5, 2, 7);
}
function drawHead(ctx: CanvasRenderingContext2D, x: number, y: number, appearance: SpriteAppearance, facing: Facing): void {
const top = y - 33;
ctx.fillStyle = appearance.skin;
ctx.fillRect(x - 7, top, 14, 13);
if (facing === "north") {
if (appearance.hairStyle !== "bald") {
ctx.fillStyle = appearance.hair;
ctx.fillRect(x - 7, top, 14, 9);
}
drawHairEdges(ctx, x, y, appearance, facing);
return;
}
drawHairEdges(ctx, x, y, appearance, facing);
ctx.fillStyle = "#23232a";
if (facing === "south") {
ctx.fillRect(x - 4, top + 6, 2, 2);
ctx.fillRect(x + 2, top + 6, 2, 2);
} else if (facing === "east") {
ctx.fillRect(x + 3, top + 6, 2, 2);
} else {
ctx.fillRect(x - 5, top + 6, 2, 2);
}
if (appearance.glasses) drawGlasses(ctx, x, top, facing);
}
function drawHairEdges(ctx: CanvasRenderingContext2D, x: number, y: number, appearance: SpriteAppearance, facing: Facing): void {
const top = y - 33;
if (appearance.hairStyle === "bald") return;
ctx.fillStyle = appearance.hair;
switch (appearance.hairStyle) {
case "buzz":
ctx.fillRect(x - 7, top, 14, 3);
break;
case "short":
ctx.fillRect(x - 7, top, 14, 4);
ctx.fillRect(x - 7, top + 4, 2, 3);
ctx.fillRect(x + 5, top + 4, 2, 3);
break;
case "bob":
ctx.fillRect(x - 7, top, 14, 4);
ctx.fillRect(x - 8, top + 2, 2, 9);
ctx.fillRect(x + 6, top + 2, 2, 9);
break;
case "long":
ctx.fillRect(x - 7, top, 14, 4);
ctx.fillRect(x - 9, top + 2, 3, 15);
ctx.fillRect(x + 6, top + 2, 3, 15);
break;
case "ponytail":
ctx.fillRect(x - 7, top, 14, 4);
if (facing === "north") ctx.fillRect(x - 2, top + 4, 4, 10);
else if (facing === "east") ctx.fillRect(x - 9, top + 3, 3, 8);
else if (facing === "west") ctx.fillRect(x + 6, top + 3, 3, 8);
else ctx.fillRect(x + 6, top + 1, 2, 5);
break;
case "curly":
ctx.fillRect(x - 7, top, 14, 4);
for (let i = 0; i < 7; i++) ctx.fillRect(x - 7 + i * 2, top + 3 + (i % 2), 2, 2);
break;
}
}
function drawGlasses(ctx: CanvasRenderingContext2D, x: number, headTop: number, facing: Facing): void {
ctx.fillStyle = "#1c1c22";
if (facing === "south") {
ctx.fillRect(x - 5, headTop + 5, 4, 1);
ctx.fillRect(x + 1, headTop + 5, 4, 1);
ctx.fillRect(x - 5, headTop + 8, 4, 1);
ctx.fillRect(x + 1, headTop + 8, 4, 1);
ctx.fillRect(x - 5, headTop + 5, 1, 4);
ctx.fillRect(x - 2, headTop + 5, 1, 4);
ctx.fillRect(x + 1, headTop + 5, 1, 4);
ctx.fillRect(x + 4, headTop + 5, 1, 4);
ctx.fillRect(x - 1, headTop + 6, 2, 1);
} else if (facing === "east") {
ctx.fillRect(x + 2, headTop + 5, 4, 1);
ctx.fillRect(x + 2, headTop + 8, 4, 1);
ctx.fillRect(x + 2, headTop + 5, 1, 4);
ctx.fillRect(x + 5, headTop + 5, 1, 4);
} else if (facing === "west") {
ctx.fillRect(x - 6, headTop + 5, 4, 1);
ctx.fillRect(x - 6, headTop + 8, 4, 1);
ctx.fillRect(x - 6, headTop + 5, 1, 4);
ctx.fillRect(x - 3, headTop + 5, 1, 4);
}
}
function drawCarriedItem(ctx: CanvasRenderingContext2D, x: number, y: number, item: Carrying, facing: Facing): void {
const side = facing === "west" ? -12 : 10;
const ix = x + side;
const iy = y - 14;
if (item === "coffee") {
ctx.fillStyle = "#f0ece2";
ctx.fillRect(ix, iy, 4, 5);
ctx.fillStyle = "#6b4a2f";
ctx.fillRect(ix, iy, 4, 1);
ctx.fillStyle = "rgba(240,240,245,0.7)";
ctx.fillRect(ix + 1, iy - 3, 1, 2);
} else {
ctx.fillStyle = "#c9553e";
ctx.fillRect(ix, iy, 5, 4);
ctx.fillStyle = "#e8b84a";
ctx.fillRect(ix + 1, iy + 1, 3, 2);
}
}
function shade(hex: string): string {
const value = parseInt(hex.slice(1), 16);
const r = Math.max(0, (value >> 16) - 36);
const g = Math.max(0, ((value >> 8) & 0xff) - 36);
const b = Math.max(0, (value & 0xff) - 36);
return `#${((r << 16) | (g << 8) | b).toString(16).padStart(6, "0")}`;
const frame = frameFor(pose);
const breath = frame.step < 0 && frame.typing < 0 && Math.floor(pose.timeMs / 1100 + pose.animSeed) % 3 === 0 ? -0.5 : 0;
const ax = Math.round(x * 2) / 2;
const ay = Math.round(y * 2) / 2;
ctx.fillStyle = "rgba(24,18,12,0.3)";
ctx.fillRect(ax - 6, ay - 0.5, 12, 1.5);
ctx.fillRect(ax - 4, ay + 1, 8, 1);
ctx.drawImage(spriteFor(appearance, frame, isCeo), ax - ANCHOR.x / 2, ay + breath - ANCHOR.y / 2, ART_W / 2, ART_H / 2);
}
@@ -19,9 +19,9 @@ export function RunRequestList({ loaded }: { loaded: LoadedRequests | null }) {
return (
<div style={{ marginBottom: 20 }}>
<div className="section-label" style={{ marginBottom: 8 }}>{t("Model calls ({count})", { count: String(requests.length) })}</div>
{requests.length === 0 && <div style={{ fontSize: 13, color: "var(--text-3)" }}>{t("This run made no model call.")}</div>}
{requests.length === 0 && <div style={{ fontSize: "var(--fs-body)", color: "var(--text-3)" }}>{t("This run made no model call.")}</div>}
{requests.map((request, index) => (
<div key={request.id} className="row" style={{ gap: 10, fontSize: 13, padding: "6px 0", borderBottom: "1px solid var(--border-soft)" }}>
<div key={request.id} className="row" style={{ gap: 10, fontSize: "var(--fs-body)", padding: "6px 0", borderBottom: "1px solid var(--border-soft)" }}>
<span className="mono" style={{ color: "var(--text-3)", width: 24 }}>{index + 1}</span>
<span style={{ width: 96 }}>{purposeLabel(request.purpose)}</span>
<span className="mono" style={{ flex: 1, minWidth: 0, overflow: "hidden", textOverflow: "ellipsis" }}>{request.model}</span>
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff. Show more