Files
model-platform/frontend/app/features/platform/WorkspaceTree.tsx
T
cb0205fcd2 feat(scripts): 跨 owner 懒加载目录树 + 跨用户可见 workspace/public
修两个后端接口问题:
1) /api/v1/workspace-directories 返回为空,目录树结构消失
2) 同 workspace 内脚本/数据互相可见但默认排除 private

后端改动
--------
* list_scripts / list_resources / list_workspace_directories 新增
  owner_user_id 可选 query 参数;缺省 = 当前请求者本人(scope 到
  workspace/{me}/...),传值时 scope 到该 owner 的子树。前端根加载
  默认只见自己一级,其他成员以折叠分组呈现。
* visibility 过滤统一:非 admin 请求者只返回 owner==me 或
  visibility ∈ {workspace, public};admin 跳过。owner=me 含自己
  的 private,owner=other 只剩其 workspace/public,排除他人 private。
* create_workspace_directory 两个分支 visibility 默认 'public'
  (非 private),使跨 owner 目录树可见;响应新增 owner_user_id 字段。
* platform.list_members 鉴权从 system_admin_context 放宽为
  系统管理员或该 workspace 活跃成员(让普通用户也能渲染同
  workspace 成员名册,用于跨 owner 分组)。
* main.py 注册 platform 模块(随 list_members 改动补齐导入)。
* .env.example 同步 common/config.py 26 个字段。

前端改动
--------
* ScriptExplorer.memberScriptGroups 改由 members 列表播种分组,
  display_name 取 members.display_name;inferredDirectories 现在按
  owner_user_id 标记,统一跨 owner 目录渲染。删除脚本目录页头与
  树分组标题的工作副本数量角标。
* WorkspaceTree 新增 ownerUserId 透传到 store.toggleExpanded;
  仅"我"的分组 mount 时 auto-expand,他人分组默认折叠,展开才
  调 loadOwnerGroup / owner-scoped loadScripts / loadChildren。
* scriptWorkspaceStore 引入 namespaced cache key
  (ownerCacheKey = `${ownerUserId ?? me}:${path}`),loadedScriptPaths
  / loadedChildPaths / loadedOwnerGroups 全部按 owner 隔离;
  toggleExpanded 用 loadPath === undefined 区分 group 头与真实
  目录,修"他人子目录点击不触发接口"的 loadPath 前缀误判 bug。
* api.ts / AuthContext 透传 ownerUserId 给 listScripts /
  listResources / listWorkspaceDirectories。

文档
----
* API.md: §3.2 创建目录 visibility 默认 public + 响应加 owner_user_id;
  §3.3.1 GET directories 加 owner_user_id 参数 + 响应字段;
  §3.4 GET scripts 改写为 owner 作用域 + visibility 过滤语义;
  §五.1 GET data-resources 新增,同一套统一语义;
  §7 intro 例外 — GET members 对系统管理员或 workspace 活跃成员开放。
* DEVELOP.md: Code layout 重写以反映 backend api/services/clients/
  schemas 拆分 + schedule domain/scheduling/application/execution/
  infrastructure 拆分 + common 子包(auth/storage/backends);
  Configuration 系统补全 26 个 settings 字段;新增
  "Owner-scoping + visibility (cross-owner browsing)" 小节;
  Per-service dev 注释用 uv run 的源布局要求;Add a new DAG endpoint /
  storage bucket 路径改为 backend/src/backend/api/* 与 services/*。

测试
----
* test_list_scripts_parent_path.py /
  test_resources.py 补充 owner_user_id 参数化直接调用 + LIKE
  前缀断言(workspace/{owner}/... 前缀)。

Co-Authored-By: Claude <noreply@anthropic.com>
2026-09-02 10:10:41 +08:00

341 lines
10 KiB
TypeScript

import { type MouseEvent as ReactMouseEvent, useEffect, useMemo } from "react";
import Icon from "../../components/common/Icon";
import type {
ScriptItem,
WorkspaceDirectory,
ResourceItem,
} from "~/services/api";
export type WorkspaceTreeTarget = {
kind: "root" | "directory" | "file";
path: string;
script?: ScriptItem;
};
type WorkspaceTreeProps = {
title: string;
scripts: ScriptItem[];
directories: WorkspaceDirectory[];
selectedId: string | null;
onSelect: (id: string) => void;
onContextMenu?: (
event: ReactMouseEvent,
target: WorkspaceTreeTarget,
) => void;
readOnly?: boolean;
dataResources?: ResourceItem[];
onCopyResourcePath?: (jupyterPath: string) => void;
// 唯一标识此 group(通常 `__group__<owner_user_id>`),让多个 owner 的 group 各自独立展开。
groupKey: string;
// 该 group 所属 owner 的 user_id —— 透传给 store.toggleExpanded,使他人
// 分组展开时走 loadOwnerGroup / 带 owner 的 loadScripts(懒加载)。
ownerUserId: string;
expandedPaths: Set<string>;
onToggle: (path: string, loadPath?: string, ownerUserId?: string) => void;
loadingChildrenPaths: Set<string>;
};
type WorkspaceTreeItemsProps = Omit<WorkspaceTreeProps, "title" | "readOnly"> & {
path: string;
depth: number;
onCopyResourcePath?: (jupyterPath: string) => void;
};
function formatTime(value: string) {
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
hour12: false,
}).format(new Date(value));
}
export function scriptIcon(item: ScriptItem) {
return item.script_type === "notebook" ? "notebook" : "python";
}
function ownedScriptPath(item: ScriptItem) {
// 数据资源的 relative_path 已经是 jupyter 路径(无 ULID 前缀);脚本相对路径形如
// `{ulid}/{ws_id}/{user_id}/...`,需要剥前两层。
if (item.script_id.startsWith("data:")) {
return item.relative_path.replaceAll("\\", "/");
}
return item.relative_path.replaceAll("\\", "/").split("/").slice(2).join("/");
}
function parentOf(path: string) {
const parts = path.split("/");
parts.pop();
return parts.join("/");
}
export function WorkspaceTreeGroup({
title,
scripts,
directories,
selectedId,
onSelect,
onContextMenu,
readOnly = false,
dataResources,
onCopyResourcePath,
groupKey,
ownerUserId,
expandedPaths,
onToggle,
loadingChildrenPaths,
}: WorkspaceTreeProps) {
const open = expandedPaths.has(groupKey);
const dataResourceScripts = useMemo(() => {
if (!dataResources) return [];
return dataResources.map((r) => ({
script_id: `data:${r.resource_id}`,
workspace_id: r.workspace_id,
current_object_id: r.storage_object_id,
owner_user_id: r.owner_user_id,
owner_display_name: null,
script_name: r.resource_name,
script_type: "python" as const,
visibility: r.visibility,
status: r.status,
is_locked: false,
// relative_path 直接是 jupyter 路径(与 Python/Notebook 同层渲染,不再带虚拟前缀)
relative_path: r.jupyter_accessible_path,
jupyter_path: r.jupyter_accessible_path,
content_hash: r.file.content_hash ?? "",
size_bytes: r.file.size_bytes,
created_at: r.created_at,
updated_at: r.updated_at,
} as unknown as ScriptItem));
}, [dataResources]);
const dataResourceDirectories = useMemo(() => {
if (!dataResources) return [];
const dirSet = new Set<string>();
for (const r of dataResources) {
const parts = r.jupyter_accessible_path.split("/");
parts.pop();
let acc = "";
for (const p of parts) {
acc = acc ? `${acc}/${p}` : p;
dirSet.add(acc);
}
}
return [...dirSet].map((path) => ({
path,
name: path.split("/").pop() ?? path,
parent_path: path.includes("/")
? path.split("/").slice(0, -1).join("/")
: "",
owner_user_id: ownerUserId,
}));
}, [dataResources, ownerUserId]);
// 默认只展开"我"的分组(!readOnly);其他成员分组默认折叠,点击才
// 按需拉取其可见内容(懒加载设计)。原本对所有 group 无条件 onToggle
// 会让所有 owner 的内容在根加载时就被全量拉取,违背"默认只拉取自己的一级"。
useEffect(() => {
if (!readOnly && !expandedPaths.has(groupKey)) {
void onToggle(groupKey, undefined, ownerUserId);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [groupKey]);
return (
<div className="tree-group">
<button
className={`tree-group__title${open ? " is-open" : ""}`}
type="button"
aria-expanded={open}
onClick={() => onToggle(groupKey, undefined, ownerUserId)}
onContextMenu={onContextMenu
? (event) => onContextMenu(event, { kind: "root", path: "" })
: undefined}
>
<Icon name="chevron" size={14} />
<Icon name="folder" size={17} />
<span>{title}</span>
</button>
{open && (
<div className="tree-group__items">
<WorkspaceTreeItems
groupKey={groupKey}
ownerUserId={ownerUserId}
path=""
depth={0}
scripts={[...scripts, ...dataResourceScripts]}
// 数据资源目录与真实/推断目录按 path 去重
directories={[
...new Map(
[...directories, ...dataResourceDirectories].map((d) => [d.path, d]),
).values(),
]}
selectedId={selectedId}
onSelect={onSelect}
onContextMenu={onContextMenu}
expandedPaths={expandedPaths}
onToggle={onToggle}
loadingChildrenPaths={loadingChildrenPaths}
onCopyResourcePath={onCopyResourcePath}
/>
{scripts.length === 0 && directories.length === 0 && dataResourceScripts.length === 0 && (
<p className="tree-group__empty">
{readOnly ? "暂无文件" : "右键此目录即可新建或上传"}
</p>
)}
</div>
)}
</div>
);
}
function WorkspaceTreeItems({
groupKey,
ownerUserId,
path,
depth,
scripts,
directories,
selectedId,
onSelect,
onContextMenu,
onCopyResourcePath,
expandedPaths,
onToggle,
loadingChildrenPaths,
}: WorkspaceTreeItemsProps) {
const childDirectories = directories.filter(
(item) => item.parent_path === path,
);
const childScripts = scripts.filter(
(item) => parentOf(ownedScriptPath(item)) === path,
);
return (
<>
{childDirectories.map((directory) => (
<DirectoryBranch
key={directory.path}
groupKey={groupKey}
ownerUserId={ownerUserId}
directory={directory}
depth={depth}
scripts={scripts}
directories={directories}
selectedId={selectedId}
onSelect={onSelect}
onContextMenu={onContextMenu}
expandedPaths={expandedPaths}
onToggle={onToggle}
loadingChildrenPaths={loadingChildrenPaths}
onCopyResourcePath={onCopyResourcePath}
/>
))}
{childScripts.map((item) => (
<button
className={`script-row${
selectedId === item.script_id ? " script-row--active" : ""
}`}
style={{ paddingLeft: 20 + depth * 16 }}
key={item.script_id}
type="button"
onClick={() => {
if (item.script_id.startsWith("data:") && onCopyResourcePath) {
onCopyResourcePath(item.relative_path);
} else {
onSelect(item.script_id);
}
}}
onContextMenu={onContextMenu
? (event) => onContextMenu(event, {
kind: "file",
path: ownedScriptPath(item),
script: item,
})
: undefined}
>
<span className={`file-icon file-icon--${
item.script_id.startsWith("data:") ? "data" : item.script_type
}`}>
<Icon name={item.script_id.startsWith("data:") ? "database" : scriptIcon(item)} size={17} />
</span>
<span className="script-row__copy">
<strong title={item.script_name}>{item.script_name}</strong>
<small>{formatTime(item.updated_at)}</small>
</span>
{item.is_locked && (
<span className="lock-badge" title="已锁定">
<Icon name="lock" size={12} />
</span>
)}
{item.visibility !== "private" && (
<span className="visibility-dot" title="Workspace 可见" />
)}
</button>
))}
</>
);
}
function DirectoryBranch({
groupKey,
ownerUserId,
directory,
depth,
scripts,
directories,
selectedId,
onSelect,
onContextMenu,
onCopyResourcePath,
expandedPaths,
onToggle,
loadingChildrenPaths,
}: Omit<WorkspaceTreeItemsProps, "path"> & {
directory: WorkspaceDirectory;
}) {
const expandKey = `${groupKey}/${directory.path}`;
const open = expandedPaths.has(expandKey);
const childrenLoading = loadingChildrenPaths.has(directory.path);
return (
<div className="directory-branch">
<button
className="directory-row"
style={{ paddingLeft: 10 + depth * 16 }}
type="button"
onClick={() => onToggle(expandKey, directory.path, ownerUserId)}
onContextMenu={onContextMenu
? (event) => onContextMenu(event, {
kind: "directory",
path: directory.path,
})
: undefined}
>
<span className={`directory-row__chevron${open ? " is-open" : ""}`}>
<Icon name="chevron" size={13} />
</span>
<Icon name="folder" size={17} />
<strong title={directory.path}>{directory.name}</strong>
{childrenLoading && <span className="loading-spinner" />}
</button>
{open && (
<WorkspaceTreeItems
groupKey={groupKey}
ownerUserId={ownerUserId}
path={directory.path}
depth={depth + 1}
scripts={scripts}
directories={directories}
selectedId={selectedId}
onSelect={onSelect}
onContextMenu={onContextMenu}
expandedPaths={expandedPaths}
onToggle={onToggle}
loadingChildrenPaths={loadingChildrenPaths}
onCopyResourcePath={onCopyResourcePath}
/>
)}
</div>
);
}