Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Feat share model run settings through links (#11710)
Eyera547fdf2ecc64
diff --git a/studio/frontend/src/app/provider.tsx b/studio/frontend/src/app/provider.tsxindex b55038b1aa9..9966b229856 100644--- a/studio/frontend/src/app/provider.tsx+++ b/studio/frontend/src/app/provider.tsx@@ -21,6 +21,7 @@ import { fetchDeviceType } from "@/config/env";import { getTauriAuthFailure, tauriAutoAuth } from "@/features/auth";import { resyncInferenceStatusAfterServerModelChange } from "@/features/chat";import { DeepLinkHandler } from "@/features/deep-links";+import { receiveSharedRunConfigUrls } from "@/features/model-picker";import {DownloadManagerPanel,dismissStartToasts,@@ -1088,7 +1089,7 @@ export function AppProvider({ children }: AppProviderProps) {<MotionConfig reducedMotion={REDUCED_MOTION_MAP[reduceMotion]}><TooltipProvider><AppearanceCustomizationEffect />- <DeepLinkHandler />+ <DeepLinkHandler onOpenUrls={receiveSharedRunConfigUrls} /><TauriWrapper>{children}</TauriWrapper><SttDownloadPrompt /><Toasterdiff --git a/studio/frontend/src/app/routes/__root.tsx b/studio/frontend/src/app/routes/__root.tsxindex f92653a41d4..35bded44922 100644--- a/studio/frontend/src/app/routes/__root.tsx+++ b/studio/frontend/src/app/routes/__root.tsx@@ -33,6 +33,7 @@ import { FIND_SCOPE_ATTRIBUTE, FindInPage } from "@/features/find-in-page";import { HfTokenWarningDialog } from "@/features/hf-auth";import { InterfaceZoom, zoomInterfaceFromMenu } from "@/features/interface-zoom";import { bootstrapPersistedCredentials } from "@/features/credentials/bootstrap";+import { SharedRunConfigLinkHandler } from "@/features/model-picker";import { backfillModelOverrides } from "@/features/model-picker/api/migrate-model-overrides";import { usePersonalizationSync } from "@/features/profile";import { RemoteCodeConsentDialog } from "@/features/security";@@ -819,6 +820,9 @@ function RootLayout() {return (<AppProvider><CredentialBootstrapGate active={!isAuthFlowRoute}>+ <SharedRunConfigLinkHandler+ chatSearch={shouldMountChat ? chatSearch : null}+ />{content}</CredentialBootstrapGate></AppProvider>diff --git a/studio/frontend/src/features/chat/index.ts b/studio/frontend/src/features/chat/index.tsindex ebd6abc1160..a6713d40a09 100644--- a/studio/frontend/src/features/chat/index.ts+++ b/studio/frontend/src/features/chat/index.ts@@ -537,4 +537,9 @@ export {} from "./utils/composer-preferences";export { isTextAttachmentName } from "./text-attachment-accept";+export {+ ggufVariantsQuery,+ runBoundedVariantsRequest,+} from "./api/gguf-variants-request";+export type { ChatModelSummary, ChatLoraSummary } from "./types/runtime";export { startLlamaCppAutoReload } from "./llama-cpp-auto-reload";diff --git a/studio/frontend/src/features/deep-links/deep-link-handler.tsx b/studio/frontend/src/features/deep-links/deep-link-handler.tsxindex 256aed8bc2d..34d15991fbb 100644--- a/studio/frontend/src/features/deep-links/deep-link-handler.tsx+++ b/studio/frontend/src/features/deep-links/deep-link-handler.tsx@@ -16,7 +16,14 @@ async function restoreMainWindow(): Promise<void> {await invoke("reveal_main_window");}-export function DeepLinkHandler() {+export function DeepLinkHandler({+ onOpenUrls,+}: {+ onOpenUrls?: (+ urls: string[],+ source: "startup" | "event",+ ) => boolean | "ignored";+}) {const navigate = useNavigate();useEffect(() => {@@ -26,8 +33,20 @@ export function DeepLinkHandler() {let receivedLiveIntent = false;let unlisten: (() => void) | undefined;- const handleUrls = (urls: string[]): boolean => {+ const handleUrls = (+ urls: string[],+ source: "startup" | "event",+ ): boolean => {if (disposed) return false;+ const sharedIntent = onOpenUrls?.(urls, source);+ if (sharedIntent === "ignored") {+ return true;+ }+ if (sharedIntent) {+ acceptIntent.clear();+ void restoreMainWindow().catch(() => undefined);+ return true;+ }let hasValidIntent = false;let intent: ReturnType<typeof parseUnslothDeepLink> = null;@@ -66,7 +85,9 @@ export function DeepLinkHandler() {if (disposed) return;const cleanup = await onOpenUrl((urls) => {- if (handleUrls(urls)) receivedLiveIntent = true;+ if (handleUrls(urls, "event")) {+ receivedLiveIntent = true;+ }});if (disposed) {cleanup();@@ -75,7 +96,9 @@ export function DeepLinkHandler() {unlisten = cleanup;const currentUrls = await getCurrent();- if (currentUrls && !receivedLiveIntent) handleUrls(currentUrls);+ if (currentUrls && !receivedLiveIntent) {+ handleUrls(currentUrls, "startup");+ }}void subscribe().catch(() => undefined);@@ -84,7 +107,7 @@ export function DeepLinkHandler() {disposed = true;unlisten?.();};- }, [navigate]);+ }, [navigate, onOpenUrls]);return null;}diff --git a/studio/frontend/src/features/deep-links/deep-link-intent.ts b/studio/frontend/src/features/deep-links/deep-link-intent.tsindex 7f310c0a6d2..ff66941011f 100644--- a/studio/frontend/src/features/deep-links/deep-link-intent.ts+++ b/studio/frontend/src/features/deep-links/deep-link-intent.ts@@ -8,7 +8,7 @@ export function createDeepLinkIntentGate(let lastIntent: { key: string; handledAt: number } | null = null;let sequence = 0;- return (model: string, file?: string): number | null => {+ const accept = (model: string, file?: string): number | null => {const handledAt = now();const key = `${model}\0${file ?? ""}`;if (@@ -21,4 +21,10 @@ export function createDeepLinkIntentGate(sequence += 1;return sequence;};++ return Object.assign(accept, {+ clear: () => {+ lastIntent = null;+ },+ });}diff --git a/studio/frontend/src/features/deep-links/index.ts b/studio/frontend/src/features/deep-links/index.tsindex 1f096aa8dd7..381ecbbc7d4 100644--- a/studio/frontend/src/features/deep-links/index.ts+++ b/studio/frontend/src/features/deep-links/index.ts@@ -2,3 +2,5 @@// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0export { DeepLinkHandler } from "./deep-link-handler";+export { createDeepLinkIntentGate } from "./deep-link-intent";+export { isValidRepoId, parseUnslothDeepLink } from "./parse-deep-link";diff --git a/studio/frontend/src/features/deep-links/parse-deep-link.ts b/studio/frontend/src/features/deep-links/parse-deep-link.tsindex 4446eec734c..182d0ff58b7 100644--- a/studio/frontend/src/features/deep-links/parse-deep-link.ts+++ b/studio/frontend/src/features/deep-links/parse-deep-link.ts@@ -25,6 +25,15 @@ function isValidRepoSegment(segment: string): boolean {);}+export function isValidRepoId(model: string): boolean {+ const segments = model.split("/");+ return (+ !model.endsWith(".git") &&+ segments.length === 2 &&+ segments.every(isValidRepoSegment)+ );+}+function isValidGgufFile(file: string): boolean {if (file.length === 0 ||@@ -85,12 +94,7 @@ export function parseUnslothDeepLink(}const model = url.searchParams.get("model") ?? "";- const segments = model.split("/");- if (- model.endsWith(".git") ||- segments.length !== 2 ||- !segments.every(isValidRepoSegment)- ) {+ if (!isValidRepoId(model)) {return null;}diff --git a/studio/frontend/src/features/hub/index.ts b/studio/frontend/src/features/hub/index.tsindex 1a96fd7d97a..51216e64cb2 100644--- a/studio/frontend/src/features/hub/index.ts+++ b/studio/frontend/src/features/hub/index.ts@@ -140,3 +140,8 @@ export { TransportConflictDialog } from "./catalog/transport-conflict-dialog";export { TrainIcon } from "./components/train-icon";export { isHiddenModelId } from "./lib/hidden-models";export { classifyUnslothSupport, studioPageForTask } from "./lib/unsloth-support";+export {+ INVENTORY_FRESHNESS_WINDOW_MS,+ isInventoryStampFresh,+} from "./inventory/inventory-freshness";+export { withAbort } from "./lib/abort-signals";diff --git a/studio/frontend/src/features/model-picker/components/model-config-page.tsx b/studio/frontend/src/features/model-picker/components/model-config-page.tsxindex 43de6a816a8..cbe092cc073 100644--- a/studio/frontend/src/features/model-picker/components/model-config-page.tsx+++ b/studio/frontend/src/features/model-picker/components/model-config-page.tsx@@ -182,6 +182,14 @@ import {vramFractionToPercent,vramPercentToFraction,} from "../model-config/per-model-config";+import {+ type RunConfigImport,+ SharedRunConfigControls,+ SharedRunConfigReview,+ cancelRunConfigImportForEdit,+ isRunConfigEditorChange,+ isRunConfigVariantUnresolved,+} from "../sharing";import { ChatTemplateEditorDialog } from "./chat-template-editor-dialog";import { MemoryEstimateRow } from "./memory-estimate-row";import type { ModelPickTarget } from "./model-selector/types";@@ -2036,6 +2044,7 @@ export function ModelConfigPage({(s) => s.loadedMlxKvQuantRequested,);const isActiveModel = loadedConfig != null;+ const sharedVariantUnresolved = isRunConfigVariantUnresolved(target);const hfToken = useChatRuntimeStore((s) => s.hfToken);const activeNativePathToken = useChatRuntimeStore((s) => s.activeNativePathToken,@@ -2194,6 +2203,15 @@ export function ModelConfigPage({const [autoOpenAdvanced, setAutoOpenAdvanced] = useState(() =>hasNonDefaultAdvanced(configState),);+ const [importedConfig, setImportedConfig] = useState<RunConfigImport | null>(+ null,+ );+ const handleSharedConfigImport = useCallback((imported: RunConfigImport) => {+ setImportedConfig(imported);+ if (Object.keys(imported.changes).length > 0) {+ setAutoOpenAdvanced(true);+ }+ }, []);// Frozen like the rest of the auto-open decision, so editing the width does not reopen the// section the user just closed.const [initialMlxKvQuant] = useState(() => configState.mlxKvQuant ?? null);@@ -2230,7 +2248,7 @@ export function ModelConfigPage({: templateDefaults.loading;// Fetch GGUF header dims to size the GPU Memory sliders; the context also fills in below.- const contextFetchKey = target.isGguf+ const contextFetchKey = target.isGguf && !sharedVariantUnresolved? `${target.id}\n${target.ggufVariant ?? ""}\n${hfToken || ""}\n${nativePathToken ?? ""}`: null;const [fetchedStagedDims, setFetchedStagedDims] = useState<{@@ -2650,7 +2668,12 @@ export function ModelConfigPage({config.nUbatch != null);const gpuIndexKind =pinnableGpuContext(gpuDevices, resolvedIsDiffusion).indexKind ?? null;+ const handleSharedConfigEdit = () => {+ cancelRunConfigImportForEdit(draftKey);+ setImportedConfig(null);+ };const update = (patch: Partial<PerModelConfig>) => {+ handleSharedConfigEdit();// Every control lands here and nothing else does: the hydration effect's own sanitising// writes go through setConfig, and marking those would have the read refuse its result.markModelConfigDraftEdited(draftKey);@@ -3178,6 +3201,9 @@ export function ModelConfigPage({};const handleSave = () => {+ if (sharedVariantUnresolved) {+ return;+ }const { effectiveRuntimeConfig } = commitDraft();const { saved, defaultConfig } = persistConfig(effectiveRuntimeConfig);if (!saved) {@@ -3200,6 +3226,9 @@ export function ModelConfigPage({};const handleRun = () => {+ if (sharedVariantUnresolved) {+ return;+ }if (budgetSettling) {return;}@@ -3266,7 +3295,14 @@ export function ModelConfigPage({};return (- <div className="hint-on-hover flex flex-col">+ <div+ className="hint-on-hover flex flex-col"+ onChange={(event) => {+ if (isRunConfigEditorChange(event)) {+ handleSharedConfigEdit();+ }+ }}+ >{variant === "page" && showHeader && (// -ml-1.5 cancels the icon's inset in its 28px circle, so the chevron starts on// the same left edge as the rows below.@@ -3295,6 +3331,14 @@ export function ModelConfigPage({</div>)}+ <SharedRunConfigReview+ target={target}+ imported={importedConfig}+ draftConfig={configState}+ currentConfig={config}+ remember={remember}+ hasSavedSettings={savedRemember}+ /><div className="space-y-5">{memoryEstimateRequest != null && (<MemoryEstimateRow@@ -3491,6 +3535,7 @@ export function ModelConfigPage({size="sm"className={FOOTER_BUTTON_CLASS}disabled={+ sharedVariantUnresolved ||stagedMetadataPending ||budgetSettling ||(!extraArgsLoadable && !sharedExtraArgsCleared) ||@@ -3516,6 +3561,7 @@ export function ModelConfigPage({// settings the load path strips or has already captured. Forget stores nothing, so// broken saved arguments must not lock it.disabled={+ sharedVariantUnresolved ||stagedMetadataPending ||budgetSettling ||(remember &&@@ -3535,6 +3581,7 @@ export function ModelConfigPage({className={`${FOOTER_BUTTON_CLASS} text-muted-foreground`}disabled={atDefault}onClick={() => {+ handleSharedConfigEdit();// Reset writes through setConfig, not update, so it marks the draft itself.markModelConfigDraftEdited(draftKey);// And drops the raw edit: token equality alone would make the discarded text@@ -3550,6 +3597,21 @@ export function ModelConfigPage({>Reset</Button>+ {target.isGguf && (+ <SharedRunConfigControls+ className={FOOTER_BUTTON_CLASS}+ target={target}+ config={config}+ ready={!extraArgsHydrating}+ canImport={variant !== "sidebar"}+ isDiffusion={resolvedIsDiffusion}+ disabled={+ sharedExtraArgsRefused ||+ (!extraArgsLoadable && !sharedExtraArgsCleared)+ }+ onImport={handleSharedConfigImport}+ />+ )}</div></div>diff --git a/studio/frontend/src/features/model-picker/index.ts b/studio/frontend/src/features/model-picker/index.tsindex 51fe7584819..69f5f5248fd 100644--- a/studio/frontend/src/features/model-picker/index.ts+++ b/studio/frontend/src/features/model-picker/index.ts@@ -83,3 +83,7 @@ export {resolveInitialConfig,resolveResidentInitialConfig,} from "./model-config/per-model-config";+export {+ SharedRunConfigLinkHandler,+ receiveSharedRunConfigUrls,+} from "./sharing";diff --git a/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts b/studio/frontend/src/features/model-picker/model-config/model-config-handoff.tsindex 606c9fd8dc8..e1639d41126 100644--- a/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts+++ b/studio/frontend/src/features/model-picker/model-config/model-config-handoff.ts@@ -19,6 +19,8 @@ import { adoptLegacyConfigKey } from "./per-model-config";export interface ModelConfigHandoffRequest {requestId: string;+ // undefined uses requestId; null opens plain /chat; a string selects that new-chat draft.+ newChatId?: string | null;id: string;displayName?: string;meta: ModelSelectorChangeMeta;@@ -183,7 +185,9 @@ export function modelConfigHandoffForDestination(destination.threadId ||destination.compareId ||destination.projectId ||- request.requestId !== destination.newChatId+ (request.newChatId === undefined+ ? request.requestId+ : request.newChatId) !== (destination.newChatId ?? null)) {return null;}diff --git a/studio/frontend/src/features/model-picker/sharing/cached-target.ts b/studio/frontend/src/features/model-picker/sharing/cached-target.tsnew file mode 100644index 00000000000..e5dea363df8--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/cached-target.ts@@ -0,0 +1,302 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { authFetch } from "@/features/auth";+import { ggufVariantsQuery, runBoundedVariantsRequest } from "@/features/chat";+import {+ type GgufVariantsResponse,+ INVENTORY_FRESHNESS_WINDOW_MS,+ buildLocalInventoryRows,+ fetchInventorySource,+ ggufVariantsMatch,+ hubTokenHeader,+ isInventoryStampFresh,+ listGgufVariants,+ residentModelIdMatches,+ useDeviceInventoryStore,+ withAbort,+} from "@/features/hub";+import {+ isOllamaModelId,+ isStandaloneGgufPath,+} from "../model-config/model-identity";+import type { resolveRunConfigTarget } from "./target";++type RunConfigTarget = NonNullable<ReturnType<typeof resolveRunConfigTarget>>;+type ResolutionOptions = {+ hfToken?: string;+ inventoryVersion: number;+ signal: AbortSignal;+ checkLocalPath?: boolean;+};+type CachedVariantsResponse = Pick<+ GgufVariantsResponse,+ "variants" | "default_variant" | "dependencies_resolved"+> & {+ resolved_locally?: boolean;+};++export class RunConfigResolutionError extends Error {}++const notGgufMessage =+ "This model has no GGUF files. Shared run settings apply only to GGUF models.";++function readVariantsResponse(value: unknown): CachedVariantsResponse {+ if (!value || typeof value !== "object") {+ throw new Error("Invalid GGUF variants response.");+ }+ const response = value as Partial<CachedVariantsResponse>;+ if (+ !Array.isArray(response.variants) ||+ !response.variants.every(+ (variant) =>+ variant &&+ typeof variant === "object" &&+ typeof variant.filename === "string" &&+ variant.filename.length > 0 &&+ typeof variant.quant === "string" &&+ variant.quant.length > 0 &&+ typeof variant.size_bytes === "number" &&+ Number.isFinite(variant.size_bytes) &&+ variant.size_bytes >= 0 &&+ (variant.downloaded === undefined ||+ typeof variant.downloaded === "boolean") &&+ (variant.partial === undefined || typeof variant.partial === "boolean"),+ ) ||+ (response.default_variant != null &&+ typeof response.default_variant !== "string") ||+ (response.resolved_locally !== undefined &&+ typeof response.resolved_locally !== "boolean") ||+ (response.dependencies_resolved !== undefined &&+ typeof response.dependencies_resolved !== "boolean")+ ) {+ throw new Error("Invalid GGUF variants response.");+ }+ return {+ variants: response.variants,+ default_variant: response.default_variant ?? null,+ resolved_locally: response.resolved_locally === true,+ dependencies_resolved: response.dependencies_resolved === true,+ };+}++function listCachedVariants(+ id: string,+ localPath: string | undefined,+ options: { hfToken?: string; signal: AbortSignal },+): Promise<CachedVariantsResponse> {+ return runBoundedVariantsRequest(options.signal, async (signal) => {+ const query = ggufVariantsQuery(id, { localPath }, true);+ const response = await authFetch(`/api/hub/gguf-variants?${query}`, {+ headers: hubTokenHeader(options.hfToken),+ signal,+ });+ if (!response.ok) {+ throw new Error("Could not check cached GGUF variants.");+ }+ return readVariantsResponse(await response.json());+ });+}++function findCachedVariant(+ target: RunConfigTarget,+ listing: CachedVariantsResponse,+) {+ const requested = target.meta.ggufVariant ?? listing.default_variant;+ return listing.variants.find(+ (entry) =>+ entry.downloaded === true &&+ !entry.partial &&+ (ggufVariantsMatch(requested, entry.quant) ||+ requested === entry.filename),+ );+}++function withVariant(+ target: RunConfigTarget,+ variant: CachedVariantsResponse["variants"][number],+ meta: Partial<RunConfigTarget["meta"]>,+): RunConfigTarget {+ return {+ ...target,+ meta: {+ ...target.meta,+ ...meta,+ ggufVariant: variant.quant,+ ggufFilename: variant.filename,+ },+ };+}++function resolveLocalTarget(+ target: RunConfigTarget,+ listing: CachedVariantsResponse,+): RunConfigTarget {+ if (isStandaloneGgufPath(target.id)) {+ return {+ ...target,+ meta: { ...target.meta, isGguf: true, ggufVariant: undefined },+ };+ }+ if (listing.variants.length === 0) {+ throw new RunConfigResolutionError(notGgufMessage);+ }+ const variant = findCachedVariant(target, listing);+ if (!variant) {+ throw new RunConfigResolutionError(+ "The selected folder does not contain a complete copy of the requested GGUF variant.",+ );+ }+ return withVariant(target, variant, { isGguf: true, isDownloaded: true });+}++export async function resolveCachedRunConfigTarget(+ target: RunConfigTarget,+ options: ResolutionOptions,+): Promise<RunConfigTarget> {+ options.signal.throwIfAborted();+ if (target.meta.isDownloaded) {+ return target;+ }+ if (target.meta.source !== "hub") {+ if (isStandaloneGgufPath(target.id) || isOllamaModelId(target.id)) {+ return target;+ }+ const listing = await listCachedVariants(target.id, target.id, options);+ options.signal.throwIfAborted();+ return resolveLocalTarget(target, listing);+ }+ if (options.checkLocalPath) {+ const listing = await listCachedVariants(target.id, target.id, options);+ options.signal.throwIfAborted();+ if (listing.resolved_locally) {+ return resolveLocalTarget(+ {+ ...target,+ id: `./${target.id}`,+ meta: { ...target.meta, source: "local" },+ },+ listing,+ );+ }+ }+ return resolveHubRunConfigTarget(target, options);+}++async function resolveHubRunConfigTarget(+ target: RunConfigTarget,+ options: ResolutionOptions,+): Promise<RunConfigTarget> {+ const readInventory = <K extends "cachedGguf" | "localModels">(source: K) => {+ const current = useDeviceInventoryStore.getState()[source];+ return fetchInventorySource(source, {+ ...options,+ force:+ current.ready &&+ !current.loading &&+ !isInventoryStampFresh(+ current.refreshedAt,+ Date.now(),+ INVENTORY_FRESHNESS_WINDOW_MS,+ ),+ });+ };+ const [cached, local] = await withAbort(+ Promise.allSettled([+ readInventory("cachedGguf"),+ readInventory("localModels"),+ ]),+ options.signal,+ );+ options.signal.throwIfAborted();+ const candidates = [+ ...(cached.status === "fulfilled" ? cached.value : [])+ .filter(+ (row) => !row.partial && residentModelIdMatches(target.id, row.repo_id),+ )+ .map((row) => ({+ loadId: row.load_id || row.repo_id,+ localPath:+ row.load_id && row.load_id !== row.repo_id+ ? row.load_id+ : row.cache_path,+ })),+ ...buildLocalInventoryRows(local.status === "fulfilled" ? local.value : [])+ .filter(+ (row) =>+ !row.partial &&+ row.isGguf &&+ row.repoId !== null &&+ residentModelIdMatches(target.id, row.repoId),+ )+ .map((row) => ({+ loadId: row.loadId,+ localPath: row.loadId === row.repoId ? row.path : row.loadId,+ })),+ ];+ for (const candidate of candidates) {+ let listing: CachedVariantsResponse;+ try {+ listing = await listCachedVariants(+ candidate.loadId,+ candidate.localPath,+ options,+ );+ } catch {+ options.signal.throwIfAborted();+ continue;+ }+ const variant = findCachedVariant(target, listing);+ if (variant) {+ return withVariant(target, variant, {+ loadId: candidate.loadId,+ isDownloaded: true,+ });+ }+ }+ return resolveHubVariantTarget(target, options);+}++async function resolveHubVariantTarget(+ target: RunConfigTarget,+ options: ResolutionOptions,+): Promise<RunConfigTarget> {+ if (+ target.meta.ggufVariant &&+ !target.meta.ggufVariant.toLowerCase().endsWith(".gguf")+ ) {+ return target;+ }+ let listing: CachedVariantsResponse;+ try {+ listing = readVariantsResponse(+ await listGgufVariants(target.id, options.hfToken, {+ signal: options.signal,+ }),+ );+ } catch {+ options.signal.throwIfAborted();+ return target;+ }+ options.signal.throwIfAborted();+ if (listing.variants.length === 0 && listing.dependencies_resolved) {+ throw new RunConfigResolutionError(notGgufMessage);+ }+ const requested = target.meta.ggufVariant ?? listing.default_variant;+ const variant = listing.variants.find((entry) =>+ target.meta.ggufVariant+ ? requested === entry.filename+ : ggufVariantsMatch(requested, entry.quant),+ );+ if (!variant) {+ if (!listing.dependencies_resolved) {+ return target;+ }+ throw new RunConfigResolutionError(+ "The shared GGUF variant is unavailable for this model. Ask the sender for an updated link.",+ );+ }+ return withVariant(target, variant, {+ isDownloaded: variant.downloaded === true && !variant.partial,+ });+}diff --git a/studio/frontend/src/features/model-picker/sharing/config-controls.tsx b/studio/frontend/src/features/model-picker/sharing/config-controls.tsxnew file mode 100644index 00000000000..ecc9fa6e8e6--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/config-controls.tsx@@ -0,0 +1,119 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { LazyImportBoundary } from "@/components/lazy-import-boundary";+import { Button } from "@/components/ui/button";+import { toast } from "@/lib/toast";+import { type ComponentProps, Suspense, lazy, useLayoutEffect } from "react";+import type { ModelPickTarget } from "../components/model-selector/types";+import {+ isExtraArgsHydratedForDraft,+ modelConfigDraftKey,+} from "../model-config/model-config-draft";+import { runConfigInbox } from "./inbox";+import { isRunConfigVariantUnresolved } from "./target";++const SharedRunConfigActions = lazy(() =>+ import("./config-ui").then((module) => ({+ default: module.SharedRunConfigActions,+ })),+);++const ConfigReview = lazy(() =>+ import("./config-ui").then((module) => ({+ default: module.SharedRunConfigReview,+ })),+);++export function isRunConfigEditorChange(event: {+ currentTarget: Node;+ target: EventTarget;+}): boolean {+ return (+ event.target instanceof Node && event.currentTarget.contains(event.target)+ );+}++export function SharedRunConfigReview({+ target,+ ...props+}: ComponentProps<typeof ConfigReview> & { target: ModelPickTarget }) {+ return (+ <>+ {props.imported && (+ <LazyImportBoundary+ fallback={+ <p role="alert" className="mb-5 text-ui-12 text-muted-foreground">+ The link settings summary could not load. Reload Unsloth and+ reopen the link to review it.+ </p>+ }+ >+ <Suspense fallback={null}>+ <ConfigReview {...props} />+ </Suspense>+ </LazyImportBoundary>+ )}+ {isRunConfigVariantUnresolved(target) && (+ <p+ role="status"+ className="mb-5 border-b border-border pb-5 text-pretty text-ui-12 leading-relaxed text-muted-foreground"+ >+ The GGUF variant could not be resolved. You can edit and share these+ settings offline. Reopen the link when the Hugging Face model is+ accessible before loading. To keep any edits, copy a new link with+ Share first.+ </p>+ )}+ </>+ );+}++export function SharedRunConfigControls({+ isDiffusion,+ ...props+}: Omit<+ ComponentProps<typeof SharedRunConfigActions>,+ "hydrated" | "draftKey"+> & {+ isDiffusion: boolean;+}) {+ const { target, canImport } = props;+ const key = modelConfigDraftKey(+ target.configId ?? target.id,+ target.ggufVariant,+ );+ useLayoutEffect(() => {+ if (canImport) {+ return runConfigInbox.retainEditor(key, (request) => {+ toast.info("Run settings import cancelled", {+ id: request.id,+ description:+ "The editor closed before the settings were imported. Reopen the link to try again.",+ });+ });+ }+ }, [canImport, key]);+ const fallback = (+ <Button+ type="button"+ size="sm"+ variant="outline"+ className={props.className}+ disabled+ >+ Share+ </Button>+ );+ return (+ <LazyImportBoundary fallback={fallback}>+ <Suspense fallback={fallback}>+ <SharedRunConfigActions+ {...props}+ draftKey={key}+ hydrated={isDiffusion || isExtraArgsHydratedForDraft(key)}+ />+ </Suspense>+ </LazyImportBoundary>+ );+}diff --git a/studio/frontend/src/features/model-picker/sharing/config-ui.tsx b/studio/frontend/src/features/model-picker/sharing/config-ui.tsxnew file mode 100644index 00000000000..b0139d2ef7f--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/config-ui.tsx@@ -0,0 +1,193 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import { ChevronDown } from "lucide-react";+import { useEffect, useState, useSyncExternalStore } from "react";+import type { ModelPickTarget } from "../components/model-selector/types";+import type { PerModelConfig } from "../model-config/per-model-config";+import {+ SHARED_CONFIG_FIELDS,+ SHARED_CONFIG_KEYS,+ formatSharedConfigValue,+} from "./fields";+import { scheduleRunConfigImport } from "./import-config";+import { type RunConfigImport, runConfigInbox } from "./inbox";+import { ShareRunConfigDialog } from "./share-dialog";++export function SharedRunConfigActions({+ target,+ draftKey: key,+ config,+ ready,+ hydrated,+ canImport,+ disabled,+ className,+ onImport,+}: {+ target: ModelPickTarget;+ draftKey: string;+ config: PerModelConfig;+ ready: boolean;+ hydrated: boolean;+ canImport: boolean;+ disabled: boolean;+ className: string;+ onImport: (imported: RunConfigImport) => void;+}) {+ const [sharing, setSharing] = useState(false);+ const pending = useSyncExternalStore(+ runConfigInbox.subscribe,+ runConfigInbox.getSnapshot,+ );+ useEffect(+ () =>+ scheduleRunConfigImport({+ canImport,+ ready,+ pending,+ key,+ hydrated,+ onImport,+ }),+ [canImport, hydrated, key, onImport, pending, ready],+ );+ return (+ <>+ <Button+ type="button"+ size="sm"+ variant="outline"+ className={className}+ disabled={!ready || disabled}+ onClick={() => setSharing(true)}+ >+ Share+ </Button>+ {sharing && (+ <ShareRunConfigDialog+ target={target}+ config={config}+ onClose={() => setSharing(false)}+ />+ )}+ </>+ );+}++function reviewTitle(changed: boolean, model?: string, ggufVariant?: string) {+ if (changed) {+ return "Settings changed by link";+ }+ if (model) {+ return "Model selected by link";+ }+ return ggufVariant+ ? "GGUF variant selected by link"+ : "Link settings already match this editor";+}++function downloadNote(model?: string, ggufVariant?: string) {+ if (model) {+ return "If the model isn’t on this device, loading downloads it from Hugging Face.";+ }+ return ggufVariant+ ? "If this variant isn’t on this device, loading downloads it."+ : null;+}++function savedSettingsNote(remember: boolean, hasSavedSettings: boolean) {+ if (remember) {+ return hasSavedSettings+ ? "Loading replaces your saved settings for this model. Close without loading to keep them."+ : "Loading saves these settings for this model.";+ }+ return hasSavedSettings+ ? "Loading clears your saved settings for this model. Close without loading to keep them."+ : "To keep these settings for next time, tick “Remember for this model”.";+}++export function SharedRunConfigReview({+ imported,+ draftConfig,+ currentConfig,+ remember = false,+ hasSavedSettings = false,+}: {+ imported: RunConfigImport | null;+ draftConfig: PerModelConfig;+ currentConfig: PerModelConfig;+ remember?: boolean;+ hasSavedSettings?: boolean;+}) {+ if (!imported) {+ return null;+ }+ const { changes: config, model, ggufVariant } = imported;+ const keys = SHARED_CONFIG_KEYS.filter((key) => Object.hasOwn(config, key));+ if (+ keys.some(+ (key) => JSON.stringify(config[key]) !== JSON.stringify(draftConfig[key]),+ )+ ) {+ return null;+ }+ const selection = [model, ggufVariant].filter(Boolean).join(" · ");+ const download = downloadNote(model, ggufVariant);+ return (+ <details open={true} className="group mb-5 border-b border-border pb-5">+ <summary className="grid cursor-pointer list-none grid-cols-[minmax(0,1fr)_auto] items-center gap-x-3 rounded-md outline-none focus-visible:ring-2 focus-visible:ring-ring/60 focus-visible:ring-offset-2 focus-visible:ring-offset-background [&::-webkit-details-marker]:hidden">+ <span className="flex min-h-8 min-w-0 items-center gap-2">+ <span className="min-w-0 truncate text-ui-13 font-medium leading-[1.25] tracking-nav text-foreground">+ {reviewTitle(keys.length > 0, model, ggufVariant)}+ </span>+ {keys.length > 0 && (+ <span className="shrink-0 rounded-md bg-[rgb(0_0_0_/_calc(0.04*var(--contrast-wash-gain,1)))] px-1.5 py-0.5 text-ui-10 font-medium tabular-nums text-muted-foreground dark:bg-muted">+ {keys.length}+ </span>+ )}+ </span>+ <ChevronDown+ aria-hidden="true"+ className="size-3.5 shrink-0 -rotate-90 text-muted-foreground transition-transform duration-200 group-open:rotate-0 group-hover:text-foreground motion-reduce:transition-none"+ />+ {selection && (+ <span className="col-span-2 -mt-1 min-w-0 text-ui-11 text-muted-foreground [overflow-wrap:anywhere]">+ {selection}+ </span>+ )}+ </summary>+ <div className="mt-3 space-y-3">+ {keys.length > 0 && (+ <dl className="space-y-2">+ {keys.map((key) => (+ <div+ key={key}+ className="grid grid-cols-[auto_minmax(0,1fr)] items-baseline gap-x-4 gap-y-0.5"+ >+ <dt className="text-ui-12 text-muted-foreground">+ {SHARED_CONFIG_FIELDS[key].label}+ </dt>+ <dd className="min-w-0 whitespace-pre-wrap text-right text-ui-12 text-foreground [overflow-wrap:anywhere]">+ {formatSharedConfigValue(key, currentConfig)}+ </dd>+ {JSON.stringify(config[key]) !==+ JSON.stringify(currentConfig[key]) && (+ <dd className="col-span-2 min-w-0 whitespace-pre-wrap text-ui-11 leading-relaxed text-muted-foreground/80 [overflow-wrap:anywhere]">+ Requested {formatSharedConfigValue(key, config)}, adjusted+ for this device or model.+ </dd>+ )}+ </div>+ ))}+ </dl>+ )}+ <div className="space-y-1 text-pretty text-ui-12 leading-relaxed text-muted-foreground">+ {download && <p>{download}</p>}+ <p>{savedSettingsNote(remember, hasSavedSettings)}</p>+ </div>+ </div>+ </details>+ );+}diff --git a/studio/frontend/src/features/model-picker/sharing/extra-args.ts b/studio/frontend/src/features/model-picker/sharing/extra-args.tsnew file mode 100644index 00000000000..624fa9d372b--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/extra-args.ts@@ -0,0 +1,187 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ EXTRA_ARGS_MAX_BYTES,+ EXTRA_ARGS_MAX_TOKENS,+ diagnoseExtraArgs,+ extraArgFlagName,+ formatExtraArgs,+} from "../model-config/llama-extra-args";+import {+ CONTEXT_LENGTH_MIN,+ KV_CACHE_DTYPES,+ N_BATCH_MAX,+ N_BATCH_MIN,+} from "../model-config/per-model-config";++type ValueRule = (value: string) => boolean;+const decimal = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/;+const flagName = /^--?[A-Za-z][A-Za-z0-9_-]{0,63}$/;+const number =+ (min: number, max: number, integer = false): ValueRule =>+ (value) => {+ if (value.length > 24 || value !== value.trim() || !decimal.test(value)) {+ return false;+ }+ const parsed = Number(value);+ return (+ Number.isFinite(parsed) &&+ parsed >= min &&+ parsed <= max &&+ (!integer || (!value.includes(".") && Number.isSafeInteger(parsed)))+ );+ };+const choice =+ (values: readonly string[]): ValueRule =>+ (value) =>+ values.includes(value);+const threads = number(-1, 1024, true);+const context: ValueRule = (value) =>+ value === "0" || number(CONTEXT_LENGTH_MIN, 2_147_483_647)(value);+const batch: ValueRule = (value) => number(N_BATCH_MIN, N_BATCH_MAX)(value);+const layers = number(-1, 2_147_483_647);+const cache: ValueRule = (value) =>+ value === "f16" || KV_CACHE_DTYPES.some((dtype) => dtype === value);+const ratio = number(0, 1);+const tensorRatio = number(0, 1_000_000);++const sharePolicy: readonly [string, ValueRule | null][] = [+ ["--threads -t", threads],+ ["--threads-batch -tb", threads],+ ["--ctx-size -c", context],+ ["--batch-size -b", batch],+ ["--ubatch-size -ub", batch],+ ["--gpu-layers --n-gpu-layers -ngl", layers],+ ["--n-cpu-moe -ncmoe", number(0, 2_147_483_647)],+ ["--main-gpu -mg", number(0, 255, true)],+ ["--flash-attn -fa", choice(["on", "off", "auto"])],+ ["--cache-type-k -ctk", cache],+ ["--cache-type-v -ctv", cache],+ ["--split-mode -sm", choice(["none", "layer", "row", "tensor"])],+ [+ "--tensor-split -ts",+ (value) => {+ const ratios = value.split(",");+ return (+ ratios.length <= 256 &&+ ratios.every(tensorRatio) &&+ ratios.some((part) => Number(part) > 0)+ );+ },+ ],+ ["--rope-scaling", choice(["none", "linear", "yarn"])],+ ["--rope-scale", number(0.001, 1_000_000)],+ ["--rope-freq-base", number(0.001, 1_000_000_000)],+ ["--rope-freq-scale", number(0.001, 1_000_000)],+ ["--yarn-orig-ctx", (value) => context(value) && !value.includes(".")],+ ["--yarn-ext-factor", number(-1, 1_000_000)],+ ["--yarn-attn-factor", number(0, 1_000_000)],+ ["--yarn-beta-fast", number(0, 1_000_000)],+ ["--yarn-beta-slow", number(0, 1_000_000)],+ ["--seed -s", number(-1, 4_294_967_295, true)],+ ["--temp --temperature", number(0, 100)],+ ["--top-k", number(0, 1_000_000, true)],+ ["--top-p", ratio],+ ["--min-p", ratio],+ ["--repeat-last-n", number(-1, 1_000_000, true)],+ ["--repeat-penalty", number(0, 100)],+ ["--presence-penalty", number(-2, 2)],+ ["--frequency-penalty", number(-2, 2)],+ ["--no-warmup", null],+ ["--no-context-shift", null],+];++const sharedFlags = new Map(+ sharePolicy.flatMap(([spellings, permits]) => {+ const names = spellings.split(" ");+ return names.map(+ (name) => [name, { canonical: names[0], permits }] as const,+ );+ }),+);++function boundedTokens(value: unknown): value is string[] {+ if (!Array.isArray(value) || value.length > EXTRA_ARGS_MAX_TOKENS) {+ return false;+ }+ for (const token of value) {+ if (typeof token !== "string" || token.length > EXTRA_ARGS_MAX_BYTES) {+ return false;+ }+ }+ return true;+}++function upstreamError(value: string[]): string | null {+ return (+ diagnoseExtraArgs(formatExtraArgs(value), null).find(+ (diagnostic) => diagnostic.level === "error",+ )?.message ?? null+ );+}++function sharedValueError(+ flag: string,+ permits: ValueRule | null,+ token: string,+ tokens: Iterator<string, undefined>,+): string | null {+ if (token.includes("=")) {+ return permits === null+ ? `${flag} does not take a value.`+ : `Write ${flag} and its value as two arguments.`;+ }+ if (!flagName.test(token)) {+ return "Extra arguments contain an unexpected token.";+ }+ if (permits === null) {+ return null;+ }+ const argument = tokens.next().value;+ if (argument === undefined) {+ return `${flag} requires a value.`;+ }+ return permits(argument)+ ? null+ : `${flag} has an invalid or unsupported value.`;+}++function sharePolicyError(value: string[]): string | null {+ const seen = new Set<string>();+ const tokens = value[Symbol.iterator]();+ for (const token of tokens) {+ const flag = extraArgFlagName(token);+ const policy = flag === null ? undefined : sharedFlags.get(flag);+ if (!policy) {+ return flag !== null && flag === flag.trim() && flagName.test(flag)+ ? `${flag} is not supported in shared links.`+ : "Extra arguments contain an unexpected token.";+ }+ if (seen.has(policy.canonical)) {+ return `${policy.canonical} is specified more than once.`;+ }+ seen.add(policy.canonical);+ const issue = sharedValueError(+ policy.canonical,+ policy.permits,+ token,+ tokens,+ );+ if (issue !== null) {+ return issue;+ }+ }+ return null;+}++export function sharedExtraArgsError(value: unknown): string | null {+ if (!boundedTokens(value)) {+ return `Extra arguments must be a list of at most ${EXTRA_ARGS_MAX_TOKENS} text tokens, each at most ${EXTRA_ARGS_MAX_BYTES} characters.`;+ }+ return sharePolicyError(value) ?? upstreamError(value);+}++export function validSharedExtraArgs(value: unknown): value is string[] {+ return sharedExtraArgsError(value) === null;+}diff --git a/studio/frontend/src/features/model-picker/sharing/fields.ts b/studio/frontend/src/features/model-picker/sharing/fields.tsnew file mode 100644index 00000000000..d6c3f3b308a--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/fields.ts@@ -0,0 +1,187 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { formatExtraArgs } from "../model-config/llama-extra-args";+import {+ type PerModelConfig,+ CACHE_RAM_MAX,+ CACHE_RAM_MIN,+ CONTEXT_LENGTH_MIN,+ CTX_CHECKPOINTS_MAX,+ CTX_CHECKPOINTS_MIN,+ KV_CACHE_DTYPES,+ LOAD_MODES,+ N_BATCH_MAX,+ N_BATCH_MIN,+ N_PARALLEL_MAX,+ N_PARALLEL_MIN,+ SPECULATIVE_TYPES,+} from "../model-config/per-model-config";+import { validSharedExtraArgs } from "./extra-args";++type Validator = (value: unknown) => boolean;++const integer = (value: unknown, min: number, max: number): boolean =>+ typeof value === "number" &&+ Number.isSafeInteger(value) &&+ value >= min &&+ value <= max;+const nullable =+ (valid: Validator): Validator =>+ (value) =>+ value === null || valid(value);+const choice = (value: unknown, values: readonly unknown[]): boolean =>+ values.includes(value);+const boolean: Validator = (value) => typeof value === "boolean";++const gpuId: Validator = (value) => integer(value, 0, 255);+const cacheType = nullable(+ (value) => value === "f16" || choice(value, KV_CACHE_DTYPES),+);++export type SharedConfigKey = Exclude<+ keyof PerModelConfig,+ "chatTemplateOverride" | "tensorSplit" | "maxSeqLength" | "mlxKvQuant"+>;+type Field = { label: string; valid: Validator; error?: string };++export const SHARED_CONFIG_FIELDS: Record<SharedConfigKey, Field> = {+ customContextLength: {+ label: "Context length",+ valid: nullable((value) =>+ integer(value, CONTEXT_LENGTH_MIN, 2_147_483_647),+ ),+ },+ kvCacheDtype: { label: "KV cache type", valid: cacheType },+ speculativeType: {+ label: "Speculative decoding",+ valid: nullable((value) => choice(value, SPECULATIVE_TYPES)),+ },+ specDraftNMax: {+ label: "Draft tokens",+ valid: nullable((value) => integer(value, 1, 16)),+ },+ specDraftCacheDtype: { label: "Draft KV cache type", valid: cacheType },+ nParallel: {+ label: "Parallel slots",+ valid: nullable((value) => integer(value, N_PARALLEL_MIN, N_PARALLEL_MAX)),+ },+ reasoningBudget: {+ label: "Reasoning budget",+ valid: (value) => integer(value, -1, 2_147_483_647),+ },+ reasoningBudgetMessage: {+ label: "Reasoning budget message",+ valid: (value) => value === "",+ error:+ "Custom reasoning messages cannot be shared through links. Configure them locally instead.",+ },+ nBatch: {+ label: "Batch size",+ valid: nullable((value) => integer(value, N_BATCH_MIN, N_BATCH_MAX)),+ },+ nUbatch: {+ label: "Micro-batch size",+ valid: nullable((value) => integer(value, N_BATCH_MIN, N_BATCH_MAX)),+ },+ loadMode: {+ label: "Load mode",+ valid: nullable((value) => choice(value, LOAD_MODES)),+ },+ ctxCheckpoints: {+ label: "Context checkpoints",+ valid: nullable((value) =>+ integer(value, CTX_CHECKPOINTS_MIN, CTX_CHECKPOINTS_MAX),+ ),+ },+ cacheRam: {+ label: "Prompt cache RAM",+ valid: nullable((value) => integer(value, CACHE_RAM_MIN, CACHE_RAM_MAX)),+ },+ tensorParallel: { label: "Tensor parallel", valid: boolean },+ disableVision: { label: "Disable vision", valid: boolean },+ llamaExtraArgs: {+ label: "Extra arguments",+ valid: nullable(validSharedExtraArgs),+ error:+ "Shared extra arguments require supported inference options and valid values. File, network, tool and template options cannot be shared.",+ },+ gpuMemoryMode: {+ label: "GPU memory mode",+ valid: (value) => value === "auto" || value === "manual",+ },+ gpuLayers: {+ label: "GPU layers",+ valid: (value) => integer(value, -1, 2_147_483_647),+ },+ nCpuMoe: {+ label: "CPU MoE layers",+ valid: (value) => integer(value, 0, 2_147_483_647),+ },+ selectedGpuIds: {+ label: "GPU devices",+ valid: nullable(+ (value) =>+ Array.isArray(value) &&+ value.length > 0 &&+ value.length <= 256 &&+ value.every(gpuId) &&+ new Set(value).size === value.length,+ ),+ },+ selectedGpuIndexKind: {+ label: "GPU device index type",+ valid: nullable((value) => value === "physical" || value === "vulkan"),+ },+};++export const SHARED_CONFIG_KEYS = Object.keys(+ SHARED_CONFIG_FIELDS,+) as SharedConfigKey[];++export function isSharedConfigKey(key: string): key is SharedConfigKey {+ return Object.hasOwn(SHARED_CONFIG_FIELDS, key);+}++export function formatSharedConfigValue(+ key: SharedConfigKey,+ config: Partial<PerModelConfig>,+): string {+ if (key === "llamaExtraArgs") {+ return formatExtraArgs(config.llamaExtraArgs) || "No extra arguments";+ }+ const value = config[key];+ return value == null+ ? "Default"+ : typeof value === "string" && value !== ""+ ? value+ : JSON.stringify(value);+}++export function mergeSharedRunConfig(+ defaults: PerModelConfig,+ patch: Partial<PerModelConfig>,+): PerModelConfig {+ const provided = Object.fromEntries(+ SHARED_CONFIG_KEYS.filter((key) => Object.hasOwn(patch, key))+ .map((key) => [key, patch[key]] as const)+ .filter(([, value]) => value !== undefined)+ .map(([key, value]) => [key, Array.isArray(value) ? [...value] : value]),+ );+ const gpuSelectionChanged = (+ ["selectedGpuIds", "selectedGpuIndexKind"] as const+ ).some(+ (key) =>+ Object.hasOwn(provided, key) &&+ JSON.stringify(provided[key] ?? null) !==+ JSON.stringify(defaults[key] ?? null),+ );+ if (+ gpuSelectionChanged ||+ provided.gpuMemoryMode === "auto" ||+ provided.gpuLayers === -1+ ) {+ provided.tensorSplit = null;+ }+ return { ...defaults, ...provided };+}diff --git a/studio/frontend/src/features/model-picker/sharing/import-config.ts b/studio/frontend/src/features/model-picker/sharing/import-config.tsnew file mode 100644index 00000000000..019b4f1dbdc--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/import-config.ts@@ -0,0 +1,92 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { toast } from "@/lib/toast";+import {+ clearExtraArgsEditForDraft,+ markModelConfigDraftEdited,+ patchModelConfigDraft,+ readModelConfigDraft,+} from "../model-config/model-config-draft";+import { SHARED_CONFIG_KEYS, mergeSharedRunConfig } from "./fields";+import {+ type RunConfigImport,+ type RunConfigRequest,+ runConfigInbox,+} from "./inbox";++export function scheduleRunConfigImport({+ canImport,+ ready,+ pending,+ key,+ hydrated,+ onImport,+}: {+ canImport: boolean;+ ready: boolean;+ pending: RunConfigRequest | null;+ key: string;+ hydrated: boolean;+ onImport: (imported: RunConfigImport) => void;+}): (() => void) | undefined {+ if (+ !(canImport && ready && pending) ||+ pending.draftKey !== key ||+ !readModelConfigDraft(key)+ ) {+ return;+ }+ let cancelled = false;+ queueMicrotask(() => {+ const draft = readModelConfigDraft(key);+ if (cancelled || !draft || runConfigInbox.getSnapshot() !== pending) {+ return;+ }+ const ggufVariant = pending.value.ggufVariant+ ? pending.target?.meta.ggufVariant+ : undefined;+ if (Object.keys(pending.value.config).length === 0) {+ runConfigInbox.take(pending.id, key);+ if (pending.value.model || ggufVariant) {+ onImport({ changes: {}, model: pending.value.model, ggufVariant });+ }+ return;+ }+ if (!hydrated) {+ runConfigInbox.take(pending.id, key);+ toast.error("Could not import run settings", {+ id: pending.id,+ description:+ "Saved model settings are unavailable. Close the editor and reopen this link to retry.",+ });+ return;+ }+ const patch = runConfigInbox.take(pending.id, key);+ if (!patch) {+ return;+ }+ const merged = mergeSharedRunConfig(draft.config, patch);+ const changes = Object.fromEntries(+ SHARED_CONFIG_KEYS.filter(+ (field) =>+ JSON.stringify(draft.config[field]) !== JSON.stringify(merged[field]),+ ).map((field) => [field, merged[field]]),+ );+ if (Object.hasOwn(patch, "llamaExtraArgs")) {+ clearExtraArgsEditForDraft(key);+ }+ markModelConfigDraftEdited(key);+ patchModelConfigDraft(key, (current) =>+ mergeSharedRunConfig(current, patch),+ );+ onImport({ changes, model: pending.value.model, ggufVariant });+ toast.success("Settings imported from link", {+ id: pending.id,+ description: "Review before loading.",+ });+ });+ return () => {+ cancelled = true;+ };+}diff --git a/studio/frontend/src/features/model-picker/sharing/inbox.ts b/studio/frontend/src/features/model-picker/sharing/inbox.tsnew file mode 100644index 00000000000..472fca0d1d4--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/inbox.ts@@ -0,0 +1,134 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import type { ModelConfigHandoffRequest } from "../model-config/model-config-handoff";+import type { PerModelConfig } from "../model-config/per-model-config";+import type { SharedRunConfig } from "./links";++export type RunConfigImport = {+ changes: Partial<PerModelConfig>;+ model?: string;+ ggufVariant?: string;+};++export type RunConfigRequest = {+ id: string;+ value: SharedRunConfig;+ selectedModel?: string;+ target?: Pick<ModelConfigHandoffRequest, "id" | "meta">;+ draftKey?: string;+ replaceHistory?: boolean;+ newChatId?: ModelConfigHandoffRequest["newChatId"];+};++export function createRunConfigInbox() {+ let pending: RunConfigRequest | null = null;+ let requestId: string | null = null;+ const listeners = new Set<() => void>();+ const editors = new Map<string, number>();+ const editedDrafts = new Set<string>();+ const publish = (next: RunConfigRequest | null, id = next?.id ?? null) => {+ if (id !== requestId) {+ editedDrafts.clear();+ }+ requestId = id;+ pending = next;+ for (const listener of listeners) {+ listener();+ }+ };+ return {+ getSnapshot: () => pending,+ begin: (id: string) => publish(null, id),+ recordEdit: (draftKey: string) => {+ if (requestId !== null) editedDrafts.add(draftKey);+ },+ wasEdited: (draftKey: string) => editedDrafts.has(draftKey),+ subscribe: (listener: () => void) => {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ submit: (request: RunConfigRequest) => publish(request),+ retainEditor: (+ draftKey: string,+ onCancel?: (request: RunConfigRequest) => void,+ ) => {+ editors.set(draftKey, (editors.get(draftKey) ?? 0) + 1);+ let released = false;+ return () => {+ if (released) {+ return;+ }+ released = true;+ const remaining = (editors.get(draftKey) ?? 1) - 1;+ if (remaining > 0) {+ editors.set(draftKey, remaining);+ } else {+ editors.delete(draftKey);+ }+ const request = pending;+ queueMicrotask(() => {+ if (+ request &&+ pending === request &&+ !editors.has(draftKey) &&+ pending?.draftKey === draftKey+ ) {+ publish(null);+ if (Object.keys(request.value.config).length > 0) {+ onCancel?.(request);+ }+ }+ });+ };+ },+ bind: (id: string, draftKey: string) => {+ if (pending?.id === id) {+ publish({ ...pending, draftKey });+ }+ },+ clear: (id = requestId) => {+ if (requestId === id) {+ publish(null);+ }+ },+ take: (id: string, draftKey: string): Partial<PerModelConfig> | null => {+ if (pending?.id !== id || pending.draftKey !== draftKey) {+ return null;+ }+ const patch = pending.value.config;+ publish(null);+ return patch;+ },+ };+}++export const runConfigInbox = createRunConfigInbox();+export const MAX_RUN_CONFIG_URL_LENGTH = 16_384;+export const nativeRunAddress = /^unsloth:\/\/run\/?(?:\?|$)/i;+export const runConfigHash = /^#run(?:\?|$)/;++export function isRunConfigLink(raw: string): boolean {+ if (raw.length > MAX_RUN_CONFIG_URL_LENGTH) {+ const fragment = raw.indexOf("#");+ return (+ nativeRunAddress.test(raw) ||+ (/^https?:\/\//i.test(raw) &&+ fragment >= 0 &&+ (raw.slice(fragment, fragment + 5) === "#run?" ||+ raw.slice(fragment) === "#run"))+ );+ }+ try {+ const url = new URL(raw);+ return (+ (url.protocol === "unsloth:" && url.hostname.toLowerCase() === "run") ||+ ((url.protocol === "http:" || url.protocol === "https:") &&+ runConfigHash.test(url.hash))+ );+ } catch {+ return false;+ }+}diff --git a/studio/frontend/src/features/model-picker/sharing/index.ts b/studio/frontend/src/features/model-picker/sharing/index.tsnew file mode 100644index 00000000000..612ce4f2cbe--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/index.ts@@ -0,0 +1,15 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++export {+ SharedRunConfigControls,+ SharedRunConfigReview,+ isRunConfigEditorChange,+} from "./config-controls";+export { SharedRunConfigLinkHandler } from "./link-handler";+export {+ cancelRunConfigImportForEdit,+ receiveSharedRunConfigUrls,+} from "./receive-link";+export type { RunConfigImport } from "./inbox";+export { isRunConfigVariantUnresolved } from "./target";diff --git a/studio/frontend/src/features/model-picker/sharing/link-editor.tsx b/studio/frontend/src/features/model-picker/sharing/link-editor.tsxnew file mode 100644index 00000000000..6044a810ef9--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/link-editor.tsx@@ -0,0 +1,160 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import { Input } from "@/components/ui/input";+import { hasAuthToken, mustChangePassword } from "@/features/auth";+import {+ type ChatSearch,+ isExternalModelId,+ useChatRuntimeStore,+} from "@/features/chat";+import { useHfTokenStore, useInventoryVersion } from "@/features/hub";+import { useNavigate, useRouterState } from "@tanstack/react-router";+import { useEffect, useRef, useState } from "react";+import { type RunConfigRequest, runConfigInbox } from "./inbox";+import {+ type RunConfigNavigation,+ navigateRunConfig,+ openRunConfigTarget,+} from "./link-lifecycle";+import { isKnownNonGgufModel, isRunConfigModelInput } from "./target";++export function SharedRunConfigLinkEditor({+ pending,+ chatSearch,+}: { pending: RunConfigRequest; chatSearch: ChatSearch | null }) {+ const navigate = useNavigate();+ const location = useRouterState({ select: (state) => state.location });+ const routeReady = useRouterState({+ select: (state) =>+ !state.isLoading &&+ state.status === "idle" &&+ state.resolvedLocation?.href === state.location.href,+ });+ const [modelInput, setModelInput] = useState("");+ const navigation = useRef<RunConfigNavigation | null>(null);+ const hfToken = useHfTokenStore((state) => state.token) || undefined;+ const inventoryVersion = useInventoryVersion();+ const currentModel = useChatRuntimeStore((state) =>+ isExternalModelId(state.params.checkpoint) ||+ isKnownNonGgufModel(state.params.checkpoint, state)+ ? ""+ : state.params.checkpoint,+ );+ const settingsHydrated = useChatRuntimeStore(+ (state) => state.settingsHydrated,+ );+ const canOpen =+ hasAuthToken() &&+ !mustChangePassword() &&+ location.pathname !== "/login" &&+ location.pathname !== "/change-password";++ useEffect(() => {+ navigateRunConfig({+ pending,+ canOpen,+ settingsHydrated,+ currentModel,+ location,+ navigation,+ navigate,+ });+ }, [canOpen, currentModel, location, navigate, pending, settingsHydrated]);++ useEffect(+ () =>+ openRunConfigTarget({+ pending,+ chatSearch,+ canOpen,+ settingsHydrated,+ currentModel,+ location,+ routeReady,+ hfToken,+ inventoryVersion,+ }),+ [+ canOpen,+ chatSearch,+ currentModel,+ location,+ pending,+ settingsHydrated,+ routeReady,+ hfToken,+ inventoryVersion,+ ],+ );++ const model = modelInput.trim();+ const validModel = isRunConfigModelInput(model);+ const chooseModel =+ canOpen &&+ settingsHydrated &&+ !pending.draftKey &&+ !pending.selectedModel &&+ !pending.value.model &&+ !currentModel;+ return (+ <Dialog+ open={chooseModel}+ onOpenChange={(open) => {+ if (!open) {+ runConfigInbox.clear(pending.id);+ }+ }}+ >+ <DialogContent className="content-start gap-5">+ <DialogHeader>+ <DialogTitle>Choose a GGUF model</DialogTitle>+ <DialogDescription>+ This link contains settings without a model. Enter a Hugging Face+ GGUF model ID, a local GGUF path on the machine running Unsloth, or+ an Ollama reference to review the settings with that model.+ </DialogDescription>+ </DialogHeader>+ <form+ className="space-y-5"+ onSubmit={(event) => {+ event.preventDefault();+ if (validModel) {+ runConfigInbox.submit({ ...pending, selectedModel: model });+ setModelInput("");+ }+ }}+ >+ <div className="space-y-2">+ <label+ htmlFor="shared-run-model"+ className="block text-sm font-medium"+ >+ GGUF model ID or local path+ </label>+ <Input+ id="shared-run-model"+ autoComplete="off"+ placeholder="owner/model-GGUF or local GGUF path"+ value={modelInput}+ onChange={(event) => setModelInput(event.target.value)}+ />+ </div>+ <div className="flex justify-end">+ <Button type="submit" disabled={!validModel}>+ Open run settings+ </Button>+ </div>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/model-picker/sharing/link-handler.tsx b/studio/frontend/src/features/model-picker/sharing/link-handler.tsxnew file mode 100644index 00000000000..6cd813c4e37--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/link-handler.tsx@@ -0,0 +1,71 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ LazyImportBoundary,+ LazyImportFailure,+} from "@/components/lazy-import-boundary";+import type { ChatSearch } from "@/features/chat";+import {+ Suspense,+ lazy,+ useEffect,+ useState,+ useSyncExternalStore,+} from "react";+import { runConfigInbox } from "./inbox";+import {+ receiveStartupRunConfigUrl,+ subscribeRunConfigSession,+} from "./receive-link";++const SharedRunConfigLinkEditor = lazy(() =>+ import("./link-editor").then((module) => ({+ default: module.SharedRunConfigLinkEditor,+ })),+);++export function SharedRunConfigLinkHandler({+ chatSearch,+}: { chatSearch: ChatSearch | null }) {+ const pending = useSyncExternalStore(+ runConfigInbox.subscribe,+ runConfigInbox.getSnapshot,+ );+ const [, setAuthRevision] = useState(0);++ useEffect(() => {+ let active = true;+ queueMicrotask(() => {+ if (active) {+ void receiveStartupRunConfigUrl();+ }+ });+ const onAuth = () => setAuthRevision((revision) => revision + 1);+ const unsubscribe = subscribeRunConfigSession(onAuth);+ return () => {+ active = false;+ unsubscribe();+ };+ }, []);++ return pending ? (+ <LazyImportBoundary+ key={pending.id}+ fallback={+ <LazyImportFailure+ message="Shared run settings could not load. Reload Unsloth and reopen the link to try again."+ reloadLabel="Reload Unsloth"+ dismissLabel="Dismiss"+ onDismiss={() => runConfigInbox.clear(pending.id)}+ testId="shared-run-settings-unavailable"+ className="fixed bottom-4 right-4 z-50 max-w-sm rounded-lg border bg-background p-4"+ />+ }+ >+ <Suspense fallback={null}>+ <SharedRunConfigLinkEditor pending={pending} chatSearch={chatSearch} />+ </Suspense>+ </LazyImportBoundary>+ ) : null;+}diff --git a/studio/frontend/src/features/model-picker/sharing/link-lifecycle.ts b/studio/frontend/src/features/model-picker/sharing/link-lifecycle.tsnew file mode 100644index 00000000000..3ad4c0ae091--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/link-lifecycle.ts@@ -0,0 +1,219 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ type ChatSearch,+ clearNewChatDraft,+ useChatRuntimeStore,+} from "@/features/chat";+import { toast } from "@/lib/toast";+import { modelConfigDraftKey } from "../model-config/model-config-draft";+import {+ clearModelConfigHandoff,+ requestModelConfigHandoff,+} from "../model-config/model-config-handoff";+import {+ RunConfigResolutionError,+ resolveCachedRunConfigTarget,+} from "./cached-target";+import { type RunConfigRequest, runConfigInbox } from "./inbox";+import { cancelEditedRunConfigImport } from "./receive-link";+import { resolveRunConfigTarget } from "./target";++export type RunConfigNavigation = {+ id: string;+ from: string;+ started: boolean;+};+type LinkContext = {+ pending: RunConfigRequest | null;+ canOpen: boolean;+ settingsHydrated: boolean;+ currentModel: string;+ location: { href: string; pathname: string; searchStr: string };+};++const newChatId = (pending: RunConfigRequest) =>+ pending.newChatId === undefined ? pending.id : pending.newChatId;++function isOpenable(+ context: LinkContext,+): context is LinkContext & { pending: RunConfigRequest } {+ const { pending } = context;+ return Boolean(+ pending &&+ !pending.draftKey &&+ context.canOpen &&+ context.settingsHydrated &&+ runConfigInbox.getSnapshot() === pending &&+ (pending.selectedModel ?? pending.value.model ?? context.currentModel),+ );+}++function atRunConfigDestination(+ pending: RunConfigRequest,+ location: LinkContext["location"],+): boolean {+ const search = new URLSearchParams(location.searchStr);+ return (+ location.pathname === "/chat" &&+ !search.has("thread") &&+ !search.has("compare") &&+ !search.has("project") &&+ search.get("new") === newChatId(pending)+ );+}++export function navigateRunConfig(+ context: LinkContext & {+ navigation: { current: RunConfigNavigation | null };+ navigate: (options: {+ to: "/chat";+ search: { new?: string };+ replace: boolean;+ }) => Promise<unknown>;+ },+): void {+ if (!isOpenable(context)) {+ return;+ }+ const { pending, location, navigation, navigate } = context;+ const atDestination = atRunConfigDestination(pending, location);+ if (navigation.current?.id === pending.id) {+ if (atDestination) {+ navigation.current.from = location.href;+ } else if (location.href !== navigation.current.from) {+ runConfigInbox.clear(pending.id);+ }+ if (navigation.current.started || !pending.target) {+ return;+ }+ }+ navigation.current = {+ id: pending.id,+ from: location.href,+ started: Boolean(pending.target),+ };+ if (+ !pending.target ||+ atDestination ||+ runConfigInbox.getSnapshot() !== pending+ ) {+ return;+ }+ navigate({+ to: "/chat",+ search: { new: newChatId(pending) ?? undefined },+ replace: pending.replaceHistory === true,+ }).catch(() => {+ if (runConfigInbox.getSnapshot()?.id !== pending.id) {+ return;+ }+ clearModelConfigHandoff(pending.id);+ runConfigInbox.clear(pending.id);+ toast.error("Could not open the model’s run settings.");+ });+}++export function openRunConfigTarget(+ context: LinkContext & {+ chatSearch: ChatSearch | null;+ routeReady: boolean;+ hfToken?: string;+ inventoryVersion: number;+ },+): (() => void) | undefined {+ if (!isOpenable(context)) {+ return;+ }+ const { pending, chatSearch, location, routeReady, hfToken } = context;+ if (pending.target) {+ if (!routeReady || !atRunConfigDestination(pending, location)) {+ return;+ }+ if (pending.newChatId === undefined) {+ clearNewChatDraft();+ const runtime = useChatRuntimeStore.getState();+ runtime.setActiveThreadId(null);+ runtime.setActiveProjectId(null);+ runtime.setIncognito(false);+ }+ runConfigInbox.bind(+ pending.id,+ modelConfigDraftKey(pending.target.id, pending.target.meta.ggufVariant),+ );+ requestModelConfigHandoff({+ requestId: pending.id,+ ...(pending.newChatId !== undefined && { newChatId: pending.newChatId }),+ ...pending.target,+ displayName: pending.target.id,+ });+ return;+ }+ const runtime = useChatRuntimeStore.getState();+ const preserveDraft =+ chatSearch !== null &&+ !chatSearch.thread &&+ !chatSearch.compare &&+ !chatSearch.project;+ const target = resolveRunConfigTarget(+ pending.value,+ runtime,+ pending.selectedModel,+ );+ if (!target) {+ return;+ }+ if (!target.meta.isGguf) {+ runConfigInbox.clear(pending.id);+ toast.error(+ "Shared run settings apply only to GGUF models. Reopen the link and choose a GGUF model.",+ );+ return;+ }+ const controller = new AbortController();+ const loadingToast = toast.loading("Resolving shared model…");+ resolveCachedRunConfigTarget(target, {+ hfToken,+ inventoryVersion: context.inventoryVersion,+ signal: controller.signal,+ checkLocalPath: !pending.value.model || Boolean(pending.selectedModel),+ })+ .then((resolved) => {+ if (+ controller.signal.aborted ||+ runConfigInbox.getSnapshot() !== pending+ ) {+ return;+ }+ const key = modelConfigDraftKey(resolved.id, resolved.meta.ggufVariant);+ if (runConfigInbox.wasEdited(key)) {+ cancelEditedRunConfigImport(key);+ return;+ }+ runConfigInbox.submit({+ ...pending,+ target: resolved,+ ...(preserveDraft && { newChatId: chatSearch.new ?? null }),+ });+ })+ .catch((error: unknown) => {+ if (+ controller.signal.aborted ||+ runConfigInbox.getSnapshot() !== pending+ ) {+ return;+ }+ runConfigInbox.clear(pending.id);+ toast.error(+ error instanceof RunConfigResolutionError+ ? error.message+ : "Could not resolve the shared model. Reopen the link to try again.",+ );+ })+ .finally(() => toast.dismiss(loadingToast));+ return () => {+ controller.abort();+ toast.dismiss(loadingToast);+ };+}diff --git a/studio/frontend/src/features/model-picker/sharing/links.ts b/studio/frontend/src/features/model-picker/sharing/links.tsnew file mode 100644index 00000000000..69a593d113a--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/links.ts@@ -0,0 +1,228 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { isValidRepoId as isShareableModelId } from "@/features/deep-links";+import type { PerModelConfig } from "../model-config/per-model-config";+import {+ SHARED_CONFIG_FIELDS,+ SHARED_CONFIG_KEYS,+ type SharedConfigKey,+ isSharedConfigKey,+} from "./fields";+import {+ MAX_RUN_CONFIG_URL_LENGTH,+ isRunConfigLink,+ nativeRunAddress,+} from "./inbox";++export const DESKTOP_RUN_CONFIG_URL_WARNING_LENGTH = 2_083;+export type SharedRunConfig = {+ model?: string;+ ggufVariant?: string;+ config: Partial<PerModelConfig>;+};+export type RunConfigLinkResult =+ | { kind: "unrelated" }+ | { kind: "invalid"; error: string }+ | { kind: "valid"; value: SharedRunConfig };++const variantSegment = /^[A-Za-z0-9_][A-Za-z0-9._ -]*$/;+const windowsDevice = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9]) *(?:\.|$)/i;+const malformedEscape = /%(?![0-9a-f]{2})/i;+export { isShareableModelId };++function validVariant(value: string): boolean {+ return (+ value.length <= 512 &&+ value+ .split("/")+ .every(+ (part) =>+ part.length <= 255 &&+ variantSegment.test(part) &&+ !part.endsWith(".") &&+ !part.endsWith(" ") &&+ !windowsDevice.test(part),+ )+ );+}++function fieldError(key: SharedConfigKey): Error {+ const field = SHARED_CONFIG_FIELDS[key];+ return new Error(field.error ?? `The setting “${field.label}” is invalid.`);+}++function linkQuery(raw: string, url: URL, native: boolean): string {+ if (invalidUrlCharacters(raw)) {+ throw new Error("This link contains invalid URL characters.");+ }+ if (+ url.username ||+ url.password ||+ (native && (url.port || url.hash || !nativeRunAddress.test(raw)))+ ) {+ throw new Error("This run configuration link has an invalid address.");+ }+ const query = native ? url.search.slice(1) : url.hash.slice(5);+ if (malformedEscape.test(query)) {+ throw new Error("This run configuration link has invalid URL encoding.");+ }+ try {+ decodeURIComponent(query);+ } catch {+ throw new Error("This run configuration link has invalid text encoding.");+ }+ return query;+}++function readParameter(+ result: SharedRunConfig,+ key: string,+ value: string,+): void {+ if (key === "v") {+ if (value !== "1") {+ throw new Error(+ "This run configuration link uses an unsupported version.",+ );+ }+ } else if (key === "model") {+ if (!isShareableModelId(value)) {+ throw new Error("Use a Hugging Face model ID such as owner/model.");+ }+ result.model = value;+ } else if (key === "ggufVariant") {+ if (!validVariant(value)) {+ throw new Error("The GGUF variant is invalid.");+ }+ result.ggufVariant = value;+ } else if (isSharedConfigKey(key)) {+ const { valid } = SHARED_CONFIG_FIELDS[key];+ let decoded: unknown = value;+ try {+ decoded = valid(value) ? value : JSON.parse(value);+ } catch {+ throw fieldError(key);+ }+ if (!valid(decoded)) {+ throw fieldError(key);+ }+ Object.assign(result.config, { [key]: decoded });+ } else {+ throw new Error(+ "This run configuration link contains an unsupported setting.",+ );+ }+}++function parseParameters(query: string): SharedRunConfig {+ const seen = new Set<string>();+ const result: SharedRunConfig = { config: {} };+ for (const [key, value] of new URLSearchParams(query)) {+ if (seen.has(key)) {+ throw new Error(+ "This run configuration link contains a repeated setting.",+ );+ }+ seen.add(key);+ readParameter(result, key, value);+ }+ if (!seen.has("v")) {+ throw new Error("This run configuration link is missing its version.");+ }+ return result;+}++function invalidUrlCharacters(raw: string): boolean {+ for (const character of raw) {+ const code = character.codePointAt(0) ?? 0;+ if (+ code <= 32 ||+ (code >= 0x7f && code <= 0x9f) ||+ (code >= 0xd800 && code <= 0xdfff)+ ) {+ return true;+ }+ }+ return false;+}++export function parseRunConfigLink(raw: string): RunConfigLinkResult {+ if (!isRunConfigLink(raw)) {+ return { kind: "unrelated" };+ }+ if (raw.length > MAX_RUN_CONFIG_URL_LENGTH) {+ return {+ kind: "invalid",+ error: "This run configuration link is too long.",+ };+ }+ const url = new URL(raw);+ try {+ const query = linkQuery(raw, url, url.protocol === "unsloth:");+ return { kind: "valid", value: parseParameters(query) };+ } catch (error) {+ return {+ kind: "invalid",+ error:+ error instanceof Error+ ? error.message+ : "Invalid run configuration link.",+ };+ }+}++function encodeParameters(value: SharedRunConfig): URLSearchParams {+ const params = new URLSearchParams({ v: "1" });+ if (value.model !== undefined) {+ params.set("model", value.model);+ }+ if (value.ggufVariant !== undefined) {+ params.set("ggufVariant", value.ggufVariant);+ }+ for (const key of SHARED_CONFIG_KEYS) {+ const field = value.config[key];+ if (field !== undefined) {+ if (!SHARED_CONFIG_FIELDS[key].valid(field)) {+ throw fieldError(key);+ }+ params.set(+ key,+ typeof field === "string" ? field : JSON.stringify(field),+ );+ }+ }+ return params;+}++function browserLink(params: URLSearchParams, address: string): string {+ const url = new URL(address);+ if (+ (url.protocol !== "http:" && url.protocol !== "https:") ||+ url.username ||+ url.password+ ) {+ throw new Error("Use an HTTP or HTTPS Unsloth Web address.");+ }+ url.pathname = "/chat";+ // Force document navigation from /chat: link intake ignores same-document hash changes.+ url.search = "?run=1";+ url.hash = `run?${params}`;+ return url.href;+}++export function createRunConfigLink(+ value: SharedRunConfig,+ browserUrl?: string,+): string {+ const params = encodeParameters(value);+ const link =+ browserUrl === undefined+ ? `unsloth://run?${params}`+ : browserLink(params, browserUrl);+ const parsed = parseRunConfigLink(link);+ if (parsed.kind === "invalid") {+ throw new Error(parsed.error);+ }+ return link;+}diff --git a/studio/frontend/src/features/model-picker/sharing/receive-link.ts b/studio/frontend/src/features/model-picker/sharing/receive-link.tsnew file mode 100644index 00000000000..c0af4ac6143--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/receive-link.ts@@ -0,0 +1,215 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ AUTH_SESSION_CLEARED_EVENT,+ AUTH_SESSION_STORED_EVENT,+ hasAuthToken,+} from "@/features/auth";+import {+ createDeepLinkIntentGate,+ parseUnslothDeepLink,+} from "@/features/deep-links";+import { isTauri } from "@/lib/api-base";+import { toast } from "@/lib/toast";+import {+ markModelConfigDraftEdited,+ modelConfigDraftKey,+} from "../model-config/model-config-draft";+import {+ clearModelConfigHandoff,+ createModelConfigHandoffRequestId,+} from "../model-config/model-config-handoff";+import { isRunConfigLink, runConfigHash, runConfigInbox } from "./inbox";++const acceptNativeIntent = createDeepLinkIntentGate(2_000);+const nativeScheme = /^unsloth:/i;+// Only the startup URL is eligible; hash changes during this session are ignored.+let startupUrl = typeof window === "undefined" ? "" : window.location.href;+const handledNativeUrlKey = "unsloth.run-config-native-handled.v1";+let handledNativeUrl = readHandledNativeUrl();+let awaitingLogin = false;+let intakeRevision = 0;++function readHandledNativeUrl(): string | null {+ try {+ return sessionStorage.getItem(handledNativeUrlKey);+ } catch {+ return null;+ }+}++function saveHandledNativeUrl(): void {+ try {+ if (handledNativeUrl) {+ sessionStorage.setItem(handledNativeUrlKey, handledNativeUrl);+ }+ } catch {+ return;+ }+}++export function subscribeRunConfigSession(onChange: () => void): () => void {+ const onCleared = () => {+ startupUrl = "";+ acceptNativeIntent.clear();+ if (!awaitingLogin) {+ const pending = runConfigInbox.getSnapshot();+ clearPendingImport();+ if (pending) {+ toast.info("Run settings import cancelled", {+ description:+ "Your session ended before the settings were imported. Reopen the link to try again.",+ });+ }+ }+ onChange();+ };+ const onStored = () => {+ saveHandledNativeUrl();+ awaitingLogin = false;+ onChange();+ };+ const unsubscribe = runConfigInbox.subscribe(() => {+ const pending = runConfigInbox.getSnapshot();+ if (!pending || pending.draftKey) {+ awaitingLogin = false;+ }+ });+ window.addEventListener(AUTH_SESSION_CLEARED_EVENT, onCleared);+ window.addEventListener(AUTH_SESSION_STORED_EVENT, onStored);+ return () => {+ unsubscribe();+ window.removeEventListener(AUTH_SESSION_CLEARED_EVENT, onCleared);+ window.removeEventListener(AUTH_SESSION_STORED_EVENT, onStored);+ };+}++function clearPendingImport() {+ intakeRevision += 1;+ awaitingLogin = false;+ const pending = runConfigInbox.getSnapshot();+ if (pending) {+ clearModelConfigHandoff(pending.id);+ }+ runConfigInbox.clear();+}++export function cancelRunConfigImportForEdit(draftKey: string): void {+ runConfigInbox.recordEdit(draftKey);+ const pending = runConfigInbox.getSnapshot();+ const targetKey = pending?.target+ ? modelConfigDraftKey(pending.target.id, pending.target.meta.ggufVariant)+ : undefined;+ if (pending?.draftKey !== draftKey && targetKey !== draftKey) {+ return;+ }+ cancelEditedRunConfigImport(draftKey);+}++export function cancelEditedRunConfigImport(draftKey: string): void {+ const pending = runConfigInbox.getSnapshot();+ if (!pending) return;+ clearPendingImport();+ if (Object.keys(pending.value.config).length > 0) {+ markModelConfigDraftEdited(draftKey);+ toast.info("Run settings import cancelled", {+ description:+ "Your newer edits were kept. Reopen the link to import its settings.",+ });+ }+}++async function receiveRunConfigUrl(+ url: string,+ replaceHistory = false,+): Promise<void> {+ startupUrl = "";+ clearPendingImport();+ const revision = intakeRevision;+ const id = createModelConfigHandoffRequestId();+ runConfigInbox.begin(id);+ awaitingLogin = !hasAuthToken();+ try {+ const { parseRunConfigLink } = await import("./links");+ if (revision !== intakeRevision) {+ return;+ }+ const parsed = parseRunConfigLink(url);+ if (parsed.kind === "valid") {+ runConfigInbox.submit({ id, value: parsed.value, replaceHistory });+ return;+ }+ clearPendingImport();+ if (parsed.kind === "invalid") {+ toast.error("Could not open shared run settings", {+ description: parsed.error,+ });+ }+ } catch {+ if (revision !== intakeRevision) {+ return;+ }+ clearPendingImport();+ acceptNativeIntent.clear();+ toast.error("Could not open shared run settings", {+ description: "Reopen the link to try again.",+ });+ }+}++export async function receiveStartupRunConfigUrl(): Promise<void> {+ const initial = startupUrl;+ startupUrl = "";+ if (!initial) {+ return;+ }+ if (!isTauri && isRunConfigLink(initial)) {+ const url = new URL(window.location.href);+ if (+ runConfigHash.test(url.hash) &&+ new URLSearchParams(url.hash.slice(4)).toString() ===+ new URLSearchParams(new URL(initial).hash.slice(4)).toString()+ ) {+ if (url.searchParams.get("run") === "1") {+ url.searchParams.delete("run");+ }+ url.hash = "";+ window.history.replaceState(window.history.state, "", url.href);+ }+ await receiveRunConfigUrl(initial, true);+ }+}++export function receiveSharedRunConfigUrls(+ urls: string[],+ source: "startup" | "event" = "event",+): boolean | "ignored" {+ for (let index = urls.length - 1; index >= 0; index -= 1) {+ const url = urls[index];+ if (!nativeScheme.test(url)) {+ continue;+ }+ const candidate = isRunConfigLink(url);+ if (!candidate && parseUnslothDeepLink(url)) {+ startupUrl = "";+ clearPendingImport();+ acceptNativeIntent.clear();+ return false;+ }+ if (!candidate) {+ continue;+ }+ if (source === "startup" && handledNativeUrl === url) {+ return "ignored";+ }+ handledNativeUrl = url;+ saveHandledNativeUrl();+ if (acceptNativeIntent(url) === null) {+ return true;+ }+ void receiveRunConfigUrl(url);+ return true;+ }+ return false;+}diff --git a/studio/frontend/src/features/model-picker/sharing/share-dialog.tsx b/studio/frontend/src/features/model-picker/sharing/share-dialog.tsxnew file mode 100644index 00000000000..7c3b77601e4--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/share-dialog.tsx@@ -0,0 +1,368 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { Button } from "@/components/ui/button";+import { Checkbox } from "@/components/ui/checkbox";+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from "@/components/ui/dialog";+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from "@/components/ui/select";+import { Textarea } from "@/components/ui/textarea";+import { isTauri } from "@/lib/api-base";+import { copyToClipboard } from "@/lib/copy-to-clipboard";+import { toast } from "@/lib/toast";+import { useId, useMemo, useState } from "react";+import type { ModelPickTarget } from "../components/model-selector/types";+import {+ DEFAULT_PER_MODEL_CONFIG,+ type PerModelConfig,+} from "../model-config/per-model-config";+import { sharedExtraArgsError } from "./extra-args";+import {+ SHARED_CONFIG_FIELDS,+ SHARED_CONFIG_KEYS,+ type SharedConfigKey,+ formatSharedConfigValue,+} from "./fields";+import {+ DESKTOP_RUN_CONFIG_URL_WARNING_LENGTH,+ type SharedRunConfig,+ createRunConfigLink,+ isShareableModelId,+} from "./links";++const SHARING_DEFAULTS: PerModelConfig = {+ ...DEFAULT_PER_MODEL_CONFIG,+ gpuMemoryMode: "auto",+ gpuLayers: -1,+ nCpuMoe: 0,+ selectedGpuIds: null,+ selectedGpuIndexKind: null,+};++const loopbackHostname = /^(?:localhost|127(?:\.\d{1,3}){3}|\[::1\])$/;++function linkPreview(value: SharedRunConfig, destination: string) {+ try {+ return {+ link: createRunConfigLink(+ value,+ destination === "browser" ? window.location.href : undefined,+ ),+ error: "",+ };+ } catch (cause) {+ return {+ link: "",+ error:+ cause instanceof Error ? cause.message : "Could not create this link.",+ };+ }+}++export function ShareRunConfigDialog({+ target,+ config: sourceConfig,+ onClose,+}: {+ target: ModelPickTarget;+ config: PerModelConfig;+ onClose: () => void;+}) {+ const id = useId();+ const config = useMemo(+ () => ({+ ...sourceConfig,+ llamaExtraArgs: sourceConfig.llamaExtraArgs ?? null,+ }),+ [sourceConfig],+ );+ const model = target.configId ?? target.id;+ const shareableModel = isShareableModelId(model);+ const fields = useMemo(+ () =>+ SHARED_CONFIG_KEYS.filter((key) => config[key] !== undefined).map(+ (key) => {+ const error =+ key === "llamaExtraArgs" && config[key] !== null+ ? sharedExtraArgsError(config[key])+ : SHARED_CONFIG_FIELDS[key].valid(config[key])+ ? null+ : (SHARED_CONFIG_FIELDS[key].error ??+ "This value cannot be shared.");+ const detail =+ error === null+ ? formatSharedConfigValue(key, config)+ : key === "llamaExtraArgs"+ ? `Excluded: ${error} Edit Extra Arguments in Run settings to share them.`+ : error;+ return { key, valid: error === null, detail };+ },+ ),+ [config],+ );+ const [includeModel, setIncludeModel] = useState(shareableModel);+ const [includeVariant, setIncludeVariant] = useState(+ shareableModel && Boolean(target.ggufVariant),+ );+ const [destination, setDestination] = useState(() =>+ !isTauri && loopbackHostname.test(window.location.hostname)+ ? "browser"+ : "desktop",+ );+ const [selected, setSelected] = useState<Set<SharedConfigKey>>(+ () =>+ new Set(+ fields+ .filter(+ ({ key, valid }) =>+ valid &&+ (key === "llamaExtraArgs"+ ? (config.llamaExtraArgs?.length ?? 0) > 0+ : JSON.stringify(config[key]) !==+ JSON.stringify(SHARING_DEFAULTS[key])),+ )+ .map(({ key }) => key),+ ),+ );+ const [copying, setCopying] = useState(false);+ const { link, error } = useMemo(+ () =>+ linkPreview(+ {+ ...(includeModel ? { model } : {}),+ ...(includeVariant && target.ggufVariant+ ? { ggufVariant: target.ggufVariant }+ : {}),+ config: Object.fromEntries(+ [...selected].map((key) => [key, config[key]]),+ ),+ },+ destination,+ ),+ [+ config,+ selected,+ includeModel,+ model,+ includeVariant,+ target.ggufVariant,+ destination,+ ],+ );+ const choice = (+ key: string,+ label: string,+ checked: boolean,+ change: (checked: boolean) => void,+ detail?: string,+ disabled = false,+ ) => (+ <div key={key}>+ <div className="flex min-h-8 items-center gap-3">+ <Checkbox+ id={`${id}-${key}`}+ aria-describedby={+ detail !== undefined ? `${id}-${key}-detail` : undefined+ }+ checked={checked}+ disabled={disabled}+ onCheckedChange={(value) => change(value === true)}+ />+ <label+ htmlFor={`${id}-${key}`}+ className={`flex min-w-0 flex-1 items-baseline justify-between gap-4 text-ui-13 ${disabled ? "cursor-not-allowed text-muted-foreground" : "cursor-pointer text-foreground"}`}+ >+ <span className="shrink-0">{label}</span>+ {detail !== undefined && !disabled && (+ <span+ id={`${id}-${key}-detail`}+ aria-hidden={true}+ title={detail}+ className="min-w-0 truncate text-ui-12 text-muted-foreground"+ >+ {detail}+ </span>+ )}+ </label>+ </div>+ {detail !== undefined && disabled && (+ <p+ id={`${id}-${key}-detail`}+ className="pb-2 pl-7 text-ui-12 leading-snug text-muted-foreground"+ >+ {detail}+ </p>+ )}+ </div>+ );+ return (+ <Dialog+ open={true}+ onOpenChange={(open) => {+ if (!open) {+ onClose();+ }+ }}+ >+ <DialogContent className="grid-cols-1 grid-rows-[auto_minmax(0,1fr)_auto] gap-5 sm:max-w-xl">+ <DialogHeader>+ <DialogTitle>Share run settings</DialogTitle>+ <DialogDescription>+ Choose what to include. Omitted settings use the recipient’s+ existing defaults. Opening a link shows the settings before running.+ </DialogDescription>+ </DialogHeader>+ <div className="@container flex min-h-0 flex-col border-y border-border/60">+ <div className="border-b border-border/60 py-2">+ {shareableModel ? (+ choice("model", "Model", includeModel, setIncludeModel, model)+ ) : (+ <p className="py-1.5 text-ui-12 leading-snug text-muted-foreground">+ This model uses a local path. The recipient can choose their own+ model.+ </p>+ )}+ {target.ggufVariant &&+ choice(+ "variant",+ "GGUF variant",+ includeVariant,+ setIncludeVariant,+ target.ggufVariant,+ )}+ </div>+ <div className="hover-scrollbar -mr-7 min-h-0 flex-1 overflow-y-auto py-2 sm:max-h-75">+ <div className="w-[100cqw]">+ {fields.map(({ key, valid, detail }) =>+ choice(+ key,+ SHARED_CONFIG_FIELDS[key].label,+ selected.has(key),+ (checked) =>+ setSelected(+ (current) =>+ new Set(+ checked+ ? [...current, key]+ : [...current].filter((item) => item !== key),+ ),+ ),+ detail,+ !valid,+ ),+ )}+ </div>+ </div>+ </div>+ <div className="space-y-4">+ <div className="space-y-1.5">+ <div className="flex min-h-9 items-center justify-between gap-4">+ {isTauri ? (+ <>+ <span className="text-ui-13 font-medium">Open in</span>+ <span className="text-ui-13 text-muted-foreground">+ Desktop+ </span>+ </>+ ) : (+ <>+ <label+ htmlFor={`${id}-destination`}+ className="text-ui-13 font-medium"+ >+ Open in+ </label>+ <Select value={destination} onValueChange={setDestination}>+ <SelectTrigger id={`${id}-destination`} className="w-32">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="desktop">Desktop</SelectItem>+ <SelectItem value="browser">Web</SelectItem>+ </SelectContent>+ </Select>+ </>+ )}+ </div>+ <p className="text-ui-12 leading-snug text-muted-foreground">+ {destination === "browser"+ ? "This link contains your Unsloth Web address. Recipients need access to that address. A localhost address opens Unsloth Web on their own computer."+ : "The recipient needs Unsloth Desktop installed."}+ </p>+ </div>+ <div className="space-y-1.5">+ <div className="flex items-center gap-2">+ <label+ htmlFor={`${id}-link`}+ className="flex h-9 min-w-0 flex-1 cursor-text items-center rounded-full border border-border bg-background px-3.5 transition-colors focus-within:border-ring dark:border-transparent dark:bg-[rgb(255_255_255_/_calc(0.06*var(--contrast-wash-gain,1)))] dark:focus-within:bg-[rgb(255_255_255_/_calc(0.12*var(--contrast-wash-gain,1)))]"+ >+ <span className="sr-only">Shareable link</span>+ <Textarea+ id={`${id}-link`}+ readOnly={true}+ value={link}+ rows={1}+ fieldSizing="fixed"+ onKeyUp={(event) => {+ if (event.key === "Tab") {+ event.currentTarget.select();+ }+ }}+ className="no-scrollbar! min-h-0 flex-1 overflow-x-auto overflow-y-hidden whitespace-pre rounded-none border-0 bg-transparent p-0 py-1 font-mono text-ui-12 leading-4 text-muted-foreground md:text-ui-12 dark:bg-transparent dark:focus-visible:bg-transparent"+ />+ </label>+ <Button+ className="shrink-0 px-4"+ disabled={!link || copying}+ onClick={async () => {+ setCopying(true);+ try {+ if (await copyToClipboard(link)) {+ toast.success("Run settings link copied");+ } else {+ toast.error(+ "Could not copy the link. Select and copy it from the link field.",+ );+ }+ } finally {+ setCopying(false);+ }+ }}+ >+ Copy link+ </Button>+ </div>+ {error && (+ <p role="alert" className="text-ui-12 text-destructive">+ {error}+ </p>+ )}+ {destination === "desktop" &&+ link.length > DESKTOP_RUN_CONFIG_URL_WARNING_LENGTH && (+ <output className="block text-ui-12 text-amber-700 dark:text-amber-300">+ Long Desktop links may not open on Windows. Include fewer+ settings{!isTauri && " or open in Web"}.+ </output>+ )}+ <p className="text-ui-12 leading-snug text-muted-foreground">+ Anyone with the link can read the included settings. Custom text,+ template code and file, network or tool arguments cannot be+ shared.+ </p>+ </div>+ </div>+ </DialogContent>+ </Dialog>+ );+}diff --git a/studio/frontend/src/features/model-picker/sharing/target.ts b/studio/frontend/src/features/model-picker/sharing/target.tsnew file mode 100644index 00000000000..e6436f97e0e--- /dev/null+++ b/studio/frontend/src/features/model-picker/sharing/target.ts@@ -0,0 +1,132 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import {+ type ChatLoraSummary,+ type ChatModelSummary,+ isExternalModelId,+} from "@/features/chat";+import { isValidRepoId as isShareableModelId } from "@/features/deep-links";+import { looksLikeLocalPath } from "@/lib/local-path";+import type { ModelPickTarget } from "../components/model-selector/types";+import type { ModelConfigHandoffRequest } from "../model-config/model-config-handoff";+import {+ ggufVariantsMatch,+ isOllamaModelId,+ isStandaloneGgufPath,+ residentModelIdMatches,+} from "../model-config/model-identity";+import type { SharedRunConfig } from "./links";++const invalidCharacters = /[\p{Cc}\p{Cs}]/u;++export function isRunConfigModelInput(model: string): boolean {+ return (+ model.length > 0 &&+ model === model.trim() &&+ !invalidCharacters.test(model) &&+ !model.includes("://") &&+ (!model.includes(":") ||+ looksLikeLocalPath(model) ||+ isStandaloneGgufPath(model) ||+ isOllamaModelId(model))+ );+}++type ModelSelection = {+ params: { checkpoint: string };+ activeGgufVariant: string | null;+ loadedIsGguf: boolean | null;+ activeNativePathToken: string | null;+ activeLoadId: string | null;+ models: readonly Pick<ChatModelSummary, "id" | "isGguf" | "isLora">[];+ loras: readonly Pick<ChatLoraSummary, "id" | "exportType">[];+};++function knownModel(id: string, selection: ModelSelection) {+ const sameModel = residentModelIdMatches(id, selection.params.checkpoint);+ const model = selection.models.find((entry) =>+ residentModelIdMatches(id, entry.id),+ );+ const lora = selection.loras.find((entry) =>+ residentModelIdMatches(id, entry.id),+ );+ return {+ sameModel,+ model,+ lora,+ isGguf:+ (sameModel ? selection.loadedIsGguf : null) ??+ model?.isGguf ??+ (lora?.exportType ? lora.exportType === "gguf" : undefined),+ };+}++export function isKnownNonGgufModel(+ id: string,+ selection: ModelSelection,+): boolean {+ return (+ id !== "" &&+ !isStandaloneGgufPath(id) &&+ knownModel(id, selection).isGguf === false+ );+}++export function resolveRunConfigTarget(+ value: SharedRunConfig,+ selection: ModelSelection,+ selectedModel?: string,+): Pick<ModelConfigHandoffRequest, "id" | "meta"> | null {+ const id = selectedModel ?? value.model ?? selection.params.checkpoint;+ if (!id || isExternalModelId(id)) {+ return null;+ }+ const {+ sameModel,+ model,+ lora,+ isGguf: knownFormat,+ } = knownModel(id, selection);+ const singleFile =+ isStandaloneGgufPath(id) || (Boolean(selectedModel) && isOllamaModelId(id));+ const isGguf = singleFile || Boolean(value.model) || knownFormat !== false;+ const ggufVariant =+ isGguf && !singleFile+ ? (value.ggufVariant ??+ (sameModel ? selection.activeGgufVariant : null) ??+ undefined)+ : undefined;+ const sameArtifact =+ sameModel &&+ selection.loadedIsGguf === isGguf &&+ (isStandaloneGgufPath(id) ||+ ggufVariantsMatch(ggufVariant, selection.activeGgufVariant));+ return {+ id,+ meta: {+ source: isShareableModelId(id) ? "hub" : "local",+ isLora: model?.isLora ?? lora?.exportType === "lora",+ isGguf,+ ggufVariant,+ ...(sameArtifact+ ? {+ loadId: selection.activeLoadId ?? selection.params.checkpoint,+ isDownloaded: true,+ }+ : {}),+ ...(sameArtifact && isGguf && selection.activeNativePathToken+ ? { nativePathToken: selection.activeNativePathToken }+ : {}),+ },+ };+}++export function isRunConfigVariantUnresolved(target: ModelPickTarget): boolean {+ return (+ target.meta.source === "hub" &&+ target.isGguf &&+ !target.meta.isDownloaded &&+ (!target.ggufVariant || target.ggufVariant.toLowerCase().endsWith(".gguf"))+ );+}diff --git a/studio/frontend/tests/helpers/sharing-links.ts b/studio/frontend/tests/helpers/sharing-links.tsnew file mode 100644index 00000000000..1b6c1669414--- /dev/null+++ b/studio/frontend/tests/helpers/sharing-links.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { isValidRepoId } from "../../src/features/deep-links/parse-deep-link.ts";+import * as fields from "../../src/features/model-picker/sharing/fields.ts";+import * as inbox from "../../src/features/model-picker/sharing/inbox.ts";+import type * as Links from "../../src/features/model-picker/sharing/links.ts";+import { loadWithStubs } from "./module-stubs.ts";++export const { createRunConfigLink, parseRunConfigLink, isShareableModelId } =+ loadWithStubs<typeof Links>(+ new URL(+ "../../src/features/model-picker/sharing/links.ts",+ import.meta.url,+ ),+ {+ "@/features/deep-links": { isValidRepoId },+ "./fields": fields,+ "./inbox": inbox,+ },+ );diff --git a/studio/frontend/tests/helpers/sharing-receiver.ts b/studio/frontend/tests/helpers/sharing-receiver.tsnew file mode 100644index 00000000000..448904e5153--- /dev/null+++ b/studio/frontend/tests/helpers/sharing-receiver.ts@@ -0,0 +1,70 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import * as events from "../../src/features/auth/session-events.ts";+import { createDeepLinkIntentGate } from "../../src/features/deep-links/deep-link-intent.ts";+import { parseUnslothDeepLink } from "../../src/features/deep-links/parse-deep-link.ts";+import type * as Drafts from "../../src/features/model-picker/model-config/model-config-draft.ts";+import { modelConfigDraftKey } from "../../src/features/model-picker/model-config/model-config-draft.ts";+import * as inboxModule from "../../src/features/model-picker/sharing/inbox.ts";+import type * as Receiver from "../../src/features/model-picker/sharing/receive-link.ts";+import { loadWithStubs } from "./module-stubs.ts";+import * as links from "./sharing-links.ts";++export const settle = () =>+ new Promise<void>((resolve) => setImmediate(resolve));++export function receiverHarness({+ desktop = false,+ signedIn = () => true,+ loadParser = () => links,+ errors = [],+ notices = [],+ cleared = [],+ drafts = { markModelConfigDraftEdited: () => undefined, modelConfigDraftKey },+}: {+ desktop?: boolean;+ signedIn?: () => boolean;+ loadParser?: () => typeof links | Promise<typeof links>;+ errors?: string[];+ notices?: { message: string; description?: string }[];+ cleared?: string[];+ drafts?: Pick<+ typeof Drafts,+ "markModelConfigDraftEdited" | "modelConfigDraftKey"+ >;+} = {}) {+ const inbox = inboxModule.createRunConfigInbox();+ let nextId = 0;+ const receiver = loadWithStubs<typeof Receiver>(+ new URL(+ "../../src/features/model-picker/sharing/receive-link.ts",+ import.meta.url,+ ),+ {+ "@/lib/api-base": { isTauri: desktop },+ "@/lib/toast": {+ toast: {+ error: (message: string) => errors.push(message),+ info: (message: string, options?: { description?: string }) =>+ notices.push({ message, description: options?.description }),+ },+ },+ "@/features/auth": { ...events, hasAuthToken: signedIn },+ "@/features/deep-links": {+ createDeepLinkIntentGate,+ parseUnslothDeepLink,+ },+ "../model-config/model-config-draft": drafts,+ "../model-config/model-config-handoff": {+ clearModelConfigHandoff: (id: string) => cleared.push(id),+ createModelConfigHandoffRequestId: () => `request-${++nextId}`,+ },+ "./inbox": { ...inboxModule, runConfigInbox: inbox },+ get "./links"() {+ return loadParser();+ },+ },+ );+ return { receiver, inbox, errors, notices, cleared };+}diff --git a/studio/frontend/tests/helpers/sharing-target.ts b/studio/frontend/tests/helpers/sharing-target.tsnew file mode 100644index 00000000000..69b3d112d12--- /dev/null+++ b/studio/frontend/tests/helpers/sharing-target.ts@@ -0,0 +1,24 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import { isExternalModelId } from "../../src/features/chat/external-providers.ts";+import { isValidRepoId } from "../../src/features/deep-links/parse-deep-link.ts";+import * as identity from "../../src/features/model-picker/model-config/model-identity.ts";+import type * as Target from "../../src/features/model-picker/sharing/target.ts";+import * as localPath from "../../src/lib/local-path.ts";+import { loadWithStubs } from "./module-stubs.ts";++export const {+ isKnownNonGgufModel,+ isRunConfigModelInput,+ isRunConfigVariantUnresolved,+ resolveRunConfigTarget,+} = loadWithStubs<typeof Target>(+ new URL("../../src/features/model-picker/sharing/target.ts", import.meta.url),+ {+ "@/features/chat": { isExternalModelId },+ "@/lib/local-path": localPath,+ "../model-config/model-identity": identity,+ "@/features/deep-links": { isValidRepoId },+ },+);diff --git a/studio/frontend/tests/share-run-configs.cached-target.test.ts b/studio/frontend/tests/share-run-configs.cached-target.test.tsnew file mode 100644index 00000000000..5dfc57e682b--- /dev/null+++ b/studio/frontend/tests/share-run-configs.cached-target.test.ts@@ -0,0 +1,659 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test, { type TestContext } from "node:test";+import type { GgufVariantDetail } from "../src/features/hub/inventory/api.ts";+import type * as CachedTarget from "../src/features/model-picker/sharing/cached-target.ts";+import type * as ImportConfig from "../src/features/model-picker/sharing/import-config.ts";+import type { RunConfigImport } from "../src/features/model-picker/sharing/inbox.ts";+import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++registerBundlerResolver();+installLocalStorageFake();+const identity = await import(+ "../src/features/model-picker/model-config/model-identity.ts"+);+const variantsRequest = await import(+ "../src/features/chat/api/gguf-variants-request.ts"+);+const abortSignals = await import("../src/features/hub/lib/abort-signals.ts");+const freshness = await import(+ "../src/features/hub/inventory/inventory-freshness.ts"+);+const hubIds = await import("../src/features/hub/lib/model-identity.ts");+const { hubTokenHeader } = await import(+ "../src/features/hub/lib/hub-token-header.ts"+);+const { buildLocalInventoryRows } = await import(+ "../src/features/hub/inventory/view-models.ts"+);+const { modelConfigTarget } = await import(+ "../src/features/model-picker/model-config/model-config-handoff.ts"+);+const { wantsDownloadManagerStaging } = await import(+ "../src/features/chat/utils/model-download-staging.ts"+);+const {+ isRunConfigModelInput,+ isRunConfigVariantUnresolved,+ resolveRunConfigTarget,+} = await import("./helpers/sharing-target.ts");++type Target = NonNullable<ReturnType<typeof resolveRunConfigTarget>>;+type Resolve = typeof resolveRunConfigTarget;+const model = "owner/Model-GGUF";+const noGguf =+ "This model has no GGUF files. Shared run settings apply only to GGUF models.";+const empty = { models: [], loras: [], activeNativePathToken: null };+const selection = {+ ...{ ...empty, params: { checkpoint: "" } },+ ...{ activeGgufVariant: null, activeLoadId: null, loadedIsGguf: null },+};+const quant: GgufVariantDetail = {+ quant: "Q4_K_M",+ filename: "model-Q4_K_M.gguf",+ size_bytes: 1024,+ downloaded: true,+};+const q8 = { ...quant, quant: "Q8_0", filename: "model-Q8_0.gguf" };+const remote = { ...quant, downloaded: false };+const partial = { ...quant, partial: true };+const pick = (+ id?: string,+ value: Parameters<Resolve>[0] = { config: {} },+ from: Parameters<Resolve>[1] = selection,+) => {+ const resolved = resolveRunConfigTarget(value, from, id);+ assert.ok(resolved);+ return resolved;+};+const target = pick(undefined, { model, ggufVariant: "Q4_K_M", config: {} });+const withVariant = (ggufVariant?: string) => ({+ ...target,+ meta: { ...target.meta, ggufVariant },+});+const row = (load_id?: string, extra = {}) => ({+ repo_id: model,+ size_bytes: 1024,+ ...(load_id && { load_id }),+ ...extra,+});+const localPath = "/models/local.gguf";+const localRow = (source: string, extra = {}) => ({+ ...{ id: localPath, path: localPath, model_id: model, source },+ ...{ model_format: "gguf", display_name: "Local", ...extra },+});+const meta = (r: Target, ...keys: (keyof Target["meta"])[]) =>+ keys.map((key) => r.meta[key]);+const handoff = (r: Target) => {+ const next = modelConfigTarget(r.id, r.meta);+ return [next.id, next.ggufVariant, next.meta.ggufFilename];+};+const staged = (r: Target) =>+ wantsDownloadManagerStaging({ id: r.id, ...r.meta });+const unresolved = (r: Target) =>+ isRunConfigVariantUnresolved(modelConfigTarget(r.id, r.meta));+const noInventory = ["cachedGguf", "localModels"];+const defaults = {+ cachedGguf: [] as object[],+ localModels: [] as object[],+ variants: [quant] as GgufVariantDetail[],+ hubVariants: [remote] as GgufVariantDetail[],+ defaultVariant: undefined as string | null | undefined,+ hubMetadataAvailable: true,+ listings: undefined as Record<string, GgufVariantDetail[]> | undefined,+ sourceErrors: [] as string[],+ listingErrors: [] as string[],+ ...{ delayMs: 0, inventoryDelayMs: 0, status: 200 },+ ...{ checkLocalPath: false, resolvedLocally: false, hubError: false },+ localResponse: undefined as unknown,+};++function harness(options: Partial<typeof defaults> = {}) {+ const o = { ...defaults, ...options };+ const scans: string[] = [];+ const requests: string[][] = [];+ const hubRequests: unknown[][] = [];+ const delay = (ms: number) =>+ ms && new Promise((resolve) => setTimeout(resolve, ms));+ const module = loadWithStubs<typeof CachedTarget>(+ new URL(+ "../src/features/model-picker/sharing/cached-target.ts",+ import.meta.url,+ ),+ {+ "@/features/auth": {+ authFetch: async (url: string) => {+ await delay(o.delayMs);+ const query = new URL(url, "http://localhost").searchParams;+ const [repo, ...rest] = ["repo_id", "local_path", "offline"].map(+ (key) => `${query.get(key)}`,+ );+ requests.push([repo, ...rest]);+ if (o.listingErrors.includes(repo)) throw new Error("unavailable");+ const listed = o.listings ? (o.listings[repo] ?? []) : o.variants;+ const body =+ "localResponse" in options+ ? o.localResponse+ : {+ variants: listed,+ default_variant: listed[0]?.quant,+ resolved_locally: o.resolvedLocally,+ };+ return new Response(JSON.stringify(body), { status: o.status });+ },+ },+ "@/features/hub": {+ ...{ ...freshness, ...abortSignals, ...hubIds, hubTokenHeader },+ buildLocalInventoryRows,+ listGgufVariants: async (+ repoId: string,+ hfToken?: string,+ init?: { signal?: AbortSignal },+ ) => {+ hubRequests.push([repoId, hfToken, init?.signal]);+ await delay(o.delayMs);+ if (o.hubError) throw new Error("Hub listing unavailable");+ return {+ variants: o.hubVariants,+ default_variant:+ "defaultVariant" in options+ ? o.defaultVariant+ : o.hubVariants[0]?.quant,+ dependencies_resolved: o.hubMetadataAvailable,+ };+ },+ useDeviceInventoryStore: {+ getState: () => {+ const idle = { ready: false, loading: false, refreshedAt: null };+ return { cachedGguf: idle, localModels: idle };+ },+ },+ fetchInventorySource: async (source: "cachedGguf" | "localModels") => {+ scans.push(source);+ await delay(o.inventoryDelayMs);+ if (o.sourceErrors.includes(source)) throw new Error("unavailable");+ return o[source];+ },+ },+ "@/features/chat": variantsRequest,+ "../model-config/model-identity": identity,+ },+ );+ return {+ Resolution: module.RunConfigResolutionError,+ ...{ scans, requests, hubRequests },+ resolve: (input: Target = target, signal = new AbortController().signal) =>+ module.resolveCachedRunConfigTarget(input, {+ inventoryVersion: 0,+ signal,+ checkLocalPath: o.checkLocalPath,+ }),+ };+}++test("local paths resolve offline, before any inventory scan or Hub lookup", async () => {+ for (const [id, checkLocalPath, variants] of [+ ["models/my-native-model", true, []],+ ["models/my-quantized-model", true, [quant]],+ ["models/model.gguf", true, [quant]],+ ["C:\\Models\\quantized-qwen", false, [quant]],+ ["checkpoint-500", false, []],+ ] as [string, boolean, GgufVariantDetail[]][]) {+ assert.equal(isRunConfigModelInput(id), true);+ const app = harness({+ ...{ sourceErrors: noInventory, hubError: true, variants },+ ...{ checkLocalPath, resolvedLocally: checkLocalPath },+ });+ const input = pick(id);+ if (variants.length === 0) {+ await assert.rejects(app.resolve(input), {+ constructor: app.Resolution,+ message: noGguf,+ });+ } else {+ const resolved = await app.resolve(input);+ const local = checkLocalPath ? `./${id}` : id;+ const file = id.endsWith(".gguf");+ assert.deepEqual(+ [resolved.id, ...meta(resolved, "source", "isGguf", "isDownloaded")],+ [local, "local", true, file ? undefined : true],+ );+ assert.deepEqual(+ handoff(resolved),+ file ? [local, null, undefined] : [local, quant.quant, quant.filename],+ );+ assert.equal(staged(resolved), false);+ }+ assert.deepEqual(+ [app.scans, app.hubRequests, app.requests],+ [[], [], [[id, id, "true"]]],+ );+ }+});++test("local files and Ollama references need no lookup; failed local checks never guess", async () => {+ const id = "/Users/test/Models/model.gguf";+ const file = harness({ sourceErrors: noInventory });+ const value = { config: {}, ggufVariant: "Q4_K_M" };+ const resolved = await file.resolve(pick(id, value));+ assert.deepEqual(+ [resolved.id, ...meta(resolved, "isGguf", "ggufVariant", "source")],+ [id, true, undefined, "local"],+ );+ assert.equal(staged(resolved), false);+ assert.deepEqual([file.scans, file.requests, file.hubRequests], [[], [], []]);+ for (const [id, checkLocalPath] of [+ ["models/qwen", true],+ ["/models/qwen", false],+ ] as const) {+ const app = harness({ checkLocalPath, status: 503 });+ await assert.rejects(app.resolve(pick(id)), /Could not check cached GGUF/);+ assert.deepEqual([app.scans, app.hubRequests], [[], []]);+ }+});++test("recipient-selected Hub IDs keep cached, uncached and non-GGUF outcomes after the local check", async () => {+ for (const cached of [false, true]) {+ const app = harness({+ checkLocalPath: true,+ cachedGguf: cached ? [row("/cache/model")] : [],+ });+ const value = { config: {}, ggufVariant: quant.quant };+ const resolved = await app.resolve(pick(model, value));+ assert.deepEqual(+ [resolved.id, ...meta(resolved, "source"), staged(resolved)],+ [model, "hub", !cached],+ );+ assert.deepEqual([app.scans, app.hubRequests], [noInventory, []]);+ }+ const input = pick("owner/native");+ const none = { checkLocalPath: true, variants: [], hubVariants: [] };+ const app = harness(none);+ await assert.rejects(app.resolve(input), {+ constructor: app.Resolution,+ message: noGguf,+ });+ assert.equal(app.hubRequests.length, 1);+ const offline = harness({ ...none, hubMetadataAvailable: false });+ assert.equal(await offline.resolve(input), input);+});++test("cached and active GGUF copies bypass staging and keep their exact load path", async () => {+ const loadId = "/cache/models--owner--Model-GGUF/snapshots/pinned";+ const app = harness({+ cachedGguf: [row(loadId, { repo_id: model.toLowerCase() })],+ });+ const resolved = await app.resolve();+ assert.equal(staged(resolved), false);+ assert.deepEqual(handoff(resolved), [loadId, quant.quant, quant.filename]);+ assert.deepEqual(+ [app.requests, app.hubRequests],+ [[[loadId, loadId, "true"]], []],+ );+ for (const [checkpoint, activeLoadId] of [+ [loadId, null],+ [model, "/secondary/pinned"],+ ] as const) {+ for (const explicit of [undefined, model]) {+ const loaded = {+ ...{ ...empty, params: { checkpoint }, activeLoadId },+ ...{ loadedIsGguf: true, activeGgufVariant: "Q4_K_M" },+ };+ const idle = harness({ sourceErrors: noInventory });+ const value = { model: explicit, config: {} };+ const kept = await idle.resolve(pick(undefined, value, loaded));+ assert.equal(handoff(kept)[0], activeLoadId ?? checkpoint);+ assert.equal(staged(kept), false);+ assert.deepEqual([idle.scans, idle.requests], [[], []]);+ const moved = { ...loaded, activeNativePathToken: "local-only" };+ const other = pick(undefined, { ...value, ggufVariant: "Q8_0" }, moved);+ const inherited = meta(+ other,+ "loadId",+ "nativePathToken",+ "isDownloaded",+ );+ assert.deepEqual(inherited, [undefined, undefined, undefined]);+ }+ }+});++test("inventory candidates are checked one by one for a complete copy", async () => {+ const cachedGguf = [row("/cache/missing"), row("/cache/available")];+ const listings = { "/cache/missing": [], "/cache/available": [quant] };+ const skipped = await harness({ cachedGguf, listings }).resolve();+ assert.deepEqual(meta(skipped, "loadId", "isDownloaded"), [+ "/cache/available",+ true,+ ]);+ const listingErrors = ["/cache/missing"];+ const failed = await harness({ cachedGguf, listingErrors }).resolve();+ assert.equal(failed.meta.loadId, "/cache/available");+ const legacy = localRow("hf_cache", { model_format: undefined });+ const local = await harness({ localModels: [legacy] }).resolve();+ assert.deepEqual(meta(local, "loadId", "isDownloaded"), [localPath, true]);+ for (const source of noInventory) {+ const app = harness({+ sourceErrors: [source],+ cachedGguf: [row("/cache/pinned")],+ localModels: [+ localRow("hf_cache", { id: model, load_id: "/local", path: "/local" }),+ ],+ });+ assert.equal(+ (await app.resolve()).meta.loadId,+ source === "localModels" ? "/cache/pinned" : "/local",+ );+ }+});++test("unrelated, incomplete, non-cache or unmatched inventory keeps the Hub target for staging", async () => {+ for (const variants of [[q8], [remote], [partial], []]) {+ const app = harness({ cachedGguf: [row("/cache/pinned")], variants });+ const resolved = await app.resolve();+ assert.equal(resolved, target);+ assert.equal(staged(resolved), true);+ }+ for (const options of [+ { cachedGguf: [row(undefined, { repo_id: "other/model" })] },+ { cachedGguf: [row(undefined, { partial: true })] },+ { localModels: [localRow("custom", { id: model, load_id: "/local" })] },+ { sourceErrors: noInventory },+ ]) {+ const app = harness(options);+ assert.equal(await app.resolve(), target);+ assert.deepEqual(+ [app.scans, app.requests, app.hubRequests],+ [noInventory, [], []],+ );+ }+ assert.equal(target.meta.isDownloaded, undefined);+});++test("Hub lookups resolve the exact file or the default, or keep an unloadable review", async () => {+ const chosen = {+ ...remote,+ quant: "chosen/Q4_K_M",+ filename: "chosen/m.gguf",+ };+ const input = withVariant(chosen.filename);+ const offline = await harness({ hubError: true }).resolve(input);+ assert.equal(offline, input);+ assert.equal(unresolved(offline), true);+ const hub = await harness({ hubVariants: [chosen] }).resolve(input);+ assert.deepEqual(handoff(hub), [model, chosen.quant, chosen.filename]);+ assert.equal(unresolved(hub), false);+ const hubVariants = [remote, { ...q8, downloaded: false }];+ const fallback = harness({ hubVariants, defaultVariant: "Q8_0" });+ const picked = await fallback.resolve(withVariant(undefined));+ assert.deepEqual(+ meta(picked, "ggufVariant", "ggufFilename", "isDownloaded"),+ ["Q8_0", q8.filename, false],+ );+ for (const variant of [chosen.filename, undefined]) {+ const missing = harness({ hubVariants: [q8], defaultVariant: "Q4_K_M" });+ await assert.rejects(missing.resolve(withVariant(variant)), {+ constructor: missing.Resolution,+ message:+ "The shared GGUF variant is unavailable for this model. Ask the sender for an updated link.",+ });+ }+});++test("cancellation cannot produce a handoff, even mid lookup", async (t) => {+ t.mock.timers.enable({ apis: ["setTimeout"] });+ for (const hubError of [false, true]) {+ const slow = harness({ delayMs: 1_000, hubError });+ const abort = new AbortController();+ const pending = slow.resolve(withVariant(quant.filename), abort.signal);+ await new Promise<void>((resolve) => setImmediate(resolve));+ assert.equal(slow.hubRequests[0][2], abort.signal);+ abort.abort();+ t.mock.timers.tick(1_000);+ await assert.rejects(pending, { name: "AbortError" });+ }+ const budgets = harness({+ ...{ delayMs: 20_000, inventoryDelayMs: 20_000 },+ cachedGguf: [row("/cache/missing"), row("/cache/available")],+ listings: { "/cache/missing": [], "/cache/available": [quant] },+ });+ const pending = budgets.resolve();+ for (let step = 0; step < 3; step += 1) {+ t.mock.timers.tick(20_000);+ await new Promise<void>((resolve) => setImmediate(resolve));+ }+ assert.equal((await pending).meta.loadId, "/cache/available");+});++test("malformed variant responses cannot mark a model downloaded or redirect a local path to the Hub", async () => {+ const bad = (field: object) => ({ variants: [{ ...quant, ...field }] });+ for (const response of [+ null,+ {},+ { variants: {} },+ { variants: [null] },+ ...[{ filename: 1 }, { filename: "" }, { quant: null }].map(bad),+ ...[{ quant: "" }, { size_bytes: -1 }, { size_bytes: "1024" }].map(bad),+ ...[{ downloaded: "true" }, { partial: "false" }].map(bad),+ { variants: [quant], default_variant: {} },+ { variants: [quant], resolved_locally: "true" },+ { variants: [quant], dependencies_resolved: "false" },+ ]) {+ const local = harness({ localResponse: response, checkLocalPath: true });+ await assert.rejects(+ local.resolve(pick("./models/native")),+ /Invalid GGUF variants response/,+ );+ assert.deepEqual([local.hubRequests, local.scans], [[], []]);+ }+});++const drafts = await import(+ "../src/features/model-picker/model-config/model-config-draft.ts"+);+const { DEFAULT_PER_MODEL_CONFIG } = await import(+ "../src/features/model-picker/model-config/per-model-config.ts"+);+const fields = await import("../src/features/model-picker/sharing/fields.ts");+const inboxModule = await import(+ "../src/features/model-picker/sharing/inbox.ts"+);+const { parseRunConfigLink } = await import("./helpers/sharing-links.ts");+type Config = typeof DEFAULT_PER_MODEL_CONFIG;+let sequence = 0;+const settle = () => Promise.resolve();+const n3 = { nParallel: 3 };++function importHarness(+ t: TestContext,+ patch: Partial<Config> = n3,+ ggufVariant: string | null = "Q4_K_M",+ value: { model?: string; ggufVariant?: string } = {},+) {+ const id = `owner/model-${++sequence}`;+ const key = drafts.modelConfigDraftKey(id, ggufVariant);+ const inbox = inboxModule.createRunConfigInbox();+ const imports: unknown[][] = [];+ const toasts: string[] = [];+ const releaseDraft = drafts.retainModelConfigDraft(key);+ t.after(releaseDraft);+ const args = { maxSeqLength: 4096, customContextLength: 4096 };+ const warm = ["--no-warmup"];+ const config = { ...DEFAULT_PER_MODEL_CONFIG, ...args, llamaExtraArgs: warm };+ drafts.primeModelConfigDraft(key, { config, remembered: true }, "none");+ const meta = { source: "hub" as const, isLora: false, isGguf: true };+ inbox.submit({+ id: "import",+ draftKey: key,+ value: { ...value, config: patch },+ target: { id, meta: { ...meta, ggufVariant: ggufVariant ?? undefined } },+ });+ const { scheduleRunConfigImport: schedule } = loadWithStubs<+ typeof ImportConfig+ >(+ new URL(+ "../src/features/model-picker/sharing/import-config.ts",+ import.meta.url,+ ),+ {+ "@/lib/toast": {+ toast: {+ error: () => toasts.push("error"),+ success: () => toasts.push("success"),+ },+ },+ "../model-config/model-config-draft": drafts,+ "./fields": fields,+ "./inbox": { ...inboxModule, runConfigInbox: inbox },+ },+ );+ const options = {+ ...{ key, canImport: true, ready: true, hydrated: true },+ pending: inbox.getSnapshot(),+ onImport: ({ changes, model, ggufVariant }: RunConfigImport) =>+ imports.push([changes, model, ggufVariant]),+ };+ const draft = () => drafts.readModelConfigDraft(key);+ const edited = () => drafts.isModelConfigDraftEdited(key);+ const count = (kind: string) => toasts.filter((k) => k === kind).length;+ return {+ ...{ inbox, key, imports, options, draft, edited, count },+ ...{ releaseDraft, schedule },+ async run(overrides: Partial<typeof options> = {}) {+ const cancel = schedule({ ...options, ...overrides });+ await settle();+ return cancel;+ },+ };+}++test("imports report changes, the linked model and only variants retained by target resolution", async (t) => {+ const m = "owner/model";+ // [settings, link variant, resolved variant, link model, reported variant; "none" = no report]+ for (const [patch, requested, resolved, model, reported] of [+ [{}, "Q8_0", "Q8_0", undefined, "Q8_0"],+ [{}, "model-Q8_0.gguf", "Q8_0", undefined, "Q8_0"],+ [{}, undefined, "Q4_K_M", undefined, "none"],+ [{}, undefined, "Q4_K_M", m, undefined],+ [n3, undefined, "Q8_0", undefined, undefined],+ [n3, "Q8_0", null, undefined, undefined],+ [n3, "Q8_0", "Q8_0", m, "Q8_0"],+ ] as const) {+ const value = { model, ggufVariant: requested };+ const app = importHarness(t, patch, resolved, value);+ const before = app.draft();+ await app.run();+ assert.equal(app.inbox.getSnapshot(), null);+ const expected = reported === "none" ? [] : [[patch, model, reported]];+ assert.deepEqual(app.imports, expected);+ const settingsOnly = Object.keys(patch).length === 0;+ assert.equal(app.draft() === before, settingsOnly);+ assert.equal(app.edited(), !settingsOnly);+ assert.equal(app.count("success"), settingsOnly ? 0 : 1);+ }+});++test("a shared context imports without touching the pinned sequence length", async (t) => {+ for (const customContextLength of [8192, null]) {+ const link = `unsloth://run?v=1&customContextLength=${customContextLength}`;+ const parsed = parseRunConfigLink(link);+ assert.ok(parsed.kind === "valid");+ const app = importHarness(t, parsed.value.config);+ await app.run();+ const config = app.draft()?.config;+ assert.equal(config?.customContextLength, customContextLength);+ assert.equal(config?.maxSeqLength, 4096);+ assert.deepEqual(app.imports[0][0], { customContextLength });+ }+});++test("Strict Mode cleanup leaves the request for the surviving editor and applies once", async (t) => {+ const app = importHarness(t);+ const firstHost = app.inbox.retainEditor(app.key);+ app.schedule(app.options)?.();+ firstHost();+ t.after(app.inbox.retainEditor(app.key));+ app.schedule(app.options);+ await app.run();+ assert.equal(app.draft()?.config.nParallel, 3);+ assert.deepEqual(app.imports, [[n3, undefined, undefined]]);+ assert.deepEqual([app.count("success"), app.edited()], [1, true]);+});++test("imports wait without consuming until the editor, draft and request line up", async (t) => {+ for (const [reason, change] of [+ ["sidebar", { canImport: false }],+ ["hydrating", { ready: false }],+ ["wrong draft", { key: "other" }],+ ["no request", { pending: null }],+ ["no draft", {}],+ ] as const) {+ const app = importHarness(t);+ if (reason === "no draft") app.releaseDraft();+ assert.equal(app.schedule({ ...app.options, ...change }), undefined);+ await settle();+ assert.equal(app.inbox.getSnapshot(), app.options.pending, reason);+ assert.deepEqual(app.imports, [], reason);+ }+});++test("a queued import cannot overwrite an unmount, edit, newer link or released draft", async (t) => {+ for (const reason of ["unmount", "edit", "new link", "draft released"]) {+ const app = importHarness(t);+ const cancel = app.schedule(app.options);+ if (reason === "unmount") cancel?.();+ if (reason === "edit") {+ app.inbox.clear("import");+ drafts.patchModelConfigDraft(app.key, (c) => ({ ...c, nParallel: 7 }));+ }+ if (reason === "new link") {+ const value = { config: { nParallel: 8 } };+ app.inbox.submit({ id: "new", draftKey: app.key, value });+ }+ if (reason === "draft released") app.releaseDraft();+ await settle();+ assert.deepEqual([app.imports, app.count("success")], [[], 0], reason);+ if (reason === "edit") assert.equal(app.draft()?.config.nParallel, 7);+ if (reason === "new link") assert.equal(app.inbox.getSnapshot()?.id, "new");+ if (reason === "draft released") assert.equal(app.draft(), undefined);+ }+});++test("failed hydration reports once, never cancels on close, and a reopened link imports once", async (t) => {+ const app = importHarness(t);+ const cancellations: string[] = [];+ const onCancel = (request: { id: string }) => cancellations.push(request.id);+ const release = app.inbox.retainEditor(app.key, onCancel);+ t.after(release);+ const before = app.draft();+ app.schedule({ ...app.options, hydrated: false });+ await app.run({ hydrated: false });+ assert.deepEqual([app.draft(), app.edited()], [before, false]);+ assert.deepEqual([app.inbox.getSnapshot(), app.count("error")], [null, 1]);+ release();+ await app.run();+ assert.deepEqual(+ [cancellations, app.imports, app.count("success")],+ [[], [], 0],+ );+});++test("imported extra arguments replace a raw edit", async (t) => {+ const edit = { text: "unfinished '", source: "--no-warmup" };+ const llamaExtraArgs = ["--rope-scaling", "yarn"];+ const unchanged = { tensorParallel: DEFAULT_PER_MODEL_CONFIG.tensorParallel };+ const patch = { customContextLength: 8192, llamaExtraArgs, ...unchanged };+ const app = importHarness(t, patch);+ drafts.setExtraArgsEditForDraft(app.key, edit);+ await app.run();+ const changes = { customContextLength: 8192, llamaExtraArgs };+ assert.deepEqual(app.imports[0][0], changes);+ assert.equal(drafts.readExtraArgsEditForDraft(app.key), undefined);+ assert.equal(app.draft()?.remember, true);+});diff --git a/studio/frontend/tests/share-run-configs.editor.test.ts b/studio/frontend/tests/share-run-configs.editor.test.tsnew file mode 100644index 00000000000..3b347851c89--- /dev/null+++ b/studio/frontend/tests/share-run-configs.editor.test.ts@@ -0,0 +1,761 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import type { ModelPickTarget } from "../src/features/model-picker/components/model-selector/types.ts";+import type { PerModelConfig } from "../src/features/model-picker/model-config/per-model-config.ts";+import type * as Controls from "../src/features/model-picker/sharing/config-controls.tsx";+import type * as ConfigUi from "../src/features/model-picker/sharing/config-ui.tsx";+import type * as LinkEditor from "../src/features/model-picker/sharing/link-editor.tsx";+import type * as LinkHandler from "../src/features/model-picker/sharing/link-handler.tsx";+import type * as ShareDialog from "../src/features/model-picker/sharing/share-dialog.tsx";+import {+ installLocalStorageFake,+ readSrc,+ registerBundlerResolver,+} from "./helpers/kit.ts";+import {+ type StubElement,+ loadWithStubs,+ stubJsxRuntime,+} from "./helpers/module-stubs.ts";++registerBundlerResolver();+installLocalStorageFake();+const [fields, sharedArgs, links, perModel, drafts, inboxes, targets] =+ await Promise.all([+ import("../src/features/model-picker/sharing/fields.ts"),+ import("../src/features/model-picker/sharing/extra-args.ts"),+ import("./helpers/sharing-links.ts"),+ import("../src/features/model-picker/model-config/per-model-config.ts"),+ import("../src/features/model-picker/model-config/model-config-draft.ts"),+ import("../src/features/model-picker/sharing/inbox.ts"),+ import("./helpers/sharing-target.ts"),+ ]);+const { mergeSharedRunConfig } = fields;+const { createRunConfigLink, parseRunConfigLink } = links;+const { DEFAULT_PER_MODEL_CONFIG: D } = perModel;+const { modelConfigDraftKey } = drafts;+const { createRunConfigInbox } = inboxes;+const { isKnownNonGgufModel, resolveRunConfigTarget } = targets;++type Inbox = ReturnType<typeof createRunConfigInbox>;+type Selection = Parameters<typeof resolveRunConfigTarget>[1];+const hubTarget: ModelPickTarget = {+ id: "owner/Model-GGUF",+ displayName: "Model",+ ggufVariant: "Q4_K_M",+ isGguf: true,+ apiLoadable: true,+ meta: { source: "hub", isLora: false },+};++function elements(node: unknown): StubElement[] {+ if (Array.isArray(node)) return node.flatMap(elements);+ if (!node || typeof node !== "object" || !("props" in node)) return [];+ const element = node as StubElement;+ return [element, ...elements(element.props.children)];+}++function text(node: unknown): string {+ if (Array.isArray(node)) return node.map(text).join("");+ if (node && typeof node === "object" && "props" in node)+ return text((node as StubElement).props.children);+ return typeof node === "string" || typeof node === "number"+ ? String(node)+ : "";+}++const find = (tree: StubElement[], type: unknown) =>+ tree.find((element) => element.type === type);+const summaryText = (node: unknown) => text(find(elements(node), "summary"));+const call = (element: StubElement | undefined, name: string, arg?: unknown) =>+ (element?.props[name] as (value?: unknown) => unknown)(arg);+const toggle = (element: StubElement | undefined, checked: boolean) =>+ call(element, "onCheckedChange", checked);+const tags = new Proxy({}, { get: (_target, name) => name });++// State by call order, effects recorded (never run); unlisted imports render as their names.+function load<T>(file: string, stubs: Record<string, unknown> = {}) {+ const states: unknown[] = [];+ const effects: (() => (() => void) | undefined)[] = [];+ const effect = (run: (typeof effects)[number]) => effects.push(run);+ let cursor = 0;+ const known: Record<string, unknown> = {+ react: {+ lazy: () => "lazy",+ Suspense: "Suspense",+ useId: () => "share",+ useMemo: (create: () => unknown) => create(),+ useRef: () => ({ current: null }),+ useSyncExternalStore: (_: unknown, get: () => unknown) => get(),+ useEffect: effect,+ useLayoutEffect: effect,+ useState: (initial: unknown) => {+ const index = cursor++;+ if (index >= states.length) {+ states.push(typeof initial === "function" ? initial() : initial);+ }+ const set = (next: unknown) => {+ states[index] =+ typeof next === "function" ? next(states[index]) : next;+ };+ return [states[index], set];+ },+ },+ "react/jsx-runtime": stubJsxRuntime(),+ "../model-config/model-config-draft": {+ modelConfigDraftKey,+ isExtraArgsHydratedForDraft: () => false,+ },+ "../model-config/per-model-config": perModel,+ "./extra-args": sharedArgs,+ "./fields": fields,+ "./links": links,+ ...stubs,+ };+ const module = loadWithStubs<T>(+ new URL(`../src/features/model-picker/sharing/${file}`, import.meta.url),+ new Proxy(known, {+ has: () => true,+ get: (target, name: string) => (name in target ? target[name] : tags),+ }),+ );+ const render = <R>(draw: () => R) => {+ cursor = 0;+ return draw();+ };+ return { module, states, effects, render };+}++const loadConfigUi = (inbox = createRunConfigInbox()) =>+ load<typeof ConfigUi>("config-ui.tsx", {+ "./inbox": { runConfigInbox: inbox },+ "./import-config": { scheduleRunConfigImport: () => undefined },+ });+const { SharedRunConfigReview } = loadConfigUi().module;+const review = (+ config: Partial<PerModelConfig> | null,+ props: Partial<Parameters<typeof SharedRunConfigReview>[0]> = {},+ selection: { model?: string; ggufVariant?: string } = {},+) => {+ const draftConfig = { ...D, ...config };+ return SharedRunConfigReview({+ imported: config && { changes: config, ...selection },+ draftConfig,+ currentConfig: draftConfig,+ ...props,+ });+};++function shareDialog(config: PerModelConfig, target = hubTarget, tauri = true) {+ const { module, render } = load<typeof ShareDialog>("share-dialog.tsx", {+ "@/lib/api-base": { isTauri: tauri },+ });+ return () => {+ const tree = elements(+ render(() =>+ module.ShareRunConfigDialog({ target, config, onClose: () => {} }),+ ),+ );+ const link = find(tree, "Textarea")?.props.value as string;+ const parsed = parseRunConfigLink(link);+ assert.ok(parsed.kind === "valid");+ const choice = (key: string) =>+ tree.find((element) => element.props.id === `share-${key}`);+ const { value } = parsed;+ return { tree, link, value, config: value.config, choice };+ };+}++test("links keep null, false, zero and empty values and drop native-only settings", () => {+ const defaults = { ...D, nParallel: 8, llamaExtraArgs: ["--metrics"] };+ const empty = [{}, { nParallel: null }, { tensorParallel: false }];+ const zero = [{ reasoningBudget: 0 }, { reasoningBudgetMessage: "" }];+ for (const patch of [...empty, ...zero, { llamaExtraArgs: [] }]) {+ const parsed = parseRunConfigLink(createRunConfigLink({ config: patch }));+ assert.ok(parsed.kind === "valid");+ const merged = mergeSharedRunConfig(defaults, parsed.value.config);+ assert.deepEqual(merged, { ...defaults, ...patch });+ }+ const native = { maxSeqLength: 8192, mlxKvQuant: "4" as const };+ const link = createRunConfigLink({ config: { nParallel: 2, ...native } });+ assert.ok(!/maxSeqLength|mlxKv/.test(link));+ const omitted = { nParallel: undefined, ...native };+ assert.deepEqual(mergeSharedRunConfig(defaults, omitted), defaults);+ const patch = { llamaExtraArgs: ["--metrics"] };+ mergeSharedRunConfig(defaults, patch).llamaExtraArgs?.push("--verbose");+ const kept = [patch, defaults].map((config) => config.llamaExtraArgs);+ assert.deepEqual(kept, [["--metrics"], ["--metrics"]]);+ for (const query of ["maxSeqLength=8192", "mlxKvQuant=4", "isGguf=true"]) {+ assert.deepEqual(parseRunConfigLink(`unsloth://run?v=1&${query}`), {+ kind: "invalid",+ error: "This run configuration link contains an unsupported setting.",+ });+ }+});++test("pending imports are scoped, replaced by newer links and consumed once", () => {+ const inbox = createRunConfigInbox();+ let notifications = 0;+ const unsubscribe = inbox.subscribe(() => notifications++);+ inbox.submit({ id: "first", value: { config: { nParallel: 2 } } });+ assert.equal(inbox.take("first", "model-A"), null);+ inbox.bind("first", "model-A");+ assert.equal(inbox.take("first", "model-B"), null);+ inbox.submit({ id: "second", value: { config: { nParallel: 4 } } });+ inbox.clear("first");+ inbox.bind("first", "model-A");+ inbox.bind("second", "model-B");+ assert.deepEqual(inbox.take("second", "model-B"), { nParallel: 4 });+ assert.equal(inbox.take("second", "model-B"), null);+ assert.equal(inbox.getSnapshot(), null);+ assert.equal(notifications, 5);+ unsubscribe();+ inbox.submit({ id: "third", value: { config: {} } });+ assert.equal(notifications, 5);+});++test("editor cleanup cancels only the last editor's own unfinished import, surviving remounts", async () => {+ const inbox = createRunConfigInbox();+ const cancelled: string[] = [];+ const onCancel = (request: { id: string }) => cancelled.push(request.id);+ inbox.submit({ id: "first", value: { config: { nParallel: 2 } } });+ inbox.bind("first", "model-A");+ inbox.retainEditor("model-A", onCancel)();+ const releaseRemount = inbox.retainEditor("model-A", onCancel);+ await Promise.resolve();+ const releasePeer = inbox.retainEditor("model-A", onCancel);+ releaseRemount();+ await Promise.resolve();+ assert.equal(inbox.getSnapshot()?.id, "first");+ assert.deepEqual(cancelled, []);+ releasePeer();+ releasePeer();+ await Promise.resolve();+ assert.equal(inbox.getSnapshot(), null);+ assert.deepEqual(cancelled, ["first"]);+ for (const nextKey of ["model-A", "model-B"]) {+ inbox.submit({ id: "old", value: { config: {} } });+ inbox.bind("old", "model-A");+ inbox.retainEditor("model-A")();+ inbox.submit({ id: "new", value: { config: {} } });+ inbox.bind("new", nextKey);+ await Promise.resolve();+ assert.equal(inbox.getSnapshot()?.id, "new", nextKey);+ }+ for (const config of [{}, { nParallel: 2 }]) {+ inbox.submit({ id: "done", draftKey: "model-A", value: { config } });+ const release = inbox.retainEditor("model-A", () => assert.fail());+ if ("nParallel" in config) inbox.take("done", "model-A");+ release();+ await Promise.resolve();+ assert.equal(inbox.getSnapshot(), null);+ }+});++const selection: Selection = {+ params: { checkpoint: "owner/model" },+ activeGgufVariant: "Q4",+ loadedIsGguf: true,+ activeNativePathToken: "token",+ activeLoadId: "/cache/owner/model",+ models: [],+ loras: [],+};+const unknown = { loadedIsGguf: null, activeGgufVariant: null };+const at = (checkpoint: string, extra: Partial<Selection> = {}) => ({+ ...unknown,+ activeNativePathToken: null,+ params: { checkpoint },+ ...extra,+});+const other = (isGguf: boolean) => ({+ models: [{ id: "owner/other", isGguf, isLora: false }],+});+const lora = (id: string, exportType: "gguf" | "lora") =>+ at(id, { loras: [{ id, exportType }] });+const file = "C:\\m.gguf";+const local = { isGguf: true, nativePathToken: "token", isDownloaded: true };+const fresh = { nativePathToken: undefined, loadId: undefined };+const none = { ggufVariant: undefined };+const u = undefined;+const c = { config: {} };+const q8 = { ggufVariant: "Q8", config: {} };++test("run config targets resolve model identity, format and local capability", () => {+ // [link value, recipient selection, chosen model, expected id and meta]+ const rows = [+ [c, {}, u, { id: "owner/model", ggufVariant: "Q4", ...local }],+ [c, {}, u, { loadId: "/cache/owner/model" }],+ [c, at(""), u, null],+ [{ ...q8, model: "owner/other" }, other(false), u, { ...fresh }],+ [{ ...q8, model: "owner/other" }, other(false), u, { isGguf: true }],+ [{ ...q8, model: "owner/other" }, other(false), u, { ggufVariant: "Q8" }],+ [{ ...c, model: "owner/other" }, other(true), u, { ...none, ...fresh }],+ [c, lora("/e", "gguf"), u, { isGguf: true, isLora: false }],+ [c, lora("/a", "lora"), u, { isGguf: false, isLora: true }],+ [q8, { params: { checkpoint: file } }, u, { ...none, ...local }],+ [+ q8,+ { activeLoadId: file, params: { checkpoint: file } },+ u,+ { loadId: file },+ ],+ [q8, { loadedIsGguf: false }, u, { isGguf: false, ...none }],+ [c, at(""), "a/n", { id: "a/n", isGguf: true, ...none }],+ [c, at("a/n"), u, { id: "a/n", isGguf: true, ...none }],+ ] as const;+ for (const [value, overrides, chosen, expected] of rows) {+ const state = { ...selection, ...overrides };+ const target = resolveRunConfigTarget(value, state, chosen);+ if (!expected) {+ assert.equal(target, null);+ continue;+ }+ const actual: Record<string, unknown> = { id: target?.id, ...target?.meta };+ for (const [key, field] of Object.entries(expected)) {+ assert.deepEqual(actual[key], field, key);+ }+ }+ const loras = [+ { id: "/e", exportType: "gguf" as const },+ { id: "/a", exportType: "lora" as const },+ ];+ const native = { ...selection, loadedIsGguf: false, loras };+ for (const [id, state, expected] of [+ ["owner/model", selection, false],+ ["owner/model", native, true],+ ["", native, false],+ [file, { ...native, params: { checkpoint: file } }, false],+ ["/a", native, true],+ ["/e", native, false],+ ["a/n", { ...selection, ...unknown }, false],+ ] as const) {+ assert.equal(isKnownNonGgufModel(id, state), expected, id);+ }+});++test("local sharing keeps the recipient's quant unless the sender includes it", () => {+ const recipient = { ...selection, activeNativePathToken: null };+ const opened = (value: Parameters<typeof resolveRunConfigTarget>[0]) =>+ resolveRunConfigTarget(value, recipient)?.meta;+ const meta = { source: "local" as const, isLora: false };+ const render = shareDialog(D, { ...hubTarget, id: "/m/Qwen", meta });+ const initial = render();+ assert.equal(initial.choice("variant")?.props.checked, false);+ assert.deepEqual(initial.value, { config: {} });+ assert.equal(opened(initial.value)?.ggufVariant, "Q4");+ assert.equal(opened(initial.value)?.isDownloaded, true);+ toggle(initial.choice("variant"), true);+ assert.equal(render().value.ggufVariant, "Q4_K_M");+ assert.equal(opened(render().value)?.ggufVariant, "Q4_K_M");+ assert.notEqual(opened(render().value)?.isDownloaded, true);+ const shareable = shareDialog(D)();+ assert.equal(shareable.choice("variant")?.props.checked, true);+ assert.equal(shareable.value.ggufVariant, "Q4_K_M");+});++test("share dialog defaults to Web only on loopback addresses", () => {+ const previous = window.location;+ try {+ for (const [address, destination] of [+ ["http://localhost:8888", "browser"],+ ["http://127.10.20.30:8888", "browser"],+ ["http://[::1]:8888", "browser"],+ ["http://192.168.1.20:8888", "desktop"],+ ["https://localhost.example.com", "desktop"],+ ]) {+ Object.assign(window, { location: new URL(`${address}/chat?p=1`) });+ const render = shareDialog(D, hubTarget, false);+ const select = find(render().tree, "Select");+ assert.equal(select?.props.value, destination, address);+ const { protocol } = new URL(render().link);+ const http = new URL(address).protocol;+ assert.equal(protocol, destination === "browser" ? http : "unsloth:");+ call(select, "onValueChange", "browser");+ const explicit = new URL(render().link);+ assert.equal(explicit.origin, new URL(address).origin);+ assert.equal(explicit.search, "?run=1");+ }+ } finally {+ Object.assign(window, { location: previous });+ }+});++test("extra arguments are always selectable; custom text, templates and native settings are not", () => {+ const recipient = {+ ...D,+ llamaExtraArgs: ["--threads", "8"],+ chatTemplateOverride: "{{ messages }}",+ reasoningBudgetMessage: "Recipient message",+ };+ for (const llamaExtraArgs of [undefined, null, [], ["--threads", "4"]]) {+ const render = shareDialog({+ ...D,+ llamaExtraArgs,+ chatTemplateOverride: "{{ sender }}",+ maxSeqLength: 4096,+ mlxKvQuant: "8",+ reasoningBudgetMessage: "Sender instruction",+ });+ const { tree, config, choice, link } = render();+ const message = choice("reasoningBudgetMessage")?.props;+ assert.deepEqual([message?.disabled, message?.checked], [true, false]);+ assert.match(text(tree), /Custom reasoning messages cannot be shared/);+ const hidden = ["chatTemplateOverride", "maxSeqLength", "mlxKvQuant"];+ assert.ok(!hidden.some(choice));+ assert.ok(!/chatTemplateOverride|maxSeqLength|mlxKv|isGguf/.test(link));+ assert.deepEqual(mergeSharedRunConfig(recipient, config), {+ ...recipient,+ ...(llamaExtraArgs?.length && { llamaExtraArgs }),+ });+ const args = choice("llamaExtraArgs");+ assert.equal(args?.props.disabled, false);+ assert.equal(args?.props.checked, Boolean(llamaExtraArgs?.length));+ if (!llamaExtraArgs?.length) {+ toggle(args, true);+ const selected = render();+ assert.equal(selected.choice("llamaExtraArgs")?.props.checked, true);+ assert.match(text(selected.tree), /No extra arguments/);+ assert.deepEqual(selected.config.llamaExtraArgs, llamaExtraArgs ?? null);+ }+ }+});++test("automatic GPU settings preserve recipient overrides until explicitly selected", () => {+ // [field, automatic value, manual value]+ const gpu = [+ ["gpuMemoryMode", "auto", "manual"],+ ["gpuLayers", -1, 20],+ ["nCpuMoe", 0, 4],+ ["selectedGpuIds", null, [1, 0]],+ ["selectedGpuIndexKind", null, "physical"],+ ] as const;+ const pick = (index: 1 | 2): Partial<PerModelConfig> =>+ Object.fromEntries(gpu.map((row) => [row[0], row[index]]));+ const [automatic, manual] = [pick(1), pick(2)];+ const render = shareDialog({ ...D, ...automatic });+ assert.deepEqual(render().config, {});+ for (const key of Object.keys(automatic)) {+ const choice = render().choice(key);+ assert.equal(choice?.props.checked || choice?.props.disabled, false);+ toggle(choice, true);+ }+ assert.deepEqual(render().config, automatic);+ assert.deepEqual(mergeSharedRunConfig({ ...D, ...manual }, render().config), {+ ...D,+ ...automatic,+ tensorSplit: null,+ });+ assert.deepEqual(shareDialog({ ...D, ...manual })().config, manual);+ assert.deepEqual(shareDialog(D)().config, {});+});++function pendingImport() {+ const inbox = createRunConfigInbox();+ const draftKey = modelConfigDraftKey(hubTarget.id, hubTarget.ggufVariant);+ inbox.submit({+ id: "pending",+ draftKey,+ value: { config: { nParallel: 3 } },+ });+ return inbox;+}+const controlProps = {+ className: "h-9 rounded-full",+ target: hubTarget,+ config: D,+ ready: true,+ canImport: true,+ disabled: false,+ onImport: () => undefined,+};++test("Share opens and closes its dialog without touching the pending import", () => {+ const inbox = pendingImport();+ const { module, render } = loadConfigUi(inbox);+ const draftKey = modelConfigDraftKey(hubTarget.id, hubTarget.ggufVariant);+ const props = { ...controlProps, draftKey, hydrated: true };+ const tree = () =>+ elements(render(() => module.SharedRunConfigActions(props)));+ assert.equal(find(tree(), "ShareRunConfigDialog"), undefined);+ call(find(tree(), "Button"), "onClick");+ call(find(tree(), "ShareRunConfigDialog"), "onClose");+ assert.equal(find(tree(), "ShareRunConfigDialog"), undefined);+ assert.equal(inbox.getSnapshot()?.id, "pending");+});++test("closing an editor before its sharing UI loads cancels the import, while effect replay retains it", async () => {+ const inbox = pendingImport();+ const notices: { id: string; description: string }[] = [];+ const { module, effects } = load<typeof Controls>("config-controls.tsx", {+ "@/lib/toast": {+ toast: { info: (_: string, notice: never) => notices.push(notice) },+ },+ "./inbox": { runConfigInbox: inbox },+ "./target": { isRunConfigVariantUnresolved: () => false },+ });+ const props = { ...controlProps, isDiffusion: false };+ module.SharedRunConfigControls({ ...props, canImport: false });+ assert.equal(effects[0](), undefined);+ const tree = elements(module.SharedRunConfigControls(props));+ assert.equal(tree[0].type, "LazyImportBoundary");+ const fallback = (tree[0].props.fallback as StubElement).props;+ assert.deepEqual(+ [fallback.disabled, fallback.className],+ [true, props.className],+ );+ assert.equal(find(tree, "lazy")?.props.target, hubTarget);+ assert.equal(find(tree, "lazy")?.props.hydrated, false);+ effects[1]()?.();+ module.SharedRunConfigControls(props);+ const releaseRemounted = effects[2]();+ await Promise.resolve();+ assert.equal(inbox.getSnapshot()?.id, "pending");+ assert.equal(notices.length, 0);+ releaseRemounted?.();+ await Promise.resolve();+ assert.equal(inbox.getSnapshot(), null);+ assert.equal(notices[0].id, "pending");+ assert.match(notices[0].description, /editor closed before the settings/);+});++test("edit cancellation includes contained controls and excludes portaled dialog controls", (t) => {+ class NodeFake extends EventTarget {+ child?: NodeFake;+ contains = (node: NodeFake) => node === this || node === this.child;+ }+ // Bare node has no DOM Node global; this file runs in its own process.+ Object.assign(globalThis, { Node: NodeFake });+ t.after(() => Reflect.deleteProperty(globalThis, "Node"));+ const editor = new NodeFake();+ editor.child = new NodeFake();+ const currentTarget = editor as unknown as Node;+ const events = load<typeof Controls>("config-controls.tsx").module;+ for (const [target, expected] of [+ [editor.child, true],+ [new NodeFake(), false],+ [new EventTarget(), false],+ ] as const) {+ const changed = events.isRunConfigEditorChange({ currentTarget, target });+ assert.equal(changed, expected);+ }+});++test("review renders field labels, values and device adjustments as text", () => {+ assert.equal(review(null), null);+ const args = ["--rope-scaling", "yarn"];+ const imported = {+ nParallel: 3,+ llamaExtraArgs: args,+ customContextLength: null,+ kvCacheDtype: "q8_0",+ selectedGpuIds: [0, 1],+ };+ const tree = review(imported);+ assert.equal(summaryText(tree), "Settings changed by link5");+ const values = elements(tree)+ .filter((e) => e.type === "dd")+ .map(text);+ assert.deepEqual(values, ["Default", "q8_0", "3", args.join(" "), "[0,1]"]);+ assert.ok(text(tree).includes("Parallel slots"));+ assert.ok(+ elements(tree).every((e) => !("dangerouslySetInnerHTML" in e.props)),+ );+ assert.ok(text(review({})).includes("already match"));+ for (const changed of [+ { nParallel: 7 },+ { llamaExtraArgs: ["-t", "4"] },+ D,+ ]) {+ const edited = { ...D, ...imported, ...changed };+ const props = { draftConfig: edited, currentConfig: edited };+ assert.equal(review(imported, props), null);+ }+ const copied = { ...D, ...imported, llamaExtraArgs: [...args] };+ assert.notEqual(review(imported, { currentConfig: copied }), null);+ assert.match(text(review({ llamaExtraArgs: null })), /No extra arguments/);+ const cleared = { currentConfig: { ...D, llamaExtraArgs: [] } };+ const adjusted = text(review({ llamaExtraArgs: args }, cleared));+ assert.match(adjusted, /No extra arguments/);+ assert.match(adjusted, /Requested --rope-scaling yarn, adjusted for this/);+});++test("review states what loading does to this model's saved settings", () => {+ const notes = [+ "Loading replaces your saved settings for this model. Close without loading to keep them.",+ "Loading saves these settings for this model.",+ "Loading clears your saved settings for this model. Close without loading to keep them.",+ "To keep these settings for next time, tick “Remember for this model”.",+ ];+ notes.forEach((note, index) => {+ const remember = index < 2;+ const hasSavedSettings = index % 2 === 0;+ const shown = text(+ review({ nParallel: 3 }, { remember, hasSavedSettings }),+ );+ assert.deepEqual(+ notes.filter((entry) => shown.includes(entry)),+ [note],+ );+ });+});++test("review identifies a linked repository or quant and explains possible downloads", () => {+ const hub = "If the model isn’t on this device, loading downloads it from";+ const quant = "If this variant isn’t on this device, loading downloads it.";+ for (const config of [{}, { nParallel: 3 }]) {+ const plain = text(review(config));+ assert.doesNotMatch(plain, /owner\/model|Hugging Face|downloads/);+ for (const [model, ggufVariant, summary, note] of [+ ["owner/model", u, "owner/model", hub],+ ["owner/Model-GGUF", "Q8_0", "owner/Model-GGUF · Q8_0", hub],+ [u, "Q8_0", "Q8_0", quant],+ ] as const) {+ const tree = review(config, {}, { model, ggufVariant });+ assert.ok(summaryText(tree).endsWith(summary));+ assert.ok(text(tree).includes(note));+ assert.doesNotMatch(text(tree), /Link settings already match/);+ if (!model) assert.doesNotMatch(text(tree), /from Hugging Face/);+ if (!model && !("nParallel" in config)) {+ assert.match(text(tree), /GGUF variant selected by link/);+ }+ }+ }+});++const yes = () => true;+const no = () => false;+const useRouterState = () => ({ pathname: "/chat" });++function linkEditor(runtime: object, inbox: Inbox) {+ const useChatRuntimeStore = (select: (state: object) => unknown) =>+ select(runtime);+ const { module, render, states } = load<typeof LinkEditor>(+ "link-editor.tsx",+ {+ "@/features/auth": { hasAuthToken: yes, mustChangePassword: no },+ "@/features/chat": { isExternalModelId: no, useChatRuntimeStore },+ "@/features/hub": { useHfTokenStore: no, useInventoryVersion: no },+ "@tanstack/react-router": { useNavigate: no, useRouterState },+ "./inbox": { runConfigInbox: inbox },+ "./target": targets,+ },+ );+ const draw = () => {+ const pending = inbox.getSnapshot();+ assert.ok(pending);+ const props = { pending, chatSearch: null };+ return elements(render(() => module.SharedRunConfigLinkEditor(props)));+ };+ return { draw, states };+}++test("settings-only chooser accepts recipient-local models and skips known GGUF selections", () => {+ const inbox = createRunConfigInbox();+ const empty = { params: { checkpoint: "" }, settingsHydrated: true };+ const { draw, states } = linkEditor(empty, inbox);+ const value = { config: { nParallel: 3 } };+ for (const model of [+ "owner/model",+ "C:\\Models\\my model.gguf",+ "./models/native",+ "ollama-manifest:registry.ollama.ai/library/llama3/latest",+ ]) {+ inbox.submit({ id: "local-choice", value });+ states.length = 0;+ assert.equal(find(draw(), "Dialog")?.props.open, true);+ assert.match(text(find(draw(), "Dialog")), /Choose a GGUF model/);+ assert.equal(find(draw(), "Button")?.props.disabled, true);+ call(find(draw(), "Input"), "onChange", { target: { value: model } });+ assert.equal(find(draw(), "Button")?.props.disabled, false, model);+ call(find(draw(), "form"), "onSubmit", { preventDefault: () => {} });+ assert.equal(inbox.getSnapshot()?.selectedModel, model);+ assert.equal(inbox.getSnapshot()?.value, value);+ assert.equal(find(draw(), "Dialog")?.props.open, false);+ }+ const bad = ["", "https://e.com/m.gguf", "external::provider::model"];+ for (const model of [...bad, "/m\u0000.gguf", "/m\ud800.gguf"]) {+ assert.equal(targets.isRunConfigModelInput(model), false, model);+ }+ const runtime = {+ ...at("a/n"),+ models: [],+ loras: [],+ settingsHydrated: true,+ };+ for (const [loadedIsGguf, model, open] of [+ [false, u, true],+ [true, u, false],+ [null, u, false],+ [false, "owner/Model-GGUF", false],+ ] as const) {+ inbox.submit({ id: "known", value: { model, config: { nParallel: 3 } } });+ const shown = linkEditor({ ...runtime, loadedIsGguf }, inbox).draw();+ assert.equal(find(shown, "Dialog")?.props.open, open, String(loadedIsGguf));+ }+});++test("startup intake waits for mount effects and survives strict effect replay", async () => {+ const inbox = createRunConfigInbox();+ let received = 0;+ let authChanged = () => {};+ let disposed = false;+ const handler = load<typeof LinkHandler>("link-handler.tsx", {+ "./inbox": { runConfigInbox: inbox },+ "./receive-link": {+ receiveStartupRunConfigUrl: () => received++,+ subscribeRunConfigSession: (onChange: () => void) => {+ authChanged = onChange;+ return () => {+ disposed = true;+ };+ },+ },+ });+ const { module, effects, states, render } = handler;+ const chatSearch = { new: "retained-draft" };+ const draw = () =>+ render(() => module.SharedRunConfigLinkHandler({ chatSearch }));+ assert.equal(draw(), null);+ effects[0]()?.();+ await Promise.resolve();+ assert.equal(received, 0);+ disposed = false;+ const cleanup = effects[0]();+ assert.equal(received, 0);+ await Promise.resolve();+ assert.equal(received, 1);+ inbox.submit({ id: "link", value: { config: { nParallel: 3 } } });+ const shown = find(elements(draw()), "lazy");+ assert.equal(shown?.props.pending, inbox.getSnapshot());+ assert.equal(shown?.props.chatSearch, chatSearch);+ authChanged();+ assert.equal(states[0], 1);+ const failure = (draw() as StubElement).props.fallback as StubElement;+ assert.equal(failure.type, "LazyImportFailure");+ call(failure, "onDismiss");+ assert.equal(draw(), null);+ cleanup?.();+ assert.equal(disposed, true);+});++test("Load and Save refuse while a shared GGUF variant is unresolved", () => {+ const page = readSrc(+ "features/model-picker/components/model-config-page.tsx",+ ).replace(/\s+/g, " ");+ for (const handler of ["handleRun", "handleSave"]) {+ const body = page.slice(page.indexOf(`const ${handler} = () => {`));+ assert.match(+ body.slice(0, 80),+ /^const \w+ = \(\) => \{ if \(sharedVariantUnresolved\) \{ return; \}/,+ );+ const button = page.slice(0, page.indexOf(`onClick={${handler}}`));+ assert.match(+ button.slice(button.lastIndexOf("disabled={")),+ /^disabled=\{ sharedVariantUnresolved \|\|/,+ );+ }+});diff --git a/studio/frontend/tests/share-run-configs.lifecycle.test.ts b/studio/frontend/tests/share-run-configs.lifecycle.test.tsnew file mode 100644index 00000000000..ac685102aa5--- /dev/null+++ b/studio/frontend/tests/share-run-configs.lifecycle.test.ts@@ -0,0 +1,701 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test, { type TestContext } from "node:test";+import type { ChatSearch } from "../src/features/chat/chat-page.tsx";+import type * as ImportConfig from "../src/features/model-picker/sharing/import-config.ts";+import type * as Lifecycle from "../src/features/model-picker/sharing/link-lifecycle.ts";+import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++registerBundlerResolver();+installLocalStorageFake();+const drafts = await import(+ "../src/features/model-picker/model-config/model-config-draft.ts"+);+const { modelConfigDraftKey } = drafts;+const fields = await import("../src/features/model-picker/sharing/fields.ts");+const { DEFAULT_PER_MODEL_CONFIG } = await import(+ "../src/features/model-picker/model-config/per-model-config.ts"+);+const { modelConfigHandoffForDestination } = await import(+ "../src/features/model-picker/model-config/model-config-handoff.ts"+);+const { resolveRunConfigTarget } = await import("./helpers/sharing-target.ts");+const links = await import("./helpers/sharing-links.ts");+const { receiverHarness, settle } = await import(+ "./helpers/sharing-receiver.ts"+);+const events = await import("../src/features/auth/session-events.ts");+const run = "unsloth://run?v=1&model=owner/model&nParallel=3";+const browserRun =+ "http://localhost/chat#run?v=1&model=owner/model&nParallel=3";+type Doc = Pick<ReturnType<typeof receiverHarness>, "inbox" | "receiver">;+const nParallel = (doc: Doc) => doc.inbox.getSnapshot()?.value.config.nParallel;+const sharing = (file: string) =>+ new URL(`../src/features/model-picker/sharing/${file}`, import.meta.url);++type Target = NonNullable<ReturnType<typeof resolveRunConfigTarget>>;+function deferred<T>() {+ let resolve!: (value: T) => void;+ let reject!: (error: Error) => void;+ const promise = new Promise<T>((yes, no) => {+ resolve = yes;+ reject = no;+ });+ return { promise, resolve, reject };+}+const at = (href: string) => {+ const url = new URL(href, "http://localhost");+ return { href, pathname: url.pathname, searchStr: url.search };+};+const navigateCall = (id?: string, replace = false) => [+ "navigate",+ { to: "/chat", search: { new: id }, replace },+];+const target: Target = {+ id: "owner/Model-GGUF",+ meta: {+ source: "hub",+ isLora: false,+ isGguf: true,+ ggufVariant: "Q4_K_M",+ loadId: "/cache/snapshot",+ isDownloaded: true,+ },+};+const key = modelConfigDraftKey(target.id, "Q4_K_M");+const handoff = (resolved: Target = target, extra = {}) => [+ "handoff",+ { requestId: "first", ...extra, ...resolved, displayName: resolved.id },+];++class ResolutionError extends Error {}++function harness(loadParser?: () => typeof links | Promise<typeof links>) {+ const calls: unknown[] = [];+ const session = sessionHarness({ loadParser });+ const { inbox, receiver } = session.loadDocument();+ const { errors, notices, cleared } = session;+ const loading = new Map<number, string>();+ let toastId = 0;+ const lookups: {+ target: Target;+ signal: AbortSignal;+ checkLocalPath?: boolean;+ result: ReturnType<typeof deferred<Target>>;+ }[] = [];+ inbox.submit({+ id: "first",+ value: { model: "owner/Model-GGUF", config: { nParallel: 3 } },+ });+ const pending = inbox.getSnapshot();+ assert.ok(pending);+ const navigationResult = deferred<void>();+ const runtime = {+ params: { checkpoint: "" },+ activeGgufVariant: null,+ loadedIsGguf: null,+ activeNativePathToken: null,+ activeLoadId: null,+ models: [] as { id: string; isGguf: boolean; isLora: boolean }[],+ loras: [],+ setActiveThreadId: (id: null) => calls.push(["thread", id]),+ setActiveProjectId: (id: null) => calls.push(["project", id]),+ setIncognito: (value: boolean) => calls.push(["incognito", value]),+ };+ const { scheduleRunConfigImport } = loadWithStubs<typeof ImportConfig>(+ sharing("import-config.ts"),+ {+ "@/lib/toast": { toast: { success: () => undefined } },+ "../model-config/model-config-draft": drafts,+ "./fields": fields,+ "./inbox": { runConfigInbox: inbox },+ },+ );+ const lifecycle = loadWithStubs<typeof Lifecycle>(+ sharing("link-lifecycle.ts"),+ {+ "@/features/chat": {+ clearNewChatDraft: () => calls.push("clear draft"),+ useChatRuntimeStore: { getState: () => runtime },+ },+ "@/lib/toast": {+ toast: {+ error: (message: string) => errors.push(message),+ loading: (message: string) =>+ loading.set(++toastId, message) && toastId,+ dismiss: (id: number) => loading.delete(id),+ },+ },+ "../model-config/model-config-draft": { modelConfigDraftKey },+ "../model-config/model-config-handoff": {+ clearModelConfigHandoff: (id: string) => cleared.push(id),+ requestModelConfigHandoff: (request: Target) => {+ assert.equal(+ inbox.getSnapshot()?.draftKey,+ modelConfigDraftKey(request.id, request.meta.ggufVariant),+ );+ calls.push(["handoff", request]);+ },+ },+ "./cached-target": {+ RunConfigResolutionError: ResolutionError,+ resolveCachedRunConfigTarget: (+ lookupTarget: Target,+ options: { signal: AbortSignal; checkLocalPath?: boolean },+ ) => {+ const result = deferred<Target>();+ lookups.push({ target: lookupTarget, ...options, result });+ return result.promise;+ },+ },+ "./inbox": { runConfigInbox: inbox },+ "./target": { resolveRunConfigTarget },+ "./receive-link": receiver,+ },+ );+ const context = {+ pending,+ canOpen: true,+ settingsHydrated: true,+ currentModel: "",+ location: at("/hub"),+ };+ const nav = {+ ...context,+ navigation: { current: null as Lifecycle.RunConfigNavigation | null },+ navigate: (options: unknown) => {+ calls.push(["navigate", options]);+ return navigationResult.promise;+ },+ };+ const open = {+ ...context,+ chatSearch: null as ChatSearch | null,+ location: at("/chat?new=first"),+ routeReady: true,+ inventoryVersion: 0,+ };+ const resolve = async (resolved = target, index = 0) => {+ lookups[index].result.resolve(resolved);+ await settle();+ };+ const lookupFromHub = (extra = {}) =>+ lifecycle.openRunConfigTarget({ ...open, ...context, ...extra });+ return {+ ...lifecycle,+ ...{ runtime, notices, cleared, receiver, inbox, calls, errors },+ ...{ loading, lookups, navigationResult, nav, open, resolve },+ lookupFromHub,+ openCurrent: (extra = {}) =>+ lifecycle.openRunConfigTarget({+ ...open,+ pending: inbox.getSnapshot(),+ ...extra,+ }),+ schedule: (onImport: () => void) =>+ scheduleRunConfigImport({+ canImport: true,+ ready: true,+ hydrated: true,+ key,+ pending: inbox.getSnapshot(),+ onImport,+ }),+ primeDraft: (t: TestContext, nParallel: number) => {+ t.after(drafts.retainModelConfigDraft(key));+ drafts.primeModelConfigDraft(+ key,+ {+ config: { ...DEFAULT_PER_MODEL_CONFIG, nParallel },+ remembered: false,+ },+ "none",+ );+ },+ prepare: async () => {+ lookupFromHub();+ assert.equal(lookups[0].checkLocalPath, false);+ assert.deepEqual([...loading.values()], ["Resolving shared model…"]);+ assert.equal(inbox.getSnapshot()?.draftKey, undefined);+ await resolve();+ assert.equal(loading.size, 0);+ const prepared = inbox.getSnapshot();+ assert.ok(prepared?.target);+ nav.pending = open.pending = prepared;+ },+ };+}++for (const [pathname, newChatId] of [+ ["/chat", null],+ ["/hub", null],+ ["/settings", "current-draft"],+] as const) {+ test(`review keeps the new chat and its draft from ${pathname}: ${newChatId}`, async () => {+ const app = harness();+ app.runtime.params.checkpoint = target.id;+ delete app.nav.pending.value.model;+ const destination = at(newChatId ? `/chat?new=${newChatId}` : "/chat");+ const context = {+ location:+ pathname === "/chat"+ ? destination+ : at(`${pathname}?new=unrelated&project=unrelated`),+ chatSearch: { new: newChatId ?? undefined },+ currentModel: target.id,+ };+ app.navigateRunConfig({ ...app.nav, ...context });+ app.openRunConfigTarget({ ...app.open, ...context });+ await app.resolve();+ const pending = app.inbox.getSnapshot();+ assert.equal(pending?.newChatId, newChatId);+ app.navigateRunConfig({ ...app.nav, ...context, pending });+ assert.deepEqual(+ app.calls.splice(0),+ pathname === "/chat" ? [] : [navigateCall(newChatId ?? undefined)],+ );+ app.openCurrent({ ...context, location: destination });+ const request = handoff(target, { newChatId })[1] as Parameters<+ typeof modelConfigHandoffForDestination+ >[0];+ assert.deepEqual(app.calls, [["handoff", request]]);+ for (const [destinationState, expected] of [+ [{ active: true, newChatId }, request],+ [{ active: true, ...(newChatId && { newChatId }) }, request],+ [{ active: false, newChatId }, null],+ [{ active: true, newChatId: "another-chat" }, null],+ [{ active: true, newChatId, threadId: "thread" }, null],+ [{ active: true, newChatId, compareId: "compare" }, null],+ [{ active: true, newChatId, projectId: "project" }, null],+ ] as const) {+ assert.equal(+ modelConfigHandoffForDestination(request, destinationState),+ expected,+ );+ }+ app.inbox.clear("first");+ assert.equal(app.calls.length, 1);+ });+}++for (const chatSearch of [+ null,+ { thread: "saved-chat" },+ { compare: "comparison" },+ { project: "project" },+]) {+ test(`availability binds the canonical draft in a fresh chat from ${JSON.stringify(chatSearch)}`, async () => {+ const app = harness();+ app.open.chatSearch = chatSearch && { new: "previous", ...chatSearch };+ await app.prepare();+ assert.equal(app.inbox.getSnapshot()?.newChatId, undefined);+ app.navigateRunConfig(app.nav);+ app.openRunConfigTarget({ ...app.open, routeReady: false });+ assert.deepEqual(app.calls, [navigateCall("first")]);+ app.openRunConfigTarget(app.open);+ assert.equal(app.inbox.take("first", "another draft"), null);+ assert.deepEqual(app.calls, [+ navigateCall("first"),+ "clear draft",+ ["thread", null],+ ["project", null],+ ["incognito", false],+ handoff(),+ ]);+ assert.equal(app.inbox.getSnapshot()?.draftKey, key);+ // A failed navigation clears only its own import.+ const superseded = chatSearch !== null;+ if (superseded) app.inbox.submit({ id: "second", value: { config: {} } });+ app.navigationResult.reject(new Error("navigation failed"));+ await settle();+ assert.equal(+ app.inbox.getSnapshot()?.id,+ superseded ? "second" : undefined,+ );+ assert.equal(app.errors.length, superseded ? 0 : 1);+ assert.deepEqual(app.cleared, superseded ? [] : ["first"]);+ });+}++test("navigation waits for availability, replaces history once, and ends when the user leaves", async () => {+ const app = harness();+ app.nav.pending.replaceHistory = true;+ app.navigateRunConfig(app.nav);+ assert.deepEqual(app.calls, []);+ await app.prepare();+ app.navigateRunConfig(app.nav);+ app.navigateRunConfig(app.nav);+ assert.deepEqual(app.calls, [navigateCall("first", true)]);+ app.navigateRunConfig({ ...app.nav, location: app.open.location });+ assert.equal(app.nav.navigation.current?.from, app.open.location.href);+ app.navigateRunConfig(app.nav);+ assert.equal(app.inbox.getSnapshot(), null);+});++for (const reason of ["login", "settings", "model", "bound", "superseded"]) {+ test(`navigation and lookup do nothing while ${reason} blocks the import`, () => {+ const app = harness();+ const patch = {+ canOpen: reason !== "login",+ settingsHydrated: reason !== "settings",+ };+ if (reason === "model") delete app.nav.pending.value.model;+ if (reason === "bound") app.nav.pending.draftKey = "already bound";+ if (reason === "superseded") app.inbox.clear("first");+ app.navigateRunConfig({ ...app.nav, ...patch });+ assert.equal(app.openRunConfigTarget({ ...app.open, ...patch }), undefined);+ assert.deepEqual([app.calls, app.lookups, app.loading.size], [[], [], 0]);+ });+}++test("failed lookups cancel the import with safe feedback", async () => {+ for (const [error, shown] of [+ [+ new Error("Private backend details"),+ "Could not resolve the shared model. Reopen the link to try again.",+ ],+ [new ResolutionError("Variant unavailable."), "Variant unavailable."],+ ] as const) {+ const app = harness();+ app.lookupFromHub();+ app.lookups[0].result.reject(error);+ await settle();+ assert.deepEqual([app.inbox.getSnapshot(), app.loading.size], [null, 0]);+ assert.deepEqual([app.errors, app.calls], [[shown], []]);+ }+});++test("a chosen model known to be safetensors is refused before any lookup", () => {+ const app = harness();+ app.runtime.models = [{ id: "owner/native", isGguf: false, isLora: false }];+ app.inbox.submit({+ id: "settings-only",+ value: { config: { nParallel: 3 } },+ selectedModel: "owner/native",+ });+ const cancel = app.lookupFromHub({ pending: app.inbox.getSnapshot() });+ assert.deepEqual(+ [cancel, app.inbox.getSnapshot(), app.lookups],+ [undefined, null, []],+ );+ assert.deepEqual(app.errors, [+ "Shared run settings apply only to GGUF models. Reopen the link and choose a GGUF model.",+ ]);+});++for (const failure of [false, true]) {+ for (const interrupt of ["cleanup", "newer link"] as const) {+ test(`stale availability ${failure ? "failures" : "successes"} after ${interrupt} are ignored`, async () => {+ const app = harness();+ app.navigateRunConfig(app.nav);+ const cancel = app.lookupFromHub();+ if (interrupt === "cleanup") {+ cancel?.();+ assert.equal(app.loading.size, 0);+ assert.equal(app.lookups[0].signal.aborted, true);+ app.lookupFromHub();+ } else app.inbox.submit({ id: "second", value: { config: {} } });+ if (failure) app.lookups[0].result.reject(new Error("stale"));+ else app.lookups[0].result.resolve(target);+ await settle();+ assert.deepEqual([app.calls, app.errors], [[], []]);+ const cleanup = interrupt === "cleanup";+ assert.equal(app.loading.size, cleanup ? 1 : 0);+ if (cleanup) await app.resolve(target, 1);+ assert.equal(app.loading.size, 0);+ const snapshot = app.inbox.getSnapshot();+ assert.equal(snapshot?.target, cleanup ? target : undefined);+ assert.equal(snapshot?.id, cleanup ? "first" : "second");+ });+ }+}++// An edit to the resolved draft cancels the import in every phase; edits to another quant do not.+for (const phase of [+ "parsing",+ "resolving",+ "resolved",+ "scheduled",+ "other quant",+] as const) {+ test(`edits during a shared import: ${phase}`, async (t) => {+ const parser = deferred<typeof links>();+ const app = harness(() => parser.promise);+ const matching = phase !== "other quant";+ app.primeDraft(t, matching ? 1 : 7);+ const edit = (when: string) => {+ if (when !== phase && matching) return;+ app.receiver.cancelRunConfigImportForEdit(+ matching ? key : modelConfigDraftKey(target.id, "Q8_0"),+ );+ if (!matching) return;+ drafts.markModelConfigDraftEdited(key);+ drafts.patchModelConfigDraft(key, { nParallel: 7 });+ };+ app.receiver.receiveSharedRunConfigUrls([+ "unsloth://run?v=1&model=owner/Model-GGUF&nParallel=3",+ ]);+ assert.equal(app.inbox.getSnapshot(), null);+ edit("parsing");+ parser.resolve(links);+ await settle();+ app.openCurrent();+ edit("resolving");+ await app.resolve();+ edit("resolved");+ if (app.inbox.getSnapshot()) {+ app.openCurrent({ location: at("/chat?new=request-1") });+ app.schedule(() => assert.ok(!matching, "A newer edit was overwritten"));+ edit("scheduled");+ await settle();+ }+ assert.equal(+ drafts.readModelConfigDraft(key)?.config.nParallel,+ matching ? 7 : 3,+ );+ assert.equal(drafts.isModelConfigDraftEdited(key), true);+ assert.equal(app.inbox.getSnapshot(), null);+ assert.deepEqual(+ app.notices.map(({ message }) => message),+ matching ? ["Run settings import cancelled"] : [],+ );+ assert.deepEqual([app.errors, app.loading.size], [[], 0]);+ });+}++function sessionHarness({+ url = browserRun,+ desktop = false,+ loadParser = (): typeof links | Promise<typeof links> => links,+} = {}) {+ const browser = installLocalStorageFake();+ const storage = new Map<string, string>();+ const getItem = (name: string) => storage.get(name) ?? null;+ const setItem = storage.set.bind(storage);+ Object.assign(globalThis, { sessionStorage: { getItem, setItem } });+ window.location.href = url;+ const historyState = { key: "existing-entry" };+ Object.assign(window, {+ history: {+ state: historyState,+ replaceState: (state: unknown, _title: string, href: string) => {+ assert.equal(state, historyState);+ window.location.href = href;+ },+ },+ });+ let signedIn = false;+ let parserLoads = 0;+ const errors: string[] = [];+ const notices: { message: string; description?: string }[] = [];+ const cleared: string[] = [];+ const signal = (value: boolean) => {+ signedIn = value;+ const { AUTH_SESSION_STORED_EVENT: on, AUTH_SESSION_CLEARED_EVENT: off } =+ events;+ browser.fireWindowEvent(value ? on : off, {});+ };+ const loadDocument = () => {+ const { inbox, receiver } = receiverHarness({+ desktop,+ signedIn: () => signedIn,+ drafts,+ ...{ errors, notices, cleared },+ loadParser: () => (parserLoads++, loadParser()),+ });+ const dispose = receiver.subscribeRunConfigSession(() => undefined);+ return { inbox, receiver, dispose };+ };+ return {+ ...{ loadDocument, storage, errors, notices, cleared },+ parserLoads: () => parserLoads,+ signIn: () => signal(true),+ signOut: () => signal(false),+ receive: async (doc: Doc, source: "startup" | "event" = "event") => {+ if (desktop) {+ doc.receiver.receiveSharedRunConfigUrls([run], source);+ await settle();+ } else await doc.receiver.receiveStartupRunConfigUrl();+ },+ };+}++// A pre-login link waits in memory through sign-in; a live session's import+// ends with one notice. Neither replays after a reload or account purge.+for (const [desktop, before, after] of [+ [true, false, false],+ [false, false, false],+ [true, true, false],+ [false, false, true],+] as const) {+ test(`session changes keep or cancel a pending link once: desktop=${desktop} signedIn=${before}/${after}`, async () => {+ const app = sessionHarness({ desktop });+ if (before) app.signIn();+ const doc = app.loadDocument();+ await app.receive(doc, "startup");+ if (after) app.signIn();+ const pending = doc.inbox.getSnapshot();+ assert.ok(pending);+ if (before) doc.inbox.bind(pending.id, "draft");+ const live = before || after;+ app.signOut();+ assert.equal(doc.inbox.getSnapshot(), live ? null : pending);+ assert.deepEqual(app.cleared, live ? [pending.id] : []);+ assert.equal(app.notices.length, live ? 1 : 0);+ app.storage.clear();+ app.signOut();+ app.signIn();+ assert.equal(doc.inbox.getSnapshot(), live ? null : pending);+ assert.equal(app.notices.length, live ? 1 : 0);+ if (live) {+ assert.equal(app.notices[0].message, "Run settings import cancelled");+ assert.match(+ app.notices[0].description ?? "",+ /session.*Reopen the link/is,+ );+ }+ doc.dispose();+ const reloaded = app.loadDocument();+ if (desktop) {+ const replay = reloaded.receiver.receiveSharedRunConfigUrls(+ [run],+ "startup",+ );+ assert.equal(replay, "ignored");+ }+ await reloaded.receiver.receiveStartupRunConfigUrl();+ assert.equal(reloaded.inbox.getSnapshot(), null);+ assert.equal(app.parserLoads(), 1);+ if (desktop) {+ await app.receive(doc);+ assert.equal(nParallel(doc), 3);+ assert.notEqual(doc.inbox.getSnapshot()?.id, pending.id);+ }+ window.location.href = browserRun;+ const reopened = desktop ? reloaded : app.loadDocument();+ await app.receive(reopened);+ assert.equal(nParallel(reopened), 3);+ assert.deepEqual(app.errors, []);+ });+}++const argsQuery = "llamaExtraArgs=%5B%22--threads%22%2C%224%22%5D";+// Valid and invalid startup fragments are consumed so dismissal, reload or+// router re-decoding cannot replay them.+for (const [url, cleaned, valid, decode] of [+ ["?run=1&keep=value#run?v=1&nParallel=3", "?keep=value", true, false],+ ["?keep=value#run?v=1&unknown=true", "?keep=value", false, false],+ ["?run=2&keep=value#run", "?run=2&keep=value", false, false],+ ["?run=1#run?v=1&selectedGpuIds=%5B0%5D", "", true, true],+ [`?run=1#run?v=1&${argsQuery}`, "", true, true],+ ["?run=1#run?v=1&selectedGpuIds=%5B1%2C1%5D", "", false, true],+] as const) {+ test(`startup consumes ${url} once (router decoding: ${decode})`, async () => {+ const app = sessionHarness({ url: `http://localhost/chat${url}` });+ const doc = app.loadDocument();+ if (decode) {+ window.location.href = window.location.href.replace(+ /%5B|%5D|%7B|%7D/gi,+ decodeURIComponent,+ );+ }+ await doc.receiver.receiveStartupRunConfigUrl();+ assert.equal(window.location.href, `http://localhost/chat${cleaned}`);+ const pending = doc.inbox.getSnapshot();+ assert.equal(pending?.replaceHistory, valid || undefined);+ assert.equal(app.errors.length, valid ? 0 : 1);+ doc.inbox.clear(pending?.id);+ doc.dispose();+ const reloaded = app.loadDocument();+ await reloaded.receiver.receiveStartupRunConfigUrl();+ assert.equal(reloaded.inbox.getSnapshot(), null);+ assert.equal(app.errors.length, valid ? 0 : 1);+ });+}++test("desktop startup ignores web fragments and still accepts native links", async () => {+ const app = sessionHarness({+ url: "tauri://localhost/chat#run?v=1&model=owner/model&nParallel=4",+ desktop: true,+ });+ const doc = app.loadDocument();+ await doc.receiver.receiveStartupRunConfigUrl();+ assert.equal(doc.inbox.getSnapshot(), null);+ for (const url of [browserRun, "unsloth://open_from_hf?model=owner/other"]) {+ assert.equal(doc.receiver.receiveSharedRunConfigUrls([url]), false);+ }+ const urls = [run, "unsloth://unrelated"];+ assert.equal(doc.receiver.receiveSharedRunConfigUrls(urls), true);+ await settle();+ assert.deepEqual(+ [nParallel(doc), doc.inbox.getSnapshot()?.replaceHistory, app.errors],+ [3, false, []],+ );+});++// A parser still loading when the session or a newer link moves on must not+// restore its link; edits made while it loads carry into model resolution.+const newerRun = "unsloth://run?v=1&model=owner/newer&nParallel=4";+const newerHub = "unsloth://open_from_hf?model=owner/newer";+for (const [name, native, signIn, during, model] of [+ ["a newer run link wins", false, true, newerRun, "owner/newer"],+ ["a newer hub link wins", false, true, newerHub, null],+ ["sign-out retires the load", true, true, "relogin", null],+ ["web edits survive", false, true, null, "owner/model"],+ ["desktop edits survive", true, true, null, "owner/model"],+ ["a pre-login link survives", false, false, "relogin", "owner/model"],+] as const) {+ test(`a delayed parser: ${name}`, async () => {+ const parser = deferred<typeof links>();+ const app = sessionHarness({+ desktop: native,+ loadParser: () => parser.promise,+ });+ if (signIn) app.signIn();+ const doc = app.loadDocument();+ doc.receiver.cancelRunConfigImportForEdit("older-draft");+ const intake = native+ ? doc.receiver.receiveSharedRunConfigUrls([run])+ : doc.receiver.receiveStartupRunConfigUrl();+ if (native) assert.equal(intake, true);+ else assert.equal(window.location.href, "http://localhost/chat");+ assert.equal(doc.inbox.getSnapshot(), null);+ doc.receiver.cancelRunConfigImportForEdit("edited-draft");+ if (during === "relogin") {+ app.signOut();+ app.signIn();+ } else if (during) doc.receiver.receiveSharedRunConfigUrls([during]);+ parser.resolve(links);+ await intake;+ await settle();+ assert.equal(doc.inbox.getSnapshot()?.value.model ?? null, model);+ assert.equal(doc.inbox.wasEdited("edited-draft"), model === "owner/model");+ assert.equal(doc.inbox.wasEdited("older-draft"), false);+ assert.deepEqual(app.errors, []);+ });+}++test("a failed parser chunk reports an error and permits reopening the same native link", async () => {+ const parser = deferred<typeof links>();+ let retry = false;+ const app = sessionHarness({+ desktop: true,+ loadParser: () => (retry ? links : parser.promise),+ });+ app.signIn();+ const doc = app.loadDocument();+ await app.receive(doc);+ parser.reject(new Error("Chunk unavailable"));+ await settle();+ assert.equal(app.errors.length, 1);+ assert.equal(doc.inbox.getSnapshot(), null);+ retry = true;+ await app.receive(doc);+ assert.equal(nParallel(doc), 3);+});diff --git a/studio/frontend/tests/share-run-configs.security.test.ts b/studio/frontend/tests/share-run-configs.security.test.tsnew file mode 100644index 00000000000..cf880db8903--- /dev/null+++ b/studio/frontend/tests/share-run-configs.security.test.ts@@ -0,0 +1,749 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++import assert from "node:assert/strict";+import test from "node:test";+import type { DeepLinkHandler as Handler } from "../src/features/deep-links/deep-link-handler.tsx";+import { createDeepLinkIntentGate } from "../src/features/deep-links/deep-link-intent.ts";+import { parseUnslothDeepLink } from "../src/features/deep-links/parse-deep-link.ts";+import { MAX_RUN_CONFIG_URL_LENGTH } from "../src/features/model-picker/sharing/inbox.ts";+import {+ installLocalStorageFake,+ registerBundlerResolver,+} from "./helpers/kit.ts";+import { loadWithStubs } from "./helpers/module-stubs.ts";++registerBundlerResolver();+installLocalStorageFake();++const { createRunConfigLink, parseRunConfigLink } = await import(+ "./helpers/sharing-links.ts"+);+const { sharedExtraArgsError, validSharedExtraArgs } = await import(+ "../src/features/model-picker/sharing/extra-args.ts"+);+const { diagnoseExtraArgs, extraArgsAreLoadable, formatExtraArgs } =+ await import("../src/features/model-picker/model-config/llama-extra-args.ts");+const { SHARED_CONFIG_KEYS, mergeSharedRunConfig } = await import(+ "../src/features/model-picker/sharing/fields.ts"+);+const { DEFAULT_PER_MODEL_CONFIG } = await import(+ "../src/features/model-picker/model-config/per-model-config.ts"+);+const { receiverHarness, settle } = await import(+ "./helpers/sharing-receiver.ts"+);++const prefixes = ["unsloth://run?v=1&", "http://localhost:8888/chat#run?v=1&"];+const browser = "http://localhost:8888/chat";+const long = "a".repeat(MAX_RUN_CONFIG_URL_LENGTH);+const query = (key: string, value: unknown) =>+ new URLSearchParams({+ nParallel: "2",+ [key]: JSON.stringify(value),+ }).toString();+const params = (key: string, value: string) =>+ new URLSearchParams({ [key]: value }).toString();+const args = (list: unknown) => query("llamaExtraArgs", list);+const valid = (config: object) => ({ kind: "valid", value: { config } });++function rejects(query: string) {+ for (const prefix of prefixes) {+ const result = parseRunConfigLink(`${prefix}${query}`);+ assert.equal(result.kind, "invalid", `${prefix}${query}`);+ assert.equal(Object.hasOwn(result, "value"), false);+ }+}++function roundTrips(+ value: Parameters<typeof createRunConfigLink>[0],+ base?: string,+) {+ const url = createRunConfigLink(value, base);+ assert.deepEqual(parseRunConfigLink(url), { kind: "valid", value });+ return url;+}++const fullConfig: Omit<+ typeof DEFAULT_PER_MODEL_CONFIG,+ "chatTemplateOverride" | "tensorSplit" | "maxSeqLength" | "mlxKvQuant"+> = {+ customContextLength: 32768,+ kvCacheDtype: "q8_0",+ speculativeType: "dspark",+ specDraftNMax: 8,+ specDraftCacheDtype: "q4_0",+ nParallel: 4,+ reasoningBudget: 0,+ reasoningBudgetMessage: "",+ nBatch: 2048,+ nUbatch: 512,+ loadMode: "mmap+mlock",+ ctxCheckpoints: 0,+ cacheRam: -1,+ tensorParallel: true,+ disableVision: false,+ llamaExtraArgs: [+ "--rope-scaling",+ "yarn",+ "--flash-attn",+ "on",+ "--no-warmup",+ ],+ gpuMemoryMode: "manual",+ gpuLayers: 0,+ nCpuMoe: 0,+ selectedGpuIds: [1, 0],+ selectedGpuIndexKind: "physical",+};++const sensitiveFlags = [+ "--model",+ "-m",+ "--model-url",+ "--hf-repo",+ "--hf-token",+ "--model-draft",+ "--spec-draft-model",+ "--spec-draft-hf",+ "--mmproj",+ "--mmproj-url",+ "--lora",+ "--lora-scaled",+ "--control-vector",+ "--control-vector-scaled",+ "--rpc",+ "--rpc-server",+ "--host",+ "--port",+ "--api-key",+ "--api-key-file",+ "--ssl-key-file",+ "--ssl-cert-file",+ "--path",+ "--media-path",+ "--log-file",+ "--logdir",+ "--log-disable",+ "--slot-save-path",+ "--prompt-cache",+ "--prompt-cache-all",+ "--file",+ "-f",+ "--grammar-file",+ "--grammar",+ "--json-schema",+ "--json-schema-file",+ "--chat-template",+ "--chat-template-file",+ "--chat-template-kwargs",+ "--jinja",+ "--tools",+ "--agent",+ "-ag",+ "--tools-runtime",+ "--mcp-servers-json",+ "--mcp-servers-config",+ "--ui-mcp-proxy",+ "--webui-config-file",+ "--cors-origins",+ "--cors-credentials",+ "--models-dir",+ "--models-preset",+ "--models-autoload",+ "--device",+ "--override-tensor",+ "--props",+ "--slots",+ "--metrics",+ "--help",+ "--completion-bash",+ "--new-unknown-option",+];++test("link addresses: case-insensitive native hosts, one exact version, empty and unrelated links", () => {+ const value = { model: "owner/model", config: { nParallel: 3 } };+ for (const address of ["unsloth://run", "UnSlOtH://RuN"]) {+ const url = createRunConfigLink(value).replace("unsloth://run", address);+ assert.deepEqual(parseRunConfigLink(url), { kind: "valid", value });+ assert.equal(parseRunConfigLink(`${url}#ignored`).kind, "invalid");+ assert.deepEqual(+ parseRunConfigLink(`${url}&reasoningBudgetMessage=${long}`),+ { kind: "invalid", error: "This run configuration link is too long." },+ );+ assert.equal(+ parseRunConfigLink(`${address.slice(0, -3)}hub?model=owner/model`).kind,+ "unrelated",+ );+ }+ for (const prefix of ["unsloth://run", "https://example.com/chat#run"]) {+ assert.deepEqual(parseRunConfigLink(`${prefix}?nParallel=3`), {+ kind: "invalid",+ error: "This run configuration link is missing its version.",+ });+ for (const query of ["v=2", "v=1&%76=1"]) {+ assert.equal(parseRunConfigLink(`${prefix}?${query}`).kind, "invalid");+ }+ assert.deepEqual(+ parseRunConfigLink(`${prefix}?nParallel=3&v=1`),+ valid({ nParallel: 3 }),+ );+ }+ for (const url of ["unsloth://run/?v=1", `${browser}#run?v=1`]) {+ assert.deepEqual(parseRunConfigLink(url), valid({}));+ }+ for (const url of ["invalid", `https://example.com/chat?unrelated=${long}`]) {+ assert.equal(parseRunConfigLink(url).kind, "unrelated");+ }+});++test("every field, the complete payload and safe identities round-trip in browser and desktop links", () => {+ assert.deepEqual(+ Object.keys(fullConfig).sort(),+ [...SHARED_CONFIG_KEYS].sort(),+ );+ for (const value of [+ ...SHARED_CONFIG_KEYS.map((key) => ({+ config: { [key]: fullConfig[key] },+ })),+ {+ model: "unsloth/Model-GGUF",+ ggufVariant: "Q4_K_M/model-00001-of-00002.gguf",+ config: fullConfig,+ },+ ]) {+ for (const base of [+ undefined,+ "http://localhost:8888/hub?token=private#old",+ "https://unsloth.example/chat",+ ]) {+ assert.ok(!roundTrips(value, base).includes("token=private"));+ }+ }+ roundTrips({ ggufVariant: "weights/model .gguf", config: {} });+});++test("GPU splits stay local, and importing a different GPU selection or automatic placement clears them", () => {+ const config = { tensorSplit: [3, 1], nParallel: 2 };+ assert.deepEqual(+ parseRunConfigLink(createRunConfigLink({ config })),+ valid({ nParallel: 2 }),+ );+ const current = {+ ...DEFAULT_PER_MODEL_CONFIG,+ ...fullConfig,+ selectedGpuIds: [0, 1],+ tensorSplit: [3, 1],+ };+ const split = (patch: object) =>+ mergeSharedRunConfig(current, patch).tensorSplit;+ for (const patch of [+ { selectedGpuIds: [1, 0] },+ { selectedGpuIndexKind: null },+ { gpuMemoryMode: "auto" },+ { gpuLayers: -1 },+ ]) {+ assert.equal(split(patch), null, JSON.stringify(patch));+ }+ for (const patch of [+ { nParallel: 2 },+ { selectedGpuIds: [0, 1] },+ { selectedGpuIds: undefined },+ ]) {+ assert.deepEqual(split(patch), [3, 1], JSON.stringify(patch));+ }+ assert.deepEqual(current.tensorSplit, [3, 1]);+});++test("invalid, smuggled, malformed or path-like input never produces a partial configuration", () => {+ const queries = [+ "customContextLength=4096&maxSeqLength=8192",+ "nParallel=2&nParallel=3",+ "hfToken=secret",+ "nParallel=0",+ "nParallel=2.5",+ "nParallel=%222%22",+ "tensorParallel=null",+ "selectedGpuIds=[1,1]",+ "selectedGpuIds=[]",+ "llamaExtraArgs=[3]",+ "reasoningBudgetMessage=null",+ "chatTemplateOverride=",+ "nParallel=2&%6eParallel=3",+ "nParallel=2&=3",+ "reasoningBudgetMessage=%",+ "reasoningBudgetMessage=%C0%AF",+ query("__proto__", { polluted: true }),+ args([["--threads", "4"]]),+ query("nParallel", { valueOf: 2 }),+ ...[+ "/etc/passwd",+ "weights/../model.gguf",+ "weights./model.gguf",+ "nul .gguf",+ "Q4_K_M\n",+ "a".repeat(256),+ ].map((variant) => params("ggufVariant", variant)),+ ...["_owner/model", "owner/repo.git", "https://attacker.invalid/model"].map(+ (model) => params("model", model),+ ),+ ];+ for (const query of queries) rejects(query);+ for (const url of [+ "unsloth://run/extra?v=1",+ "unsloth://user@run?v=1",+ "unsloth://run:80?v=1",+ "unsloth://run?v=1&nParallel=\t2",+ "https://user:pass@localhost/chat#run?v=1",+ ]) {+ assert.equal(parseRunConfigLink(url).kind, "invalid", url);+ }+ const merged = mergeSharedRunConfig(+ DEFAULT_PER_MODEL_CONFIG,+ JSON.parse('{"__proto__":{"polluted":true},"command":"x","nParallel":2}'),+ );+ assert.equal(Object.getPrototypeOf(merged), Object.prototype);+ assert.equal(Object.hasOwn(merged, "command"), false);+ assert.equal(Object.hasOwn(Object.prototype, "polluted"), false);+ assert.equal(merged.nParallel, 2);+});++test("generation enforces bounded sizes and the same restrictions as receiving a link", () => {+ for (const config of [+ { nBatch: Number.NaN },+ { llamaExtraArgs: ["--host", "x"] },+ { reasoningBudgetMessage: "\u{1F9A5}".repeat(2049) },+ ]) {+ assert.throws(() => createRunConfigLink({ config }));+ }+ for (const ggufVariant of ["C:/model.gguf", "COM1 .gguf"]) {+ assert.throws(() => createRunConfigLink({ ggufVariant, config: {} }));+ }+ for (const base of ["file:///index.html", "https://user:[email protected]/"]) {+ assert.throws(() => createRunConfigLink({ config: {} }, base));+ }+});++test("invalid field values use readable labels for malformed and decoded input", () => {+ const error = "The setting “KV cache type” is invalid.";+ for (const prefix of prefixes) {+ for (const value of ["unsupported", "%22unterminated"]) {+ assert.deepEqual(parseRunConfigLink(`${prefix}kvCacheDtype=${value}`), {+ kind: "invalid",+ error,+ });+ }+ for (const value of ["", "%22%22"]) {+ assert.deepEqual(+ parseRunConfigLink(`${prefix}reasoningBudgetMessage=${value}`),+ valid({ reasoningBudgetMessage: "" }),+ );+ }+ }+});++test("sensitive and unknown flags are rejected in every spelling and encoding", () => {+ for (const flag of sensitiveFlags) {+ for (const spelling of [+ flag,+ flag.replaceAll("-", "_"),+ `${flag}=x`,+ `${flag} x`,+ ]) {+ rejects(args([spelling, "x"]));+ rejects(args(["--threads", "4", spelling]));+ }+ const json = JSON.stringify([flag, "x"]);+ for (const variant of [+ encodeURIComponent(json).replaceAll("-", "%2d"),+ encodeURIComponent(JSON.stringify([encodeURIComponent(flag), "x"])),+ encodeURIComponent(json.replaceAll("-", "\\u002d")),+ encodeURIComponent(encodeURIComponent(json)),+ ]) {+ rejects(`nParallel=2&llamaExtraArgs=${variant}`);+ }+ }+});++test("only exact argument boundaries and bounded inference values are accepted", () => {+ for (const argv of [+ ["--threads", "4.0"],+ ["--threads", "4", "orphan"],+ ["--no-warmup", "x"],+ ["--threads", "-2"],+ ["--threads", "0x4"],+ ["-c", "127"],+ ["--flash-attn", "on --agent"],+ ["--cache-type-k", "q8_0;whoami"],+ ["--tensor-split", "0,0"],+ ["--tensor-split", Array(257).fill("1").join(",")],+ ["--temperature", "101"],+ ["-t4"],+ ]) {+ rejects(args(argv));+ }+ for (const argv of [+ [],+ ["-t", "-1", "-c", "0", "--seed", "-1", "--top-p", "0.95"],+ ["--no-warmup", "--flash-attn", "auto", "-ts", "3,1.5,0", "-ngl", "-1"],+ ["-s", "4294967295", "--threads_batch", "4", "--cache_type_k", "q8_0"],+ ]) {+ roundTrips({ config: { llamaExtraArgs: argv } });+ }+});++test("sharing diagnostics identify the offending option without exposing its value", () => {+ const unexpected = "Extra arguments contain an unexpected token.";+ for (const [argv, message] of [+ [["-ts", "1,1"], null],+ [["--threads"], "--threads requires a value."],+ [["--threads", "1025"], "--threads has an invalid or unsupported value."],+ [+ ["-ts", "1,1", "--tensor-split", "2,1"],+ "--tensor-split is specified more than once.",+ ],+ [["--threads=4"], "Write --threads and its value as two arguments."],+ [["--no-warmup=true"], "--no-warmup does not take a value."],+ [["x"], unexpected],+ [[" --threads"], unexpected],+ [[`--${"x".repeat(1000)}`], unexpected],+ ] as const) {+ assert.equal(sharedExtraArgsError([...argv]), message);+ }+ for (const flag of sensitiveFlags) {+ assert.equal(+ sharedExtraArgsError(["--threads", "4", `${flag}=C:\\key`]),+ `${flag} is not supported in shared links.`,+ );+ }+});++test("shared arguments use upstream diagnostics offline without letting normalization bypass the allowlist", () => {+ for (const argv of [+ ["--batch-size", "1"],+ ["-ncmoe", "1.5"],+ ]) {+ const diagnostics = diagnoseExtraArgs(formatExtraArgs(argv), null);+ assert.equal(extraArgsAreLoadable(diagnostics), false);+ const upstreamError = diagnostics.find((item) => item.level === "error");+ assert.equal(sharedExtraArgsError(argv), upstreamError?.message);+ rejects(args(argv));+ }+ const loadable = ["--chat_template", "{{ x }}"];+ assert.equal(+ extraArgsAreLoadable(diagnoseExtraArgs(formatExtraArgs(loadable), null)),+ true,+ );+ const sparse = new Array<string>(3);+ sparse[0] = "--threads";+ sparse[2] = "4";+ for (const argv of [loadable, sparse, [1], "--threads 4"]) {+ assert.equal(validSharedExtraArgs(argv), false);+ }+});++test("templates and custom reasoning messages cannot enter links or clear a recipient's own", () => {+ const recipient = {+ ...DEFAULT_PER_MODEL_CONFIG,+ chatTemplateOverride: "Mine",+ };+ for (const template of [null, "{{ x }}"]) {+ rejects(query("chatTemplateOverride", template));+ rejects(args(["--chat-template", template]));+ const config = { nParallel: 2, chatTemplateOverride: template };+ for (const base of [undefined, browser]) {+ assert.deepEqual(+ parseRunConfigLink(createRunConfigLink({ config }, base)),+ valid({ nParallel: 2 }),+ );+ }+ assert.equal(+ mergeSharedRunConfig(recipient, config).chatTemplateOverride,+ "Mine",+ );+ }+ for (const message of ["<script>alert(1)</script>", "Review\u200bthis"]) {+ for (const base of [undefined, browser]) {+ assert.throws(+ () =>+ createRunConfigLink(+ { config: { reasoningBudgetMessage: message } },+ base,+ ),+ /Custom reasoning messages/,+ );+ const prefix = base ? `${base}#run?` : "unsloth://run?";+ for (const text of [message, JSON.stringify(message)]) {+ const encoded = encodeURIComponent(text);+ assert.equal(+ parseRunConfigLink(`${prefix}v=1&reasoningBudgetMessage=${encoded}`)+ .kind,+ "invalid",+ );+ }+ }+ }+});++const hub = "unsloth://open_from_hf?model=owner/model";+const run = "unsloth://run?v=1&model=owner/model&nParallel=3";+const invalid =+ "unsloth://run?v=1&llamaExtraArgs=%5B%22--host%22%2C%220.0.0.0%22%5D";++function desktopSession() {+ const values = new Map<string, string>();+ const storage = {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => values.set(key, value),+ };+ Object.assign(globalThis, { sessionStorage: storage });+ return storage;+}++function harness(sharedLinks = true) {+ const { inbox, errors, receiver } = receiverHarness({ desktop: true });+ const navigations: {+ to: string;+ search: { model: string; intent: number };+ }[] = [];+ const commands: string[] = [];+ const counts = { subscriptions: 0, unsubscriptions: 0 };+ let listener: ((urls: string[]) => void) | undefined;+ let cleanup: (() => void) | undefined;+ let releaseStartup!: (urls: string[] | null) => void;+ const startup = new Promise<string[] | null>((resolve) => {+ releaseStartup = resolve;+ });+ const { DeepLinkHandler } = loadWithStubs<{+ DeepLinkHandler: typeof Handler;+ }>(+ new URL(+ "../src/features/deep-links/deep-link-handler.tsx",+ import.meta.url,+ ),+ {+ "@/lib/api-base": { isTauri: true },+ "@tanstack/react-router": {+ useNavigate: () => async (to: (typeof navigations)[number]) =>+ navigations.push(to),+ },+ react: { useEffect: (effect: () => () => void) => (cleanup = effect()) },+ "./deep-link-intent": { createDeepLinkIntentGate },+ "./parse-deep-link": { parseUnslothDeepLink },+ "@tauri-apps/api/core": {+ invoke: async (command: string) => commands.push(command),+ },+ "@tauri-apps/plugin-deep-link": {+ getCurrent: () => startup,+ onOpenUrl: async (callback: typeof listener) => {+ counts.subscriptions += 1;+ listener = callback;+ return () => (counts.unsubscriptions += 1);+ },+ },+ },+ );+ DeepLinkHandler(+ sharedLinks ? { onOpenUrls: receiver.receiveSharedRunConfigUrls } : {},+ );+ return {+ inbox,+ navigations,+ commands,+ errors,+ counts,+ releaseStartup,+ emit: (urls: string[]) => {+ assert.ok(listener);+ listener(urls);+ },+ cleanup: () => cleanup?.(),+ };+}++async function started(startup: string[] | null, sharedLinks = true) {+ const app = harness(sharedLinks);+ await settle();+ app.releaseStartup(startup);+ await settle();+ return app;+}++for (const [delivery, url] of [+ ["startup", run],+ ["live", invalid],+] as const) {+ test(`a ${delivery} run link is not replayed by a later desktop document but a new event is: ${url}`, async () => {+ desktopSession();+ const accepted = (app: ReturnType<typeof harness>) => {+ assert.deepEqual(app.commands, ["reveal_main_window"]);+ assert.equal(app.errors.length, url === invalid ? 1 : 0);+ assert.equal(app.inbox.getSnapshot() !== null, url === run);+ app.cleanup();+ };+ const before = await started(delivery === "startup" ? [url] : null);+ if (delivery === "live") before.emit([url]);+ await settle();+ accepted(before);+ const after = await started([hub, url]);+ assert.equal(after.inbox.getSnapshot(), null);+ assert.deepEqual(+ [after.navigations, after.commands, after.errors],+ [[], [], []],+ );+ after.emit([url]);+ await settle();+ accepted(after);+ });+}++test("a different startup link, a fresh desktop session and blocked session storage still open run links", async (t) => {+ desktopSession();+ (await started([run])).cleanup();+ for (const [reset, nParallel] of [+ [false, 4],+ [true, 3],+ ["blocked", 3],+ ] as const) {+ if (reset) {+ const storage = desktopSession();+ if (reset === "blocked") {+ for (const method of ["getItem", "setItem"] as const) {+ t.mock.method(storage, method, () => {+ throw new Error("Storage blocked");+ });+ }+ }+ }+ const app = await started([run.replace("=3", `=${nParallel}`)]);+ assert.equal(app.inbox.getSnapshot()?.value.config.nParallel, nParallel);+ assert.deepEqual(app.commands, ["reveal_main_window"]);+ assert.deepEqual(app.errors, []);+ app.cleanup();+ }+});++for (const sharedLinks of [false, true]) {+ test(`Hub links keep routing and deduplication with sharing ${sharedLinks ? "enabled; a rejected run link retires the duplicate without resetting its sequence" : "absent"}`, async () => {+ const app = await started([hub], sharedLinks);+ for (const url of [hub, "https://example.invalid/unrelated", hub]) {+ app.emit([url]);+ }+ await settle();+ assert.deepEqual(+ app.navigations.map(({ to, search }) => [to, search.model]),+ [["/hub", "owner/model"]],+ );+ assert.equal(app.inbox.getSnapshot(), null);+ assert.deepEqual(app.commands, ["reveal_main_window"]);+ if (sharedLinks) {+ app.emit([invalid]);+ await settle();+ app.emit([hub]);+ await settle();+ assert.equal(app.navigations.length, 2);+ assert.equal(+ app.navigations[1].search.intent,+ app.navigations[0].search.intent + 1,+ );+ assert.equal(app.errors.length, 1);+ }+ app.cleanup();+ assert.deepEqual(app.counts, { subscriptions: 1, unsubscriptions: 1 });+ });+}++test("the newest recognized intent wins in mixed native batches, and web fragments never replace a pending native intent", async () => {+ const app = await started(null);+ app.emit([hub, run]);+ await settle();+ assert.equal(app.navigations.length, 0);+ const pending = app.inbox.getSnapshot();+ assert.equal(pending?.value.config.nParallel, 3);+ for (const url of [+ "https://example.invalid/chat#run?v=1&model=owner/other&nParallel=4",+ "http://localhost/chat#run?v=1&unknown=true",+ ]) {+ app.emit([url]);+ assert.equal(app.inbox.getSnapshot(), pending);+ }+ app.emit([run, hub]);+ assert.equal(app.navigations.length, 1);+ assert.equal(app.inbox.getSnapshot(), null);+ app.emit([run]);+ await settle();+ app.emit([hub, "https://example.invalid/chat#run?v=1&nParallel=4"]);+ assert.equal(app.inbox.getSnapshot(), null);+ assert.equal(app.navigations.length, 2);+ app.emit([hub, invalid]);+ await settle();+ assert.equal(app.navigations.length, 2);+ assert.equal(app.errors.length, 1);+ app.cleanup();+});++test("live shared links supersede delayed desktop startup URLs and disposal ignores later events", async () => {+ const app = harness();+ await settle();+ app.emit([run]);+ await settle();+ const pending = app.inbox.getSnapshot();+ app.releaseStartup([hub]);+ await settle();+ app.cleanup();+ app.emit([hub]);+ app.emit([invalid]);+ await settle();+ assert.equal(app.inbox.getSnapshot(), pending);+ assert.equal(app.navigations.length, 0);+ assert.deepEqual(app.errors, []);+ assert.deepEqual(app.counts, { subscriptions: 1, unsubscriptions: 1 });+});++test("10,000 deterministic adversarial inputs reject against independent expectations", () => {+ let seed = 0x5eed;+ const next = () => {+ seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0;+ return seed;+ };+ const prototypes = Object.getOwnPropertyDescriptors(Object.prototype);+ const hostile = [";", "\\", "/", "\n", "\u0000", "\u202e", "$", "`", " "];+ const mutations = [+ () =>+ query("llamaExtraArgs", [+ "--threads",+ `${1 + (next() % 1024)}${hostile[next() % hostile.length]}`,+ ]),+ () =>+ query("llamaExtraArgs", [+ sensitiveFlags[next() % sensitiveFlags.length],+ String(next()),+ ]),+ () => new URLSearchParams({ nParallel: String(65 + next()) }).toString(),+ () => new URLSearchParams({ model: `owner/../model${next()}` }).toString(),+ () =>+ new URLSearchParams({ ggufVariant: `../model${next()}.gguf` }).toString(),+ () => `nParallel=2&%6eParallel=${1 + (next() % 64)}`,+ () => query("__proto__", { polluted: next() }),+ () =>+ query("llamaExtraArgs", [+ "-t",+ "4",+ "--threads",+ String(1 + (next() % 1024)),+ ]),+ () =>+ new URLSearchParams({+ customContextLength: "4096",+ maxSeqLength: String(4097 + (next() % 1000)),+ }).toString(),+ () => query("tensorParallel", { value: next() }),+ ];+ for (let index = 0; index < 10_000; index += 1) {+ rejects(mutations[index % mutations.length]());+ }+ assert.deepEqual(+ Object.getOwnPropertyDescriptors(Object.prototype),+ prototypes,+ );+});