import { useAtomValue } from "@effect/atom-react"; import { useFocusEffect } from "@react-navigation/native"; import { playbookStepLabel } from "@t3tools/client-runtime/j5/playbooks"; import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import type { EnvironmentId, ProjectId } from "@t3tools/contracts"; import type { PlaybookSource } from "@t3tools/contracts/j5"; import { useCallback, useState } from "react"; import { Alert, Modal, Pressable, ScrollView, Share, View } from "react-native"; import { SafeAreaView } from "react-native-safe-area-context"; import { AppText as Text, AppTextInput as TextInput } from "../../components/ui/AppText"; import { Menu } from "../../components/ui/Menu"; import { environmentProjects } from "../../state/projects"; import { useEnvironmentQuery } from "../../state/query"; import { useAtomCommand } from "../../state/use-atom-command"; import { useRemoteConnectionStatus } from "../../state/use-remote-environment-registry"; import { AgentFolderPickerModal } from "../agents/AgentFolderPickerModal"; import { useOwnedEnvironmentIds } from "../sharing/guestAccess"; import { j5Environment } from "../state"; import { useStartPlaybookConversation } from "./startPlaybookConversation"; export function PlaybookLibrarySettingsSection({ environmentId, }: { environmentId: EnvironmentId | null; }) { const { connectedEnvironments } = useRemoteConnectionStatus(); // Playbooks are managed on the servers the person owns (People and access AC27). const owned = useOwnedEnvironmentIds(); const environments = connectedEnvironments.filter((entry) => owned.has(entry.environmentId)); const environment = environments.find((entry) => entry.environmentId === environmentId); return environment ? ( ({ environmentId: entry.environmentId, label: entry.environmentLabel, }))} /> ) : ( No environment connected. ); } function PlaybookLibrary({ environmentId, label, environments, }: { environmentId: EnvironmentId; label: string; environments: ReadonlyArray<{ environmentId: EnvironmentId; label: string }>; }) { const [projectId, setProjectId] = useState(null); // As upstream's pickers: an archived project is not offered, but the chosen one stays listed. const projects = useAtomValue(environmentProjects.projectsAtom).filter( (project) => project.environmentId === environmentId && (project.archivedAt == null || project.id === projectId), ); const project = projects.find((entry) => entry.id === projectId) ?? null; // A project's .j5/playbooks files join the list and win over a same-named library copy. const scope = project ? { projectId: project.id } : {}; const query = useEnvironmentQuery(j5Environment.playbookLibrary({ environmentId, input: scope })); const sources = useEnvironmentQuery(j5Environment.playbookSources({ environmentId, input: {} })); const canOperate = useAtomValue(j5Environment.savePlaybook.permissionAtom(environmentId)); const save = useAtomCommand(j5Environment.savePlaybook, { reportFailure: false }); const setFolders = useAtomCommand(j5Environment.setPlaybookFolders, { reportFailure: false }); const exportDefinition = useAtomCommand(j5Environment.exportPlaybook, { reportFailure: false }); const remove = useAtomCommand(j5Environment.deletePlaybook, { reportFailure: false }); const rename = useAtomCommand(j5Environment.renamePlaybook, { reportFailure: false }); const [picking, setPicking] = useState(false); const [importing, setImporting] = useState(false); const [name, setName] = useState(""); const [yaml, setYaml] = useState(""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const startConversation = useStartPlaybookConversation(environmentId); const openConversation = (playbook: string | null) => void act(() => startConversation({ playbook, projects, projectId: project?.id ?? null })); const [details, setDetails] = useState(null); const [copyTarget, setCopyTarget] = useState<{ name: string; destination: EnvironmentId; source: PlaybookSource; } | null>(null); const [renameTarget, setRenameTarget] = useState<{ name: string; title: string; source: PlaybookSource; } | null>(null); const canSaveDestination = useAtomValue( j5Environment.savePlaybook.permissionAtom(copyTarget?.destination ?? environmentId), ); const folderPaths = (sources.data?.folders ?? []).flatMap((entry) => entry.source.kind === "folder" ? [entry.source.path] : [], ); const detail = query.data?.playbooks.find((entry) => entry.name === details); const { refresh } = query; useFocusEffect( useCallback(() => { refresh(); }, [refresh]), ); async function act(operation: () => Promise) { if (busy) return; setBusy(true); setError(null); const result = await settlePromise(operation); setBusy(false); if (result._tag === "Failure") { const cause = squashAtomCommandFailure(result); setError(cause instanceof Error ? cause.message : "Playbook action failed."); return; } query.refresh(); sources.refresh(); } async function changeFolders(folders: string[]) { const result = await setFolders({ environmentId, input: { folders } }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); } const closeEditor = () => { if (!busy) { setImporting(false); setCopyTarget(null); setRenameTarget(null); setName(""); setYaml(""); setError(null); } }; return ( <> {projects.length > 0 ? ( ({ id: entry.id, title: entry.title, state: entry.id === project?.id ? ("on" as const) : ("off" as const), })), ]} onPressAction={({ nativeEvent }) => setProjectId(nativeEvent.event ? (nativeEvent.event as ProjectId) : null) } > {project?.title ?? "Library only"} ▾ ) : ( Available in every project. )} { const action = nativeEvent.event; if (action === "create") openConversation(null); else if (action === "import") { setError(null); setImporting(true); } else if (action === "folder") setPicking(true); else { query.refresh(); sources.refresh(); } }} > Add / manage {project ? ( Includes {project.title}'s .j5/playbooks folder. Those override a library playbook with the same name in that project. ) : null} {error || sources.error || query.error ? ( {error ?? sources.error ?? query.error} ) : null} {query.isPending && !query.data ? Loading playbooks… : null} {query.data?.playbooks.length === 0 ? ( No playbooks yet Create a repeatable workflow with your agent, or import YAML. ) : null} {query.data?.playbooks.map((playbook) => { const source = playbook.source ?? { kind: "environment" }; return ( {playbook.title} entry.environmentId !== environmentId || source.kind !== "environment", ) .map((entry) => ({ id: `copy:${entry.environmentId}`, title: entry.environmentId === environmentId ? "Copy to library" : `Copy to ${entry.label}`, attributes: { disabled: busy || !!playbook.issue }, })), { id: "delete", title: source.kind === "folder" ? "Delete unavailable: edit source folder" : "Delete", attributes: { disabled: busy || !canOperate || source.kind === "folder" }, }, ]} onPressAction={({ nativeEvent }) => { const action = nativeEvent.event; if (action === "chat") openConversation(playbook.name); else if (action === "steps") setDetails(playbook.name); else if (action.startsWith("copy:")) { const destination = environments.find( (entry) => `copy:${entry.environmentId}` === action, ); if (destination) { setError(null); setName(playbook.name); setCopyTarget({ name: playbook.name, source, destination: destination.environmentId, }); } } else if (action === "rename") { setError(null); setRenameTarget({ name: playbook.name, title: playbook.title, source }); } else if (action === "export") void act(async () => { const result = await exportDefinition({ environmentId, input: { ...scope, name: playbook.name, source }, }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); await Share.share({ title: result.value.fileName, message: result.value.yaml, }); }); else if (action === "delete") Alert.alert("Delete playbook", `Delete ${playbook.title}?`, [ { text: "Cancel", style: "cancel" }, { text: "Delete", style: "destructive", onPress: () => void act(async () => { const result = await remove({ environmentId, input: { ...scope, name: playbook.name, source }, }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); }), }, ]); }} > ••• {playbook.description} {playbook.stepCount} {playbook.stepCount === 1 ? "step" : "steps"} {source.kind === "folder" ? " · From source folder" : ""} {source.kind === "workspace" ? ` · From ${project?.title ?? "project"}` : ""} {playbook.overridesLibrary ? " · Overrides library copy" : ""} {playbook.issue ? ( {playbook.issue.message} ) : null} {(playbook.warnings ?? []).map((warning) => ( {warning.message} ))} ); })} {sources.data?.folders .filter((entry) => entry.source.kind === "folder" || entry.issue) .map((entry) => ( {entry.source.kind === "folder" ? entry.path : "Environment library"} {entry.issue ? ( {entry.issue.message} ) : null} {entry.source.kind === "folder" ? ( void act(() => changeFolders( folderPaths.filter( (folder) => entry.source.kind !== "folder" || folder !== entry.source.path, ), ), ) } > Remove source ) : null} ))} {picking ? ( setPicking(false)} onSelect={(path) => { setPicking(false); void act(() => changeFolders([...folderPaths, path])); }} /> ) : null} {detail ? ( setDetails(null)} > {/* SafeAreaView takes no className, so the theme surface and flex go on a View. */} {/* The persona sheets' header: the title, and Done at the top. */} {detail.title} setDetails(null)} className="px-3 py-2" > Done {detail.description} {detail.steps.map((step, index) => ( {playbookStepLabel(step, index)} ))} ) : null} {importing || copyTarget || renameTarget ? ( {/* SafeAreaView takes no className, so the theme surface and flex go on a View. */} {renameTarget ? "Rename playbook" : copyTarget ? "Copy playbook" : "Import playbook"} Available in every project on the environment. renameTarget ? setRenameTarget({ ...renameTarget, title: value }) : setName(value) } editable={!busy} autoCapitalize="none" className="rounded-lg border border-border p-3 text-foreground" /> {importing ? ( ) : null} {error ? ( {error} ) : null} Cancel void act(async () => { if (renameTarget) { const result = await rename({ environmentId, input: { ...scope, ...renameTarget, title: renameTarget.title.trim() }, }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); setRenameTarget(null); } else { let text = yaml; if (copyTarget) { const result = await exportDefinition({ environmentId, input: { ...scope, name: copyTarget.name, source: copyTarget.source }, }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); text = result.value.yaml; } const result = await save({ environmentId: copyTarget?.destination ?? environmentId, input: { name, yaml: text }, }); if (result._tag === "Failure") throw squashAtomCommandFailure(result); setImporting(false); setCopyTarget(null); setName(""); setYaml(""); } }) } > {renameTarget ? "Save" : copyTarget ? "Copy" : "Import"} ) : null} ); }