Compare commits
5
Commits
da6a73f740
...
383ef82400
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
383ef82400 | ||
|
|
7e1135beb1 | ||
|
|
b30d6118fe | ||
|
|
35b9808d97 | ||
|
|
7460163287 |
@@ -192,7 +192,7 @@ Set in Settings > Environment (super admin), not `.env`. `envs` (private; encryp
|
||||
- Notification `badge` is `icons/badge-96.png` (white silhouette; Android masks by alpha, so never the opaque app icon). Brave on Android has no WebAPK, so its notifications always carry Brave's name and icon.
|
||||
- `public/sw.js` is served `no-store`; navigations network-only (authenticated HTML never cached); `/api/`, `/ws`, `/media/`, `/computers/`, `/build-info.json` never intercepted. A new worker takes over by itself (`skipWaiting` on install; nothing in it is per-version) and never reloads a page; there is no update prompt. In development the worker and caches are actively removed (`clear-development-service-worker.ts`, stub `/sw.js`).
|
||||
- **Precache (production):** a navigation without the current build cookie gets `loading.html`, which downloads all of `.bunext/public` into `cobble-assets-<build_id>`, verifies, sets the cookie and reloads (falls back to network on stall). React knows nothing of this.
|
||||
- Phone shell: rail is a slide-over below `md` (the shared `src/components/general/side-panel.tsx`, always mounted so it slides both ways; the rail passes `inertWhenClosed={false}` since it is the page's own rail from `md` up); rail internals use the `@rail:` container variant, not viewport `lg:`. Two swipes anywhere on a phone page move between panes: to the right opens the rail's drawer, to the left the conversation's bot panel (`cobble:open-bot-panel`, `src/utils/bot-panel-open-event.ts`, answered only by a conversation's header, so a page without one slides nothing). They are flicks, read by `src/hooks/use-horizontal-swipe.ts` (a field, a `data-no-swipe` panel, a box that scrolls sideways, a text selection, a finger down longer than `AppData.MobileSwipeMaxMs`, an open twui modal, a screen from `md` up and the open drawer all own the touch), with the thresholds and the one-decision state machine in `src/utils/swipe-gesture.ts` (`AppData.MobileSwipeMinPx`, `MobileSwipeAxisRatio`), tested without a browser. `LiveSocket` is remounted on online/pageshow/visibility since twui stops retrying after three attempts. Nothing is queued offline.
|
||||
- Phone shell: rail is a slide-over below `md` (the shared `src/components/general/side-panel.tsx`, always mounted so it slides both ways; the rail passes `inertWhenClosed={false}` since it is the page's own rail from `md` up); rail internals use the `@rail:` container variant, not viewport `lg:`. Two swipes anywhere on a phone page move between panes: to the right opens the rail's drawer, to the left the conversation's bot panel (`cobble:open-bot-panel`, `src/utils/bot-panel-open-event.ts`, answered only by a conversation's header, so a page without one slides nothing). They are flicks, read by `src/hooks/use-horizontal-swipe.ts` (a field, a `data-no-swipe` panel, a box that scrolls sideways, a text selection, a finger down longer than `AppData.MobileSwipeMaxMs`, an open twui modal, a screen from `md` up and the open drawer all own the touch), with the thresholds and the one-decision state machine in `src/utils/swipe-gesture.ts` (`AppData.MobileSwipeMinPx`, `MobileSwipeAxisRatio`), tested without a browser. An open panel answers the one swipe back off its edge (`src/hooks/use-swipe-to-close.ts`, `sidePanelCloseSwipe`): a left drag closes the rail's drawer, a right drag the bot panel; `SidePanel` gives both the same phone width (`w-[420px] max-w-[92vw]`). `LiveSocket` is remounted on online/pageshow/visibility since twui stops retrying after three attempts. Nothing is queued offline.
|
||||
- **Web Push:** `push_subscriptions`, `user_presence`; VAPID keys generated into `envs` by `ensureVapidKeys`. `pushBotNotice` is the one trigger, skipped while the user is present (`AppData.PushPresenceWindowMs`, per user not per device). Best effort, no retry. Needs HTTPS.
|
||||
|
||||
### Bot files and folders
|
||||
@@ -231,6 +231,7 @@ Read-only browser of every volume (`src/utils/storage-volumes.ts`: bots, workspa
|
||||
- **Harnesses** (`src/dict/harness-dict.ts`): `text` (always on), `vision`, `transcription`, `speech`, `image`, `image_edit`, `video`, `video_edit`, `embedding`. One `harness_settings` row each (provider, pinned model or automatic, `fallback`, `enabled`, `options`). Transcription, speech, video and embedding have no automatic picks: unavailable until a model is picked.
|
||||
- **Images:** `generate_image` attaches what it makes to the reply unless `attach: false` (a coordinator once asked a user to judge three versions they were never sent). It takes reference images (`references` as `[file:ID]`, `reference_media_ids` for uploads, checked like a picture source by `loadReferenceImages`). With references the call goes to `image_edit` (no automatic picks; only while its `fallback` is on does `HarnessFallbacks` hand it to `image`, both while it is unpicked or off and after its pick fails), and only models that take image input are tried (`orderImageCandidates`), never one that would drop them. OpenRouter takes references on `/images` (`input_references`), other providers as multipart on `image_edit_path` (`/images/edits`); DashScope/Model Studio hosts (`dashscope*.aliyuncs.com`, `*.maas.aliyuncs.com`) take them as the `image` extension field on `/images/generations` instead (they have no multipart edits endpoint) and always answer with URLs, ignoring `b64_json` (`isDashScopeHost` in the adapter). The Token Plan host (`token-plan.*.maas.aliyuncs.com`) has no compatible images route, so its call goes straight to Alibaba's native `multimodal-generation` on the host root (`dashscope-native-image.ts`, the documented body: `size` as `width*height`, no `prompt_extend`); a workspace host that answers 404/405 on the compatible route falls back to the same call. xAI takes no `size` (`imageRequestFields` maps one onto `aspect_ratio`).
|
||||
- **Videos:** `generate_video` (`src/harness/video/`), offered only while `video` or `video_edit` has a model for the bot there (no video model is free). A video is a job at the provider: asked for at `video_path`, checked every `AppData.VideoPollIntervalMs` for at most `VideoMaxWaitMs` (below the tool timeout), downloaded from the provider itself (`<video_path>/<id>/content`, never a URL it hands back, so the key stays home). Still images go as first/last frames or references; videos to change (inline `data:` URLs, `VideoSourceMaxBytes`) go to `video_edit`'s pick, which hands over to the `video` models that take videos like `image_edit` does (`orderVideoCandidates`). OpenRouter takes JSON (`frame_images`, `input_references` with `video_url`); other providers get OpenAI's (Sora) form with one start image and no videos.
|
||||
- **Transcription:** `transcribeAudio` -> `src/harness/providers/openai-compatible/transcribe.ts`. An OpenAI-compatible host gets multipart `/audio/transcriptions`; a DashScope host (`dashscope-hosts.ts`: `isDashScopeHost`, `isTokenPlanHost`, the Token Plan included) has no such route, so an ASR model there goes to `dashscope-native-transcribe.ts` (JSON `input_audio` as a `data:` URL of the bytes, `parameters.format`, at the host root's `/api/v1/services/aigc/multimodal-generation/generation`), and an async-only slug (filetrans, paraformer) is refused unretryably naming the synchronous model to pick instead.
|
||||
- **Transforming images without a model:** `transform_image` (never "edit": that word is the `image_edit` harness) (`src/harness/image/transform-image.ts`, sharp) runs ordered steps (crop, resize, rotate, flip, grayscale, blur, sharpen, adjust, trim) on raw pixels, so the order is the bot's, after turning the source upright by EXIF. Source checked like a picture (`grabPictureSource`), never SVG. Saves a new file and shows the bot a preview so it checks the crop.
|
||||
- **Providers** (`src/dict/harness-provider-dict.ts`): OpenRouter default plus OpenAI-compatible ones; one adapter today (`src/harness/providers/openai-compatible/`). Keys encrypted in private `harness_providers`, falling back to the preset env.
|
||||
- **Catalog:** `harness_models`, synced hourly. OpenRouter "free" means `:free` or `openrouter/free`, never zero prices. Auto picks: `rank-auto-models`. A custom provider's `/models` lists ids and nothing else, so its form takes a **context window** (`harness_providers.context_length`) and the sync writes it into every model that reports none of its own (`modelContextLength`); leaving it empty leaves them unknown, and a run then works to `AppData.HarnessUnknownContextWindow` (1,000,000) less the answer reserve. That guess is not silent: the model picker marks a model with no declared window, and a provider that refuses the prompt for size stops the run with its own message and the fix (`fatal`, below). Never learn a smaller window into the constant: the provider has the last word.
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "cobble",
|
||||
"version": "0.27.5",
|
||||
"version": "0.27.6",
|
||||
"module": "index.ts",
|
||||
"type": "module",
|
||||
"private": true,
|
||||
|
||||
@@ -84,44 +84,44 @@ export default function FilePreviewModal({
|
||||
}}
|
||||
className="max-w-[95vw]! w-[95vw] h-[90vh] p-0 bg-paper flex flex-col overflow-hidden"
|
||||
>
|
||||
<Row className="w-full gap-3! flex-nowrap items-center pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
|
||||
<Stack className="min-w-0 grow gap-0! items-start">
|
||||
<Stack className="w-full min-w-0 gap-1! items-stretch pl-5 pr-14 py-3 border-0 border-b border-solid border-hairline">
|
||||
<Row className="w-full gap-3! flex-wrap sm:flex-nowrap items-center">
|
||||
<H2
|
||||
title={name}
|
||||
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate w-full"
|
||||
className="text-base! leading-6! tracking-normal! font-bold text-ink truncate min-w-0 w-full sm:w-auto sm:grow"
|
||||
>
|
||||
{base_name}
|
||||
</H2>
|
||||
<FilePreviewDetails size={size} full_path={full_path} />
|
||||
</Stack>
|
||||
{stepping ? (
|
||||
<FilePreviewStepper
|
||||
index={index}
|
||||
count={count}
|
||||
onPrevious={() => step({ by: -1 })}
|
||||
onNext={() => step({ by: 1 })}
|
||||
/>
|
||||
) : null}
|
||||
<Link
|
||||
href={url}
|
||||
download={base_name}
|
||||
title={`Download ${base_name}`}
|
||||
className={ActionClassName}
|
||||
>
|
||||
<Download size={16} aria-hidden />
|
||||
<Span className="hidden sm:inline">Download</Span>
|
||||
</Link>
|
||||
<Link
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Open in a new tab"
|
||||
aria-label="Open in a new tab"
|
||||
className={ActionClassName}
|
||||
>
|
||||
<SquareArrowOutUpRight size={16} aria-hidden />
|
||||
</Link>
|
||||
</Row>
|
||||
{stepping ? (
|
||||
<FilePreviewStepper
|
||||
index={index}
|
||||
count={count}
|
||||
onPrevious={() => step({ by: -1 })}
|
||||
onNext={() => step({ by: 1 })}
|
||||
/>
|
||||
) : null}
|
||||
<Link
|
||||
href={url}
|
||||
download={base_name}
|
||||
title={`Download ${base_name}`}
|
||||
className={ActionClassName}
|
||||
>
|
||||
<Download size={16} aria-hidden />
|
||||
<Span className="hidden sm:inline">Download</Span>
|
||||
</Link>
|
||||
<Link
|
||||
href={url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
title="Open in a new tab"
|
||||
aria-label="Open in a new tab"
|
||||
className={ActionClassName}
|
||||
>
|
||||
<SquareArrowOutUpRight size={16} aria-hidden />
|
||||
</Link>
|
||||
</Row>
|
||||
<FilePreviewDetails size={size} full_path={full_path} />
|
||||
</Stack>
|
||||
<Stack className="relative grow min-h-0 gap-0! items-stretch w-full">
|
||||
<FilePreviewBody
|
||||
key={url}
|
||||
|
||||
@@ -11,7 +11,12 @@ import useStorageFolder from "@/src/hooks/use-storage-folder";
|
||||
import useTopModalEscape from "@/src/hooks/use-top-modal-escape";
|
||||
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
|
||||
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
|
||||
import { storagePathName, storageSpecHref, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import {
|
||||
storageBreadcrumbs,
|
||||
storagePathName,
|
||||
storageSpecHref,
|
||||
type StorageSpec,
|
||||
} from "@/src/utils/storage-volumes";
|
||||
import FilesBreadcrumbRow from "./files-breadcrumb-row";
|
||||
import FilesSearchInput from "./files-search-input";
|
||||
import StorageEntryRow from "./storage-entry-row";
|
||||
@@ -38,8 +43,14 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
|
||||
const [search, set_search] = useState("");
|
||||
const query = useDebouncedValue({ value: search.trim() });
|
||||
const { folder, loading, error } = useStorageFolder({ spec, path, search: query });
|
||||
const name = folder?.breadcrumbs.at(-1)?.name || folder?.label || storagePathName({ volume: spec.volume, path });
|
||||
|
||||
const crumbs = useMemo(
|
||||
() => storageBreadcrumbs({ spec, path }),
|
||||
[spec.volume, spec.owner_id, path],
|
||||
);
|
||||
const name =
|
||||
crumbs.at(-1)?.name ||
|
||||
folder?.label ||
|
||||
storagePathName({ volume: spec.volume, path });
|
||||
const gallery = useMemo(
|
||||
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
|
||||
[folder],
|
||||
@@ -69,7 +80,7 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
|
||||
{name}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{folderSummary({ folder })}
|
||||
{folderSummary({ folder, loading })}
|
||||
</Span>
|
||||
</Stack>
|
||||
<Link
|
||||
@@ -82,10 +93,13 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
|
||||
</Link>
|
||||
</Row>
|
||||
<Stack className="w-full gap-0! items-stretch px-5">
|
||||
<FilesBreadcrumbRow crumbs={folder?.breadcrumbs || []} onOpenFolder={openFolder} />
|
||||
<FilesBreadcrumbRow crumbs={crumbs} onOpenFolder={openFolder} />
|
||||
<FilesSearchInput value={search} onChange={set_search} />
|
||||
</Stack>
|
||||
<Stack className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4">
|
||||
<Stack
|
||||
key={`${path}|${query}`}
|
||||
className="grow min-h-0 w-full mt-2 gap-0! items-stretch overflow-y-auto px-5 pb-4"
|
||||
>
|
||||
{folder?.entries.length ? (
|
||||
folder.entries.map((entry) => (
|
||||
<StorageEntryRow
|
||||
@@ -98,10 +112,10 @@ export default function FolderPreviewModal({ spec, path: start_path, onClose }:
|
||||
))
|
||||
) : (
|
||||
<Span className="py-8 text-[13px] leading-[18px] text-ink-secondary">
|
||||
{emptyFolderText({ folder, search, loading, error })}
|
||||
{emptyFolderText({ folder, search: query, loading, error })}
|
||||
</Span>
|
||||
)}
|
||||
</Stack>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -54,6 +54,17 @@ describe("SidePanel", () => {
|
||||
expect(html.match(/data-no-swipe/g)?.length).toBe(2);
|
||||
});
|
||||
|
||||
test("the rail's drawer and the bot panel open to the same phone width", () => {
|
||||
const html = renderToString(
|
||||
<SidePanel side="left" open onClose={onClose} label="Bots">
|
||||
<p>crew</p>
|
||||
</SidePanel>,
|
||||
);
|
||||
|
||||
expect(html).toContain("w-[420px]");
|
||||
expect(html).toContain("max-w-[92vw]");
|
||||
});
|
||||
|
||||
test("a panel that is also part of the page is never inert", () => {
|
||||
const html = renderToString(
|
||||
<SidePanel
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
"use client";
|
||||
|
||||
import type { ReactNode } from "react";
|
||||
import { useRef, type ReactNode, type RefObject } from "react";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
import useSwipeToClose from "@/src/hooks/use-swipe-to-close";
|
||||
import sidePanelCloseSwipe from "@/src/utils/side-panel-close-swipe";
|
||||
|
||||
type Props = {
|
||||
/** Which edge it slides in from. */
|
||||
@@ -34,7 +36,10 @@ const Edges = {
|
||||
* to wait on a timer for an exit to play.
|
||||
*
|
||||
* The panel carries `data-no-swipe`, so a phone's sideways swipes never
|
||||
* start on it or on its backdrop: what is open stays the one on top.
|
||||
* start on it or on its backdrop: what is open stays the one on top. An
|
||||
* open panel closes on the one swipe it does answer, a drag back towards the
|
||||
* edge it slid in from (`useSwipeToClose`), which is the way back out of the
|
||||
* swipe that opened it.
|
||||
*/
|
||||
export default function SidePanel({
|
||||
side,
|
||||
@@ -48,6 +53,14 @@ export default function SidePanel({
|
||||
}: Props) {
|
||||
const edge = Edges[side];
|
||||
const hidden = !open && inertWhenClosed;
|
||||
const panel_ref = useRef<HTMLDivElement>(null);
|
||||
|
||||
useSwipeToClose({
|
||||
panel_ref,
|
||||
enabled: open,
|
||||
direction: sidePanelCloseSwipe({ side }),
|
||||
on_close: onClose,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -64,8 +77,9 @@ export default function SidePanel({
|
||||
aria-hidden={hidden || undefined}
|
||||
inert={hidden}
|
||||
data-no-swipe
|
||||
componentRef={panel_ref as RefObject<HTMLDivElement>}
|
||||
className={twMerge(
|
||||
"fixed inset-y-0 z-40 w-[280px] max-w-[85vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
|
||||
"fixed inset-y-0 z-40 w-[420px] max-w-[92vw] shrink-0 h-full gap-0! items-stretch bg-paper border-0 border-solid border-hairline shadow-popover transition-transform duration-[var(--m-base)] pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]",
|
||||
edge.place,
|
||||
open ? "translate-x-0" : edge.closed,
|
||||
className,
|
||||
|
||||
@@ -202,27 +202,3 @@ export function canSeePath({ resolved, path }: { resolved: ResolvedStorageSpec;
|
||||
function joinPath({ relative, name }: { relative: string; name: string }) {
|
||||
return relative ? `${relative}/${name}` : name;
|
||||
}
|
||||
|
||||
/**
|
||||
* The breadcrumb trail of a folder, from the volume's top: one crumb per
|
||||
* segment, each with the address that opens it.
|
||||
*/
|
||||
export function storageBreadcrumbs({
|
||||
spec,
|
||||
path: relative,
|
||||
}: {
|
||||
spec: StorageSpec;
|
||||
path?: string | null;
|
||||
}) {
|
||||
const segments = (relative || "").split("/").filter(Boolean);
|
||||
const crumbs = [{ name: "", href: storageSpecHref({ spec }) }];
|
||||
|
||||
for (let i = 1; i <= segments.length; i++) {
|
||||
crumbs.push({
|
||||
name: segments[i - 1] || "",
|
||||
href: storageSpecHref({ spec, path: segments.slice(0, i).join("/") }),
|
||||
});
|
||||
}
|
||||
|
||||
return crumbs;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,8 @@ type Params = {
|
||||
|
||||
/**
|
||||
* Turns speech into text with the transcription harness: its
|
||||
* speech-to-text model gets the file at `/audio/transcriptions`.
|
||||
* speech-to-text model gets the file, at `/audio/transcriptions` or, on
|
||||
* Alibaba's hosts, at their native multimodal route.
|
||||
*/
|
||||
export default async function transcribeAudio({
|
||||
audio,
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
|
||||
/**
|
||||
* Alibaba's native routes (images, speech) live at the host root, beside
|
||||
* `<base>/compatible-mode/v1`, never under it.
|
||||
*/
|
||||
export const NativeGenerationPath = "/api/v1/services/aigc/multimodal-generation/generation";
|
||||
|
||||
/**
|
||||
* The host root: the native routes live beside `<base>/compatible-mode/v1`,
|
||||
* never under it.
|
||||
*/
|
||||
export function dashScopeOrigin({ base_url }: { base_url: string }) {
|
||||
try {
|
||||
return new URL(base_url).origin;
|
||||
} catch {
|
||||
throw new HarnessError({
|
||||
message: `The provider's base URL can't be read as an address: ${base_url}`,
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Alibaba's Token Plan host. Its models are served only by the native
|
||||
* calls; the compatible routes 404, and trying one first benches the model
|
||||
* before the request that works.
|
||||
*/
|
||||
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
|
||||
if (!base_url) return false;
|
||||
|
||||
try {
|
||||
return new URL(base_url).hostname.startsWith("token-plan.");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A DashScope or Model Studio host, where the native calls take the
|
||||
* provider's own extensions (`image` references, audio input). The shared
|
||||
* `dashscope` hosts and the workspace `maas` hosts both count; a custom
|
||||
* provider pointed elsewhere keeps the standard behaviour.
|
||||
*/
|
||||
export function isDashScopeHost({ base_url }: { base_url?: string | null }) {
|
||||
if (!base_url) return false;
|
||||
|
||||
try {
|
||||
const host = new URL(base_url).hostname;
|
||||
|
||||
return (
|
||||
host == "dashscope.aliyuncs.com" ||
|
||||
host == "dashscope-intl.aliyuncs.com" ||
|
||||
host.endsWith(".maas.aliyuncs.com")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate, HarnessImageOutput } from "../../types";
|
||||
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
|
||||
import downloadProviderFile from "./download-provider-file";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
@@ -24,8 +25,6 @@ type Params = {
|
||||
* how the native API takes image editing too. The answer carries image URLs,
|
||||
* downloaded here under the same guards as every other provider URL.
|
||||
*/
|
||||
export const NativeImagePath = "/api/v1/services/aigc/multimodal-generation/generation";
|
||||
|
||||
export default async function generateImageNative({
|
||||
candidate,
|
||||
prompt,
|
||||
@@ -40,8 +39,8 @@ export default async function generateImageNative({
|
||||
|
||||
const res = await providerRequest({
|
||||
provider,
|
||||
base_url: nativeOrigin({ base_url: provider.base_url }),
|
||||
path: NativeImagePath,
|
||||
base_url: dashScopeOrigin({ base_url: provider.base_url }),
|
||||
path: NativeGenerationPath,
|
||||
json: {
|
||||
model: model.slug,
|
||||
input: {
|
||||
@@ -90,7 +89,7 @@ export default async function generateImageNative({
|
||||
|
||||
if (!urls.length) {
|
||||
throw new HarnessError({
|
||||
message: `${name}: no image came back from ${NativeImagePath}.`,
|
||||
message: `${name}: no image came back from ${NativeGenerationPath}.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
@@ -112,21 +111,6 @@ export default async function generateImageNative({
|
||||
return { images };
|
||||
}
|
||||
|
||||
/**
|
||||
* The host root: the native routes live beside `<base>/compatible-mode/v1`,
|
||||
* never under it.
|
||||
*/
|
||||
function nativeOrigin({ base_url }: { base_url: string }) {
|
||||
try {
|
||||
return new URL(base_url).origin;
|
||||
} catch {
|
||||
throw new HarnessError({
|
||||
message: `The provider's base URL can't be read as an address: ${base_url}`,
|
||||
retryable: false,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The tool's size is a plain `1024x1024`; the native API wants
|
||||
* `1024*1024` and ignores anything that isn't a pair of pixels.
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
import { dashScopeOrigin, NativeGenerationPath } from "./dashscope-hosts";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
type Params = {
|
||||
candidate: HarnessCandidate;
|
||||
audio: { data: Uint8Array; format: string };
|
||||
language?: string;
|
||||
signal: AbortSignal;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the audio formats the browser records are called as MIME types.
|
||||
* DashScope takes a data URL, and Safari's `audio/mp4` recording arrives
|
||||
* here as `m4a`, which no browser spells as a MIME type.
|
||||
*/
|
||||
const AudioMimeTypes: Record<string, string> = {
|
||||
m4a: "audio/mp4",
|
||||
mp4: "audio/mp4",
|
||||
mp3: "audio/mpeg",
|
||||
ogg: "audio/ogg",
|
||||
opus: "audio/ogg",
|
||||
};
|
||||
|
||||
/**
|
||||
* Qwen-ASR on Alibaba's native multimodal route. The Token Plan host and the
|
||||
* workspace Model Studio hosts have no `/audio/transcriptions` at all: the
|
||||
* model is asked on the host root (beside `compatible-mode/v1`) with the
|
||||
* audio inline as a data URL, and answers its transcript at `output.text`.
|
||||
*
|
||||
* The formats Alibaba documents are wav, mp3 and opus, but live calls take
|
||||
* every format the recorders here produce (webm, m4a, ogg) when the label
|
||||
* matches the bytes, so the browser's own recording is sent as it is rather
|
||||
* than re-encoded first.
|
||||
*/
|
||||
export default async function transcribeNative({
|
||||
candidate,
|
||||
audio,
|
||||
language,
|
||||
signal,
|
||||
}: Params): Promise<{ text: string }> {
|
||||
const { provider, model } = candidate;
|
||||
const name = provider.name || "Alibaba Cloud";
|
||||
const format = audio.format.toLowerCase();
|
||||
const mime_type = AudioMimeTypes[format] || `audio/${format}`;
|
||||
const data_url = `data:${mime_type};base64,${Buffer.from(audio.data).toString("base64")}`;
|
||||
const hint = languageHint({ language });
|
||||
|
||||
const res = await providerRequest({
|
||||
provider,
|
||||
base_url: dashScopeOrigin({ base_url: provider.base_url }),
|
||||
path: NativeGenerationPath,
|
||||
json: {
|
||||
model: model.slug,
|
||||
input: {
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: [{ type: "input_audio", input_audio: { data: data_url } }],
|
||||
},
|
||||
],
|
||||
},
|
||||
parameters: {
|
||||
format,
|
||||
...(hint ? { language_hints: [hint] } : {}),
|
||||
},
|
||||
},
|
||||
signal,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
|
||||
const json = await res.json().catch(() => null);
|
||||
|
||||
/**
|
||||
* A cut-off or malformed answer is a failed call, not silence: saying
|
||||
* it failed lets the harness try the next model instead of handing the
|
||||
* user an empty transcript.
|
||||
*/
|
||||
if (json === null) {
|
||||
throw new HarnessError({
|
||||
message: `${name} returned an unreadable transcript.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
}
|
||||
|
||||
const text = String(json?.output?.text ?? json?.text ?? "").trim();
|
||||
|
||||
if (!text) {
|
||||
throw new HarnessError({
|
||||
message: `${name} returned an empty transcript.`,
|
||||
retryable: true,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
}
|
||||
|
||||
return { text };
|
||||
}
|
||||
|
||||
/**
|
||||
* `language_hints` takes a language (`en`), not a locale (`en-US`), so the
|
||||
* browser's BCP-47 tag is cut to its primary subtag.
|
||||
*/
|
||||
function languageHint({ language }: { language?: string }) {
|
||||
const primary = language?.trim().split(/[-_]/)[0]?.toLowerCase() ?? "";
|
||||
|
||||
return /^[a-z]{2,3}$/.test(primary) ? primary : undefined;
|
||||
}
|
||||
@@ -2,6 +2,7 @@ import { AppData } from "@/src/data/app-data";
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessAdapter, HarnessCandidate, HarnessImageOutput } from "../../types";
|
||||
import grabProviderPreset from "../grab-provider-preset";
|
||||
import { isDashScopeHost, isTokenPlanHost } from "./dashscope-hosts";
|
||||
import downloadProviderFile from "./download-provider-file";
|
||||
import generateImageNative from "./dashscope-native-image";
|
||||
import imageRequestFields from "./image-request-fields";
|
||||
@@ -217,37 +218,5 @@ async function editForm({ model, prompt, n, size, references, signal }: EditForm
|
||||
* Alibaba's DashScope and Model Studio (`maas`) hosts serve the OpenAI
|
||||
* images protocol with their own quirks: references go in the `image`
|
||||
* extension field on `/images/generations` (no multipart `/images/edits`),
|
||||
* and the response is always URLs. The shared `dashscope` hosts and the
|
||||
* workspace `maas` hosts both count; a custom provider pointed elsewhere
|
||||
* keeps the standard behaviour.
|
||||
* and the response is always URLs.
|
||||
*/
|
||||
/**
|
||||
* Alibaba's Token Plan host. Its image models are served only by the native
|
||||
* call; the compatible `/images/generations` path 404s, and trying it first
|
||||
* benches the model before the picture is made.
|
||||
*/
|
||||
export function isTokenPlanHost({ base_url }: { base_url?: string | null }) {
|
||||
if (!base_url) return false;
|
||||
|
||||
try {
|
||||
return new URL(base_url).hostname.startsWith("token-plan.");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function isDashScopeHost({ base_url }: { base_url?: string | null }) {
|
||||
if (!base_url) return false;
|
||||
|
||||
try {
|
||||
const host = new URL(base_url).hostname;
|
||||
|
||||
return (
|
||||
host == "dashscope.aliyuncs.com" ||
|
||||
host == "dashscope-intl.aliyuncs.com" ||
|
||||
host.endsWith(".maas.aliyuncs.com")
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,9 +3,14 @@ import HarnessError from "../../harness-error";
|
||||
import type { HarnessCandidate } from "../../types";
|
||||
|
||||
let payload: unknown = { text: "hello world" };
|
||||
let request: any = null;
|
||||
|
||||
mock.module("./provider-request", () => ({
|
||||
default: async () => ({ json: async () => payload }),
|
||||
default: async (args: any) => {
|
||||
request = args;
|
||||
|
||||
return { json: async () => payload };
|
||||
},
|
||||
}));
|
||||
|
||||
const { default: transcribe } = await import("./transcribe");
|
||||
@@ -23,6 +28,7 @@ const signal = new AbortController().signal;
|
||||
afterAll(() => mock.restore());
|
||||
beforeEach(() => {
|
||||
payload = { text: "hello world" };
|
||||
request = null;
|
||||
});
|
||||
|
||||
describe("transcribe", () => {
|
||||
@@ -64,4 +70,82 @@ describe("transcribe", () => {
|
||||
|
||||
expect(result.usage).toEqual({ prompt_tokens: 10, completion_tokens: 2 });
|
||||
});
|
||||
});
|
||||
|
||||
test("Alibaba's hosts are asked on the native route, not /audio/transcriptions", async () => {
|
||||
payload = { output: { text: " 你好 " } };
|
||||
|
||||
const result = await transcribe({
|
||||
candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }),
|
||||
audio,
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(result.text).toBe("你好");
|
||||
expect(request.path).toBe("/api/v1/services/aigc/multimodal-generation/generation");
|
||||
expect(request.base_url).toBe("https://token-plan.ap-southeast-1.maas.aliyuncs.com");
|
||||
expect(request.form).toBeUndefined();
|
||||
expect(request.json.model).toBe("qwen-audio-3.0-asr-flash");
|
||||
expect(request.json.input.messages[0].content[0]).toEqual({
|
||||
type: "input_audio",
|
||||
input_audio: { data: "data:audio/wav;base64,AQID" },
|
||||
});
|
||||
expect(request.json.parameters).toEqual({ format: "wav" });
|
||||
});
|
||||
|
||||
test("the native call labels the recording's format and cuts the language to its primary subtag", async () => {
|
||||
payload = { output: { text: "hello" } };
|
||||
|
||||
await transcribe({
|
||||
candidate: tokenPlanCandidate({ slug: "qwen-audio-3.0-asr-flash" }),
|
||||
audio: { data: new Uint8Array([1, 2, 3]), format: "webm" },
|
||||
language: "en-US",
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(request.json.input.messages[0].content[0].input_audio.data).toStartWith(
|
||||
"data:audio/webm;base64,",
|
||||
);
|
||||
expect(request.json.parameters).toEqual({ format: "webm", language_hints: ["en"] });
|
||||
});
|
||||
|
||||
test("a model that only transcribes as a job is refused without a call", async () => {
|
||||
const error = await transcribe({
|
||||
candidate: tokenPlanCandidate({ slug: "qwen3-asr-flash-filetrans" }),
|
||||
audio,
|
||||
signal,
|
||||
}).catch((thrown: unknown) => thrown);
|
||||
|
||||
expect(error).toBeInstanceOf(HarnessError);
|
||||
expect(error).toMatchObject({ retryable: false });
|
||||
expect(request).toBeNull();
|
||||
});
|
||||
|
||||
test("an ASR model on another provider keeps the OpenAI-style upload", async () => {
|
||||
payload = { text: "hello" };
|
||||
|
||||
await transcribe({
|
||||
candidate: {
|
||||
...candidate,
|
||||
model: { slug: "qwen3-asr-flash" },
|
||||
} as unknown as HarnessCandidate,
|
||||
audio,
|
||||
signal,
|
||||
});
|
||||
|
||||
expect(request.path).toBe("/audio/transcriptions");
|
||||
expect(request.form).toBeInstanceOf(FormData);
|
||||
});
|
||||
});
|
||||
|
||||
function tokenPlanCandidate({ slug }: { slug: string }) {
|
||||
return {
|
||||
key: `transcription:${slug}`,
|
||||
provider: {
|
||||
kind: "custom",
|
||||
base_url: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
|
||||
name: "Alibaba Cloud Token Plan",
|
||||
},
|
||||
model: { slug },
|
||||
source: "pinned",
|
||||
} as unknown as HarnessCandidate;
|
||||
}
|
||||
@@ -1,10 +1,25 @@
|
||||
import HarnessError from "../../harness-error";
|
||||
import type { HarnessAdapter } from "../../types";
|
||||
import { isDashScopeHost } from "./dashscope-hosts";
|
||||
import transcribeNative from "./dashscope-native-transcribe";
|
||||
import providerRequest from "./provider-request";
|
||||
|
||||
/**
|
||||
* The native Qwen-ASR models: the only synchronous speech models Alibaba's
|
||||
* DashScope/Model Studio hosts serve, at their own route rather than
|
||||
* `/audio/transcriptions`.
|
||||
*/
|
||||
const NativeAsrModel = /asr|paraformer/i;
|
||||
/**
|
||||
* File transcription is a job at the provider (submit, then poll), which
|
||||
* this adapter doesn't run: it would queue a task and wait for nothing.
|
||||
*/
|
||||
const AsyncOnlyAsrModel = /filetrans|paraformer/i;
|
||||
|
||||
/**
|
||||
* `POST /audio/transcriptions` as an OpenAI-style file upload, which
|
||||
* OpenRouter, OpenAI, Groq and local servers all take.
|
||||
* OpenRouter, OpenAI, Groq and local servers all take. Alibaba's hosts have
|
||||
* no such route, so their ASR models go to the native call instead.
|
||||
*/
|
||||
const transcribe: HarnessAdapter["transcribe"] = async ({
|
||||
candidate,
|
||||
@@ -12,6 +27,18 @@ const transcribe: HarnessAdapter["transcribe"] = async ({
|
||||
language,
|
||||
signal,
|
||||
}) => {
|
||||
if (isDashScopeHost({ base_url: candidate.provider.base_url }) && NativeAsrModel.test(candidate.model.slug)) {
|
||||
if (AsyncOnlyAsrModel.test(candidate.model.slug)) {
|
||||
throw new HarnessError({
|
||||
message: `${candidate.provider.name || "Alibaba Cloud"}: ${candidate.model.slug} only transcribes as an asynchronous job, which this harness doesn't run. Pick a synchronous ASR model such as qwen-audio-3.0-asr-flash.`,
|
||||
retryable: false,
|
||||
candidate_key: candidate.key,
|
||||
});
|
||||
}
|
||||
|
||||
return await transcribeNative({ candidate, audio, language, signal });
|
||||
}
|
||||
|
||||
const form = new FormData();
|
||||
|
||||
form.append("model", candidate.model.slug);
|
||||
|
||||
@@ -6,6 +6,7 @@ import swipeGesture, {
|
||||
IdleSwipeGesture,
|
||||
type SwipeGesture,
|
||||
} from "@/src/utils/swipe-gesture";
|
||||
import touchInField from "@/src/utils/touch-in-field";
|
||||
|
||||
/**
|
||||
* Below this width the rail is a slide-over (Tailwind's `md`), so the
|
||||
@@ -15,11 +16,10 @@ import swipeGesture, {
|
||||
const PhoneMaxWidth = 768;
|
||||
|
||||
/**
|
||||
* What a touch on belongs to instead of the page: a field being typed in,
|
||||
* a code editor, or a panel the app slid in itself.
|
||||
* What a touch on belongs to instead of the page: a panel the app slid in
|
||||
* itself. A field is `touchInField`.
|
||||
*/
|
||||
const OwnedTargets =
|
||||
"input, textarea, select, [contenteditable='true'], .cm-editor, [data-no-swipe]";
|
||||
const OwnedTargets = "[data-no-swipe]";
|
||||
|
||||
type Params = {
|
||||
/**
|
||||
@@ -38,6 +38,7 @@ type Params = {
|
||||
*/
|
||||
function ownsTouch({ target }: { target: EventTarget | null }): boolean {
|
||||
if (!(target instanceof Element)) return true;
|
||||
if (touchInField({ target })) return true;
|
||||
if (target.closest(OwnedTargets)) return true;
|
||||
|
||||
for (let node: Element | null = target; node; node = node.parentElement) {
|
||||
|
||||
@@ -23,6 +23,11 @@ type Params = {
|
||||
* One folder of the files browser. The page's own copy is used when it is
|
||||
* the folder asked for and nothing is searched; anything else loads from
|
||||
* the API, so a page never carries the whole volume.
|
||||
*
|
||||
* A loaded folder is only ever handed back for the volume and path it
|
||||
* belongs to: opening another folder shows its own name and a loading
|
||||
* line, never the previous folder's entries (which would still be
|
||||
* clickable, and open the folder the user just left).
|
||||
*/
|
||||
export default function useStorageFolder({ spec, path, search, page_folder }: Params) {
|
||||
const from_page = Boolean(
|
||||
@@ -33,21 +38,22 @@ export default function useStorageFolder({ spec, path, search, page_folder }: Pa
|
||||
page_folder.path == path &&
|
||||
!search,
|
||||
);
|
||||
const [folder, set_folder] = useState<StorageFolderPayload | null>(
|
||||
from_page ? page_folder || null : null,
|
||||
const request_key = folderKey({ spec, path });
|
||||
const [loaded, set_loaded] = useState<{ key: string; folder: StorageFolderPayload | null } | null>(
|
||||
from_page && page_folder ? { key: request_key, folder: page_folder } : null,
|
||||
);
|
||||
const [loading, set_loading] = useState(!from_page && Boolean(spec));
|
||||
const [error, set_error] = useState<string>();
|
||||
|
||||
useEffect(() => {
|
||||
if (!spec) {
|
||||
set_folder(null);
|
||||
set_loaded(null);
|
||||
set_loading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
if (from_page) {
|
||||
set_folder(page_folder || null);
|
||||
set_loaded({ key: request_key, folder: page_folder || null });
|
||||
set_loading(false);
|
||||
set_error(undefined);
|
||||
return;
|
||||
@@ -77,12 +83,12 @@ export default function useStorageFolder({ spec, path, search, page_folder }: Pa
|
||||
set_loading(false);
|
||||
|
||||
if (!res?.success || !res.singleRes) {
|
||||
set_folder(null);
|
||||
set_loaded({ key: request_key, folder: null });
|
||||
set_error(res?.msg || `Couldn't open that folder.`);
|
||||
return;
|
||||
}
|
||||
|
||||
set_folder(res.singleRes);
|
||||
set_loaded({ key: request_key, folder: res.singleRes });
|
||||
};
|
||||
|
||||
load().catch(() => {});
|
||||
@@ -90,5 +96,16 @@ export default function useStorageFolder({ spec, path, search, page_folder }: Pa
|
||||
return () => controller.abort();
|
||||
}, [spec?.volume, spec?.owner_id, path, search, from_page, page_folder]);
|
||||
|
||||
return { folder, loading, error };
|
||||
const folder = loaded?.key == request_key ? loaded.folder : null;
|
||||
const pending = Boolean(spec) && loaded?.key != request_key;
|
||||
|
||||
return { folder, loading: loading || pending, error };
|
||||
}
|
||||
|
||||
/**
|
||||
* What a loaded folder belongs to: its volume, its owner and its path. A
|
||||
* search is left out, since filtered entries are still that folder's.
|
||||
*/
|
||||
function folderKey({ spec, path }: { spec: Params["spec"]; path: string }) {
|
||||
return `${spec?.volume || ""}:${spec?.owner_id ?? ""}:${path}`;
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, type RefObject } from "react";
|
||||
import { AppData } from "@/src/data/app-data";
|
||||
import swipeGesture, {
|
||||
IdleSwipeGesture,
|
||||
type SwipeGesture,
|
||||
} from "@/src/utils/swipe-gesture";
|
||||
import touchInField from "@/src/utils/touch-in-field";
|
||||
|
||||
type Params = {
|
||||
/** The panel itself: only a finger that lands on it counts. */
|
||||
panel_ref: RefObject<HTMLElement | null>;
|
||||
/** Only while it is open; a panel that is closed keeps no listener. */
|
||||
enabled: boolean;
|
||||
/** The way back off the edge the panel slid in from. */
|
||||
direction: "left" | "right";
|
||||
on_close: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Closes an open side panel with a phone swipe back towards the edge it slid
|
||||
* in from, where the page's own swipes are blocked on it (`data-no-swipe`).
|
||||
* It reads the finger on the panel alone, so the panel that is open is the
|
||||
* one that answers, and leaves the page's swipe hook to the page.
|
||||
*
|
||||
* The thresholds and the state machine are `swipe-gesture.ts`, the same ones
|
||||
* the page's swipes use: a flick, not a long drag, and one that is clearly
|
||||
* more sideways than up or down.
|
||||
*/
|
||||
export default function useSwipeToClose({
|
||||
panel_ref,
|
||||
enabled,
|
||||
direction,
|
||||
on_close,
|
||||
}: Params) {
|
||||
const close = useRef(on_close);
|
||||
|
||||
close.current = on_close;
|
||||
|
||||
useEffect(() => {
|
||||
const panel = panel_ref.current;
|
||||
|
||||
if (!panel || !enabled) return;
|
||||
|
||||
let gesture: SwipeGesture = IdleSwipeGesture;
|
||||
let touched_at = 0;
|
||||
|
||||
const restart = () => {
|
||||
gesture = IdleSwipeGesture;
|
||||
};
|
||||
|
||||
const onStart = (event: TouchEvent) => {
|
||||
restart();
|
||||
|
||||
if (event.touches.length != 1) return;
|
||||
if (document.getElementById("twui-modal-root")?.childElementCount) return;
|
||||
if (touchInField({ target: event.target })) return;
|
||||
|
||||
const touch = event.touches[0];
|
||||
|
||||
if (!touch) return;
|
||||
|
||||
touched_at = Date.now();
|
||||
gesture = swipeGesture({
|
||||
gesture: IdleSwipeGesture,
|
||||
input: { type: "start", x: touch.clientX, y: touch.clientY },
|
||||
}).gesture;
|
||||
};
|
||||
|
||||
const onMove = (event: TouchEvent) => {
|
||||
if (!gesture.touching) return;
|
||||
|
||||
const touch = event.touches[0];
|
||||
|
||||
if (!touch || event.touches.length != 1) {
|
||||
restart();
|
||||
return;
|
||||
}
|
||||
|
||||
/**
|
||||
* A finger that has rested on the panel, or that is selecting
|
||||
* text, is reading it, not pushing it away.
|
||||
*/
|
||||
if (Date.now() - touched_at > AppData.MobileSwipeMaxMs) {
|
||||
restart();
|
||||
return;
|
||||
}
|
||||
|
||||
if (window.getSelection()?.toString()) {
|
||||
restart();
|
||||
return;
|
||||
}
|
||||
|
||||
const step = swipeGesture({
|
||||
gesture,
|
||||
input: { type: "move", x: touch.clientX, y: touch.clientY },
|
||||
});
|
||||
|
||||
gesture = step.gesture;
|
||||
|
||||
if (step.swipe != direction) return;
|
||||
|
||||
restart();
|
||||
close.current();
|
||||
};
|
||||
|
||||
panel.addEventListener("touchstart", onStart, { passive: true });
|
||||
panel.addEventListener("touchmove", onMove, { passive: true });
|
||||
panel.addEventListener("touchend", restart);
|
||||
panel.addEventListener("touchcancel", restart);
|
||||
|
||||
return () => {
|
||||
panel.removeEventListener("touchstart", onStart);
|
||||
panel.removeEventListener("touchmove", onMove);
|
||||
panel.removeEventListener("touchend", restart);
|
||||
panel.removeEventListener("touchcancel", restart);
|
||||
};
|
||||
}, [panel_ref, enabled, direction]);
|
||||
}
|
||||
@@ -76,7 +76,6 @@ export default function BotPanel({ bot, open, on_open, on_close }: Props) {
|
||||
open={open}
|
||||
onClose={on_close}
|
||||
label={`Edit ${name}`}
|
||||
className="w-[420px] max-w-[92vw]"
|
||||
>
|
||||
<Row className="shrink-0 gap-3! flex-nowrap items-center px-4 py-3 border-0 border-b border-solid border-hairline">
|
||||
<Stack className="shrink-0">
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import BotSuggestionChip from "./bot-suggestion-chip";
|
||||
|
||||
const longStep =
|
||||
"Write a full launch plan for next quarter with owners, deadlines and the review checkpoints for every team";
|
||||
|
||||
function render({ step }: { step: string }) {
|
||||
return renderToString(<BotSuggestionChip step={step} />);
|
||||
}
|
||||
|
||||
describe("BotSuggestionChip", () => {
|
||||
test("shows the step and keeps it inside the chip", () => {
|
||||
const html = render({ step: longStep });
|
||||
|
||||
expect(html).toContain(longStep);
|
||||
// The twui button's content wrapper is nowrap by default, which let a
|
||||
// long step spill out of the button's outline on a phone.
|
||||
expect(html).toContain("[&_.twui-button-content-wrapper]:whitespace-normal");
|
||||
expect(html).toContain("[&_.twui-button-content-wrapper]:min-w-0");
|
||||
expect(html).toContain("break-words");
|
||||
expect(html).toContain("max-w-full");
|
||||
});
|
||||
});
|
||||
@@ -22,10 +22,10 @@ export default function BotSuggestionChip({ step }: Props) {
|
||||
color="gray"
|
||||
size="smaller"
|
||||
title={`Put this in your input: ${step}`}
|
||||
className="inline-flex h-auto max-w-full gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0"
|
||||
className="inline-flex h-auto max-w-full min-w-0 gap-1! flex-nowrap align-middle px-2! py-1! text-left text-[13px] font-normal whitespace-normal [&_.twui-button-content-wrapper]:min-w-0 [&_.twui-button-content-wrapper]:whitespace-normal"
|
||||
onClick={() => onUseSuggestion({ text: step })}
|
||||
>
|
||||
<Span className="min-w-0">{step}</Span>
|
||||
<Span className="min-w-0 break-words">{step}</Span>
|
||||
<ArrowUpRight size={14} aria-hidden className="shrink-0" />
|
||||
</Button>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import Button from "@moduletrace/twui/layout/Button";
|
||||
import Card from "@moduletrace/twui/elements/Card";
|
||||
import Span from "@moduletrace/twui/layout/Span";
|
||||
import { TriangleAlert, X } from "lucide-react";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
type Props = {
|
||||
message: string;
|
||||
tone?: "error" | "warning";
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
/**
|
||||
* Why the last send didn't go, or why dictation stopped, under the composer.
|
||||
* A card rather than a line of grey text, so a failed send reads as a
|
||||
* failure, and it can be put away once read.
|
||||
*/
|
||||
export default function ComposerNotice({
|
||||
message,
|
||||
tone = "error",
|
||||
onClose,
|
||||
}: Props) {
|
||||
return (
|
||||
<Card
|
||||
role="alert"
|
||||
className={twMerge(
|
||||
"w-full gap-2! rounded-default border-solid py-2! px-3!",
|
||||
tone == "error"
|
||||
? "border-error/40! bg-error/5!"
|
||||
: "border-warning/40! bg-warning/5!",
|
||||
)}
|
||||
>
|
||||
<TriangleAlert
|
||||
size={15}
|
||||
aria-hidden
|
||||
className={twMerge(
|
||||
"shrink-0",
|
||||
tone == "error" ? "text-error" : "text-warning",
|
||||
)}
|
||||
/>
|
||||
<Span className="min-w-0 flex-1 text-xs leading-5 break-words">
|
||||
{message}
|
||||
</Span>
|
||||
<Button
|
||||
title="Dismiss"
|
||||
aria-label="Dismiss"
|
||||
type="button"
|
||||
variant="ghost"
|
||||
color="text"
|
||||
size="smaller"
|
||||
onClick={onClose}
|
||||
className="shrink-0 rounded-default-xs p-1! text-ink-secondary hover:text-ink"
|
||||
>
|
||||
<X size={14} aria-hidden />
|
||||
</Button>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
} from "react";
|
||||
import Row from "@moduletrace/twui/layout/Row";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import P from "@moduletrace/twui/layout/P";
|
||||
import type {
|
||||
BotExtensionsPayload,
|
||||
BotMessageAttachment,
|
||||
@@ -34,10 +33,12 @@ import ComposerAttachments from "./composer-attachments";
|
||||
import ComposerClearButton from "./composer-clear-button";
|
||||
import ComposerEditor from "./composer-editor";
|
||||
import ComposerMentionList from "./composer-mention-list";
|
||||
import ComposerNotice from "./composer-notice";
|
||||
import ComposerReplyPreview from "./composer-reply-preview";
|
||||
import ComposerSendButton from "./composer-send-button";
|
||||
import ComposerTools from "./composer-tools";
|
||||
import ComposerVoiceButton from "./composer-voice-button";
|
||||
import { twMerge } from "tailwind-merge";
|
||||
|
||||
/**
|
||||
* What the conversation can do to the composer from outside it.
|
||||
@@ -477,13 +478,23 @@ export default function Composer({
|
||||
/>
|
||||
</Row>
|
||||
{notice ? (
|
||||
<P
|
||||
role="alert"
|
||||
className="w-full max-w-container mx-auto px-3 md:px-6 -mt-5 pb-3 text-xs text-ink-secondary"
|
||||
<Stack
|
||||
className={twMerge(
|
||||
"w-full px-3 pb-3 md:px-6 gap-0! items-stretch max-w-container m-auto",
|
||||
"mb-4",
|
||||
)}
|
||||
>
|
||||
{notice}
|
||||
</P>
|
||||
<ComposerNotice
|
||||
message={notice}
|
||||
tone={error ? "error" : "warning"}
|
||||
onClose={() => {
|
||||
setError(undefined);
|
||||
recorder.setError(undefined);
|
||||
}}
|
||||
/>
|
||||
</Stack>
|
||||
) : null}
|
||||
|
||||
<ComposerTools
|
||||
bot={bot}
|
||||
workspace_id={workspace_id}
|
||||
|
||||
@@ -5,6 +5,7 @@ import Span from "@moduletrace/twui/layout/Span";
|
||||
import Stack from "@moduletrace/twui/layout/Stack";
|
||||
import type { StorageFolderPayload, StorageSpecOption } from "@/src/types";
|
||||
import type { StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import { storageBreadcrumbs } from "@/src/utils/storage-volumes";
|
||||
import { emptyFolderText, folderSummary } from "@/src/utils/folder-text";
|
||||
import imagePreviewGallery from "@/src/utils/image-preview-gallery";
|
||||
import FilesBreadcrumbRow from "@/src/components/general/files-breadcrumb-row";
|
||||
@@ -48,6 +49,7 @@ export default function FilesBrowser({
|
||||
() => imagePreviewGallery({ items: (folder?.entries || []).map((entry) => ({ ...entry, url: entry.url || "" })) }),
|
||||
[folder],
|
||||
);
|
||||
const crumbs = spec ? storageBreadcrumbs({ spec, path }) : folder?.breadcrumbs || [];
|
||||
|
||||
return (
|
||||
<Row className="w-full mt-6 gap-6! flex-wrap items-start lg:flex-nowrap">
|
||||
@@ -82,16 +84,14 @@ export default function FilesBrowser({
|
||||
<Stack className="grow min-w-0 w-full items-stretch">
|
||||
<Stack className="gap-1! items-stretch">
|
||||
<H2 className="text-[18px]! leading-6 font-bold tracking-normal text-ink">
|
||||
{folder?.breadcrumbs.at(-1)?.name ||
|
||||
folder?.label ||
|
||||
"Files"}
|
||||
{crumbs.at(-1)?.name || folder?.label || "Files"}
|
||||
</H2>
|
||||
<Span className="text-[13px] leading-[18px] text-ink-secondary">
|
||||
{folderSummary({ folder })}
|
||||
{folderSummary({ folder, loading })}
|
||||
</Span>
|
||||
</Stack>
|
||||
<FilesBreadcrumbRow
|
||||
crumbs={folder?.breadcrumbs || []}
|
||||
crumbs={crumbs}
|
||||
onOpenFolder={onOpenFolder}
|
||||
/>
|
||||
<FilesSearchInput value={search} onChange={onSearch} />
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import listStorageEntries, { storageBreadcrumbs } from "@/src/functions/backend/storage/list-storage-entries";
|
||||
import listStorageEntries from "@/src/functions/backend/storage/list-storage-entries";
|
||||
import resolveStoragePath from "@/src/functions/backend/storage/resolve-storage-path";
|
||||
import resolveStorageSpec, { grabStorageSpecs } from "@/src/functions/backend/storage/resolve-storage-spec";
|
||||
import type { PagePropsType, StorageFolderPayload } from "@/src/types";
|
||||
import { parseStorageSpec, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import { parseStorageSpec, storageBreadcrumbs, type StorageSpec } from "@/src/utils/storage-volumes";
|
||||
import type { BunextPageServerFn } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import userAuth from "@/src/functions/backend/auth/user-auth";
|
||||
import listStorageEntries, { storageBreadcrumbs } from "@/src/functions/backend/storage/list-storage-entries";
|
||||
import listStorageEntries from "@/src/functions/backend/storage/list-storage-entries";
|
||||
import resolveStoragePath from "@/src/functions/backend/storage/resolve-storage-path";
|
||||
import resolveStorageSpec from "@/src/functions/backend/storage/resolve-storage-spec";
|
||||
import type { StorageFolderPayload } from "@/src/types";
|
||||
import parseWithSchema from "@/src/utils/parse-with-schema";
|
||||
import safeErrorMessage from "@/src/utils/safe-error-message";
|
||||
import { StorageListRequestSchema } from "@/src/schemas/storage-schema";
|
||||
import { parseStorageSpec } from "@/src/utils/storage-volumes";
|
||||
import { parseStorageSpec, storageBreadcrumbs } from "@/src/utils/storage-volumes";
|
||||
import type { APIResponseObject, BunextAPIRouteHandler } from "@moduletrace/bunext/types";
|
||||
|
||||
/**
|
||||
|
||||
@@ -30,6 +30,11 @@ describe("folderSummary", () => {
|
||||
test("asks for a folder when there is none", () => {
|
||||
expect(folderSummary({ folder: null })).toBe("Pick a folder to look inside.");
|
||||
});
|
||||
|
||||
test("a folder still loading is never counted as none", () => {
|
||||
expect(folderSummary({ folder: null, loading: true })).toBe("Loading...");
|
||||
expect(folderSummary({ folder: folder({ total: 4 }), loading: true })).toBe("Loading...");
|
||||
});
|
||||
});
|
||||
|
||||
describe("emptyFolderText", () => {
|
||||
|
||||
@@ -5,7 +5,14 @@ import type { StorageFolderPayload } from "@/src/types";
|
||||
* that isn't on disk, that it isn't there. A stale folder link must never
|
||||
* read as an empty folder.
|
||||
*/
|
||||
export function folderSummary({ folder }: { folder: StorageFolderPayload | null }) {
|
||||
export function folderSummary({
|
||||
folder,
|
||||
loading,
|
||||
}: {
|
||||
folder: StorageFolderPayload | null;
|
||||
loading?: boolean;
|
||||
}) {
|
||||
if (loading) return "Loading...";
|
||||
if (!folder) return "Pick a folder to look inside.";
|
||||
|
||||
if (folder.missing) {
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import sidePanelCloseSwipe from "./side-panel-close-swipe";
|
||||
|
||||
describe("sidePanelCloseSwipe", () => {
|
||||
test("a panel from the left closes on a swipe back to the left", () => {
|
||||
expect(sidePanelCloseSwipe({ side: "left" })).toBe("left");
|
||||
});
|
||||
|
||||
test("a panel from the right closes on a swipe back to the right", () => {
|
||||
expect(sidePanelCloseSwipe({ side: "right" })).toBe("right");
|
||||
});
|
||||
|
||||
test("closing is always the opposite of the page swipe that opened it", () => {
|
||||
expect(sidePanelCloseSwipe({ side: "left" })).not.toBe("right");
|
||||
expect(sidePanelCloseSwipe({ side: "right" })).not.toBe("left");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,15 @@
|
||||
export type SidePanelSide = "left" | "right";
|
||||
|
||||
type Params = {
|
||||
side: SidePanelSide;
|
||||
};
|
||||
|
||||
/**
|
||||
* The swipe that closes a panel: back towards the edge it slid in from, so
|
||||
* the way it came. The rail slides in from the left and closes on a drag to
|
||||
* the left; the bot panel slides in from the right and closes on a drag to
|
||||
* the right. That is the opposite of the page swipe that opens each one.
|
||||
*/
|
||||
export default function sidePanelCloseSwipe({ side }: Params): "left" | "right" {
|
||||
return side == "left" ? "left" : "right";
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import {
|
||||
isSameStorageSpec,
|
||||
isStorageVolume,
|
||||
parseStorageSpec,
|
||||
storageBreadcrumbs,
|
||||
storagePathName,
|
||||
storageSpecHref,
|
||||
storageVolumeFromRef,
|
||||
@@ -77,6 +78,28 @@ describe("volume names", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("storageBreadcrumbs", () => {
|
||||
const spec = { volume: "computers", owner_id: 1 } as const;
|
||||
|
||||
test("at the top of a volume there is only the way back to it", () => {
|
||||
expect(storageBreadcrumbs({ spec })).toEqual([
|
||||
{ name: "", href: `${StorageBrowserPath}?volume=computers&owner=1` },
|
||||
]);
|
||||
expect(storageBreadcrumbs({ spec, path: "/" })).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("walks down one crumb per segment", () => {
|
||||
expect(storageBreadcrumbs({ spec, path: "seo/raw mes" })).toEqual([
|
||||
{ name: "", href: `${StorageBrowserPath}?volume=computers&owner=1` },
|
||||
{ name: "seo", href: `${StorageBrowserPath}?volume=computers&owner=1&path=seo` },
|
||||
{
|
||||
name: "raw mes",
|
||||
href: `${StorageBrowserPath}?volume=computers&owner=1&path=seo%2Fraw+mes`,
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("isSameStorageSpec", () => {
|
||||
test("compares volume and owner", () => {
|
||||
const a = { volume: "bots", owner_id: 1 } as const;
|
||||
|
||||
@@ -154,6 +154,31 @@ export function storageSpecHref({ spec, path }: { spec: StorageSpec; path?: stri
|
||||
return `${StorageBrowserPath}?${query.toString()}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The breadcrumb trail of a folder, from the volume's top: one crumb per
|
||||
* segment, each with the address that opens it. Built from the path asked
|
||||
* for, so a trail can be shown while its listing still loads.
|
||||
*/
|
||||
export function storageBreadcrumbs({
|
||||
spec,
|
||||
path: relative,
|
||||
}: {
|
||||
spec: StorageSpec;
|
||||
path?: string | null;
|
||||
}) {
|
||||
const segments = (relative || "").split("/").filter(Boolean);
|
||||
const crumbs = [{ name: "", href: storageSpecHref({ spec }) }];
|
||||
|
||||
for (let i = 1; i <= segments.length; i++) {
|
||||
crumbs.push({
|
||||
name: segments[i - 1] || "",
|
||||
href: storageSpecHref({ spec, path: segments.slice(0, i).join("/") }),
|
||||
});
|
||||
}
|
||||
|
||||
return crumbs;
|
||||
}
|
||||
|
||||
/**
|
||||
* A folder's label for a chip: the last path segment, or the volume's
|
||||
* title at the top.
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
/**
|
||||
* Where a sideways drag belongs to the control instead of the page: typing,
|
||||
* selecting a field's text or moving its caret all live here.
|
||||
*/
|
||||
export const FieldTouchTargets =
|
||||
"input, textarea, select, [contenteditable='true'], .cm-editor";
|
||||
|
||||
type Params = {
|
||||
target: EventTarget | null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether a touch landed on a field, which owns it: a swipe read there would
|
||||
* take a caret or a selection, not a pane.
|
||||
*/
|
||||
export default function touchInField({ target }: Params): boolean {
|
||||
if (!(target instanceof Element)) return false;
|
||||
|
||||
return Boolean(target.closest(FieldTouchTargets));
|
||||
}
|
||||
Reference in New Issue
Block a user