Open-source manufacturing ERP, MES and QMS. Quoting, MRP, inventory, shop floor, quality and lot/serial traceability on one Postgres schema, with a REST API and MCP server. Self-host or use Carbon Cloud.
TypeScript ai-agentsbill-of-materialserpinventory-managementleanmanufacturingmanufacturing-execution-systemmcp-servermesmrpopen-source-erppostgresqlproduction-planningqmsquality-management-systemreact-routerself-hostedsupabasetraceabilitytypescript
feat(items): resume a CAD upload a reload cut off, under its own path (#1954)
Sid6846be3fa409
diff --git a/apps/erp/app/components/CadModel.tsx b/apps/erp/app/components/CadModel.tsxindex 0c6d4aea59..7f4e76a7ed 100644--- a/apps/erp/app/components/CadModel.tsx+++ b/apps/erp/app/components/CadModel.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";-import { convertKbToString, TEMP_STAGING_BUCKET } from "@carbon/files";+import { convertKbToString } from "@carbon/files";import { supportedModelTypes } from "@carbon/files/cad";import { useAction, useRevalidator } from "@carbon/query";import {@@ -30,7 +30,6 @@ import { ModelPreview } from "@carbon/viewer/model-preview";import { OptimizeProgress } from "@carbon/viewer/optimize-progress";import { useOptimizedModel } from "@carbon/viewer/use-optimized-model";import { Trans, useLingui } from "@lingui/react/macro";-import { nanoid } from "nanoid";import { useState } from "react";import { useDropzone } from "react-dropzone";import { LuBox, LuCloudUpload, LuRefreshCw, LuZap } from "react-icons/lu";@@ -39,7 +38,8 @@ import type { ModelUpload } from "~/types";import type { ViewDirection } from "~/utils/model-thumbnail";import { regenerateModelThumbnail } from "~/utils/model-thumbnail";import { getPrivateUrl, getRawModelUrl, path } from "~/utils/path";-import { UploadProgress } from "./UploadProgress";+import type { InterruptedUpload } from "~/utils/resumable-upload";+import { InterruptedUploadNotice, UploadProgress } from "./UploadProgress";const SIZE_LIMIT = getFileSizeLimit("CAD_MODEL_UPLOAD");@@ -83,7 +83,14 @@ const CadModel = ({const mode = useMode();const { carbon } = useCarbon();const revalidator = useRevalidator();- const { upload, runUpload } = useModelUpload();+ // What the model is for, so an upload a reload cut off is offered back here.+ const uploadScope =+ Object.entries(metadata ?? {})+ .filter(([, id]) => id)+ .map(([key, id]) => `${key}:${id}`)+ .join(",") || "cad";+ const { upload, runUpload, interrupted, dismissInterrupted } =+ useModelUpload(uploadScope);const fetcher = useAction();const [file, setFile] = useState<File | null>(null);@@ -197,8 +204,6 @@ const CadModel = ({);const onFileChange = async (file: File | null) => {- const modelId = nanoid();-setFile(file);if (file) {@@ -206,19 +211,17 @@ const CadModel = ({toast.error("Failed to initialize carbon client");return;}- const fileExtension = file.name.split(".").pop();- const fileName = `${companyId}/models/${modelId}.${fileExtension}`;-// Raw CAD lands in `temp-staging` (2.5 GB cap) via a resumable (TUS) upload// — a standard buffered upload times out on multi-GB files. The// optimise/assembly jobs read it from there and write the gated artifacts- // (<=50 MB) to `private`.+ // (<=50 MB) to `private`. The id and path are the upload's: a resumed+ // upload keeps its own.const toastId = toast.loading(`Uploading ${file.name}…`);- const { error: uploadError } = await runUpload({- bucket: TEMP_STAGING_BUCKET,- path: fileName,- file- });+ const {+ error: uploadError,+ modelId,+ modelPath: fileName+ } = await runUpload(file);if (uploadError) {toast.error("Failed to upload file to storage", { id: toastId });setFile(null);@@ -432,6 +435,8 @@ const CadModel = ({isReadOnly={isReadOnly}titleExtras={titleExtras}onFileChange={onFileChange}+ interrupted={interrupted}+ onDismissInterrupted={dismissInterrupted}/>);}}@@ -448,6 +453,8 @@ type CadModelUploadProps = {className?: string;isReadOnly?: boolean;onFileChange: (file: File | null) => void;+ interrupted?: InterruptedUpload | null;+ onDismissInterrupted?: () => void;};const CadModelUpload = ({@@ -456,7 +463,9 @@ const CadModelUpload = ({file,isReadOnly,className,- onFileChange+ onFileChange,+ interrupted,+ onDismissInterrupted}: CadModelUploadProps) => {const hasFile = !!file;const { isPhone } = useViewport();@@ -522,6 +531,15 @@ const CadModelUpload = ({</div>)}</div>+ {!isReadOnly && interrupted && onDismissInterrupted && (+ <div className="px-4 pb-3">+ <InterruptedUploadNotice+ name={interrupted.name}+ percent={interrupted.percent}+ onDismiss={onDismissInterrupted}+ />+ </div>+ )}</div>);}@@ -594,6 +612,14 @@ const CadModelUpload = ({<p className="text-xs text-muted-foreground group-hover:text-foreground">Supports {supportedModelTypes.join(", ")} files</p>+ {interrupted && onDismissInterrupted && (+ <InterruptedUploadNotice+ className="mt-4 max-w-md"+ name={interrupted.name}+ percent={interrupted.percent}+ onDismiss={onDismissInterrupted}+ />+ )}</>)}</div>diff --git a/apps/erp/app/components/UploadProgress.tsx b/apps/erp/app/components/UploadProgress.tsxindex b430c2ae12..7f3a1cab5b 100644--- a/apps/erp/app/components/UploadProgress.tsx+++ b/apps/erp/app/components/UploadProgress.tsx@@ -2,8 +2,10 @@// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,// including ports, remain AGPLv3; serving them over a network requires releasing their source.-import { BarProgress, cn } from "@carbon/react";-import { LuLoaderCircle } from "react-icons/lu";+import { BarProgress, Button, cn } from "@carbon/react";+import { RoundingMode, round } from "@carbon/utils";+import { Trans } from "@lingui/react/macro";+import { LuCircleAlert, LuLoaderCircle } from "react-icons/lu";function formatBytes(n: number): string {if (n >= 1024 ** 3) return `${(n / 1024 ** 3).toFixed(2)} GB`;@@ -56,3 +58,53 @@ export function UploadProgress({</div>);}++export type InterruptedUploadNoticeProps = {+ name: string;+ percent: number;+ onDismiss: () => void;+ className?: string;+};++/**+ * An upload a reload cut off. The browser cannot read the file again until the+ * user picks it, so this says to drop it again; the upload then continues where+ * it stopped. Rendered inside a drop zone, so Dismiss stops its click from+ * opening the file picker.+ */+export function InterruptedUploadNotice({+ name,+ percent,+ onDismiss,+ className+}: InterruptedUploadNoticeProps) {+ // Down, so it never claims more than was sent.+ const stopped = round(percent, 0, RoundingMode.Down);+ return (+ <div+ className={cn(+ "flex w-full items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-left text-xs text-muted-foreground",+ className+ )}+ >+ <LuCircleAlert className="h-3.5 w-3.5 shrink-0 text-primary" />+ <span className="min-w-0 flex-1">+ <Trans>+ The upload of{" "}+ <span className="font-medium text-foreground">{name}</span> stopped at{" "}+ {stopped}%. Drop the same file again to continue.+ </Trans>+ </span>+ <Button+ size="sm"+ variant="ghost"+ onClick={(event) => {+ event.stopPropagation();+ onDismiss();+ }}+ >+ <Trans>Dismiss</Trans>+ </Button>+ </div>+ );+}diff --git a/apps/erp/app/hooks/useModelUpload.ts b/apps/erp/app/hooks/useModelUpload.tsindex a3e68de23c..c5f38f0722 100644--- a/apps/erp/app/hooks/useModelUpload.ts+++ b/apps/erp/app/hooks/useModelUpload.ts@@ -3,8 +3,18 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";-import { useCallback, useState } from "react";-import { uploadModelResumable } from "~/utils/resumable-upload";+import { TEMP_STAGING_BUCKET } from "@carbon/files";+import { nanoid } from "nanoid";+import { useCallback, useEffect, useState } from "react";+import {+ findInterruptedUpload,+ forgetUpload,+ type InterruptedUpload,+ noteUploadProgress,+ noteUploadStarted,+ uploadModelResumable+} from "~/utils/resumable-upload";+import { useUser } from "./useUser";export type ModelUploadProgress = {percent: number;@@ -12,45 +22,91 @@ export type ModelUploadProgress = {total: number;};+export type ModelUploadResult = {+ error: unknown;+ /** The model's id: the uploaded file's name without its extension. */+ modelId: string;+ /** Where the file is in `temp-staging`. */+ modelPath: string;+};++function modelIdOf(path: string) {+ return path.slice(path.lastIndexOf("/") + 1).split(".")[0];+}+/**- * Shared resumable (TUS) model-upload logic — the single source of truth for- * every CAD upload surface (CadModel, PartForm, ToolForm). Owns the progress- * state (render it with `<UploadProgress {...upload} />`) and swallows the- * upload into a `{ error }` result so callers keep their existing flow.+ * Shared resumable (TUS) model upload for every CAD upload surface (CadModel,+ * PartForm, ToolForm). Owns the progress state (render it with+ * `<UploadProgress {...upload} />`) and returns `{ error, modelId, modelPath }`.+ *+ * The id and path come from the upload, not the caller: dropping a file whose+ * upload a reload cut off resumes that upload, under its own path. `scope`+ * names what the model is for (`item:<id>`, `new-part`, …); `interrupted` is+ * the upload a reload cut off there, so the page can say to drop it again.*/-export function useModelUpload() {+export function useModelUpload(scope: string) {const { accessToken } = useCarbon();+ const {+ company: { id: companyId }+ } = useUser();const [upload, setUpload] = useState<ModelUploadProgress | null>(null);+ const [interrupted, setInterrupted] = useState<InterruptedUpload | null>(+ null+ );++ useEffect(() => {+ let current = true;+ findInterruptedUpload(scope).then((found) => {+ if (current) setInterrupted(found);+ });+ return () => {+ current = false;+ };+ }, [scope]);const runUpload = useCallback(- async ({- bucket,- path,- file- }: {- bucket: string;- path: string;- file: File;- }): Promise<{ error: unknown }> => {+ async (file: File): Promise<ModelUploadResult> => {+ const extension = file.name.split(".").pop();+ let modelPath = `${companyId}/models/${nanoid()}.${extension}`;setUpload({ percent: 0, uploaded: 0, total: file.size });try {- await uploadModelResumable({+ ({ path: modelPath } = await uploadModelResumable({accessToken,- bucket,- path,+ bucket: TEMP_STAGING_BUCKET,+ path: modelPath,+ preferPath: interrupted?.path,file,- onProgress: (percent, uploaded, total) =>- setUpload({ percent, uploaded, total })- });- return { error: null };+ onStart: (path) => {+ modelPath = path;+ noteUploadStarted(scope, {+ path,+ name: file.name,+ size: file.size+ });+ },+ onProgress: (percent, uploaded, total) => {+ setUpload({ percent, uploaded, total });+ noteUploadProgress(modelPath, percent);+ }+ }));+ forgetUpload(modelPath);+ // A different file landed here instead: the old reminder no longer applies.+ if (interrupted) forgetUpload(interrupted.path);+ setInterrupted(null);+ return { error: null, modelId: modelIdOf(modelPath), modelPath };} catch (error) {- return { error };+ return { error, modelId: modelIdOf(modelPath), modelPath };} finally {setUpload(null);}},- [accessToken]+ [accessToken, companyId, interrupted, scope]);- return { upload, runUpload };+ const dismissInterrupted = useCallback(() => {+ if (interrupted) forgetUpload(interrupted.path);+ setInterrupted(null);+ }, [interrupted]);++ return { upload, runUpload, interrupted, dismissInterrupted };}diff --git a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx b/apps/erp/app/modules/items/ui/Parts/PartForm.tsxindex 02023d845c..5b44ac8271 100644--- a/apps/erp/app/modules/items/ui/Parts/PartForm.tsx+++ b/apps/erp/app/modules/items/ui/Parts/PartForm.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";-import { convertKbToString, TEMP_STAGING_BUCKET } from "@carbon/files";+import { convertKbToString } from "@carbon/files";import { supportedModelTypes } from "@carbon/files/cad";import { ValidatedForm } from "@carbon/form";import {@@ -24,7 +24,6 @@ import {import { getFileSizeLimit, INPUT_FORMAT } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { nanoid } from "nanoid";import { useEffect, useState } from "react";import { flushSync } from "react-dom";import { useDropzone } from "react-dropzone";@@ -46,7 +45,10 @@ import {UnitOfMeasure} from "~/components/Form";import { ReplenishmentSystemIcon } from "~/components/Icons";-import { UploadProgress } from "~/components/UploadProgress";+import {+ InterruptedUploadNotice,+ UploadProgress+} from "~/components/UploadProgress";import {useCompanySettings,useCurrencyDecimals,@@ -87,7 +89,8 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {const [modelIsUploading, setModelIsUploading] = useState(false);const [modelFile, setModelFile] = useState<File | null>(null);const { carbon } = useCarbon();- const { upload, runUpload } = useModelUpload();+ const { upload, runUpload, interrupted, dismissInterrupted } =+ useModelUpload("new-part");const {company: { id: companyId },id: userId@@ -99,18 +102,15 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {setModelIsUploading(true);});- const modelId = nanoid();- const fileExtension = file.name.split(".").pop();- const fileName = `${companyId}/models/${modelId}.${fileExtension}`;-// Resumable (TUS) upload — a standard buffered upload times out on multi-GB// CAD files. The record goes in after it: inserting it starts the- // optimise, which reads the file.- const { error: uploadError } = await runUpload({- bucket: TEMP_STAGING_BUCKET,- path: fileName,- file- });+ // optimise, which reads the file. The id and path are the upload's: a+ // resumed upload keeps its own.+ const {+ error: uploadError,+ modelId,+ modelPath: fileName+ } = await runUpload(file);const recordInsert = uploadError? null: await carbon.from("modelUpload").insert({@@ -422,6 +422,14 @@ const PartForm = ({ initialValues, type = "card", onClose }: PartFormProps) => {<p className="text-xs text-muted-foreground group-hover:text-foreground">{t`Supports ${supportedModelTypes.join(", ")} files`}</p>+ {interrupted && (+ <InterruptedUploadNotice+ className="mt-3"+ name={interrupted.name}+ percent={interrupted.percent}+ onDismiss={dismissInterrupted}+ />+ )}</Loading>)}</div>diff --git a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsxindex debe155492..c1674d2023 100644--- a/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx+++ b/apps/erp/app/modules/items/ui/Tools/ToolForm.tsx@@ -3,7 +3,7 @@// including ports, remain AGPLv3; serving them over a network requires releasing their source.import { useCarbon } from "@carbon/auth";-import { convertKbToString, TEMP_STAGING_BUCKET } from "@carbon/files";+import { convertKbToString } from "@carbon/files";import { supportedModelTypes } from "@carbon/files/cad";import { ValidatedForm } from "@carbon/form";import {@@ -24,7 +24,6 @@ import {import { getFileSizeLimit, INPUT_FORMAT } from "@carbon/utils";import { Trans, useLingui } from "@lingui/react/macro";import type { PostgrestResponse } from "@supabase/supabase-js";-import { nanoid } from "nanoid";import { useEffect, useState } from "react";import { flushSync } from "react-dom";import { useDropzone } from "react-dropzone";@@ -45,7 +44,10 @@ import {UnitOfMeasure} from "~/components/Form";import { ReplenishmentSystemIcon, TrackingTypeIcon } from "~/components/Icons";-import { UploadProgress } from "~/components/UploadProgress";+import {+ InterruptedUploadNotice,+ UploadProgress+} from "~/components/UploadProgress";import {useCompanySettings,useCurrencyDecimals,@@ -86,7 +88,8 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {const [modelIsUploading, setModelIsUploading] = useState(false);const [modelFile, setModelFile] = useState<File | null>(null);const { carbon } = useCarbon();- const { upload, runUpload } = useModelUpload();+ const { upload, runUpload, interrupted, dismissInterrupted } =+ useModelUpload("new-tool");const {company: { id: companyId },id: userId@@ -98,18 +101,15 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {setModelIsUploading(true);});- const modelId = nanoid();- const fileExtension = file.name.split(".").pop();- const fileName = `${companyId}/models/${modelId}.${fileExtension}`;-// Resumable (TUS) upload — a standard buffered upload times out on multi-GB// CAD files. The record goes in after it: inserting it starts the- // optimise, which reads the file.- const { error: uploadError } = await runUpload({- bucket: TEMP_STAGING_BUCKET,- path: fileName,- file- });+ // optimise, which reads the file. The id and path are the upload's: a+ // resumed upload keeps its own.+ const {+ error: uploadError,+ modelId,+ modelPath: fileName+ } = await runUpload(file);const recordInsert = uploadError? null: await carbon.from("modelUpload").insert({@@ -406,6 +406,14 @@ const ToolForm = ({ initialValues, type = "card", onClose }: ToolFormProps) => {<p className="text-xs text-muted-foreground group-hover:text-foreground">{t`Supports ${supportedModelTypes.join(", ")} files`}</p>+ {interrupted && (+ <InterruptedUploadNotice+ className="mt-3"+ name={interrupted.name}+ percent={interrupted.percent}+ onDismiss={dismissInterrupted}+ />+ )}</Loading>)}</div>diff --git a/apps/erp/app/utils/resumable-upload.test.ts b/apps/erp/app/utils/resumable-upload.test.tsnew file mode 100644index 0000000000..4c8afb08d0--- /dev/null+++ b/apps/erp/app/utils/resumable-upload.test.ts@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Carbon (github.com/crbnos/carbon). Modified or adapted versions of this file,+// including ports, remain AGPLv3; serving them over a network requires releasing their source.++import { describe, expect, it } from "vitest";+import { pickResumableUpload } from "./resumable-upload";++const stored = (bucketName: string, objectName: string) => ({+ metadata: { bucketName, objectName }+});++const options = {+ bucket: "temp-staging",+ path: "co1/models/NEW.stl",+ running: new Set<string>()+};++describe("pickResumableUpload", () => {+ it("resumes an earlier upload of the file to the same company's models", () => {+ const earlier = stored("temp-staging", "co1/models/OLD.stl");+ expect(pickResumableUpload([earlier], options)).toBe(earlier);+ });++ it("never resumes another company's upload, or another bucket's", () => {+ expect(+ pickResumableUpload(+ [+ stored("temp-staging", "co2/models/OLD.stl"),+ stored("private", "co1/models/OLD.stl")+ ],+ options+ )+ ).toBeUndefined();+ });++ it("skips an upload still running in this tab", () => {+ expect(+ pickResumableUpload([stored("temp-staging", "co1/models/OLD.stl")], {+ ...options,+ running: new Set(["co1/models/OLD.stl"])+ })+ ).toBeUndefined();+ });++ it("prefers the upload the page offered to continue", () => {+ const first = stored("temp-staging", "co1/models/A.stl");+ const offered = stored("temp-staging", "co1/models/B.stl");+ expect(+ pickResumableUpload([first, offered], {+ ...options,+ preferPath: "co1/models/B.stl"+ })+ ).toBe(offered);+ });+});diff --git a/apps/erp/app/utils/resumable-upload.ts b/apps/erp/app/utils/resumable-upload.tsindex cf558244b1..913ae410b4 100644--- a/apps/erp/app/utils/resumable-upload.ts+++ b/apps/erp/app/utils/resumable-upload.ts@@ -9,7 +9,8 @@ import * as tus from "tus-js-client";// file into ONE multipart request; a multi-GB CAD model then times out at the// dev `.dev` proxy (it waits for storage to respond, but storage only responds// once the entire body has arrived). TUS streams the file in fixed chunks, so-// the gateways never see a multi-GB body, and a dropped chunk is retried.+// the gateways never see a multi-GB body, a dropped chunk is retried, and an+// upload a reload cut off resumes when the same file is dropped again.//// Supabase requires the chunk size to be EXACTLY 6 MB (except the final chunk).const CHUNK_SIZE = 6 * 1024 * 1024;@@ -63,11 +64,16 @@ export type ResumableUploadOptions = {/** The signed-in user's Supabase access token (from `useCarbon()`). */accessToken: string;bucket: string;- /** Object key within the bucket, e.g. `${companyId}/models/${id}.step`. */+ /** Object key within the bucket, e.g. `${companyId}/models/${id}.step`.+ * Used unless an unfinished upload of the same file is resumed. */path: string;+ /** Which unfinished upload to resume when several match the file. */+ preferPath?: string;file: File;/** Overwrite an existing object at `path` (default true). */upsert?: boolean;+ /** The path the bytes go to: `path`, or the resumed upload's. */+ onStart?: (path: string) => void;onProgress?: (percent: number,bytesUploaded: number,@@ -75,16 +81,64 @@ export type ResumableUploadOptions = {) => void;};-/** Upload a file to Supabase Storage via the resumable (TUS) protocol. */+// Paths an upload in this tab is still sending. A second drop of the same file+// must not resume the first while it runs.+const inFlight = new Set<string>();++type StoredUpload = { metadata: { [key: string]: string } };++/**+ * Which of tus's stored uploads of this file to resume, if any: one to the same+ * bucket and folder (the same company's models; the browser may hold another+ * company's), not still running in this tab, `preferPath` first.+ */+export function pickResumableUpload<T extends StoredUpload>(+ previous: T[],+ {+ bucket,+ path,+ preferPath,+ running+ }: { bucket: string; path: string; preferPath?: string; running: Set<string> }+): T | undefined {+ const folder = path.slice(0, path.lastIndexOf("/") + 1);+ const resumable = previous.filter(+ (p) =>+ p.metadata.bucketName === bucket &&+ p.metadata.objectName?.startsWith(folder) &&+ !running.has(p.metadata.objectName)+ );+ return (+ resumable.find((p) => p.metadata.objectName === preferPath) ?? resumable[0]+ );+}++/**+ * Upload a file to Supabase Storage via the resumable (TUS) protocol, and+ * resolve to the path it was written to.+ *+ * tus recognises an unfinished upload by the FILE (name, size, type, mtime),+ * not by its destination. Resuming one therefore continues ITS path, not the+ * one passed in, and the caller must record the path this returns. Recording+ * the new path while the bytes went to the old one left a model with no file.+ */export function uploadModelResumable({accessToken,bucket,path,+ preferPath,file,upsert = true,+ onStart,onProgress-}: ResumableUploadOptions): Promise<void> {+}: ResumableUploadOptions): Promise<{ path: string }> {return new Promise((resolve, reject) => {+ const metadata = {+ bucketName: bucket,+ objectName: path,+ contentType: file.type || "application/octet-stream",+ cacheControl: "3600"+ };const upload = new tus.Upload(file, {endpoint: `${SUPABASE_URL}/storage/v1/upload/resumable`,httpStack: new PublicOriginHttpStack(new tus.DefaultHttpStack({})),@@ -95,19 +149,13 @@ export function uploadModelResumable({"x-upsert": upsert ? "true" : "false"},uploadDataDuringCreation: true,- // Never resume an earlier attempt. tus fingerprints the FILE (name,- // size, type, mtime), not the destination, and every attempt uploads to- // a new path. Resuming sent the bytes to the earlier attempt's object- // while the caller recorded the new path, so the model had no file.- storeFingerprintForResuming: false,+ removeFingerprintOnSuccess: true,chunkSize: CHUNK_SIZE,- metadata: {- bucketName: bucket,- objectName: path,- contentType: file.type || "application/octet-stream",- cacheControl: "3600"+ metadata,+ onError: (error) => {+ inFlight.delete(metadata.objectName);+ reject(error);},- onError: reject,onProgress: (bytesUploaded, bytesTotal) => {onProgress?.(bytesTotal ? (bytesUploaded / bytesTotal) * 100 : 0,@@ -115,8 +163,133 @@ export function uploadModelResumable({bytesTotal);},- onSuccess: () => resolve()+ onSuccess: () => {+ inFlight.delete(metadata.objectName);+ resolve({ path: metadata.objectName });+ }});- upload.start();++ upload.findPreviousUploads().then((previous) => {+ const earlier = pickResumableUpload(previous, {+ bucket,+ path,+ preferPath,+ running: inFlight+ });+ if (earlier) {+ // Also what a new upload is created with, should the stored one have+ // expired on the server.+ metadata.objectName = earlier.metadata.objectName;+ upload.resumeFromPreviousUpload(earlier);+ }+ inFlight.add(metadata.objectName);+ onStart?.(metadata.objectName);+ upload.start();+ }, reject);});}++/** An upload the page lost (a reload, a closed tab) before it finished. */+export type InterruptedUpload = {+ path: string;+ name: string;+ size: number;+ percent: number;+};++type UploadNote = InterruptedUpload & { scope: string; startedAt: number };++const NOTE_PREFIX = "carbon:model-upload:";+// Supabase discards an unfinished resumable upload after 24 hours.+const NOTE_MAX_AGE_MS = 24 * 60 * 60 * 1000;++/**+ * Runs `use` against localStorage. Storage can be missing or throw (a private+ * window, blocked site data, a full quota); a lost note only costs the+ * reminder, never the upload, so the error is swallowed.+ */+function withStorage<T>(use: (store: Storage) => T): T | null {+ try {+ return use(window.localStorage);+ } catch {+ return null;+ }+}++function readNote(store: Storage, key: string): UploadNote | null {+ const raw = store.getItem(key);+ return raw ? (JSON.parse(raw) as UploadNote) : null;+}++/** Remember an upload under `scope` (the record it belongs to) until it ends. */+export function noteUploadStarted(+ scope: string,+ upload: Omit<InterruptedUpload, "percent">+) {+ const note: UploadNote = {+ ...upload,+ scope,+ percent: 0,+ startedAt: Date.now()+ };+ withStorage((store) =>+ store.setItem(NOTE_PREFIX + upload.path, JSON.stringify(note))+ );+}++/** Saves the progress about once per percent, not on every chunk event. */+export function noteUploadProgress(path: string, percent: number) {+ withStorage((store) => {+ const note = readNote(store, NOTE_PREFIX + path);+ if (!note || percent - note.percent < 1) return;+ store.setItem(NOTE_PREFIX + path, JSON.stringify({ ...note, percent }));+ });+}++export function forgetUpload(path: string) {+ withStorage((store) => store.removeItem(NOTE_PREFIX + path));+}++/**+ * The newest unfinished upload noted under `scope` that tus can still resume.+ * Notes past the server's 24 hours, or with no tus entry left, are dropped.+ */+export async function findInterruptedUpload(+ scope: string+): Promise<InterruptedUpload | null> {+ const store = withStorage((store) => store);+ if (!store) return null;+ try {+ const resumable = new Set(+ (await tus.defaultOptions.urlStorage.findAllUploads()).map(+ (p) => p.metadata.objectName+ )+ );+ const now = Date.now();+ const notes: UploadNote[] = [];+ for (const key of Object.keys(store)) {+ if (!key.startsWith(NOTE_PREFIX)) continue;+ const note = readNote(store, key);+ if (+ !note ||+ now - note.startedAt > NOTE_MAX_AGE_MS ||+ !resumable.has(note.path)+ ) {+ store.removeItem(key);+ } else if (note.scope === scope && !inFlight.has(note.path)) {+ notes.push(note);+ }+ }+ const newest = notes.sort((a, b) => b.startedAt - a.startedAt)[0];+ return newest+ ? {+ path: newest.path,+ name: newest.name,+ size: newest.size,+ percent: newest.percent+ }+ : null;+ } catch {+ return null;+ }+}diff --git a/packages/locale/locales/de/erp.po b/packages/locale/locales/de/erp.poindex 0c8b6c2346..6d48b8a947 100644--- a/packages/locale/locales/de/erp.po+++ b/packages/locale/locales/de/erp.po@@ -23631,6 +23631,9 @@ msgstr "Der Buchwert der Einheit ist für Sie nicht sichtbar, daher werden ihremsgid "The units of measure you buy, stock, and sell in"msgstr "Die Maßeinheiten, in denen Sie kaufen, lagern und verkaufen"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "Das US-Steuersystem für Abschreibung mit IRS-Anlageklassen-Tabellen, das als separater Steuerstundungsplan neben dem Handelsabschreibungsplan läuft."diff --git a/packages/locale/locales/en/erp.po b/packages/locale/locales/en/erp.poindex 9c30031832..fb5ea8923b 100644--- a/packages/locale/locales/en/erp.po+++ b/packages/locale/locales/en/erp.po@@ -23631,6 +23631,9 @@ msgstr "The unit's book value is not visible to you, so its cost of goods sold amsgid "The units of measure you buy, stock, and sell in"msgstr "The units of measure you buy, stock, and sell in"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."diff --git a/packages/locale/locales/es/erp.po b/packages/locale/locales/es/erp.poindex 2a8ba66cd6..05252ca174 100644--- a/packages/locale/locales/es/erp.po+++ b/packages/locale/locales/es/erp.po@@ -23631,6 +23631,9 @@ msgstr "El valor en libros de la unidad no es visible para usted, por lo que nomsgid "The units of measure you buy, stock, and sell in"msgstr "Las unidades de medida en las que compras, almacenas y vendes"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "El sistema de depreciación fiscal de EE.UU. con tablas de clase de propiedad del IRS, ejecutado como un programa fiscal separado junto al programa contable."diff --git a/packages/locale/locales/fr/erp.po b/packages/locale/locales/fr/erp.poindex 50360ed5b6..cb9b3e801f 100644--- a/packages/locale/locales/fr/erp.po+++ b/packages/locale/locales/fr/erp.po@@ -23631,6 +23631,9 @@ msgstr "La valeur comptable de l'unité n'est pas visible, donc son coût des mamsgid "The units of measure you buy, stock, and sell in"msgstr "Les unités de mesure dans lesquelles vous achetez, stockez et vendez"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "Le système d'amortissement fiscal américain avec des tables de classe de propriété IRS, exécuté comme un planning fiscal distinct aux côtés du planning comptable."diff --git a/packages/locale/locales/hi/erp.po b/packages/locale/locales/hi/erp.poindex 71af56c7b6..7617d8ab18 100644--- a/packages/locale/locales/hi/erp.po+++ b/packages/locale/locales/hi/erp.po@@ -23631,6 +23631,9 @@ msgstr "इकाई का बही मूल्य आपको दिखाmsgid "The units of measure you buy, stock, and sell in"msgstr "आप जो इकाइयाँ खरीदते, स्टॉक करते और बेचते हैं"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "अमेरिकी कर मूल्यह्रास प्रणाली IRS संपत्ति-वर्ग तालिकाओं के साथ, पुस्तक अनुसूची के साथ एक अलग कर अनुसूची के रूप में चलाई जाती है।"diff --git a/packages/locale/locales/it/erp.po b/packages/locale/locales/it/erp.poindex cf4ee64b48..5019a60160 100644--- a/packages/locale/locales/it/erp.po+++ b/packages/locale/locales/it/erp.po@@ -23631,6 +23631,9 @@ msgstr "Il valore contabile dell'unità non è visibile a te, quindi il costo demsgid "The units of measure you buy, stock, and sell in"msgstr "Le unità di misura in cui acquisti, immagazzini e vendi"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "Il sistema di ammortamento fiscale US con tabelle di classificazione della proprietà IRS, eseguito come programma fiscale separato insieme al programma contabile."diff --git a/packages/locale/locales/ja/erp.po b/packages/locale/locales/ja/erp.poindex 68d2d8fb1f..fbdea02568 100644--- a/packages/locale/locales/ja/erp.po+++ b/packages/locale/locales/ja/erp.po@@ -23631,6 +23631,9 @@ msgstr "この個の帳簿価額はあなたに表示されないため、そのmsgid "The units of measure you buy, stock, and sell in"msgstr "購入、在庫、販売する単位"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "米国の税務減価償却制度で、IRS固定資産分類表を使用し、帳簿的減価償却スケジュールと並行して別税務スケジュールとして実行されます。"diff --git a/packages/locale/locales/ko/erp.po b/packages/locale/locales/ko/erp.poindex e714937bc4..fda2c39d42 100644--- a/packages/locale/locales/ko/erp.po+++ b/packages/locale/locales/ko/erp.po@@ -23631,6 +23631,9 @@ msgstr "자산의 장부가액이 표시되지 않으므로, 그 매출원가msgid "The units of measure you buy, stock, and sell in"msgstr "구매, 재고, 판매 시 사용하는 측정 단위"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "미국 세금 감가상각 시스템으로, IRS 자산 클래스 테이블과 함께 별도의 세금 스케줄로 실행됩니다."diff --git a/packages/locale/locales/pl/erp.po b/packages/locale/locales/pl/erp.poindex 9373ee4805..19fcb8fa2b 100644--- a/packages/locale/locales/pl/erp.po+++ b/packages/locale/locales/pl/erp.po@@ -23631,6 +23631,9 @@ msgstr "Wartość księgowa sztuki nie jest dla ciebie widoczna, dlatego jej kosmsgid "The units of measure you buy, stock, and sell in"msgstr "Jednostki miary, w których kupujesz, magazynujesz i sprzedajesz"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "Amerykański system amortyzacji podatkowej z tabelami klas mienia IRS, uruchamiany jako oddzielny harmonogram podatkowy obok harmonogramu księgi."diff --git a/packages/locale/locales/pt/erp.po b/packages/locale/locales/pt/erp.poindex 9c62a000f6..c94099df94 100644--- a/packages/locale/locales/pt/erp.po+++ b/packages/locale/locales/pt/erp.po@@ -23631,6 +23631,9 @@ msgstr "O valor contábil da unidade não é visível para você, então seu cusmsgid "The units of measure you buy, stock, and sell in"msgstr "As unidades de medida que você compra, estoca e vende"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "O sistema de depreciação fiscal dos EUA com tabelas de classe de propriedade do IRS, executado como um calendário fiscal separado ao lado do calendário contábil."diff --git a/packages/locale/locales/ru/erp.po b/packages/locale/locales/ru/erp.poindex a8600c2416..94591583b1 100644--- a/packages/locale/locales/ru/erp.po+++ b/packages/locale/locales/ru/erp.po@@ -23631,6 +23631,9 @@ msgstr "Балансовая стоимость единицы вам недосmsgid "The units of measure you buy, stock, and sell in"msgstr "Единицы измерения, в которых вы покупаете, храните и продаете"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "Американская система налоговой амортизации с таблицами категорий имущества IRS, работающая как отдельный налоговый график вместе с графиком книг."diff --git a/packages/locale/locales/tr/erp.po b/packages/locale/locales/tr/erp.poindex bf8e9d160f..c85580f1cd 100644--- a/packages/locale/locales/tr/erp.po+++ b/packages/locale/locales/tr/erp.po@@ -23631,6 +23631,9 @@ msgstr "Adete ait defter değeri sizin için görünür değildir, bu nedenle samsgid "The units of measure you buy, stock, and sell in"msgstr "Satın aldığınız, stokladığınız ve sattığınız ölçü birimleri"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "IRS mülkiyet sınıfı tabloları ile ABD vergi amortisman sistemi, kitap çizelgesi ile birlikte ayrı bir vergi planı olarak çalıştırılır."diff --git a/packages/locale/locales/zh/erp.po b/packages/locale/locales/zh/erp.poindex 92a52711d4..a8952b6779 100644--- a/packages/locale/locales/zh/erp.po+++ b/packages/locale/locales/zh/erp.po@@ -23631,6 +23631,9 @@ msgstr "该件的账面价值对您不可见,因此不显示其销售成本和msgid "The units of measure you buy, stock, and sell in"msgstr "您购买、库存和销售的计量单位"+msgid "The upload of <0>{name}</0> stopped at {stopped}%. Drop the same file again to continue."+msgstr ""+msgid "The US tax depreciation system with IRS property-class tables, run as a separate tax schedule alongside the book schedule."msgstr "美国税务折旧系统,包含国税局资产等级表,作为独立的税务计划与账簿计划并行运行。"