Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion apps/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ Local ports: `www` 3000, `dash` 3001, `service` 3005, `workflow` 3008. `apps/fun
## `www`

- `src/libs/orpc/client.rsc.ts` is server-only and may attach `CH_API_KEY`; the browser client must never receive an API key.
- Content pages have no revalidate timer. `src/libs/orpc/client.rsc.ts` tags each server read with `WwwCacheTag` or `wwwFeedCacheTag`, and `workflow` invalidates those tags through the Vercel API, one five-minute window per tag; nothing calls into www. A write that changes what www renders must end in `scheduleFeedRevalidationStep` (in a workflow) or `workflow.startSiteRevalidation(tag)`.
- A mode is a URL space with its own frame, so the route decides it and nothing stores it. `src/app/[locale]/layout.tsx` renders the document and what every mode shares (providers, the page container, the chat dock); tech pages live under `(tech)` with the ruled frame, hobby pages under `hobby` with theirs. A frame that brings its own palette marks itself with `data-site-mode`: `@chia/themes/hobby.css` keys off it through `:root:has()` and the reader palette steps aside there. The hobby stage is the only writer of `--media-color`, on `<html>`, and every hobby token derives from it. A work's page, `/hobby/[kind]/[slug]`, is intercepted into the `[locale]/@modal` slot when it is reached from inside the site; the page and the sheet render the same component.
- Content pages have no revalidate timer. `src/libs/orpc/client.rsc.ts` tags each server read with `WwwCacheTag` or `wwwFeedCacheTag`, and `workflow` invalidates those tags through the Vercel API, one five-minute window per tag; nothing calls into www. A write that changes what www renders must end in `scheduleFeedRevalidationStep` (in a workflow) or `workflow.startSiteRevalidation(tag)`. Hobby pages read only `media.list` and `media.get`, tagged `WwwCacheTag.Media`.
- The blog navigation and related posts load in the browser, so no cached page depends on a post other than its own. Home and projects keep a timer because Spotify and GitHub send no change event.
- Pages set canonical, hreflang and `og:url` through `localizedMetadata` in `src/libs/i18n/alternates.ts`; the middleware sends no alternate links. Every URL the site emits (links, sitemap, RSS, `feedUrl`) leaves the default locale unprefixed, because `/zh-TW/…` redirects.
- Browser requests use the Better Auth session cookie and may access only public or caller-owned procedures. Shared reads (`@chia/services/shared/shared-reads`) go without credentials so a CDN can serve them.
Expand Down
1 change: 1 addition & 0 deletions apps/dash/.next/dev/types/link.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ declare namespace __next_route_internal_types__ {
| `/feed/notes` // ../../../src/app/(workspace)/(operator)/feed/(manage)/notes/page.tsx
| `/feed/posts` // ../../../src/app/(workspace)/(operator)/feed/(manage)/posts/page.tsx
| `/icon.png` // ../../../src/app/icon.png
| `/media` // ../../../src/app/(workspace)/(operator)/media/page.tsx
| `/memory` // ../../../src/app/(workspace)/(operator)/memory/page.tsx
| `/profile` // ../../../src/app/(workspace)/(operator)/profile/page.tsx
| `/rag` // ../../../src/app/(workspace)/(operator)/rag/page.tsx
Expand Down
6 changes: 4 additions & 2 deletions apps/dash/.next/dev/types/routes.d.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
// This file is generated automatically by Next.js
// Do not edit this file manually

type AppRoutes = "/" | "/agents" | "/api-keys" | "/assets" | "/auth/callback/sent-success" | "/auth/login" | "/feed" | "/feed/draft/[id]" | "/feed/drafts" | "/feed/edit/[id]" | "/feed/notes" | "/feed/posts" | "/memory" | "/profile" | "/rag" | "/rag/chunks" | "/rag/maintenance" | "/rag/runs" | "/reports" | "/reports/[id]" | "/settings" | "/settings/spotify" | "/tags" | "/users"
type AppRoutes = "/" | "/agents" | "/api-keys" | "/assets" | "/auth/callback/sent-success" | "/auth/login" | "/feed" | "/feed/draft/[id]" | "/feed/drafts" | "/feed/edit/[id]" | "/feed/notes" | "/feed/posts" | "/media" | "/memory" | "/profile" | "/rag" | "/rag/chunks" | "/rag/maintenance" | "/rag/runs" | "/reports" | "/reports/[id]" | "/settings" | "/settings/spotify" | "/tags" | "/users"
type AppRouteHandlerRoutes = "/api/v1/health" | "/favicon.ico" | "/icon.png" | "/robots.txt"
type PageRoutes = never
type LayoutRoutes = "/" | "/agents" | "/auth" | "/feed" | "/memory" | "/profile" | "/rag" | "/reports" | "/settings" | "/tags"
type LayoutRoutes = "/" | "/agents" | "/auth" | "/feed" | "/media" | "/memory" | "/profile" | "/rag" | "/reports" | "/settings" | "/tags"
type RedirectRoutes = never
type RewriteRoutes = never
type Routes = AppRoutes | PageRoutes | LayoutRoutes | RedirectRoutes | RewriteRoutes | AppRouteHandlerRoutes
Expand All @@ -27,6 +27,7 @@ interface ParamMap {
"/feed/notes": {}
"/feed/posts": {}
"/icon.png": {}
"/media": {}
"/memory": {}
"/profile": {}
"/rag": {}
Expand All @@ -50,6 +51,7 @@ interface LayoutSlotMap {
"/agents": never
"/auth": never
"/feed": never
"/media": never
"/memory": never
"/profile": never
"/rag": never
Expand Down
81 changes: 81 additions & 0 deletions apps/dash/__tests__/media-form.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import { describe, expect, it } from "vitest";

import { Locale, MediaStatus } from "@chia/db/types";

import { mediaFormSchema } from "@/components/media/form";
import type { MediaFormInput } from "@/components/media/form";

const fields = (overrides: Partial<MediaFormInput> = {}): MediaFormInput => ({
status: MediaStatus.Completed,
rating: 8,
favorite: false,
startedOn: "",
finishedOn: "2026-11-01",
originalTitle: " 葬送のフリーレン ",
releaseYear: 2023,
color: " #D6E4A1 ",
steamAppId: null,
playtimeHours: 87.5,
achievementsUnlocked: 31,
achievementsTotal: 42,
translations: {
[Locale.ZhTW]: { title: "葬送的芙莉蓮", comment: " 很好看 " },
[Locale.En]: { title: "", comment: "ignored without a title" },
},
...overrides,
});

describe("mediaFormSchema", () => {
it("turns blank fields into nulls and drops a locale without a title", () => {
expect(mediaFormSchema.parse(fields())).toEqual({
status: MediaStatus.Completed,
rating: 8,
favorite: false,
startedOn: null,
finishedOn: "2026-11-01",
originalTitle: "葬送のフリーレン",
releaseYear: 2023,
color: "#D6E4A1",
steamAppId: null,
playtimeMinutes: 5250,
achievementsUnlocked: 31,
achievementsTotal: 42,
translations: {
[Locale.ZhTW]: { title: "葬送的芙莉蓮", comment: "很好看" },
},
});
});

it("requires a title in at least one locale", () => {
const result = mediaFormSchema.safeParse(
fields({
translations: {
[Locale.ZhTW]: { title: " ", comment: "" },
[Locale.En]: { title: "", comment: "" },
},
})
);
expect(result.success).toBe(false);
});

it("refuses a colour that is not #rrggbb and accepts a blank one", () => {
expect(mediaFormSchema.safeParse(fields({ color: "teal" })).success).toBe(
false
);
expect(mediaFormSchema.parse(fields({ color: "" })).color).toBeNull();
});

it("refuses more unlocked achievements than the game has", () => {
const result = mediaFormSchema.safeParse(
fields({ achievementsUnlocked: 43 })
);
expect(result.error?.issues[0]?.path).toEqual(["achievementsUnlocked"]);
});

it("refuses a finish date before the start date", () => {
const result = mediaFormSchema.safeParse(
fields({ startedOn: "2026-11-02" })
);
expect(result.error?.issues[0]?.path).toEqual(["finishedOn"]);
});
});
12 changes: 12 additions & 0 deletions apps/dash/src/app/(workspace)/(operator)/media/layout.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import type { ReactNode } from "react";
import { ViewTransition } from "react";

const Layout = ({ children }: { children: ReactNode }) => {
return (
<ViewTransition>
<article className="page-container py-8">{children}</article>
</ViewTransition>
);
};

export default Layout;
24 changes: 24 additions & 0 deletions apps/dash/src/app/(workspace)/(operator)/media/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import "server-only";
import { Suspense } from "react";

import { Spinner } from "@heroui/react";

import { MediaManager } from "@/components/media/media-manager";

export const dynamic = "force-dynamic";

const MediaPage = () => (
<section className="flex w-full flex-col gap-6">
<h1 className="text-2xl font-semibold">Media log</h1>
<Suspense
fallback={
<div className="flex justify-center py-12">
<Spinner size="sm" />
</div>
}>
<MediaManager />
</Suspense>
</section>
);

export default MediaPage;
3 changes: 2 additions & 1 deletion apps/dash/src/components/assets/file-explorer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,14 +7,15 @@ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { FolderOpen, Info } from "lucide-react";
import { toast } from "sonner";

import { STORAGE_BASE_URL } from "@chia/utils/config";

import { orpc } from "@/libs/orpc/client";

import { DeleteConfirmModal } from "./delete-confirm-modal";
import { ExplorerToolbar } from "./explorer-toolbar";
import { FileDetailPanel } from "./file-detail-panel";
import { FileTreeDrawer } from "./file-tree-drawer";
import { FileTreePanel } from "./file-tree-panel";
import { STORAGE_BASE_URL } from "./utils";

export const FileExplorer = () => {
const [selectedPath, setSelectedPath] = useState<string | null>(null);
Expand Down
2 changes: 0 additions & 2 deletions apps/dash/src/components/assets/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export const STORAGE_BASE_URL = "https://storage.chia1104.dev";

export function formatBytes(bytes: number, decimals = 2): string {
if (bytes === 0) return "0 Bytes";
const k = 1024;
Expand Down
209 changes: 209 additions & 0 deletions apps/dash/src/components/media/add-drawer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
"use client";

import { useState } from "react";

import {
Button,
Drawer,
Input,
Label,
ListBox,
Select,
Spinner,
TextField,
} from "@heroui/react";
import { useDebouncedValue } from "@tanstack/react-pacer";
import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";

import { MediaStatus } from "@chia/db/types";
import type { MediaKind } from "@chia/db/types";
import { isEnumValue } from "@chia/utils/is";
import { Image } from "@chiastack/ui/image";

import { DrawerPanel } from "@/components/commons/drawer-panel";
import { orpc } from "@/libs/orpc/client";

import { KIND_LABEL, STATUS_OPTIONS } from "./form";
import type { MediaCandidate, MediaEntryView } from "./form";

const SEARCH_DEBOUNCE_MS = 400;
const MIN_QUERY_CHARS = 2;

const SOURCE_LABEL = {
"tmdb:movie": "TMDB",
"tmdb:tv": "TMDB",
anilist: "AniList",
igdb: "IGDB",
} satisfies Record<MediaCandidate["source"], string>;

/**
* Searches the catalogues of `kind` and logs the picked work. The catalogue supplies the titles
* and cover, so only the status is asked here; `onAdded` opens the new entry for the rest.
*/
export const AddDrawer = ({
isOpen,
kind,
onAdded,
onClose,
}: {
isOpen: boolean;
kind: MediaKind;
onAdded: (entry: MediaEntryView) => void;
onClose: () => void;
}) => {
const [query, setQuery] = useState("");
const [status, setStatus] = useState<MediaStatus>(MediaStatus.Completed);
const [debouncedQuery] = useDebouncedValue(query.trim(), {
wait: SEARCH_DEBOUNCE_MS,
});
const canSearch = debouncedQuery.length >= MIN_QUERY_CHARS;

const search = useQuery(
orpc.media.search.queryOptions({
input: { kind, query: debouncedQuery },
enabled: isOpen && canSearch,
retry: false,
})
);

const create = useMutation(
orpc.media.create.mutationOptions({
onSuccess({ entry }) {
setQuery("");
onAdded(entry);
toast.success("Logged; add your rating and dates");
},
onError(error) {
toast.error(error.message);
},
})
);

const candidates = canSearch ? (search.data?.items ?? []) : [];

return (
<Drawer.Backdrop
isOpen={isOpen}
onOpenChange={(open) => !open && onClose()}>
<DrawerPanel>
<Drawer.CloseTrigger />
<Drawer.Header>
<Drawer.Heading>{`Log ${KIND_LABEL[kind].toLowerCase()}`}</Drawer.Heading>
</Drawer.Header>
<Drawer.Body className="flex flex-col gap-4">
<div className="flex flex-wrap items-end gap-4">
<TextField
autoFocus
className="min-w-48 flex-1"
onChange={setQuery}
value={query}>
<Label className="text-xs">Title</Label>
<Input placeholder="Search the catalogue" variant="secondary" />
</TextField>
<Select
className="w-40"
onChange={(key) => {
if (key !== null && isEnumValue(MediaStatus, key))
setStatus(key);
}}
value={status}
variant="secondary">
<Label className="text-xs">Log as</Label>
<Select.Trigger>
<Select.Value />
<Select.Indicator />
</Select.Trigger>
<Select.Popover>
<ListBox items={STATUS_OPTIONS}>
{(item) => (
<ListBox.Item id={item.id}>{item.label}</ListBox.Item>
)}
</ListBox>
</Select.Popover>
</Select>
</div>

{search.isError ? (
<p className="text-danger text-sm">
The catalogue did not answer: {search.error.message}
</p>
) : null}
{canSearch && search.isFetching ? (
<div className="flex justify-center py-6">
<Spinner size="sm" />
</div>
) : null}
{canSearch && search.isSuccess && candidates.length === 0 ? (
<p className="text-muted text-sm">
Nothing matches “{debouncedQuery}”. Try the original title.
</p>
) : null}

<ul className="flex flex-col gap-2">
{candidates.map((candidate) => (
<li
key={`${candidate.source}:${candidate.sourceId}`}
className="border-separator flex items-center gap-3 rounded-xl border p-2">
<div className="bg-default relative aspect-2/3 w-12 shrink-0 overflow-hidden rounded-md">
{candidate.posterUrl ? (
<Image.Root>
<Image.Resource
src={candidate.posterUrl}
alt=""
className="absolute inset-0 h-full w-full object-cover"
/>
</Image.Root>
) : null}
</div>
<div className="flex min-w-0 flex-1 flex-col gap-0.5">
<a
className="truncate text-sm font-medium hover:underline"
href={candidate.url}
rel="noopener noreferrer"
target="_blank">
{candidate.title}
</a>
<span className="text-muted truncate text-xs">
{[
candidate.releaseYear,
candidate.originalTitle === candidate.title
? null
: candidate.originalTitle,
SOURCE_LABEL[candidate.source],
]
.filter((part) => part !== null)
.join(" · ")}
</span>
</div>
<Button
isDisabled={create.isPending}
isPending={
create.isPending &&
create.variables.source === candidate.source &&
create.variables.sourceId === candidate.sourceId
}
size="sm"
variant="secondary"
onPress={() =>
create.mutate({
kind,
source: candidate.source,
sourceId: candidate.sourceId,
status,
rating: null,
favorite: false,
startedOn: null,
finishedOn: null,
})
}>
Log
</Button>
</li>
))}
</ul>
</Drawer.Body>
</DrawerPanel>
</Drawer.Backdrop>
);
};
Loading
Loading